diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 000000000..fa1e1b9c1 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,13 @@ +# cargo-nextest settings. CI selects the `ci` profile with NEXTEST_PROFILE=ci. +[profile.default] +slow-timeout = { period = "60s", terminate-after = 5 } + +[profile.ci] +fail-fast = false +# Report flaky tests instead of hiding them: no retries. +retries = 0 +failure-output = "immediate-final" +slow-timeout = { period = "60s", terminate-after = 5 } + +[profile.ci.junit] +path = "junit.xml" diff --git a/.cursor/cloud-install.sh b/.cursor/cloud-install.sh new file mode 100755 index 000000000..1402647d1 --- /dev/null +++ b/.cursor/cloud-install.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Idempotent Cloud Agent bootstrap for PCBCraft. Mirrors CI package and toolchain setup. +set -euo pipefail + +LINUX_DEPS=( + libxkbcommon-dev libwayland-dev libx11-dev libxi-dev libxrandr-dev + libxcursor-dev libgl1-mesa-dev libxkbcommon-x11-0 +) +RUNTIME_DEPS=(xvfb xauth mesa-vulkan-drivers libvulkan1 imagemagick) +BUILD_DEPS=(build-essential pkg-config curl ca-certificates git) + +if ! dpkg -s "${LINUX_DEPS[0]}" >/dev/null 2>&1; then + sudo apt-get update + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + "${BUILD_DEPS[@]}" "${LINUX_DEPS[@]}" "${RUNTIME_DEPS[@]}" +fi + +if ! command -v rustup >/dev/null; then + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain none +fi + +if [[ -f "$HOME/.cargo/env" ]]; then + # shellcheck disable=SC1091 + source "$HOME/.cargo/env" +fi + +for bin in cargo rustc rustup; do + if [[ -x "$HOME/.cargo/bin/$bin" ]] && [[ ! -e "/usr/local/bin/$bin" ]]; then + sudo ln -sf "$HOME/.cargo/bin/$bin" "/usr/local/bin/$bin" + fi +done + +if ! command -v rustup >/dev/null; then + echo "rustup install failed" >&2 + exit 1 +fi + +MSRV="$(sed -n 's/^rust-version *= *"\(.*\)"/\1/p' Cargo.toml)" +if [[ -z "$MSRV" ]]; then + echo "workspace Cargo.toml has no rust-version" >&2 + exit 1 +fi + +if ! rustup toolchain list -v | grep -q "^${MSRV}-"; then + rustup toolchain install "${MSRV}" --profile minimal -c rustfmt -c clippy +fi +rustup default "${MSRV}" + +if ! command -v cargo-nextest >/dev/null; then + cargo install cargo-nextest --locked --force + sudo ln -sf "$HOME/.cargo/bin/cargo-nextest" /usr/local/bin/cargo-nextest +fi + +if ! command -v cargo-deny >/dev/null; then + cargo install cargo-deny --locked --force + sudo ln -sf "$HOME/.cargo/bin/cargo-deny" /usr/local/bin/cargo-deny +fi + +cargo fetch --locked +cargo build --locked -p xtask +cargo build --locked -p pcbcraft -p pcbcraft-cli diff --git a/.cursor/environment.json b/.cursor/environment.json new file mode 100644 index 000000000..ab9b37183 --- /dev/null +++ b/.cursor/environment.json @@ -0,0 +1,5 @@ +{ + "name": "PCBCraft", + "user": "ubuntu", + "install": "bash .cursor/cloud-install.sh" +} diff --git a/.cursor/rules/pcbcraft-core.mdc b/.cursor/rules/pcbcraft-core.mdc new file mode 100644 index 000000000..9f05654e5 --- /dev/null +++ b/.cursor/rules/pcbcraft-core.mdc @@ -0,0 +1,15 @@ +--- +description: PCBCraft invariants for every agent session +alwaysApply: true +--- + +# PCBCraft core + +Full rules: repository root `AGENTS.md`. Architecture: `docs/architecture.md`. + +- **Base:** fork `wdunn001/pcbcraft` `main`. Issues on `tangency-labs/pcbcraft`. +- **CI proof:** green GitHub Actions on the fork for your pushed commit (required). Local `cargo xtask ci` optional (`docs/ci.md`). +- **Engine:** typed commands only; invalid batches leave state untouched; no production panics/unwrap. +- **UI shell lane:** do not edit `crates/ui-egui/src/lib.rs` unless issue tag `conflict:ui-egui-lib` and you hold that lane. +- **One window, MCP-first, crate layering** — see AGENTS.md (no egui in lower crates). +- **Never** name other EDA products; **never** open PRs or push to `main` as a worker. diff --git a/.cursor/rules/pcbcraft-pipeline.mdc b/.cursor/rules/pcbcraft-pipeline.mdc new file mode 100644 index 000000000..4f26bcc83 --- /dev/null +++ b/.cursor/rules/pcbcraft-pipeline.mdc @@ -0,0 +1,31 @@ +--- +description: Claiming issues, build reports, and parallel-safe delivery on PCBCraft +alwaysApply: false +--- + +# Pipeline (workers and reviewers) + +Details: `CONTRIBUTING.md`, onboarding `https://github.com/wdunn001/pcbcraft/issues/1`. + +## Claim + +```text +CLAIM @ until clone branch +``` + +Only `ready` + `status:open`. Shared machine → also `conflict:parallel-safe`. One issue per agent unless stacked epic children. Check no live lease first. + +## Build + +1. `git fetch origin main && git merge origin/main` before final push. +2. Push `-` to the fork; wait for green Actions. +3. Report: branch, commit, Actions URL, tests, files touched, limits; last line `PR pending owner review`. +4. Research / Enrichment / Review comments start with `Base: fork/main at `. + +## Parallelism + +Maximize concurrent agents on parallel-safe tickets. Serial lane: `crates/ui-egui/src/lib.rs` (`conflict:ui-egui-lib`). New e2e: `crates/ui-egui/tests/e2e/.rs`, name `a_newcomer_*`. + +## Stop rule + +Identical failure twice → `status:blocked`, stop fixing blindly. diff --git a/.cursor/rules/pcbcraft-rust.mdc b/.cursor/rules/pcbcraft-rust.mdc new file mode 100644 index 000000000..a94e6bf94 --- /dev/null +++ b/.cursor/rules/pcbcraft-rust.mdc @@ -0,0 +1,13 @@ +--- +description: Rust crate edits in PCBCraft engine and IO layers +globs: crates/**/*.rs,xtask/**/*.rs,apps/**/*.rs +alwaysApply: false +--- + +# Rust edits + +- Mutations live in `crates/engine`; schemas and validation bounds stay strict. +- Golden fixtures under `crates//tests/fixtures/` for readers/writers. +- Unit test names as sentences: `rejects_out_of_range`, not `test_foo`. +- Before push: prefer fork CI; optional local `cargo xtask test -p ` for tight loops. +- Layer check is in CI: `cargo xtask policy` (see `docs/ci.md`). diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..b5e7dc98d --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,25 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions: + patterns: ["*"] + + - package-ecosystem: cargo + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + cargo-minor: + update-types: [minor, patch] + ignore: + # egui, eframe and craft-ui move together; bump them by hand. + - dependency-name: egui + update-types: [version-update:semver-major, version-update:semver-minor] + - dependency-name: eframe + update-types: [version-update:semver-major, version-update:semver-minor] + - dependency-name: craft-ui diff --git a/.github/docs-ci-notes-issue-479.txt b/.github/docs-ci-notes-issue-479.txt new file mode 100644 index 000000000..83966686e --- /dev/null +++ b/.github/docs-ci-notes-issue-479.txt @@ -0,0 +1,4 @@ +For docs-agent D451: update docs/ci.md Releases section to list, per linux-x86_64 and linux-aarch64: +- pcbcraft--linux-.AppImage and .AppImage.zsync +- pcbcraft--linux-.deb and .rpm +Keep the existing .tar.gz line. Note packaging/linux/package.sh (CI: build-dist.yml Linux jobs on ubuntu-22.04) and that legacy flat tarballs still come from .github/scripts/package.sh. diff --git a/.github/scripts/package.sh b/.github/scripts/package.sh new file mode 100644 index 000000000..c5aee073c --- /dev/null +++ b/.github/scripts/package.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Package release binaries that were already built with `cargo build --release`. +# Used by .github/workflows/build-dist.yml for nightly and tagged builds. +# +# usage: package.sh +# platform: linux-x86_64 | linux-aarch64 | windows-x86_64 | macos-universal +# +# Reads binaries from target//release. Writes archives into . +set -euo pipefail + +platform=$1 +version=$2 +out=$3 +mkdir -p "$out" +out=$(cd "$out" && pwd) + +name="pcbcraft-$version-$platform" +stage="$(mktemp -d)/$name" +mkdir -p "$stage" +docs=(LICENSE NOTICE ATTRIBUTION.md README.md) +cp "${docs[@]}" "$stage/" +mkdir -p "$stage/examples" +cp examples/* "$stage/examples/" + +case "$platform" in + linux-x86_64 | linux-aarch64) + triple=$([ "$platform" = linux-x86_64 ] && echo x86_64-unknown-linux-gnu || echo aarch64-unknown-linux-gnu) + install -m 755 "target/$triple/release/pcbcraft" "target/$triple/release/pcbcraft-cli" "$stage/" + tar -C "$(dirname "$stage")" -czf "$out/$name.tar.gz" "$name" + ;; + windows-x86_64) + triple=x86_64-pc-windows-msvc + cp "target/$triple/release/pcbcraft.exe" "target/$triple/release/pcbcraft-cli.exe" "$stage/" + (cd "$(dirname "$stage")" && 7z a -tzip -bso0 "$out/$name.zip" "$name") + ;; + macos-universal) + # One binary for Apple silicon and Intel. + bin="$stage/bin" + mkdir -p "$bin" + for exe in pcbcraft pcbcraft-cli; do + lipo -create \ + "target/aarch64-apple-darwin/release/$exe" \ + "target/x86_64-apple-darwin/release/$exe" \ + -output "$bin/$exe" + done + app="$stage/PCBCraft.app" + mkdir -p "$app/Contents/MacOS" + cp "$bin/pcbcraft" "$app/Contents/MacOS/pcbcraft" + cat > "$app/Contents/Info.plist" < + + + + CFBundleNamePCBCraft + CFBundleDisplayNamePCBCraft + CFBundleIdentifier${MACOS_BUNDLE_ID:-io.github.tangency-labs.pcbcraft} + CFBundleExecutablepcbcraft + CFBundlePackageTypeAPPL + CFBundleShortVersionString${version#v} + CFBundleVersion${version#v} + LSMinimumSystemVersion11.0 + NSHighResolutionCapable + + +PLIST + rm "$bin/pcbcraft" + tar -C "$(dirname "$stage")" -czf "$out/$name.tar.gz" "$name" + hdiutil create -quiet -volname "PCBCraft $version" -srcfolder "$stage" -ov -format UDZO "$out/$name.dmg" + ;; + *) + echo "unknown platform $platform" >&2 + exit 1 + ;; +esac + +ls -l "$out" diff --git a/.github/workflows/build-dist.yml b/.github/workflows/build-dist.yml new file mode 100644 index 000000000..2990628ac --- /dev/null +++ b/.github/workflows/build-dist.yml @@ -0,0 +1,286 @@ +# Release builds for every platform. Called by nightly.yml and release.yml so +# nightly runs exercise the exact packaging that a tagged release uses. +# No build cache here: release artifacts are built from a clean state. +# +# Linux: AppImage (+ .zsync), .deb, .rpm, FHS .tar.gz (Flatpak/Snap), then Flatpak and Snap +# repackage jobs. No Snap Store or Flathub upload in CI. +# +# docs-agent (D451): when Linux installers land, extend docs/ci.md Releases section with +# AppImage (+ .zsync), .deb, and .rpm per arch; point packaging/linux/package.sh for repro. +name: Build distributables + +on: + workflow_call: + inputs: + version: + description: Version string used in archive names, for example v0.1.0 or nightly-20261028 + required: true + type: string + ref: + description: Commit, branch or tag to build + required: true + type: string + retention-days: + required: false + type: number + default: 14 + +permissions: {} + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + CARGO_NET_RETRY: 10 + +jobs: + native: + name: Package (${{ matrix.platform }}) + runs-on: ${{ matrix.os }} + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - platform: linux-x86_64 + os: ubuntu-22.04 + targets: x86_64-unknown-linux-gnu + deb: amd64 + - platform: linux-aarch64 + os: ubuntu-22.04-arm + targets: aarch64-unknown-linux-gnu + deb: arm64 + - platform: windows-x86_64 + os: windows-2025 + targets: x86_64-pc-windows-msvc + - platform: macos-universal + os: macos-15 + targets: aarch64-apple-darwin,x86_64-apple-darwin + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + - name: Install window-system packages + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libxkbcommon-dev libwayland-dev \ + libx11-dev libxi-dev libxrandr-dev libxcursor-dev libgl1-mesa-dev + - name: Install Linux packaging tools + if: runner.os == 'Linux' + env: + NFPM_VERSION: 2.47.0 + run: | + sudo apt-get install -y --no-install-recommends desktop-file-utils appstream zsync rpm \ + librsvg2-bin + curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \ + "https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb" + sudo dpkg -i "$RUNNER_TEMP/nfpm.deb" + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + targets: ${{ matrix.targets }} + - name: Build release binaries + shell: bash + env: + TARGETS: ${{ matrix.targets }} + run: | + for target in ${TARGETS//,/ }; do + cargo build --locked --release -p pcbcraft -p pcbcraft-cli --target "$target" + done + - name: Package Linux installers + if: runner.os == 'Linux' + shell: bash + env: + PCBCRAFT_DIST_TAG: ${{ inputs.version }} + DIST: ${{ github.workspace }}/dist + LINUX_TARGET: ${{ matrix.targets }} + run: packaging/linux/package.sh --skip-build + - name: Check Linux packages + if: runner.os == 'Linux' + shell: bash + env: + VERSION: ${{ inputs.version }} + LINUX_TARGET: ${{ matrix.targets }} + run: | + dpkg-deb --info dist/*.deb + dpkg-deb --contents dist/*.deb | grep -E 'usr/bin/pcbcraft$|usr/bin/pcbcraft-cli$|metainfo|applications|ATTRIBUTION.md' + rpm -qip dist/*.rpm + rpm -qlp dist/*.rpm | grep -E '/usr/bin/pcbcraft$|ATTRIBUTION.md' + ldd "target/$LINUX_TARGET/release/pcbcraft" + for appimage in dist/*.AppImage; do + chmod +x "$appimage" + APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --help + "$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|' + test -s "$appimage.zsync" + done + - name: Package + shell: bash + env: + PLATFORM: ${{ matrix.platform }} + VERSION: ${{ inputs.version }} + run: bash .github/scripts/package.sh "$PLATFORM" "$VERSION" dist + - name: Linux FHS tarball for Flatpak and Snap + if: runner.os == 'Linux' + shell: bash + env: + PCBCRAFT_DIST_TAG: ${{ inputs.version }} + DIST: ${{ github.workspace }}/dist + LINUX_TARGET: ${{ matrix.targets }} + run: packaging/linux/package.sh --skip-build --formats tar + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist-${{ matrix.platform }} + path: dist/* + if-no-files-found: error + retention-days: ${{ inputs.retention-days }} + + flatpak: + name: Flatpak (${{ matrix.arch }}) + needs: native + permissions: + contents: read + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - { arch: x86_64, platform: linux-x86_64, runner: ubuntu-24.04 } + - { arch: aarch64, platform: linux-aarch64, runner: ubuntu-24.04-arm } + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist-${{ matrix.platform }} + path: dist + - name: Install flatpak-builder + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Build the Flatpak bundle + shell: bash + env: + PCBCRAFT_DIST_TAG: ${{ inputs.version }} + DIST: ${{ github.workspace }}/dist + run: | + tarball="dist/pcbcraft-$PCBCRAFT_DIST_TAG-linux-${{ matrix.arch }}.tar.gz" + test -s "$tarball" + packaging/linux/flatpak-bundle.sh --no-test "$tarball" + - name: Version-less Flatpak name for latest download links + shell: bash + env: + VERSION: ${{ inputs.version }} + run: | + shopt -s nullglob + for f in dist/pcbcraft-"$VERSION"-linux-*.flatpak; do + cp -- "$f" "dist/pcbcraft-${f#dist/pcbcraft-$VERSION-}" + done + ls -l dist/*.flatpak + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist-flatpak-${{ matrix.arch }} + path: dist/*.flatpak + if-no-files-found: error + retention-days: ${{ inputs.retention-days }} + + snap: + name: Snap (${{ matrix.arch }}) + needs: native + permissions: + contents: read + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - { arch: x86_64, platform: linux-x86_64, runner: ubuntu-24.04 } + - { arch: aarch64, platform: linux-aarch64, runner: ubuntu-24.04-arm } + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist-${{ matrix.platform }} + path: dist + - name: Install snapcraft + run: sudo snap install snapcraft --classic + - name: Build the snap + shell: bash + env: + PCBCRAFT_DIST_TAG: ${{ inputs.version }} + DIST: ${{ github.workspace }}/dist + run: | + tarball="dist/pcbcraft-$PCBCRAFT_DIST_TAG-linux-${{ matrix.arch }}.tar.gz" + test -s "$tarball" + sudo --preserve-env=PCBCRAFT_DIST_TAG,DIST,PCBCRAFT_VERSION,VERSION,ROOT env "PATH=$PATH" \ + packaging/linux/snap-pack.sh --destructive-mode "$tarball" + sudo chown -R "$(id -u):$(id -g)" dist target 2>/dev/null || sudo chown -R "$(id -u):$(id -g)" dist + - name: Install and check the snap + shell: bash + env: + PCBCRAFT_DIST_TAG: ${{ inputs.version }} + run: | + snap_file="dist/pcbcraft-$PCBCRAFT_DIST_TAG-linux-${{ matrix.arch }}.snap" + sudo snap install --dangerous "$snap_file" + snap info --verbose "$snap_file" | head -n 12 + pcbcraft.cli help >/dev/null + - name: Version-less snap name for latest download links + shell: bash + env: + VERSION: ${{ inputs.version }} + run: | + shopt -s nullglob + for f in dist/pcbcraft-"$VERSION"-linux-*.snap; do + cp -- "$f" "dist/pcbcraft-${f#dist/pcbcraft-$VERSION-}" + done + ls -l dist/*.snap + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist-snap-${{ matrix.arch }} + path: dist/*.snap + if-no-files-found: error + retention-days: ${{ inputs.retention-days }} + + web: + name: Package (web) + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + targets: wasm32-unknown-unknown + - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 + with: + tool: trunk + - name: Build the browser bundle + working-directory: apps/pcbcraft-web + run: trunk build --release --public-url ./ + - name: Package + env: + VERSION: ${{ inputs.version }} + run: | + name="pcbcraft-$VERSION-web" + mkdir -p dist "stage/$name" + cp -r apps/pcbcraft-web/dist/. "stage/$name/" + cp LICENSE NOTICE ATTRIBUTION.md "stage/$name/" + (cd stage && zip -qr "../dist/$name.zip" "$name") + ls -l dist + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist-web + path: dist/* + if-no-files-found: error + retention-days: ${{ inputs.retention-days }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2edabeb37..67d082ed5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,22 +1,484 @@ -name: Rust checks -on: [push, pull_request] -permissions: - contents: read +# Pull request and branch gate. Each job runs one `cargo xtask` step, so any +# failure can be reproduced locally with the same command. See docs/ci.md. +name: CI + +on: + push: + branches: ["**"] + pull_request: + merge_group: + workflow_dispatch: + +permissions: {} + +concurrency: + # One run per pull request or branch. A new push cancels the older run, + # except on main where every commit keeps its result. + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + CARGO_NET_RETRY: 10 + RUST_BACKTRACE: 1 + # Build dependencies needed by eframe's x11 and wayland features. + LINUX_DEPS: libxkbcommon-dev libwayland-dev libx11-dev libxi-dev libxrandr-dev libxcursor-dev libgl1-mesa-dev + jobs: - linux: - runs-on: ubuntu-latest + changes: + name: Changes + # In the upstream repository, branch pushes other than main are covered by + # their pull request. Forks run on every push so stacked branches get + # results without waiting for workflow approval upstream. + if: >- + github.event_name != 'push' + || github.ref == 'refs/heads/main' + || github.repository != 'tangency-labs/pcbcraft' + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: + contents: read + outputs: + rust: ${{ steps.filter.outputs.rust }} steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + fetch-depth: 0 + persist-credentials: false + - id: filter + name: Skip heavy jobs for documentation-only changes + env: + EVENT: ${{ github.event_name }} + PR_BASE: ${{ github.event.pull_request.base.sha }} + PUSH_BEFORE: ${{ github.event.before }} + run: | + base="" + if [ "$EVENT" = pull_request ]; then + base=$(git merge-base "$PR_BASE" HEAD || true) + elif [ "$EVENT" = push ] && [ -n "$PUSH_BEFORE" ] && ! echo "$PUSH_BEFORE" | grep -qE '^0+$'; then + base="$PUSH_BEFORE" + fi + if [ -z "$base" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null; then + echo "No usable base commit; running everything." + echo "rust=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + changed=$(git diff --name-only "$base" HEAD) + printf 'Changed files:\n%s\n' "$changed" + code=$(printf '%s\n' "$changed" | grep -vE '^$|\.md$|^docs/|^LICENSE$|^NOTICE$|^\.github/ISSUE_TEMPLATE/' || true) + if [ -n "$code" ]; then + echo "rust=true" >> "$GITHUB_OUTPUT" + else + echo "Only documentation changed; skipping build jobs." + echo "rust=false" >> "$GITHUB_OUTPUT" + fi + + policy: + name: Format and policy + needs: changes + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + components: rustfmt + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: xtask + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo xtask policy + - run: cargo xtask fmt + + lint: + name: Clippy and docs + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft-laptop"]') || 'ubuntu-24.04' }} + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install window-system packages + run: | + sudo apt-get update + # shellcheck disable=SC2086 # LINUX_DEPS is a word list + sudo apt-get install -y --no-install-recommends $LINUX_DEPS + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + components: clippy + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: lint + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo xtask clippy + - run: cargo xtask docs + + docs-check: + name: Documentation standard + needs: changes + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install window-system packages + run: | + sudo apt-get update + # shellcheck disable=SC2086 # LINUX_DEPS is a word list + sudo apt-get install -y --no-install-recommends $LINUX_DEPS + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: docs-check + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo xtask docs check + + test: + name: Tests + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft-laptop"]') || 'ubuntu-24.04' }} + permissions: + contents: read + env: + NEXTEST_PROFILE: ci + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install window-system packages + run: | + sudo apt-get update + # shellcheck disable=SC2086 # LINUX_DEPS is a word list + sudo apt-get install -y --no-install-recommends $LINUX_DEPS + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 + with: + tool: cargo-nextest + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: test + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo xtask test + - name: Upload test report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: test-report + path: target/nextest/ci/junit.xml + if-no-files-found: ignore + retention-days: 14 + + e2e: + name: E2E stories and control coverage + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft-laptop"]') || 'ubuntu-24.04' }} + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install window-system packages + run: | + sudo apt-get update + # shellcheck disable=SC2086 # LINUX_DEPS is a word list + sudo apt-get install -y --no-install-recommends $LINUX_DEPS + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: test + save-if: false + # Runs every a_newcomer_* story, walks every page of the UI, and fails + # naming each control that has no tooltip or no story. + - run: cargo xtask e2e + - name: Upload the control coverage report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: e2e-coverage + path: target/e2e/ + if-no-files-found: ignore + retention-days: 14 + + strings: + name: UI strings are in the catalog + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install window-system packages + run: | + sudo apt-get update + # shellcheck disable=SC2086 # LINUX_DEPS is a word list + sudo apt-get install -y --no-install-recommends $LINUX_DEPS + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: strings + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo xtask strings check + + wasm: + name: WebAssembly + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable targets: wasm32-unknown-unknown - components: rustfmt, clippy - - name: Window-system dependencies - run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libwayland-dev libx11-dev libxi-dev libxrandr-dev libxcursor-dev libgl1-mesa-dev - - run: cargo xtask ci - windows: - runs-on: windows-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - run: cargo build -p pcbcraft -p pcbcraft-cli + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: wasm + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo xtask wasm + + msrv: + name: Minimum Rust version + needs: changes + # Main and manual runs only: pull requests share a small pool of hosted runners. + if: needs.changes.outputs.rust == 'true' && github.event_name != 'pull_request' + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install window-system packages + run: | + sudo apt-get update + # shellcheck disable=SC2086 # LINUX_DEPS is a word list + sudo apt-get install -y --no-install-recommends $LINUX_DEPS + - name: Read rust-version from Cargo.toml + id: msrv + run: echo "version=$(sed -n 's/^rust-version *= *"\(.*\)"/\1/p' Cargo.toml)" >> "$GITHUB_OUTPUT" + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: ${{ steps.msrv.outputs.version }} + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: msrv + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo xtask msrv + + deny: + name: Licenses and advisories + needs: changes + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 + with: + tool: cargo-deny + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: xtask + save-if: false + - run: cargo xtask deny + + screenshots: + name: UI screenshots (${{ matrix.side }}) + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: + contents: read + strategy: + fail-fast: false + matrix: + # Pull requests also capture their base so reviewers can compare. + side: ${{ fromJSON(github.event_name == 'pull_request' && '["head","base"]' || '["head"]') }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Check out the base commit next to the head + if: matrix.side == 'base' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: base-tree + persist-credentials: false + - name: Install window-system and software rendering packages + run: | + sudo apt-get update + # shellcheck disable=SC2086 # LINUX_DEPS is a word list + sudo apt-get install -y --no-install-recommends $LINUX_DEPS \ + xvfb xauth mesa-vulkan-drivers libvulkan1 libxkbcommon-x11-0 + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: screenshots + save-if: ${{ github.ref == 'refs/heads/main' && matrix.side == 'head' }} + - name: Build the desktop app + env: + SIDE: ${{ matrix.side }} + run: | + # The base tree builds into the same target directory so both sides + # share the cache and the binary path. + if [ "$SIDE" = base ]; then + CARGO_TARGET_DIR="$PWD/target" cargo build --locked -p pcbcraft --manifest-path base-tree/Cargo.toml + else + cargo build --locked -p pcbcraft + fi + - name: Capture views under Xvfb with Mesa software Vulkan + env: + SIDE: ${{ matrix.side }} + WGPU_BACKEND: vulkan + run: | + xvfb-run -a -s '-screen 0 1600x1100x24' \ + env -u WAYLAND_DISPLAY \ + cargo xtask screenshots --bin target/debug/pcbcraft --out "screenshots/$SIDE" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: ${{ !cancelled() }} + with: + name: screenshots-${{ matrix.side }} + path: screenshots/${{ matrix.side }} + if-no-files-found: warn + retention-days: 30 + + screenshot-sheet: + name: UI screenshot sheet + needs: screenshots + if: ${{ !cancelled() && needs.screenshots.result != 'skipped' }} + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: + contents: read + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: screenshots-head + path: shots/head + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + # Only pull requests capture a base. + if: github.event_name == 'pull_request' + continue-on-error: true + with: + name: screenshots-base + path: shots/base + - name: Build one side-by-side sheet + run: | + sudo apt-get update && sudo apt-get install -y --no-install-recommends imagemagick + mkdir -p sheet + args=() + for head in shots/head/*.png; do + name=$(basename "$head") + base="shots/base/$name" + if [ -d shots/base ]; then + if [ -f "$base" ]; then args+=("$base"); else args+=("null:"); fi + fi + args+=("$head") + done + tile=1x + [ -d shots/base ] && tile=2x + montage "${args[@]}" -resize 50% -tile "$tile" -geometry +6+6 -background '#222' sheet/ui-screenshots.png + - id: upload + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ui-screenshots.png + path: sheet/ui-screenshots.png + archive: false + retention-days: 30 + - name: Link the sheet from the run summary + env: + SHEET_URL: ${{ steps.upload.outputs.artifact-url }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + { + echo "## UI screenshots" + echo + echo "[Open the screenshot sheet]($SHEET_URL). Left column is the base branch, right column is this change." + echo "Full-size PNGs are in the screenshots-head and screenshots-base artifacts of [this run]($RUN_URL)." + } >> "$GITHUB_STEP_SUMMARY" + + build: + name: Build (${{ matrix.os }}) + needs: changes + # Main and manual runs only: pull requests share a small pool of hosted runners. + if: needs.changes.outputs.rust == 'true' && github.event_name != 'pull_request' + runs-on: ${{ matrix.os }} + permissions: + contents: read + strategy: + fail-fast: false + matrix: + # Windows on every change; macOS on main, merge queue and manual runs. + os: ${{ fromJSON((github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref != 'refs/heads/main')) && '["windows-2025"]' || '["windows-2025","macos-15"]') }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + shared-key: build + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo build --locked -p pcbcraft -p pcbcraft-cli + + result: + name: CI result + # The single check to mark as required in branch protection. + needs: [changes, policy, lint, docs-check, strings, test, e2e, wasm, msrv, deny, screenshots, build] + if: always() + runs-on: ${{ github.repository == 'wdunn001/pcbcraft' && fromJSON('["self-hosted","pcbcraft"]') || 'ubuntu-24.04' }} + permissions: {} + steps: + - env: + RESULTS: ${{ toJSON(needs.*.result) }} + CHANGES: ${{ needs.changes.result }} + run: | + echo "$RESULTS" + if [ "$CHANGES" = skipped ]; then + echo "Branch push covered by its pull request run." + exit 0 + fi + if echo "$RESULTS" | grep -qE '"(failure|cancelled)"'; then + echo "A required job failed or was cancelled." + exit 1 + fi diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 000000000..fdf54d08e --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,69 @@ +# Nightly: platform packages from main as workflow artifacts, plus an advisory +# scan that catches new security advisories without a code change. +name: Nightly + +on: + schedule: + - cron: "17 5 * * *" + workflow_dispatch: + +permissions: {} + +concurrency: + group: nightly + cancel-in-progress: true + +jobs: + stamp: + name: Version stamp + runs-on: ubuntu-24.04 + permissions: + contents: read + outputs: + version: ${{ steps.stamp.outputs.version }} + sha: ${{ steps.stamp.outputs.sha }} + changed: ${{ steps.stamp.outputs.changed }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - id: stamp + env: + EVENT: ${{ github.event_name }} + run: | + sha=$(git rev-parse HEAD) + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "version=nightly-$(date -u +%Y%m%d)-$(git rev-parse --short=8 HEAD)" >> "$GITHUB_OUTPUT" + # Scheduled runs skip packaging when main has not moved for a day. + age=$(( $(date +%s) - $(git log -1 --format=%ct) )) + if [ "$EVENT" = workflow_dispatch ] || [ "$age" -lt 90000 ]; then + echo "changed=true" >> "$GITHUB_OUTPUT" + else + echo "changed=false" >> "$GITHUB_OUTPUT" + fi + + dist: + name: Distributables + needs: stamp + if: needs.stamp.outputs.changed == 'true' + permissions: + contents: read + uses: ./.github/workflows/build-dist.yml + with: + version: ${{ needs.stamp.outputs.version }} + ref: ${{ needs.stamp.outputs.sha }} + retention-days: 14 + + advisories: + name: Security advisories + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 + with: + tool: cargo-deny + - run: cargo deny --workspace --all-features check advisories diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000..7636237f4 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,169 @@ +# Tagged release: build every platform, attach checksums and GPL source +# archives, and open a DRAFT GitHub Release. A maintainer reviews and +# publishes it by hand; this workflow never publishes. +# +# Primary packages are also attached without the tag in their names +# (pcbcraft-linux-x86_64.tar.gz, pcbcraft-windows-x86_64.zip, ...) so +# releases/latest/download/ links keep working across releases. +name: Release + +on: + push: + tags: ["v*"] + workflow_dispatch: + inputs: + tag: + description: Existing tag to build, for example v0.1.0 + required: true + type: string + +permissions: {} + +concurrency: + group: release-${{ github.event.inputs.tag || github.ref_name }} + cancel-in-progress: false + +jobs: + verify: + name: Verify tag + runs-on: ubuntu-24.04 + permissions: + contents: read + outputs: + tag: ${{ steps.tag.outputs.tag }} + steps: + - id: tag + env: + INPUT_TAG: ${{ github.event.inputs.tag }} + REF_NAME: ${{ github.ref_name }} + run: | + tag=${INPUT_TAG:-$REF_NAME} + if ! echo "$tag" | grep -qE '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then + echo "Tag $tag is not of the form vX.Y.Z or vX.Y.Z-suffix" >&2 + exit 1 + fi + echo "tag=$tag" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: refs/tags/${{ steps.tag.outputs.tag }} + persist-credentials: false + - name: Tag matches the workspace version + env: + TAG: ${{ steps.tag.outputs.tag }} + run: | + version=$(sed -n '/^\[workspace.package\]/,/^\[/s/^version *= *"\(.*\)"/\1/p' Cargo.toml) + if [ "v$version" != "${TAG%%-*}" ] && [ "v$version" != "$TAG" ]; then + echo "Cargo.toml version $version does not match tag $TAG" >&2 + exit 1 + fi + + dist: + name: Distributables + needs: verify + permissions: + contents: read + uses: ./.github/workflows/build-dist.yml + with: + version: ${{ needs.verify.outputs.tag }} + ref: refs/tags/${{ needs.verify.outputs.tag }} + retention-days: 7 + + source: + name: Source archives + needs: verify + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: refs/tags/${{ needs.verify.outputs.tag }} + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - name: Source tarball and vendored dependencies + env: + TAG: ${{ needs.verify.outputs.tag }} + run: | + mkdir -p dist + git archive --format=tar.gz --prefix="pcbcraft-$TAG/" -o "dist/pcbcraft-$TAG-source.tar.gz" HEAD + # Complete corresponding source for the binaries, including every + # Rust dependency at the locked version, so the build works offline. + stage="pcbcraft-$TAG" + git archive --format=tar --prefix="$stage/" HEAD | tar -x + (cd "$stage" && mkdir -p .cargo && cargo vendor --locked --versioned-dirs vendor >> .cargo/config.toml) + tar -czf "dist/pcbcraft-$TAG-source-vendored.tar.gz" "$stage" + ls -l dist + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist-source + path: dist/* + if-no-files-found: error + retention-days: 7 + + draft: + name: Draft GitHub Release + needs: [verify, dist, source] + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: refs/tags/${{ needs.verify.outputs.tag }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: dist-* + path: dist + merge-multiple: true + - name: Version-less copies for permanent download links + working-directory: dist + env: + TAG: ${{ needs.verify.outputs.tag }} + run: | + shopt -s nullglob + for f in "pcbcraft-$TAG-"*; do + case "$f" in + *-source.tar.gz | *-source-vendored.tar.gz) ;; + *.tar.gz | *.zip | *.dmg) + cp -- "$f" "pcbcraft-${f#"pcbcraft-$TAG-"}" ;; + esac + done + for f in pcbcraft-linux-x86_64.tar.gz pcbcraft-linux-aarch64.tar.gz \ + pcbcraft-windows-x86_64.zip pcbcraft-macos-universal.tar.gz \ + pcbcraft-macos-universal.dmg pcbcraft-web.zip; do + test -s "$f" || { echo "missing version-less copy $f" >&2; exit 1; } + done + ls -l pcbcraft-linux-* pcbcraft-windows-* pcbcraft-macos-* pcbcraft-web.zip + - name: Checksums + working-directory: dist + run: | + sha256sum -- * | tee SHA256SUMS.txt + cat SHA256SUMS.txt + - name: Changelog from commits since the previous tag + env: + TAG: ${{ needs.verify.outputs.tag }} + run: | + previous=$(git describe --tags --abbrev=0 --match 'v*' "$TAG^" 2>/dev/null || true) + range=${previous:+$previous..}$TAG + { + if [ -n "$previous" ]; then echo "Changes since $previous:"; else echo "Changes:"; fi + echo + git log --no-merges --reverse --format='- %s (%h)' "$range" + echo + echo "Binaries are not code-signed yet. Verify downloads against SHA256SUMS.txt." + echo "The source archives are the complete corresponding source under GPL-3.0-or-later." + } > notes.md + cat notes.md + - name: Create the draft release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.verify.outputs.tag }} + run: | + prerelease=() + case "$TAG" in *-*) prerelease=(--prerelease) ;; esac + gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --draft --verify-tag \ + "${prerelease[@]}" --title "PCBCraft $TAG" --notes-file notes.md dist/* diff --git a/.gitignore b/.gitignore index ee2526dd6..8156fb354 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ /target/ *.pcbcraft.tmp /work/ +__pycache__/ + +site/docs-preview/ +/apps/pcbcraft-web/dist/ diff --git a/AGENTS.md b/AGENTS.md index 936cdca23..f7bf05b9d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,23 +1,52 @@ -# PCBCraft - -A complete EDA application being built in Rust, GPL-3.0-or-later, MCP-first. - -Read README.md, ROADMAP.md and docs/architecture.md at the start of work. - -- One main window. Document/workspace tabs and docked panes. Never spawn separate - schematic, board, library, checks or 3D windows. Keep project and selection shared. -- Everything that edits the project is a typed engine command. UI, CLI and MCP - call the same engine. Programmatic commands never open dialogs. -- Validate all input; finite bounded coordinates and dimensions, bounded counts, - stable IDs, reference integrity. Invalid commands and batches leave state untouched. -- No unsafe or production unwrap/expect/panic/todo/unimplemented/unreachable. -- Lower crates never depend on egui, eframe, wgpu, or MCP. UI is replaceable. -- KiCad source may be inspected and GPL-compatible code adapted. Record exact - source/revision/license in ATTRIBUTION.md for adaptations. Translation to Rust - does not remove attribution or copyleft requirements. Check individual licenses. -- Shared Craft dependencies retain their licenses and notices. Do not copy ArtCraft - trademarks or proprietary assets. Pin craft-libs revisions. -- Keep real feature limitations visible. Do not represent initial checks as complete - ERC/DRC or a basic route as a shove router. Track parity by workflows and fixtures. -- Before committing: cargo xtask ci. Inspect rendered UI for UI changes. -- Do not publish releases or push to third-party repositories without authorization. +# PCBCraft agent instructions + +Rust EDA app, GPL-3.0-or-later, MCP-first. **Codebase of record:** [wdunn001/pcbcraft](https://github.com/wdunn001/pcbcraft) branch `main` (not upstream tangency-labs until integrator opens a PR). Onboarding: [docs/getting-started.md](docs/getting-started.md), fork issue [#1](https://github.com/wdunn001/pcbcraft/issues/1), full pipeline in CONTRIBUTING.md. + +## Before coding + +Read README.md (what works), ROADMAP.md, docs/architecture.md. For a claimed issue, read its body plus every `### Research` and `### Enrichment` comment. + +## Before editing a file (docs/doc-standard.md) + +- **Pre-edit:** read the file's `//!` header and the doc block of each function you change. +- **Pre-edit:** confirm every path under `# Dependencies` and every `Contract:` line exists. If one is missing, stop and report it on the issue. Do not guess a path. +- **Pre-edit:** before editing a trait or the engine command registry, open every file under its `# Implementations`. If the list is missing or stale, stop and report. +- Never shorten a `# Do not` section; only append to it. +- Each rule lives at the layer it governs (this file, `//!` header, trait or shared type, function). Point up to a rule; do not copy it down. +- `cargo xtask docs check` must pass (docs/ci.md). + +## Parallel agents + +- **One clone or worktree per agent.** Never share a checkout another agent is using. +- **One claimed issue** unless stacked children of one epic. +- **Workers** claim only upstream issues tagged `ready` and `status:open`. On a shared machine, also require `conflict:parallel-safe`. +- **Conflict lane:** only the active `conflict:ui-egui-lib` ticket may edit `crates/ui-egui/src/lib.rs`. Everyone else keeps UI shell changes out of that file; put `a_newcomer_*` tests in `crates/ui-egui/src/e2e/.rs` (helpers in `src/e2e/support.rs`). +- **Branch** from fork `main`: `-` (see CONTRIBUTING.md §7). Merge latest fork `main` before final push. Push your branch only; never push to `main`; do not open pull requests (maintainer integrates). + +## CI (source of truth) + +Green **GitHub Actions on the fork** for the commit you report is required proof. Push early; link the run in your build report. Local `cargo xtask ci` is optional; job list in docs/ci.md. Done = merged into fork `main` with Actions green there. + +## Architecture invariants + +- One main window: tabs and docked panes only; shared project and selection. +- All mutations: typed engine commands (UI, CLI, MCP); programmatic paths never open dialogs. +- Validate inputs (bounded coords, counts, stable IDs, reference integrity). Invalid command/batch leaves state untouched. +- No `unsafe`; no production `unwrap`/`expect`/`panic`/`todo`/`unimplemented`/`unreachable`. +- Layering: geom → doc/library → rules/io → engine → mcp/ui-egui → apps. Lower crates never depend on egui, eframe, wgpu, or MCP. + +## Content and honesty + +- GPL adaptations: record source, revision, license in ATTRIBUTION.md. Pin craft-libs; no proprietary Craft trademarks/assets. +- Do not name other EDA products in code, docs, UI, commits, or issue comments. +- Do not oversell checks or routing; state limits in UI where users hit them. +- UI: every control gets a tooltip of at most two lines: what it does, why or when, its shortcut, and its limits. Disabled controls say how to enable them. Full rule: [docs/tooltips.md](docs/tooltips.md). Real margins; inspect rendered UI for visual changes (`track:ui-design` → screenshots in report). +- No AI attribution in commits. No releases or third-party pushes without authorization. + +## Stuck + +Same build/test failure twice with identical output → post output, set `status:blocked`, stop (CONTRIBUTING.md §9). + +## Cloud Agent fleet + +Workers push a branch only and never open a pull request; the integrator merges with `git merge`. Full text: docs/agents/README.md, section "Fleet rules". diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 5b309469d..703b52dcc 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -4,9 +4,22 @@ |---|---|---|---| | craft-ui | https://github.com/storytold/craft-libs | 1aa81a773aa9198a0e4c0daeda954d622475af38; MIT OR Apache-2.0 | Shared egui tab and widget components, Cargo dependency | | SolidCraft architecture | https://github.com/bherbruck/solidcraft | README / AGENTS consulted; MIT OR Apache-2.0 | Architectural reference; no implementation copied | +| SolidCraft agent chat backend | https://github.com/bherbruck/solidcraft | 32558d0a; MIT OR Apache-2.0 | Adapted into `crates/assistant/src/backend.rs` | +| SolidCraft agent chat transcript | https://github.com/bherbruck/solidcraft | 32558d0a; MIT OR Apache-2.0 | Adapted into `crates/assistant/src/transcript.rs` and `turn.rs` | +| SolidCraft agent chat test script backend | https://github.com/bherbruck/solidcraft | 32558d0a; MIT OR Apache-2.0 | Adapted into `crates/assistant/src/script.rs` | +| SolidCraft agent chat API backend | https://github.com/bherbruck/solidcraft | 32558d0a; MIT OR Apache-2.0 | Adapted into `crates/assistant/src/api.rs` | +| SolidCraft agent chat gate | https://github.com/bherbruck/solidcraft | 32558d0a; MIT OR Apache-2.0 | Adapted into `crates/assistant/src/gate.rs` | +| SolidCraft agent chat connections and presets | https://github.com/bherbruck/solidcraft | 32558d0a; MIT OR Apache-2.0 | Adapted into `crates/assistant/src/connections.rs` | +| SolidCraft agent chat settings page | https://github.com/bherbruck/solidcraft | 32558d0a; MIT OR Apache-2.0 | Adapted in shape into `crates/ui-egui/src/assistant/settings.rs` | +| SolidCraft Linux packaging | https://github.com/bherbruck/solidcraft | packaging/linux and packaging/env.sh at 2026-03; MIT OR Apache-2.0 | Adapted AppImage, deb, and rpm scripts, nfpm config, AppRun, and postinst for PCBCraft | +| IBM Plex Sans (SemiBold) | https://github.com/IBM/plex | Copyright IBM Corp., Reserved Font Name "Plex"; SIL Open Font License 1.1, text in `assets/brand/fonts/OFL.txt` | Outlined to paths in the wordmark masters under `assets/brand/`; the font file is kept there only so `assets/brand/build.sh` can regenerate them | | KiCad board format | https://dev-docs.kicad.org/en/file-formats/sexpr-pcb/ | Public format documentation | Original limited board writer | | KiCad library formats | https://dev-docs.kicad.org/en/file-formats/ | Public format documentation | Original Rust symbol/footprint readers | | KiCad library fixtures | https://gitlab.com/kicad/libraries/kicad-symbols and https://gitlab.com/kicad/libraries/kicad-footprints | Ubuntu packages 10.0.6~ubuntu24.04.1; CC-BY-SA 4.0 + KiCad design-output exception | Extracted R/LED/LM2904/LM358 symbols and unmodified R_0805 footprint; community contributors; exact provenance/checksums and modifications in docs/kicad-libraries.md; original license in crates/library/tests/fixtures/LICENSE-kicad-libraries.md | +| IBM Plex Sans | https://github.com/IBM/plex | Variable font 2.x, cut to static weights 400, 500 and 600; SIL OFL 1.1 (crates/ui-egui/assets/fonts/OFL-IBMPlex.txt) | Interface font, embedded in `crates/ui-egui/src/fonts.rs` | +| JetBrains Mono | https://github.com/JetBrains/JetBrainsMono | Regular; SIL OFL 1.1 (crates/ui-egui/assets/fonts/OFL-JetBrainsMono.txt) | Numbers, references and net names font, embedded in `crates/ui-egui/src/fonts.rs` | +| Open library recorded answers | https://gitlab.com/kicad/libraries/kicad-symbols, https://gitlab.com/kicad/libraries/kicad-footprints and https://gitlab.com/kicad/libraries/kicad-packages3D | Repository revisions 45efbd93, a337146e and 89757151; CC-BY-SA 4.0 + KiCad design-output exception | Unmodified R and C symbols, R_0603 footprint and STEP model, folder listings reduced to a few entries, revision answers reduced to id and date; used only as test fixtures in crates/library/tests/fixtures/open_library; recording script and licence beside them (LICENSE-kicad-libraries.md) | +| Showcase sensor node | `cargo xtask showcase` (`xtask/src/showcase/`) | Original design by the PCBCraft authors; CC BY-SA 4.0 | `examples/showcase.pcbcraft` and `examples/showcase-with-findings.pcbcraft`; every symbol, footprint and placement is defined in code, no third-party library data | KiCad's official PCB_POINT API/source documentation was consulted to distinguish non-manufactured reference-point metadata from copper/outline geometry; exact links @@ -18,3 +31,11 @@ the KiCad data license and source attribution embedded in the native collection. No KiCad implementation code has been copied or ported in this implementation. PCBCraft sample circuits are original; imported symbol/footprint artwork retains its KiCad data license and design-output exception. Dependencies retain their own licenses. + +The octagonal-hull walkaround and shove router in crates/engine/src/route and +crates/geom/src/hull.rs is an original implementation from published algorithm +descriptions. No third-party router source was copied or ported. + +## UI icons (assets/icons/ui) + +Generic icons are copied from Lucide (lucide-static 0.468.0), ISC license with MIT for parts derived from Feather; the license text is in assets/icons/ui/LICENSE-lucide.txt. Each file names its source icon in a leading comment. Domain icons (via, pads, zone, keepout, net, track, diff pair, footprint, courtyard, drill, stackup, layers, board outline, cutout, mounting hole, wire, bus, label, port, power, no-connect, junction, part, sheet, drill file) are drawn for PCBCraft and carry the project license. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..8468b7063 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,21 @@ +# PCBCraft — Claude Code + +Follow **AGENTS.md** in this repo; it is the canonical rule set for all agents. This file adds Claude-specific workflow only. + +## Start + +1. Confirm you are on fork `main` or a branch from it (`git fetch origin main`). +2. If working an issue: `gh issue view N -R tangency-labs/pcbcraft` and read Research/Enrichment comments. +3. Skim README.md and docs/architecture.md once per session; do not re-read on every edit. + +## Parallel work + +Prefer **many agents on many `conflict:parallel-safe` issues** over one agent on a broad ticket. Do not touch `crates/ui-egui/src/lib.rs` unless the issue is the active `conflict:ui-egui-lib` lane. Separate clone per agent. + +## Verify + +Trust **fork CI**, not local habit alone: push the branch to github.com/wdunn001/pcbcraft and wait for Actions. Run `cargo xtask ci` locally only when iterating quickly; the build report must link the green Actions run for the same commit. + +## Deliver + +Build report on the upstream issue ends with `PR pending owner review`. No worker-opened PRs. See CONTRIBUTING.md §4 worker checklist and fork issue #1. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..fc0e5be80 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,476 @@ +# Contributing to PCBCraft + +This file explains how work moves through the PCBCraft tracker, from a request to a merged change. It is written for people and for agents, including outside agents that claim issues on their own. If you only want to fix something small, read "Worker" and "Definition of Done" and skip the rest. + +**The codebase of record is the fork's `main`: github.com/wdunn001/pcbcraft, branch `main`.** Every upstream pull request and every contributor branch is merged into it, so it is the actual PCBCraft as it stands. Read code there, branch from it, merge the latest fork `main` into your branch before your final push, and resolve conflicts on your side. Upstream `main` on tangency-labs/pcbcraft lags behind it; upstream receives a pull request only after the maintainer has tested the integrated change. + +Issues live upstream on tangency-labs/pcbcraft. CI is GitHub Actions on the fork: pushing a branch there runs the whole gate, and the Actions run is the proof of a green build. In this file "fork/main" means that branch, and `Base: fork/main at ` is the first line of every `### Research`, `### Enrichment` and `### Review` comment, so everyone names the same code. + +**Definition of done for the program:** a fully featured, complete build on the fork's `main` that contains every upstream pull request and every contributor branch, with as few conflicts as possible. A change is done when it is merged into fork `main` and the full GitHub Actions build on fork `main` is green. Everything else in this file serves that. + +**Start here.** Get the latest code from fork `main`. Find work on the upstream tracker: `gh issue list -R tangency-labs/pcbcraft --search "ready in:body" --state open`, then claim one with a `CLAIM` comment (section 3). Deliver by pushing a branch to a fork, waiting for a green Actions run, and posting a build report. Issues come first: nothing is built that is not an enriched, tagged issue. No upstream pull request is opened until the maintainer has tested the change. + +## 1. The pipeline at a glance + +Every piece of work becomes an issue before anyone touches code. The issue then moves through fixed stages. Tags on the first line of the issue body say which stage it is in. + +``` + request raw ticket researched enriched + (owner, user, agent) -> [reporter] ------------> [researcher] -----------> [enricher] ---------> ready + stage:research research:done enrich:done `ready` + or stage:enrich stage:enrich full Tags line + research:n/a + + ready --> [worker claims] --> [worker builds] ---> branch pushed --------> [reviewer] ---------> [integrator] + CLAIM own clone off Actions run green ### Review merge commit into + status:claimed fork/main, merges build report comment approved or fork main, Actions + fork/main before "PR pending owner changes requested green on fork main + the final push review" = DONE + status:in-progress -> + status:needs-owner-test + + fork main --> [owner test] --> upstream pull request --> upstream main + owner runs the one PR per feature, status:pr-open, + integrated build targets upstream main then closed +``` + +Stages in words: + +1. **Raw ticket.** A reporter files a short issue: the request in the requester's words, the goal, links. Tags: `stage:research`, or `stage:enrich` plus `research:n/a` when there is no open standards or design question. +2. **Research.** A researcher answers the standards, format, machine or reference-rule questions, posts a `### Research` comment, sets `research:done` and moves the issue to `stage:enrich`. +3. **Enrichment.** An enricher verifies file and function names, lists every place to change, dependencies and order, the conflict lane, the test list, tooltips, text catalog, accessibility and logging needs, and splits the work into one-PR children. It posts `### Enrichment`, writes the full Tags line, sets `enrich:done` and replaces `stage:enrich` with `ready`. +4. **Ready.** A worker may claim it. Workers claim only `ready` issues. Workers who share a build machine with others also need `conflict:parallel-safe`. +5. **Work.** The worker claims, branches off fork `main`, builds, tests, merges the latest fork `main` back in, pushes the branch, waits for the Actions run, and posts a build report ending in "PR pending owner review". +6. **Review.** A reviewer checks the pushed branch against the acceptance criteria and posts `### Review`. +7. **Integration.** The integrator merges the branch into fork `main` with a merge commit. When the Actions build on fork `main` is green, the change is done. +8. **Owner test.** The maintainer runs fork `main`. Only then does a pull request to upstream open. + +## 2. Roles, step by step + +Replace `N` with the issue number and `` with your handle (a GitHub login or an agent name such as `claude-agent-docs`). All commands use the GitHub CLI, `gh`, authenticated as you. + +### Reporter + +Anyone who turns a request into an issue. The maintainer's coordinator does this for the owner's requests; outside contributors may file their own. + +1. Search first so the request is not already tracked: + ```sh + gh issue list -R tangency-labs/pcbcraft --search "" --state all + ``` +2. Create the issue with the body template below. The first line is the Tags line. Keep the How section short or write "To be completed by the enrichment stage"; the enricher fills it in. + ```sh + gh issue create -R tangency-labs/pcbcraft --title "" --body-file body.md + ``` +3. Choose the stage. If the work depends on an open standards, file format, machine or reference-rule question, tag `stage:research` and `research:needed`. Otherwise tag `stage:enrich` and `research:n/a`. +4. Add the new issue to the program status epic #352 (comment on it, or edit if you have access). + +Body template (the sections after Acceptance are copied verbatim into every issue): + +```markdown +**Tags:** `track:ai-handoff` `kind:feature` `area:layout` `status:open` `stage:enrich` `research:n/a` +## What +One paragraph: what changes for the user or the code. + +## Why +Who asked, what it unblocks, which issues depend on it. + +## How +To be completed by the enrichment stage. + +## Acceptance +- Observable results, each one testable. Name the `a_newcomer_*` test for UI work. + +### Rules for whoever picks this up +- Branch off fork main (wdunn001/pcbcraft) and merge the latest fork main into your branch before your final push. Push the branch; do not open a PR. The maintainer opens upstream PRs after testing. +- New code and PR text may not name other EDA tools. +- Typed engine commands with bounded validation; no unwrap/expect/panic anywhere, tests included. +- The GitHub Actions run on your pushed branch must be green; it is the proof. +- Every new control gets a tooltip; panels keep real margins and padding. +- End-to-end tests in crates/ui-egui are named like `a_newcomer_*` and must read like a story for someone who has never seen the app. + +### Claiming +Comment `CLAIM ` to take this. A coder's claim lasts 6 hours and any other stage's claim lasts 2 hours; renew with `CLAIM-RENEW `. An expired claim may be taken over. +``` + +### Researcher + +Takes `stage:research` issues. The deliverable is a comment, not code. + +1. Find work: + ```sh + gh issue list -R tangency-labs/pcbcraft --search "stage:research in:body" --state open + ``` +2. Check what is already known before reading anything new: the `### Enrichment` and `### Research` comments on this issue and on every issue it links, and the research notes (ask on the issue). Open the comment with what was already covered and where, so the same defect is not researched twice. +3. Read the published specifications, standards and reference material the question needs. Read the code paths the issue names, so the findings say what the code does today and what the specification says it must do. +4. Post one `### Research` comment. Format: + ```markdown + ### Research + + Base: fork/main at + Already covered: #286 enrichment items 1, 2 and 6. New here: items 3 to 5. + One line on what was read (specification name and revision, code paths). + + 1. **Finding title.** What the code does, what the standard requires, file and line anchors, the change this implies. + 2. **Next finding.** ... + + Owner decision: the question the maintainer must answer, if any, stated as a choice. + ``` + Research comment #351 is the model: numbered findings, each tied to a section of the specification and a place in the code, ending with one owner decision. +5. Update the Tags line: add `research:done`, replace `stage:research` with `stage:enrich`. If `enrich:done` is already present, set `ready` instead of `stage:enrich`. If the maintainer must decide something, add `owner-decision`, say what the choice is, and add one line to the "Open decisions for the owner" list in #352 (section 3, "Owner decisions"). +6. Captured sources (specification pages, datasheets, application notes) go into the project's knowledge base. Ask on the issue if you want a source captured; the maintainer's research agents maintain the manifest. + +### Enricher + +Takes `stage:enrich` issues. The enricher owns the Tags line and makes the issue buildable without further questions. + +1. Find work: + ```sh + gh issue list -R tangency-labs/pcbcraft --search "stage:enrich in:body" --state open + ``` +2. Read the code on fork `main` and record the commit: the first line of the enrichment is `Base: fork/main at `. If the work must build on a branch not yet merged into fork `main`, say so on the next line (`Stacks on: feat- at `) and prefer to have that branch integrated first. Anchors are file names plus function, type or constant names (`crates/doc/src/lib.rs: Pad::outline_points, Pad::bounding_radius`), never bare line numbers; line numbers go stale within a day on this repository, names can be grepped. Verify every anchor exists at the recorded commit before posting. +3. Post one `### Enrichment` comment. Paste the Definition of Ready checklist (section 4) at the top and tick it, with "n/a" and one word of reason where an item does not apply, then cover, in this order: + - Corrections to the issue body (for example "there is no pad shape enum; shape is a free string in two places"). + - Every place that must change, grouped by crate, with anchors. + - Free wins: code paths that start working with no change once the core change lands. + - Behaviour details the worker must honour (validation bounds, closed rings, convexity assumptions, error codes). + - Existing bugs in the same code that this issue should fix while it is there. + - Tests to add, named, per crate, including the `a_newcomer_*` story test for any UI work. + - Tooltips, text catalog entries, accessibility and logging needs. + - Ordering and dependencies against other issues, and the conflict lane. + - Out of scope: what this issue does not do, with the follow-up issue number. + - Split into one-PR children when the work is `size:l`; file the children and list them. + The enrichment on #281 is the model. +4. Rewrite the whole Tags line in the same pass: track, kind, area, milestone, crate, conflict, size, machine, status, then `ready` (when research is done or n/a) or `stage:research` (when research is still needed), then `research:*` and `enrich:done`. How to edit the line safely is in section 3. +5. If an owner decision is needed before work can start, add `owner-decision` and `status:blocked`, say what the choice is, and add it to the decision list in #352. +6. Scope added later goes through the enricher again. Anyone who adds a requirement to an issue after the `### Enrichment` comment posts it as `### Enrichment (update)` and refreshes the test list and the Tags line in the same comment. A loose "scope note" comment with no update does not count; a worker who finds one asks for the update before claiming. + +### Worker + +Takes `ready` issues. A worker is a human or an agent that writes the code. + +**Find work** + +```sh +# everything a worker may claim +gh issue list -R tangency-labs/pcbcraft --state open --search "ready in:body status:open in:body" +# only what can run alongside other workers (required when you share a build machine) +gh issue list -R tangency-labs/pcbcraft --state open --search "ready in:body status:open in:body conflict:parallel-safe in:body" +``` + +Read the issue body, every `### Research` and `### Enrichment` comment, and the linked issues. Check the program status epic #352 for who is working nearby. + +**Claim** + +```sh +gh issue comment N -R tangency-labs/pcbcraft --body "CLAIM " +``` + +Optionally add one or two lines of plan under the claim, as on #281. Then set `status:claimed` on the Tags line (section 3). Do not claim more than one issue at a time unless they are stacked children of one epic. Your lease is 6 hours; renew it with `CLAIM-RENEW `. An expired claim may be taken over. + +**Branch** + +One clone or worktree per agent. Never work in a checkout another agent is using. Clone the codebase of record and branch off its `main`: + +```sh +git clone https://github.com/wdunn001/pcbcraft.git pcbcraft- +cd pcbcraft- +git remote add upstream https://github.com/tangency-labs/pcbcraft.git +git checkout -b feat- origin/main +``` + +Branch from the base the enrichment recorded (`Base: fork/main at `, or the `Stacks on:` branch when there is one). Branch names follow section 7. If you do not have push access to the maintainer's fork, add it as a remote named `fork`, work on your own fork and push there; the report names the fork and branch. + +Before your final push, bring the latest fork `main` into your branch and resolve conflicts on your side, so the integrator receives a branch that merges cleanly: + +```sh +git fetch origin main +git merge origin/main +# resolve, build, test, commit the merge +``` + +A branch that does not merge cleanly into fork `main` at review time goes back to the worker. + +**Build and test** + +CI is GitHub Actions on the fork, and it runs on every pushed branch. The Actions run is the proof of a green build; link it in your report. Running the gate yourself before pushing is optional and saves round trips: + +```sh +cargo xtask ci +``` + +It runs formatting, dependency layer checks, clippy with warnings denied, the workspace tests (including the `a_newcomer_*` end-to-end tests) and the WebAssembly check. Once the CI pipeline branch (#340) is merged, the Actions gate also runs policy, docs, MSRV and license checks, the full e2e suite and the screenshot sheet; `docs/ci.md` lists every job and its local command. If you build on a shared machine, cap parallelism (`CARGO_BUILD_JOBS=4`) and keep your own target directory; do not run full builds on a laptop when a build machine or Actions can do it. + +For UI changes, look at the rendered result (section 6). + +**Push** + +```sh +git push -u origin feat- +``` + +Push only your feature branch. Do not push to `main` on any repository and do not open a pull request. The integrator merges into the fork's `main`; the maintainer opens upstream pull requests after testing. Set `status:in-progress` on the first push. + +**Report** + +Post a build report on the issue when the branch is complete. Format (the report on #281 is the model, with the Done checklist added): + +```markdown +Implemented on branch feat- (fork /pcbcraft), commit , based on at , 7 commits above the base. + +Built: +- What landed, per crate, in plain sentences. + +Bugs fixed in passing: +- ... + +Acceptance: +- criterion 1: test `clearance_to_a_chamfered_corner_measures_the_cut_edge` +- criterion 2: not done, reason, follow-up #NNN + +Tests: first lines of the `cargo xtask ci` output, not the word green. CI run: . + +Files touched: list, and "crates/ui-egui/src/lib.rs untouched" or the lane ticket number. + +Screenshots: (UI changes only). + +Limitations: what the change does not do, stated plainly, with follow-up issue numbers. + +Definition of Done: +- [x] ... (the list from section 4, ticked) + +PR pending owner review. +``` + +Then set `status:needs-owner-test` on the Tags line. Nothing else is required of the worker; the reviewer and integrator pick it up from the comment. + +### Reviewer + +Checks each "PR pending owner review" branch against its issue before integration. + +1. Find work: + ```sh + gh issue list -R tangency-labs/pcbcraft --state open --search "status:needs-owner-test in:body" + ``` +2. Fetch the branch into your own read-only clone and read the diff against its recorded base. Start the `### Review` with `Base: fork/main at `. Confirm the branch merges cleanly into current fork `main`; a branch that does not goes back to the worker. Check that the Actions run in the report is green and for the branch head; if it is missing or red, fail the branch. +3. Walk the Acceptance list and the test list from the enrichment, running each named test. Check the rules in section 5 (no unwrap or panic, typed commands, validation bounds, no other tools named in the diff or in the comments, tooltips, margins, attribution). Confirm `crates/ui-egui/src/lib.rs` is untouched when the issue is `conflict:parallel-safe`. For UI work, open the screenshots. The reviewer reads and runs; it never edits the branch. +4. Post one `### Review` comment: + ```markdown + ### Review + + Base: fork/main at + + Branch feat- at . + + Acceptance: + - [x] criterion, evidence (test name, file, screenshot) + - [ ] criterion, what is missing + + Rules: pass, or the rule and the place it is broken. + + Verdict: approved for integration + ``` + or `Verdict: changes requested` followed by the list. The worker fixes and reposts a build report; the reviewer reviews again. +5. The reviewer does not merge and does not change the status tag; the verdict is the signal the integrator waits for. + +### Integrator + +One agent owns the integration branch, the fork's `main`. It merges every reviewed branch so the maintainer can test everything together. + +1. Watch for `### Review` comments with "approved for integration" and for new or force-pushed branches on the fork. +2. Merge each branch into the fork's `main` with a merge commit, never a squash or a rebase of `main`: + ```sh + git checkout main && git pull --ff-only origin main + git merge --no-ff feat- + ``` +3. Resolve conflicts in the merge commit, keeping both sides' intent; if the resolution is not obvious, ask on both issues before pushing. +4. Push the merge, then watch the GitHub Actions run on fork `main`. The change is done when that full build is green; if it is red, fix forward on a branch or report on the issue, and never rewrite `main`. Where a local run is cheap, run `cargo xtask ci` on the merged tree before the push: + ```sh + git push origin main + ``` +5. Never rewrite the fork's `main`, never push to upstream, never open upstream pull requests. +6. Keep a ledger in `integration-ledger.md`: date, branch, branch head, issue, fork main before and after, Actions run, conflict files and how each was resolved. Comment on each issue with the merge commit, and post any resolution that changes logic so the worker and reviewer see it. + +### Owner test + +The maintainer tests with one packaged command that builds the branch or fork `main` and produces the screenshot sheet. It wraps `cargo xtask screenshots` from the CI pipeline (#340); the command is tracked as its own issue. Until it exists, run `cargo xtask screenshots --out target/screenshots` yourself. Only after the maintainer has tested: + +- The maintainer opens one pull request per feature from the feature branch to upstream `main`, with a body that starts with the Tags line, and sets `status:pr-open` on the issue. +- Upstream pull requests merge only with green CI. +- When upstream merges, the issue closes, and the status epic #352 is updated. + +If the maintainer finds a problem, they comment on the issue; the status goes back to `status:in-progress` and the worker continues on the same branch. + +## 3. Tags and claiming + +The maintainer has read permission upstream, so GitHub labels cannot be used. Tags live on the first line of every issue and pull request body, as one `**Tags:**` line of backticked tags, in this order: track, kind, area, milestone, crate, conflict, size, machine, status, stage (or `ready`), research, enrich, owner-decision. + +``` +**Tags:** `track:ai-handoff` `kind:feature` `area:layout` `milestone:m2` `crate:engine` `crate:ui-egui` `conflict:ui-egui-lib` `size:m` `status:open` `ready` `research:n/a` `enrich:done` +``` + +Vocabulary, one line each. "One" means exactly one value. + +| Namespace | Values | +| --- | --- | +| track (one or more) | `track:ai-handoff` an agent can take it without asking; `track:ui-design` it changes what the user sees | +| kind (one) | `kind:feature` `kind:epic` `kind:bug` `kind:research` `kind:chore` `kind:refactor` `kind:docs` | +| area (one or two) | `area:schematic` `area:layout` `area:library` `area:rules` `area:io` `area:artifacts` `area:3d` `area:sim` `area:ui-shell` `area:mcp` `area:ci` `area:docs` `area:packaging` `area:kb` | +| milestone (zero to two) | `milestone:m1` to `milestone:m4` from ROADMAP.md, `milestone:m5` Inner copper layers (epic #316), `milestone:m6` Manufacturing artifacts (epic #322) | +| crate (one or more) | `crate:engine` `crate:doc` `crate:rules` `crate:io` `crate:geom` `crate:library` `crate:mcp` `crate:ui-egui` `crate:xtask` `crate:sim` `crate:apps` | +| conflict (one) | `conflict:ui-egui-lib` edits crates/ui-egui/src/lib.rs; `conflict:parallel-safe` stays out of that file | +| size (one) | `size:s` one PR, one crate, under a day; `size:m` one PR, several crates; `size:l` several PRs or an epic | +| machine (zero or more) | `machine:neoden-yy1` `machine:eufymake-e1` `machine:snapmaker-cnc` `machine:commarker-b6` | +| status (one) | `status:open` `status:claimed` `status:in-progress` `status:pr-open` `status:needs-owner-test` `status:blocked` | +| stage (one) | `stage:research` `stage:enrich` `ready` (bare; an issue never carries both `ready` and a `stage:` tag) | +| research | `research:needed` `research:done` `research:n/a` | +| enrich | `enrich:done` (an `### Enrichment` comment exists) | +| flag | `owner-decision` the maintainer must choose something; say what in the body or a comment | + +Deriving the stage: no enrichment and research needed gives `stage:research`; no enrichment and research done or n/a gives `stage:enrich`; enrichment done and research still needed gives `stage:research`; enrichment done and research done or n/a gives `ready`. + +**Who sets which tag** + +- Reporter: the first line, with at least `track:`, `kind:`, `area:`, `status:open` and the stage. +- Researcher: `research:done`, and the move from `stage:research` to `stage:enrich` (or to `ready` if enrichment already happened). +- Enricher: the whole line, including `enrich:done` and `ready`. +- Worker: `status:claimed` on `CLAIM`, `status:in-progress` on first push, `status:needs-owner-test` with the build report. +- Maintainer: `status:pr-open` when the upstream pull request opens. +- Anyone: correct a wrong `area:`, `crate:` or `conflict:` tag; set `owner-decision` on hitting a question; clear it when recording the answer. + +**The conflict lane.** `crates/ui-egui/src/lib.rs` holds the tabs, docks, menus and inspector sections, and nearly every UI change lands there. It is edited serially: one `conflict:ui-egui-lib` ticket at a time, by the maintainer's UI shell lane, and nobody else touches that file in parallel. If your work needs a line in lib.rs, say so in the issue and wait for the lane rather than editing it; `conflict:parallel-safe` work proceeds alongside anything else. + +**Editing the Tags line.** Several agents edit issues at once. Fetch, change the first line only, write back in the same step, and never touch other body text or comments: + +```sh +gh issue view N -R tangency-labs/pcbcraft --json body -q .body > body.md +# edit line 1 only +gh issue edit N -R tangency-labs/pcbcraft --body-file body.md +``` + +**Claiming and leases.** Claim a `ready` issue with `status:open` by posting one comment: `CLAIM @ until clone branch `. A lease lasts 6 hours for coders and 2 hours for research, enrichment and review. Renew it with `CLAIM-RENEW ` and a one-line progress note; every push also renews it, and you post a line at least every 2 hours while working. An expired claim may be taken over: comment `CLAIM (takeover, previous claim expired)`, set `status:claimed`, and the earlier claimer stops. Before claiming, check the issue has no live lease. Abandoning a claim: comment "Releasing claim" and set `status:open`. Claims that do not use the format fall back to 5 days with no pushed branch. + +**Comment headings in use.** `CLAIM `, `### Research`, `### Standards` (research on rule and output issues), `### Enrichment`, `### Enrichment (update)`, `### Review`, and a build report whose last line is `PR pending owner review`. Use these exact headings so searches and the status epic find them. + +**Owner decisions.** A question only the maintainer can answer (strategy, accounts, signing, a convention such as the internal Y axis direction) does not wait in a comment thread. Whoever hits it sets `owner-decision` on the issue and adds one line to the "Open decisions for the owner" list in #352: `- [ ] #351: Y-up internally with a display flip? (asked by research, 2026-10-28)`. The maintainer answers on the issue or in #352; whoever records the answer clears the tag and ticks the line. + +## 4. Definition of Ready and Definition of Done + +Both lists are pasted into the issue and ticked, not only read: the enricher pastes Ready at the top of `### Enrichment`, the worker pastes Done at the end of the build report. "n/a" with one word of reason is an acceptable tick; a blank box blocks the stage. Keep the lists to what the next person cannot discover alone. + +**Definition of Ready** (the enricher ticks this before setting `ready`): + +- [ ] Goal in one sentence, in the requester's words, with the owner direction quoted if one exists. +- [ ] Acceptance criteria as numbered observable statements: what the user sees or what the test asserts. +- [ ] Research is done or marked n/a; `### Research` findings are reflected in How. +- [ ] Test list: exact test names and the file each goes in, including the `a_newcomer_*` story test for UI work. +- [ ] Anchors: file plus function, type or constant names, verified by reading the code at `Base: fork/main at `. No bare line numbers. +- [ ] `Base: fork/main at ` recorded and conflict lane set (`conflict:ui-egui-lib` or `conflict:parallel-safe`). +- [ ] Dependencies: issues that must land first, and what breaks if they do not; blocked issues carry `status:blocked`. +- [ ] Out of scope: what this issue does not do, with the follow-up issue number. +- [ ] Tooltips, text catalog, accessibility and logging needs listed for UI work. +- [ ] Owner decisions: none, or listed with `owner-decision` set and a line in #352. +- [ ] Text rule: title and body name no other EDA tool. +- [ ] Size is `s` or `m`; `size:l` work is split into children first. The full Tags line is set. + +**Definition of Done** (the worker ticks this in the build report; the reviewer and integrator check it): + +- [ ] Branch, commit, merge-base and the number of commits above the base are in the report, and fork main was merged into the branch before the final push. +- [ ] Each acceptance criterion is listed with the test name or screenshot that proves it, or "not done" with the reason and a follow-up number. +- [ ] Every test from the enrichment exists and passes; new behaviour has unit tests; file writers have golden fixtures; UI work has a readable `a_newcomer_*` test. +- [ ] The link to the green GitHub Actions run on the fork for the same commit is in the report, with the first lines of the `cargo xtask ci` output if you ran it locally. +- [ ] No `unwrap`, `expect`, `panic`, `todo`, `unimplemented` or `unreachable` in production code; invalid input leaves state untouched. +- [ ] Every edit goes through a typed engine command with bounded validation. +- [ ] Every new control has a tooltip; panels keep real margins and padding; labels are short and plain. +- [ ] For `track:ui-design`: screenshots attached or linked. +- [ ] Files touched are listed; `crates/ui-egui/src/lib.rs` is untouched for `conflict:parallel-safe` work, or the lane ticket is named. +- [ ] No other EDA tool is named in code, comments, UI strings, docs, commit messages or the report. +- [ ] Adapted code is recorded in ATTRIBUTION.md with source, revision and license. +- [ ] Limitations and follow-ups are stated with issue numbers, and shown in the UI where the user would meet them. +- [ ] Branch pushed to the fork; report ends in "PR pending owner review"; `status:needs-owner-test` set. + +After the worker: `### Review` verdict "approved for integration"; merged into the fork's `main` with a merge commit and the Actions build on fork `main` green, which is the program's definition of done; the maintainer has run it with the owner-test command (section 6); an upstream pull request is open; #352 is updated. + +## 5. Code rules + +These come from AGENTS.md and apply to every change. + +- **One window.** Document and workspace tabs plus docked panes. Never spawn separate schematic, board, library, checks or 3D windows. Project and selection are shared. +- **Typed engine commands.** Everything that edits the project is a command in `crates/engine` with a JSON schema. UI, CLI and MCP call the same engine. Programmatic commands never open dialogs. +- **Validation.** Finite, bounded coordinates and dimensions; bounded counts; stable IDs; reference integrity. An invalid command or batch leaves the document, revision and history untouched. +- **No panics.** No `unsafe`; no production `unwrap`, `expect`, `panic`, `todo`, `unimplemented` or `unreachable`. Tests may use `?` with `Result<(), String>`; the e2e tests do. The CI pipeline branch lints these at deny and forbids source `allow` of them. +- **Crate layering.** geom (L0) under doc and library (L1) under rules and io (L2) under engine (L3) under mcp and ui-egui (L4) under the apps. Lower crates never depend on egui, eframe, wgpu or MCP. `cargo xtask ci` checks the layers. +- **Adapted GPL code.** Source from other GPL-compatible projects may be inspected and adapted. Record the exact source, revision and license in ATTRIBUTION.md. Translating to Rust does not remove attribution or copyleft. Check each file's license. Do not copy trademarks or proprietary assets from shared Craft dependencies; pin craft-libs revisions. +- **Honest limits.** Do not present initial checks as complete ERC/DRC, or a basic route as a shove router. Track parity by workflows and fixtures, not by percentages. +- **Names.** Never name other EDA tools in code, docs, UI strings, issues or pull requests. Describe formats and behaviours instead ("the board interchange format", "the plot layer format"). +- **UI.** Every control gets a tooltip. Panels keep real margins and padding. Labels are short plain words. UI changes are inspected rendered, not only in tests. +- **Publishing.** Do not publish releases or push to third-party repositories without authorization. + +## 6. Testing + +- **Unit tests** live beside the code in each crate (`#[cfg(test)]` modules) and cover validation bounds, rejections and the happy path. Name them as sentences: `padstack_rejects_chamfer_ratio_out_of_range`. +- **Golden fixtures** cover every file writer and reader. Put fixture files under `crates//tests/fixtures/` and compare whole outputs, not substrings. For output that an independent parser exists for, read the output back with that parser as a dev-dependency. Fixtures from external libraries keep their license file beside them. +- **End-to-end tests** are named `a_newcomer_`. They drive the real `App` headlessly with the `frame`, `tap`, `paints_text` and `scrolled_to` helpers, and every assertion message is a plain sentence that someone who has never seen the app could follow ("the matching part stays in the list"). One test per user-visible feature. They live in `crates/ui-egui/src/e2e/.rs` (helpers in `src/e2e/support.rs`), one file per area (library, nets, rules, builds, board, checks, artifacts, layout, layers, shell). Put new tests in the matching area file, or add a new area file plus one `mod ;` line in `src/e2e/mod.rs`, and never add one to lib.rs. CI runs the full e2e suite as a required check, uploads a screenshot sheet, and fails if any control lacks a tooltip or an e2e story. +- **Engine round trips** for any new document field: save and load a project carrying it and compare. +- **Screenshots for UI changes.** Render the change and attach the image to the build report. On `main` today: + ```sh + xvfb-run -a -s '-screen 0 1600x1100x24' \ + env -u WAYLAND_DISPLAY WGPU_BACKEND=vulkan \ + cargo run -p pcbcraft -- --sample --capture pcbcraft.png + ``` + `cargo xtask screenshots --out target/screenshots` (from the CI pipeline, #340) captures the standard views, and CI uploads a side-by-side sheet of base and head. Add a view there when a new tab or dialog deserves one. If your issue carries `track:ui-design`, you produce the screenshots yourself and put the sheet path in your report; never ask the owner for evidence you can produce. +- **Where to run.** CI runs on GitHub Actions on the owner's fork. Push early and use the run as proof. A local `cargo xtask ci` is optional. + +## 7. Branches, commits, merge flow + +**Branch names.** `-`, or `--` when the area is not obvious from the slug. Kind prefixes: `feat`, `fix`, `docs`, `chore`, `refactor`, `research`. Examples: `feat-chamfered-pads`, `feat-artifacts-drill-map`, `docs-contributing`, `ci-pipeline` (older name, kept). One branch per issue; children of an epic may stack, base named in the report. + +**Commits.** Imperative subject under 72 characters that says what changed ("Add chamfered and custom pad shapes"), a blank line, then a body in plain sentences when the subject is not enough. Reference the issue (`#281`) in the body. No AI attribution lines or trailers, no em-dashes, no other tools named. Commit as yourself. + +**Merge flow.** + +1. Worker pushes `feat-` to the fork. CI runs on the push. +2. Reviewer approves in `### Review`. +3. Integrator merges `feat-` into the fork's `main` with `--no-ff`, resolving conflicts in the merge commit. The fork's `main` is never rewritten. The change is done when the Actions build on fork `main` is green. +4. Maintainer tests the fork's `main` with the owner-test command. +5. Maintainer opens one pull request per feature from `feat-` to upstream `main`. The pull request body starts with the Tags line. It merges with green CI. + +Pull requests are never opened by workers, reviewers or the integrator. Pushing to any `main` is reserved to the integrator (fork) and upstream merges (upstream). + +## 8. Where knowledge lives + +- **Program status epic #352** on tangency-labs/pcbcraft: every roadmap line with its issue, what is in flight, open owner decisions, and the enrichment and research comment links. Update it when an issue is opened, claimed, finished or dropped. +- **The issue itself**: body, `### Research`, `### Enrichment`, build reports, `### Review`. +- **Repository docs**: AGENTS.md (rules for all agents), CLAUDE.md (Claude Code workflow), `.cursor/rules/*.mdc` (Cursor Agent rules; see [Cursor rules docs](https://cursor.com/docs/rules)), `docs/agents/` (role briefs for parallel workers), README.md (what works, how to run), ROADMAP.md (milestones), `docs/architecture.md` (layers and decisions), `docs/validation.md` (evidence for the initial subset), `docs/mcp.md` (MCP client setup), `docs/ci.md` (every CI job and its local command), ATTRIBUTION.md (provenance). +- **Research notes**, available on request from the maintainer: the feature parity matrix, per-issue research notes (routing, length and impedance, pours, fabrication checks, 3D view, simulation), the manufacturing artifact format survey, the shop equipment and machine profile notes, the tagging standard and the coordinator's queue. Ask on the issue you are working and the relevant note is posted or summarised there. A searchable knowledge base of captured standards and sources backs the research stage; findings from it arrive on issues as `### Research` comments. + +## 9. Instructions adopted from the pipeline review + +These come from a review of the pipeline against the tracker on 2026-10-28 and are in force. + +- **Queue and claims.** Check that an issue has no live lease before claiming (section 3). Open owner questions go in #352: set `owner-decision`, state the choice and your recommendation in one paragraph, and add one line to "Open decisions for the owner". Do not wait in the thread. +- **One base.** The only base is fork main. Branch from it with `git fetch origin && git checkout -b - origin/main` (in a clone of the fork), push only your feature branch, never main. The integrator merges reviewed branches into fork main with merge commits and posts any logic-changing conflict resolution on your issue. If your branch falls behind, merge fork main into it and fix conflicts on your side; if you have no choice but to rebase, push with `git push origin +`. Never rewrite fork main and never touch upstream. +- **Anchors.** Anchors in an enrichment are file paths plus function or type names, never line numbers, verified at `Base: fork/main at `. To add scope after enrichment, post `### Enrichment (update)` and edit the Ready block; a bare scope comment sends the issue back to `stage:enrich`. +- **Research dedupe.** Before researching, read every `### Research` and `### Enrichment` comment on the issue and on the issues it links, and search the research notes and source manifest for its number. Open your `### Research` comment with what is already covered and where, then what is new. +- **Tests out of lib.rs.** Do not edit `crates/ui-egui/src/lib.rs` unless your issue is tagged `conflict:ui-egui-lib` and is the active ticket on that lane. Put your `a_newcomer_*` test in `crates/ui-egui/src/e2e/.rs` (helpers in `src/e2e/support.rs`). If your feature needs a lib.rs change (a tab, a menu item, a dock page), ship the engine, io and test work first as a parallel-safe branch and file a one-line follow-up for the lib.rs part. +- **Screenshots yourself.** For `track:ui-design`, you produce the visual evidence (section 6). A description of what renders is not evidence. +- **Stop after two failures.** If the same build or test fails twice with the same output, do not try a third time: post the output, set `status:blocked`, and stop. +- **Done block.** Your final comment ends with the Definition of Done list (section 4), every line filled. Limitations you list become follow-up issues, not prose. + +## 10. Proposed improvements + +These are proposals, not current rules. Follow sections 1 to 9 until an item moves up. + +- **Queue view and gate script.** A script over the `gh` JSON that parses the Tags line of every issue and prints counts per stage and status, claims with no `ready` tag, expired leases, issues whose latest comment postdates the enrichment, and open owner decisions; with a flag that rewrites a Queue section in #352. Workers would claim only from its `claimable` output. Instruction when adopted: run `scripts/queue.sh claimable` before you claim and claim only an issue it lists. +- **A `status:needs-review` status.** Between `in-progress` and `needs-owner-test`, set by the worker with the build report; the reviewer moves it to `needs-owner-test` on pass or back to `in-progress` on fail, and the worker never sets `needs-owner-test` on its own work. A reviewer verdict would end in `VERDICT: pass` or `VERDICT: fail`. +- **Lease sweeper.** A command that lists expired claims and, on request, posts "Claim expired, released" and sets `status:open`. +- **Anchor check.** `scripts/queue.sh anchors ` greps every anchor in an enrichment at fork main and flags missing ones; run by the enricher before posting and by the worker before claiming. +- **Text-rule linter before posting.** `scripts/post-check.sh ` fails on forbidden product names, em-dashes, AI attribution and a malformed Tags line; run it before every `gh issue comment`, `edit` or `create`. +- **Packaged owner test with branch option.** `cargo xtask owner-test --branch `, wrapping the screenshot capture, a side-by-side sheet against fork main and the one-line command to run the branch. +- **Real labels.** Once the maintainer has triage permission upstream, convert the Tags vocabulary into GitHub labels and keep the body line as a mirror for search. +- **Required check.** Mark the CI result job as a required check on fork main and upstream main once the CI pipeline is merged. +- **Integration ledger in the repository.** Publish the integrator's ledger as a file in the fork. +- **Versioned pipeline rules and agent definitions.** Partially adopted: AGENTS.md, CLAUDE.md, `.cursor/rules/`, and `docs/agents/` in the fork. Still to do: pre-post check scripts (`scripts/post-check.sh`, `scripts/queue.sh`). +- **Budgets per agent and per stage.** Turn and cost limits on every headless worker, sized by the `size:` tag, and a cap per stage so research does not starve enrichment. +- **Lessons loop.** Append each reviewer fail and each worker limitation to a lessons file per issue. When a review fails a branch for a reason that has failed another branch, open a `kind:chore` issue to encode the check in `cargo xtask`. + +Changes to this file go through the same pipeline: file an issue tagged `kind:docs` `area:docs`, claim it, and push a `docs-` branch. diff --git a/Cargo.lock b/Cargo.lock index 72e3b1566..ecd68f0da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,16 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "Inflector" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" +dependencies = [ + "lazy_static", + "regex", +] + [[package]] name = "accesskit" version = "0.24.1" @@ -13,12 +23,127 @@ dependencies = [ "uuid", ] +[[package]] +name = "accesskit_atspi_common" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954" +dependencies = [ + "accesskit", + "accesskit_consumer 0.36.0", + "atspi-common", + "phf", + "serde", + "zvariant 5.15.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_macos" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +dependencies = [ + "accesskit", + "accesskit_consumer 0.38.0", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus 5.19.0", +] + +[[package]] +name = "accesskit_windows" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21" +dependencies = [ + "accesskit", + "accesskit_consumer 0.35.0", + "hashbrown 0.16.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313" +dependencies = [ + "accesskit", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "raw-window-handle", + "winit", +] + [[package]] name = "adler2" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + [[package]] name = "ahash" version = "0.8.12" @@ -33,6 +158,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -73,11 +207,20 @@ dependencies = [ "libc", ] +[[package]] +name = "approx" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f2a05fd1bd10b2527e20a2cd32d8873d115b8b39fe219ee25f42a8aca6ba278" +dependencies = [ + "num-traits", +] + [[package]] name = "arboard" -version = "3.6.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" dependencies = [ "clipboard-win", "image", @@ -89,10 +232,22 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "x11rb", ] +[[package]] +name = "array-macro" +version = "2.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "220a2c618ab466efe41d0eace94dfeff1c35e3aa47891bdb95e1c0fefffd3c99" + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + [[package]] name = "arrayvec" version = "0.7.8" @@ -114,12 +269,191 @@ dependencies = [ "libloading", ] +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-fs" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5" +dependencies = [ + "async-lock", + "blocking", + "futures-lite", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.6", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.6", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.6", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus 5.19.0", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names 4.3.5", + "zvariant 5.15.1", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus 5.19.0", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -162,6 +496,24 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -180,6 +532,28 @@ dependencies = [ "objc2 0.6.5", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "branches" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f11502672c5570f77f6bdf573332483f8475bab6a7fda00f1fae8ddb5a6245c0" +dependencies = [ + "rustc_version", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -203,9 +577,15 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.8", + "syn 3.0.9", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -240,7 +620,7 @@ checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "tracing", ] @@ -263,16 +643,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ "calloop 0.14.5", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-client", ] +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + [[package]] name = "cc" -version = "1.8.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" dependencies = [ "find-msvc-tools", "jobserver", @@ -301,11 +690,45 @@ dependencies = [ "libc", ] +[[package]] +name = "cgmath" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a98d30140e3296250832bbaaff83b27dcd6fa3cc70fb6f1f3e5c9c0023b5317" +dependencies = [ + "approx", + "num-traits", + "serde", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -332,9 +755,9 @@ dependencies = [ [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -350,8 +773,14 @@ dependencies = [ ] [[package]] -name = "core-foundation" -version = "0.9.4" +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "core-foundation" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" dependencies = [ @@ -359,6 +788,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -372,7 +811,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -385,7 +824,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ "libc", ] @@ -399,13 +847,32 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -418,12 +885,92 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "dbus-secret-service" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" +dependencies = [ + "aes", + "block-padding", + "cbc", + "dbus", + "fastrand", + "hkdf", + "num", + "once_cell", + "sha2", + "zeroize", +] + +[[package]] +name = "derive-new" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3418329ca0ad70234b9735dc4ceed10af4df60eff9c8e7b06cb5e520d92c3535" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -440,6 +987,17 @@ dependencies = [ "objc2 0.6.5", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "dlib" version = "0.5.3" @@ -529,7 +1087,7 @@ dependencies = [ "bitflags 2.13.2", "emath", "epaint", - "itertools", + "itertools 0.15.0", "log", "nohash-hasher", "profiling", @@ -566,6 +1124,7 @@ version = "0.36.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98466000559d66ba4db786a30448b01483946add4188e7f10f522a27b4fb89cc" dependencies = [ + "accesskit_winit", "arboard", "bytemuck", "egui", @@ -581,6 +1140,21 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_extras" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05cbdc785020861553f230f23d330ba1fb72613b9d8e0e457f3bdc8ba6db6dcf" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools 0.15.0", + "log", + "profiling", + "resvg", +] + [[package]] name = "egui_glow" version = "0.36.2" @@ -611,6 +1185,53 @@ dependencies = [ "serde", ] +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enum-map" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6866f3bfdf8207509a033af1a75a7b08abda06bbaaeae6669323fd5a097df2e9" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "enumn" version = "0.1.14" @@ -656,9 +1277,9 @@ checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13" [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" @@ -685,6 +1306,26 @@ dependencies = [ "num-traits", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -714,9 +1355,9 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" [[package]] name = "find-msvc-tools" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "flate2" @@ -729,6 +1370,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + [[package]] name = "foldhash" version = "0.2.0" @@ -737,9 +1384,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "font-types" -version = "0.12.6" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c92d9081c7ab3bd83ef1eecdfad090f3d966e3ce74106779664114cfe1a6274" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ "bytemuck", "serde", @@ -763,7 +1410,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" dependencies = [ "proc-macro2", "quote", - "syn 3.0.8", + "syn 3.0.9", ] [[package]] @@ -772,12 +1419,57 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -791,21 +1483,48 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-io", + "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -868,6 +1587,42 @@ dependencies = [ "web-sys", ] +[[package]] +name = "gltf" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7" +dependencies = [ + "byteorder", + "gltf-json", + "lazy_static", + "serde_json", +] + +[[package]] +name = "gltf-derive" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14070e711538afba5d6c807edb74bcb84e5dbb9211a3bf5dea0dfab5b24f4c51" +dependencies = [ + "inflections", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gltf-json" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6176f9d60a7eab0a877e8e96548605dedbde9190a7ae1e80bbcc1c9af03ab14" +dependencies = [ + "gltf-derive", + "serde", + "serde_derive", + "serde_json", +] + [[package]] name = "glutin" version = "0.32.3" @@ -1008,57 +1763,291 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" [[package]] -name = "image" -version = "0.25.10" +name = "hex" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" dependencies = [ - "bytemuck", - "byteorder-lite", - "moxcms", - "num-traits", - "png", - "tiff", + "hmac", ] [[package]] -name = "indexmap" -version = "2.14.2" +name = "hmac" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "equivalent", - "hashbrown 0.17.1", + "digest", ] [[package]] -name = "itertools" -version = "0.15.0" +name = "i_float" +version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +checksum = "9ecaff1ce29bcacd72cdf581ba6fce636ef4c4e0b2da7e7846dd0137d98141e2" dependencies = [ - "either", + "libm", ] [[package]] -name = "itoa" -version = "1.0.18" +name = "i_key_sort" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "14269ee362009550495e20650ff3c2bca14a8147fe251e216760381ffed90b6f" [[package]] -name = "jni" -version = "0.22.4" +name = "i_overlay" +version = "9.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +checksum = "913fd692c02408adc76cead636f8e7e07c705f8b995a8b54b454b995e8e197d5" dependencies = [ - "cfg-if", - "combine", - "jni-macros", - "jni-sys 0.4.1", - "log", - "simd_cesu8", - "thiserror 2.0.21", + "i_float", + "i_key_sort", + "i_shape", + "i_tree", +] + +[[package]] +name = "i_shape" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa1878f91ef7921feaf1b2346253ebc5e661878b22d5715195c1d5dcf0f20ae5" +dependencies = [ + "i_float", +] + +[[package]] +name = "i_tree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048af31de955890c62a8506fec511335a5089e91e1c516537add16f96c507d84" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", +] + +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inflections" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a" + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", "walkdir", "windows-link", ] @@ -1125,6 +2114,34 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "katexit" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccfb0b7ce7938f84a5ecbdca5d0a991e46bc9d6d078934ad5e92c5270fe547db" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "byteorder", + "dbus-secret-service", + "log", + "secret-service", + "security-framework 2.11.1", + "security-framework 3.7.0", + "windows-sys 0.60.2", + "zbus 4.4.0", + "zeroize", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -1142,6 +2159,17 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + [[package]] name = "kurbo" version = "0.13.1" @@ -1154,11 +2182,26 @@ dependencies = [ "smallvec", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" -version = "0.2.190" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] [[package]] name = "libloading" @@ -1185,7 +2228,7 @@ dependencies = [ "bitflags 2.13.2", "libc", "plain", - "redox_syscall 0.9.4", + "redox_syscall 0.9.5", ] [[package]] @@ -1206,11 +2249,17 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "litrs" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" [[package]] name = "lock_api" @@ -1227,6 +2276,17 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "matext4cgmath" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6541e181de37f70f0aceb25441823a3d0efa9cc1d23f475a0d3926678949178" +dependencies = [ + "cgmath", + "katexit", + "num-complex", +] + [[package]] name = "memchr" version = "2.8.3" @@ -1235,13 +2295,28 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", ] +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -1340,12 +2415,98 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + [[package]] name = "nohash-hasher" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1372,7 +2533,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -1706,13 +2867,29 @@ dependencies = [ [[package]] name = "ordered-float" -version = "5.5.0" +version = "5.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" dependencies = [ "num-traits", ] +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -1741,10 +2918,34 @@ name = "pcbcraft" version = "0.1.0" dependencies = [ "eframe", + "keyring", + "pcbcraft-assistant", "pcbcraft-engine", "pcbcraft-io", + "pcbcraft-library", "pcbcraft-mcp", "pcbcraft-ui-egui", + "serde_json", + "tempfile", + "ureq", +] + +[[package]] +name = "pcbcraft-assistant" +version = "0.1.0" +dependencies = [ + "pcbcraft-engine", + "pcbcraft-mcp", + "serde", + "serde_json", +] + +[[package]] +name = "pcbcraft-calc" +version = "0.1.0" +dependencies = [ + "serde", + "toml", ] [[package]] @@ -1755,6 +2956,7 @@ dependencies = [ "pcbcraft-io", "pcbcraft-mcp", "serde_json", + "tempfile", ] [[package]] @@ -1772,6 +2974,7 @@ dependencies = [ name = "pcbcraft-engine" version = "0.1.0" dependencies = [ + "base64", "pcbcraft-doc", "pcbcraft-geom", "pcbcraft-io", @@ -1779,13 +2982,17 @@ dependencies = [ "pcbcraft-rules", "serde", "serde_json", + "tempfile", "thiserror 2.0.21", + "toml", ] [[package]] name = "pcbcraft-geom" version = "0.1.0" dependencies = [ + "i_float", + "i_overlay", "serde", "thiserror 2.0.21", ] @@ -1794,13 +3001,22 @@ dependencies = [ name = "pcbcraft-io" version = "0.1.0" dependencies = [ + "base64", + "gltf", "image", "pcbcraft-doc", "pcbcraft-geom", "pcbcraft-library", + "pcbcraft-rules", + "png 0.18.1", + "serde", "serde_json", + "sha2", "tempfile", "thiserror 2.0.21", + "toml", + "truck-meshalgo", + "truck-stepio", ] [[package]] @@ -1809,6 +3025,8 @@ version = "0.1.0" dependencies = [ "pcbcraft-geom", "serde", + "serde_json", + "tempfile", "thiserror 2.0.21", ] @@ -1817,8 +3035,10 @@ name = "pcbcraft-mcp" version = "0.1.0" dependencies = [ "base64", + "getrandom 0.3.4", "pcbcraft-engine", "pcbcraft-io", + "pcbcraft-library", "serde_json", "tempfile", ] @@ -1833,22 +3053,36 @@ dependencies = [ "serde", ] +[[package]] +name = "pcbcraft-sim" +version = "0.1.0" + +[[package]] +name = "pcbcraft-text" +version = "0.1.0" + [[package]] name = "pcbcraft-ui-egui" version = "0.1.0" dependencies = [ + "base64", "craft-ui", "eframe", "egui", + "egui_extras", "image", + "pcbcraft-assistant", "pcbcraft-doc", "pcbcraft-engine", "pcbcraft-geom", + "pcbcraft-io", "pcbcraft-library", "pcbcraft-mcp", "pcbcraft-rules", + "pcbcraft-text", "serde", "serde_json", + "tempfile", ] [[package]] @@ -1858,6 +3092,7 @@ dependencies = [ "eframe", "pcbcraft-engine", "pcbcraft-mcp", + "pcbcraft-text", "pcbcraft-ui-egui", "wasm-bindgen", "wasm-bindgen-futures", @@ -1865,23 +3100,72 @@ dependencies = [ ] [[package]] -name = "peniko" -version = "0.6.1" +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo 0.13.1", + "linebender_resource_handle", + "smallvec", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" dependencies = [ - "bytemuck", - "color", - "kurbo", - "linebender_resource_handle", - "smallvec", + "siphasher", ] [[package]] -name = "percent-encoding" -version = "2.3.2" +name = "pico-args" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" [[package]] name = "pin-project" @@ -1909,6 +3193,17 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -1921,6 +3216,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "png" version = "0.18.1" @@ -1944,7 +3252,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -1978,19 +3286,71 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "presser" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit", + "toml_edit 0.25.17+spec-1.1.0", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", ] [[package]] @@ -2050,6 +3410,36 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -2074,6 +3464,35 @@ dependencies = [ "objc2-quartz-core 0.3.2", ] +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "rclite" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e09665c494a9de2bd230e1aedc0c2fb20481a51f28f7db84d0c9bcfe2fe537b2" +dependencies = [ + "branches", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -2105,33 +3524,110 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "renderdoc-sys" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "resvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" +dependencies = [ + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "robust" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839" + [[package]] name = "ron" -version = "0.12.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81116b9531d61eabc41aeb228e4b6b2435bcca3233b98cf3b3077d4e6e9debb3" +checksum = "97b3fe97c18ff24299ea56f802c5693eb34266fb0bc8317f4e101debc8a3ceaf" dependencies = [ "bitflags 2.13.2", - "once_cell", "serde", "serde_derive", "typeid", "unicode-ident", ] +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + [[package]] name = "rustc-hash" version = "1.1.0" @@ -2168,9 +3664,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -2179,6 +3675,71 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "ruststep" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df866eb24b48dd4bb8a3cb0dfeb3a25ff2c251ed93aae1cbfc03eb8ee3c7dcc" +dependencies = [ + "Inflector", + "derive-new", + "derive_more", + "itertools 0.10.5", + "nom", + "ruststep-derive", + "serde", + "thiserror 1.0.69", +] + +[[package]] +name = "ruststep-derive" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bfdd035ae42e977d18e3197065392784566ef230eda4241d15799ea2154e84" +dependencies = [ + "Inflector", + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2206,6 +3767,61 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "secret-service" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" +dependencies = [ + "aes", + "cbc", + "futures-util", + "generic-array", + "hkdf", + "num", + "once_cell", + "rand", + "serde", + "sha2", + "zbus 4.4.0", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -2234,31 +3850,73 @@ version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ - "serde_derive", + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", ] [[package]] -name = "serde_derive" -version = "1.0.229" +name = "sha1" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.8", + "cfg-if", + "cpufeatures", + "digest", ] [[package]] -name = "serde_json" -version = "1.0.154" +name = "sha2" +version = "0.10.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", + "cfg-if", + "cpufeatures", + "digest", ] [[package]] @@ -2267,6 +3925,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -2289,6 +3957,21 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "skrifa" version = "0.44.0" @@ -2316,9 +3999,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.3" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" dependencies = [ "serde", ] @@ -2361,7 +4044,7 @@ dependencies = [ "libc", "log", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "wayland-backend", "wayland-client", @@ -2395,6 +4078,18 @@ dependencies = [ "serde", ] +[[package]] +name = "spade" +version = "2.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9699399fd9349b00b184f5635b074f9ec93afffef30c853f8c875b32c0f8c7fa" +dependencies = [ + "hashbrown 0.16.1", + "num-traits", + "robust", + "smallvec", +] + [[package]] name = "spirv" version = "0.4.0+sdk-1.4.341.0" @@ -2404,12 +4099,54 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo 0.11.3", + "siphasher", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "2.0.119" @@ -2423,15 +4160,26 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.8" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01016da373cd8f7ef12624f796309f5c31ba8d646dd08856c02cd741d823c622" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -2441,7 +4189,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -2491,7 +4239,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.8", + "syn 3.0.9", ] [[package]] @@ -2508,15 +4256,72 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.17.16", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tokio" -version = "1.53.2" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "pin-project-lite", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + [[package]] name = "toml_datetime" version = "1.1.2+spec-1.1.0" @@ -2526,6 +4331,31 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap", + "toml_datetime 0.6.11", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + [[package]] name = "toml_edit" version = "0.25.17+spec-1.1.0" @@ -2533,9 +4363,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap", - "toml_datetime", + "toml_datetime 1.1.2+spec-1.1.0", "toml_parser", - "winnow", + "winnow 1.0.4", ] [[package]] @@ -2544,9 +4374,15 @@ version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ - "winnow", + "winnow 1.0.4", ] +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tracing" version = "0.1.44" @@ -2555,61 +4391,290 @@ checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "log", "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tracing-core" version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "truck-base" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c279de9e92e5dc20a188deb0bb9a4bd421a6a185e57e03e19025e84a36c5a05" +dependencies = [ + "cgmath", + "matext4cgmath", + "rustc-hash 2.1.3", + "serde", +] + +[[package]] +name = "truck-derivers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "421ff1c5a303aed64e295d9b30e8424ee7a2fa251617a59ae4acfd078496009f" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "truck-geometry" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d9d85f203fdbc2d206a38b8e7c4417a05a2eb589be8b81ecfe9f98faafc425d" +dependencies = [ + "serde", + "thiserror 1.0.69", + "truck-base", + "truck-geotrait", +] + +[[package]] +name = "truck-geotrait" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a31fe98d5a0589ad20576260e214af23dea21a8d125da81ad3bbcb666f411f" +dependencies = [ + "getrandom 0.2.17", + "rand", + "thiserror 1.0.69", + "truck-base", + "truck-derivers", +] + +[[package]] +name = "truck-meshalgo" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e18f325738e822c79bb1a48897ec789cbf50cbeeb0841105295f9da85bdf3613" +dependencies = [ + "array-macro", + "derive_more", + "itertools 0.13.0", + "rayon", + "rustc-hash 2.1.3", + "spade", + "truck-base", + "truck-geometry", + "truck-polymesh", + "truck-topology", +] + +[[package]] +name = "truck-modeling" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8082c2dfac8c2732a014d81807fb5d24dbac0d72ee4de2a705b7fbc05fa05b18" +dependencies = [ + "derive_more", + "rustc-hash 2.1.3", + "serde", + "thiserror 1.0.69", + "truck-base", + "truck-geometry", + "truck-geotrait", + "truck-polymesh", + "truck-topology", +] + +[[package]] +name = "truck-polymesh" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8f22def310af4a89c37beb4839bbf702b302d2c112ea29553759f0e16622fbf" +dependencies = [ + "array-macro", + "bytemuck", + "itertools 0.13.0", + "rustc-hash 2.1.3", + "serde", + "thiserror 1.0.69", + "truck-base", + "truck-geotrait", +] + +[[package]] +name = "truck-stepio" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d29cf5b0dec4b927e80b5dca26ce3ca69601c77ea5b9c953e30bfc3e123d189" +dependencies = [ + "chrono", + "derive_more", + "ruststep", + "serde", + "truck-derivers", + "truck-geometry", + "truck-geotrait", + "truck-modeling", + "truck-polymesh", + "truck-topology", +] + +[[package]] +name = "truck-topology" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf62a1610405c5e39ab5eb6948f326fc1641689734a6b8207a80792133fe0e78" +dependencies = [ + "parking_lot", + "rayon", + "rclite", + "rustc-hash 2.1.3", + "serde", + "thiserror 1.0.69", + "truck-base", + "truck-geotrait", +] [[package]] name = "type-map" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" -dependencies = [ - "rustc-hash 2.1.3", -] +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] -name = "typeid" -version = "1.0.3" +name = "untrusted" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] -name = "unicode-general-category" -version = "1.1.0" +name = "ureq" +version = "2.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "url", + "webpki-roots 0.26.11", +] [[package]] -name = "unicode-ident" -version = "1.0.26" +name = "url" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] [[package]] -name = "unicode-segmentation" -version = "1.13.3" +name = "usvg" +version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64", + "data-url", + "flate2", + "imagesize", + "kurbo 0.11.3", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "xmlwriter", +] [[package]] -name = "unicode-width" -version = "0.2.2" +name = "utf8_iter" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] name = "uuid" -version = "1.28.0" +version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ + "js-sys", "serde_core", + "wasm-bindgen", ] [[package]] @@ -2655,6 +4720,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -2707,7 +4778,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.8", + "syn 3.0.9", "wasm-bindgen-shared", ] @@ -2728,7 +4799,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -2741,7 +4812,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -2763,7 +4834,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -2875,6 +4946,24 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.11", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -3363,7 +5452,7 @@ dependencies = [ "calloop 0.13.0", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -3399,6 +5488,24 @@ dependencies = [ "xkbcommon-dl", ] +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "1.0.4" @@ -3414,6 +5521,12 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "x11-dl" version = "2.21.0" @@ -3436,7 +5549,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -3452,6 +5565,16 @@ version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" +[[package]] +name = "xdg-home" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "xkbcommon-dl" version = "0.4.2" @@ -3477,33 +5600,311 @@ version = "0.8.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + [[package]] name = "xtask" version = "0.1.0" dependencies = [ + "pcbcraft-doc", + "pcbcraft-engine", + "pcbcraft-geom", + "pcbcraft-io", + "pcbcraft-library", + "pcbcraft-rules", + "pcbcraft-text", "serde_json", ] +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zbus" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +dependencies = [ + "async-broadcast", + "async-executor", + "async-fs", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix", + "ordered-stream", + "rand", + "serde", + "serde_repr", + "sha1", + "static_assertions", + "tracing", + "uds_windows", + "windows-sys 0.52.0", + "xdg-home", + "zbus_macros 4.4.0", + "zbus_names 3.0.0", + "zvariant 4.2.0", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.6", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.4", + "zbus_macros 5.19.0", + "zbus_names 4.3.5", + "zvariant 5.15.1", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant 5.15.1", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant 5.15.1", +] + +[[package]] +name = "zbus_macros" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils 2.1.0", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names 4.3.5", + "zvariant 5.15.1", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zbus_names" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +dependencies = [ + "serde", + "static_assertions", + "zvariant 4.2.0", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow 1.0.4", + "zvariant 5.15.1", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow 1.0.4", + "zbus_names 4.3.5", + "zvariant 5.15.1", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + [[package]] name = "zerocopy" -version = "0.8.62" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.62" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" dependencies = [ "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -3530,3 +5931,81 @@ checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ "zune-core", ] + +[[package]] +name = "zvariant" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +dependencies = [ + "endi", + "enumflags2", + "serde", + "static_assertions", + "zvariant_derive 4.2.0", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 1.0.4", + "zcheapstr", + "zvariant_derive 5.15.1", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zvariant_derive" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils 2.1.0", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zvariant_utils" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow 1.0.4", +] diff --git a/Cargo.toml b/Cargo.toml index 3af9a8753..c96922993 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,16 +15,31 @@ pcbcraft-rules = { path = "crates/rules" } pcbcraft-io = { path = "crates/io" } pcbcraft-engine = { path = "crates/engine" } pcbcraft-mcp = { path = "crates/mcp" } +pcbcraft-assistant = { path = "crates/assistant" } pcbcraft-ui-egui = { path = "crates/ui-egui" } pcbcraft-library = { path = "crates/library" } +pcbcraft-text = { path = "crates/text" } +pcbcraft-sim = { path = "crates/sim" } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" +toml = "0.8" +# Pinned: polygon booleans and round offsets for copper pour fill. +i_overlay = "=9.1.0" egui = "0.36" -eframe = { version = "0.36", default-features = false, features = ["default_fonts", "wgpu", "x11", "wayland", "persistence"] } +egui_extras = { version = "0.36", default-features = false, features = ["svg"] } +eframe = { version = "0.36", default-features = false, features = ["default_fonts", "wgpu", "x11", "wayland", "persistence", "accesskit"] } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1aa81a773aa9198a0e4c0daeda954d622475af38" } -image = { version = "0.25", default-features = false, features = ["png"] } +image = { version = "0.25", default-features = false, features = ["png", "bmp"] } +png = "0.18.1" base64 = "0.22" +sha2 = "0.10" +getrandom = "0.3" +# glTF reader for 3D model files; MIT OR Apache-2.0, pure Rust. No image decoding. +# STEP reading and tessellation for 3D model files; Apache-2.0, pure Rust. +truck-stepio = "0.3" +truck-meshalgo = { version = "0.4", default-features = false, features = ["tessellation"] } +gltf = { version = "1", default-features = false, features = ["utils"] } tempfile = "3" [workspace.lints.rust] diff --git a/README.md b/README.md index b90377e41..4ea791d84 100644 --- a/README.md +++ b/README.md @@ -1,170 +1,74 @@ # PCBCraft -**A Rust EDA application, MCP-first, with one window and tabbed workspaces.** - -GPL-3.0-or-later. Inspired by KiCad workflows and the SolidCraft / Craft application -architecture. Uses the pinned `craft-ui` library from `storytold/craft-libs`. - -**Status: first working foundation, not a KiCad replacement yet.** The current -vertical slice is a flat schematic → assigned SMD PCB → basic routing → checks → KiCad -board export. The complete EDA roadmap is in [ROADMAP.md](ROADMAP.md). - -## What works - -- One native Rust window with Schematic, PCB Layout, Libraries and Checks tabs; - project browser and properties remain docked in the same window. -- Dark default, light theme, persistent accent and grid preferences, zoom around - the cursor, middle-button pan, symbol previews and drag-to-move. -- Periodic project recovery and recovery on normal close, using application storage. -- Original resistor, capacitor, LED and two-pin connector symbols; explicit - logical nets and pin-to-pin orthogonal wire presentations. -- Background search and geometry previews of installed KiCad symbol/footprint - libraries, including inherited definitions. Place supported symbols with - independently movable schematic units within one physical package, assign - matching front SMD or plated through-hole footprints, and embed used definitions. -- Symbol and footprint editors in the Libraries tab: editable pins, unit membership, - pad/drill dimensions, and line/rectangle/circle/arc/polyline/text graphics. Save - undoable project-library definitions and reusable `.pcbcraft-lib` collections. -- Schematic-to-PCB sync retains existing placements and reconciles pad nets. -- Real circle/rectangle/roundrect/oval front SMD and plated through-hole pads, - circular/oval offset drills, plus generic starter pads; - straight or two-segment orthogonal tracks; - airwires from actual same-layer copper connectivity. -- Editable rectangular board width/height and dimensioned circular cutouts, - exported as Edge.Cuts. Constrained/parametric outline sketches are planned. -- Initial pin assignment/net-population checks and copper short, clearance, - board-edge, cutout and unrouted checks with affected object IDs. -- 26 engine commands, discoverable schemas, atomic batches, stable IDs, - revision guards, 32-step undo/redo and validated atomic project saves. -- 44 MCP tools: every engine command plus library discovery/search/inspection, - design inspection, checks, persistence, - export and PNG previews. Headless or bridged into the actual running desktop. -- Rust browser entry point; the shared UI and engine compile to WebAssembly. - Browser host-file open/save/export are not implemented yet. - -## Run on Linux / WSL - -Install Rust 1.95+ and window-system development libraries. On Ubuntu: +One native window for schematic, board layout, libraries and checks. Every edit +goes through a typed engine command. The desktop, the CLI and MCP call the same +commands. + +GPL-3.0-or-later. UI toolkit: pinned `craft-ui` from `storytold/craft-libs`. + +This is a working foundation: a schematic, assigned footprints, basic routing, +checks, and fabrication output. It is not a finished production suite. Open +items live in [ROADMAP.md](ROADMAP.md). + +**Start here:** [docs/getting-started.md](docs/getting-started.md) + +## Run + +Rust 1.95 or newer. On Ubuntu, install window libraries first: ```sh sudo apt install build-essential pkg-config libxkbcommon-dev libwayland-dev \ libx11-dev libxi-dev libxrandr-dev libxcursor-dev libgl1-mesa-dev -rustup target add wasm32-unknown-unknown -cargo run -p pcbcraft -- --sample --control 127.0.0.1:7991 -cargo run -p pcbcraft -- --project led.pcbcraft --tab pcb ``` -WSLg can display the Linux app on Windows. For automated UI capture without a -desktop, use Xvfb with `--capture`: +Then: ```sh -xvfb-run -a -s '-screen 0 1600x1100x24' \ - env -u WAYLAND_DISPLAY WGPU_BACKEND=vulkan \ - cargo run -p pcbcraft -- --sample --capture /tmp/pcbcraft.png +git clone https://github.com/wdunn001/pcbcraft.git +cd pcbcraft +cargo run -p pcbcraft -- --sample ``` -Windows can also build natively with `cargo run -p pcbcraft -- --sample`. - -## First circuit - -Load **LED example**, or press **A** to select a symbol and click to place it. -Press **W**, then click two pin circles to connect them. A new net is created -atomically if neither pin is assigned; conflicting existing nets are rejected. -Click **Sync to PCB** to generate footprints. Press **X** and click two same-net -pads to route between them. Open **Checks** to inspect remaining findings. Save -the native `.pcbcraft` project or export its board to `.kicad_pcb`. - -The route tool is a simple orthogonal pad-to-pad operation. It does not avoid -obstacles; inspect its clearance findings. Footprint movement does not drag tracks. -Wire crossings do not implicitly join logical nets. - -## KiCad libraries - -Install KiCad's symbol and footprint libraries, then open **Libraries**. Search a -symbol, preview it and choose **Place in schematic**. Select its placed component, -choose **Assign footprint in Libraries**, and assign a package whose numbered pads -match its pins. **Sync to PCB** retains placement and reports symbols that still -need footprints. The project embeds used geometry, so reopening needs no library -installation. The desktop discovers Linux, Windows and Ubuntu WSL library folders; -custom paths and `KICAD10_SYMBOL_DIR` / `KICAD10_FOOTPRINT_DIR` are supported. - -Multi-unit symbols share one component/reference, physical pin map and footprint; -each unit can move/rotate independently. Select its drawing or choose the unit in -Properties. All units, including separate power units, are initially placed. -Placement supports up to 32 units, 64 unique physical pins, and front SMD/plated -through-hole circle/rect/roundrect/oval pads. Repeated common pin numbers across -units, unsupported graphical pin styles, NPTH mechanical holes, back SMD placement, -3D models, footprint copper graphics and general KiCad project import remain planned. -Rounded-pad clearance uses sampled outlines with a small conservative error bound; -connectivity uses inscribed pad bounds and can conservatively flag corner contacts. -See [library formats, limits and provenance](docs/kicad-libraries.md). - -Choose **Edit a copy**, **New symbol**, or **New footprint** inside Libraries to -author a definition. Edit pins/pads and drawing primitives with a live preview, -then save to **Project library**. Save/load a `.pcbcraft-lib` collection to reuse -it elsewhere. Original nodes and attribution notices are retained for imported -copies; native libraries reject unknown data fields rather than discarding them. -Library edits do not silently change placed definitions. Reassign a revised -footprint or place a revised symbol explicitly. KiCad library writing and advanced -interactive library drawing remain planned. - -The portable `examples/dual-amplifier.pcbcraft` demonstrates three LM358 units, -one edited DIP8 package with an offset oval drill, and front/back routing. - -## Keyboard defaults - -| Shortcut | Action | -|---|---| -| A | Inline add-symbol chooser (schematic) | -| W | Wire between pins (schematic) | -| X | Route between pads (PCB) | -| M | Move selection, then click destination | -| R | Rotate selection 90° | -| E | Show properties | -| Delete | Delete selection | -| Escape | Cancel tool / placement preview | -| Ctrl+Z / Ctrl+Y | Undo / redo (Ctrl+Shift+Z also redoes) | -| Ctrl+S | Save to the inline project path | -| Ctrl+K | Inline command panel | -| Home | Fit the active canvas | - -These are the initial KiCad-style defaults, not a complete configurable KiCad keymap. - -## CLI and MCP +Same `cargo run` line on native Windows. Headless MCP: ```sh -cargo run -p pcbcraft-cli -- commands -cargo run -p pcbcraft-cli -- sample --out led.pcbcraft -cargo run -p pcbcraft-cli -- run examples/led-indicator.json --save led.pcbcraft --export led.kicad_pcb -cargo run -p pcbcraft-cli -- checks --project led.pcbcraft -cargo run -p pcbcraft-cli -- snapshot --sample --view pcb --out led.png cargo run -p pcbcraft-cli -- mcp -cargo run -p pcbcraft-cli -- mcp --connect 127.0.0.1:7991 ``` -See [docs/mcp.md](docs/mcp.md) for client configuration and request examples. -MCP uses JSON-RPC over newline-delimited stdio. Logs/errors go to stderr. +Fork of record: [wdunn001/pcbcraft](https://github.com/wdunn001/pcbcraft). Tagged +builds, when published, appear under +[Releases](https://github.com/wdunn001/pcbcraft/releases). -## Development +## First circuit -```sh -cargo xtask ci # formatting, clippy, tests, UI/engine/browser wasm checks -cargo build -p pcbcraft -p pcbcraft-cli -# Browser: install Trunk, then: -cd apps/pcbcraft-web && trunk serve -``` +Load **LED example**. **A** places a symbol; click to drop it. **W**, then two +pin circles, draws a wire. If neither pin has a net, one is created; two +different existing nets are refused. **Sync to PCB** creates footprints for +assigned parts. **X**, then two same-net pads, routes an orthogonal track. +**Checks** lists what is still wrong. + +Save a `.pcbcraft` project. The route tool does not dodge obstacles. Moving a +footprint does not drag its tracks. Crossing wires do not join nets. + +Default keys: [docs/getting-started.md](docs/getting-started.md#keyboard). + +## Docs -Keep build products outside the mounted Windows tree in WSL for better filesystem -performance, e.g. `CARGO_TARGET_DIR=$HOME/.cache/pcbcraft-target`. +| Page | Contents | +| --- | --- | +| [Getting started](docs/getting-started.md) | Clone, first run, MCP, fork workflow | +| [What is implemented](docs/capabilities.md) | Editing, libraries, checks, export | +| [Roadmap](ROADMAP.md) | Open work by milestone | +| [Architecture](docs/architecture.md) | Crate layers and MCP-first rules | +| [MCP](docs/mcp.md) | Client config and request shape | +| [CI](docs/ci.md) | GitHub Actions jobs; do not run the full suite on a laptop | +| [CONTRIBUTING](CONTRIBUTING.md) | Issue tags through merge | +| [AGENTS](AGENTS.md) | Parallel agents, UI lane, honesty rules | -Architecture: [docs/architecture.md](docs/architecture.md). Agent instructions: -[AGENTS.md](AGENTS.md). Provenance: [ATTRIBUTION.md](ATTRIBUTION.md). +Doc index: [docs/README.md](docs/README.md). ## License -PCBCraft is licensed under GNU GPL version 3 or later; see [LICENSE](LICENSE). -Third-party dependencies retain their own licenses and notices. No KiCad source -implementation has been copied or ported in this initial version. KiCad is an -independent project; PCBCraft is not affiliated with or endorsed by the KiCad team. -KiCad library fixtures retain CC-BY-SA 4.0 with the design-output exception; the -data license is separate from the Rust application's GPL license. +GNU GPL version 3 or later; see [LICENSE](LICENSE). Third-party crates keep +their own notices. Provenance of adapted code and library fixtures: +[ATTRIBUTION.md](ATTRIBUTION.md). diff --git a/ROADMAP.md b/ROADMAP.md index 6c1edc57a..557e85bc3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,8 +2,13 @@ The target is a complete Rust EDA application with MCP access to every feature. This checklist records implementation, not an estimated parity percentage. +Each open line names the tracker issue that carries it. The program status epic, +tangency-labs/pcbcraft#352, mirrors this list with what is in flight and the open +owner decisions. Milestone names here match the `milestone:` tags described in +CONTRIBUTING.md: M1 to M4 are `milestone:m1` to `milestone:m4`, M5 is +`milestone:m5`, M6 is `milestone:m6`. -## M0 — MCP-first foundation (implemented) +## M0: MCP-first foundation (implemented) - [x] Rust workspace and enforced dependency direction - [x] Stable IDs, typed commands, discoverable schemas, revision guards @@ -13,7 +18,7 @@ This checklist records implementation, not an estimated parity percentage. - [x] Pinned craft-ui integration; dark/light/accent/grid preferences - [x] Native and WebAssembly compilation gates -## M1 — First circuit (implemented subset) +## M1: First circuit (implemented subset) - [x] Four original two-pin symbol templates and generic SMD footprints - [x] Explicit pin nets and orthogonal schematic wire presentation @@ -21,46 +26,116 @@ This checklist records implementation, not an estimated parity percentage. - [x] Basic straight and orthogonal tracks, same-layer copper connectivity, airwires - [x] Initial ERC/DRC with affected object references - [x] Rectangular outline dimensions and circular cutouts -- [x] KiCad PCB subset export and external KiCad CLI validation -- [x] Read/search/preview installed KiCad symbol and footprint libraries +- [x] Board interchange subset export validated with an external checker +- [x] Read/search/preview installed symbol and footprint libraries - [x] Embed placed single/multi-unit symbols and assigned front SMD/PTH footprints -- [x] Actual pad geometry in UI, previews, clearance checks and KiCad export +- [x] Actual pad geometry in UI, previews, clearance checks and board export - [x] Native project-library symbol/footprint editors with pins, pads and graphics - [x] Multi-unit packages with independently movable schematic units and one footprint - [x] Reusable native library collections, attribution, atomic saves and undoable load - [x] Plated through-hole pads, circular/oval offset drills, front/back pad bridges -- [ ] Interactive canvas library drawing and KiCad library writers -- [ ] Repeated common pins, graphical pin styles, NPTH holes and back SMD placement -- [ ] Explicit wire vertices, junctions, labels, buses and hierarchy -- [ ] General KiCad import with unknown-field preservation and round-trip fixtures -- [ ] Complete pin-type electrical rules and project/net-class rules -- [ ] Browser download/upload and project recovery -- [ ] Configurable shortcut profiles and complete KiCad default keymap - -## M2 — Serious board layout - -- [ ] Custom/chamfered pad shapes, vias and multilayer stackups -- [ ] Interactive 45° routing, obstacle avoidance, shove and track dragging -- [ ] Differential pairs, length tuning, impedance-aware constraints -- [ ] Copper zones, thermal reliefs, islands, keepouts, robust polygon operations -- [ ] Comprehensive clearance and manufacturing checks -- [ ] Gerber, Excellon, placement files, BOM and fabrication packages - -## M3 — Sketch-driven board geometry and mechanical coordination - -- [ ] Line/arc outline sketch model inspired by SolidCraft's planar sketch workflow -- [ ] Dimensions, constraints, named parameters and expression-driven regeneration -- [ ] Slots, notches, mounting holes and dimensioned patterns -- [ ] PCB/enclosure coordination, shared mounting datums and STEP exchange -- [ ] Real 3D board tab with component bodies and inspection - -## M4 — Complete workflows and distribution - -- [ ] Simulation strategy compatible with the Rust-only constraint -- [ ] Full schematic/PCB/library editor workflows and reference-project parity suite -- [ ] Autosave/recovery, project migration, large-board responsiveness -- [ ] Native Windows/Linux/macOS packaging, browser distribution -- [ ] Craft Launcher integration where authorized by its maintainers +- [ ] Interactive canvas library drawing (#300) and library writers (#301) (#300 subset on fork main; #459, #460 remain open) +- [ ] Repeated common pins (#302) and back SMD placement (#305) +- [x] Graphical pin styles on project-library symbols (#303 subset on fork main) +- [x] Unplated footprint holes and board mounting holes/slots (#304 subset on fork main) +- [x] Explicit wire vertices, junctions, labels and no-connect flags (#308 subset on fork main) +- [ ] Buses (#308) and hierarchy (#306, #307) (#308 subset on fork main; #379, #380, #461, #462, #464, #465 remain open) +- [ ] General import of boards and schematics with unknown-field preservation and round-trip fixtures (#309, #310, #311) (#309 subset on fork main; #310, #311, #458, #463 remain open) +- [ ] Complete pin-type electrical rules (#312) and project/net-class rules with fabrication presets (#313) (#312 subset on fork main; #381, #382, #384, #466, #467 remain open) +- [ ] Browser download/upload and project recovery (#314) (#314 subset on fork main; #438, #440 remain open) +- [x] Configurable shortcut profiles and a complete default keymap (#315) +- [ ] Schematic and board stay in sync automatically (#332) + +## M2: Serious board layout + +- [x] Chamfered and custom polygon pad shapes with exact clearance outlines (#281) +- [x] Plated vias, stitch grids and editable copper pours with cutouts (thermal reliefs and keepouts #284 remain open) +- [x] Inner copper layer stackups (#317) +- [ ] Interactive 45° routing, obstacle avoidance, shove and track dragging (#282) (#282 subset on fork main; the drag interface remains open) +- [x] Differential pair routing as one coupled gesture (#341 subset on fork main; skew tuning #407 remains open) +- [x] Length tuning and impedance-aware constraints (#283) +- [ ] Copper zone thermal reliefs, islands, keepouts and robust polygon operations (#284) (#284 subset on fork main; the pour panel and keepout interface remain open) +- [ ] Comprehensive clearance and manufacturing checks (#285) (#285 subset on fork main; #489 remains open) +- [x] Checks on drawn machine layers against the copper and vias they cross (#277) +- [ ] Design-intent electrical checks: power pins, decoupling and pull-ups (#334) (#334 subset on fork main; #492, #498, #499, #501 remain open) +- [x] Many fabrication plots, drill, placement, BOM and named output jobs (#286 subset on fork main; fabrication-valid copper gerbers #351 remain open) +- [ ] Everyday editing: copy and paste, box select, measure, groups and track cleanup (#342) (#342 subset on fork main; #427, #428 remain open) +- [x] Logos and reference images placed as bitmaps and traced to silk, mask or copper (#343) +- [x] Initial Gerber copper layer writer (pad flashes and tracks) + +## M3: Sketch-driven board geometry and mechanical coordination + +- [ ] Line/arc outline sketch model inspired by a planar sketch workflow (#287) +- [x] Dimensions, constraints, named parameters and expression-driven regeneration (#288) +- [x] Unplated mounting holes, routed slots and rectangular edge notches (#289 subset on fork main; sketch-driven patterns remain in #287) +- [x] PCB/enclosure coordination, shared mounting datums and STEP exchange (#290) +- [ ] Component bodies in STEP and enclosure model import (#321) (#321 subset on fork main; STEP part bodies are in, glTF, VRML and STEP model import remain open) +- [ ] Real 3D board tab with component bodies and inspection (#291) (#291 subset on fork main; #542, #670 remain open) + +## M4: Complete workflows and distribution + +- [ ] Simulation strategy compatible with the Rust-only constraint (#292) +- [ ] Full schematic/PCB/library editor workflows +- [x] Reference-project parity suite with golden outputs (#293) +- [ ] Autosave/recovery, project migration, large-board responsiveness (#294) +- [ ] Native Windows/Linux/macOS packaging and browser distribution (#295), built by the CI/CD pipeline (#340) (#295 subset on fork main; #468, #469, #470, #477, #480, #482 remain open) +- [ ] Craft Launcher integration where authorized by its maintainers (#296) +- [ ] Compare two versions of a design (#335) +- [x] Open and inspect fabrication files (#336) +- [ ] Drawing frames and title blocks for schematics and drawings (#337) (#337 subset on fork main; #430, #431 remain open) +- [ ] Accessibility: keyboard-only use, screen reader names and scalable text (#339) (#339 subset on fork main; keyboard-only use and scalable text remain open) +- [ ] Text catalog and translations for every user-visible string (#349) (#349 subset on fork main; #604 remains open) +- [ ] Design calculators: track width, via, impedance, divider and unit conversion (#350) + +## M5: Inner copper layers + +Epic #316. Tag: `milestone:m5`. + +- [x] Layer model for any number of copper layers, with migration of existing designs (#317) +- [ ] Route, pour and check on inner layers (#318) (#318 subset on fork main; #385, #386 remain open) +- [ ] Fabrication outputs per copper layer (#319) +- [x] Blind, buried and micro vias (#320) + +## M6: Manufacturing artifacts + +Epic #322. Tag: `milestone:m6`. Artifacts are first-class project +objects with a stale marker and a preview, produced for fabrication houses and +for in-house machines. + +- [ ] Artifact records with stale marker and preview (#323) (#323 subset on fork main; #387, #388 remain open) +- [ ] Machine profiles (#324) (#324 subset on fork main; #357, #390 remain open) +- [x] Fabrication-house plots with attributes, drill split and drill map (#325) +- [ ] BOM artifact (#326) +- [ ] Assembly and fabrication drawings (#327) +- [x] Fabrication-layer PNG rasters via output jobs (#328 subset on fork main; UV-specific workflows and drawn-layer BMP export remain open) +- [ ] CNC isolation G-code (#329) +- [ ] CNC drilling and outline G-code (#330) +- [ ] Paste stencil and laser cut paths (#331) +- [x] Plot drawn layers for laser, mill and printer output (#276 on fork main) +- [x] Panel fabrication export with breakaway and tooling holes (#338 subset on fork main; interactive panel UI #417-#419 remain open) + +## Workbench and UX + +User-interface work that cuts across milestones. These lines carry +`track:ui-design` and no `milestone:` tag. + +- [x] Top menu bar, Start page, plain menu labels, canvas handles, pin and pad click wiring, stackup-first Layers, status strip, Review groups, custom checks, unified library sources and sets, drawn machine layer model +- [x] Workbench layout: top menu bar, library left, assistant and Layers tree right, tool strip under the tabs (#299) +- [ ] One vector-style Layers tree replaces the Parts, Nets and Layers docks (#274) (scope continues in #756) +- [x] Draw directly on your own layers from the canvas (#275) +- [x] Rules and Checks as top tabs, Project Settings with breathing room (#278) +- [x] Right-click context menu on the canvas (#279) +- [ ] Library browser with filters in the left dock (#280) +- [x] Online part sources: search distributor catalogs from the library (#333) +- [x] Find and place open-library footprints by name (#76) +- [x] Generate IPC-style land patterns from package parameters and read-only footprint checks (#344 subset on fork main) +- [ ] Parts table: edit every part's fields in one grid (#345) (#345 subset on fork main; #435, #436 remain open) +- [ ] Schematic tool strip: wiring, labels, shapes, text and tables drawn on the sheet (#346) (#346 subset on fork main; #443, #444, #445, #475 remain open) +- [ ] Several designs open at once, one document tab each (#347) (#347 subset on fork main; #439, #441, #442 remain open) +- [x] Assistant pane backed by the typed command surface (#348) +- [ ] Assistant epic: bring the assistant structure of a sibling Craft app into PCBCraft (#360), with its core crate (#366), backends (#367, #374), settings (#368), edit gate (#369), context (#370), knowledge retrieval (#371), transcript (#372), offline behaviour and story suite (#373) and shared home decision (#375) (#360 subset on fork main; #371, #374, #375 remain open) +- [x] Move the end-to-end stories out of the UI crate's lib.rs into `crates/ui-egui/tests/e2e/.rs` (#392) +- [ ] Help reference: electrical engineering terms, formulas and calculators inside the app (issue to be filed; related to #350) No feature is considered complete solely because a command exists. Workflows need usable UI, working MCP access, reference fixtures and meaningful verification. diff --git a/apps/pcbcraft-cli/Cargo.toml b/apps/pcbcraft-cli/Cargo.toml index afb529231..ce738e2b8 100644 --- a/apps/pcbcraft-cli/Cargo.toml +++ b/apps/pcbcraft-cli/Cargo.toml @@ -13,3 +13,6 @@ pcbcraft-engine.workspace = true pcbcraft-mcp.workspace = true pcbcraft-io.workspace = true serde_json.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/apps/pcbcraft-cli/src/main.rs b/apps/pcbcraft-cli/src/main.rs index 881ba66a9..aac15eef7 100644 --- a/apps/pcbcraft-cli/src/main.rs +++ b/apps/pcbcraft-cli/src/main.rs @@ -1,6 +1,6 @@ use pcbcraft_engine::{Command, Session}; use serde_json::{Value, json}; -use std::path::Path; +use std::path::{Path, PathBuf}; fn option<'a>(args: &'a [String], key: &str) -> Option<&'a str> { args.iter() @@ -8,6 +8,77 @@ fn option<'a>(args: &'a [String], key: &str) -> Option<&'a str> { .and_then(|i| args.get(i + 1)) .map(String::as_str) } + +fn flag(args: &[String], key: &str) -> bool { + args.iter().any(|a| a == key) +} + +fn empty_session(name: Option<&str>) -> Result { + let mut session = Session::default(); + if let Some(title) = name { + session + .execute("project.rename", json!({"name": title}), None) + .map_err(|e| e.to_string())?; + } + Ok(session) +} + +fn write_new_project(path: &Path, name: Option<&str>) -> Result<(), String> { + if path.exists() { + return Err(format!("{} already exists", path.display())); + } + let session = empty_session(name)?; + pcbcraft_io::save(&session.project, path)?; + Ok(()) +} + +fn scaffold_build_json(name: Option<&str>) -> Value { + let mut commands: Vec = Vec::new(); + if let Some(title) = name { + commands.push(Command { + command: "project.rename".into(), + params: json!({"name": title}), + }); + } + json!({"commands": commands}) +} + +fn init_project_directory(dir: &Path, name: Option<&str>, force: bool) -> Result { + if dir.exists() { + if !dir.is_dir() { + return Err(format!("{} is not a directory", dir.display())); + } + if !force { + let mut entries = std::fs::read_dir(dir).map_err(|e| e.to_string())?; + if entries.next().is_some() { + return Err(format!( + "{} is not empty; pass --force to scaffold anyway", + dir.display() + )); + } + } + } else { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + let design = dir.join("design.pcbcraft"); + if design.exists() && !force { + return Err(format!("{} already exists", design.display())); + } + write_new_project(&design, name)?; + let build_path = dir.join("build.json"); + if build_path.exists() && !force { + return Err(format!("{} already exists", build_path.display())); + } + let script = scaffold_build_json(name); + pcbcraft_io::atomic_write( + &build_path, + serde_json::to_string_pretty(&script) + .map_err(|e| e.to_string())? + .as_bytes(), + )?; + Ok(design) +} + fn run() -> Result<(), String> { let args: Vec<_> = std::env::args().skip(1).collect(); let action = args.first().map(String::as_str).unwrap_or("help"); @@ -46,12 +117,26 @@ fn run() -> Result<(), String> { } println!("{result}"); } - "mcp" => pcbcraft_mcp::serve( - &mut std::io::stdin().lock(), - &mut std::io::stdout().lock(), - &pcbcraft_mcp::shared(session), - option(&args, "--connect"), - )?, + "mcp" => { + let hub = pcbcraft_mcp::DocumentHub::new( + session, + option(&args, "--project").map(str::to_string), + )?; + if let Some(address) = option(&args, "--http") { + // The endpoint and token go to stderr (or a 0600 file); stdout stays unused. + let token_file = option(&args, "--token-file").map(Path::new); + let (listener, token) = + pcbcraft_mcp::http::start_http(address, token_file, &mut std::io::stderr())?; + pcbcraft_mcp::http::serve_listener(&hub, &listener, &token); + return Ok(()); + } + pcbcraft_mcp::serve( + &mut std::io::stdin().lock(), + &mut std::io::stdout().lock(), + &hub, + option(&args, "--connect"), + )? + } "run" => { let path = args .get(1) @@ -77,6 +162,29 @@ fn run() -> Result<(), String> { } println!("{result}"); } + "new" => { + let path = option(&args, "--out").ok_or("new requires --out design.pcbcraft")?; + let title = option(&args, "--name"); + write_new_project(Path::new(path), title)?; + println!("{}", json!({"path":path,"name":title})); + } + "init" => { + let dir = option(&args, "--dir") + .or_else(|| args.get(1).map(String::as_str)) + .ok_or("init requires DIRECTORY or --dir PATH")?; + let title = option(&args, "--name"); + let force = flag(&args, "--force"); + let design = init_project_directory(Path::new(dir), title, force)?; + println!( + "{}", + json!({ + "directory": dir, + "design": design.to_string_lossy(), + "build": Path::new(dir).join("build.json").to_string_lossy(), + "name": title, + }) + ); + } "sample" => { let path = option(&args, "--out").ok_or("sample requires --out design.pcbcraft")?; let sample = Session::sample().map_err(|e| e.to_string())?; @@ -98,16 +206,111 @@ fn run() -> Result<(), String> { pcbcraft_io::atomic_write(Path::new(path), &bytes)?; println!("{}", json!({"path":path,"view":view})); } + "diff" => { + let path_a = args + .get(1) + .ok_or("usage: pcbcraft-cli diff PATH_A PATH_B [--format text|json]")?; + let path_b = args + .get(2) + .ok_or("usage: pcbcraft-cli diff PATH_A PATH_B [--format text|json]")?; + let format = option(&args, "--format").unwrap_or("text"); + let left = pcbcraft_io::load(Path::new(path_a))?; + let right = pcbcraft_io::load(Path::new(path_b))?; + let diff = pcbcraft_io::project_diff(&left, &right); + match format { + "json" => println!("{}", diff.to_json()), + "text" => { + if diff.is_empty() { + println!("designs match"); + } else { + println!("{}", diff.to_text()); + } + } + other => return Err(format!("unknown diff format: {other}")), + } + if !diff.is_empty() { + std::process::exit(1); + } + } "help" | "--help" | "-h" => println!( - "PCBCraft — Rust EDA, MCP-first\n\ncommands | inspect | checks | sample | run | export | snapshot | tool | mcp\n\nCommon: --sample or --project FILE\nTool: pcbcraft-cli tool NAME --args JSON [--save FILE]\nMCP: pcbcraft-cli mcp [--connect 127.0.0.1:7991]\nDesktop: pcbcraft --sample --control 127.0.0.1:7991\nSee README.md and docs/mcp.md for schemas and examples." + "PCBCraft — Rust EDA, MCP-first\n\n\ +commands | inspect | checks | new | init | sample | run | export | snapshot | diff | tool | mcp\n\n\ +Common: --sample or --project FILE\n\ +new: pcbcraft-cli new --out design.pcbcraft [--name TITLE]\n\ +init: pcbcraft-cli init DIRECTORY [--name TITLE] [--force]\n\ +Diff: pcbcraft-cli diff FILE_A FILE_B [--format text|json] (exit 1 when designs differ)\n\ +Tool: pcbcraft-cli tool NAME --args JSON [--save FILE]\n\ +MCP: pcbcraft-cli mcp [--connect 127.0.0.1:7991 | --http 127.0.0.1:PORT [--token-file FILE]]\n\ +Desktop: pcbcraft --sample --control 127.0.0.1:7991\n\ +See README.md and docs/mcp.md for schemas and examples." ), _ => return Err(format!("unknown action: {action}")), } Ok(()) } + fn main() { if let Err(error) = run() { eprintln!("pcbcraft-cli: {error}"); std::process::exit(1); } } + +#[cfg(test)] +mod tests { + use super::*; + use pcbcraft_io::load; + + #[test] + fn new_writes_an_empty_native_project_file() -> Result<(), String> { + let dir = tempfile::tempdir().map_err(|e| e.to_string())?; + let path = dir.path().join("blank.pcbcraft"); + write_new_project(&path, None)?; + let project = load(&path)?; + assert_eq!(project.name, "Untitled circuit"); + assert!(project.components.is_empty()); + Ok(()) + } + + #[test] + fn new_applies_the_optional_title() -> Result<(), String> { + let dir = tempfile::tempdir().map_err(|e| e.to_string())?; + let path = dir.path().join("named.pcbcraft"); + write_new_project(&path, Some("Bench power"))?; + let project = load(&path)?; + assert_eq!(project.name, "Bench power"); + Ok(()) + } + + #[test] + fn init_scaffolds_a_directory_with_design_and_build_json() -> Result<(), String> { + let root = tempfile::tempdir().map_err(|e| e.to_string())?; + let folder = root.path().join("my-board"); + let design = init_project_directory(&folder, Some("My board"), false)?; + assert_eq!(design, folder.join("design.pcbcraft")); + let loaded = load(&design)?; + assert_eq!(loaded.name, "My board"); + let build_text = pcbcraft_io::read_text(&folder.join("build.json"))?; + let build: Value = serde_json::from_str(&build_text).map_err(|e| e.to_string())?; + let commands = build + .get("commands") + .and_then(Value::as_array) + .map(|v| v.len()) + .unwrap_or(0); + assert_eq!(commands, 1); + Ok(()) + } + + #[test] + fn init_refuses_a_nonempty_directory_without_force() -> Result<(), String> { + let root = tempfile::tempdir().map_err(|e| e.to_string())?; + let folder = root.path().join("busy"); + std::fs::create_dir_all(&folder).map_err(|e| e.to_string())?; + std::fs::write(folder.join("notes.txt"), b"keep").map_err(|e| e.to_string())?; + let err = init_project_directory(&folder, None, false) + .err() + .ok_or("expected init to fail on a non-empty directory")?; + assert!(err.contains("not empty")); + Ok(()) + } +} diff --git a/apps/pcbcraft-web/Cargo.toml b/apps/pcbcraft-web/Cargo.toml index 62ae47bf8..a0e08cdb1 100644 --- a/apps/pcbcraft-web/Cargo.toml +++ b/apps/pcbcraft-web/Cargo.toml @@ -13,8 +13,9 @@ pcbcraft-ui-egui.workspace = true eframe.workspace = true pcbcraft-engine.workspace = true pcbcraft-mcp.workspace = true +pcbcraft-text.workspace = true [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" -web-sys = { version = "0.3", features = ["Window", "Document", "HtmlCanvasElement", "console"] } +web-sys = { version = "0.3", features = ["Window", "Document", "HtmlCanvasElement", "console", "Element"] } diff --git a/apps/pcbcraft-web/index.html b/apps/pcbcraft-web/index.html index d18edd462..e6729a044 100644 --- a/apps/pcbcraft-web/index.html +++ b/apps/pcbcraft-web/index.html @@ -1,2 +1,2 @@ -PCBCraft +PCBCraft diff --git a/apps/pcbcraft-web/src/main.rs b/apps/pcbcraft-web/src/main.rs index 225f217e1..18429a051 100644 --- a/apps/pcbcraft-web/src/main.rs +++ b/apps/pcbcraft-web/src/main.rs @@ -1,3 +1,17 @@ +//! Browser entry point: starts the egui app on the page's canvas. +//! +//! Local rules: the page text that appears before the wasm loads lives in +//! `index.html` and `webgpu-check.js`; its wording must equal the catalog key +//! `web.needs_webgpu` (test `the_page_message_matches_the_catalog`). The wasm +//! build needs a browser with WebGPU; a failed start shows the same message. +//! +//! # Dependencies +//! - `crates/text/strings/en.txt` (message text) +//! - `apps/pcbcraft-web/index.html` and `apps/pcbcraft-web/webgpu-check.js` +//! +//! # Do not +//! - Add text literals here; read them from the catalog. + #[cfg(not(target_arch = "wasm32"))] fn main() { eprintln!("Build the web app with trunk in apps/pcbcraft-web."); @@ -8,6 +22,7 @@ fn main() { wasm_bindgen_futures::spawn_local(async { if let Err(error) = start().await { web_sys::console::error_1(&error); + show_start_failure(); } }); } @@ -21,7 +36,7 @@ async fn start() -> Result<(), wasm_bindgen::JsValue> { .get_element_by_id("pcbcraft") .ok_or_else(|| wasm_bindgen::JsValue::from_str("missing pcbcraft canvas"))? .dyn_into::()?; - let session = pcbcraft_mcp::shared(pcbcraft_engine::Session::default()); + let session = pcbcraft_mcp::shared(demo_session()); eframe::WebRunner::new() .start( canvas, @@ -34,3 +49,80 @@ async fn start() -> Result<(), wasm_bindgen::JsValue> { ) .await } + +/// Show the "needs WebGPU" notice that `index.html` carries, hide the canvas. +/// +/// Called when the app fails to start after load, which is what a browser +/// without a usable graphics adapter produces. The text is the page's own +/// paragraph, kept equal to catalog key `web.needs_webgpu` by a test. +/// +/// # Rules +/// - Best effort: a missing element is ignored, the console already has the error. +/// +/// # Dependencies +/// - `apps/pcbcraft-web/index.html` (`#needs-webgpu`, `#pcbcraft`) +/// +/// # Do not +/// - Panic or return an error; this runs on the failure path. +#[cfg(target_arch = "wasm32")] +fn show_start_failure() { + let Some(document) = web_sys::window().and_then(|window| window.document()) else { + return; + }; + if let Some(notice) = document.get_element_by_id("needs-webgpu") { + let _ = notice.remove_attribute("hidden"); + } + if let Some(canvas) = document.get_element_by_id("pcbcraft") { + let _ = canvas.set_attribute("hidden", ""); + } +} + +/// The session the demo opens with: the built-in sample board. +/// +/// The desktop app's `--sample` flag builds the same project, so checks and +/// tabs behave identically. If the sample cannot be built the demo starts +/// empty rather than failing. +/// +/// # Rules +/// - Never panic; fall back to an empty session. +/// +/// # Dependencies +/// - `crates/engine/src/lib.rs` (`Session::sample`) +/// +/// # Do not +/// - Read files; the browser has none. +#[cfg(any(target_arch = "wasm32", test))] +fn demo_session() -> pcbcraft_engine::Session { + pcbcraft_engine::Session::sample().unwrap_or_default() +} + +#[cfg(test)] +mod tests { + /// The demo opens on a board with parts and nets. + #[test] + fn the_demo_starts_with_a_sample() { + let session = super::demo_session(); + assert!(!session.project.components.is_empty(), "no parts"); + assert!(!session.project.nets.is_empty(), "no nets"); + } + + /// The paragraph in index.html says what the catalog says. + #[test] + fn the_page_message_matches_the_catalog() { + let html = include_str!("../index.html"); + let catalog = pcbcraft_text::Catalog::english(); + for key in [ + "web.needs_webgpu", + "web.download_desktop", + "web.download_desktop.tip", + ] { + assert!(catalog.defines(key), "{key} missing from the catalog"); + assert!( + html.contains(&catalog.get(key)), + "index.html does not carry the catalog text of {key}" + ); + } + let script = include_str!("../webgpu-check.js"); + assert!(script.contains("needs-webgpu")); + } +} diff --git a/apps/pcbcraft-web/tests/webgpu-check.test.js b/apps/pcbcraft-web/tests/webgpu-check.test.js new file mode 100644 index 000000000..5310e4e17 --- /dev/null +++ b/apps/pcbcraft-web/tests/webgpu-check.test.js @@ -0,0 +1,36 @@ +// Run with: node apps/pcbcraft-web/tests/webgpu-check.test.js +const assert = require("node:assert"); +const { pcbcraftNeedsWebGpu } = require("../webgpu-check.js"); + +function fakeDocument() { + const removed = []; + const loaders = ["script", "link"].map((name) => ({ name, remove: () => removed.push(name) })); + const notice = { hidden: true }; + const canvas = { hidden: false }; + return { + removed, + notice, + canvas, + getElementById: (id) => (id === "needs-webgpu" ? notice : id === "pcbcraft" ? canvas : null), + querySelectorAll: () => loaders, + }; +} + +function the_message_shows_without_webgpu() { + const doc = fakeDocument(); + assert.strictEqual(pcbcraftNeedsWebGpu({}, doc), true); + assert.strictEqual(doc.notice.hidden, false, "the message is shown"); + assert.strictEqual(doc.canvas.hidden, true, "the canvas is hidden"); + assert.strictEqual(doc.removed.length, 2, "the wasm loaders are removed"); +} + +function the_page_starts_normally_with_webgpu() { + const doc = fakeDocument(); + assert.strictEqual(pcbcraftNeedsWebGpu({ gpu: {} }, doc), false); + assert.strictEqual(doc.notice.hidden, true); + assert.strictEqual(doc.removed.length, 0); +} + +the_message_shows_without_webgpu(); +the_page_starts_normally_with_webgpu(); +console.log("ok"); diff --git a/apps/pcbcraft-web/webgpu-check.js b/apps/pcbcraft-web/webgpu-check.js new file mode 100644 index 000000000..d3d30dc6c --- /dev/null +++ b/apps/pcbcraft-web/webgpu-check.js @@ -0,0 +1,30 @@ +// Runs before the browser build starts. Without WebGPU the wasm cannot draw +// anything, so this shows a plain message and keeps the wasm from loading. +// The text must equal catalog key web.needs_webgpu (checked by a test in +// src/main.rs). Do not fetch the wasm from here. +function pcbcraftNeedsWebGpu(nav, doc) { + if (nav && nav.gpu) { + return false; + } + var notice = doc.getElementById("needs-webgpu"); + if (notice) { + notice.hidden = false; + } + var canvas = doc.getElementById("pcbcraft"); + if (canvas) { + canvas.hidden = true; + } + var loaders = doc.querySelectorAll( + 'script[type="module"], link[rel="modulepreload"], link[rel="preload"]' + ); + for (var i = 0; i < loaders.length; i += 1) { + loaders[i].remove(); + } + return true; +} +if (typeof module !== "undefined") { + module.exports = { pcbcraftNeedsWebGpu: pcbcraftNeedsWebGpu }; +} +if (typeof document !== "undefined") { + pcbcraftNeedsWebGpu(navigator, document); +} diff --git a/apps/pcbcraft/Cargo.toml b/apps/pcbcraft/Cargo.toml index 2b6f0b7a8..4e6ecd301 100644 --- a/apps/pcbcraft/Cargo.toml +++ b/apps/pcbcraft/Cargo.toml @@ -13,4 +13,12 @@ pcbcraft-ui-egui.workspace = true pcbcraft-engine.workspace = true pcbcraft-mcp.workspace = true pcbcraft-io.workspace = true -eframe.workspace = true +serde_json.workspace = true +eframe = { workspace = true, features = ["accesskit"] } +pcbcraft-assistant.workspace = true +pcbcraft-library.workspace = true +ureq = { version = "2", default-features = false, features = ["tls"] } +keyring = { version = "3", default-features = false, features = ["apple-native", "windows-native", "async-secret-service", "async-io", "crypto-rust"] } + +[dev-dependencies] +tempfile.workspace = true diff --git a/apps/pcbcraft/src/host.rs b/apps/pcbcraft/src/host.rs new file mode 100644 index 000000000..7322f6a3b --- /dev/null +++ b/apps/pcbcraft/src/host.rs @@ -0,0 +1,101 @@ +//! What the desktop app offers the assistant: a way to send HTTP requests and the system keychain. +//! +//! Context: `pcbcraft_ui_egui::Host` carries both into the window; the browser build passes +//! neither. Nothing here runs until the user presses Test or sends a message. +//! Rules: redirects are never followed (a redirect is an error, so a key cannot travel on); +//! replies are read up to [`MAX_REPLY`] bytes; error text never includes request headers. +//! Do not: log a request, a header or a key. + +use pcbcraft_assistant::{HttpFn, HttpRequest, Secrets}; +use std::io::Read; +use std::sync::Arc; +use std::time::Duration; + +/// Most bytes of a reply read. +const MAX_REPLY: u64 = 16 * 1024 * 1024; +/// The keychain service name. +const SERVICE: &str = "PCBCraft assistant"; + +/// The host the window gets. +pub fn host() -> pcbcraft_ui_egui::Host { + pcbcraft_ui_egui::Host { + http: Some(http()), + secrets: Some(Arc::new(Keychain)), + } +} + +fn http() -> HttpFn { + let agent = ureq::AgentBuilder::new().redirects(0).build(); + Arc::new(move |request: &HttpRequest| send(&agent, request)) +} + +fn send(agent: &ureq::Agent, request: &HttpRequest) -> Result<(u16, Vec), String> { + let mut call = agent + .request(request.method, &request.url) + .timeout(Duration::from_secs(request.timeout_s.max(1))); + for (name, value) in &request.headers { + call = call.set(name, value); + } + let reply = match &request.body { + Some(body) => call.send_bytes(body), + None => call.call(), + }; + let response = match reply { + Ok(r) => r, + Err(ureq::Error::Status(_, r)) => r, + Err(e) => return Err(transport_error(&e)), + }; + let status = response.status(); + let mut body = Vec::new(); + response + .into_reader() + .take(MAX_REPLY) + .read_to_end(&mut body) + .map_err(|e| e.to_string())?; + Ok((status, body)) +} + +/// A short sentence for a failure to reach the server. +fn transport_error(e: &ureq::Error) -> String { + match e { + ureq::Error::Transport(t) => match t.kind() { + ureq::ErrorKind::Dns => "The address could not be found.".into(), + ureq::ErrorKind::ConnectionFailed => "The server did not answer.".into(), + ureq::ErrorKind::Io => "The connection broke or timed out.".into(), + _ => "The request failed.".into(), + }, + ureq::Error::Status(code, _) => format!("The server answered {code}."), + } +} + +/// The system keychain, one entry per connection. +struct Keychain; + +impl Keychain { + fn entry(id: &str) -> Result { + keyring::Entry::new(SERVICE, id).map_err(|e| e.to_string()) + } +} + +impl Secrets for Keychain { + fn get(&self, id: &str) -> Result, String> { + match Self::entry(id)?.get_password() { + Ok(secret) => Ok(Some(secret)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(e.to_string()), + } + } + + fn set(&self, id: &str, secret: &str) -> Result<(), String> { + Self::entry(id)? + .set_password(secret) + .map_err(|e| e.to_string()) + } + + fn delete(&self, id: &str) -> Result<(), String> { + match Self::entry(id)?.delete_credential() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(e) => Err(e.to_string()), + } + } +} diff --git a/apps/pcbcraft/src/main.rs b/apps/pcbcraft/src/main.rs index 434a73c81..ad2ee889b 100644 --- a/apps/pcbcraft/src/main.rs +++ b/apps/pcbcraft/src/main.rs @@ -1,3 +1,8 @@ +mod host; +// The transport behind the Library tab's Online source. Its background read and +// cache purge helpers are for the settings page and are not called yet. +#[allow(dead_code)] +mod online_http; fn main() -> eframe::Result { let args: Vec<_> = std::env::args().skip(1).collect(); let option = |key: &str| { @@ -8,7 +13,7 @@ fn main() -> eframe::Result { }; if args.iter().any(|a| a == "--help" || a == "-h") { println!( - "PCBCraft — one-window Rust EDA\n\n--sample | --project FILE\n--control 127.0.0.1:7991\n--tab schematic|pcb|libraries|project-library|symbol-editor|footprint-editor|checks\n--light\n--capture /absolute/path.png" + "PCBCraft — one-window Rust EDA\n\n--sample | --project FILE\n--control 127.0.0.1:7991\n--size WxH\n--tab files|schematic|pcb|rules|settings|libraries|project-library|symbol-editor|footprint-editor|checks|3d\n--light\n--capture /absolute/path.png\n--select REFERENCE\n--search WORDS\n--place-first-online\n--left library|layers\n--context-menu\n--show file-export|export-dialog\n--menu tree-layer|tree-part|tree-net|library-card|finding|page-tab\n--sheet\n--target silk|edge\n--view3d top|front|side|bottom" ); return Ok(()); } @@ -23,6 +28,13 @@ fn main() -> eframe::Result { } else { pcbcraft_engine::Session::default() }; + if args.iter().any(|a| a == "--sample") { + // The demo board shows the default 45 degree corners. + let cut = serde_json::json!({"points":[[3.0,0.0],[57.0,0.0],[60.0,3.0],[60.0,37.0],[57.0,40.0],[3.0,40.0],[0.0,37.0],[0.0,3.0]]}); + if let Err(e) = session.execute("board.set_outline", cut, None) { + eprintln!("sample outline: {e}"); + } + } if let Some(path) = option("--project") { let result = pcbcraft_io::load(std::path::Path::new(&path)) .and_then(|project| session.replace(project).map_err(|e| e.to_string())); @@ -31,9 +43,22 @@ fn main() -> eframe::Result { std::process::exit(1); } } - let shared = pcbcraft_mcp::shared(session); + let hub = match pcbcraft_mcp::DocumentHub::new(session, option("--project")) { + Ok(h) => h, + Err(e) => { + eprintln!("documents: {e}"); + std::process::exit(1); + } + }; + let shared = match hub.active_session() { + Ok(s) => s, + Err(e) => { + eprintln!("documents: {e}"); + std::process::exit(1); + } + }; if let Some(address) = option("--control") - && let Err(e) = pcbcraft_mcp::start_bridge(shared.clone(), &address) + && let Err(e) = pcbcraft_mcp::start_bridge(hub.clone(), &address) { eprintln!("control bridge: {e}"); std::process::exit(1); @@ -42,8 +67,21 @@ fn main() -> eframe::Result { let tab = option("--tab"); let light = args.iter().any(|a| a == "--light"); let project_path = option("--project"); + let select = option("--select"); + let left = option("--left"); + let context_menu = args.iter().any(|a| a == "--context-menu"); + let menu_tag = option("--menu"); + let show = option("--show"); + let sheet = args.iter().any(|a| a == "--sheet"); + let target = option("--target"); + let search = option("--search"); + let view3d = option("--view3d"); + let place_first = args.iter().any(|a| a == "--place-first-online"); + let offline = std::sync::Arc::new(std::sync::atomic::AtomicBool::new( + args.iter().any(|a| a == "--offline"), + )); let options = eframe::NativeOptions { - viewport: egui_viewport(), + viewport: egui_viewport(option("--size").as_deref()), ..Default::default() }; eframe::run_native( @@ -52,13 +90,41 @@ fn main() -> eframe::Result { Box::new(move |cc| { Ok(Box::new( pcbcraft_ui_egui::App::new(cc, shared, capture, tab.as_deref(), light) - .with_project_path(project_path), + .with_project_path(project_path) + .with_capture_select(select) + .with_left_tab(left) + .with_capture_view(context_menu) + .with_capture_menu(menu_tag) + .with_capture_sheet(sheet) + .with_capture_show(show) + .with_capture_target(target) + .with_capture_search(search) + .with_capture_view3d(view3d) + .with_capture_place(place_first) + .with_online_fetcher( + Box::new(online_http::HttpFetcher::new( + online_http::Policy::default(), + offline.clone(), + )), + offline, + ) + .with_host(host::host()), )) }), ) } -fn egui_viewport() -> eframe::egui::ViewportBuilder { - eframe::egui::ViewportBuilder::default() - .with_inner_size([1440.0, 940.0]) +fn egui_viewport(size: Option<&str>) -> eframe::egui::ViewportBuilder { + let size = size + .and_then(|s| s.split_once('x')) + .and_then(|(w, h)| Some([w.parse::().ok()?, h.parse::().ok()?])) + .filter(|[w, h]| (400.0..=4000.0).contains(w) && (300.0..=3000.0).contains(h)) + .unwrap_or([1440.0, 940.0]); + let builder = eframe::egui::ViewportBuilder::default() + .with_inner_size(size) .with_min_inner_size([1000.0, 680.0]) + .with_app_id("io.github.tangency-labs.pcbcraft"); + match pcbcraft_ui_egui::brand::window_icon() { + Some(icon) => builder.with_icon(std::sync::Arc::new(icon)), + None => builder, + } } diff --git a/apps/pcbcraft/src/online_http.rs b/apps/pcbcraft/src/online_http.rs new file mode 100644 index 000000000..539a53580 --- /dev/null +++ b/apps/pcbcraft/src/online_http.rs @@ -0,0 +1,600 @@ +//! The desktop transport for online CAD sources: the [`Fetcher`] that the open +//! library source reads through. The library crate stays network-free; this +//! file is the only place that opens a socket for it. +//! +//! # Rules +//! - Plain GET over HTTPS to an allowlisted host. No cookies, no credentials, no user info in the URL. +//! - Every call carries a timeout, a response size cap and a User-Agent naming PCBCraft and its version. +//! - Redirects are followed by hand, at most [`MAX_REDIRECTS`] times, and only to the same host. +//! - Calls are spaced at least [`Policy::min_gap`] apart, so the hosts see a few requests per second at most. +//! - Offline mode answers before any socket is opened. +//! - `Fetcher::get` blocks. Call it from a worker thread; [`HttpFetcher::get_in_background`] does that for a caller on the UI thread. +//! +//! # Dependencies +//! - crates/library/src/open_library.rs +//! - crates/library/src/cad_cache.rs +//! - apps/pcbcraft/src/host.rs (same HTTP client, separate agent: no assistant keys travel here) + +use pcbcraft_library::cad::MAX_FILE_BYTES; +use pcbcraft_library::cad_cache::CadCache; +use pcbcraft_library::open_library::{FetchError, Fetcher}; +use std::io::Read; +use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// Hosts the open library source reads from. +pub const OPEN_LIBRARY_HOSTS: &[&str] = &["gitlab.com"]; +/// Most redirects followed for one call. +pub const MAX_REDIRECTS: usize = 3; + +/// The limits one transport works under. +/// +/// # Rules +/// - `allowed_hosts` is matched against the whole host name, never a suffix. +/// - `require_https` is on outside tests. +/// +/// # Dependencies +/// - crates/library/src/cad.rs (the size cap) +/// +/// # Do not +/// - Add a field that carries a credential. +#[derive(Clone, Debug)] +pub struct Policy { + /// Hosts a request may go to. + pub allowed_hosts: Vec, + /// Most body bytes read. + pub max_bytes: usize, + /// Time for the whole call, redirects included per hop. + pub timeout: Duration, + /// Time to open the connection. + pub connect_timeout: Duration, + /// Least time between two calls. + pub min_gap: Duration, + /// Refuse plain http. Tests switch this off to reach a loopback server. + pub require_https: bool, +} + +impl Default for Policy { + fn default() -> Self { + Self { + allowed_hosts: OPEN_LIBRARY_HOSTS.iter().map(|h| (*h).to_owned()).collect(), + max_bytes: MAX_FILE_BYTES, + timeout: Duration::from_secs(20), + connect_timeout: Duration::from_secs(8), + min_gap: Duration::from_millis(250), + require_https: true, + } + } +} + +/// The User-Agent every call sends. +pub fn user_agent() -> String { + format!( + "PCBCraft/{} (+https://github.com/tangency-labs/pcbcraft)", + env!("CARGO_PKG_VERSION") + ) +} + +/// The desktop [`Fetcher`]. +/// +/// # Rules +/// - The offline flag is shared with the settings toggle; flipping it takes effect on the next call. +/// +/// # Dependencies +/// - crates/library/src/open_library.rs +/// +/// # Do not +/// - Call `get` on the UI thread; use [`HttpFetcher::get_in_background`]. +/// +/// Contract: crates/library/src/open_library.rs +pub struct HttpFetcher { + agent: ureq::Agent, + policy: Policy, + offline: Arc, + last: Mutex>, +} + +impl HttpFetcher { + /// A transport under `policy`, switched off while `offline` is set. + pub fn new(policy: Policy, offline: Arc) -> Self { + let agent = ureq::AgentBuilder::new() + .redirects(0) + .timeout_connect(policy.connect_timeout) + .user_agent(&user_agent()) + .build(); + Self { + agent, + policy, + offline, + last: Mutex::new(None), + } + } + + /// Run `get` on its own thread and hand back the receiving end, so the + /// window keeps drawing while the answer travels. + pub fn get_in_background(self: &Arc, url: &str) -> Receiver, FetchError>> { + let (tx, rx) = channel(); + let me = Arc::clone(self); + let url = url.to_owned(); + std::thread::spawn(move || { + // A closed receiver only means nobody waits any more. + let _ = tx.send(me.get(&url)); + }); + rx + } + + fn pace(&self) { + let wait = match self.last.lock() { + Ok(mut last) => { + let now = Instant::now(); + let due = last.map(|t| t + self.policy.min_gap).unwrap_or(now); + *last = Some(due.max(now)); + due.saturating_duration_since(now) + } + Err(_) => Duration::ZERO, + }; + if !wait.is_zero() { + std::thread::sleep(wait); + } + } + + fn check(&self, parts: &Parts) -> Result<(), FetchError> { + if self.policy.require_https && parts.scheme != "https" { + return Err(FetchError::Failed( + "Only secure addresses are used for online libraries.".into(), + )); + } + if !self.policy.require_https && parts.scheme != "https" && parts.scheme != "http" { + return Err(FetchError::Failed( + "That address is not a web address.".into(), + )); + } + if !self.policy.allowed_hosts.iter().any(|h| h == &parts.host) { + return Err(FetchError::Failed(format!( + "{} is not one of the online library sites.", + parts.host + ))); + } + Ok(()) + } +} + +/// Contract: crates/library/src/open_library.rs +impl Fetcher for HttpFetcher { + fn get(&self, url: &str) -> Result, FetchError> { + if self.offline.load(Ordering::SeqCst) { + return Err(FetchError::Offline( + "Online libraries are switched off. Saved parts still open.".into(), + )); + } + let first = Parts::parse(url)?; + self.check(&first)?; + let mut current = url.to_owned(); + for _ in 0..=MAX_REDIRECTS { + self.pace(); + let reply = self.agent.get(¤t).timeout(self.policy.timeout).call(); + let response = match reply { + Ok(r) => r, + Err(ureq::Error::Status(_, r)) => r, + Err(e) => return Err(transport_error(&e)), + }; + let status = response.status(); + match status { + 200..=299 => return read_capped(response, self.policy.max_bytes), + 301 | 302 | 303 | 307 | 308 => { + let Some(location) = response.header("location") else { + return Err(FetchError::Failed("The host sent a bad redirect.".into())); + }; + let next = resolve(¤t, location)?; + let parts = Parts::parse(&next)?; + if parts.host != first.host { + return Err(FetchError::Failed( + "The host tried to send the request to another site, so it was stopped." + .into(), + )); + } + self.check(&parts)?; + current = next; + } + 404 | 410 => return Err(FetchError::NotFound), + 429 => { + let wait = response + .header("retry-after") + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(30); + return Err(FetchError::RateLimited { + retry_after_secs: wait.min(3600), + }); + } + other => { + return Err(FetchError::Failed(format!("The host answered {other}."))); + } + } + } + Err(FetchError::Failed( + "The host redirected too many times.".into(), + )) + } +} + +/// Read a body up to the cap; one byte more is a refusal. +fn read_capped(response: ureq::Response, max: usize) -> Result, FetchError> { + let too_big = + || FetchError::Failed("The file is larger than the size limit, so it was not read.".into()); + if let Some(len) = response + .header("content-length") + .and_then(|v| v.trim().parse::().ok()) + && len > max + { + return Err(too_big()); + } + let mut body = Vec::new(); + response + .into_reader() + .take(max as u64 + 1) + .read_to_end(&mut body) + .map_err(|e| io_error(&e))?; + if body.len() > max { + return Err(too_big()); + } + Ok(body) +} + +fn io_error(e: &std::io::Error) -> FetchError { + match e.kind() { + std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => { + FetchError::Failed("The host took too long to answer.".into()) + } + _ => FetchError::Failed("The connection broke before the answer arrived.".into()), + } +} + +fn transport_error(e: &ureq::Error) -> FetchError { + match e { + ureq::Error::Transport(t) => match t.kind() { + ureq::ErrorKind::Dns | ureq::ErrorKind::ConnectionFailed => { + FetchError::Offline("No connection to the online library.".into()) + } + ureq::ErrorKind::Io => FetchError::Failed("The host took too long to answer.".into()), + _ => FetchError::Failed("The request could not be sent.".into()), + }, + ureq::Error::Status(code, _) => FetchError::Failed(format!("The host answered {code}.")), + } +} + +/// Scheme, host and port of an address, with user info refused. +struct Parts { + scheme: String, + host: String, +} + +impl Parts { + fn parse(url: &str) -> Result { + let bad = || FetchError::Failed("That is not a valid web address.".into()); + let (scheme, rest) = url.split_once("://").ok_or_else(bad)?; + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + if authority.is_empty() || authority.contains('@') || url.contains(char::is_whitespace) { + return Err(bad()); + } + let host = match authority.rsplit_once(':') { + Some((h, port)) if port.chars().all(|c| c.is_ascii_digit()) => h, + _ => authority, + }; + Ok(Self { + scheme: scheme.to_ascii_lowercase(), + host: host.to_ascii_lowercase(), + }) + } +} + +/// Resolve a Location value against the address it came from. +fn resolve(base: &str, location: &str) -> Result { + if location.contains("://") { + return Ok(location.to_owned()); + } + let bad = || FetchError::Failed("The host sent a bad redirect.".into()); + let (scheme, rest) = base.split_once("://").ok_or_else(bad)?; + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + let path = location.strip_prefix('/').ok_or_else(bad)?; + Ok(format!("{scheme}://{authority}/{path}")) +} + +/// Empty the online cache: every stored file and listing under `dir`. +/// +/// # Rules +/// - Only the cache's own `files` and `listings` folders are removed. +/// +/// # Dependencies +/// - crates/library/src/cad_cache.rs +/// +/// # Do not +/// - Call it while an import is writing; the settings button disables itself during one. +pub fn purge_cache(dir: &Path) -> Result<(), FetchError> { + CadCache::open(dir) + .purge() + .map_err(|e| FetchError::Failed(format!("{e:?}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + use std::net::{TcpListener, TcpStream}; + use std::sync::atomic::AtomicUsize; + + type TestResult = Result<(), Box>; + + /// A loopback server that answers each connection with the next scripted reply. + struct Server { + port: u16, + seen: Arc>>, + connections: Arc, + } + + fn serve(replies: Vec>) -> Result> { + let listener = TcpListener::bind("127.0.0.1:0")?; + let port = listener.local_addr()?.port(); + let seen = Arc::new(Mutex::new(Vec::new())); + let connections = Arc::new(AtomicUsize::new(0)); + let (s, c) = (Arc::clone(&seen), Arc::clone(&connections)); + std::thread::spawn(move || { + for reply in replies { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + c.fetch_add(1, Ordering::SeqCst); + let request = read_request(&mut stream); + if let Ok(mut s) = s.lock() { + s.push(request); + } + if reply.is_empty() { + std::thread::sleep(Duration::from_secs(3)); + continue; + } + let _ = stream.write_all(&reply); + } + }); + Ok(Server { + port, + seen, + connections, + }) + } + + fn read_request(stream: &mut TcpStream) -> String { + let mut got = Vec::new(); + let mut buf = [0u8; 512]; + while !got.windows(4).any(|w| w == b"\r\n\r\n") { + match stream.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => got.extend_from_slice(&buf[..n]), + } + } + String::from_utf8_lossy(&got).into_owned() + } + + fn ok(body: &[u8]) -> Vec { + let mut r = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nSet-Cookie: a=b\r\nConnection: close\r\n\r\n", + body.len() + ) + .into_bytes(); + r.extend_from_slice(body); + r + } + + fn status(line: &str, headers: &str) -> Vec { + format!("HTTP/1.1 {line}\r\n{headers}Content-Length: 0\r\nConnection: close\r\n\r\n") + .into_bytes() + } + + fn local(max_bytes: usize) -> (HttpFetcher, Arc) { + let offline = Arc::new(AtomicBool::new(false)); + let policy = Policy { + allowed_hosts: vec!["127.0.0.1".into()], + max_bytes, + timeout: Duration::from_millis(600), + min_gap: Duration::ZERO, + require_https: false, + ..Policy::default() + }; + (HttpFetcher::new(policy, Arc::clone(&offline)), offline) + } + + fn got(f: &HttpFetcher, u: &str) -> Result, String> { + f.get(u).map_err(|e| format!("{e:?}")) + } + + fn url(s: &Server, path: &str) -> String { + format!("http://127.0.0.1:{}{path}", s.port) + } + + #[test] + fn the_request_names_the_app_and_sends_no_cookie_or_credential() -> TestResult { + let server = serve(vec![ok(b"one"), ok(b"two")])?; + let (fetcher, _) = local(1024); + assert_eq!(got(&fetcher, &url(&server, "/a"))?, b"one"); + assert_eq!(got(&fetcher, &url(&server, "/b"))?, b"two"); + let seen = server.seen.lock().map_err(|_| "poisoned")?; + let first = seen.first().ok_or("no request")?.to_ascii_lowercase(); + assert!(first.contains(&format!( + "user-agent: {}", + user_agent().to_ascii_lowercase() + ))); + assert!(user_agent().starts_with("PCBCraft/")); + for request in seen.iter() { + let lower = request.to_ascii_lowercase(); + assert!(!lower.contains("cookie:") && !lower.contains("authorization:")); + } + Ok(()) + } + + #[test] + fn the_transport_refuses_an_oversized_body() -> TestResult { + let server = serve(vec![ok(&[7u8; 64]), { + // No length header: the cap must hold while streaming. + let mut r = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".to_vec(); + r.extend_from_slice(&[7u8; 64]); + r + }])?; + let (fetcher, _) = local(16); + for _ in 0..2 { + let err = fetcher.get(&url(&server, "/big")).err(); + assert!( + matches!(&err, Some(FetchError::Failed(m)) if m.contains("size limit")), + "{err:?}" + ); + } + Ok(()) + } + + #[test] + fn offline_mode_opens_no_connection() -> TestResult { + let server = serve(vec![ok(b"x")])?; + let (fetcher, offline) = local(1024); + offline.store(true, Ordering::SeqCst); + let err = fetcher.get(&url(&server, "/a")).err(); + assert!(matches!(err, Some(FetchError::Offline(_)))); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(server.connections.load(Ordering::SeqCst), 0); + offline.store(false, Ordering::SeqCst); + assert_eq!(got(&fetcher, &url(&server, "/a"))?, b"x"); + Ok(()) + } + + #[test] + fn redirects_to_another_host_are_refused() -> TestResult { + let away = status("302 Found", "Location: http://localhost:9/steal\r\n"); + let server = serve(vec![away])?; + let (fetcher, _) = local(1024); + let err = fetcher.get(&url(&server, "/a")).err(); + assert!( + matches!(&err, Some(FetchError::Failed(m)) if m.contains("another site")), + "{err:?}" + ); + Ok(()) + } + + #[test] + fn a_redirect_on_the_same_host_is_followed() -> TestResult { + let hop = status("301 Moved Permanently", "Location: /moved\r\n"); + let server = serve(vec![hop, ok(b"there")])?; + let (fetcher, _) = local(1024); + assert_eq!(got(&fetcher, &url(&server, "/a"))?, b"there"); + Ok(()) + } + + #[test] + fn a_host_off_the_list_is_refused_before_any_socket() -> TestResult { + let (fetcher, _) = local(1024); + let err = fetcher.get("http://example.com/a").err(); + assert!(matches!(&err, Some(FetchError::Failed(m)) if m.contains("not one of"))); + let err = fetcher.get("http://user:pw@127.0.0.1/a").err(); + assert!(matches!(err, Some(FetchError::Failed(_)))); + let strict = HttpFetcher::new(Policy::default(), Arc::new(AtomicBool::new(false))); + let err = strict.get("http://gitlab.com/a").err(); + assert!(matches!(&err, Some(FetchError::Failed(m)) if m.contains("secure"))); + Ok(()) + } + + #[test] + fn statuses_map_to_plain_errors() -> TestResult { + let server = serve(vec![ + status("404 Not Found", ""), + status("429 Too Many Requests", "Retry-After: 7\r\n"), + status("500 Internal Server Error", ""), + ])?; + let (fetcher, _) = local(1024); + assert_eq!( + fetcher.get(&url(&server, "/a")).err(), + Some(FetchError::NotFound) + ); + assert_eq!( + fetcher.get(&url(&server, "/b")).err(), + Some(FetchError::RateLimited { + retry_after_secs: 7 + }) + ); + assert!( + matches!(fetcher.get(&url(&server, "/c")).err(), Some(FetchError::Failed(m)) if m.contains("500")) + ); + Ok(()) + } + + #[test] + fn a_silent_host_times_out() -> TestResult { + let server = serve(vec![Vec::new()])?; + let (fetcher, _) = local(1024); + let started = Instant::now(); + let err = fetcher.get(&url(&server, "/a")).err(); + assert!(matches!(err, Some(FetchError::Failed(_))), "{err:?}"); + assert!(started.elapsed() < Duration::from_secs(3)); + Ok(()) + } + + #[test] + fn the_background_call_runs_off_the_calling_thread() -> TestResult { + let server = serve(vec![ok(b"bg")])?; + let (fetcher, _) = local(1024); + let rx = Arc::new(fetcher).get_in_background(&url(&server, "/a")); + let body = rx + .recv_timeout(Duration::from_secs(5))? + .map_err(|e| format!("{e:?}"))?; + assert_eq!(body, b"bg"); + Ok(()) + } + + #[test] + fn calls_are_spaced_by_the_minimum_gap() -> TestResult { + let server = serve(vec![ok(b"1"), ok(b"2"), ok(b"3")])?; + let policy = Policy { + allowed_hosts: vec!["127.0.0.1".into()], + min_gap: Duration::from_millis(150), + require_https: false, + ..Policy::default() + }; + let fetcher = HttpFetcher::new(policy, Arc::new(AtomicBool::new(false))); + let started = Instant::now(); + for p in ["/a", "/b", "/c"] { + got(&fetcher, &url(&server, p))?; + } + assert!(started.elapsed() >= Duration::from_millis(300)); + Ok(()) + } + + #[test] + fn purge_empties_the_cache_directory() -> TestResult { + let dir = tempfile::tempdir()?; + let cache = CadCache::open(dir.path()); + cache.put("open-library", "symbols/Device.kicad_sym", None, b"data")?; + assert!(cache.disk_bytes() > 0); + purge_cache(dir.path()).map_err(|e| format!("{e:?}"))?; + assert_eq!(CadCache::open(dir.path()).disk_bytes(), 0); + assert!(!dir.path().join("files").exists()); + Ok(()) + } + + /// Manual check against the real host; run by hand, never in CI: + /// `cargo test -p pcbcraft live_ -- --ignored --nocapture`. + #[test] + #[ignore = "reaches the live open library host"] + fn live_search_a_resistor_and_fetch_one_symbol() -> TestResult { + use pcbcraft_library::cad::{CadKind, CadSource}; + use pcbcraft_library::open_library::OpenLibrarySource; + let dir = tempfile::tempdir()?; + let fetcher = HttpFetcher::new(Policy::default(), Arc::new(AtomicBool::new(false))); + let source = OpenLibrarySource::new(Box::new(fetcher), CadCache::open(dir.path())); + let found = source + .search(CadKind::Symbol, "resistor") + .map_err(|e| format!("{e:?}"))?; + println!("found {} symbols, first: {:?}", found.len(), found.first()); + let first = found.first().ok_or("no results")?; + let file = source.fetch(first).map_err(|e| format!("{e:?}"))?; + println!("fetched {} bytes", file.bytes.len()); + assert!(!file.bytes.is_empty()); + Ok(()) + } +} diff --git a/assets/brand/build.sh b/assets/brand/build.sh new file mode 100755 index 000000000..6fc3229d3 --- /dev/null +++ b/assets/brand/build.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Regenerate the brand masters and every platform icon (#687). +# Runs tools/build.py in a Python container with librsvg, fontTools and Pillow, +# so it behaves the same on a workstation, on the build host and in CI. +# Usage: assets/brand/build.sh (needs docker; PYTHON_IMAGE overrides the image) +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +IMAGE="${PYTHON_IMAGE:-python:3.11-slim}" +docker run --rm -v "$ROOT":/w -w /w "$IMAGE" bash -c ' + set -e + apt-get update -qq >/dev/null + apt-get install -y -qq librsvg2-bin >/dev/null + pip install -q fonttools pillow 2>&1 | grep -v notice || true + python3 assets/brand/tools/build.py + chown -R '"$(id -u):$(id -g)"' assets/brand +' diff --git a/assets/brand/fonts/IBMPlexSans-Variable.ttf b/assets/brand/fonts/IBMPlexSans-Variable.ttf new file mode 100644 index 000000000..30f837e8b Binary files /dev/null and b/assets/brand/fonts/IBMPlexSans-Variable.ttf differ diff --git a/assets/brand/fonts/OFL.txt b/assets/brand/fonts/OFL.txt new file mode 100644 index 000000000..c35c4c618 --- /dev/null +++ b/assets/brand/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright © 2017 IBM Corp. with Reserved Font Name "Plex" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/brand/generated/linux/hicolor/128x128/apps/io.github.tangency-labs.pcbcraft.png b/assets/brand/generated/linux/hicolor/128x128/apps/io.github.tangency-labs.pcbcraft.png new file mode 100644 index 000000000..769cb1728 Binary files /dev/null and b/assets/brand/generated/linux/hicolor/128x128/apps/io.github.tangency-labs.pcbcraft.png differ diff --git a/assets/brand/generated/linux/hicolor/16x16/apps/io.github.tangency-labs.pcbcraft.png b/assets/brand/generated/linux/hicolor/16x16/apps/io.github.tangency-labs.pcbcraft.png new file mode 100644 index 000000000..3ac598569 Binary files /dev/null and b/assets/brand/generated/linux/hicolor/16x16/apps/io.github.tangency-labs.pcbcraft.png differ diff --git a/assets/brand/generated/linux/hicolor/24x24/apps/io.github.tangency-labs.pcbcraft.png b/assets/brand/generated/linux/hicolor/24x24/apps/io.github.tangency-labs.pcbcraft.png new file mode 100644 index 000000000..23f8cb478 Binary files /dev/null and b/assets/brand/generated/linux/hicolor/24x24/apps/io.github.tangency-labs.pcbcraft.png differ diff --git a/assets/brand/generated/linux/hicolor/256x256/apps/io.github.tangency-labs.pcbcraft.png b/assets/brand/generated/linux/hicolor/256x256/apps/io.github.tangency-labs.pcbcraft.png new file mode 100644 index 000000000..7145a9583 Binary files /dev/null and b/assets/brand/generated/linux/hicolor/256x256/apps/io.github.tangency-labs.pcbcraft.png differ diff --git a/assets/brand/generated/linux/hicolor/32x32/apps/io.github.tangency-labs.pcbcraft.png b/assets/brand/generated/linux/hicolor/32x32/apps/io.github.tangency-labs.pcbcraft.png new file mode 100644 index 000000000..9dbde16a3 Binary files /dev/null and b/assets/brand/generated/linux/hicolor/32x32/apps/io.github.tangency-labs.pcbcraft.png differ diff --git a/assets/brand/generated/linux/hicolor/48x48/apps/io.github.tangency-labs.pcbcraft.png b/assets/brand/generated/linux/hicolor/48x48/apps/io.github.tangency-labs.pcbcraft.png new file mode 100644 index 000000000..169cd1f2d Binary files /dev/null and b/assets/brand/generated/linux/hicolor/48x48/apps/io.github.tangency-labs.pcbcraft.png differ diff --git a/assets/brand/generated/linux/hicolor/512x512/apps/io.github.tangency-labs.pcbcraft.png b/assets/brand/generated/linux/hicolor/512x512/apps/io.github.tangency-labs.pcbcraft.png new file mode 100644 index 000000000..1b73c8d1e Binary files /dev/null and b/assets/brand/generated/linux/hicolor/512x512/apps/io.github.tangency-labs.pcbcraft.png differ diff --git a/assets/brand/generated/linux/hicolor/64x64/apps/io.github.tangency-labs.pcbcraft.png b/assets/brand/generated/linux/hicolor/64x64/apps/io.github.tangency-labs.pcbcraft.png new file mode 100644 index 000000000..9a6dd56b6 Binary files /dev/null and b/assets/brand/generated/linux/hicolor/64x64/apps/io.github.tangency-labs.pcbcraft.png differ diff --git a/assets/brand/generated/linux/hicolor/scalable/apps/io.github.tangency-labs.pcbcraft.svg b/assets/brand/generated/linux/hicolor/scalable/apps/io.github.tangency-labs.pcbcraft.svg new file mode 100644 index 000000000..b0e58bb35 --- /dev/null +++ b/assets/brand/generated/linux/hicolor/scalable/apps/io.github.tangency-labs.pcbcraft.svg @@ -0,0 +1,5 @@ + + +PCBCraft app icon + + diff --git a/assets/brand/generated/macos/pcbcraft.icns b/assets/brand/generated/macos/pcbcraft.icns new file mode 100644 index 000000000..c04b0ecbc Binary files /dev/null and b/assets/brand/generated/macos/pcbcraft.icns differ diff --git a/assets/brand/generated/preview/icon-128.png b/assets/brand/generated/preview/icon-128.png new file mode 100644 index 000000000..769cb1728 Binary files /dev/null and b/assets/brand/generated/preview/icon-128.png differ diff --git a/assets/brand/generated/preview/icon-16.png b/assets/brand/generated/preview/icon-16.png new file mode 100644 index 000000000..3ac598569 Binary files /dev/null and b/assets/brand/generated/preview/icon-16.png differ diff --git a/assets/brand/generated/preview/icon-32.png b/assets/brand/generated/preview/icon-32.png new file mode 100644 index 000000000..9dbde16a3 Binary files /dev/null and b/assets/brand/generated/preview/icon-32.png differ diff --git a/assets/brand/generated/preview/icon-512.png b/assets/brand/generated/preview/icon-512.png new file mode 100644 index 000000000..1b73c8d1e Binary files /dev/null and b/assets/brand/generated/preview/icon-512.png differ diff --git a/assets/brand/generated/preview/pcbcraft-icon.png b/assets/brand/generated/preview/pcbcraft-icon.png new file mode 100644 index 000000000..1b73c8d1e Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-icon.png differ diff --git a/assets/brand/generated/preview/pcbcraft-logo-dark.png b/assets/brand/generated/preview/pcbcraft-logo-dark.png new file mode 100644 index 000000000..7d121660f Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-logo-dark.png differ diff --git a/assets/brand/generated/preview/pcbcraft-logo-light.png b/assets/brand/generated/preview/pcbcraft-logo-light.png new file mode 100644 index 000000000..84684a4c1 Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-logo-light.png differ diff --git a/assets/brand/generated/preview/pcbcraft-logo-mono.png b/assets/brand/generated/preview/pcbcraft-logo-mono.png new file mode 100644 index 000000000..f67baea97 Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-logo-mono.png differ diff --git a/assets/brand/generated/preview/pcbcraft-mark-dark.png b/assets/brand/generated/preview/pcbcraft-mark-dark.png new file mode 100644 index 000000000..d9274a495 Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-mark-dark.png differ diff --git a/assets/brand/generated/preview/pcbcraft-mark-light.png b/assets/brand/generated/preview/pcbcraft-mark-light.png new file mode 100644 index 000000000..e562a1730 Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-mark-light.png differ diff --git a/assets/brand/generated/preview/pcbcraft-mark-mono.png b/assets/brand/generated/preview/pcbcraft-mark-mono.png new file mode 100644 index 000000000..c65ac3c61 Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-mark-mono.png differ diff --git a/assets/brand/generated/preview/pcbcraft-wordmark-dark.png b/assets/brand/generated/preview/pcbcraft-wordmark-dark.png new file mode 100644 index 000000000..8e449049e Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-wordmark-dark.png differ diff --git a/assets/brand/generated/preview/pcbcraft-wordmark-light.png b/assets/brand/generated/preview/pcbcraft-wordmark-light.png new file mode 100644 index 000000000..19a31e937 Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-wordmark-light.png differ diff --git a/assets/brand/generated/preview/pcbcraft-wordmark-mono.png b/assets/brand/generated/preview/pcbcraft-wordmark-mono.png new file mode 100644 index 000000000..141ed4840 Binary files /dev/null and b/assets/brand/generated/preview/pcbcraft-wordmark-mono.png differ diff --git a/assets/brand/generated/preview/sizes-sheet.png b/assets/brand/generated/preview/sizes-sheet.png new file mode 100644 index 000000000..44886217e Binary files /dev/null and b/assets/brand/generated/preview/sizes-sheet.png differ diff --git a/assets/brand/generated/preview/zoom-16.png b/assets/brand/generated/preview/zoom-16.png new file mode 100644 index 000000000..badd8c537 Binary files /dev/null and b/assets/brand/generated/preview/zoom-16.png differ diff --git a/assets/brand/generated/preview/zoom-32.png b/assets/brand/generated/preview/zoom-32.png new file mode 100644 index 000000000..444240343 Binary files /dev/null and b/assets/brand/generated/preview/zoom-32.png differ diff --git a/assets/brand/generated/web/apple-touch-icon.png b/assets/brand/generated/web/apple-touch-icon.png new file mode 100644 index 000000000..083f18336 Binary files /dev/null and b/assets/brand/generated/web/apple-touch-icon.png differ diff --git a/assets/brand/generated/web/favicon.ico b/assets/brand/generated/web/favicon.ico new file mode 100644 index 000000000..0a96ac453 Binary files /dev/null and b/assets/brand/generated/web/favicon.ico differ diff --git a/assets/brand/generated/web/favicon.svg b/assets/brand/generated/web/favicon.svg new file mode 100644 index 000000000..fdae53847 --- /dev/null +++ b/assets/brand/generated/web/favicon.svg @@ -0,0 +1,5 @@ + + +PCBCraft app icon, 16 px version + + diff --git a/assets/brand/generated/web/icon-192.png b/assets/brand/generated/web/icon-192.png new file mode 100644 index 000000000..b551affcb Binary files /dev/null and b/assets/brand/generated/web/icon-192.png differ diff --git a/assets/brand/generated/web/icon-512.png b/assets/brand/generated/web/icon-512.png new file mode 100644 index 000000000..1b73c8d1e Binary files /dev/null and b/assets/brand/generated/web/icon-512.png differ diff --git a/assets/brand/generated/web/icon-maskable-512.png b/assets/brand/generated/web/icon-maskable-512.png new file mode 100644 index 000000000..f060542aa Binary files /dev/null and b/assets/brand/generated/web/icon-maskable-512.png differ diff --git a/assets/brand/generated/web/icon-monochrome-512.png b/assets/brand/generated/web/icon-monochrome-512.png new file mode 100644 index 000000000..4d163cdeb Binary files /dev/null and b/assets/brand/generated/web/icon-monochrome-512.png differ diff --git a/assets/brand/generated/web/manifest.webmanifest b/assets/brand/generated/web/manifest.webmanifest new file mode 100644 index 000000000..8f02934b3 --- /dev/null +++ b/assets/brand/generated/web/manifest.webmanifest @@ -0,0 +1,35 @@ +{ + "name": "PCBCraft", + "short_name": "PCBCraft", + "description": "Schematic capture, PCB layout and design checks in the browser.", + "start_url": ".", + "display": "standalone", + "theme_color": "#0b1a16", + "background_color": "#0b1a16", + "icons": [ + { + "src": "icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any" + }, + { + "src": "icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any" + }, + { + "src": "icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icon-monochrome-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "monochrome" + } + ] +} diff --git a/assets/brand/generated/windows/pcbcraft.ico b/assets/brand/generated/windows/pcbcraft.ico new file mode 100644 index 000000000..a215f346a Binary files /dev/null and b/assets/brand/generated/windows/pcbcraft.ico differ diff --git a/assets/brand/pcbcraft-icon-16.svg b/assets/brand/pcbcraft-icon-16.svg new file mode 100644 index 000000000..fdae53847 --- /dev/null +++ b/assets/brand/pcbcraft-icon-16.svg @@ -0,0 +1,5 @@ + + +PCBCraft app icon, 16 px version + + diff --git a/assets/brand/pcbcraft-icon-32.svg b/assets/brand/pcbcraft-icon-32.svg new file mode 100644 index 000000000..030610017 --- /dev/null +++ b/assets/brand/pcbcraft-icon-32.svg @@ -0,0 +1,5 @@ + + +PCBCraft app icon, 32 px version + + diff --git a/assets/brand/pcbcraft-icon.svg b/assets/brand/pcbcraft-icon.svg new file mode 100644 index 000000000..b0e58bb35 --- /dev/null +++ b/assets/brand/pcbcraft-icon.svg @@ -0,0 +1,5 @@ + + +PCBCraft app icon + + diff --git a/assets/brand/pcbcraft-logo-dark.svg b/assets/brand/pcbcraft-logo-dark.svg new file mode 100644 index 000000000..325c01106 --- /dev/null +++ b/assets/brand/pcbcraft-logo-dark.svg @@ -0,0 +1,5 @@ + + +PCBCraft logo, for dark backgrounds + + diff --git a/assets/brand/pcbcraft-logo-light.svg b/assets/brand/pcbcraft-logo-light.svg new file mode 100644 index 000000000..09513f2e7 --- /dev/null +++ b/assets/brand/pcbcraft-logo-light.svg @@ -0,0 +1,5 @@ + + +PCBCraft logo, for light backgrounds + + diff --git a/assets/brand/pcbcraft-logo-mono.svg b/assets/brand/pcbcraft-logo-mono.svg new file mode 100644 index 000000000..60fb855ea --- /dev/null +++ b/assets/brand/pcbcraft-logo-mono.svg @@ -0,0 +1,5 @@ + + +PCBCraft logo, one colour + + diff --git a/assets/brand/pcbcraft-mark-dark.svg b/assets/brand/pcbcraft-mark-dark.svg new file mode 100644 index 000000000..77b015e75 --- /dev/null +++ b/assets/brand/pcbcraft-mark-dark.svg @@ -0,0 +1,5 @@ + + +PCBCraft mark, for dark backgrounds + + diff --git a/assets/brand/pcbcraft-mark-light.svg b/assets/brand/pcbcraft-mark-light.svg new file mode 100644 index 000000000..f2e253977 --- /dev/null +++ b/assets/brand/pcbcraft-mark-light.svg @@ -0,0 +1,5 @@ + + +PCBCraft mark, for light backgrounds + + diff --git a/assets/brand/pcbcraft-mark-mono.svg b/assets/brand/pcbcraft-mark-mono.svg new file mode 100644 index 000000000..47d54f406 --- /dev/null +++ b/assets/brand/pcbcraft-mark-mono.svg @@ -0,0 +1,5 @@ + + +PCBCraft mark, one colour + + diff --git a/assets/brand/pcbcraft-wordmark-dark.svg b/assets/brand/pcbcraft-wordmark-dark.svg new file mode 100644 index 000000000..fa7f4bbbd --- /dev/null +++ b/assets/brand/pcbcraft-wordmark-dark.svg @@ -0,0 +1,5 @@ + + +PCBCraft wordmark, for dark backgrounds + + diff --git a/assets/brand/pcbcraft-wordmark-light.svg b/assets/brand/pcbcraft-wordmark-light.svg new file mode 100644 index 000000000..a10275bec --- /dev/null +++ b/assets/brand/pcbcraft-wordmark-light.svg @@ -0,0 +1,5 @@ + + +PCBCraft wordmark, for light backgrounds + + diff --git a/assets/brand/pcbcraft-wordmark-mono.svg b/assets/brand/pcbcraft-wordmark-mono.svg new file mode 100644 index 000000000..48a41f248 --- /dev/null +++ b/assets/brand/pcbcraft-wordmark-mono.svg @@ -0,0 +1,5 @@ + + +PCBCraft wordmark, one colour + + diff --git a/assets/brand/tools/build.py b/assets/brand/tools/build.py new file mode 100644 index 000000000..8b3e5dd75 --- /dev/null +++ b/assets/brand/tools/build.py @@ -0,0 +1,395 @@ +#!/usr/bin/env python3 +"""Build the PCBCraft brand masters and every platform icon. + +Run through `assets/brand/build.sh`, which provides rsvg-convert, fontTools and +Pillow in a container. Output is deterministic: the same script gives the same +files, and the files are committed so a normal build needs no rasteriser. + +Mark: concept 2, Layer stack (#686), finished in #687. Three offset plates +(solder mask green, copper, silkscreen) with a pin-1 chamfer, and a via drilled +through the stack so each plate shows a ring of the plate below it. + +Masters are written to assets/brand/. Platform icons and previews are written +to assets/brand/generated/. Wordmark: IBM Plex Sans SemiBold, SIL OFL 1.1, +outlined to paths from assets/brand/fonts/IBMPlexSans-Variable.ttf. +""" +import os +import shutil +import struct +import subprocess +import sys +import json + +HERE = os.path.dirname(os.path.abspath(__file__)) +BRAND = os.path.dirname(HERE) +GEN = os.path.join(BRAND, "generated") +APP_ID = "io.github.tangency-labs.pcbcraft" + +# Palette. Dark-page values and light-page values per #686 section 2. +TILE = "#0b1a16" +DARK = dict(green="#1f7a5f", copper="#d98e4f", top="#f1eee4", text="#f1eee4") +LIGHT = dict(green="#14503f", copper="#a8571f", top="#1b2a25", text="#1b2a25") +MONO = dict(green="#000", copper="#000", top="#000", text="#000") + +# Mark geometry in a 392 x 392 box (plate, offset, chamfer, via centre). +BOX = 392 +GEOM_FULL = dict(s=264, d=64, c=72, cx=196, cy=196, box=392) +# 32 px grid: whole-pixel plates, 3 px visible strips. +GEOM_32 = dict(s=16, d=4, c=4, cx=14, cy=10, box=24) +# 16 px grid: whole-pixel plates, 2 px visible strips. +GEOM_16 = dict(s=8, d=3, c=2, cx=9, cy=5, box=14) + + +def n(v): + s = ("%.2f" % v).rstrip("0").rstrip(".") + return s if s != "-0" else "0" + + +def plate_origin(g, k): + return g["d"] * k, g["box"] - g["s"] - g["d"] * k + + +def plate_d(g, k): + """Chamfered square (pin-1 corner top left) for plate k, 0 bottom.""" + x, y = plate_origin(g, k) + s, c = g["s"], g["c"] + return "M%s %sL%s %sH%sV%sH%sZ" % (n(x), n(y + c), n(x + c), n(y), n(x + s), n(y + s), n(x)) + + +def via_centre(g): + """Via position: inside the top plate, over the copper plate.""" + return g["cx"], g["cy"] + + +def circle_d(cx, cy, r): + return "M%s %sa%s %s 0 1 0 %s 0a%s %s 0 1 0 %s 0Z" % ( + n(cx - r), n(cy), n(r), n(r), n(2 * r), n(r), n(r), n(-2 * r)) + + +def mark_body(g, pal, gap, holes, hole_gap, uid): + """SVG elements for the mark in the box 0..g["box"], no wrapper. + + holes: radii of the via hole in plates (bottom, middle, top); None for none. + gap: transparent gap left around every upper plate. hole_gap: same around + the hole edges. Gaps are cut with masks, so the mark has no background. + """ + cx, cy = via_centre(g) + cols = [pal["green"], pal["copper"], pal["top"]] + defs, body = [], [] + for k in range(3): + d = plate_d(g, k) + if holes[k]: + d += circle_d(cx, cy, holes[k]) + cuts = [] + for j in range(k + 1, 3): + outline = plate_d(g, j) + cut = '' % ( + outline, n(2 * gap)) + if holes[j]: + # Keep the hole open for the plate below, with its own gap. + cut = ('' + '' % ( + outline, n(2 * gap), outline + circle_d(cx, cy, holes[j]))) + if hole_gap: + cut += '' % ( + n(cx), n(cy), n(holes[j]), n(2 * hole_gap)) + cuts.append(cut) + attrs = 'd="%s" fill="%s"' % (d, cols[k]) + if holes[k]: + attrs += ' fill-rule="evenodd"' + if cuts: + mid = "%s-m%d" % (uid, k) + defs.append( + '' + '%s' % ( + mid, n(g["box"] + 16), n(g["box"] + 16), n(g["box"] + 16), n(g["box"] + 16), "".join(cuts))) + attrs += ' mask="url(#%s)"' % mid + body.append("" % attrs) + return "%s%s" % ("".join(defs), "".join(body)) + + +# Variants: (geometry, gap, holes bottom/middle/top, hole gap) +FULL_COLOUR = (GEOM_FULL, 8, (12, 30, 52), 8) +FULL_MONO = (GEOM_FULL, 16, (None, None, 64), 16) +SMALL_32 = (GEOM_32, 1, (None, None, 3.5), 1) +SMALL_16 = (GEOM_16, 1, (None, None, 1.2), 0) + + +def mark(pal, variant, uid): + g, gap, holes, hg = variant + return mark_body(g, pal, gap, holes, hg, uid) + + +def svg(w, h, view, inner, title, extra=""): + return ('\n' + '\n%s\n%s\n\n') % (n(w), n(h), view, title, extra, title, inner) + + +def tile_icon(variant, size, radius, scale=1.0, uid="i"): + """Icon with the dark tile. size is the canvas, scale shrinks the mark.""" + g = variant[0] + k = size / 512.0 if g is GEOM_FULL else size / (32.0 if g is GEOM_32 else 16.0) + mark_px = g["box"] * k * scale if g is not GEOM_FULL else 392 * k * scale + off = (size - mark_px) / 2.0 + tile = '' % (n(size), n(size), n(radius), TILE) + unit = mark_px / g["box"] + inner = tile + '%s' % ( + n(off), n(off), n(unit), mark(DARK, variant, uid)) + return inner + + +# ---- wordmark ------------------------------------------------------------- + +def outline_wordmark(): + from fontTools.ttLib import TTFont + from fontTools.varLib import instancer + from fontTools.pens.svgPathPen import SVGPathPen + from fontTools.pens.transformPen import TransformPen + + font = TTFont(os.path.join(BRAND, "fonts", "IBMPlexSans-Variable.ttf")) + font = instancer.instantiateVariableFont(font, {"wght": 600}, inplace=False) + upm = font["head"].unitsPerEm + cmap = font.getBestCmap() + gs = font.getGlyphSet() + hmtx = font["hmtx"] + cap = font["OS/2"].sCapHeight + # Cap height 150 units against the 392 unit mark. + scale = 150.0 / cap + + def run(text, x): + out = [] + for ch in text: + gn = cmap[ord(ch)] + pen = SVGPathPen(gs, ntos=lambda v: n(v)) + tp = TransformPen(pen, (scale, 0, 0, -scale, x, 0)) + gs[gn].draw(tp) + out.append(pen.getCommands()) + x += hmtx[gn][0] * scale + return " ".join(out), x + + pcb, x = run("PCB", 0) + craft, x = run("Craft", x) + return pcb, craft, x, cap * scale + + +def wordmark_svg(pal, parts, uid): + pcb, craft, width, cap = parts + copper = pal["copper"] if pal is not MONO else "#000" + return ('' % (pcb, pal["text"], craft, copper)), width, cap + + +def write(path, text): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + + +def render(src, dst, size): + os.makedirs(os.path.dirname(dst), exist_ok=True) + subprocess.run(["rsvg-convert", "-w", str(size), "-h", str(size), src, "-o", dst], check=True) + + +def render_w(src, dst, width): + os.makedirs(os.path.dirname(dst), exist_ok=True) + subprocess.run(["rsvg-convert", "-w", str(width), src, "-o", dst], check=True) + + +def png_size(path): + with open(path, "rb") as f: + head = f.read(24) + return struct.unpack(">II", head[16:24]) + + +def make_ico(pngs, dst): + data = [open(p, "rb").read() for p in pngs] + out = struct.pack("= 256 else w, 0 if h >= 256 else h, 0, 0, 1, 32, len(d), offset) + offset += len(d) + with open(dst, "wb") as f: + f.write(out + entries + b"".join(data)) + + +def make_icns(entries, dst): + body = b"" + for typ, p in entries: + d = open(p, "rb").read() + body += typ.encode() + struct.pack(">I", len(d) + 8) + d + with open(dst, "wb") as f: + f.write(b"icns" + struct.pack(">I", len(body) + 8) + body) + + +def main(): + parts = outline_wordmark() + + # --- masters --------------------------------------------------------- + m = {} + m["pcbcraft-icon.svg"] = svg(512, 512, "0 0 512 512", tile_icon(FULL_COLOUR, 512, 96, uid="a"), + "PCBCraft app icon") + m["pcbcraft-icon-32.svg"] = svg(32, 32, "0 0 32 32", tile_icon(SMALL_32, 32, 6, uid="b"), + "PCBCraft app icon, 32 px version") + m["pcbcraft-icon-16.svg"] = svg(16, 16, "0 0 16 16", tile_icon(SMALL_16, 16, 3, uid="c"), + "PCBCraft app icon, 16 px version") + for name, pal, label in (("dark", DARK, "for dark backgrounds"), ("light", LIGHT, "for light backgrounds")): + m["pcbcraft-mark-%s.svg" % name] = svg(392, 392, "0 0 392 392", mark(pal, FULL_COLOUR, "m" + name), + "PCBCraft mark, %s" % label) + m["pcbcraft-mark-mono.svg"] = svg(392, 392, "0 0 392 392", mark(MONO, FULL_MONO, "mm"), + "PCBCraft mark, one colour") + + for name, pal, vr, label in (("dark", DARK, FULL_COLOUR, "for dark backgrounds"), + ("light", LIGHT, FULL_COLOUR, "for light backgrounds"), + ("mono", MONO, FULL_MONO, "one colour")): + word, width, cap = wordmark_svg(pal, parts, name) + # Wordmark alone: baseline at y = cap, so the box is the cap height. + pad = 0 + m["pcbcraft-wordmark-%s.svg" % name] = svg( + width, cap, "0 0 %s %s" % (n(width), n(cap)), + '%s' % (n(cap), word), "PCBCraft wordmark, %s" % label) + gapx = 56 + total = 392 + gapx + width + base = 196 + cap / 2.0 + lock = (mark(pal, vr, "l" + name) + + '%s' % (n(392 + gapx), n(base), word)) + m["pcbcraft-logo-%s.svg" % name] = svg(total, 392, "0 0 %s 392" % n(total), lock, + "PCBCraft logo, %s" % label) + for name, text in m.items(): + write(os.path.join(BRAND, name), text) + + # --- generated platform icons ---------------------------------------- + if os.path.isdir(GEN): + shutil.rmtree(GEN) + os.makedirs(GEN) + work = os.path.join(GEN, ".work") + os.makedirs(work) + + def src_for(size): + if size <= 16: + return os.path.join(BRAND, "pcbcraft-icon-16.svg") + if size <= 32: + return os.path.join(BRAND, "pcbcraft-icon-32.svg") + return os.path.join(BRAND, "pcbcraft-icon.svg") + + lin = os.path.join(GEN, "linux", "hicolor") + for s in (16, 24, 32, 48, 64, 128, 256, 512): + render(src_for(s), os.path.join(lin, "%dx%d" % (s, s), "apps", APP_ID + ".png"), s) + scal = os.path.join(lin, "scalable", "apps") + os.makedirs(scal) + shutil.copy(os.path.join(BRAND, "pcbcraft-icon.svg"), os.path.join(scal, APP_ID + ".svg")) + + # Windows + wpngs = [] + for s in (16, 24, 32, 48, 64, 128, 256): + p = os.path.join(work, "win-%d.png" % s) + render(src_for(s), p, s) + wpngs.append(p) + os.makedirs(os.path.join(GEN, "windows")) + make_ico(wpngs, os.path.join(GEN, "windows", "pcbcraft.ico")) + + # macOS: rounded tile at 80 percent of the canvas, transparent margin. + def mac_svg(variant, canvas): + g = variant[0] + grid = 512 if g is GEOM_FULL else (32 if g is GEOM_32 else 16) + r = {512: 96, 32: 6, 16: 3}[grid] + inner = tile_icon(variant, grid, r, uid="x") + pad = grid * 0.1 + body = '%s' % (n(pad), n(pad), inner) + return svg(grid, grid, "0 0 %d %d" % (grid, grid), body, "PCBCraft app icon") + + def mac_png(px, name): + variant = SMALL_16 if px <= 16 else (SMALL_32 if px <= 32 else FULL_COLOUR) + s = os.path.join(work, "mac-%s.svg" % name) + write(s, mac_svg(variant, px)) + p = os.path.join(work, "mac-%s.png" % name) + render(s, p, px) + return p + + ents = [] + for typ, px in (("icp4", 16), ("icp5", 32), ("icp6", 64), ("ic07", 128), ("ic08", 256), ("ic09", 512), + ("ic10", 1024), ("ic11", 32), ("ic12", 64), ("ic13", 256), ("ic14", 512)): + ents.append((typ, mac_png(px, typ))) + os.makedirs(os.path.join(GEN, "macos")) + make_icns(ents, os.path.join(GEN, "macos", "pcbcraft.icns")) + + # Web + web = os.path.join(GEN, "web") + os.makedirs(web) + fav = [] + for s in (16, 32, 48): + p = os.path.join(work, "fav-%d.png" % s) + render(src_for(s), p, s) + fav.append(p) + make_ico(fav, os.path.join(web, "favicon.ico")) + shutil.copy(os.path.join(BRAND, "pcbcraft-icon-16.svg"), os.path.join(web, "favicon.svg")) + + def square(size, scale, pal=DARK, variant=FULL_COLOUR, tile=True): + k = size / 512.0 + mark_px = 392 * k * scale + off = (size - mark_px) / 2.0 + inner = ('' % (size, size, TILE)) if tile else "" + inner += '%s' % ( + n(off), n(off), n(mark_px / 392.0), mark(pal, variant, "w")) + return svg(size, size, "0 0 %d %d" % (size, size), inner, "PCBCraft app icon") + + for name, size, scale, tile, pal, variant in ( + ("apple-touch-icon", 180, 0.84, True, DARK, FULL_COLOUR), + ("icon-maskable-512", 512, 0.72, True, DARK, FULL_COLOUR), + ("icon-monochrome-512", 512, 0.72, False, MONO, FULL_MONO)): + s = os.path.join(work, name + ".svg") + write(s, square(size, scale, pal, variant, tile)) + render(s, os.path.join(web, name + ".png"), size) + render(os.path.join(BRAND, "pcbcraft-icon.svg"), os.path.join(web, "icon-192.png"), 192) + render(os.path.join(BRAND, "pcbcraft-icon.svg"), os.path.join(web, "icon-512.png"), 512) + manifest = { + "name": "PCBCraft", + "short_name": "PCBCraft", + "description": "Schematic capture, PCB layout and design checks in the browser.", + "start_url": ".", + "display": "standalone", + "theme_color": TILE, + "background_color": TILE, + "icons": [ + {"src": "icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"}, + {"src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"}, + {"src": "icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"}, + {"src": "icon-monochrome-512.png", "sizes": "512x512", "type": "image/png", "purpose": "monochrome"}, + ], + } + write(os.path.join(web, "manifest.webmanifest"), json.dumps(manifest, indent=2) + "\n") + + # Previews: every master, and the sized results the report lists. + prev = os.path.join(GEN, "preview") + for name in sorted(m): + if name.startswith("pcbcraft-icon-"): + continue + base = name[:-4] + if "logo" in name or "wordmark" in name: + render_w(os.path.join(BRAND, name), os.path.join(prev, base + ".png"), 1200) + else: + render(os.path.join(BRAND, name), os.path.join(prev, base + ".png"), 512) + for s in (16, 32, 128, 512): + shutil.copy(os.path.join(lin, "%dx%d" % (s, s), "apps", APP_ID + ".png"), + os.path.join(prev, "icon-%d.png" % s)) + try: + from PIL import Image + for s, z in ((16, 16), (32, 8)): + im = Image.open(os.path.join(prev, "icon-%d.png" % s)).convert("RGBA") + im.resize((s * z, s * z), Image.NEAREST).save(os.path.join(prev, "zoom-%d.png" % s)) + sheet = Image.new("RGBA", (16 + 24 + 32 + 48 + 64 + 40, 80), (244, 242, 236, 255)) + x = 8 + for s in (16, 24, 32, 48, 64): + im = Image.open(os.path.join(lin, "%dx%d" % (s, s), "apps", APP_ID + ".png")).convert("RGBA") + sheet.alpha_composite(im, (x, 8)) + x += s + 8 + sheet.resize((sheet.width * 4, sheet.height * 4), Image.NEAREST).save(os.path.join(prev, "sizes-sheet.png")) + except ImportError: + print("Pillow missing: zoom previews skipped", file=sys.stderr) + shutil.rmtree(work) + print("brand build done") + + +if __name__ == "__main__": + main() diff --git a/assets/icons/ui/LICENSE-lucide.txt b/assets/icons/ui/LICENSE-lucide.txt new file mode 100644 index 000000000..325e8ff0a --- /dev/null +++ b/assets/icons/ui/LICENSE-lucide.txt @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/assets/icons/ui/add.svg b/assets/icons/ui/add.svg new file mode 100644 index 000000000..a80be3282 --- /dev/null +++ b/assets/icons/ui/add.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/assistant.svg b/assets/icons/ui/assistant.svg new file mode 100644 index 000000000..bfaaedbd5 --- /dev/null +++ b/assets/icons/ui/assistant.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/board-outline.svg b/assets/icons/ui/board-outline.svg new file mode 100644 index 000000000..b9893ba36 --- /dev/null +++ b/assets/icons/ui/board-outline.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/bom.svg b/assets/icons/ui/bom.svg new file mode 100644 index 000000000..f468096eb --- /dev/null +++ b/assets/icons/ui/bom.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/box.svg b/assets/icons/ui/box.svg new file mode 100644 index 000000000..f16cc6c8b --- /dev/null +++ b/assets/icons/ui/box.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/bus.svg b/assets/icons/ui/bus.svg new file mode 100644 index 000000000..8ba7c3acf --- /dev/null +++ b/assets/icons/ui/bus.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/check.svg b/assets/icons/ui/check.svg new file mode 100644 index 000000000..59616c93b --- /dev/null +++ b/assets/icons/ui/check.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/chevron-down.svg b/assets/icons/ui/chevron-down.svg new file mode 100644 index 000000000..bc8b193e1 --- /dev/null +++ b/assets/icons/ui/chevron-down.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/chevron-right.svg b/assets/icons/ui/chevron-right.svg new file mode 100644 index 000000000..64a04ffa1 --- /dev/null +++ b/assets/icons/ui/chevron-right.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/circle.svg b/assets/icons/ui/circle.svg new file mode 100644 index 000000000..df2731dca --- /dev/null +++ b/assets/icons/ui/circle.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/close.svg b/assets/icons/ui/close.svg new file mode 100644 index 000000000..d94587756 --- /dev/null +++ b/assets/icons/ui/close.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/copy.svg b/assets/icons/ui/copy.svg new file mode 100644 index 000000000..a81f0d18b --- /dev/null +++ b/assets/icons/ui/copy.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/courtyard.svg b/assets/icons/ui/courtyard.svg new file mode 100644 index 000000000..95c26d018 --- /dev/null +++ b/assets/icons/ui/courtyard.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/cpu.svg b/assets/icons/ui/cpu.svg new file mode 100644 index 000000000..dc7083e26 --- /dev/null +++ b/assets/icons/ui/cpu.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/cutout.svg b/assets/icons/ui/cutout.svg new file mode 100644 index 000000000..f363dea57 --- /dev/null +++ b/assets/icons/ui/cutout.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/diff-pair.svg b/assets/icons/ui/diff-pair.svg new file mode 100644 index 000000000..2448c4ffb --- /dev/null +++ b/assets/icons/ui/diff-pair.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/drill-file.svg b/assets/icons/ui/drill-file.svg new file mode 100644 index 000000000..8507dcc09 --- /dev/null +++ b/assets/icons/ui/drill-file.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/drill.svg b/assets/icons/ui/drill.svg new file mode 100644 index 000000000..d66277e76 --- /dev/null +++ b/assets/icons/ui/drill.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/error.svg b/assets/icons/ui/error.svg new file mode 100644 index 000000000..30bfaa72c --- /dev/null +++ b/assets/icons/ui/error.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/eye-off.svg b/assets/icons/ui/eye-off.svg new file mode 100644 index 000000000..b0d00ea65 --- /dev/null +++ b/assets/icons/ui/eye-off.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/eye.svg b/assets/icons/ui/eye.svg new file mode 100644 index 000000000..6bf438322 --- /dev/null +++ b/assets/icons/ui/eye.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/fit.svg b/assets/icons/ui/fit.svg new file mode 100644 index 000000000..a60c7bc0c --- /dev/null +++ b/assets/icons/ui/fit.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/focus.svg b/assets/icons/ui/focus.svg new file mode 100644 index 000000000..d8f41af31 --- /dev/null +++ b/assets/icons/ui/focus.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/folder.svg b/assets/icons/ui/folder.svg new file mode 100644 index 000000000..9037f826a --- /dev/null +++ b/assets/icons/ui/folder.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/footprint.svg b/assets/icons/ui/footprint.svg new file mode 100644 index 000000000..d5a0c4a8c --- /dev/null +++ b/assets/icons/ui/footprint.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/globe.svg b/assets/icons/ui/globe.svg new file mode 100644 index 000000000..7b8d68009 --- /dev/null +++ b/assets/icons/ui/globe.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/grid.svg b/assets/icons/ui/grid.svg new file mode 100644 index 000000000..45f1453fb --- /dev/null +++ b/assets/icons/ui/grid.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/help.svg b/assets/icons/ui/help.svg new file mode 100644 index 000000000..7222d6ed8 --- /dev/null +++ b/assets/icons/ui/help.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/info.svg b/assets/icons/ui/info.svg new file mode 100644 index 000000000..60a639b32 --- /dev/null +++ b/assets/icons/ui/info.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/junction.svg b/assets/icons/ui/junction.svg new file mode 100644 index 000000000..0f6b4799b --- /dev/null +++ b/assets/icons/ui/junction.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/keepout.svg b/assets/icons/ui/keepout.svg new file mode 100644 index 000000000..da86c7f96 --- /dev/null +++ b/assets/icons/ui/keepout.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/label.svg b/assets/icons/ui/label.svg new file mode 100644 index 000000000..c99efc568 --- /dev/null +++ b/assets/icons/ui/label.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/layer-copper.svg b/assets/icons/ui/layer-copper.svg new file mode 100644 index 000000000..d773e2681 --- /dev/null +++ b/assets/icons/ui/layer-copper.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/layer-core.svg b/assets/icons/ui/layer-core.svg new file mode 100644 index 000000000..1c1dbb2a8 --- /dev/null +++ b/assets/icons/ui/layer-core.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/layer-mask.svg b/assets/icons/ui/layer-mask.svg new file mode 100644 index 000000000..01ac114e7 --- /dev/null +++ b/assets/icons/ui/layer-mask.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/layer-paste.svg b/assets/icons/ui/layer-paste.svg new file mode 100644 index 000000000..f3b2784f7 --- /dev/null +++ b/assets/icons/ui/layer-paste.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/layer-silk.svg b/assets/icons/ui/layer-silk.svg new file mode 100644 index 000000000..223e29178 --- /dev/null +++ b/assets/icons/ui/layer-silk.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/layers.svg b/assets/icons/ui/layers.svg new file mode 100644 index 000000000..0dcf3046b --- /dev/null +++ b/assets/icons/ui/layers.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/library.svg b/assets/icons/ui/library.svg new file mode 100644 index 000000000..04a608aab --- /dev/null +++ b/assets/icons/ui/library.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/line.svg b/assets/icons/ui/line.svg new file mode 100644 index 000000000..3e7df0c60 --- /dev/null +++ b/assets/icons/ui/line.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/lock.svg b/assets/icons/ui/lock.svg new file mode 100644 index 000000000..ce90b765d --- /dev/null +++ b/assets/icons/ui/lock.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/measure.svg b/assets/icons/ui/measure.svg new file mode 100644 index 000000000..90eee227e --- /dev/null +++ b/assets/icons/ui/measure.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/menu.svg b/assets/icons/ui/menu.svg new file mode 100644 index 000000000..d17f2fcc7 --- /dev/null +++ b/assets/icons/ui/menu.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/mounting-hole.svg b/assets/icons/ui/mounting-hole.svg new file mode 100644 index 000000000..875cc55ab --- /dev/null +++ b/assets/icons/ui/mounting-hole.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/move.svg b/assets/icons/ui/move.svg new file mode 100644 index 000000000..01ec1ae80 --- /dev/null +++ b/assets/icons/ui/move.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/net.svg b/assets/icons/ui/net.svg new file mode 100644 index 000000000..9f7b4f468 --- /dev/null +++ b/assets/icons/ui/net.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/no-connect.svg b/assets/icons/ui/no-connect.svg new file mode 100644 index 000000000..522183191 --- /dev/null +++ b/assets/icons/ui/no-connect.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/omega.svg b/assets/icons/ui/omega.svg new file mode 100644 index 000000000..c589856b4 --- /dev/null +++ b/assets/icons/ui/omega.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/open.svg b/assets/icons/ui/open.svg new file mode 100644 index 000000000..2125a88d0 --- /dev/null +++ b/assets/icons/ui/open.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/pad-smd.svg b/assets/icons/ui/pad-smd.svg new file mode 100644 index 000000000..068742851 --- /dev/null +++ b/assets/icons/ui/pad-smd.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/pad-th.svg b/assets/icons/ui/pad-th.svg new file mode 100644 index 000000000..ff464c62d --- /dev/null +++ b/assets/icons/ui/pad-th.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/part.svg b/assets/icons/ui/part.svg new file mode 100644 index 000000000..4352f82a3 --- /dev/null +++ b/assets/icons/ui/part.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/plot.svg b/assets/icons/ui/plot.svg new file mode 100644 index 000000000..187d5ea04 --- /dev/null +++ b/assets/icons/ui/plot.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/plug.svg b/assets/icons/ui/plug.svg new file mode 100644 index 000000000..298d05438 --- /dev/null +++ b/assets/icons/ui/plug.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/port.svg b/assets/icons/ui/port.svg new file mode 100644 index 000000000..6f1c8a319 --- /dev/null +++ b/assets/icons/ui/port.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/power.svg b/assets/icons/ui/power.svg new file mode 100644 index 000000000..c4a6ab7ae --- /dev/null +++ b/assets/icons/ui/power.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/preview/contact-sheet.png b/assets/icons/ui/preview/contact-sheet.png new file mode 100644 index 000000000..4efb911ec Binary files /dev/null and b/assets/icons/ui/preview/contact-sheet.png differ diff --git a/assets/icons/ui/redo.svg b/assets/icons/ui/redo.svg new file mode 100644 index 000000000..5cdaf0246 --- /dev/null +++ b/assets/icons/ui/redo.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/rotate-ccw.svg b/assets/icons/ui/rotate-ccw.svg new file mode 100644 index 000000000..e99a4694c --- /dev/null +++ b/assets/icons/ui/rotate-ccw.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/rotate.svg b/assets/icons/ui/rotate.svg new file mode 100644 index 000000000..9e33b68ee --- /dev/null +++ b/assets/icons/ui/rotate.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/route.svg b/assets/icons/ui/route.svg new file mode 100644 index 000000000..ad0c8896d --- /dev/null +++ b/assets/icons/ui/route.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/save.svg b/assets/icons/ui/save.svg new file mode 100644 index 000000000..b9f132df1 --- /dev/null +++ b/assets/icons/ui/save.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/search.svg b/assets/icons/ui/search.svg new file mode 100644 index 000000000..19ede161e --- /dev/null +++ b/assets/icons/ui/search.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/select.svg b/assets/icons/ui/select.svg new file mode 100644 index 000000000..50e2094c4 --- /dev/null +++ b/assets/icons/ui/select.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/settings.svg b/assets/icons/ui/settings.svg new file mode 100644 index 000000000..1891c3e57 --- /dev/null +++ b/assets/icons/ui/settings.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/shapes.svg b/assets/icons/ui/shapes.svg new file mode 100644 index 000000000..6c313215e --- /dev/null +++ b/assets/icons/ui/shapes.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/sheet.svg b/assets/icons/ui/sheet.svg new file mode 100644 index 000000000..cc3e20ba4 --- /dev/null +++ b/assets/icons/ui/sheet.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/stackup.svg b/assets/icons/ui/stackup.svg new file mode 100644 index 000000000..64c09d114 --- /dev/null +++ b/assets/icons/ui/stackup.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/star-filled.svg b/assets/icons/ui/star-filled.svg new file mode 100644 index 000000000..9d461ca8f --- /dev/null +++ b/assets/icons/ui/star-filled.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/star.svg b/assets/icons/ui/star.svg new file mode 100644 index 000000000..b5543ff4b --- /dev/null +++ b/assets/icons/ui/star.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/text.svg b/assets/icons/ui/text.svg new file mode 100644 index 000000000..b4f51ce46 --- /dev/null +++ b/assets/icons/ui/text.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/track.svg b/assets/icons/ui/track.svg new file mode 100644 index 000000000..3e0be8426 --- /dev/null +++ b/assets/icons/ui/track.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/trash.svg b/assets/icons/ui/trash.svg new file mode 100644 index 000000000..2f2a3b10e --- /dev/null +++ b/assets/icons/ui/trash.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/undo.svg b/assets/icons/ui/undo.svg new file mode 100644 index 000000000..2bcae303d --- /dev/null +++ b/assets/icons/ui/undo.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/unlock.svg b/assets/icons/ui/unlock.svg new file mode 100644 index 000000000..732c48b92 --- /dev/null +++ b/assets/icons/ui/unlock.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/via.svg b/assets/icons/ui/via.svg new file mode 100644 index 000000000..971966475 --- /dev/null +++ b/assets/icons/ui/via.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/view-3d.svg b/assets/icons/ui/view-3d.svg new file mode 100644 index 000000000..bf8b30bf3 --- /dev/null +++ b/assets/icons/ui/view-3d.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/view-front.svg b/assets/icons/ui/view-front.svg new file mode 100644 index 000000000..5f526bf17 --- /dev/null +++ b/assets/icons/ui/view-front.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/view-side.svg b/assets/icons/ui/view-side.svg new file mode 100644 index 000000000..978f5cd19 --- /dev/null +++ b/assets/icons/ui/view-side.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/view-top.svg b/assets/icons/ui/view-top.svg new file mode 100644 index 000000000..ca52cf400 --- /dev/null +++ b/assets/icons/ui/view-top.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/warning.svg b/assets/icons/ui/warning.svg new file mode 100644 index 000000000..a95cd861c --- /dev/null +++ b/assets/icons/ui/warning.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/wire.svg b/assets/icons/ui/wire.svg new file mode 100644 index 000000000..bfe0c5ae2 --- /dev/null +++ b/assets/icons/ui/wire.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/zone.svg b/assets/icons/ui/zone.svg new file mode 100644 index 000000000..2f1b2f257 --- /dev/null +++ b/assets/icons/ui/zone.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/zoom-in.svg b/assets/icons/ui/zoom-in.svg new file mode 100644 index 000000000..e1d9aa67a --- /dev/null +++ b/assets/icons/ui/zoom-in.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/ui/zoom-out.svg b/assets/icons/ui/zoom-out.svg new file mode 100644 index 000000000..daa129cfd --- /dev/null +++ b/assets/icons/ui/zoom-out.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/platforms/linux/io.github.tangency-labs.pcbcraft.desktop b/assets/platforms/linux/io.github.tangency-labs.pcbcraft.desktop new file mode 100644 index 000000000..5b3a5cbcc --- /dev/null +++ b/assets/platforms/linux/io.github.tangency-labs.pcbcraft.desktop @@ -0,0 +1,14 @@ +[Desktop Entry] +Type=Application +Name=PCBCraft +GenericName=PCB design +Comment=Schematic capture, PCB layout, design checks, and KiCad export +Exec=pcbcraft %f +TryExec=pcbcraft +Icon=io.github.tangency-labs.pcbcraft +Terminal=false +StartupNotify=true +StartupWMClass=io.github.tangency-labs.pcbcraft +Categories=Electronics;Engineering; +Keywords=pcb;eda;schematic;layout;kicad; +MimeType=application/x-pcbcraft; diff --git a/assets/platforms/linux/io.github.tangency-labs.pcbcraft.metainfo.xml.in b/assets/platforms/linux/io.github.tangency-labs.pcbcraft.metainfo.xml.in new file mode 100644 index 000000000..42be3315f --- /dev/null +++ b/assets/platforms/linux/io.github.tangency-labs.pcbcraft.metainfo.xml.in @@ -0,0 +1,45 @@ + + + io.github.tangency-labs.pcbcraft + CC0-1.0 + GPL-3.0-or-later + PCBCraft + Open-source Rust PCB design + + PCBCraft contributors + + +

+ PCBCraft is an open-source PCB design application written in Rust. Capture schematics, + place and route a board, run design checks, and export KiCad-compatible output. +

+
    +
  • Unified schematic and PCB editing in one window
  • +
  • Symbol and footprint libraries with KiCad import
  • +
  • Routing, design rules, and headless checks via pcbcraft-cli
  • +
  • MCP server for agent-driven workflows
  • +
+
+ io.github.tangency-labs.pcbcraft.desktop + io.github.tangency-labs.pcbcraft + https://github.com/tangency-labs/pcbcraft + https://github.com/tangency-labs/pcbcraft/issues + + Electronics + Engineering + + + pcb + eda + schematic + + + pcbcraft + pcbcraft-cli + application/x-pcbcraft + + + + + +
diff --git a/assets/platforms/linux/io.github.tangency-labs.pcbcraft.mime.xml b/assets/platforms/linux/io.github.tangency-labs.pcbcraft.mime.xml new file mode 100644 index 000000000..92b6bc84f --- /dev/null +++ b/assets/platforms/linux/io.github.tangency-labs.pcbcraft.mime.xml @@ -0,0 +1,9 @@ + + + + PCBCraft design + + + + + diff --git a/crates/assistant/Cargo.toml b/crates/assistant/Cargo.toml new file mode 100644 index 000000000..274026502 --- /dev/null +++ b/crates/assistant/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "pcbcraft-assistant" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +pcbcraft-engine.workspace = true +pcbcraft-mcp.workspace = true +serde.workspace = true +serde_json.workspace = true diff --git a/crates/assistant/src/api.rs b/crates/assistant/src/api.rs new file mode 100644 index 000000000..f0e7a02e2 --- /dev/null +++ b/crates/assistant/src/api.rs @@ -0,0 +1,1075 @@ +// Adapted from SolidCraft (MIT OR Apache-2.0), commit 32558d0a: +// crates/ui-egui/src/agent_chat/api_client.rs +//! The API backend: a model behind an OpenAI-compatible chat completions endpoint or an +//! Anthropic-compatible Messages endpoint. It runs the tool loop itself. Each tool call goes out on +//! the [`StartContext::tools`] channel (the host gates it and runs it on the displayed session) and +//! the result goes back to the model. The host supplies the HTTP function; nothing here touches the +//! network by itself. + +use crate::backend::{ + ChatBackend, Event, HttpFn, HttpRequest, ModelInfo, PromptPart, StartContext, ToolStatus, +}; +use crate::prompt::SYSTEM_NOTE; +use crate::tool_names::{ToolNames, to_wire}; +use crate::turn::ToolRequest; +use serde_json::{Value, json}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::Duration; + +/// Model requests for one message, at most (each answer with tool calls is one). +pub const MAX_REQUESTS_PER_TURN: usize = 24; +/// Longest tool result handed back to the model. +pub const MAX_TOOL_TEXT: usize = 20_000; +/// Messages kept in the conversation (the system note stays). +pub const MAX_HISTORY: usize = 240; +const REQUEST_TIMEOUT_S: u64 = 300; +const TOOL_TIMEOUT: Duration = Duration::from_secs(330); +const CANCEL_POLL: Duration = Duration::from_millis(40); +const ANTHROPIC_MAX_TOKENS: u64 = 8192; +const ANTHROPIC_VERSION: &str = "2023-06-01"; +const TEST_TIMEOUT_S: u64 = 60; +/// Shown when the model ran out of room for its answer (`length`, `max_tokens`). +const NOTE_CUT_BY_LENGTH: &str = "The model stopped early because the answer hit its length limit. Ask for a shorter answer or a smaller step."; +/// Shown when the endpoint filtered the answer (`content_filter`). +const NOTE_FILTERED: &str = + "The endpoint filtered the answer, so it may be missing or partial. Try rewording the request."; +/// Shown when the model declined to answer (`refusal`). +const NOTE_REFUSED: &str = + "The model declined to answer this request. Try rewording it or asking for a smaller step."; +/// Tools the model is not offered. None today. +const HIDDEN_TOOLS: &[&str] = &[]; + +/// Which wire shape the endpoint speaks. +/// +/// # Dependencies +/// - `crates/assistant/Cargo.toml` (serde for wire encoding) +/// +/// # Rules +/// - Derives `Clone`, `Copy`, `Debug`, `PartialEq`, `Eq`, `serde::Serialize`, `serde::Deserialize`. +/// - This enum represents the protocol used to communicate with the model. +/// - Each variant corresponds to a specific API protocol. +/// +/// # Do not +/// - Add new variants without updating the `tool_list` and `tool_names` logic. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum Protocol { + OpenAi, + Anthropic, +} + +/// Where the model is and how to reach it. +/// +/// # Dependencies +/// - `crates/assistant/Cargo.toml` (serde for saved connection fields) +/// +/// # Rules +/// - This struct holds the configuration for connecting to the model. +/// - `protocol` specifies the API protocol to use. +/// - `base_url` is the address of the model. +/// - `key` is the authentication key, sent only over HTTPS or to this computer. +/// +/// # Do not +/// - Store sensitive information in plain text; use secure storage mechanisms. +#[derive(Clone)] +pub struct ApiConfig { + pub protocol: Protocol, + pub base_url: String, + pub model: String, + pub key: Option, + /// Added after the standing system note (the design summary, later). + pub system_note: String, +} + +enum Cmd { + Prompt(Vec), + NewChat, + SetModel(String), +} + +/// The running backend; the loop lives on a thread of its own. +pub struct ApiBackend { + cmds: Option>, + events: Receiver, + cancel: Arc, +} + +/// Whether a key may be sent to this address: HTTPS, or this computer. +pub fn key_safe_for(base_url: &str) -> bool { + let lower = base_url.trim().to_ascii_lowercase(); + if lower.starts_with("https://") { + return true; + } + let Some(rest) = lower.strip_prefix("http://") else { + return false; + }; + let host = rest.split(['/', '?', '#']).next().unwrap_or(""); + let host = host.rsplit('@').next().unwrap_or(""); + let name = if let Some(v6) = host.strip_prefix('[') { + v6.split(']').next().unwrap_or("") + } else { + host.split(':').next().unwrap_or("") + }; + matches!(name, "localhost" | "127.0.0.1" | "::1") +} + +impl ApiBackend { + pub fn start(cfg: ApiConfig, ctx: StartContext, http: HttpFn) -> Result { + if cfg.base_url.trim().is_empty() { + return Err("Enter the address of the model first.".into()); + } + if cfg.key.is_some() && !key_safe_for(&cfg.base_url) { + return Err("A key is only sent over https, or to this computer.".into()); + } + let (cmd_tx, cmd_rx) = channel::(); + let (ev_tx, events) = channel::(); + let cancel = Arc::new(AtomicBool::new(false)); + let stop = cancel.clone(); + let tool_list = pcbcraft_mcp::tool_list(); + let tool_names = ToolNames::from_list(&tool_list)?; + let tools = match cfg.protocol { + Protocol::OpenAi => openai_tools(&tool_list), + Protocol::Anthropic => anthropic_tools(&tool_list), + }; + let spawned = std::thread::Builder::new() + .name("assistant-api".into()) + .spawn(move || { + let mut w = Worker { + cfg, + http, + tool_sink: ctx.tools, + tools, + tool_names, + history: Vec::new(), + events: ev_tx, + cancel: stop, + requests_made: 0, + }; + w.run(cmd_rx); + }); + spawned.map_err(|e| format!("Could not start the assistant: {e}"))?; + Ok(ApiBackend { + cmds: Some(cmd_tx), + events, + cancel, + }) + } +} + +impl ChatBackend for ApiBackend { + fn poll(&mut self) -> Vec { + self.events.try_iter().take(512).collect() + } + fn prompt(&mut self, parts: &[PromptPart]) { + self.cancel.store(false, Ordering::Relaxed); + if let Some(c) = &self.cmds { + let _ = c.send(Cmd::Prompt(parts.to_vec())); + } + } + fn cancel(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } + fn set_model(&mut self, model: &str) { + if let Some(c) = &self.cmds { + let _ = c.send(Cmd::SetModel(model.to_string())); + } + } + fn new_session(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + if let Some(c) = &self.cmds { + let _ = c.send(Cmd::NewChat); + } + } + fn answer_permission(&mut self, _key: u64, _option: Option<&str>) {} + fn authenticate(&mut self, _method: &str) {} + fn set_mode(&mut self, _mode: &str) {} + fn shutdown(&mut self, _wait: bool) { + self.cancel.store(true, Ordering::Relaxed); + self.cmds = None; + } +} + +impl Drop for ApiBackend { + fn drop(&mut self) { + self.shutdown(false); + } +} + +struct Worker { + cfg: ApiConfig, + http: HttpFn, + tool_sink: Option>, + tools: Vec, + tool_names: ToolNames, + history: Vec, + events: Sender, + cancel: Arc, + requests_made: usize, +} + +impl Worker { + fn emit(&self, e: Event) { + let _ = self.events.send(e); + } + + fn agent_name(&self) -> String { + format!("API · {}", self.cfg.model) + } + + fn run(&mut self, cmds: Receiver) { + self.emit(Event::Ready { + agent: self.agent_name(), + images: true, + }); + let listed = match self.cfg.protocol { + Protocol::OpenAi => model_list(&self.http, &self.cfg.base_url, self.cfg.key.as_deref()), + Protocol::Anthropic => { + anthropic_model_list(&self.http, &self.cfg.base_url, self.cfg.key.as_deref()) + } + }; + if let Ok(mut available) = listed { + if !self.cfg.model.is_empty() && !available.iter().any(|m| m.id == self.cfg.model) { + available.insert( + 0, + ModelInfo { + id: self.cfg.model.clone(), + name: self.cfg.model.clone(), + description: String::new(), + }, + ); + } + if !available.is_empty() { + self.emit(Event::Models { + current: self.cfg.model.clone(), + available, + }); + } + } + for cmd in cmds { + match cmd { + Cmd::Prompt(parts) => self.turn(parts), + Cmd::SetModel(m) => self.cfg.model = m, + Cmd::NewChat => { + self.history.clear(); + self.cancel.store(false, Ordering::Relaxed); + self.emit(Event::Ready { + agent: self.agent_name(), + images: true, + }); + } + } + } + } + + fn cancelled(&self) -> bool { + self.cancel.load(Ordering::Relaxed) + } + + fn turn(&mut self, parts: Vec) { + self.history.push(user_message(self.cfg.protocol, &parts)); + self.trim_history(); + for n in 1..=MAX_REQUESTS_PER_TURN { + // The history here is complete: a cancelled request goes back to it. + let sound = self.history.len(); + if self.cancelled() { + self.emit(Event::TurnEnded { + reason: "cancelled".into(), + }); + return; + } + self.emit(Event::Note(format!( + "request {n} of {MAX_REQUESTS_PER_TURN}" + ))); + let result = self.request(); + if self.cancelled() { + self.history.truncate(sound); + self.emit(Event::TurnEnded { + reason: "cancelled".into(), + }); + return; + } + let reply = match result { + Ok(r) => r, + Err(e) => { + self.emit(Event::Error(e)); + self.emit(Event::TurnEnded { + reason: "error".into(), + }); + return; + } + }; + for (thought, text) in reply.text { + self.emit(Event::Text { thought, text }); + } + let stop = reply.stop.as_deref().unwrap_or(""); + let cut_by_length = matches!(stop, "length" | "max_tokens"); + let note = stop_note(stop); + // A cut-off answer may hold cut-off tool arguments: none of its calls run, and the + // message goes back to the model without them so the history stays well formed. + if note.is_some() && (reply.calls.is_empty() || cut_by_length) { + let kept = if reply.calls.is_empty() { + reply.assistant + } else { + without_calls(reply.assistant) + }; + self.history.push(kept); + if let Some(note) = note { + self.emit(Event::Note(note.to_string())); + } + self.emit(Event::TurnEnded { + reason: stop.to_string(), + }); + return; + } + self.history.push(reply.assistant); + if reply.calls.is_empty() { + self.emit(Event::TurnEnded { + reason: String::new(), + }); + return; + } + let mut results = Vec::new(); + for c in reply.calls.iter().take(32) { + // The model uses the wire name; the host, the permission prompts and the UI use the MCP name. + let mcp = self.tool_names.mcp_name(&c.name).map(str::to_string); + let shown_name = mcp.as_deref().unwrap_or(&c.name); + let args = c.arguments.clone().unwrap_or_else(|_| json!({})); + self.requests_made += 1; + let tool_id = format!("{}-{}", c.id, self.requests_made); + self.emit(Event::Tool { + id: tool_id.clone(), + title: Some(tool_title(shown_name, &args)), + kind: Some(String::new()), + status: Some(ToolStatus::InProgress), + output: None, + }); + let (text, failed) = if self.cancelled() { + ("cancelled by the user".to_string(), true) + } else if let Err(e) = &c.arguments { + (format!("Not run: {e}"), true) + } else if let Some(mcp) = &mcp { + match self.call_tool(mcp, args) { + Ok(r) => tool_text(&r), + Err(e) => (e, true), + } + } else { + (format!("unknown tool `{}`", c.name), true) + }; + let shown: String = text.chars().take(2000).collect(); + self.emit(Event::Tool { + id: tool_id, + title: None, + kind: None, + status: Some(if failed { + ToolStatus::Failed + } else { + ToolStatus::Completed + }), + output: Some(shown), + }); + match self.cfg.protocol { + Protocol::OpenAi => self.history.push(json!({"role": "tool", "tool_call_id": c.id, "content": text})), + Protocol::Anthropic => results.push(json!({"type": "tool_result", "tool_use_id": c.id, "content": text, "is_error": failed})), + } + } + if self.cfg.protocol == Protocol::Anthropic && !results.is_empty() { + self.history + .push(json!({"role": "user", "content": results})); + } + } + // The cap is reached: tell the model to stop and report, and show the user why. + self.history.push(user_text( + self.cfg.protocol, + "Stop calling tools now. Report what you did and what is left.", + )); + self.emit(Event::Text { + thought: false, + text: "\n(Stopped after 24 requests for one message.)".into(), + }); + self.emit(Event::TurnEnded { + reason: "max_turn_requests".into(), + }); + } + + /// Send one tool call to the host and wait for its answer, looking at Stop while it waits. + fn call_tool(&self, name: &str, args: Value) -> Result { + let Some(sink) = &self.tool_sink else { + return Err("The assistant has no design tools in this session.".into()); + }; + let (reply, answer) = channel(); + sink.send(ToolRequest { + name: name.to_string(), + args, + reply, + }) + .map_err(|_| "The design tools stopped.".to_string())?; + let deadline = std::time::Instant::now() + TOOL_TIMEOUT; + loop { + if self.cancelled() { + return Err("cancelled by the user".into()); + } + match answer.recv_timeout(CANCEL_POLL) { + Ok(v) => return Ok(v), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) + if std::time::Instant::now() < deadline => {} + Err(_) => return Err("The design tools did not answer.".into()), + } + } + } + + /// Keep the conversation bounded and starting at a user message. + fn trim_history(&mut self) { + let extra = self.history.len().saturating_sub(MAX_HISTORY); + self.history.drain(..extra); + let lead = self + .history + .iter() + .take_while(|m| !starts_a_turn(m)) + .count(); + self.history.drain(..lead); + } + + fn request(&self) -> Result { + let body = self.body(); + let (status, v) = self.post(&body)?; + if status != 200 { + return Err(http_error(status, &v)); + } + Ok(reply(self.cfg.protocol, &v)) + } + + fn system_text(&self) -> String { + if self.cfg.system_note.trim().is_empty() { + SYSTEM_NOTE.to_string() + } else { + format!("{SYSTEM_NOTE}\n\n{}", self.cfg.system_note) + } + } + + fn body(&self) -> Value { + match self.cfg.protocol { + Protocol::OpenAi => { + let mut messages = Vec::with_capacity(self.history.len() + 1); + messages.push(json!({"role": "system", "content": self.system_text()})); + messages.extend(self.history.iter().cloned()); + let mut body = json!({"model": self.cfg.model, "messages": messages}); + if !self.tools.is_empty() { + body["tools"] = Value::Array(self.tools.clone()); + } + body + } + Protocol::Anthropic => { + let mut body = json!({ + "model": self.cfg.model, + "max_tokens": ANTHROPIC_MAX_TOKENS, + "system": self.system_text(), + "messages": &self.history, + }); + if !self.tools.is_empty() { + body["tools"] = Value::Array(self.tools.clone()); + } + body + } + } + } + + fn post(&self, body: &Value) -> Result<(u16, Value), String> { + let mut headers = vec![("Content-Type".to_string(), "application/json".to_string())]; + let url = match self.cfg.protocol { + Protocol::OpenAi => format!( + "{}/chat/completions", + self.cfg.base_url.trim_end_matches('/') + ), + Protocol::Anthropic => { + headers.push(( + "anthropic-version".to_string(), + ANTHROPIC_VERSION.to_string(), + )); + endpoint(&self.cfg.base_url, "messages") + } + }; + if let Some(k) = &self.cfg.key { + match self.cfg.protocol { + Protocol::OpenAi => headers.push(("Authorization".into(), format!("Bearer {k}"))), + Protocol::Anthropic => headers.push(("x-api-key".into(), k.clone())), + } + } + let req = HttpRequest { + method: "POST", + url, + headers, + body: Some(body.to_string().into_bytes()), + timeout_s: REQUEST_TIMEOUT_S, + }; + // The request runs on its own thread so Stop does not wait for the model. + let (tx, rx) = channel(); + let http = self.http.clone(); + std::thread::spawn(move || { + let _ = tx.send(http(&req)); + }); + // streaming: follow-up + let (status, bytes) = loop { + if self.cancelled() { + return Err("cancelled by the user".into()); + } + match rx.recv_timeout(CANCEL_POLL) { + Ok(r) => break r.map_err(|e| redact(&e, self.cfg.key.as_deref()))?, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(_) => return Err("The request ended without an answer.".into()), + } + }; + Ok(( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + )) + } +} + +/// An error text with the key taken out, if it ever got in. +fn redact(text: &str, key: Option<&str>) -> String { + match key.filter(|k| !k.is_empty()) { + Some(k) => text.replace(k, "(key)"), + None => text.to_string(), + } +} + +/// An endpoint's refusal as a plain sentence: the status and the body's `error.message`. The key is +/// never part of it. +pub fn http_error(status: u16, body: &Value) -> String { + let detail = body + .pointer("/error/message") + .or_else(|| body.get("error")) + .and_then(Value::as_str) + .unwrap_or("") + .chars() + .take(300) + .collect::(); + let what = match status { + 401 | 403 => "the endpoint did not accept the key", + 404 => "the endpoint has nothing at that address", + 429 => "the endpoint is busy, try again soon", + _ => "", + }; + format!( + "HTTP {status}{}{}", + if what.is_empty() { + String::new() + } else { + format!(": {what}") + }, + if detail.is_empty() { + String::new() + } else { + format!(" ({detail})") + } + ) +} + +fn tool_arguments(raw: Option<&Value>) -> Result { + let text = match raw { + None | Some(Value::Null) => return Ok(json!({})), + Some(v @ Value::Object(_)) => return Ok(v.clone()), + Some(Value::String(s)) => s.trim(), + Some(_) => return Err("the tool arguments must be a JSON object".into()), + }; + if text.is_empty() { + return Ok(json!({})); + } + match serde_json::from_str::(text) { + Ok(v @ Value::Object(_)) => Ok(v), + Ok(_) => Err("the tool arguments must be a JSON object".into()), + Err(e) => Err(format!( + "the tool arguments were not valid JSON ({e}); send the call again with a JSON object" + )), + } +} + +fn user_text(protocol: Protocol, text: &str) -> Value { + user_message(protocol, &[PromptPart::Text(text.to_string())]) +} + +fn user_message(protocol: Protocol, parts: &[PromptPart]) -> Value { + let pictures = parts + .iter() + .any(|p| matches!(p, PromptPart::Picture { .. })); + if !pictures { + let text: Vec<&str> = parts + .iter() + .filter_map(|p| { + if let PromptPart::Text(t) = p { + Some(t.as_str()) + } else { + None + } + }) + .collect(); + return json!({"role": "user", "content": text.join("\n")}); + } + let content: Vec = parts + .iter() + .filter_map(|p| match (protocol, p) { + (_, PromptPart::Text(t)) => Some(json!({"type": "text", "text": t})), + (Protocol::OpenAi, PromptPart::Picture { mime, base64 }) => { + Some(json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}})) + } + (Protocol::Anthropic, PromptPart::Picture { mime, base64 }) => { + Some(json!({"type": "image", "source": {"type": "base64", "media_type": mime, "data": base64}})) + } + (_, PromptPart::Document { .. }) => None, + }) + .collect(); + json!({"role": "user", "content": content}) +} + +fn starts_a_turn(message: &Value) -> bool { + message["role"] == "user" + && !message["content"] + .as_array() + .is_some_and(|blocks| blocks.iter().any(|b| b["type"] == "tool_result")) +} + +#[derive(Debug)] +struct Call { + id: String, + name: String, + arguments: Result, +} + +#[derive(Debug)] +struct Reply { + text: Vec<(bool, String)>, + calls: Vec, + assistant: Value, + /// `finish_reason` (OpenAI) or `stop_reason` (Anthropic), when the endpoint sent one. + stop: Option, +} + +/// The note for a stop value that means the answer was cut off or held back, else `None`. +fn stop_note(stop: &str) -> Option<&'static str> { + match stop { + "length" | "max_tokens" => Some(NOTE_CUT_BY_LENGTH), + "content_filter" => Some(NOTE_FILTERED), + "refusal" => Some(NOTE_REFUSED), + _ => None, + } +} + +/// An assistant message with its tool calls taken out. An emptied message gets a short placeholder, +/// because both protocols refuse an assistant message with nothing in it. +fn without_calls(mut message: Value) -> Value { + const PLACEHOLDER: &str = "(answer cut off)"; + if let Some(obj) = message.as_object_mut() { + obj.remove("tool_calls"); + } + match message.get_mut("content") { + Some(Value::Array(blocks)) => { + blocks.retain(|b| b["type"] != "tool_use"); + if blocks.is_empty() { + blocks.push(json!({"type": "text", "text": PLACEHOLDER})); + } + } + Some(Value::String(t)) if t.is_empty() => *t = PLACEHOLDER.to_string(), + Some(Value::Null) | None => message["content"] = json!(PLACEHOLDER), + _ => {} + } + message +} + +fn reply(protocol: Protocol, body: &Value) -> Reply { + match protocol { + Protocol::OpenAi => openai_reply(body), + Protocol::Anthropic => anthropic_reply(body), + } +} + +fn openai_reply(body: &Value) -> Reply { + let message = body + .pointer("/choices/0/message") + .cloned() + .unwrap_or(Value::Null); + let text = message + .get("content") + .and_then(Value::as_str) + .filter(|t| !t.is_empty()) + .map(|t| vec![(false, t.to_string())]) + .unwrap_or_default(); + let raw: Vec = message + .get("tool_calls") + .and_then(Value::as_array) + .map(|a| a.iter().take(32).cloned().collect()) + .unwrap_or_default(); + let calls = raw + .iter() + .enumerate() + .map(|(i, c)| Call { + id: c + .get("id") + .and_then(Value::as_str) + .map_or_else(|| format!("call-{i}"), str::to_string), + name: c + .pointer("/function/name") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(), + arguments: tool_arguments(c.pointer("/function/arguments")), + }) + .collect(); + let mut assistant = json!({"role": "assistant", "content": message.get("content").cloned().unwrap_or(Value::Null)}); + if !raw.is_empty() { + assistant["tool_calls"] = Value::Array(raw); + } + let stop = body + .pointer("/choices/0/finish_reason") + .and_then(Value::as_str) + .map(str::to_string); + Reply { + text, + calls, + assistant, + stop, + } +} + +fn anthropic_reply(body: &Value) -> Reply { + let content = body.get("content").cloned().unwrap_or(Value::Null); + let mut text = Vec::new(); + let mut calls = Vec::new(); + let assistant = match &content { + Value::Array(blocks) => { + let mut kept = Vec::new(); + for (i, block) in blocks.iter().take(128).enumerate() { + match block.get("type").and_then(Value::as_str) { + Some("text") => { + if let Some(t) = block + .get("text") + .and_then(Value::as_str) + .filter(|t| !t.trim().is_empty()) + { + text.push((false, t.to_string())); + } + kept.push(block.clone()); + } + Some("thinking") => { + let thought = block.get("thinking").or_else(|| block.get("text")); + if let Some(t) = thought + .and_then(Value::as_str) + .filter(|t| !t.trim().is_empty()) + { + text.push((true, t.to_string())); + } + kept.push(block.clone()); + } + Some("tool_use") if calls.len() < 32 => { + calls.push(Call { + id: block + .get("id") + .and_then(Value::as_str) + .map_or_else(|| format!("toolu-{i}"), str::to_string), + name: block + .get("name") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(), + arguments: match block.get("input") { + None | Some(Value::Null) => Ok(json!({})), + Some(v @ Value::Object(_)) => Ok(v.clone()), + Some(_) => Err("the tool arguments must be a JSON object".into()), + }, + }); + kept.push(block.clone()); + } + Some("tool_use") => {} + _ => kept.push(block.clone()), + } + } + json!({"role": "assistant", "content": kept}) + } + Value::String(s) => { + if !s.trim().is_empty() { + text.push((false, s.clone())); + } + json!({"role": "assistant", "content": content.clone()}) + } + _ => json!({"role": "assistant", "content": content.clone()}), + }; + let stop = body + .get("stop_reason") + .and_then(Value::as_str) + .map(str::to_string); + Reply { + text, + calls, + assistant, + stop, + } +} + +pub(crate) fn tool_entries(list: &Value) -> impl Iterator { + list.get("tools") + .and_then(Value::as_array) + .into_iter() + .flat_map(|a| a.iter().take(128)) + .filter_map(|t| { + let name = t.get("name")?.as_str()?; + (!HIDDEN_TOOLS.contains(&name)).then_some((name, t)) + }) +} + +fn schema_of(t: &Value) -> Value { + t.get("inputSchema") + .cloned() + .filter(Value::is_object) + .unwrap_or(json!({"type": "object", "properties": {}})) +} + +/// The tool list (MCP `tools/list` shape) as OpenAI function tools. Names go out through +/// [`to_wire`] (see `crates/assistant/src/tool_names.rs`). +pub fn openai_tools(list: &Value) -> Vec { + tool_entries(list) + .map(|(name, t)| { + json!({"type": "function", "function": { + "name": to_wire(name), + "description": t.get("description").and_then(Value::as_str).unwrap_or(""), + "parameters": schema_of(t), + }}) + }) + .collect() +} + +/// The tool list as Anthropic tools, names through [`to_wire`]. +pub fn anthropic_tools(list: &Value) -> Vec { + tool_entries(list) + .map(|(name, t)| { + json!({ + "name": to_wire(name), + "description": t.get("description").and_then(Value::as_str).unwrap_or(""), + "input_schema": schema_of(t), + }) + }) + .collect() +} + +/// `{base}/v1/{path}`, whether the base ends in `/v1` or not. +pub fn endpoint(base_url: &str, path: &str) -> String { + let base = base_url.trim_end_matches('/'); + if base.to_ascii_lowercase().ends_with("/v1") { + format!("{base}/{path}") + } else { + format!("{base}/v1/{path}") + } +} + +fn anthropic_headers(base_url: &str, key: Option<&str>) -> Result, String> { + let mut headers = vec![( + "anthropic-version".to_string(), + ANTHROPIC_VERSION.to_string(), + )]; + if let Some(k) = key { + if !key_safe_for(base_url) { + return Err("A key is only sent over https, or to this computer.".into()); + } + headers.push(("x-api-key".to_string(), k.to_string())); + } + Ok(headers) +} + +fn parse_models(v: &Value, name_field: Option<&str>) -> Vec { + v.get("data") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .take(500) + .filter_map(|m| { + let id = m.get("id").and_then(Value::as_str)?.to_string(); + let name = name_field + .and_then(|f| m.get(f)) + .and_then(Value::as_str) + .map_or_else(|| id.clone(), str::to_string); + Some(ModelInfo { + id, + name, + description: String::new(), + }) + }) + .collect() + }) + .unwrap_or_default() +} + +fn get_json( + http: &HttpFn, + url: String, + headers: Vec<(String, String)>, + key: Option<&str>, +) -> Result { + let req = HttpRequest { + method: "GET", + url, + headers, + body: None, + timeout_s: 15, + }; + let (status, bytes) = http(&req).map_err(|e| redact(&e, key))?; + let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + if status != 200 { + return Err(http_error(status, &v)); + } + Ok(v) +} + +fn bearer_headers(base_url: &str, key: Option<&str>) -> Result, String> { + let mut headers = Vec::new(); + if let Some(k) = key { + if !key_safe_for(base_url) { + return Err("A key is only sent over https, or to this computer.".into()); + } + headers.push(("Authorization".to_string(), format!("Bearer {k}"))); + } + Ok(headers) +} + +/// `GET {base}/models` of an OpenAI-compatible endpoint. +pub fn model_list( + http: &HttpFn, + base_url: &str, + key: Option<&str>, +) -> Result, String> { + let v = get_json( + http, + format!("{}/models", base_url.trim_end_matches('/')), + bearer_headers(base_url, key)?, + key, + )?; + Ok(parse_models(&v, None)) +} + +/// Ask an OpenAI-compatible endpoint for its models: how many, and whether `model` is one. +pub fn test_endpoint( + http: &HttpFn, + base_url: &str, + key: Option<&str>, + model: &str, +) -> Result { + let models = model_list(http, base_url, key)?; + let found = model.is_empty() || models.iter().any(|m| m.id == model); + Ok(if found { + format!("Connected. The endpoint lists {} models.", models.len()) + } else { + format!("Connected, but the endpoint does not list the model {model}.") + }) +} + +/// The models of an Anthropic-compatible endpoint (some have no such list). +pub fn anthropic_model_list( + http: &HttpFn, + base_url: &str, + key: Option<&str>, +) -> Result, String> { + let v = get_json( + http, + endpoint(base_url, "models"), + anthropic_headers(base_url, key)?, + key, + )?; + Ok(parse_models(&v, Some("display_name"))) +} + +/// Test an Anthropic-compatible endpoint with the smallest message there is. +pub fn test_anthropic_endpoint( + http: &HttpFn, + base_url: &str, + key: Option<&str>, + model: &str, +) -> Result { + let model = model.trim(); + if model.is_empty() { + return Err("Choose a model first.".into()); + } + let mut headers = anthropic_headers(base_url, key)?; + headers.push(("Content-Type".to_string(), "application/json".to_string())); + let body = json!({"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": "Hello"}]}); + let req = HttpRequest { + method: "POST", + url: endpoint(base_url, "messages"), + headers, + body: Some(body.to_string().into_bytes()), + timeout_s: TEST_TIMEOUT_S, + }; + let (status, bytes) = http(&req).map_err(|e| redact(&e, key))?; + let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + if status != 200 { + return Err(http_error(status, &v)); + } + let said: String = v + .get("content") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|b| b.get("text").and_then(Value::as_str)) + .collect::>() + .join("") + }) + .unwrap_or_default(); + Ok(if said.trim().is_empty() { + format!("The model {model} answered.") + } else { + said + }) +} + +/// A tool call's result as text for the model, and whether it failed. Long text is clipped. +pub fn tool_text(r: &Value) -> (String, bool) { + let failed = r.get("isError").and_then(Value::as_bool).unwrap_or(false); + let parts: Vec = r + .get("content") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .take(16) + .map(|c| match c.get("type").and_then(Value::as_str) { + Some("text") => c + .get("text") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(), + Some("image") => "[a picture of the view]".to_string(), + _ => String::new(), + }) + .collect() + }) + .unwrap_or_default(); + let mut text = parts.join("\n"); + if text.len() > MAX_TOOL_TEXT { + let mut cut = MAX_TOOL_TEXT; + while !text.is_char_boundary(cut) { + cut -= 1; + } + text.truncate(cut); + text.push_str("\n...(cut)"); + } + (text, failed) +} + +fn tool_title(name: &str, args: &Value) -> String { + match name { + "execute" => format!( + "execute: {}", + args.get("command").and_then(Value::as_str).unwrap_or("?") + ), + "batch" => { + let ids: Vec<&str> = args + .get("commands") + .and_then(Value::as_array) + .map(|c| { + c.iter() + .filter_map(|s| s.get("command").and_then(Value::as_str)) + .take(4) + .collect() + }) + .unwrap_or_default(); + format!("batch: {}", ids.join(", ")) + } + _ => name.to_string(), + } +} diff --git a/crates/assistant/src/api_tests.rs b/crates/assistant/src/api_tests.rs new file mode 100644 index 000000000..e4fd55d30 --- /dev/null +++ b/crates/assistant/src/api_tests.rs @@ -0,0 +1,673 @@ +//! API backend tests with a fake HTTP function: nothing here touches the network. + +use crate::api::*; +use crate::backend::{ + ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus, +}; +use crate::tool_names::{ToolNames, to_wire}; +use crate::turn::ToolRequest; +use serde_json::{Value, json}; +use std::sync::mpsc::channel; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +type Log = Arc>>; + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + match m.lock() { + Ok(g) => g, + Err(e) => e.into_inner(), + } +} + +/// A fake endpoint: `GET` answers an empty model list, the Nth `POST` is answered by `reply`. +fn fake(reply: impl Fn(usize) -> (u16, Value) + Send + Sync + 'static) -> (HttpFn, Log) { + let log: Log = Arc::default(); + let seen = log.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + let n = { + let mut l = lock(&seen); + l.push(r.clone()); + l.iter().filter(|x| x.method == "POST").count() + }; + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } + let (status, body) = reply(n); + Ok((status, body.to_string().into_bytes())) + }); + (http, log) +} + +fn posts(log: &Log) -> Vec { + lock(log) + .iter() + .filter(|r| r.method == "POST") + .map(|r| { + serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap_or(Value::Null) + }) + .collect() +} + +fn cfg(protocol: Protocol) -> ApiConfig { + ApiConfig { + protocol, + base_url: "http://127.0.0.1:1/v1".into(), + model: "m".into(), + key: None, + system_note: String::new(), + } +} + +/// A host that answers every tool call with `text`; the names it was asked are kept. +fn host(text: &'static str) -> (StartContext, Arc>>) { + let (tx, rx) = channel::(); + let names = Arc::new(Mutex::new(Vec::new())); + let kept = names.clone(); + std::thread::spawn(move || { + for r in rx { + lock(&kept).push(r.name.clone()); + let _ = r + .reply + .send(json!({"content": [{"type": "text", "text": text}], "isError": false})); + } + }); + ( + StartContext { + work_dir: std::path::PathBuf::new(), + tools: Some(tx), + }, + names, + ) +} + +/// Poll until `done` matches an event, giving up after ten seconds. +fn run_until(b: &mut ApiBackend, done: impl Fn(&Event) -> bool) -> Result, String> { + let end = Instant::now() + Duration::from_secs(10); + let mut all = Vec::new(); + while Instant::now() < end { + for e in b.poll() { + let stop = done(&e); + all.push(e); + if stop { + return Ok(all); + } + } + std::thread::sleep(Duration::from_millis(5)); + } + Err(format!("no end of turn; saw {all:?}")) +} + +fn ended(e: &Event) -> bool { + matches!(e, Event::TurnEnded { .. }) +} + +fn say(b: &mut ApiBackend, t: &str) { + b.prompt(&[PromptPart::Text(t.into())]); +} + +fn openai_text(t: &str) -> Value { + json!({"choices": [{"message": {"role": "assistant", "content": t}}]}) +} + +fn first_mcp_name() -> Result { + let list = pcbcraft_mcp::tool_list(); + list["tools"][0]["name"] + .as_str() + .map(str::to_string) + .ok_or_else(|| "no tools".to_string()) +} + +/// The first tool's name as a model sees and uses it. +fn first_tool_name() -> Result { + first_mcp_name().map(|n| to_wire(&n)) +} + +fn openai_call_of(name: &str, n: usize) -> Value { + let calls: Vec = + (0..n).map(|i| json!({"id": format!("c{i}"), "type": "function", "function": {"name": name, "arguments": "{}"}})).collect(); + json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": calls}}]}) +} + +#[test] +fn an_openai_reply_with_two_tool_calls_runs_both_through_the_tools_channel_and_sends_their_results_back() +-> Result<(), String> { + let name = first_tool_name()?; + let mcp = first_mcp_name()?; + let n2 = name.clone(); + let (http, log) = fake(move |n| { + ( + 200, + if n == 1 { + openai_call_of(&n2, 2) + } else { + openai_text("done") + }, + ) + }); + let (ctx, names) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::OpenAi), ctx, http)?; + say(&mut b, "look"); + run_until(&mut b, ended)?; + assert_eq!(*lock(&names), vec![mcp.clone(), mcp]); + let sent = posts(&log); + assert_eq!(sent.len(), 2); + let tool_msgs = sent[1]["messages"] + .as_array() + .ok_or("no messages")? + .iter() + .filter(|m| m["role"] == "tool") + .count(); + assert_eq!(tool_msgs, 2); + assert_eq!(sent[0]["messages"][0]["role"], "system"); + Ok(()) +} + +#[test] +fn an_anthropic_reply_sends_all_tool_results_in_one_user_message() -> Result<(), String> { + let name = first_tool_name()?; + let n2 = name.clone(); + let (http, log) = fake(move |n| { + if n == 1 { + ( + 200, + json!({"content": [ + {"type": "tool_use", "id": "a", "name": n2, "input": {}}, + {"type": "tool_use", "id": "b", "name": n2, "input": {}}]}), + ) + } else { + (200, json!({"content": [{"type": "text", "text": "done"}]})) + } + }); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::Anthropic), ctx, http)?; + say(&mut b, "look"); + run_until(&mut b, ended)?; + let sent = posts(&log); + let results = sent[1]["messages"] + .as_array() + .ok_or("no messages")? + .iter() + .filter(|m| m["role"] == "user" && m["content"].is_array()) + .count(); + assert_eq!(results, 1); + assert_eq!( + sent[1]["messages"][2]["content"].as_array().map(Vec::len), + Some(2) + ); + assert_eq!( + sent[0]["system"].as_str().map(|s| s.contains("PCBCraft")), + Some(true) + ); + let versioned = lock(&log).iter().filter(|r| r.method == "POST").all(|r| { + r.headers + .iter() + .any(|(k, v)| k == "anthropic-version" && v == "2023-06-01") + }); + assert!(versioned); + Ok(()) +} + +#[test] +fn the_turn_stops_after_twenty_four_requests_and_tells_the_model() -> Result<(), String> { + let name = first_tool_name()?; + let (http, log) = fake(move |_| (200, openai_call_of(&name, 1))); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::OpenAi), ctx, http)?; + say(&mut b, "loop"); + let events = run_until(&mut b, ended)?; + assert_eq!(posts(&log).len(), 24); + assert!( + matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "max_turn_requests") + ); + assert!( + events + .iter() + .any(|e| matches!(e, Event::Note(n) if n == "request 24 of 24")) + ); + // The next message carries the stop note, so the model reports instead of carrying on. + say(&mut b, "again"); + let end = Instant::now() + Duration::from_secs(10); + while posts(&log).len() < 25 && Instant::now() < end { + std::thread::sleep(Duration::from_millis(5)); + } + let sent = posts(&log); + let last = sent.last().ok_or("no request")?.to_string(); + assert!(last.contains("Stop calling tools now")); + Ok(()) +} + +#[test] +fn a_tool_result_longer_than_the_cap_is_clipped_with_a_note() { + let long = "x".repeat(MAX_TOOL_TEXT + 500); + let (text, failed) = + tool_text(&json!({"content": [{"type": "text", "text": long}], "isError": false})); + assert!(!failed); + assert!(text.len() < MAX_TOOL_TEXT + 20); + assert!(text.ends_with("(cut)")); +} + +#[test] +fn cancel_between_requests_ends_the_turn_with_reason_cancelled() -> Result<(), String> { + let name = first_tool_name()?; + let (http, log) = fake(move |_| (200, openai_call_of(&name, 1))); + let (tx, rx) = channel::(); + let (seen_tx, seen_rx) = channel::<()>(); + std::thread::spawn(move || { + for r in rx { + let _ = seen_tx.send(()); + std::thread::sleep(Duration::from_millis(150)); + let _ = r + .reply + .send(json!({"content": [{"type": "text", "text": "late"}], "isError": false})); + } + }); + let ctx = StartContext { + work_dir: std::path::PathBuf::new(), + tools: Some(tx), + }; + let mut b = ApiBackend::start(cfg(Protocol::OpenAi), ctx, http)?; + say(&mut b, "go"); + seen_rx + .recv_timeout(Duration::from_secs(10)) + .map_err(|e| e.to_string())?; + b.cancel(); + let events = run_until(&mut b, ended)?; + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "cancelled")); + assert_eq!(posts(&log).len(), 1); + Ok(()) +} + +#[test] +fn a_401_reply_becomes_a_plain_sentence_without_the_key_in_it() -> Result<(), String> { + let (http, _) = fake(|_| { + ( + 401, + json!({"error": {"message": "Incorrect API key provided"}}), + ) + }); + let (ctx, _) = host("ok"); + let mut c = cfg(Protocol::OpenAi); + c.key = Some("sk-secret-123".into()); + let mut b = ApiBackend::start(c, ctx, http)?; + say(&mut b, "hi"); + let events = run_until(&mut b, ended)?; + let err = events + .iter() + .find_map(|e| { + if let Event::Error(t) = e { + Some(t.clone()) + } else { + None + } + }) + .ok_or("no error")?; + assert!(err.starts_with("HTTP 401")); + assert!(err.contains("Incorrect API key provided")); + assert!(!err.contains("sk-secret-123")); + let body = http_error(401, &json!({"error": {"message": "bad"}})); + assert!(!body.contains("sk-")); + Ok(()) +} + +#[test] +fn a_key_never_goes_to_a_plain_http_address_off_this_computer() { + assert!(key_safe_for("https://api.example.com/v1")); + assert!(key_safe_for("http://localhost:11434/v1")); + assert!(key_safe_for("http://127.0.0.1:8080")); + assert!(!key_safe_for("http://192.168.1.5/v1")); + assert!(!key_safe_for("http://localhost.evil.example/v1")); + assert!(!key_safe_for("http://localhost@evil.example/v1")); +} + +#[test] +fn the_tool_list_maps_every_registry_command_to_a_function_tool_with_its_schema() +-> Result<(), String> { + let list = pcbcraft_mcp::tool_list(); + let source = list["tools"].as_array().ok_or("no tools")?; + let open = openai_tools(&list); + let anth = anthropic_tools(&list); + assert_eq!(open.len(), source.len().min(128)); + assert_eq!(anth.len(), open.len()); + for (i, t) in open.iter().enumerate() { + assert_eq!(t["type"], "function"); + assert_eq!( + t["function"]["name"].as_str(), + source[i]["name"].as_str().map(to_wire).as_deref() + ); + assert_eq!(t["function"]["parameters"], source[i]["inputSchema"]); + assert_eq!(anth[i]["input_schema"], source[i]["inputSchema"]); + } + Ok(()) +} + +#[test] +fn model_list_reads_the_data_ids() -> Result<(), String> { + let (http, _) = fake(|_| (200, Value::Null)); + let http2: HttpFn = Arc::new(move |r: &HttpRequest| { + assert_eq!(r.url, "http://h/v1/models"); + http(r)?; + Ok(( + 200, + br#"{"data":[{"id":"a"},{"id":"b"},{"nope":1}]}"#.to_vec(), + )) + }); + let models = model_list(&http2, "http://h/v1", None)?; + assert_eq!( + models.iter().map(|m| m.id.as_str()).collect::>(), + vec!["a", "b"] + ); + Ok(()) +} + +#[test] +fn test_anthropic_endpoint_returns_the_model_text_on_200_and_the_error_sentence_otherwise() +-> Result<(), String> { + let ok: HttpFn = Arc::new(|r: &HttpRequest| { + assert_eq!(r.url, "https://h/v1/messages"); + Ok(( + 200, + br#"{"content":[{"type":"text","text":"Hi there"}]}"#.to_vec(), + )) + }); + assert_eq!( + test_anthropic_endpoint(&ok, "https://h", None, "m")?, + "Hi there" + ); + let bad: HttpFn = Arc::new(|_| Ok((404, br#"{"error":{"message":"no such model"}}"#.to_vec()))); + let err = test_anthropic_endpoint(&bad, "https://h", None, "m") + .err() + .ok_or("expected an error")?; + assert!(err.starts_with("HTTP 404")); + assert!(err.contains("no such model")); + Ok(()) +} + +#[test] +fn a_302_reply_is_an_error_and_no_second_request_follows() -> Result<(), String> { + let (http, log) = fake(|_| (302, json!({}))); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::OpenAi), ctx, http)?; + say(&mut b, "hi"); + let events = run_until(&mut b, ended)?; + assert!( + events + .iter() + .any(|e| matches!(e, Event::Error(t) if t.starts_with("HTTP 302"))) + ); + assert_eq!(posts(&log).len(), 1); + Ok(()) +} + +fn every_name_in(body: &Value, protocol: Protocol) -> Vec { + let tools = body["tools"].as_array().cloned().unwrap_or_default(); + tools + .iter() + .filter_map(|t| match protocol { + Protocol::OpenAi => t["function"]["name"].as_str(), + Protocol::Anthropic => t["name"].as_str(), + }) + .map(str::to_string) + .collect() +} + +fn is_hosted_legal(name: &str) -> bool { + (1..=64).contains(&name.len()) + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +#[test] +fn every_outgoing_tool_name_matches_the_hosted_name_pattern() -> Result<(), String> { + for protocol in [Protocol::OpenAi, Protocol::Anthropic] { + let (http, log) = fake(move |_| match protocol { + Protocol::OpenAi => (200, openai_text("hi")), + Protocol::Anthropic => (200, json!({"content": [{"type": "text", "text": "hi"}]})), + }); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(protocol), ctx, http)?; + say(&mut b, "hello"); + run_until(&mut b, ended)?; + let sent = posts(&log); + let names = every_name_in(sent.first().ok_or("no request")?, protocol); + assert!(!names.is_empty()); + assert!( + names.iter().any(|n| n.contains("__")), + "no dotted tool seen" + ); + if let Some(bad) = names.iter().find(|n| !is_hosted_legal(n)) { + return Err(format!("{protocol:?} sent the illegal name {bad}")); + } + } + Ok(()) +} + +#[test] +fn two_different_mcp_tool_names_never_share_a_wire_name() -> Result<(), String> { + ToolNames::from_list(&pcbcraft_mcp::tool_list())?; + let clash = json!({"tools": [{"name": "a.b"}, {"name": "a__b"}]}); + let err = ToolNames::from_list(&clash) + .err() + .ok_or("no collision found")?; + assert!(err.contains("a.b") && err.contains("a__b")); + Ok(()) +} + +#[test] +fn a_reply_that_calls_the_wire_name_runs_the_dotted_tool() -> Result<(), String> { + for protocol in [Protocol::OpenAi, Protocol::Anthropic] { + let wire = to_wire("library.search"); + assert_ne!(wire, "library.search"); + let (http, _) = fake(move |n| match (n, protocol) { + (1, Protocol::OpenAi) => (200, openai_call_of(&wire, 1)), + (1, Protocol::Anthropic) => ( + 200, + json!({"content": [{"type": "tool_use", "id": "a", "name": wire, "input": {}}]}), + ), + (_, Protocol::OpenAi) => (200, openai_text("done")), + (_, Protocol::Anthropic) => { + (200, json!({"content": [{"type": "text", "text": "done"}]})) + } + }); + let (ctx, names) = host("ok"); + let mut b = ApiBackend::start(cfg(protocol), ctx, http)?; + say(&mut b, "find"); + let events = run_until(&mut b, ended)?; + assert_eq!(*lock(&names), vec!["library.search".to_string()]); + let titled = events + .iter() + .any(|e| matches!(e, Event::Tool { title: Some(t), .. } if t == "library.search")); + assert!(titled, "the UI should show the MCP name"); + } + Ok(()) +} + +#[test] +fn the_assistant_message_in_history_keeps_the_wire_name() -> Result<(), String> { + let wire = to_wire("library.search"); + let used = wire.clone(); + let (http, log) = fake(move |n| { + if n == 1 { + (200, openai_call_of(&used, 1)) + } else { + (200, openai_text("done")) + } + }); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::OpenAi), ctx, http)?; + say(&mut b, "find"); + run_until(&mut b, ended)?; + let sent = posts(&log); + let second = sent.get(1).ok_or("no second request")?; + let carried = second["messages"] + .as_array() + .ok_or("no messages")? + .iter() + .find(|m| m["role"] == "assistant") + .and_then(|m| m["tool_calls"][0]["function"]["name"].as_str()); + assert_eq!(carried, Some(wire.as_str())); + Ok(()) +} + +#[test] +fn a_model_that_invents_a_name_gets_unknown_tool() -> Result<(), String> { + let (http, _) = fake(|n| { + if n == 1 { + (200, openai_call_of("library__does_not_exist", 1)) + } else { + (200, openai_text("done")) + } + }); + let (ctx, names) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::OpenAi), ctx, http)?; + say(&mut b, "go"); + let events = run_until(&mut b, ended)?; + assert!(lock(&names).is_empty()); + let failed = events.iter().any(|e| { + matches!(e, Event::Tool { status: Some(ToolStatus::Failed), output: Some(o), .. } + if o.starts_with("unknown tool")) + }); + assert!(failed); + Ok(()) +} + +#[test] +fn to_wire_keeps_legal_names_and_clips_long_ones_the_same_way_each_time() { + assert_eq!(to_wire("batch"), "batch"); + assert_eq!(to_wire("a-b_c9"), "a-b_c9"); + assert_eq!(to_wire("library.save"), "library__save"); + assert_eq!(to_wire("a b"), "a_b"); + let long = format!("{}.tail", "x".repeat(80)); + let once = to_wire(&long); + assert_eq!(once.len(), 64); + assert_eq!(once, to_wire(&long)); + assert!(is_hosted_legal(&once)); + let other = format!("{}.tail2", "x".repeat(80)); + assert_ne!(once, to_wire(&other)); +} + +fn openai_stopped(text: &str, reason: &str) -> Value { + json!({"choices": [{"finish_reason": reason, + "message": {"role": "assistant", "content": text}}]}) +} + +fn notes_of(events: &[Event]) -> Vec<&str> { + events + .iter() + .filter_map(|e| match e { + Event::Note(n) if !n.starts_with("request ") => Some(n.as_str()), + _ => None, + }) + .collect() +} + +#[test] +fn an_openai_reply_cut_by_length_shows_a_note_and_ends_the_turn_with_that_reason() +-> Result<(), String> { + let (http, _) = fake(|_| (200, openai_stopped("The board has", "length"))); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::OpenAi), ctx, http)?; + say(&mut b, "describe"); + let events = run_until(&mut b, ended)?; + let notes = notes_of(&events); + assert_eq!(notes.len(), 1); + assert!(notes[0].contains("length limit")); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "length")); + Ok(()) +} + +#[test] +fn an_anthropic_reply_with_max_tokens_shows_a_note() -> Result<(), String> { + let (http, _) = fake(|_| { + ( + 200, + json!({"stop_reason": "max_tokens", "content": [{"type": "text", "text": "The"}]}), + ) + }); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::Anthropic), ctx, http)?; + say(&mut b, "describe"); + let events = run_until(&mut b, ended)?; + assert_eq!(notes_of(&events).len(), 1); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "max_tokens")); + Ok(()) +} + +#[test] +fn a_content_filter_or_refusal_stop_shows_a_note() -> Result<(), String> { + for (protocol, reason) in [ + (Protocol::OpenAi, "content_filter"), + (Protocol::Anthropic, "refusal"), + ] { + let (http, _) = fake(move |_| match protocol { + Protocol::OpenAi => (200, openai_stopped("", reason)), + Protocol::Anthropic => (200, json!({"stop_reason": reason, "content": []})), + }); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(protocol), ctx, http)?; + say(&mut b, "go"); + let events = run_until(&mut b, ended)?; + assert_eq!(notes_of(&events).len(), 1, "{reason}"); + let ended_with = + matches!(events.last(), Some(Event::TurnEnded { reason: r }) if r == reason); + assert!(ended_with, "{reason}"); + } + Ok(()) +} + +#[test] +fn a_normal_stop_ends_with_an_empty_reason_and_no_note() -> Result<(), String> { + for reply in [ + openai_stopped("done", "stop"), + json!({"stop_reason": "end_turn", "content": [{"type": "text", "text": "done"}]}), + openai_text("done"), + ] { + let protocol = if reply.get("choices").is_some() { + Protocol::OpenAi + } else { + Protocol::Anthropic + }; + let (http, _) = fake(move |_| (200, reply.clone())); + let (ctx, _) = host("ok"); + let mut b = ApiBackend::start(cfg(protocol), ctx, http)?; + say(&mut b, "go"); + let events = run_until(&mut b, ended)?; + assert!(notes_of(&events).is_empty()); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason.is_empty())); + } + Ok(()) +} + +#[test] +fn a_cut_reply_with_tool_calls_runs_none_of_them() -> Result<(), String> { + let name = first_tool_name()?; + let (http, log) = fake(move |n| { + if n == 1 { + let mut r = openai_call_of(&name, 2); + r["choices"][0]["finish_reason"] = json!("length"); + (200, r) + } else { + (200, openai_text("ok then")) + } + }); + let (ctx, names) = host("ok"); + let mut b = ApiBackend::start(cfg(Protocol::OpenAi), ctx, http)?; + say(&mut b, "go"); + let events = run_until(&mut b, ended)?; + assert!(lock(&names).is_empty()); + assert_eq!(notes_of(&events).len(), 1); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "length")); + // The next message still works: the history holds no call without an answer. + say(&mut b, "smaller"); + run_until(&mut b, ended)?; + let sent = posts(&log); + let second = sent.get(1).ok_or("no second request")?; + let dangling = second["messages"] + .as_array() + .ok_or("no messages")? + .iter() + .any(|m| m.get("tool_calls").is_some()); + assert!(!dangling); + Ok(()) +} diff --git a/crates/assistant/src/backend.rs b/crates/assistant/src/backend.rs new file mode 100644 index 000000000..c1b5ca034 --- /dev/null +++ b/crates/assistant/src/backend.rs @@ -0,0 +1,288 @@ +// Adapted from SolidCraft (MIT OR Apache-2.0), commit 32558d0a: +// crates/ui-egui/src/agent_chat/backend.rs + +use serde_json::Value; +use std::sync::Arc; + +/// One part of a message to the agent. +/// +/// # Dependencies +/// - none yet +/// +/// # Rules +/// - This enum represents a part of a message sent to the agent. +/// - `Text` is plain text content. +/// - `Picture` is an image sent to the agent (PNG format). +/// - `Document` is a PDF document sent to the agent. +/// +/// # Do not +/// - Add new variants without updating the `tool_list` and `tool_names` logic. +#[derive(Clone, Debug, PartialEq)] +pub enum PromptPart { + Text(String), + /// A picture of the design (PNG), sent only to agents that take images. + Picture { + mime: String, + base64: String, + }, + /// A file the agent reads as a document (a PDF), sent only to agents that take documents. + Document { + name: String, + /// Where it is on this machine (a `file://` link). + uri: String, + mime: String, + base64: String, + }, +} + +/// What a backend reports to the pane. +/// +/// # Dependencies +/// - none yet +/// +/// # Rules +/// - This enum represents events reported by the backend to the UI pane. +/// - `Documents` indicates if the agent accepts document inputs. +/// - `Ready` signals the agent is prepared to receive messages. +/// - `Text` streams text output from the agent. +/// - `Tool` reports tool calls made by the agent. +/// +/// # Do not +/// - Add new variants without updating the event handling logic. +#[derive(Clone, Debug, PartialEq)] +pub enum Event { + /// Whether the agent takes documents (PDFs) in a message; sent before [`Event::Ready`]. + Documents(bool), + /// Ready for a message. `agent`: its name and version; `images`: it takes pictures. + Ready { agent: String, images: bool }, + /// Text it streams (`thought`: its reasoning, shown dimmed). + Text { thought: bool, text: String }, + /// A new tool call, or news about one. + Tool { + id: String, + title: Option, + kind: Option, + status: Option, + output: Option, + }, + /// A short progress note (such as `request 2 of 24`). + Note(String), + /// Its plan, replaced whole: each entry with its status. + Plan(Vec<(String, String)>), + /// It asks before running something of its own; answered with [`ChatBackend::answer_permission`]. + Permission { + key: u64, + title: String, + options: Vec, + }, + /// It needs the user to sign in; `methods` are its own ways to do so. + AuthRequired { methods: Vec }, + /// What it says about its login. + AuthStatus(String), + /// Its own modes and the current one. + Modes { + current: String, + available: Vec<(String, String)>, + }, + /// Its models (empty `available`: only the current one changed). + Models { + current: String, + available: Vec, + }, + /// The message is answered (`reason`: why it stopped, empty for a normal end). + TurnEnded { reason: String }, + /// Something failed; the backend is still running unless [`Event::Exited`] follows. + Error(String), + /// It ended; its last error output. + Exited { tail: Vec }, +} + +/// What a backend gets to start. +pub struct StartContext { + /// Its working folder: an empty folder of the app's own, not the user's files. + pub work_dir: std::path::PathBuf, + /// Where in-process tool calls go, for backends that run their own tool loop. + pub tools: Option>, +} + +/// A chat backend. Methods never block the frame; replies arrive through [`ChatBackend::poll`]. +pub trait ChatBackend { + /// What arrived since the last call. + fn poll(&mut self) -> Vec; + /// Send a message (the pane only sends one after [`Event::Ready`] and while no turn runs). + fn prompt(&mut self, parts: &[PromptPart]); + /// Stop the message being answered; open permission questions count as cancelled. + fn cancel(&mut self); + /// Start a fresh conversation on the running backend (no restart); [`Event::Ready`] follows. + fn new_session(&mut self); + /// Answer an [`Event::Permission`] with one of its options (`None`: cancelled). + fn answer_permission(&mut self, key: u64, option: Option<&str>); + /// Ask the backend to sign in by itself with one of its methods (it opens the browser). + fn authenticate(&mut self, method: &str); + /// Use one of the models it reported in [`Event::Models`]. + fn set_model(&mut self, model: &str); + /// Switch to one of the modes it reported in [`Event::Modes`]. + fn set_mode(&mut self, mode: &str); + /// Its process, for status and tests. + fn pid(&self) -> Option { + None + } + /// End it and everything it started. `wait`: block until done (quitting). + fn shutdown(&mut self, wait: bool); +} + +/// One HTTP request of the API backend (the desktop host sends it; nothing else in the chat +/// reaches the network). +#[derive(Clone, Debug, PartialEq)] +pub struct HttpRequest { + pub method: &'static str, + pub url: String, + pub headers: Vec<(String, String)>, + pub body: Option>, + pub timeout_s: u64, +} + +/// Sends an [`HttpRequest`]: the status and the body, or why it failed. +pub type HttpFn = Arc Result<(u16, Vec), String> + Send + Sync>; + +/// The system keychain (the desktop host's), for API keys: never in the preferences. +pub trait Secrets: Send + Sync { + fn get(&self, id: &str) -> Result, String>; + fn set(&self, id: &str, secret: &str) -> Result<(), String>; + fn delete(&self, id: &str) -> Result<(), String>; +} + +/// One way to log in that the agent offers. +#[derive(Clone, Debug, PartialEq)] +pub struct AuthMethod { + pub id: String, + pub name: String, + pub description: String, + pub kind: AuthKind, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum AuthKind { + Agent, + Terminal { + args: Vec, + command: Option<(String, Vec)>, + }, + EnvVar { + vars: Vec, + }, +} + +/// One model the agent offers. +#[derive(Clone, Debug, PartialEq)] +pub struct ModelInfo { + pub id: String, + pub name: String, + pub description: String, +} + +/// A tool call's state as the agent reports it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToolStatus { + Pending, + InProgress, + Completed, + Failed, +} + +/// One choice of a permission request. +#[derive(Clone, Debug, PartialEq)] +pub struct PermissionOption { + pub id: String, + pub name: String, + /// `allow_once`, `allow_always`, `reject_once` or `reject_always`. + pub kind: String, +} + +/// Standard base64 with padding (RFC 4648), for pictures in messages. +pub fn base64(data: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let b = [ + chunk.first().copied().unwrap_or(0), + chunk.get(1).copied().unwrap_or(0), + chunk.get(2).copied().unwrap_or(0), + ]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + for (i, shift) in [18u32, 12, 6, 0].into_iter().enumerate() { + if i <= chunk.len() { + let idx = ((n >> shift) & 63) as usize; + let ch = T.get(idx).copied().unwrap_or(b'A'); + out.push(char::from(ch)); + } else { + out.push('='); + } + } + } + out +} + +/// A message's parts as ACP content blocks. +pub fn content_blocks(parts: &[PromptPart]) -> Vec { + parts + .iter() + .map(|p| match p { + PromptPart::Text(t) => serde_json::json!({"type": "text", "text": t}), + PromptPart::Picture { mime, base64 } => { + serde_json::json!({"type": "image", "mimeType": mime, "data": base64}) + } + PromptPart::Document { uri, mime, base64, .. } => { + serde_json::json!({"type": "resource", "resource": {"uri": uri, "mimeType": mime, "blob": base64}}) + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base64_matches_the_rfc_examples() { + for (i, o) in [ + ("", ""), + ("f", "Zg=="), + ("fo", "Zm8="), + ("foo", "Zm9v"), + ("foob", "Zm9vYg=="), + ("fooba", "Zm9vYmE="), + ("foobar", "Zm9vYmFy"), + ] { + assert_eq!(base64(i.as_bytes()), o); + } + } + + #[test] + fn pictures_go_as_image_blocks() { + let b = content_blocks(&[ + PromptPart::Text("hi".into()), + PromptPart::Picture { + mime: "image/png".into(), + base64: "AA==".into(), + }, + ]); + assert_eq!(b[1]["type"], "image"); + assert_eq!(b[1]["mimeType"], "image/png"); + } + + #[test] + fn documents_go_as_embedded_resources() { + let doc = PromptPart::Document { + name: "brief.pdf".into(), + uri: "file:///a/brief.pdf".into(), + mime: "application/pdf".into(), + base64: "AA==".into(), + }; + let b = content_blocks(&[doc]); + assert_eq!(b[0]["type"], "resource"); + assert_eq!(b[0]["resource"]["uri"], "file:///a/brief.pdf"); + assert_eq!(b[0]["resource"]["mimeType"], "application/pdf"); + assert_eq!(b[0]["resource"]["blob"], "AA=="); + } +} diff --git a/crates/assistant/src/connections.rs b/crates/assistant/src/connections.rs new file mode 100644 index 000000000..50aa6fdaa --- /dev/null +++ b/crates/assistant/src/connections.rs @@ -0,0 +1,173 @@ +//! Saved model connections and the checks on their addresses. +//! +//! Context: Settings keeps a list of [`Connection`]s in the preferences file. A connection never +//! holds its key: the key lives in the system keychain under [`key_id`], and `has_key` only +//! records that one is stored. +//! Rules: adapted from SolidCraft (MIT OR Apache-2.0), commit 32558d0a, +//! `crates/ui-egui/src/agent_chat/agents.rs` (presets, URL checks, ids). An address has a scheme, +//! no query or fragment, no trailing slash, and at most 2048 bytes. +//! Do not: write a key into a [`Connection`], a log line or the design file. + +use crate::api::{ApiConfig, Protocol}; +use serde::{Deserialize, Serialize}; + +/// Longest address kept. +const MAX_URL: usize = 2048; + +/// One saved model endpoint. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Connection { + /// Stable id, also the keychain entry name (see `key_id`). + pub id: String, + /// The name shown in lists. + pub name: String, + /// The wire format it uses. + pub protocol: Protocol, + /// The server address, as `normalize_url` leaves it. + pub base_url: String, + /// The model name to ask for. + pub model: String, + /// True when a key is stored in the keychain for this connection. + #[serde(default)] + pub has_key: bool, + /// True when the model takes pictures (Attach view sends one). + #[serde(default)] + pub images: bool, +} + +/// A starting point offered by the Add connection dialog. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Preset { + /// The name shown in the preset list. + pub name: &'static str, + /// The address it fills in (empty for a custom one). + pub base_url: &'static str, + /// The wire format it uses. + pub protocol: Protocol, +} + +/// Local servers first, then a custom address of each protocol. +pub const PRESETS: &[Preset] = &[ + Preset { + name: "Local model server", + base_url: "http://localhost:11434/v1", + protocol: Protocol::OpenAi, + }, + Preset { + name: "Second local server", + base_url: "http://localhost:1234/v1", + protocol: Protocol::OpenAi, + }, + Preset { + name: "Custom OpenAI-compatible address", + base_url: "", + protocol: Protocol::OpenAi, + }, + Preset { + name: "Custom Anthropic-compatible address", + base_url: "", + protocol: Protocol::Anthropic, + }, +]; + +/// Check and tidy an address: a scheme is required, a query or fragment is refused, a trailing +/// slash is dropped. +pub fn normalize_url(url: &str) -> Result { + let url = url.trim(); + if url.len() > MAX_URL { + return Err(format!("The address is longer than {MAX_URL} bytes.")); + } + let lower = url.to_ascii_lowercase(); + if !(lower.starts_with("http://") || lower.starts_with("https://")) { + return Err("The address must start with http:// or https://.".into()); + } + if url.contains('?') || url.contains('#') { + return Err("The address must not contain a query or a fragment.".into()); + } + let tidy = url.trim_end_matches('/'); + if tidy.len() <= "https://".len() && tidy.ends_with("//") { + return Err("The address has no host.".into()); + } + Ok(tidy.to_string()) +} + +/// A fresh id starting with `prefix` that no connection in `existing` has. +pub fn new_id(existing: &[Connection], prefix: &str) -> String { + (1u32..) + .map(|n| format!("{prefix}-{n}")) + .find(|id| !existing.iter().any(|c| &c.id == id)) + .unwrap_or_else(|| format!("{prefix}-0")) +} + +/// The keychain entry name for a connection's key. +pub fn key_id(connection_id: &str) -> String { + format!("connection:{connection_id}") +} + +/// The settings the API backend starts with for `connection` and its key. +pub fn config_for(connection: &Connection, key: Option, system_note: String) -> ApiConfig { + ApiConfig { + protocol: connection.protocol, + base_url: connection.base_url.clone(), + model: connection.model.clone(), + key, + system_note, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalize_url_rejects_queries_fragments_and_missing_schemes() { + assert!(normalize_url("localhost:11434/v1").is_err()); + assert!(normalize_url("http://a/v1?x=1").is_err()); + assert!(normalize_url("http://a/v1#top").is_err()); + assert_eq!( + normalize_url(" http://localhost:11434/v1/ "), + Ok("http://localhost:11434/v1".into()) + ); + assert!(normalize_url(&format!("https://{}", "a".repeat(2100))).is_err()); + } + + #[test] + fn key_safe_for_allows_https_anywhere_and_http_on_loopback_only() { + use crate::api::key_safe_for; + assert!(key_safe_for("https://api.example.com/v1")); + assert!(key_safe_for("http://localhost:11434/v1")); + assert!(key_safe_for("http://127.0.0.1:1234/v1")); + assert!(!key_safe_for("http://10.0.0.5:1234/v1")); + } + + #[test] + fn new_id_skips_ids_in_use() { + let c = |id: &str| Connection { + id: id.into(), + name: String::new(), + protocol: Protocol::OpenAi, + base_url: String::new(), + model: String::new(), + has_key: false, + images: false, + }; + assert_eq!(new_id(&[c("api-1"), c("api-2")], "api"), "api-3"); + } + + #[test] + fn a_connection_serializes_without_any_key_text() -> Result<(), String> { + let c = Connection { + id: "api-1".into(), + name: "Home".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:11434/v1".into(), + model: "m".into(), + has_key: true, + images: false, + }; + let text = serde_json::to_string(&c).map_err(|e| e.to_string())?; + assert!(text.contains("\"has_key\":true")); + assert!(!text.contains("sk-secret")); + Ok(()) + } +} diff --git a/crates/assistant/src/context.rs b/crates/assistant/src/context.rs new file mode 100644 index 000000000..b3a3d5de8 --- /dev/null +++ b/crates/assistant/src/context.rs @@ -0,0 +1,283 @@ +//! What the model is told about the open design with each message. +//! +//! Context: the pane builds a [`Context`] from the design summary (`design.summary`), the active +//! tab and the selection, and sends [`note`] before the user's words. The first message of a +//! conversation carries the whole note; later ones carry only what changed. +//! Rules: the note is plain text under [`MAX_NOTE`] characters, built from the design only (no +//! file paths, no keys); a picture is sent only to a connection that takes pictures and is at +//! most [`MAX_PICTURE_BYTES`]. +//! Do not: put the whole project in the note; the model calls `inspect_design` for that. + +use crate::backend::PromptPart; +use serde_json::Value; + +/// Longest context note, in characters. +pub const MAX_NOTE: usize = 2000; +/// Largest picture sent, in bytes of PNG. +pub const MAX_PICTURE_BYTES: usize = 4 * 1024 * 1024; + +/// The selected object. +#[derive(Clone, Debug, PartialEq)] +pub struct Selection { + /// What it is, for example a resistor. + pub kind: String, + /// Its stable id. + pub id: u64, + /// Its reference, if it has one. + pub reference: String, + /// Its value, if it has one. + pub value: String, + /// The nets it touches. + pub net: String, + /// Where it sits, in millimetres. + pub position: Option<(f64, f64)>, + /// Its layer, if it has one. + pub layer: String, +} + +/// What the pane knows when the user presses Send. +#[derive(Clone, Debug)] +pub struct Context { + /// The view. + pub tab: &'static str, + /// What is selected, if anything. + pub selection: Option, + /// The output of `design.summary`. + pub summary: Value, +} + +/// What an earlier message already told the model. +#[derive(Clone, Debug, PartialEq)] +pub struct Sent { + /// The design revision. + pub revision: u64, + /// The id of the selected object. + pub selection: Option, + /// The view. + pub tab: &'static str, +} + +impl Context { + /// What a message built from this context tells the model, for the next delta. + pub fn sent(&self) -> Sent { + Sent { + revision: self.summary["revision"].as_u64().unwrap_or(0), + selection: self.selection.as_ref().map(|s| s.id), + tab: self.tab, + } + } +} + +fn selection_line(s: &Selection) -> String { + let mut line = format!("Selected: {}", s.kind); + if !s.reference.is_empty() { + line.push_str(&format!(" {}", s.reference)); + } + if !s.value.is_empty() { + line.push_str(&format!(" ({})", s.value)); + } + line.push_str(&format!(", id {}", s.id)); + if let Some((x, y)) = s.position { + line.push_str(&format!(", at {x:.1}, {y:.1} mm")); + } + if !s.net.is_empty() { + line.push_str(&format!(", net {}", s.net)); + } + if !s.layer.is_empty() { + line.push_str(&format!(", layer {}", s.layer)); + } + line.push('.'); + line +} + +fn clip(mut text: String) -> String { + if text.chars().count() > MAX_NOTE { + text = text.chars().take(MAX_NOTE - 12).collect(); + text.push_str("\n"); + } + text +} + +/// The context note for a message. With `since` it holds only what changed (and is empty when +/// nothing did). The note sits in a `` fence the system note explains. +pub fn note(ctx: &Context, since: Option<&Sent>) -> String { + let now = ctx.sent(); + let selection = ctx.selection.as_ref().map(selection_line); + if let Some(before) = since { + if *before == now { + return String::new(); + } + let mut lines = vec!["".to_string()]; + if before.revision != now.revision { + lines.push(format!( + "The design changed: revision {} to {}.", + before.revision, now.revision + )); + } + if before.tab != now.tab { + lines.push(format!("View: {}.", now.tab)); + } + if before.selection != now.selection { + lines.push(selection.unwrap_or_else(|| "Nothing is selected.".to_string())); + } + lines.push("".to_string()); + return clip(lines.join("\n")); + } + let s = &ctx.summary; + let num = |v: &Value| v.as_u64().unwrap_or(0); + let mut lines = vec![ + "".to_string(), + format!("View: {}.", ctx.tab), + format!( + "Design \"{}\", revision {}. Board {} x {} mm, {} layers.", + s["name"].as_str().unwrap_or(""), + num(&s["revision"]), + s["board"]["width"], + s["board"]["height"], + num(&s["board"]["layers"]), + ), + format!( + "{} components, {} nets, {} tracks, {} vias. Findings: {} errors, {} warnings, {} notes.", + num(&s["counts"]["components"]), + num(&s["counts"]["nets"]), + num(&s["counts"]["tracks"]), + num(&s["counts"]["vias"]), + num(&s["findings"]["errors"]), + num(&s["findings"]["warnings"]), + num(&s["findings"]["notes"]), + ), + ]; + if let Some(line) = selection { + lines.push(line); + } + let parts: Vec = s["parts"] + .as_array() + .into_iter() + .flatten() + .map(|p| { + format!( + "{} {}", + p["reference"].as_str().unwrap_or(""), + p["value"].as_str().unwrap_or("") + ) + .trim() + .to_string() + }) + .collect(); + let nets: Vec = s["nets"] + .as_array() + .into_iter() + .flatten() + .map(|n| { + format!( + "{} ({} pins)", + n["name"].as_str().unwrap_or(""), + num(&n["pins"]) + ) + }) + .collect(); + let mut tail = Vec::new(); + for (label, list) in [("Parts", parts), ("Nets", nets)] { + if !list.is_empty() { + tail.push(format!("{label}: {}.", list.join("; "))); + } + } + let mut text = lines.join("\n"); + // Keep the lists inside the budget: shorten them rather than the selection line. + let budget = MAX_NOTE.saturating_sub(text.chars().count() + 24); + let mut tail_text = tail.join("\n"); + if tail_text.chars().count() > budget { + tail_text = tail_text.chars().take(budget.saturating_sub(18)).collect(); + tail_text.push_str(" ... and more."); + } + if !tail_text.is_empty() { + text.push('\n'); + text.push_str(&tail_text); + } + text.push_str("\n"); + clip(text) +} + +/// A picture of the view as a message part, or a note saying why it was left out. +pub fn picture(takes_pictures: bool, png_base64: Option<&str>) -> Result { + if !takes_pictures { + return Err( + "The picture was left out: this connection is not set to take pictures.".into(), + ); + } + let data = png_base64.ok_or("The picture could not be made.")?; + // Base64 is 4 bytes for every 3. + if data.len() / 4 * 3 > MAX_PICTURE_BYTES { + return Err("The picture was left out: it is larger than 4 MB.".into()); + } + Ok(PromptPart::Picture { + mime: "image/png".into(), + base64: data.to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn ctx(revision: u64, selected: Option) -> Context { + Context { + tab: "schematic", + selection: selected.map(|id| Selection { + kind: "resistor".into(), + id, + reference: "R1".into(), + value: "330".into(), + net: "LED".into(), + position: Some((40.0, 14.0)), + layer: String::new(), + }), + summary: json!({"name":"LED indicator","revision":revision, + "board":{"width":80,"height":50,"layers":2}, + "counts":{"components":3,"nets":3,"tracks":0,"vias":0}, + "findings":{"errors":0,"warnings":1,"notes":0}, + "parts":[{"reference":"R1","value":"330"},{"reference":"D1","value":"LED"}], + "nets":[{"name":"LED","pins":2}]}), + } + } + + #[test] + fn the_first_message_of_a_turn_carries_the_context_note_and_the_second_carries_only_the_delta() + { + let first = note(&ctx(3, Some(2)), None); + assert!(first.starts_with("") && first.ends_with("")); + assert!(first.contains("revision 3") && first.contains("Parts: R1 330; D1 LED")); + assert!(first.chars().count() <= MAX_NOTE); + let c = ctx(5, Some(2)); + let delta = note(&c, Some(&ctx(3, Some(2)).sent())); + assert!(delta.contains("revision 3 to 5")); + assert!( + !delta.contains("Parts:"), + "the delta does not repeat the design" + ); + assert_eq!(note(&c, Some(&c.sent())), "", "nothing new, nothing sent"); + } + + #[test] + fn a_selected_part_is_named_in_the_note_with_its_net_and_position() { + let n = note(&ctx(1, Some(7)), None); + assert!( + n.contains("Selected: resistor R1 (330), id 7, at 40.0, 14.0 mm, net LED."), + "{n}" + ); + } + + #[test] + fn attach_view_is_left_out_with_a_note_for_a_connection_that_takes_no_pictures() { + assert!( + picture(false, Some("AA==")).is_err_and(|e| e.contains("not set to take pictures")) + ); + assert!(matches!( + picture(true, Some("AA==")), + Ok(PromptPart::Picture { .. }) + )); + let huge = "A".repeat(MAX_PICTURE_BYTES * 2); + assert!(picture(true, Some(&huge)).is_err_and(|e| e.contains("4 MB"))); + } +} diff --git a/crates/assistant/src/describe.rs b/crates/assistant/src/describe.rs new file mode 100644 index 000000000..9e866cb10 --- /dev/null +++ b/crates/assistant/src/describe.rs @@ -0,0 +1,67 @@ +//! Plain-English text for what a batch would change. +//! +//! Context: the approval card shows [`summary_text`] before the user allows an edit. +//! Rules: counts and names, no icons; the pane maps the text through its catalog. + +use pcbcraft_engine::ChangeSummary; + +fn group(verb: &str, list: &[(String, String)]) -> Option { + if list.is_empty() { + return None; + } + if list.len() <= 2 { + let names: Vec<&str> = list.iter().map(|(_, n)| n.as_str()).collect(); + return Some(format!("{verb} {}", names.join(" and "))); + } + let kind = list.first().map_or("objects", |(k, _)| k.as_str()); + Some(format!("{verb} {} {kind}s", list.len())) +} + +/// For example "adds R1, moves 2 tracks, revision 7 to 8". +pub fn summary_text(s: &ChangeSummary, revision: u64) -> String { + let mut parts: Vec = [ + group("adds", &s.added), + group("removes", &s.removed), + group("moves", &s.moved), + group("changes", &s.changed), + ] + .into_iter() + .flatten() + .collect(); + if s.nets_changed > 0 { + parts.push(format!("changes {} nets", s.nets_changed)); + } + if s.board_changed { + parts.push("changes the board".into()); + } + if s.more > 0 { + parts.push(format!("and {} more", s.more)); + } + if parts.is_empty() { + parts.push("changes nothing".into()); + } + parts.push(format!("revision {revision} to {}", revision + 1)); + parts.join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_summary_reads_as_one_plain_line() { + let s = ChangeSummary { + added: vec![("component".into(), "R1".into())], + moved: vec![ + ("track".into(), "1".into()), + ("track".into(), "2".into()), + ("track".into(), "3".into()), + ], + ..ChangeSummary::default() + }; + assert_eq!( + summary_text(&s, 7), + "adds R1, moves 3 tracks, revision 7 to 8" + ); + } +} diff --git a/crates/assistant/src/gate.rs b/crates/assistant/src/gate.rs new file mode 100644 index 000000000..51f456afe --- /dev/null +++ b/crates/assistant/src/gate.rs @@ -0,0 +1,419 @@ +//! The gate between the model and the design: a verdict for every tool call. +//! +//! Context: adapted from SolidCraft (MIT OR Apache-2.0), commit 32558d0a, +//! `crates/ui-egui/src/agent_chat/gate.rs`, mapped to PCBCraft's tool names from +//! `pcbcraft_mcp::tool_list()` (`../../mcp/src/lib.rs`). +//! Rules: reads run in every mode; design edits ask in mode Ask; file and session actions ask +//! outside mode All; a name not in the tool list, or arguments the engine's schema rejects, are +//! refused with the engine's reason. Every tool in the list gets a verdict in every mode. +//! Do not: let a tool that writes a file or replaces the design into the read list. + +use serde_json::Value; + +/// How much the assistant may do without asking. +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Ord, + PartialOrd, + serde::Serialize, + serde::Deserialize, +)] +pub enum Mode { + /// Ask before every edit. + #[default] + Ask, + /// Edits to the design run; files and sessions still ask. + Edits, + /// Everything runs. + All, +} + +impl Mode { + /// Every mode, in the order Settings lists them. + pub const ALL: [Mode; 3] = [Mode::Ask, Mode::Edits, Mode::All]; + + /// The short id kept in files. + pub fn id(self) -> &'static str { + match self { + Mode::Ask => "ask", + Mode::Edits => "edits", + Mode::All => "all", + } + } + + /// The mode for an id from [`Mode::id`]. + pub fn parse(id: &str) -> Option { + Mode::ALL.into_iter().find(|m| m.id() == id) + } + + /// The words Settings shows. + pub fn label(self) -> &'static str { + match self { + Mode::Ask => "Ask every time", + Mode::Edits => "Auto-allow design edits", + Mode::All => "Allow everything", + } + } +} + +/// What to do with one tool call. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Verdict { + /// Run it now; `change` is true when it edits the design (counts toward the turn limit). + Run { + /// True when the call edits the design. + change: bool, + }, + /// Wait for the user; the text says why. + Ask(String), + /// Do not run it; the text is the reason given to the model. + Refuse(String), +} + +/// Tools that only read. +const READS: &[&str] = &[ + "list_commands", + "inspect_design", + "checks", + "screenshot", + "board_mesh", + "design.summary", + "library.catalog", + "library.search", + "library.list", + "library.inspect_symbol", + "library.inspect_footprint", + "library.sources", + "library.compare", + "design.recents", +]; +/// Tools that touch files or replace the whole design. +const SESSION_ACTIONS: &[&str] = &[ + "open", + "save", + "export", + "new_design", + "sample_design", + "library.add_folder", + "library.remove_folder", + "library.save", +]; +/// Parameter names that always hold a file or folder. +pub const FILE_KEYS: &[&str] = &[ + "path", + "directory", + "dir", + "file", + "filename", + "folder", + "output_path", +]; +/// Parameter names that sometimes hold a file name. +pub const AMBIGUOUS_KEYS: &[&str] = &["name", "source", "target"]; +/// Endings that make an ambiguous value read like a file name. +pub const FILE_EXTENSIONS: &[&str] = &[ + ".pcbcraft", + ".zip", + ".csv", + ".txt", + ".svg", + ".png", + ".pdf", + ".dxf", + ".json", + ".kicad_pcb", + ".kicad_mod", + ".kicad_sym", + ".pcbcraft-lib", +]; + +/// The most commands one batch may carry. +const BATCH_LIMIT: usize = 128; + +fn is_file_tool(tool: &str) -> bool { + SESSION_ACTIONS.contains(&tool) + || tool.ends_with(".write") + || tool.ends_with(".export") + || tool.ends_with("_svg") + || tool.starts_with("library.export_") +} + +fn reads_like_a_file(value: &str) -> bool { + value.contains('/') + || value.contains('\\') + || FILE_EXTENSIONS + .iter() + .any(|e| value.to_ascii_lowercase().ends_with(e)) +} + +/// True when a command's parameters name a file or folder. +fn params_touch_files(params: &Value) -> bool { + let Some(map) = params.as_object() else { + return false; + }; + map.iter().any(|(k, v)| { + (FILE_KEYS.contains(&k.as_str()) && v.is_string()) + || (AMBIGUOUS_KEYS.contains(&k.as_str()) && v.as_str().is_some_and(reads_like_a_file)) + }) +} + +fn commands_of(tool: &str, args: &Value) -> Vec { + match tool { + "execute" => vec![args.clone()], + "batch" | "dry_run" => args + .get("commands") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(), + _ => vec![], + } +} + +/// True when the call edits the design (the turn's change count and undo step). +pub fn edits_design(tool: &str, _args: &Value) -> bool { + match tool { + "open" | "new_design" | "sample_design" | "undo" | "redo" => true, + t if READS.contains(&t) || is_file_tool(t) || t == "dry_run" => false, + _ => true, + } +} + +/// Decide what happens to `tool` called with `args`. +/// +/// `undo_left` is how many of this message's own changes `undo` could still take back; asking +/// for more undoes work from before the message. `always` holds keys the user chose to always +/// allow (see [`tool_key`]). +pub fn request( + tool: &str, + args: &Value, + mode: Mode, + undo_left: usize, + always: &[String], +) -> Verdict { + if let Err(reason) = pcbcraft_mcp::check_args(tool, args) { + return Verdict::Refuse(reason); + } + if tool == "batch" && commands_of(tool, args).len() > BATCH_LIMIT { + return Verdict::Refuse(format!("a batch holds at most {BATCH_LIMIT} commands")); + } + if READS.contains(&tool) { + return Verdict::Run { change: false }; + } + if tool == "dry_run" + || (tool == "execute" + && args.get("command").and_then(Value::as_str) == Some("design.summary")) + { + return Verdict::Run { change: false }; + } + if tool == "undo" || tool == "redo" { + return if undo_left == 0 && mode != Mode::All { + Verdict::Ask("undoes work done before this message".into()) + } else { + Verdict::Run { change: true } + }; + } + let files = is_file_tool(tool) + || commands_of(tool, args).iter().any(|c| { + let name = c.get("command").and_then(Value::as_str).unwrap_or(""); + is_file_tool(name) || c.get("params").is_some_and(params_touch_files) + }) + || (!matches!(tool, "execute" | "batch") && params_touch_files(args)); + if files { + return if mode == Mode::All { + Verdict::Run { + change: edits_design(tool, args), + } + } else { + Verdict::Ask("works with files or replaces the design".into()) + }; + } + if mode != Mode::Ask || always.contains(&tool_key(tool, args)) { + Verdict::Run { change: true } + } else { + Verdict::Ask("changes the design".into()) + } +} + +/// The name "Always allow" remembers: the command for `execute`, `batch` for a batch. +pub fn tool_key(tool: &str, args: &Value) -> String { + if tool == "execute" + && let Some(command) = args.get("command").and_then(Value::as_str) + { + return command.to_string(); + } + tool.to_string() +} + +/// A plain title for the approval card. +pub fn describe(tool: &str, args: &Value) -> String { + let text = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).map(str::to_string); + match tool { + "batch" => format!("Batch of {} commands", commands_of(tool, args).len()), + "execute" => describe_command( + &text(args, "command").unwrap_or_default(), + args.get("params").unwrap_or(&Value::Null), + ), + "undo" => "Undo the last change".into(), + "redo" => "Redo the last change".into(), + "new_design" => "Start a new empty design".into(), + "sample_design" => "Load the example design".into(), + "open" | "save" => { + let path = text(args, "path").unwrap_or_default(); + let name = path.rsplit(['/', '\\']).next().unwrap_or(""); + let verb = if tool == "open" { + "Open" + } else { + "Save the design to" + }; + format!("{verb} {name}") + } + other => describe_command(other, args), + } +} + +fn describe_command(command: &str, params: &Value) -> String { + let get = |k: &str| params.get(k).and_then(Value::as_str); + if command == "component.add" { + let kind = get("kind").unwrap_or("part"); + return match (get("reference"), get("value")) { + (Some(r), Some(v)) => format!("Add {kind} {r} ({v})"), + (Some(r), None) => format!("Add {kind} {r}"), + _ => format!("Add a {kind}"), + }; + } + command.replace(['.', '_'], " ") +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn add(reference: &str) -> Value { + json!({"command":"component.add","params":{"kind":"resistor","reference":reference,"value":"10k","position":{"x":1.0,"y":2.0}}}) + } + + #[test] + fn the_gate_refuses_and_limits() { + assert!(matches!( + request("no_such_tool", &json!({}), Mode::All, 0, &[]), + Verdict::Refuse(_) + )); + let many = json!({"commands": vec![add("R1"); 129]}); + assert!(matches!( + request("batch", &many, Mode::All, 0, &[]), + Verdict::Refuse(_) + )); + } + + #[test] + fn file_actions_wait_for_the_user() { + for mode in [Mode::Ask, Mode::Edits] { + assert!(matches!( + request("save", &json!({"path":"/tmp/a.pcbcraft"}), mode, 0, &[]), + Verdict::Ask(_) + )); + assert!(matches!( + request("gerber.export", &json!({"path":"/tmp/out"}), mode, 0, &[]), + Verdict::Ask(_) + )); + } + assert_eq!( + request( + "save", + &json!({"path":"/tmp/a.pcbcraft"}), + Mode::All, + 0, + &[] + ), + Verdict::Run { change: false } + ); + } + + #[test] + fn permission_modes_decide_what_asks() { + let a = add("R1"); + assert!(matches!( + request("execute", &a, Mode::Ask, 0, &[]), + Verdict::Ask(_) + )); + assert_eq!( + request("execute", &a, Mode::Edits, 0, &[]), + Verdict::Run { change: true } + ); + assert_eq!( + request("execute", &a, Mode::Ask, 0, &["component.add".into()]), + Verdict::Run { change: true } + ); + assert_eq!( + request("inspect_design", &json!({}), Mode::Ask, 0, &[]), + Verdict::Run { change: false } + ); + assert!(matches!( + request("undo", &json!({}), Mode::Edits, 0, &[]), + Verdict::Ask(_) + )); + assert_eq!( + request("undo", &json!({}), Mode::Edits, 2, &[]), + Verdict::Run { change: true } + ); + } + + #[test] + fn every_tool_in_the_list_gets_a_verdict_in_every_mode() { + let list = pcbcraft_mcp::tool_list(); + let names: Vec = list["tools"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| t["name"].as_str().map(str::to_string)) + .collect(); + assert!(names.len() > 100); + for name in &names { + for mode in [Mode::Ask, Mode::Edits, Mode::All] { + // Empty arguments may be refused by the schema; the call must still not panic + // and a file tool must never run silently outside mode All. + let v = request(name, &json!({}), mode, 0, &[]); + if is_file_tool(name) && mode != Mode::All { + assert!( + !matches!(v, Verdict::Run { .. }), + "{name} ran without asking" + ); + } + } + } + for read in READS.iter().filter(|r| names.iter().any(|n| n == *r)) { + assert!(!is_file_tool(read), "{read} is both a read and a file tool"); + } + } + + #[test] + fn a_malformed_execute_is_refused_with_the_engines_reason_and_runs_nothing() { + let bad = + json!({"command":"component.add","params":{"kind":"resistor","position":"nowhere"}}); + match request("execute", &bad, Mode::All, 0, &[]) { + Verdict::Refuse(reason) => assert!(!reason.is_empty()), + other => assert_eq!(other, Verdict::Refuse(String::new()), "must refuse"), + } + let unknown = json!({"command":"no.such","params":{}}); + assert!( + matches!(request("execute", &unknown, Mode::All, 0, &[]), Verdict::Refuse(r) if r.contains("unknown")) + ); + } + + #[test] + fn the_card_title_names_the_part() { + let a = add("R1"); + assert_eq!(describe("execute", &a), "Add resistor R1 (10k)"); + assert_eq!(tool_key("execute", &a), "component.add"); + assert_eq!( + describe("batch", &json!({"commands":[{},{}]})), + "Batch of 2 commands" + ); + } +} diff --git a/crates/assistant/src/guard.rs b/crates/assistant/src/guard.rs new file mode 100644 index 000000000..31582c1c3 --- /dev/null +++ b/crates/assistant/src/guard.rs @@ -0,0 +1,70 @@ +//! Whether the assistant may send anything at all. +//! +//! Context: the pane asks [`can_send`] before it starts a connection or sends a message, and +//! explains the answer in its own words (the catalog). +//! Rules: with the assistant switched off, with no connection, or with no way to send requests +//! (the browser build), no request leaves the app. +//! Do not: add a path that sends without asking this first. + +/// Why nothing may be sent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Blocked { + /// The assistant is switched off in Settings. + Disabled, + /// This build has no way to send requests (the browser build). + NoHttp, + /// No connection has been added yet. + NoConnection, +} + +impl std::fmt::Display for Blocked { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Blocked::Disabled => "The assistant is switched off in Settings.", + Blocked::NoHttp => "The assistant needs the desktop app.", + Blocked::NoConnection => "Add a model connection in Settings to start.", + }) + } +} + +/// `Ok` only when the assistant is on, this build can send requests and a connection exists. +pub fn can_send(enabled: bool, has_connection: bool, host_has_http: bool) -> Result<(), Blocked> { + if !enabled { + Err(Blocked::Disabled) + } else if !host_has_http { + Err(Blocked::NoHttp) + } else if !has_connection { + Err(Blocked::NoConnection) + } else { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::CountingHttp; + + #[test] + fn no_request_leaves_the_app_until_a_connection_exists() { + let http = CountingHttp::new(Ok((200, b"{}".to_vec()))); + let sender = http.http(); + for _ in 0..10 { + // The pane only sends when the guard says so. + if can_send(true, false, true).is_ok() { + let _ = sender(&crate::HttpRequest { + method: "GET", + url: "http://localhost/".into(), + headers: vec![], + body: None, + timeout_s: 1, + }); + } + assert_eq!(can_send(true, false, true), Err(Blocked::NoConnection)); + } + assert_eq!(http.calls(), 0); + assert_eq!(can_send(false, true, true), Err(Blocked::Disabled)); + assert_eq!(can_send(true, true, false), Err(Blocked::NoHttp)); + assert!(can_send(true, true, true).is_ok()); + } +} diff --git a/crates/assistant/src/http.rs b/crates/assistant/src/http.rs new file mode 100644 index 000000000..29c30bc81 --- /dev/null +++ b/crates/assistant/src/http.rs @@ -0,0 +1,234 @@ +//! Plain `http://` client for the API backend: std only, no TLS, no redirects. +//! +//! Context: [`crate::HttpFn`] is injected by the host. This is the host-independent +//! implementation for loopback and LAN endpoints; `https://` stays the app layer's job. +//! Local rules: every request has a deadline, the reply body has a size cap, a redirect +//! is returned as its status and never followed, no panics. + +use crate::backend::{HttpFn, HttpRequest}; +use std::io::{Read, Write}; +use std::net::{TcpStream, ToSocketAddrs}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +/// Largest reply body accepted, in bytes. +pub const MAX_BODY: usize = 8 * 1024 * 1024; +/// Largest reply header block accepted, in bytes. +const MAX_HEAD: usize = 64 * 1024; + +/// The plain-HTTP implementation of [`HttpFn`]. +/// +/// What and why: lets the real backend run over a socket without a host app, so the +/// end-to-end tests exercise the same transport code. +/// +/// # Rules +/// The `timeout_s` of the request is one deadline for connect, send and receive. +/// # Dependencies +/// `src/backend.rs` (`HttpRequest`, `HttpFn`). +/// # Do not +/// Follow redirects, add TLS, or put the request headers in an error text. +pub fn plain_http() -> HttpFn { + Arc::new(plain_request) +} + +/// Send one request over `http://` and return the status and the body. +/// +/// # Rules +/// Errors are plain sentences. A reply cut short of its announced length is an error. +/// # Dependencies +/// `src/backend.rs`. +/// # Do not +/// Echo header values (they may hold a key). +pub fn plain_request(req: &HttpRequest) -> Result<(u16, Vec), String> { + let (host, port, path) = split_url(&req.url)?; + let deadline = Instant::now() + Duration::from_secs(req.timeout_s.max(1)); + let mut stream = connect(&host, port, deadline)?; + let mut head = format!( + "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept: application/json\r\n", + req.method, path, host + ); + for (k, v) in &req.headers { + if k.contains(['\r', '\n', ':']) || v.contains(['\r', '\n']) { + return Err("A request header was not valid.".into()); + } + let lower = k.to_ascii_lowercase(); + if matches!(lower.as_str(), "host" | "connection" | "content-length") { + continue; + } + head.push_str(&format!("{k}: {v}\r\n")); + } + let body = req.body.as_deref().unwrap_or(&[]); + if req.body.is_some() { + head.push_str(&format!("Content-Length: {}\r\n", body.len())); + } + head.push_str("\r\n"); + set_timeouts(&stream, deadline)?; + stream + .write_all(head.as_bytes()) + .and_then(|_| stream.write_all(body)) + .map_err(|e| io_text(&e, "send the request"))?; + let raw = read_all(&mut stream, deadline)?; + parse_reply(&raw) +} + +fn split_url(url: &str) -> Result<(String, u16, String), String> { + let lower = url.to_ascii_lowercase(); + let rest = if lower.starts_with("http://") { + &url[7..] + } else if lower.starts_with("https://") { + return Err("This connection cannot do https here; use an http address.".into()); + } else { + return Err("The address must start with http://".into()); + }; + let (auth, path) = match rest.find(['/', '?']) { + Some(i) if rest.as_bytes()[i] == b'/' => (&rest[..i], rest[i..].to_string()), + Some(i) => (&rest[..i], format!("/{}", &rest[i..])), + None => (rest, "/".to_string()), + }; + if auth.is_empty() || auth.contains('@') { + return Err("The address has no usable host.".into()); + } + let (host, port) = match auth.rsplit_once(':') { + Some((h, p)) if !p.contains(']') => { + let port = p + .parse::() + .map_err(|_| "The port is not a number.".to_string())?; + (h.to_string(), port) + } + _ => (auth.to_string(), 80), + }; + if path.contains(['\r', '\n', ' ']) || host.contains(['\r', '\n', ' ']) { + return Err("The address has characters that are not allowed.".into()); + } + Ok((host, port, path)) +} + +fn connect(host: &str, port: u16, deadline: Instant) -> Result { + let bare = host.trim_start_matches('[').trim_end_matches(']'); + let addrs = (bare, port) + .to_socket_addrs() + .map_err(|_| "The host name could not be found.".to_string())?; + let mut last = "No address to connect to.".to_string(); + for a in addrs { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err("The request timed out.".into()); + } + match TcpStream::connect_timeout(&a, left) { + Ok(s) => return Ok(s), + Err(e) => last = io_text(&e, "connect"), + } + } + Err(last) +} + +fn set_timeouts(s: &TcpStream, deadline: Instant) -> Result<(), String> { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err("The request timed out.".into()); + } + s.set_read_timeout(Some(left)) + .and_then(|_| s.set_write_timeout(Some(left))) + .map_err(|e| io_text(&e, "set up the connection")) +} + +fn io_text(e: &std::io::Error, what: &str) -> String { + use std::io::ErrorKind::{TimedOut, WouldBlock}; + if matches!(e.kind(), TimedOut | WouldBlock) { + "The request timed out.".into() + } else { + format!("Could not {what}: {}.", e.kind()) + } +} + +fn read_all(s: &mut TcpStream, deadline: Instant) -> Result, String> { + let mut out = Vec::new(); + let mut buf = [0u8; 8192]; + loop { + set_timeouts(s, deadline)?; + match s.read(&mut buf) { + Ok(0) => return Ok(out), + Ok(n) => { + out.extend_from_slice(&buf[..n]); + if out.len() > MAX_BODY + MAX_HEAD { + return Err("The reply is larger than the limit.".into()); + } + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + // A reset after some bytes is a cut-off reply; parse_reply says so if short. + Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset && !out.is_empty() => { + return Ok(out); + } + Err(e) => return Err(io_text(&e, "read the reply")), + } + } +} + +fn find(hay: &[u8], needle: &[u8]) -> Option { + hay.windows(needle.len()).position(|w| w == needle) +} + +fn parse_reply(raw: &[u8]) -> Result<(u16, Vec), String> { + let end = find(raw, b"\r\n\r\n").ok_or("The reply ended before its headers did.")?; + if end > MAX_HEAD { + return Err("The reply headers are larger than the limit.".into()); + } + let head = String::from_utf8_lossy(&raw[..end]).into_owned(); + let mut lines = head.split("\r\n"); + let status = lines + .next() + .and_then(|l| l.split(' ').nth(1)) + .and_then(|c| c.parse::().ok()) + .ok_or("The reply was not HTTP.")?; + let mut length: Option = None; + let mut chunked = false; + for l in lines { + if let Some((k, v)) = l.split_once(':') { + let (k, v) = (k.trim().to_ascii_lowercase(), v.trim()); + if k == "content-length" { + length = v.parse().ok(); + } else if k == "transfer-encoding" && v.to_ascii_lowercase().contains("chunked") { + chunked = true; + } + } + } + let body = &raw[end + 4..]; + let body = if chunked { + dechunk(body)? + } else if let Some(n) = length { + if body.len() < n { + return Err("The reply was cut off before it finished.".into()); + } + body[..n].to_vec() + } else { + body.to_vec() + }; + if body.len() > MAX_BODY { + return Err("The reply is larger than the limit.".into()); + } + Ok((status, body)) +} + +fn dechunk(mut b: &[u8]) -> Result, String> { + let cut = || "The reply was cut off before it finished.".to_string(); + let mut out = Vec::new(); + loop { + let eol = find(b, b"\r\n").ok_or_else(cut)?; + let size_text = String::from_utf8_lossy(&b[..eol]).into_owned(); + let size_text = size_text.split(';').next().unwrap_or("").trim().to_string(); + let size = usize::from_str_radix(&size_text, 16) + .map_err(|_| "The reply had a bad chunk size.".to_string())?; + b = &b[eol + 2..]; + if size == 0 { + return Ok(out); + } + if b.len() < size + 2 { + return Err(cut()); + } + out.extend_from_slice(&b[..size]); + if out.len() > MAX_BODY { + return Err("The reply is larger than the limit.".into()); + } + b = &b[size + 2..]; + } +} diff --git a/crates/assistant/src/lib.rs b/crates/assistant/src/lib.rs new file mode 100644 index 000000000..d22fe0af0 --- /dev/null +++ b/crates/assistant/src/lib.rs @@ -0,0 +1,48 @@ +//! Assistant conversation model: backend seam, transcript, and turn accounting (no UI). +mod api; +mod backend; +mod connections; +mod context; +mod describe; +mod gate; +mod guard; +mod http; +mod prompt; +mod script; +mod store; +mod text; +mod tool_names; +mod transcript; +mod turn; + +pub use api::{ + ApiBackend, ApiConfig, MAX_HISTORY, MAX_REQUESTS_PER_TURN as MAX_API_REQUESTS_PER_TURN, + MAX_TOOL_TEXT, Protocol, anthropic_model_list, anthropic_tools, endpoint, http_error, + key_safe_for, model_list, openai_tools, test_anthropic_endpoint, test_endpoint, +}; +pub use backend::{ + AuthKind, AuthMethod, ChatBackend, Event, HttpFn, HttpRequest, ModelInfo, PermissionOption, + PromptPart, Secrets, StartContext, ToolStatus, base64, content_blocks, +}; +pub use connections::{Connection, PRESETS, Preset, config_for, key_id, new_id, normalize_url}; +pub use context::{Context, MAX_NOTE, MAX_PICTURE_BYTES, Selection, Sent, note, picture}; +pub use describe::summary_text; +pub use gate::{ + AMBIGUOUS_KEYS, FILE_EXTENSIONS, FILE_KEYS, Mode, Verdict, describe, edits_design, request, + tool_key, +}; +pub use guard::{Blocked, can_send}; +pub use http::{MAX_BODY, plain_http, plain_request}; +pub use prompt::SYSTEM_NOTE; +pub use script::{CountingHttp, ScriptBackend}; +pub use store::{ + clear as clear_transcript, export_markdown, load as load_transcript, save as save_transcript, + transcript_path, +}; +pub use text::{MAX_PROMPT, check_prompt_length, prompt_too_long_reason}; +pub use tool_names::{ToolNames, to_wire}; +pub use transcript::{Item, MAX_ITEMS, Transcript}; +pub use turn::{DEFAULT_TURN_LIMIT, MAX_REQUESTS_PER_TURN, ToolRequest, Turn}; + +#[cfg(test)] +mod api_tests; diff --git a/crates/assistant/src/prompt.rs b/crates/assistant/src/prompt.rs new file mode 100644 index 000000000..21f33171a --- /dev/null +++ b/crates/assistant/src/prompt.rs @@ -0,0 +1,8 @@ +//! The standing instructions every API backend sends with each request. + +/// PCBCraft's system note: what the app is and how the model should use its tools. +pub const SYSTEM_NOTE: &str = "You are the assistant inside PCBCraft, a schematic and board editor. \ +The design is reachable only through the listed tools. Call inspect_design first to see what is \ +there. Prefer one batch call over many execute calls, and give expected_revision with every edit \ +so a stale edit is refused. Edits wait for the user's approval, so say what you propose and why. \ +A context note inside tags, with the design summary and what the user has selected, comes before each message; call design.summary again after your edits to confirm them, and call inspect_design only when you need an object's full record. Keep answers short and plain. Units are millimetres and degrees."; diff --git a/crates/assistant/src/script.rs b/crates/assistant/src/script.rs new file mode 100644 index 000000000..559e7c2a8 --- /dev/null +++ b/crates/assistant/src/script.rs @@ -0,0 +1,142 @@ +// Adapted from SolidCraft (MIT OR Apache-2.0), commit 32558d0a: +// crates/ui-egui/src/agent_chat/tests.rs (Script backend) + +use crate::backend::{ChatBackend, Event, PromptPart}; +use std::sync::{Arc, Mutex}; + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + match m.lock() { + Ok(g) => g, + Err(e) => e.into_inner(), + } +} + +/// A backend that records what the pane asks of it, and reports what the test pushes. +#[derive(Clone, Default)] +pub struct ScriptBackend { + calls: Arc>>, + events: Arc>>, + prompts: Arc>>>, +} + +impl ScriptBackend { + pub fn calls(&self) -> Vec { + lock(&self.calls).clone() + } + + pub fn prompts(&self) -> Vec> { + lock(&self.prompts).clone() + } + + pub fn report(&self, e: Event) { + lock(&self.events).push(e); + } +} + +impl ChatBackend for ScriptBackend { + fn poll(&mut self) -> Vec { + std::mem::take(&mut *lock(&self.events)) + } + + fn prompt(&mut self, parts: &[PromptPart]) { + let text = parts + .iter() + .find_map(|p| { + if let PromptPart::Text(t) = p { + Some(t.clone()) + } else { + None + } + }) + .unwrap_or_default(); + lock(&self.calls).push(format!("prompt: {text}")); + lock(&self.prompts).push(parts.to_vec()); + } + + fn cancel(&mut self) { + lock(&self.calls).push("cancel".into()); + } + + fn new_session(&mut self) { + lock(&self.calls).push("new_session".into()); + } + + fn set_model(&mut self, model: &str) { + lock(&self.calls).push(format!("set_model: {model}")); + } + + fn answer_permission(&mut self, key: u64, option: Option<&str>) { + lock(&self.calls).push(format!("permission: {key} {option:?}")); + } + + fn authenticate(&mut self, _: &str) {} + + fn set_mode(&mut self, _: &str) {} + + fn shutdown(&mut self, _: bool) {} +} + +/// An `HttpFn` that counts its calls and answers with a fixed reply, so a test can prove that +/// nothing was sent. +#[derive(Clone)] +pub struct CountingHttp { + count: Arc, + reply: Result<(u16, Vec), String>, +} + +impl CountingHttp { + /// A sender that answers every request with `reply`. + pub fn new(reply: Result<(u16, Vec), String>) -> Self { + Self { + count: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + reply, + } + } + + /// How many requests were sent so far. + pub fn calls(&self) -> usize { + self.count.load(std::sync::atomic::Ordering::SeqCst) + } + + /// The sender to hand to the host. + pub fn http(&self) -> crate::backend::HttpFn { + let me = self.clone(); + Arc::new(move |_| { + me.count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + me.reply.clone() + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::{Event, ToolStatus}; + + #[test] + fn script_backend_replays_events_and_records_prompts() { + let mut backend = ScriptBackend::default(); + backend.prompt(&[PromptPart::Text("hello".into())]); + backend.report(Event::Text { + thought: false, + text: "hi".into(), + }); + backend.report(Event::Tool { + id: "t1".into(), + title: Some("run".into()), + kind: None, + status: Some(ToolStatus::Pending), + output: None, + }); + backend.report(Event::TurnEnded { + reason: String::new(), + }); + let events = backend.poll(); + assert_eq!(events.len(), 3); + assert!(matches!(&events[0], Event::Text { text, .. } if text == "hi")); + assert!(matches!(&events[1], Event::Tool { id, .. } if id == "t1")); + assert!(matches!(&events[2], Event::TurnEnded { reason } if reason.is_empty())); + assert_eq!(backend.prompts().len(), 1); + assert_eq!(backend.calls(), vec!["prompt: hello".to_string()]); + } +} diff --git a/crates/assistant/src/store.rs b/crates/assistant/src/store.rs new file mode 100644 index 000000000..9ec14f79f --- /dev/null +++ b/crates/assistant/src/store.rs @@ -0,0 +1,330 @@ +//! The conversation of one design, kept on this computer outside the design file. +//! +//! Context: one JSON-lines file per design under the user's configuration folder, next to the +//! recent-designs list. Written when a message ends, when the design is saved and when the app +//! saves its state; read when that design opens. +//! Rules: approvals, undo rows and permission questions come back as plain notes (they cannot be +//! answered any more); context notes and pictures are never written, so neither are keys; at most +//! [`MAX_ITEMS`] items and 4 MB are kept, oldest dropped first; an unsaved design has no file; +//! loading never fails (a damaged line is skipped and counted). +//! Do not: write a connection key, a context note or a picture here. + +use crate::transcript::{Item, MAX_ITEMS}; +use serde_json::{Value, json}; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::path::PathBuf; + +/// Largest file written, in bytes. +const MAX_BYTES: usize = 4 * 1024 * 1024; +/// Longest line read back, in bytes. +const MAX_LINE: usize = 512 * 1024; + +/// The file for a design, or `None` for a design that has no path yet. +pub fn transcript_path(design_path: Option<&str>) -> Option { + let design = design_path.map(str::trim).filter(|p| !p.is_empty())?; + let directory = |key: &str| { + std::env::var(key) + .ok() + .map(|v| v.trim().to_owned()) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + }; + let base = directory("XDG_CONFIG_HOME") + .or_else(|| directory("APPDATA")) + .or_else(|| directory("HOME").map(|h| h.join(".config")))?; + let mut hasher = DefaultHasher::new(); + design.as_bytes().hash(&mut hasher); + Some( + base.join("pcbcraft") + .join("assistant") + .join(format!("{:016x}.jsonl", hasher.finish())), + ) +} + +fn to_line(item: &Item) -> Option { + Some(match item { + Item::User { text } => json!({"k": "user", "text": text}), + Item::Assistant { text } => json!({"k": "assistant", "text": text}), + Item::Thought { text } => json!({"k": "thought", "text": text}), + Item::ToolCall { title, .. } => json!({"k": "tool", "text": title}), + Item::Plan(steps) => json!({"k": "plan", "steps": steps}), + Item::Note { text, error } => json!({"k": "note", "text": text, "error": error}), + Item::Approval { title, answer, .. } => { + let word = match answer { + Some(true) => "allowed", + Some(false) => "denied", + None => "not answered", + }; + json!({"k": "note", "text": format!("Asked to {title}; {word}"), "error": false}) + } + Item::UndoStep { changes, .. } => { + json!({"k": "note", "text": format!("{changes} changes in one undo step"), "error": false}) + } + Item::Permission { title, answer, .. } => json!({ + "k": "note", + "text": format!("{title}: {}", answer.as_deref().unwrap_or("not answered")), + "error": false, + }), + Item::Queued { .. } => return None, + }) +} + +/// Write the items, newest kept, with a temporary file and a rename. Returns how many were kept. +pub fn save(items: &[Item], path: &std::path::Path) -> Result { + let start = items.len().saturating_sub(MAX_ITEMS); + let mut lines: Vec = items[start..] + .iter() + .filter_map(to_line) + .map(|v| v.to_string()) + .collect(); + let mut total: usize = lines.iter().map(|l| l.len() + 1).sum(); + let mut drop = 0; + while total > MAX_BYTES && drop < lines.len() { + total -= lines[drop].len() + 1; + drop += 1; + } + lines.drain(..drop); + let kept = lines.len(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let temp = path.with_extension("tmp"); + let mut text = lines.join("\n"); + text.push('\n'); + std::fs::write(&temp, text).map_err(|e| e.to_string())?; + std::fs::rename(&temp, path).map_err(|e| e.to_string())?; + Ok(kept) +} + +/// Read a transcript back; the second value counts the lines that could not be used. +pub fn load(path: &std::path::Path) -> (Vec, usize) { + let Ok(text) = std::fs::read_to_string(path) else { + return (Vec::new(), 0); + }; + let mut items = Vec::new(); + let mut skipped = 0; + for line in text.lines().filter(|l| !l.trim().is_empty()) { + let parsed: Option = if line.len() <= MAX_LINE { + serde_json::from_str(line).ok() + } else { + None + }; + let Some(v) = parsed else { + skipped += 1; + continue; + }; + let text = v["text"].as_str().unwrap_or("").to_string(); + let item = match v["k"].as_str() { + Some("user") => Item::User { text }, + Some("assistant") => Item::Assistant { text }, + Some("thought") => Item::Thought { text }, + Some("tool") => Item::ToolCall { + id: String::new(), + title: text, + status: None, + content: None, + }, + Some("note") => Item::Note { + text, + error: v["error"].as_bool().unwrap_or(false), + }, + Some("plan") => Item::Plan( + v["steps"] + .as_array() + .into_iter() + .flatten() + .filter_map(|s| Some((s[0].as_str()?.to_string(), s[1].as_str()?.to_string()))) + .collect(), + ), + _ => { + skipped += 1; + continue; + } + }; + items.push(item); + } + let extra = items.len().saturating_sub(MAX_ITEMS); + items.drain(..extra); + (items, skipped) +} + +/// Remove the file; a missing file is fine. +pub fn clear(path: &std::path::Path) { + let _ = std::fs::remove_file(path); +} + +/// The calendar date of a count of days since 1970-01-01. +fn civil(days: i64) -> (i64, i64, i64) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (yoe + era * 400 + i64::from(m <= 2), m, d) +} + +/// The conversation as Markdown, with the design name and the date at the top. +pub fn export_markdown(items: &[Item], design: &str, unix_seconds: u64) -> String { + let (y, m, d) = civil(i64::try_from(unix_seconds / 86_400).unwrap_or(0)); + let mut out = format!("# {design}\n\nConversation exported {y:04}-{m:02}-{d:02}.\n"); + let mut tools: Vec<&str> = Vec::new(); + let flush = |out: &mut String, tools: &mut Vec<&str>| { + for t in tools.drain(..) { + out.push_str(&format!("- {t}\n")); + } + }; + for item in items { + match item { + Item::ToolCall { title, .. } => tools.push(title), + other => { + if !tools.is_empty() { + flush(&mut out, &mut tools); + } + match other { + Item::User { text } => out.push_str(&format!("\n## You\n\n{text}\n")), + Item::Assistant { text } => { + out.push_str(&format!("\n## Assistant\n\n{text}\n")) + } + Item::Note { text, .. } => out.push_str(&format!("\n_{text}_\n")), + Item::Approval { .. } | Item::UndoStep { .. } => { + if let Some(v) = to_line(other) { + out.push_str(&format!("\n_{}_\n", v["text"].as_str().unwrap_or(""))); + } + } + _ => {} + } + } + } + } + flush(&mut out, &mut tools); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("pcbcraft-store-{}-{name}", std::process::id())) + } + + #[test] + fn a_transcript_round_trips_through_jsonl_with_approvals_turned_into_notes() + -> Result<(), String> { + let items = vec![ + Item::User { + text: "add R1".into(), + }, + Item::Approval { + id: 1, + title: "Add resistor R1".into(), + detail: "adds R1".into(), + answer: Some(true), + }, + Item::UndoStep { + changes: 1, + undone: false, + }, + Item::Assistant { + text: "Done".into(), + }, + ]; + let path = temp("round.jsonl"); + save(&items, &path)?; + let (back, skipped) = load(&path); + clear(&path); + assert_eq!(skipped, 0); + assert_eq!(back.len(), 4); + assert!( + matches!(&back[1], Item::Note { text, .. } if text == "Asked to Add resistor R1; allowed") + ); + assert!( + matches!(&back[2], Item::Note { text, .. } if text == "1 changes in one undo step") + ); + Ok(()) + } + + #[test] + fn a_transcript_past_the_cap_keeps_the_newest_items() -> Result<(), String> { + let items: Vec = (0..MAX_ITEMS + 10) + .map(|i| Item::Note { + text: format!("n{i}"), + error: false, + }) + .collect(); + let path = temp("cap.jsonl"); + let kept = save(&items, &path)?; + let (back, _) = load(&path); + clear(&path); + assert_eq!(kept, MAX_ITEMS); + assert!(matches!(&back[0], Item::Note { text, .. } if text == "n10")); + Ok(()) + } + + #[test] + fn a_damaged_line_is_skipped_and_counted() -> Result<(), String> { + let path = temp("bad.jsonl"); + std::fs::write( + &path, + "{\"k\":\"user\",\"text\":\"hi\"}\nnot json\n{\"k\":\"mystery\"}\n", + ) + .map_err(|e| e.to_string())?; + let (back, skipped) = load(&path); + clear(&path); + assert_eq!(back.len(), 1); + assert_eq!(skipped, 2); + assert_eq!(load(&temp("missing.jsonl")), (Vec::new(), 0)); + Ok(()) + } + + #[test] + fn an_unsaved_design_is_not_persisted_until_it_has_a_path() { + assert_eq!(transcript_path(None), None); + assert_eq!(transcript_path(Some(" ")), None); + let a = transcript_path(Some("/a/b.pcbcraft")); + assert!(a.is_some()); + assert_ne!(a, transcript_path(Some("/a/c.pcbcraft"))); + assert_eq!(a, transcript_path(Some("/a/b.pcbcraft"))); + } + + #[test] + fn export_markdown_names_the_design_and_keeps_the_order() { + let items = vec![ + Item::User { + text: "hello".into(), + }, + Item::ToolCall { + id: "t".into(), + title: "inspect design".into(), + status: None, + content: None, + }, + Item::Assistant { text: "hi".into() }, + ]; + let md = export_markdown(&items, "LED indicator", 1_767_225_600); + assert!(md.starts_with("# LED indicator")); + assert!(md.contains("2026-01-01"), "{md}"); + let you = md.find("## You").unwrap_or(usize::MAX); + let tool = md.find("- inspect design").unwrap_or(usize::MAX); + let asst = md.find("## Assistant").unwrap_or(usize::MAX); + assert!(you < tool && tool < asst); + } + + #[test] + fn no_key_or_context_note_appears_in_the_file() -> Result<(), String> { + // Context notes are sent to the model but never become transcript items. + let items = vec![Item::User { + text: "move R1".into(), + }]; + let path = temp("secret.jsonl"); + save(&items, &path)?; + let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?; + clear(&path); + assert!(!text.contains("") && !text.contains("sk-secret")); + Ok(()) + } +} diff --git a/crates/assistant/src/text.rs b/crates/assistant/src/text.rs new file mode 100644 index 000000000..86a36f405 --- /dev/null +++ b/crates/assistant/src/text.rs @@ -0,0 +1,29 @@ +//! Plain refusal reasons the pane maps to catalog strings. + +pub use crate::transcript::MAX_PROMPT; + +/// Returns an error when `char_count` exceeds [`MAX_PROMPT`]. +pub fn check_prompt_length(char_count: usize) -> Result<(), String> { + if char_count > MAX_PROMPT { + Err(prompt_too_long_reason(char_count)) + } else { + Ok(()) + } +} + +pub fn prompt_too_long_reason(char_count: usize) -> String { + format!("That message is {char_count} characters; the limit is {MAX_PROMPT}.") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_prompt_longer_than_the_cap_is_refused_with_the_reason() { + let over = MAX_PROMPT + 1; + let err = check_prompt_length(over).err().unwrap_or_default(); + assert_eq!(err, prompt_too_long_reason(over)); + assert!(err.contains(&MAX_PROMPT.to_string())); + } +} diff --git a/crates/assistant/src/tool_names.rs b/crates/assistant/src/tool_names.rs new file mode 100644 index 000000000..b14e1ec6e --- /dev/null +++ b/crates/assistant/src/tool_names.rs @@ -0,0 +1,96 @@ +//! Wire-safe tool names for the hosted model endpoints. +//! +//! Context: MCP tool names are namespaced with dots (`library.save`), but the OpenAI function name +//! pattern (`^[a-zA-Z0-9_-]{1,64}$`) and the Anthropic one (`^[a-zA-Z0-9_-]{1,128}$`) exclude the dot. +//! The map lives at the API edge: [`to_wire`] makes a name legal on the way out and [`ToolNames`] +//! turns the name the model used back into the MCP name on the way in. +//! +//! Local rules: inbound lookup is by table, never by string replacement, so a name the model made up +//! is unknown. Two MCP names that share a wire name are an error, never a silent merge. + +use serde_json::Value; +use std::collections::BTreeMap; + +/// Longest wire name; the stricter of the two hosted patterns. +const WIRE_MAX: usize = 64; +/// Characters kept from a name that is too long, before `_` and four hex digits. +const CLIPPED_KEEP: usize = WIRE_MAX - 5; + +/// An MCP tool name as a legal wire name. +/// +/// Every `.` becomes `__`, any other character outside `[A-Za-z0-9_-]` becomes `_`, and a result +/// over 64 characters is cut to 59 plus `_` and four hex digits of an FNV-1a hash of the original +/// name, so the same name always gives the same answer and the 64 limit always holds. +/// +/// # Rules +/// - Legal names without a dot come back unchanged. +/// +/// # Dependencies +/// - `crates/assistant/src/api.rs` writes it into the tool lists. +/// +/// # Do not +/// - Use this to go back to the MCP name; [`ToolNames::mcp_name`] does that. +pub fn to_wire(name: &str) -> String { + let mut wire = String::with_capacity(name.len()); + for c in name.chars() { + match c { + '.' => wire.push_str("__"), + c if c.is_ascii_alphanumeric() || c == '_' || c == '-' => wire.push(c), + _ => wire.push('_'), + } + } + if wire.len() <= WIRE_MAX { + return wire; + } + let kept: String = wire.chars().take(CLIPPED_KEEP).collect(); + format!("{kept}_{:04x}", fnv1a(name) & 0xffff) +} + +/// FNV-1a over the bytes of `text`, folded to 32 bits. +fn fnv1a(text: &str) -> u32 { + let mut hash: u32 = 0x811c_9dc5; + for b in text.bytes() { + hash ^= u32::from(b); + hash = hash.wrapping_mul(0x0100_0193); + } + hash +} + +/// The table from the wire name the model uses to the MCP name the host runs. +/// +/// # Dependencies +/// - `crates/assistant/src/api.rs` builds it in `ApiBackend::start` and reads it in `Worker::turn`. +/// +/// # Do not +/// - Add names by hand; the table comes from the tool list only. +#[derive(Debug, Default)] +pub struct ToolNames { + to_mcp: BTreeMap, +} + +impl ToolNames { + /// The table for a tool list (MCP `tools/list` shape, hidden tools left out). + /// + /// Errors with a plain sentence naming both tools when two different MCP names share a wire name. + pub fn from_list(list: &Value) -> Result { + let mut to_mcp: BTreeMap = BTreeMap::new(); + for (name, _) in crate::api::tool_entries(list) { + let wire = to_wire(name); + if let Some(other) = to_mcp.get(&wire) { + if other != name { + return Err(format!( + "The tools `{other}` and `{name}` would share the name `{wire}` on the wire." + )); + } + continue; + } + to_mcp.insert(wire, name.to_string()); + } + Ok(ToolNames { to_mcp }) + } + + /// The MCP name for a wire name, or `None` for a name the model made up. + pub fn mcp_name(&self, wire: &str) -> Option<&str> { + self.to_mcp.get(wire).map(String::as_str) + } +} diff --git a/crates/assistant/src/transcript.rs b/crates/assistant/src/transcript.rs new file mode 100644 index 000000000..5d587ca7a --- /dev/null +++ b/crates/assistant/src/transcript.rs @@ -0,0 +1,300 @@ +// Adapted from SolidCraft (MIT OR Apache-2.0), commit 32558d0a: +// crates/ui-egui/src/agent_chat/mod.rs (conversation items and event handling) + +use crate::backend::{Event, PermissionOption, ToolStatus}; + +/// Most entries kept in the conversation; older ones are dropped. +pub const MAX_ITEMS: usize = 2000; +/// Longest message sent (see [`crate::text::check_prompt_length`]). +pub const MAX_PROMPT: usize = 100_000; + +#[derive(Clone, Debug, PartialEq)] +pub enum Item { + User { + text: String, + }, + Assistant { + text: String, + }, + Thought { + text: String, + }, + ToolCall { + id: String, + title: String, + status: Option, + content: Option, + }, + Plan(Vec<(String, String)>), + Permission { + key: u64, + title: String, + options: Vec, + answer: Option, + }, + Approval { + id: u64, + title: String, + /// What the change would do, in plain words (empty when unknown). + detail: String, + answer: Option, + }, + Queued { + text: String, + }, + Note { + text: String, + error: bool, + }, + UndoStep { + changes: u32, + undone: bool, + }, +} + +#[derive(Default)] +pub struct Transcript { + pub items: Vec, +} + +impl Transcript { + pub fn push(&mut self, item: Item) { + if self.items.len() >= MAX_ITEMS { + self.items.drain(..MAX_ITEMS / 10); + } + self.items.push(item); + } + + /// User and assistant lines, in order (for tests). + pub fn texts(&self) -> Vec { + self.items + .iter() + .filter_map(|i| match i { + Item::User { text } | Item::Assistant { text } | Item::Queued { text } => { + Some(text.clone()) + } + _ => None, + }) + .collect() + } + + pub fn waiting(&self) -> usize { + self.items + .iter() + .filter(|i| matches!(i, Item::Permission { answer: None, .. })) + .count() + } + + /// Answer the agent's permission question at `index` (`None`: cancelled). + pub fn answer(&mut self, index: usize, option: Option<&str>) { + let Some(Item::Permission { + options, answer, .. + }) = self.items.get_mut(index) + else { + return; + }; + if answer.is_some() { + return; + } + let label = option + .and_then(|o| options.iter().find(|x| x.id == o)) + .map_or_else(|| "Cancelled".to_string(), |o| o.name.clone()); + *answer = Some(label); + } + + /// Apply one backend event to the transcript (core streaming and tool updates). + pub fn on_event(&mut self, e: Event) { + match e { + Event::Text { thought, text } => { + if thought { + if let Some(Item::Thought { text: last }) = self.items.last_mut() { + last.push_str(&text); + } else { + self.push(Item::Thought { text }); + } + } else if let Some(Item::Assistant { text: last }) = self.items.last_mut() { + last.push_str(&text); + } else { + self.push(Item::Assistant { text }); + } + } + Event::Tool { + id, + title, + status, + output, + .. + } => { + let existing = self + .items + .iter_mut() + .rev() + .find(|i| matches!(i, Item::ToolCall { id: x, .. } if *x == id)); + if let Some(Item::ToolCall { + title: t, + status: s, + content: c, + .. + }) = existing + { + if let Some(v) = title { + *t = v; + } + if status.is_some() { + *s = status; + } + if output.is_some() { + *c = output; + } + } else { + self.push(Item::ToolCall { + id, + title: title.unwrap_or_default(), + status, + content: output, + }); + } + } + Event::Plan(entries) => { + let turn = self + .items + .iter() + .rposition(|i| matches!(i, Item::User { .. })) + .unwrap_or(0); + if let Some(Item::Plan(p)) = self + .items + .iter_mut() + .skip(turn) + .rev() + .find(|i| matches!(i, Item::Plan(_))) + { + *p = entries; + } else { + self.push(Item::Plan(entries)); + } + } + Event::Permission { + key, + title, + options, + } => { + self.push(Item::Permission { + key, + title, + options, + answer: None, + }); + } + Event::Error(text) => self.push(Item::Note { text, error: true }), + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::Event; + + fn chat() -> Transcript { + Transcript::default() + } + + #[test] + fn streamed_text_joins_and_tool_updates_change_their_call() { + let mut c = chat(); + for e in [ + Event::Text { + thought: false, + text: "Mak".into(), + }, + Event::Text { + thought: false, + text: "ing a box".into(), + }, + Event::Tool { + id: "t".into(), + title: Some("batch".into()), + kind: Some("other".into()), + status: Some(ToolStatus::Pending), + output: None, + }, + Event::Tool { + id: "t".into(), + title: None, + kind: None, + status: Some(ToolStatus::Completed), + output: Some("ok".into()), + }, + ] { + c.on_event(e); + } + assert_eq!(c.items.len(), 2); + assert!(matches!(&c.items[0], Item::Assistant { text } if text == "Making a box")); + assert!( + matches!(&c.items[1], Item::ToolCall { title, status: Some(ToolStatus::Completed), content: Some(o), .. } if title == "batch" && o == "ok") + ); + } + + #[test] + fn a_plan_update_replaces_the_turns_plan() { + let mut c = chat(); + c.push(Item::User { text: "go".into() }); + c.on_event(Event::Plan(vec![("a".into(), "pending".into())])); + c.on_event(Event::Text { + thought: false, + text: "working".into(), + }); + c.on_event(Event::Plan(vec![("a".into(), "completed".into())])); + let plans: Vec<_> = c + .items + .iter() + .filter(|i| matches!(i, Item::Plan(_))) + .collect(); + assert_eq!(plans.len(), 1); + assert!(matches!(plans[0], Item::Plan(p) if p[0].1 == "completed")); + } + + #[test] + fn a_permission_is_answered_once() { + let mut c = chat(); + let opts = vec![PermissionOption { + id: "allow".into(), + name: "Allow".into(), + kind: "allow_once".into(), + }]; + c.push(Item::Permission { + key: 5, + title: "batch".into(), + options: opts, + answer: None, + }); + assert_eq!(c.waiting(), 1); + c.answer(0, Some("allow")); + c.answer(0, None); + assert!(matches!(&c.items[0], Item::Permission { answer: Some(a), .. } if a == "Allow")); + assert_eq!(c.waiting(), 0); + } + + #[test] + fn the_transcript_drops_its_oldest_item_past_the_cap() { + let mut c = chat(); + for i in 0..MAX_ITEMS { + c.push(Item::Note { + text: format!("n{i}"), + error: false, + }); + } + assert_eq!(c.items.len(), MAX_ITEMS); + c.push(Item::Note { + text: "extra".into(), + error: false, + }); + assert_eq!(c.items.len(), MAX_ITEMS - MAX_ITEMS / 10 + 1); + assert!( + !c.items + .iter() + .any(|i| matches!(i, Item::Note { text, .. } if text == "n0")) + ); + } +} diff --git a/crates/assistant/src/turn.rs b/crates/assistant/src/turn.rs new file mode 100644 index 000000000..80d4ddd2f --- /dev/null +++ b/crates/assistant/src/turn.rs @@ -0,0 +1,153 @@ +// Adapted from SolidCraft (MIT OR Apache-2.0), commit 32558d0a: +// crates/ui-egui/src/agent_chat/mod.rs (turn accounting) + +use pcbcraft_engine::Session; +use serde_json::Value; +use std::sync::mpsc::Sender; + +/// Changes the agent may make in one turn; the seeded default when the user turns the limit on. +pub const DEFAULT_TURN_LIMIT: u32 = 24; +/// Hard stop on tool-loop iterations per user message. +pub const MAX_REQUESTS_PER_TURN: u32 = 400; + +/// One in-process tool call the host runs on behalf of a backend. +#[derive(Debug)] +pub struct ToolRequest { + pub name: String, + pub args: Value, + pub reply: Sender, +} + +/// The message being answered: what undo and the limits need. +#[derive(Clone, Debug, PartialEq)] +pub struct Turn { + pub started_revision: u64, + pub history_len_at_start: usize, + pub changes: u32, + pub requests: u32, + pub message: String, +} + +/// Told to the model when a limit is reached. +const STOP_TEXT: &str = "Stop calling tools now. Report what you did and what is left."; + +impl Turn { + /// Count one tool request; `change` is true when it edits the design. Returns the text to give + /// the model instead of running the tool once `change_limit` changes or + /// [`MAX_REQUESTS_PER_TURN`] requests are used. + pub fn admit(&mut self, change: bool, change_limit: u32) -> Result<(), &'static str> { + if self.requests >= MAX_REQUESTS_PER_TURN || (change && self.changes >= change_limit) { + return Err(STOP_TEXT); + } + self.requests += 1; + if change { + self.changes += 1; + } + Ok(()) + } + + /// End the turn: merge everything it changed into one undo step. Returns the number of + /// changes and the history length right after the merge (the Undo button is live while the + /// history still has that length), or `None` when the message changed nothing. + pub fn finish(&self, session: &mut Session) -> Option<(u32, usize)> { + if self.changes == 0 || session.history_len() <= self.history_len_at_start { + return None; + } + session.squash_undo_since(self.history_len_at_start); + Some((self.changes, session.history_len())) + } + + pub fn new(started_revision: u64, history_len_at_start: usize, message: String) -> Self { + Self { + started_revision, + history_len_at_start, + changes: 0, + requests: 0, + message, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pcbcraft_engine::Command; + use serde_json::json; + + fn add(reference: &str) -> Command { + Command { + command: "component.add".into(), + params: json!({"kind":"resistor","reference":reference,"value":"1k","position":{"x":5.0,"y":5.0}}), + } + } + + fn work(session: &mut Session, turn: &mut Turn, n: usize) -> Result<(), String> { + for i in 0..n { + turn.admit(true, 24).map_err(str::to_string)?; + session + .batch(&[add(&format!("R{i}"))], None) + .map_err(|e| e.to_string())?; + } + Ok(()) + } + + #[test] + fn a_messages_changes_undo_as_one_step() -> Result<(), String> { + let mut s = Session::default(); + s.batch(&[add("R9")], None).map_err(|e| e.to_string())?; + let mut turn = Turn::new(s.revision, s.history_len(), "add three".into()); + work(&mut s, &mut turn, 3)?; + let (changes, len) = turn.finish(&mut s).ok_or("no undo step")?; + assert_eq!(changes, 3); + assert_eq!(s.history_len(), len); + s.undo().map_err(|e| e.to_string())?; + assert_eq!( + s.project.components.len(), + 1, + "only the earlier part is left" + ); + Ok(()) + } + + #[test] + fn an_interrupted_turns_changes_undo_as_one_step() -> Result<(), String> { + let mut s = Session::default(); + let mut turn = Turn::new(s.revision, s.history_len(), "add many".into()); + work(&mut s, &mut turn, 2)?; + // Stop pressed: the turn ends early but still merges what it did. + assert!(turn.finish(&mut s).is_some()); + s.undo().map_err(|e| e.to_string())?; + assert!(s.project.components.is_empty()); + Ok(()) + } + + #[test] + fn merging_finds_the_turns_start_when_the_history_was_trimmed() -> Result<(), String> { + let mut s = Session::default(); + for i in 0..40 { + s.batch(&[add(&format!("P{i}"))], None) + .map_err(|e| e.to_string())?; + } + let before = s.history_len(); + let mut turn = Turn::new(s.revision, before, "more".into()); + work(&mut s, &mut turn, 3)?; + // The history stayed at its cap, so the start is gone: nothing is merged. + let kept = s.history_len(); + let _ = turn.finish(&mut s); + assert_eq!(s.history_len(), kept, "a trimmed history is left as it was"); + Ok(()) + } + + #[test] + fn the_turn_limit_tells_the_model_to_stop() { + let mut turn = Turn::new(0, 0, "go".into()); + for _ in 0..2 { + assert!(turn.admit(true, 2).is_ok()); + } + assert!(turn.admit(true, 2).is_err()); + assert!( + turn.admit(false, 2).is_ok(), + "reads still run past the change limit" + ); + } +} diff --git a/crates/assistant/tests/openai_wire.rs b/crates/assistant/tests/openai_wire.rs new file mode 100644 index 000000000..dd83129e9 --- /dev/null +++ b/crates/assistant/tests/openai_wire.rs @@ -0,0 +1,198 @@ +//! End-to-end: the real `ApiBackend` and the real plain HTTP function against a loopback +//! fake OpenAI-compatible server. No external network. + +mod support; + +use pcbcraft_assistant::{ + ApiBackend, ApiConfig, ChatBackend, Event, HttpRequest, PromptPart, Protocol, StartContext, + ToolRequest, plain_http, plain_request, +}; +use serde_json::json; +use std::sync::mpsc::channel; +use std::time::{Duration, Instant}; +use support::{FakeServer, Reply, first_tool_name}; + +fn cfg(url: &str, key: Option<&str>) -> ApiConfig { + ApiConfig { + protocol: Protocol::OpenAi, + base_url: url.into(), + model: "m".into(), + key: key.map(str::to_string), + system_note: String::new(), + } +} + +/// A host that answers every tool call with "ok". +fn host() -> StartContext { + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for r in rx { + let _ = r + .reply + .send(json!({"content": [{"type": "text", "text": "ok"}], "isError": false})); + } + }); + StartContext { + work_dir: std::path::PathBuf::new(), + tools: Some(tx), + } +} + +fn run_until(b: &mut ApiBackend, done: impl Fn(&Event) -> bool) -> Result, String> { + let end = Instant::now() + Duration::from_secs(15); + let mut all = Vec::new(); + while Instant::now() < end { + for e in b.poll() { + let stop = done(&e); + all.push(e); + if stop { + return Ok(all); + } + } + std::thread::sleep(Duration::from_millis(5)); + } + Err(format!("no end of turn; saw {all:?}")) +} + +fn ended(e: &Event) -> bool { + matches!(e, Event::TurnEnded { .. }) +} + +fn start(srv: &FakeServer, key: Option<&str>, ctx: StartContext) -> Result { + let mut b = ApiBackend::start(cfg(&srv.url, key), ctx, plain_http())?; + b.prompt(&[PromptPart::Text("go".into())]); + Ok(b) +} + +#[test] +fn a_two_call_tool_loop_runs_over_a_socket_and_sends_tool_ids_back() -> Result<(), String> { + let name = first_tool_name()?; + let srv = FakeServer::start(vec![Reply::calls(&name, 1), Reply::text("done")])?; + let mut b = start(&srv, None, host())?; + run_until(&mut b, ended)?; + let posts = srv.posts(); + assert_eq!(posts.len(), 2); + assert_eq!(posts[0].path, "/v1/chat/completions"); + assert!( + posts[0].body["tools"] + .as_array() + .is_some_and(|t| !t.is_empty()) + ); + let msgs = posts[1].body["messages"].as_array().ok_or("no messages")?; + let roles: Vec<&str> = msgs.iter().filter_map(|m| m["role"].as_str()).collect(); + assert_eq!(roles, vec!["system", "user", "assistant", "tool"]); + assert_eq!(msgs[3]["tool_call_id"], "c0"); + Ok(()) +} + +#[test] +fn the_turn_stops_at_twenty_four_requests_over_a_socket() -> Result<(), String> { + let name = first_tool_name()?; + let srv = FakeServer::start(vec![Reply::calls(&name, 1)])?; + let mut b = start(&srv, None, host())?; + let events = run_until(&mut b, ended)?; + assert_eq!(srv.posts().len(), 24); + assert!( + matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "max_turn_requests") + ); + Ok(()) +} + +#[test] +fn cancel_while_the_server_is_slow_ends_the_turn_as_cancelled() -> Result<(), String> { + let srv = FakeServer::start(vec![Reply::text("late").after(3000)])?; + let mut b = start(&srv, None, host())?; + let end = Instant::now() + Duration::from_secs(10); + while srv.posts().is_empty() && Instant::now() < end { + std::thread::sleep(Duration::from_millis(5)); + } + let t = Instant::now(); + b.cancel(); + let events = run_until(&mut b, ended)?; + assert!(t.elapsed() < Duration::from_secs(2)); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "cancelled")); + Ok(()) +} + +#[test] +fn a_401_is_a_plain_sentence_and_the_key_stays_out_of_it() -> Result<(), String> { + let srv = FakeServer::start(vec![Reply::json( + 401, + json!({"error": {"message": "Incorrect API key provided"}}), + )])?; + let mut b = start(&srv, Some("sk-secret-123"), host())?; + let events = run_until(&mut b, ended)?; + let err = events + .iter() + .find_map(|e| { + if let Event::Error(t) = e { + Some(t.clone()) + } else { + None + } + }) + .ok_or("no error")?; + assert!(err.starts_with("HTTP 401"), "{err}"); + assert!(!err.contains("sk-secret-123")); + let sent = srv.posts(); + assert!( + sent[0] + .headers + .iter() + .any(|(k, v)| k == "authorization" && v == "Bearer sk-secret-123") + ); + assert!(!format!("{events:?}").contains("sk-secret-123")); + Ok(()) +} + +#[test] +fn a_reply_that_is_not_json_ends_the_turn_without_a_crash() -> Result<(), String> { + let srv = FakeServer::start(vec![Reply { + status: 200, + body: "oops".into(), + delay_ms: 0, + }])?; + let mut b = start(&srv, None, host())?; + let events = run_until(&mut b, ended)?; + assert!(events.iter().any(|e| matches!(e, Event::Error(_))) || events.len() > 1); + assert_eq!(srv.posts().len(), 1); + Ok(()) +} + +#[test] +fn a_slow_server_hits_the_request_timeout() -> Result<(), String> { + let srv = FakeServer::start(vec![Reply::text("late").after(4000)])?; + let req = HttpRequest { + method: "POST", + url: format!("{}/chat/completions", srv.url), + headers: vec![], + body: Some(b"{}".to_vec()), + timeout_s: 1, + }; + let t = Instant::now(); + let err = plain_request(&req).err().ok_or("expected a timeout")?; + assert!(err.contains("timed out"), "{err}"); + assert!(t.elapsed() < Duration::from_secs(3)); + Ok(()) +} + +#[test] +fn the_plain_function_refuses_https_and_does_not_follow_redirects() -> Result<(), String> { + let mk = |url: String| HttpRequest { + method: "GET", + url, + headers: vec![], + body: None, + timeout_s: 5, + }; + assert!(plain_request(&mk("https://127.0.0.1:1/".into())).is_err()); + let srv = FakeServer::start(vec![])?; + let _ = srv; + let redirect = FakeServer::start(vec![Reply::json(302, json!({}))])?; + let mut r = mk(format!("{}/x", redirect.url)); + r.method = "POST"; + r.body = Some(b"{}".to_vec()); + assert_eq!(plain_request(&r)?.0, 302); + assert_eq!(redirect.posts().len(), 1); + Ok(()) +} diff --git a/crates/assistant/tests/support/mod.rs b/crates/assistant/tests/support/mod.rs new file mode 100644 index 000000000..d24745d72 --- /dev/null +++ b/crates/assistant/tests/support/mod.rs @@ -0,0 +1,194 @@ +//! Test-only fake OpenAI-compatible server on 127.0.0.1:0, plus small helpers. +//! +//! Context: `FakeServer` replays a script of replies, one per request, and records what it +//! received. Local rules: loopback only, every wait has a timeout, no panics in helpers. +#![allow(dead_code)] + +use serde_json::{Value, json}; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// One scripted reply. +/// +/// # Do not +/// Put a real key in a reply body. +#[derive(Clone)] +pub struct Reply { + pub status: u16, + pub body: String, + pub delay_ms: u64, +} + +impl Reply { + /// A JSON reply with `status`. + pub fn json(status: u16, v: Value) -> Reply { + Reply { + status, + body: v.to_string(), + delay_ms: 0, + } + } + /// A 200 chat completion with plain text. + pub fn text(t: &str) -> Reply { + Reply::json( + 200, + json!({"choices": [{"message": {"role": "assistant", "content": t}}]}), + ) + } + /// A 200 chat completion asking for `n` calls of tool `name` with empty arguments. + pub fn calls(name: &str, n: usize) -> Reply { + let calls: Vec = (0..n) + .map(|i| { + json!({"id": format!("c{i}"), "type": "function", + "function": {"name": name, "arguments": "{}"}}) + }) + .collect(); + Reply::json( + 200, + json!({"choices": [{"message": {"role": "assistant", + "content": null, "tool_calls": calls}}]}), + ) + } + /// The same reply after waiting `ms` milliseconds. + pub fn after(mut self, ms: u64) -> Reply { + self.delay_ms = ms; + self + } +} + +/// What the server saw for one request. +#[derive(Clone, Debug)] +pub struct Seen { + pub method: String, + pub path: String, + pub headers: Vec<(String, String)>, + pub body: Value, +} + +/// The fake server; it stops when dropped. +pub struct FakeServer { + pub url: String, + seen: Arc>>, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + match m.lock() { + Ok(g) => g, + Err(e) => e.into_inner(), + } +} + +impl FakeServer { + /// Bind a loopback port and answer POSTs from `script` in order (the last reply repeats). + /// `GET` answers an empty model list. + pub fn start(script: Vec) -> Result { + let listener = TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?; + let port = listener.local_addr().map_err(|e| e.to_string())?.port(); + let seen: Arc>> = Arc::default(); + let log = seen.clone(); + std::thread::spawn(move || { + let mut posts = 0usize; + for conn in listener.incoming() { + let Ok(conn) = conn else { continue }; + let Some(req) = read_request(&conn) else { + continue; + }; + let is_post = req.method == "POST"; + lock(&log).push(req); + let reply = if is_post { + let r = script.get(posts).or(script.last()).cloned(); + posts += 1; + r + } else { + Some(Reply::json(200, json!({"data": []}))) + }; + if let Some(r) = reply { + std::thread::spawn(move || answer(conn, r)); + } + } + }); + Ok(FakeServer { + url: format!("http://127.0.0.1:{port}/v1"), + seen, + }) + } + + /// Every request so far. + pub fn requests(&self) -> Vec { + lock(&self.seen).clone() + } + + /// The JSON bodies of the POST requests so far. + pub fn posts(&self) -> Vec { + self.requests() + .into_iter() + .filter(|r| r.method == "POST") + .collect() + } +} + +fn answer(mut c: TcpStream, r: Reply) { + std::thread::sleep(Duration::from_millis(r.delay_ms)); + let out = format!( + "HTTP/1.1 {} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + r.status, + r.body.len(), + r.body + ); + let _ = c.write_all(out.as_bytes()); +} + +fn read_request(mut c: &TcpStream) -> Option { + let _ = c.set_read_timeout(Some(Duration::from_secs(10))); + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let end = loop { + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break i; + } + let n = c.read(&mut chunk).ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&chunk[..n]); + }; + let head = String::from_utf8_lossy(&buf[..end]).into_owned(); + let mut lines = head.split("\r\n"); + let mut first = lines.next()?.split(' '); + let method = first.next()?.to_string(); + let path = first.next()?.to_string(); + let headers: Vec<(String, String)> = lines + .filter_map(|l| l.split_once(':')) + .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string())) + .collect(); + let len = headers + .iter() + .find(|(k, _)| k == "content-length") + .and_then(|(_, v)| v.parse::().ok()) + .unwrap_or(0); + let mut body = buf[end + 4..].to_vec(); + while body.len() < len { + let n = c.read(&mut chunk).ok()?; + if n == 0 { + break; + } + body.extend_from_slice(&chunk[..n]); + } + let body = serde_json::from_slice(&body).unwrap_or(Value::Null); + Some(Seen { + method, + path, + headers, + body, + }) +} + +/// The name of the first registry tool, so scripted calls are real ones. +pub fn first_tool_name() -> Result { + pcbcraft_mcp::tool_list()["tools"][0]["name"] + .as_str() + .map(str::to_string) + .ok_or_else(|| "no tools".to_string()) +} diff --git a/crates/calc/Cargo.toml b/crates/calc/Cargo.toml new file mode 100644 index 000000000..bcafa0bb1 --- /dev/null +++ b/crates/calc/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "pcbcraft-calc" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] + +[dev-dependencies] +serde.workspace = true +toml.workspace = true diff --git a/crates/calc/data/calculators.toml b/crates/calc/data/calculators.toml new file mode 100644 index 000000000..45b043506 --- /dev/null +++ b/crates/calc/data/calculators.toml @@ -0,0 +1,1286 @@ +# PCBCraft Help reference: calculators. +# Machine-readable companion to calculators.md. One [[calculator]] per tool. +# Every calculator becomes one engine read command `calc.` (crates/calc, see +# calculators.md section "Where it lives") and one card in the Help Reference panel. +# +# Field notes +# inputs[].range closed interval the command accepts; outside it the command +# returns Error::Invalid with the range in the message. +# formula exact expression the implementation must use. SI units unless +# the unit column says otherwise. +# accuracy what the model claims against its own reference, never against +# reality; fabrication tolerance dominates. +# vector golden test. `expect` values were computed by +# pcbcraft-research/ee-thesaurus/vectors.py (stdlib Python) and +# cross-checked against the named reference. Tolerance is relative. +# +# Constants shared by several calculators (crates/calc/src/consts.rs): +# RHO_CU = 1.72e-8 ohm m annealed copper at 20 C +# ALPHA_CU = 0.00393 1/K copper temperature coefficient of resistance +# K_CU = 385 W/(m K) copper thermal conductivity +# OZ_UM = 34.79 um copper thickness per oz/ft2 (fabs round to 35) +# MIL_MM = 0.0254 mm +# C0 = 299792458 m/s +# ZF0 = 376.730313668 ohm + +schema_version = 1 + +# ---------------------------------------------------------------- basic circuit + +[[calculator]] +id = "ohms_law" +name = "Ohm's law and power" +group = "basic" +summary = "Give any two of voltage, current and resistance; get the third and the power." +inputs = [ + { name = "voltage", unit = "V", range = [0.0, 1.0e6], optional = true }, + { name = "current", unit = "A", range = [0.0, 1.0e6], optional = true }, + { name = "resistance", unit = "ohm", range = [1.0e-9, 1.0e12], optional = true }, +] +outputs = ["voltage V", "current A", "resistance ohm", "power W"] +formula = "V = I R; P = V I = I^2 R = V^2 / R. Exactly two inputs must be given." +source = "Ohm's law and Joule heating, any introductory circuits text (Horowitz and Hill, The Art of Electronics, 3rd ed., ch. 1)." +validity = "Linear resistors at DC or RMS AC. Not for reactive loads (use reactance)." +accuracy = "exact" +[[calculator.vector]] +inputs = { voltage = 12, resistance = 100 } +expect = { current = 0.12, power = 1.44 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { current = 0.02, resistance = 330 } +expect = { voltage = 6.6, power = 0.132 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { voltage = 5, current = 2 } +expect = { resistance = 2.5, power = 10 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" + +[[calculator]] +id = "series_parallel" +name = "Series and parallel R, C, L" +group = "basic" +summary = "Combine up to 16 resistors, capacitors or inductors in series or in parallel." +inputs = [ + { name = "kind", unit = "enum", values = ["resistor", "capacitor", "inductor"] }, + { name = "values", unit = "ohm | F | H", range = [1.0e-15, 1.0e12], array = [2, 16] }, +] +outputs = ["series", "parallel"] +formula = "R, L series = sum; parallel = 1 / sum(1/x). C is the reverse: parallel = sum, series = 1 / sum(1/x)." +source = "Kirchhoff's laws; any introductory text." +validity = "Ideal components." +accuracy = "exact" +[[calculator.vector]] +inputs = { kind = "resistor", values = [100, 220, 330] } +expect = { series = 650, parallel = 56.8966 } +tolerance = 1e-5 +crosscheck = "hand arithmetic: 1/(0.01+0.0045455+0.0030303)" +[[calculator.vector]] +inputs = { kind = "capacitor", values = [1.0e-6, 2.2e-6] } +expect = { parallel = 3.2e-6, series = 6.875e-7 } +tolerance = 1e-5 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { kind = "inductor", values = [10e-6, 22e-6] } +expect = { series = 32e-6, parallel = 6.875e-6 } +tolerance = 1e-5 +crosscheck = "hand arithmetic" + +[[calculator]] +id = "voltage_divider" +name = "Voltage divider with load" +group = "basic" +summary = "Output voltage of two resistors, with an optional load resistor across the output." +inputs = [ + { name = "vin", unit = "V", range = [0.0, 1.0e5] }, + { name = "r1", unit = "ohm", range = [1.0e-3, 1.0e12] }, + { name = "r2", unit = "ohm", range = [1.0e-3, 1.0e12] }, + { name = "load", unit = "ohm", range = [1.0e-3, 1.0e12], optional = true }, +] +outputs = ["vout V", "current A (through r1)", "r2_effective ohm", "power_r1 W", "power_r2 W"] +formula = "R2e = load given ? R2 || load : R2; Vout = Vin R2e / (R1 + R2e); I = Vin / (R1 + R2e)." +source = "Horowitz and Hill, The Art of Electronics, 3rd ed., section 1.2.3 (voltage dividers) and Thevenin loading." +validity = "Linear resistors; load modelled as a resistor to ground." +accuracy = "exact" +[[calculator.vector]] +inputs = { vin = 12, r1 = 10000, r2 = 4700 } +expect = { vout = 3.83673, current = 8.16327e-4 } +tolerance = 1e-5 +crosscheck = "hand arithmetic 12*4700/14700" +[[calculator.vector]] +inputs = { vin = 12, r1 = 10000, r2 = 4700, load = 10000 } +expect = { vout = 2.90722 } +tolerance = 1e-5 +crosscheck = "4700||10000 = 3197.3 ohm; 12*3197.3/13197.3" +[[calculator.vector]] +inputs = { vin = 3.3, r1 = 1000, r2 = 1000, load = 100000 } +expect = { vout = 1.64179 } +tolerance = 1e-5 +crosscheck = "1000||100000 = 990.1; 3.3*990.1/1990.1" + +[[calculator]] +id = "led_resistor" +name = "LED series resistor" +group = "basic" +summary = "Resistor for an LED from supply voltage, forward voltage and wanted current, with the resistor's power and the nearest E-series value." +inputs = [ + { name = "supply", unit = "V", range = [0.1, 1000.0] }, + { name = "forward_voltage", unit = "V", range = [0.1, 50.0] }, + { name = "current", unit = "A", range = [1.0e-6, 10.0] }, + { name = "series", unit = "enum", values = ["E6", "E12", "E24", "E96"], default = "E24" }, +] +outputs = ["resistance ohm", "power W", "nearest_standard ohm", "current_with_standard A"] +formula = "R = (Vs - Vf) / I; P = (Vs - Vf) I. Refuse when Vf >= Vs." +source = "Ohm's law; typical Vf: red 1.8 to 2.2 V, green or blue or white 2.8 to 3.4 V (any LED datasheet)." +validity = "One LED or a series string whose total Vf is entered. Vf is current dependent, so the result is a starting point." +accuracy = "exact for the given Vf" +[[calculator.vector]] +inputs = { supply = 5, forward_voltage = 2.0, current = 0.02 } +expect = { resistance = 150, power = 0.06, nearest_standard = 150 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { supply = 12, forward_voltage = 3.2, current = 0.35 } +expect = { resistance = 25.1429, power = 3.08, nearest_standard = 24 } +tolerance = 1e-5 +crosscheck = "hand arithmetic; E24 nearest to 25.14 is 24 (log distance 0.0464 vs 27 at 0.0714)" +[[calculator.vector]] +inputs = { supply = 3.3, forward_voltage = 1.8, current = 0.005 } +expect = { resistance = 300, power = 0.0075, nearest_standard = 300 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" + +[[calculator]] +id = "rc_rl_time_constant" +name = "RC and RL time constant and cutoff" +group = "basic" +summary = "Time constant and the -3 dB corner frequency of a first-order RC or RL network." +inputs = [ + { name = "kind", unit = "enum", values = ["rc", "rl"] }, + { name = "resistance", unit = "ohm", range = [1.0e-3, 1.0e12] }, + { name = "capacitance", unit = "F", range = [1.0e-15, 1.0], optional = true }, + { name = "inductance", unit = "H", range = [1.0e-12, 1.0e3], optional = true }, +] +outputs = ["tau s", "cutoff Hz", "t_63 s", "t_95 s (3 tau)", "t_99 s (5 tau)"] +formula = "RC: tau = R C. RL: tau = L / R. fc = 1 / (2 pi tau)." +source = "First-order response; Horowitz and Hill, 3rd ed., section 1.4.2 and 1.7.1." +validity = "Single-pole networks only." +accuracy = "exact" +[[calculator.vector]] +inputs = { kind = "rc", resistance = 10000, capacitance = 100e-9 } +expect = { tau = 1.0e-3, cutoff = 159.155 } +tolerance = 1e-5 +crosscheck = "1/(2 pi 1e-3) = 159.15 Hz" +[[calculator.vector]] +inputs = { kind = "rl", resistance = 50, inductance = 10e-3 } +expect = { tau = 2.0e-4, cutoff = 795.775 } +tolerance = 1e-5 +crosscheck = "50/(2 pi 0.01)" +[[calculator.vector]] +inputs = { kind = "rc", resistance = 1000, capacitance = 1e-6 } +expect = { tau = 1.0e-3, cutoff = 159.155 } +tolerance = 1e-5 +crosscheck = "same tau as the first vector" + +[[calculator]] +id = "lc_resonance" +name = "Resonant frequency" +group = "basic" +summary = "Resonant frequency of an inductor and capacitor, or the L or C needed for a target frequency." +inputs = [ + { name = "inductance", unit = "H", range = [1.0e-12, 1.0e3], optional = true }, + { name = "capacitance", unit = "F", range = [1.0e-15, 1.0], optional = true }, + { name = "frequency", unit = "Hz", range = [1.0e-3, 1.0e12], optional = true }, +] +outputs = ["frequency Hz", "inductance H", "capacitance F", "characteristic_impedance ohm (sqrt(L/C))"] +formula = "f0 = 1 / (2 pi sqrt(L C)); solve for the missing one of the three." +source = "Thomson's formula; any circuits text." +validity = "Lossless LC. Real parts shift f0 by their parasitics." +accuracy = "exact" +[[calculator.vector]] +inputs = { inductance = 10e-6, capacitance = 100e-9 } +expect = { frequency = 159155 } +tolerance = 1e-5 +crosscheck = "sqrt(1e-12) = 1e-6; 1/(2 pi 1e-6)" +[[calculator.vector]] +inputs = { inductance = 1e-3, capacitance = 1e-6 } +expect = { frequency = 5032.92 } +tolerance = 1e-5 +crosscheck = "1/(2 pi sqrt(1e-9))" +[[calculator.vector]] +inputs = { inductance = 2.2e-6, capacitance = 22e-12 } +expect = { frequency = 2.28769e7 } +tolerance = 1e-5 +crosscheck = "sqrt(4.84e-17) = 6.957e-9" + +[[calculator]] +id = "reactance" +name = "Reactance" +group = "basic" +summary = "Reactance of a capacitor or inductor at a frequency." +inputs = [ + { name = "frequency", unit = "Hz", range = [1.0e-3, 1.0e12] }, + { name = "capacitance", unit = "F", range = [1.0e-15, 1.0], optional = true }, + { name = "inductance", unit = "H", range = [1.0e-12, 1.0e3], optional = true }, +] +outputs = ["xc ohm", "xl ohm"] +formula = "Xc = 1 / (2 pi f C); Xl = 2 pi f L." +source = "Any circuits text." +validity = "Ideal components; ignores ESR and self resonance." +accuracy = "exact" +[[calculator.vector]] +inputs = { frequency = 1000, capacitance = 1e-6 } +expect = { xc = 159.155 } +tolerance = 1e-5 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { frequency = 1e6, inductance = 10e-6 } +expect = { xl = 62.8319 } +tolerance = 1e-5 +crosscheck = "2 pi 10 = 62.83" +[[calculator.vector]] +inputs = { frequency = 100e6, capacitance = 100e-9 } +expect = { xc = 0.0159155 } +tolerance = 1e-5 +crosscheck = "hand arithmetic" + +[[calculator]] +id = "decibel" +name = "Decibel conversions" +group = "basic" +summary = "Convert between power ratio, voltage ratio, dB, dBm and watts." +inputs = [ + { name = "mode", unit = "enum", values = ["power_ratio", "voltage_ratio", "dbm_to_w", "w_to_dbm"] }, + { name = "value", unit = "ratio | dB | dBm | W", range = [-300.0, 1.0e12] }, +] +outputs = ["db", "ratio", "dbm", "watts"] +formula = "dB(power) = 10 log10(P2/P1); dB(voltage, equal impedance) = 20 log10(V2/V1); dBm = 10 log10(P / 1 mW); P = 1 mW * 10^(dBm/10)." +source = "IEEE Std 100 definitions; any RF text." +validity = "Voltage form assumes equal source and load impedance." +accuracy = "exact" +[[calculator.vector]] +inputs = { mode = "power_ratio", value = 2 } +expect = { db = 3.0103 } +tolerance = 1e-5 +crosscheck = "10 log10 2" +[[calculator.vector]] +inputs = { mode = "voltage_ratio", value = 10 } +expect = { db = 20 } +tolerance = 1e-9 +crosscheck = "20 log10 10" +[[calculator.vector]] +inputs = { mode = "w_to_dbm", value = 0.5 } +expect = { dbm = 26.9897 } +tolerance = 1e-5 +crosscheck = "10 log10(500)" +[[calculator.vector]] +inputs = { mode = "dbm_to_w", value = 30 } +expect = { watts = 1.0 } +tolerance = 1e-9 +crosscheck = "30 dBm is 1 W by definition" + +# ---------------------------------------------------------------- copper and current + +[[calculator]] +id = "trace_width" +name = "Trace width for current" +group = "copper" +summary = "Minimum copper width for a current and allowed temperature rise. IPC-2152 table lookup when inside its published range, IPC-2221 formula otherwise, both stated." +inputs = [ + { name = "current", unit = "A", range = [0.001, 100.0] }, + { name = "temperature_rise", unit = "K", range = [1.0, 100.0], default = 10 }, + { name = "copper_weight", unit = "oz/ft2", range = [0.25, 6.0], default = 1 }, + { name = "layer", unit = "enum", values = ["external", "internal"], default = "external" }, + { name = "method", unit = "enum", values = ["auto", "ipc2152", "ipc2221"], default = "auto" }, +] +outputs = ["width mm", "width mil", "cross_section mil2", "method_used", "notes"] +formula = """ +IPC-2221 (closed form, both layers): I = k dT^0.44 A^0.725, A in mil^2, k = 0.048 external, 0.024 internal. + A = (I / (k dT^0.44))^(1/0.725); width_mil = A / thickness_mil; thickness_mil = oz * 34.79 / 25.4. +IPC-2152 (table, used by `auto` only when layer = external, copper_weight = 1 and 1 A <= I <= 10 A and dT = 10 K): + log-log interpolation in the published 1 oz / 10 K external table + (A, mil): (1,10) (2,30) (3,50) (4,80) (5,110) (6,150) (7,180) (8,220) (9,260) (10,300). + Other copper weights scale width by 1/oz as a stated approximation (constant cross-section), flagged in notes. +""" +source = """ +IPC-2221 constants: Sierra Circuits, "How to optimize your PCB trace using IPC-2152" (sources/standards/ipc2152-protoexpress.txt) and Altium IPC-2221 calculator page (sources/standards/ipc2221-trace-calc-altium.txt); the standard itself is paywalled (IPC-2221C, shop.ipc.org). +IPC-2152 table: Altium, "PCB trace width vs current table" (sources/standards/ipc2152-altium-width-table.txt), a secondary reproduction of one IPC-2152 chart; the standard is paywalled (shop.ipc.org/ipc-2152). +Cross-check table: Philip McGaw trace width vs current table (sources/standards/trace-width-philipmcgaw.txt). +""" +validity = """ +IPC-2221 curves come from 1950s test boards; the standard describes them as conservative. Assumptions stated to the user: still air, no adjacent copper planes, trace length much longer than width, FR-4. +IPC-2152 published chart only covers 1 oz external copper at 10 K rise here; anything else falls back to IPC-2221 and the notes say so. +Internal layers: IPC-2152 found internal and external traces behave about the same when a plane is nearby; IPC-2221 halves internal current. The notes mention this. +""" +accuracy = "IPC-2221: matches the published 10 K table within 1 % (the 1 % is the 34.79 vs 35 um copper rounding). IPC-2152: interpolation of a secondary reproduction; treat as +-10 %." +[[calculator.vector]] +inputs = { current = 1, temperature_rise = 10, copper_weight = 1, layer = "external", method = "ipc2221" } +expect = { cross_section = 16.296, width_mm = 0.3022, width_mil = 11.8976 } +tolerance = 1e-4 +crosscheck = "Philip McGaw table: 1 A external 1 oz 10 C = 0.300 mm (0.7 % diff from copper thickness rounding)" +[[calculator.vector]] +inputs = { current = 2, temperature_rise = 10, copper_weight = 1, layer = "external", method = "ipc2221" } +expect = { cross_section = 42.3931, width_mm = 0.786154 } +tolerance = 1e-4 +crosscheck = "Philip McGaw table: 2 A external 1 oz = 0.781 mm" +[[calculator.vector]] +inputs = { current = 3, temperature_rise = 10, copper_weight = 1, layer = "internal", method = "ipc2221" } +expect = { cross_section = 192.927, width_mm = 3.57772 } +tolerance = 1e-4 +crosscheck = "Philip McGaw table: 3 A internal 1 oz = 3.56 mm" +[[calculator.vector]] +inputs = { current = 2, temperature_rise = 20, copper_weight = 2, layer = "external", method = "ipc2221" } +expect = { cross_section = 27.8356, width_mm = 0.258097 } +tolerance = 1e-4 +crosscheck = "vectors.py; dT^0.44 = 20^0.44 = 3.737" +[[calculator.vector]] +inputs = { current = 2, temperature_rise = 10, copper_weight = 1, layer = "external", method = "ipc2152" } +expect = { width_mil = 30, width_mm = 0.762 } +tolerance = 1e-9 +crosscheck = "table row read directly" +[[calculator.vector]] +inputs = { current = 2.5, temperature_rise = 10, copper_weight = 1, layer = "external", method = "ipc2152" } +expect = { width_mil = 39.7387, width_mm = 1.00936 } +tolerance = 1e-4 +crosscheck = "log-log between (2,30) and (3,50)" +[[calculator.vector]] +inputs = { current = 5, temperature_rise = 10, copper_weight = 1, layer = "external", method = "ipc2152" } +expect = { width_mil = 110, width_mm = 2.794 } +tolerance = 1e-9 +crosscheck = "table row read directly" + +[[calculator]] +id = "via_current_resistance" +name = "Via current and resistance" +group = "copper" +summary = "Current a plated via carries for a temperature rise, its DC resistance, and how many vias in parallel reach a target current." +inputs = [ + { name = "drill", unit = "mm", range = [0.05, 10.0] }, + { name = "plating", unit = "um", range = [5.0, 100.0], default = 25 }, + { name = "length", unit = "mm", range = [0.1, 10.0], default = 1.6 }, + { name = "temperature_rise", unit = "K", range = [1.0, 100.0], default = 10 }, + { name = "target_current", unit = "A", range = [0.001, 100.0], optional = true }, +] +outputs = ["barrel_area mm2", "current A", "resistance ohm", "count (for target_current)"] +formula = """ +A = pi/4 ((drill + 2 plating)^2 - drill^2) [mm^2]; A_mil2 = A / 0.0254^2. +I = 0.024 dT^0.44 A_mil2^0.725 (IPC-2221 internal-conductor constant, the usual via convention). +R = RHO_CU length / A. count = ceil(target_current / I). +""" +source = "IPC-2221 formula as for trace_width; via convention (barrel area with internal k) as described in Altium 'PCB via size and pad size guidelines' (sources/standards/via-pad-size-altium.txt). Copper resistivity 1.72e-8 ohm m (CRC Handbook)." +validity = "Plating thickness is what the fab actually deposits (IPC-6012 Class 2 average 20 um, Class 3 25 um); barrel resistance ignores the pad to barrel transition." +accuracy = "same as IPC-2221; resistance exact for the modelled cylinder" +[[calculator.vector]] +inputs = { drill = 0.3, plating = 25, length = 1.6, temperature_rise = 10 } +expect = { barrel_area = 0.0255254, current = 0.95117, resistance = 1.07814e-3 } +tolerance = 1e-4 +crosscheck = "hand: A = pi/4 (0.35^2 - 0.3^2) = 0.02553 mm2; R = 1.72e-8 * 1.6e-3 / 2.553e-8" +[[calculator.vector]] +inputs = { drill = 0.5, plating = 25, length = 1.6, temperature_rise = 10 } +expect = { barrel_area = 0.0412334, current = 1.34666, resistance = 6.6742e-4 } +tolerance = 1e-4 +crosscheck = "vectors.py" +[[calculator.vector]] +inputs = { drill = 0.2, plating = 20, length = 1.0, temperature_rise = 10, target_current = 3 } +expect = { barrel_area = 0.013823, current = 0.609732, resistance = 1.2443e-3, count = 5 } +tolerance = 1e-4 +crosscheck = "ceil(3 / 0.6097) = 5" + +[[calculator]] +id = "trace_resistance_drop" +name = "Trace resistance and voltage drop" +group = "copper" +summary = "DC resistance of a copper trace at a temperature, and the voltage drop and heat at a current." +inputs = [ + { name = "width", unit = "mm", range = [0.01, 100.0] }, + { name = "copper_weight", unit = "oz/ft2", range = [0.25, 6.0], default = 1 }, + { name = "length", unit = "mm", range = [0.1, 10000.0] }, + { name = "current", unit = "A", range = [0.0, 100.0], default = 0 }, + { name = "temperature", unit = "C", range = [-55.0, 200.0], default = 20 }, +] +outputs = ["resistance ohm", "voltage_drop V", "power W"] +formula = "t = oz * 34.79e-6 m; R20 = RHO_CU L / (w t); R = R20 (1 + ALPHA_CU (T - 20)); V = I R; P = I^2 R." +source = "Resistivity and temperature coefficient of copper, CRC Handbook of Chemistry and Physics (1.72e-8 ohm m, 0.00393 /K)." +validity = "DC and low frequency. Above about 1 MHz skin depth (66 um at 1 MHz for copper) makes the effective thickness smaller; a note says so when the user enters a frequency in the future." +accuracy = "exact for the model; real copper is 2 to 10 % thinner than nominal after etching" +[[calculator.vector]] +inputs = { width = 0.25, copper_weight = 1, length = 100, current = 0.5, temperature = 20 } +expect = { resistance = 0.197758, voltage_drop = 0.098879, power = 0.0494395 } +tolerance = 1e-4 +crosscheck = "hand: 1.72e-8 * 0.1 / (0.25e-3 * 34.79e-6)" +[[calculator.vector]] +inputs = { width = 1.0, copper_weight = 1, length = 50, current = 2.0, temperature = 20 } +expect = { resistance = 0.0247197, voltage_drop = 0.0494395 } +tolerance = 1e-4 +crosscheck = "quarter width x half length of vector 1 gives one eighth the resistance" +[[calculator.vector]] +inputs = { width = 0.25, copper_weight = 1, length = 100, current = 0.5, temperature = 70 } +expect = { resistance = 0.236617, voltage_drop = 0.118309 } +tolerance = 1e-4 +crosscheck = "vector 1 times (1 + 0.00393 * 50) = 1.1965" + +# ---------------------------------------------------------------- impedance and signal integrity + +[[calculator]] +id = "microstrip" +name = "Microstrip impedance" +group = "impedance" +summary = "Characteristic impedance and effective permittivity of a surface trace over one plane, or the width for a target impedance." +model = "Hammerstad and Jensen 1980 quasi-static, with the Hammerstad thickness correction" +inputs = [ + { name = "width", unit = "mm", range = [0.01, 100.0], optional = true }, + { name = "height", unit = "mm", range = [0.01, 10.0] }, + { name = "er", unit = "", range = [1.0, 20.0] }, + { name = "thickness", unit = "mm", range = [0.0, 0.5], default = 0.035 }, + { name = "target", unit = "ohm", range = [1.0, 1000.0], optional = true }, +] +outputs = ["z0 ohm", "eeff", "delay ps/mm", "width_for_target mm"] +formula = """ +u = w/h, ZF0 = 376.730313668. +ZL1(u) = ZF0/(2 pi) ln( f(u)/u + sqrt(1 + (2/u)^2) ), f(u) = 6 + (2 pi - 6) exp( -(30.666/u)^0.7528 ) +eeff(u, er) = (er+1)/2 + (er-1)/2 (1 + 10/u)^(-a b) +a(u) = 1 + ln( (u^4 + (u/52)^2) / (u^4 + 0.432) )/49 + ln( 1 + (u/18.1)^3 )/18.7 +b(er) = 0.564 ((er - 0.9)/(er + 3))^0.053 +thickness (tn = t/h): du1 = tn/pi ln( 1 + 4e/tn tanh^2( sqrt(6.517 u) ) ); dur = du1 (1 + sech( sqrt(er - 1) ))/2; u1 = u + du1; ur = u + dur +Z0 = ZL1(ur) / sqrt(eeff(ur, er)); eeff_t = eeff(ur, er) (ZL1(u1)/ZL1(ur))^2 +delay = sqrt(eeff_t) / C0. +width_for_target: bisection of Z0(w) on [0.01, 100] mm, 80 steps (Z0 is monotonic in w). +""" +source = "Qucs technical documentation, microstrip line, https://qucs.sourceforge.net/tech/node75.html (transcription checked in pcbcraft-research/research-283-length-impedance.md); independent implementation scikit-rf MLine (BSD-3) https://scikit-rf.readthedocs.io/en/latest/_modules/skrf/media/mline.html. Original: E. Hammerstad and O. Jensen, 'Accurate models for microstrip computer-aided design', IEEE MTT-S 1980." +validity = "0.01 <= w/h <= 100, er < 128 (fit range). Quasi-static: no dispersion, fine below a few GHz on FR-4. Solder mask not modelled (lowers Z0 by 1 to 3 ohm)." +accuracy = "Fit error 0.01 % (w/h <= 1) and 0.03 % (w/h <= 1000) for Z0 against the zero-thickness quasi-static solution; eeff within 0.2 %. Fabrication tolerance on h and er dominates (5 to 10 %)." +[[calculator.vector]] +inputs = { width = 1.0, height = 1.6, er = 4.5, thickness = 0.035 } +expect = { z0 = 85.0992, eeff = 3.09458, delay = 5.86786 } +tolerance = 1e-4 +crosscheck = "research-283-length-impedance.md H-J column: 85.10 ohm" +[[calculator.vector]] +inputs = { width = 2.0, height = 1.6, er = 4.5, thickness = 0.035 } +expect = { z0 = 62.146, eeff = 3.25145 } +tolerance = 1e-4 +crosscheck = "research-283 table: 62.15 ohm" +[[calculator.vector]] +inputs = { width = 0.2, height = 1.6, er = 4.5, thickness = 0.035 } +expect = { z0 = 137.798 } +tolerance = 1e-4 +crosscheck = "research-283 table: 137.80 ohm" +[[calculator.vector]] +inputs = { height = 1.6, er = 4.5, thickness = 0.035, target = 50 } +expect = { width_for_target = 2.96591 } +tolerance = 1e-3 +crosscheck = "research-283: 50 ohm H-J width 2.966 mm" +[[calculator.vector]] +inputs = { width = 0.3, height = 0.2, er = 4.2, thickness = 0.035 } +expect = { z0 = 55.6389, eeff = 3.0048 } +tolerance = 1e-4 +crosscheck = "vectors.py; typical 4-layer outer trace" + +[[calculator]] +id = "embedded_microstrip" +name = "Embedded microstrip impedance" +group = "impedance" +summary = "Microstrip whose trace is covered by a dielectric layer (prepreg or thick mask), lowering the impedance." +model = "Hammerstad-Jensen surface microstrip plus the exponential cover correction of the effective permittivity" +inputs = [ + { name = "width", unit = "mm", range = [0.01, 100.0] }, + { name = "height", unit = "mm", range = [0.01, 10.0] }, + { name = "cover", unit = "mm", range = [0.0, 10.0], description = "dielectric above the trace top" }, + { name = "er", unit = "", range = [1.0, 20.0] }, + { name = "thickness", unit = "mm", range = [0.0, 0.5], default = 0.035 }, +] +outputs = ["z0 ohm", "eeff"] +formula = """ +(Z0s, eeff_s) = microstrip(w, h, er, t) +f = exp(-2 cover / h); eeff_e = eeff_s f + er (1 - f) +Z0 = Z0s sqrt(eeff_s / eeff_e) +""" +source = "The cover correction appears on calculator pages and in Wadell, 'Transmission Line Design Handbook' (Artech, 1991) ch. 3 as the usual engineering estimate; the IPC-2141 embedded form (paragraph 4.2.3) is paywalled and was criticised as wrong in the source trail (see Altium, 'Clearing trace impedance calculators and formulas', https://resources.altium.com/p/clearing-trace-impedance-calculators-and-formulas)." +validity = "cover <= 2 h. With cover >= 2 h the result approaches a fully buried line (eeff -> er) and a stripline model is better." +accuracy = "Engineering estimate, about 5 %. The UI labels it 'estimate; confirm with a field solver or the fab's stackup tool'." +[[calculator.vector]] +inputs = { width = 1.0, height = 1.6, cover = 0.1, er = 4.5, thickness = 0.035 } +expect = { z0 = 82.9155, eeff = 3.25972 } +tolerance = 1e-4 +crosscheck = "sanity: 0.1 mm cover lowers 85.10 ohm by 2.6 %" +[[calculator.vector]] +inputs = { width = 0.3, height = 0.2, cover = 0.2, er = 4.2, thickness = 0.035 } +expect = { z0 = 47.9943, eeff = 4.03825 } +tolerance = 1e-4 +crosscheck = "sanity: cover = h gives eeff near er" +[[calculator.vector]] +inputs = { width = 2.0, height = 1.6, cover = 1.6, er = 4.5, thickness = 0.035 } +expect = { z0 = 53.8463, eeff = 4.33103 } +tolerance = 1e-4 +crosscheck = "sanity: Z0s / sqrt(er/eeff_s) limit = 62.15 * sqrt(3.2515/4.5) = 52.8 ohm, approached" + +[[calculator]] +id = "stripline" +name = "Stripline impedance" +group = "impedance" +summary = "Trace centred between two planes (inner layer)." +model = "Steer 2020 closed form with thickness (as reproduced on Wikipedia 'Stripline'), equivalent to Cohn 1954" +inputs = [ + { name = "width", unit = "mm", range = [0.01, 100.0] }, + { name = "spacing", unit = "mm", range = [0.02, 20.0], description = "plane to plane distance b" }, + { name = "er", unit = "", range = [1.0, 20.0] }, + { name = "thickness", unit = "mm", range = [0.0, 0.5], default = 0.018 }, +] +outputs = ["z0 ohm", "delay ps/mm"] +formula = """ +W = w/b, T = t/b +Weff = W - (0.35 - W)^2 / (1 + 12 T) if W < 0.35, else W +Cf = (2/pi) ln(1/(1-T) + 1) - (T/pi) ln(1/(1-T)^2 - 1) +Z0 = (30 pi / sqrt(er)) (1 - T) / (Weff + Cf) +delay = sqrt(er) / C0 (fully embedded: eeff = er) +""" +source = "Wikipedia, 'Stripline', formula section citing M. Steer, Microwave and RF Design (LibreTexts 3.7, 2020); original S. B. Cohn, IRE Trans. MTT-2, 1954. Cross-check: IPC-2141 form Z0 = 60/sqrt(er) ln(4 b / (0.67 pi (0.8 w + t))) as printed by NextPCB, https://www.nextpcb.com/blog/pcb-impedance-calculator-microstrip-stripline-guide (that page's variable definition for h is inconsistent; b plane-to-plane makes its example agree)." +validity = "W/(1-T) > 0.05 and T < 0.025 for the stated accuracy; symmetric only. Offset (asymmetric) stripline is a follow-up." +accuracy = "At least 1 % against the exact conformal mapping (Steer). The IPC-2141 cross-check agrees within 1.2 % on the three vectors." +[[calculator.vector]] +inputs = { width = 0.2, spacing = 0.6, er = 4.2, thickness = 0.018 } +expect = { z0 = 55.0317 } +tolerance = 1e-4 +crosscheck = "IPC-2141 form with b = 0.6: 54.37 ohm (1.2 % lower)" +[[calculator.vector]] +inputs = { width = 0.12, spacing = 0.4, er = 4.2, thickness = 0.018 } +expect = { z0 = 55.7365 } +tolerance = 1e-4 +crosscheck = "IPC-2141 form: 55.54 ohm" +[[calculator.vector]] +inputs = { width = 0.3, spacing = 1.0, er = 4.5, thickness = 0.035 } +expect = { z0 = 54.9677 } +tolerance = 1e-4 +crosscheck = "IPC-2141 form: 54.68 ohm" + +[[calculator]] +id = "coplanar_waveguide" +name = "Coplanar waveguide impedance" +group = "impedance" +summary = "Trace with ground copper on both sides on the same layer, with or without a plane underneath." +model = "Quasi-static conformal mapping (Wen 1969; Ghione and Naldi 1984) with finite substrate, elliptic integral ratio by the Hilberg approximation" +inputs = [ + { name = "width", unit = "mm", range = [0.01, 100.0] }, + { name = "gap", unit = "mm", range = [0.01, 100.0] }, + { name = "height", unit = "mm", range = [0.01, 10.0] }, + { name = "er", unit = "", range = [1.0, 20.0] }, + { name = "ground_backed", unit = "bool", default = false }, +] +outputs = ["z0 ohm", "eeff", "delay ps/mm"] +formula = """ +K/K'(k): for 0 <= k <= 1/sqrt2: pi / ln( 2 (1 + sqrt(k')) / (1 - sqrt(k')) ), k' = sqrt(1 - k^2); + for 1/sqrt2 <= k <= 1: ln( 2 (1 + sqrt(k)) / (1 - sqrt(k)) ) / pi. +k1 = w / (w + 2 s) +CPW, finite substrate h: k2 = sinh(pi w / 4h) / sinh(pi (w + 2s) / 4h) + eeff = 1 + (er - 1)/2 * [K/K'(k2)] / [K/K'(k1)]; Z0 = 30 pi / (sqrt(eeff) K/K'(k1)) +Ground-backed CPW: k3 = tanh(pi w / 4h) / tanh(pi (w + 2s) / 4h) + q = K/K'(k3) / (K/K'(k1) + K/K'(k3)); eeff = 1 + q (er - 1); Z0 = 60 pi / (sqrt(eeff) (K/K'(k1) + K/K'(k3))) +Thickness ignored (Qucs eq. 12.14 to 12.18 is the optional refinement). +""" +source = "Qucs technical documentation, coplanar waveguides, https://qucs.sourceforge.net/tech/node86.html, eq. 12.4 to 12.13; scikit-rf CPW media (same equations) https://scikit-rf.readthedocs.io/en/latest/_modules/skrf/media/cpw.html." +validity = "Quasi-static; ground copper much wider than w + 2s; no thickness. Ground-backed form assumes the side grounds are tied to the plane by vias within a small fraction of a wavelength." +accuracy = "Hilberg ratio accurate to about 3e-6 (Qucs citing Gupta); formulas 'effectively exact' for the quasi-static zero-thickness case. Thickness and etch factor add a few percent." +[[calculator.vector]] +inputs = { width = 1.0, gap = 0.5, height = 1.6, er = 4.5, ground_backed = false } +expect = { z0 = 74.1723, eeff = 2.64227 } +tolerance = 1e-4 +crosscheck = "Hilberg ratio checked against numeric K(k) integration at k = 1/3: 0.639630785 both" +[[calculator.vector]] +inputs = { width = 1.0, gap = 0.5, height = 1.6, er = 4.5, ground_backed = true } +expect = { z0 = 67.099, eeff = 2.85453 } +tolerance = 1e-4 +crosscheck = "sanity: ground plane lowers Z0 and raises eeff" +[[calculator.vector]] +inputs = { width = 0.5, gap = 0.3, height = 1.6, er = 4.5, ground_backed = false } +expect = { z0 = 77.1232, eeff = 2.71546 } +tolerance = 1e-4 +crosscheck = "vectors.py" +[[calculator.vector]] +inputs = { width = 1.0, gap = 0.2, height = 0.2, er = 4.2, ground_backed = true } +expect = { z0 = 25.8399, eeff = 3.38531 } +tolerance = 1e-4 +crosscheck = "sanity: wide trace on thin dielectric is low impedance, near the microstrip value for w/h = 5" + +[[calculator]] +id = "differential_pair" +name = "Differential pair impedance" +group = "impedance" +summary = "Differential impedance of two equal surface traces side by side, and the gap or width for a target." +model = "Hammerstad-Jensen single-ended Z0 times the edge-coupling factor 2 (1 - 0.48 exp(-0.96 s/h)), widely attributed to IPC-2141" +inputs = [ + { name = "width", unit = "mm", range = [0.01, 100.0] }, + { name = "gap", unit = "mm", range = [0.01, 100.0] }, + { name = "height", unit = "mm", range = [0.01, 10.0] }, + { name = "er", unit = "", range = [1.0, 20.0] }, + { name = "thickness", unit = "mm", range = [0.0, 0.5], default = 0.035 }, + { name = "target", unit = "ohm", range = [10.0, 1000.0], optional = true }, +] +outputs = ["zdiff ohm", "z0_single ohm", "width_for_target mm (gap held)", "coupling_factor"] +formula = "Zdiff = 2 Z0(w, h, er, t) (1 - 0.48 exp(-0.96 s / h)); width_for_target by bisection with s fixed." +source = "Coupling factor as printed by NextPCB differential microstrip calculator https://www.nextpcb.com/differential-microstrip-impedance-calculator and many others, attributed to IPC-2141 (paywalled; TOC at https://www.ipc.org/TOC/IPC-2141A.pdf lists 4.4.1 edge-coupled surface microstrip). Not confirmed against the standard text (pcbcraft-research/research-283-length-impedance.md). Upgrade path: Hammerstad-Jensen coupled microstrip even/odd modes, Qucs https://qucs.sourceforge.net/tech/node77.html, odd-mode error under 0.3 %." +validity = "0.1 <= w/h <= 10, s/h >= 0.1, loosely coupled pairs (s >= w). For s < w the factor underestimates coupling." +accuracy = "Unverified against the standard; treat as +-10 %. The UI shows the word 'estimate' and the follow-up issue swaps in the coupled H-J model." +[[calculator.vector]] +inputs = { width = 0.2, gap = 0.2, height = 0.2, er = 4.2, thickness = 0.035 } +expect = { zdiff = 110.345, z0_single = 67.5956 } +tolerance = 1e-4 +crosscheck = "factor = 2 (1 - 0.48 e^-0.96) = 1.6325" +[[calculator.vector]] +inputs = { width = 0.3, gap = 0.2, height = 0.2, er = 4.2, thickness = 0.035 } +expect = { zdiff = 90.8262, z0_single = 55.6389 } +tolerance = 1e-4 +crosscheck = "Z0 single from microstrip vector 5" +[[calculator.vector]] +inputs = { width = 1.0, gap = 0.5, height = 1.6, er = 4.5, thickness = 0.035 } +expect = { zdiff = 109.677, z0_single = 85.0992 } +tolerance = 1e-4 +crosscheck = "factor = 2 (1 - 0.48 e^-0.3) = 1.2888" + +[[calculator]] +id = "propagation_delay" +name = "Propagation delay and length matching" +group = "impedance" +summary = "Signal speed on a trace from its effective permittivity, and the copper length a skew budget allows." +inputs = [ + { name = "eeff", unit = "", range = [1.0, 20.0], description = "from microstrip/stripline, or er for a buried trace" }, + { name = "length", unit = "mm", range = [0.0, 10000.0], optional = true }, + { name = "skew_budget", unit = "ps", range = [0.0, 1.0e6], optional = true }, +] +outputs = ["delay ps/mm", "delay ps/inch", "total_delay ps", "allowed_mismatch mm"] +formula = "tpd = sqrt(eeff) / C0; total = tpd L; allowed_mismatch = skew_budget / tpd." +source = "Johnson and Graham, High-Speed Digital Design (1993), ch. 1 (velocity of propagation); C0 = 299792458 m/s (SI)." +validity = "Quasi-TEM; use the eeff the impedance calculator gave for the same trace." +accuracy = "exact for the given eeff" +[[calculator.vector]] +inputs = { eeff = 3.2 } +expect = { delay = 5.96698, delay_inch = 151.561 } +tolerance = 1e-5 +crosscheck = "rule of thumb: about 150 ps/inch for FR-4 microstrip (Johnson and Graham)" +[[calculator.vector]] +inputs = { eeff = 4.5 } +expect = { delay = 7.07596, delay_inch = 179.729 } +tolerance = 1e-5 +crosscheck = "rule of thumb: about 180 ps/inch for FR-4 stripline" +[[calculator.vector]] +inputs = { eeff = 1.0 } +expect = { delay = 3.33564, delay_inch = 84.7253 } +tolerance = 1e-5 +crosscheck = "free space 1/c = 3.3356 ps/mm" +[[calculator.vector]] +inputs = { eeff = 3.2, skew_budget = 10 } +expect = { allowed_mismatch = 1.67589 } +tolerance = 1e-5 +crosscheck = "10 ps / 5.967 ps/mm" +[[calculator.vector]] +inputs = { eeff = 4.5, skew_budget = 25 } +expect = { allowed_mismatch = 3.53309 } +tolerance = 1e-5 +crosscheck = "25 / 7.076" + +[[calculator]] +id = "crosstalk" +name = "Crosstalk rule of thumb" +group = "impedance" +summary = "Rough near-end coupling between two parallel surface traces from their edge gap and dielectric height, plus the 3W spacing." +inputs = [ + { name = "gap", unit = "mm", range = [0.01, 100.0], description = "edge to edge" }, + { name = "height", unit = "mm", range = [0.01, 10.0] }, + { name = "width", unit = "mm", range = [0.01, 100.0] }, +] +outputs = ["coupling (fraction of aggressor swing)", "coupling_db", "three_w_gap mm", "spacing_for_minus_20db mm"] +formula = "coupling = 1 / (1 + (s/h)^2); dB = 20 log10(coupling); 3W gap = 2 w (centre to centre 3 w); s for -20 dB: s = 3 h." +source = "Johnson and Graham, High-Speed Digital Design (1993), section 5.4 crosstalk estimate (the 1/(1+(D/H)^2) form); 3W rule, Mark Montrose, Printed Circuit Board Design Techniques for EMC Compliance (IEEE Press, 2000)." +validity = "Order of magnitude only; microstrip over one plane; coupled length short against the rise time. Stripline couples less." +accuracy = "Rule of thumb; typical real values within a factor of 2." +[[calculator.vector]] +inputs = { gap = 0.2, height = 0.2, width = 0.2 } +expect = { coupling = 0.5, coupling_db = -6.0206, three_w_gap = 0.4 } +tolerance = 1e-4 +crosscheck = "s = h gives half" +[[calculator.vector]] +inputs = { gap = 0.6, height = 0.2, width = 0.2 } +expect = { coupling = 0.1, coupling_db = -20.0 } +tolerance = 1e-9 +crosscheck = "s = 3h gives one tenth, -20 dB" +[[calculator.vector]] +inputs = { gap = 0.1, height = 0.1, width = 0.15 } +expect = { coupling = 0.5, three_w_gap = 0.3 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" + +# ---------------------------------------------------------------- spacing and safety + +[[calculator]] +id = "conductor_spacing_ipc2221" +name = "Conductor spacing by voltage (IPC-2221)" +group = "spacing" +summary = "Minimum copper to copper spacing for a peak voltage, by board location class B1 to A7." +inputs = [ + { name = "voltage", unit = "V peak", range = [0.0, 100000.0] }, + { name = "location", unit = "enum", values = ["B1", "B2", "B3", "B4", "A5", "A6", "A7"], default = "B2" }, +] +outputs = ["spacing mm", "row_label", "location_description"] +formula = """ +Table lookup (V peak, mm) by column B1 internal | B2 external uncoated to 3050 m | B3 external uncoated above 3050 m | B4 external polymer coated | A5 assembly conformal coated | A6 component lead uncoated | A7 component lead coated: + <=15: 0.05 0.1 0.1 0.05 0.13 0.13 0.13 + <=30: 0.05 0.1 0.1 0.05 0.13 0.25 0.13 + <=50: 0.1 0.6 0.6 0.13 0.13 0.4 0.13 + <=100: 0.1 0.6 1.5 0.13 0.13 0.5 0.13 + <=150: 0.2 0.6 3.2 0.4 0.4 0.8 0.4 + <=170: 0.2 1.25 3.2 0.4 0.4 0.8 0.4 + <=250: 0.2 1.25 6.4 0.4 0.4 0.8 0.4 + <=300: 0.2 2.5 12.5 0.4 0.4 0.8 0.8 + <=500: 0.25 2.5 12.5 0.8 0.8 1.5 0.8 + >500: per volt 0.0025 0.005 0.025 0.00305 0.00305 0.00305 0.00305 (spacing = V * slope) +""" +source = "Reproductions of IPC-2221B table 6-1: Philip McGaw, 'Creepage and clearance' (sources/standards/ipc2221-spacing-philipmcgaw.txt), SFCircuits PCB School (sources/standards/ipc2221-spacing-sfcircuits.txt), Altium high-voltage calculator page (sources/standards/ipc2221-spacing-altium.txt); the standard is paywalled (IPC-2221C, shop.ipc.org)." +validity = "IPC-2221 is a design standard, not a safety standard; for mains or anything a person can touch use creepage_clearance_iec60664 and the product safety standard. Solder mask does not count as the B4 coating." +accuracy = "Table values reproduced identically by three secondary sources; the >500 V slopes are the standard's own linear extension." +[[calculator.vector]] +inputs = { voltage = 48, location = "B2" } +expect = { spacing = 0.6 } +tolerance = 1e-9 +crosscheck = "row 31 to 50 V, external uncoated" +[[calculator.vector]] +inputs = { voltage = 325.3, location = "B2" } +expect = { spacing = 2.5 } +tolerance = 1e-9 +crosscheck = "230 V RMS mains peak 325 V, row 301 to 500 V" +[[calculator.vector]] +inputs = { voltage = 325.3, location = "B4" } +expect = { spacing = 0.8 } +tolerance = 1e-9 +crosscheck = "same row, coated column" +[[calculator.vector]] +inputs = { voltage = 1000, location = "B2" } +expect = { spacing = 5.0 } +tolerance = 1e-9 +crosscheck = "1000 * 0.005" +[[calculator.vector]] +inputs = { voltage = 1000, location = "B1" } +expect = { spacing = 2.5 } +tolerance = 1e-9 +crosscheck = "1000 * 0.0025" + +[[calculator]] +id = "creepage_clearance_iec60664" +name = "Creepage and clearance (IEC 60664-1 lookup)" +group = "spacing" +summary = "Minimum clearance through air for the impulse voltage and creepage along the surface for the working voltage, pollution degree and material group." +inputs = [ + { name = "working_voltage", unit = "V RMS", range = [10.0, 1000.0] }, + { name = "mains_voltage", unit = "V RMS", range = [50.0, 1000.0], description = "nominal mains voltage line to neutral, picks the impulse voltage" }, + { name = "overvoltage_category", unit = "enum", values = ["I", "II", "III", "IV"], default = "II" }, + { name = "pollution_degree", unit = "enum", values = ["1", "2", "3"], default = "2" }, + { name = "material_group", unit = "enum", values = ["I", "II", "IIIa", "IIIb"], default = "IIIa", description = "from CTI: I >= 600, II 400 to 599, IIIa 175 to 399, IIIb 100 to 174" }, + { name = "insulation", unit = "enum", values = ["functional", "basic", "reinforced"], default = "basic" }, + { name = "altitude", unit = "m", range = [0.0, 5000.0], default = 2000 }, +] +outputs = ["impulse_voltage kV", "clearance mm", "creepage mm", "notes"] +formula = """ +1. Rated impulse voltage (Table F.1), by mains voltage ceiling (V) and overvoltage category I/II/III/IV in kV: + <=50: 0.33 0.5 0.8 1.5 | <=100: 0.5 0.8 1.5 2.5 | <=150: 0.8 1.5 2.5 4.0 | <=300: 1.5 2.5 4.0 6.0 | <=600: 2.5 4.0 6.0 8.0 | <=1000: 4.0 6.0 8.0 12.0 +2. Clearance (Table F.2, inhomogeneous field, up to 2000 m) by impulse kV -> mm: + 0.33: 0.01 | 0.5: 0.04 | 0.8: 0.1 | 1.5: 0.5 | 2.5: 1.5 | 4.0: 3.0 | 6.0: 5.5 | 8.0: 8.0 | 12: 14 + pollution degree 2 floor 0.2 mm, degree 3 floor 0.8 mm. Altitude above 2000 m: multiply by the F.8 factor (2000 m 1.00, 3000 m 1.14, 4000 m 1.29, 5000 m 1.48). + reinforced: use the impulse voltage one step higher in the F.1 ladder. +3. Creepage (Table F.5) by working voltage ceiling, pollution degree 1 (all groups) | degree 2 group I, II, III | degree 3 group I, II, III in mm: + 50: 0.18 | 0.6 0.85 1.2 | 1.5 1.7 1.9 + 63: 0.2 | 0.63 0.9 1.25 | 1.6 1.8 2.0 + 80: 0.22 | 0.67 0.95 1.3 | 1.7 1.9 2.1 + 100: 0.25 | 0.71 1.0 1.4 | 1.8 2.0 2.2 + 125: 0.28 | 0.75 1.05 1.5 | 1.9 2.1 2.4 + 160: 0.32 | 0.8 1.1 1.6 | 2.0 2.2 2.5 + 200: 0.42 | 1.0 1.4 2.0 | 2.5 2.8 3.2 + 250: 0.56 | 1.25 1.8 2.5 | 3.2 3.6 4.0 + 320: 0.75 | 1.6 2.2 3.2 | 4.0 4.5 5.0 + 400: 1.0 | 2.0 2.8 4.0 | 5.0 5.6 6.3 + 500: 1.3 | 2.5 3.6 5.0 | 6.3 7.1 8.0 + 630: 1.8 | 3.2 4.5 6.3 | 8.0 9.0 10.0 + 800: 2.4 | 4.0 5.6 8.0 | 10.0 11.0 12.5 + 1000: 3.2 | 5.0 7.1 10.0 | 12.5 14.0 16.0 + reinforced creepage = 2 x basic. Creepage is never less than clearance: result = max(creepage, clearance). +""" +source = "IEC 60664-1:2020 (paywalled, https://webstore.iec.ch/en/publication/59671). Table values from secondary reproductions: PTR Hartmann (sources/standards/creepage-ptr-hartmann.txt), Wurth Elektronik creepage and clearance of connectors PDF, Battery Design creepage calculator, VIOX IEC 60664-1 calculator (sources/standards/creepage-viox-calc.txt), Elektor parts 1 to 3 (sources/standards/creepage-elektor-part*.txt), TI SLUP421 and SLUAAR5 (sources/standards/iec60664-ti-*.pdf). Material group thresholds from IEC 60664-1 clause 4.8.1.3 as quoted by TI SLUAAR5." +validity = "Low-voltage equipment up to 1000 V RMS, frequency to 30 kHz. Product standards (IEC 62368-1, 60335, 61010, 60601) override these with their own tables. Secondary reproductions: the implementer must verify every row against the standard before the panel drops the 'verify' label." +accuracy = "Lookup; values are the standard's own. The panel shows 'reproduced from secondary sources, verify against IEC 60664-1' until a licensed copy has been checked." +[[calculator.vector]] +inputs = { working_voltage = 230, mains_voltage = 230, overvoltage_category = "II", pollution_degree = "2", material_group = "IIIa", insulation = "basic" } +expect = { impulse_voltage = 2.5, clearance = 1.5, creepage = 2.5 } +tolerance = 1e-9 +crosscheck = "Elektor part 2 worked example: 230 V mains, OVC II, PD2, group III: 1.5 mm clearance, 2.5 mm creepage (sources/standards/creepage-elektor-part2.txt)" +[[calculator.vector]] +inputs = { working_voltage = 230, mains_voltage = 230, overvoltage_category = "II", pollution_degree = "2", material_group = "IIIa", insulation = "reinforced" } +expect = { impulse_voltage = 4.0, clearance = 3.0, creepage = 5.0 } +tolerance = 1e-9 +crosscheck = "reinforced: next impulse step 4 kV -> 3.0 mm; creepage doubled to 5.0 mm (the usual 'about 5 mm' mains reinforced figure)" +[[calculator.vector]] +inputs = { working_voltage = 48, mains_voltage = 120, overvoltage_category = "II", pollution_degree = "2", material_group = "I", insulation = "functional" } +expect = { impulse_voltage = 1.5, clearance = 0.5, creepage = 0.6 } +tolerance = 1e-9 +crosscheck = "F.5 row 50 V, PD2, group I = 0.6 mm; F.2 1.5 kV = 0.5 mm" +[[calculator.vector]] +inputs = { working_voltage = 400, mains_voltage = 400, overvoltage_category = "III", pollution_degree = "3", material_group = "IIIa", insulation = "basic" } +expect = { impulse_voltage = 6.0, clearance = 5.5, creepage = 6.3 } +tolerance = 1e-9 +crosscheck = "F.1 600 V row, OVC III = 6 kV -> 5.5 mm; F.5 400 V PD3 group III = 6.3 mm" + +# ---------------------------------------------------------------- power and components + +[[calculator]] +id = "decoupling_capacitor" +name = "Decoupling capacitor sizing" +group = "components" +summary = "Bulk capacitance for a current step within a ripple budget, and the self-resonant frequency above which a capacitor stops being one." +inputs = [ + { name = "current_step", unit = "A", range = [1.0e-6, 1000.0] }, + { name = "step_time", unit = "s", range = [1.0e-12, 1.0] }, + { name = "ripple", unit = "V", range = [1.0e-4, 10.0] }, + { name = "esl", unit = "H", range = [1.0e-12, 1.0e-6], default = 1.0e-9, description = "capacitor plus mounting inductance" }, + { name = "capacitance", unit = "F", range = [1.0e-12, 1.0], optional = true, description = "a chosen part, for its self-resonance" }, +] +outputs = ["capacitance_needed F", "self_resonance Hz", "impedance_target ohm (ripple / current_step)"] +formula = "C = I dt / dV; f_srf = 1 / (2 pi sqrt(ESL C)); Ztarget = dV / I." +source = "Analog Devices MT-101 'Decoupling Techniques' (manifest: https://www.analog.com/media/en/training-seminars/tutorials/MT-101.pdf); the charge-balance form is in any power integrity text (Bogatin, Signal and Power Integrity Simplified, ch. 13)." +validity = "First-order. Below the SRF the part is a capacitor; above it the mounting inductance dominates, so several values in parallel cover a wider band. Place small ones nearest the pin." +accuracy = "Order of magnitude starting point." +[[calculator.vector]] +inputs = { current_step = 1.0, step_time = 5e-9, ripple = 0.05 } +expect = { capacitance_needed = 1.0e-7, impedance_target = 0.05 } +tolerance = 1e-9 +crosscheck = "1 A * 5 ns / 50 mV = 100 nF" +[[calculator.vector]] +inputs = { current_step = 0.5, step_time = 10e-9, ripple = 0.1 } +expect = { capacitance_needed = 5.0e-8 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { current_step = 0.5, step_time = 10e-9, ripple = 0.1, esl = 1e-9, capacitance = 100e-9 } +expect = { self_resonance = 1.59155e7 } +tolerance = 1e-5 +crosscheck = "1/(2 pi sqrt(1e-16)) = 15.9 MHz, the textbook 0603 100 nF SRF range" + +[[calculator]] +id = "i2c_pullup" +name = "I2C pull-up resistor" +group = "components" +summary = "Smallest and largest pull-up for an I2C bus from supply, sink current, rise time budget and bus capacitance." +inputs = [ + { name = "vcc", unit = "V", range = [1.0, 6.0] }, + { name = "vol_max", unit = "V", range = [0.0, 1.0], default = 0.4 }, + { name = "iol", unit = "A", range = [1.0e-4, 0.03], default = 3.0e-3 }, + { name = "rise_time", unit = "s", range = [1.0e-9, 1.0e-5], description = "1000 ns standard, 300 ns fast, 120 ns fast-plus" }, + { name = "bus_capacitance", unit = "F", range = [1.0e-12, 1.0e-9], description = "400 pF max standard and fast, 550 pF fast-plus" }, +] +outputs = ["rp_min ohm", "rp_max ohm", "suggested ohm (geometric mean, nearest E24)"] +formula = "Rp_min = (Vcc - VOL_max) / IOL; Rp_max = tr / (0.8473 Cb) (tr measured 30 % to 70 %, 0.8473 = ln(0.7/0.3))." +source = "Texas Instruments SLVA689, 'I2C Bus Pull-Up Resistor Calculation', equations 1 and 6 (sources/netrules/ti-slva689-i2c-pullup-sizing.txt). Bus limits from the NXP I2C-bus specification UM10204 (public)." +validity = "Open-drain bus; VOL and IOL from the weakest device on the bus." +accuracy = "exact for the model" +[[calculator.vector]] +inputs = { vcc = 3.3, vol_max = 0.4, iol = 3e-3, rise_time = 300e-9, bus_capacitance = 100e-12 } +expect = { rp_min = 966.667, rp_max = 3540.66 } +tolerance = 1e-5 +crosscheck = "SLVA689 figure: 3.3 V, 3 mA gives 967 ohm minimum" +[[calculator.vector]] +inputs = { vcc = 5.0, vol_max = 0.4, iol = 3e-3, rise_time = 1000e-9, bus_capacitance = 400e-12 } +expect = { rp_min = 1533.33, rp_max = 2950.55 } +tolerance = 1e-5 +crosscheck = "standard mode at the 400 pF limit: 1000e-9 / (0.8473 * 400e-12)" +[[calculator.vector]] +inputs = { vcc = 3.3, vol_max = 0.4, iol = 3e-3, rise_time = 120e-9, bus_capacitance = 50e-12 } +expect = { rp_min = 966.667, rp_max = 2832.53 } +tolerance = 1e-5 +crosscheck = "fast-mode plus on a short bus" + +[[calculator]] +id = "crystal_load_capacitors" +name = "Crystal load capacitors" +group = "components" +summary = "The two external capacitors for a Pierce oscillator from the crystal's specified load capacitance and the board stray capacitance." +inputs = [ + { name = "load_capacitance", unit = "pF", range = [4.0, 40.0] }, + { name = "stray_capacitance", unit = "pF", range = [0.0, 15.0], default = 3, description = "pin plus trace stray per side, typically 2 to 5 pF" }, + { name = "c1", unit = "pF", range = [1.0, 100.0], optional = true, description = "check mode: the pair you fitted" }, + { name = "c2", unit = "pF", range = [1.0, 100.0], optional = true }, +] +outputs = ["c1_c2 pF (equal pair)", "effective_load pF (check mode)", "nearest_e24 pF"] +formula = "CL = C1 C2 / (C1 + C2) + Cstray. For C1 = C2: C1 = C2 = 2 (CL - Cstray). Check mode returns CL for the fitted pair." +source = "Microchip AN826, 'Crystal Oscillator Basics and Crystal Selection', load capacitance section (sources/netrules/microchip-an826-crystal-oscillator-basics.txt); Raspberry Pi 'Hardware design with RP2040' crystal section (sources/netrules/rpi-hardware-design-with-rp2040.txt) as a worked example." +validity = "Pierce oscillator with the crystal between two pins. Cstray is a guess until measured; trim by checking frequency." +accuracy = "exact for the model; stray guess dominates" +[[calculator.vector]] +inputs = { load_capacitance = 12.5, stray_capacitance = 3 } +expect = { c1_c2 = 19 } +tolerance = 1e-9 +crosscheck = "2 (12.5 - 3) = 19; check: 19*19/38 + 3 = 12.5" +[[calculator.vector]] +inputs = { load_capacitance = 18, stray_capacitance = 5 } +expect = { c1_c2 = 26 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { load_capacitance = 8, stray_capacitance = 2.5 } +expect = { c1_c2 = 11 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" + +[[calculator]] +id = "timer_555" +name = "555 timer" +group = "components" +summary = "Astable frequency and duty cycle, or monostable pulse width, for the classic timer." +inputs = [ + { name = "mode", unit = "enum", values = ["astable", "monostable"] }, + { name = "r1", unit = "ohm", range = [1000.0, 1.0e7] }, + { name = "r2", unit = "ohm", range = [1000.0, 1.0e7], optional = true }, + { name = "c", unit = "F", range = [1.0e-12, 1.0e-2] }, +] +outputs = ["frequency Hz", "duty_cycle %", "t_high s", "t_low s", "pulse_width s"] +formula = "Astable: t_high = ln2 (R1 + R2) C; t_low = ln2 R2 C; f = 1 / (t_high + t_low); D = (R1 + R2) / (R1 + 2 R2). Monostable: t = ln3 R C (1.0986 R C, often rounded to 1.1 R C)." +source = "Wikipedia, '555 timer IC', design formulas section and worked tables (checked 2026-10-28); any 555 datasheet (TI NE555)." +validity = "Bipolar or CMOS 555 with R1 >= 1 k; duty cycle is always above 50 % in the basic astable." +accuracy = "exact for the model; the chip's comparator thresholds add a few percent" +[[calculator.vector]] +inputs = { mode = "astable", r1 = 8200, r2 = 68000, c = 10e-9 } +expect = { frequency = 1000.48, duty_cycle = 52.8433 } +tolerance = 1e-5 +crosscheck = "Wikipedia table: 8.2 k, 68 k, 10 nF gives 1 kHz (+0.048 %) at 52.8 %" +[[calculator.vector]] +inputs = { mode = "astable", r1 = 1000, r2 = 10000, c = 100e-9 } +expect = { frequency = 686.998, duty_cycle = 52.381 } +tolerance = 1e-5 +crosscheck = "1.4427 / (21000 * 100e-9)" +[[calculator.vector]] +inputs = { mode = "monostable", r1 = 91000, c = 10e-9 } +expect = { pulse_width = 9.99737e-4 } +tolerance = 1e-5 +crosscheck = "Wikipedia table: 91 k, 10 nF gives 1 ms (-0.026 %)" + +[[calculator]] +id = "opamp_gain" +name = "Op-amp gain" +group = "components" +summary = "Gain of the inverting and non-inverting resistor-feedback amplifiers, in ratio and dB." +inputs = [ + { name = "topology", unit = "enum", values = ["inverting", "non_inverting"] }, + { name = "rf", unit = "ohm", range = [1.0, 1.0e9] }, + { name = "rin", unit = "ohm", range = [1.0, 1.0e9], description = "input resistor (inverting) or ground resistor (non-inverting)" }, +] +outputs = ["gain", "gain_db", "input_impedance ohm (inverting: rin)"] +formula = "Inverting: G = -Rf / Rin. Non-inverting: G = 1 + Rf / Rg. dB = 20 log10 |G|." +source = "Horowitz and Hill, 3rd ed., sections 4.2.1 and 4.2.2." +validity = "Ideal op-amp, closed-loop gain well below the open-loop gain at the frequency of interest." +accuracy = "exact for the model" +[[calculator.vector]] +inputs = { topology = "inverting", rf = 100000, rin = 10000 } +expect = { gain = -10, gain_db = 20 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { topology = "non_inverting", rf = 47000, rin = 4700 } +expect = { gain = 11 } +tolerance = 1e-9 +crosscheck = "hand arithmetic" +[[calculator.vector]] +inputs = { topology = "non_inverting", rf = 1.0, rin = 1.0e9 } +expect = { gain = 1.000000001 } +tolerance = 1e-6 +crosscheck = "follower limit" + +[[calculator]] +id = "ldo_thermal" +name = "LDO dissipation and junction temperature" +group = "components" +summary = "Heat in a linear regulator and its junction temperature from theta-JA." +inputs = [ + { name = "vin", unit = "V", range = [0.5, 100.0] }, + { name = "vout", unit = "V", range = [0.1, 100.0] }, + { name = "iout", unit = "A", range = [0.0, 20.0] }, + { name = "iq", unit = "A", range = [0.0, 0.1], default = 0 }, + { name = "theta_ja", unit = "K/W", range = [1.0, 500.0] }, + { name = "ambient", unit = "C", range = [-55.0, 125.0], default = 25 }, + { name = "tj_max", unit = "C", range = [85.0, 175.0], default = 125 }, +] +outputs = ["power W", "rise K", "tj C", "headroom K (tj_max - tj)", "max_iout_at_tj_max A"] +formula = "P = (Vin - Vout) Iout + Vin Iq; Tj = Ta + P theta_JA; Imax = (((Tj_max - Ta)/theta_JA) - Vin Iq) / (Vin - Vout)." +source = "Any LDO datasheet thermal section, for example TI TLV1117 or the TI application report SLVA118 'Understanding thermal dissipation and design of a heatsink'; theta-JA definition JEDEC JESD51-2." +validity = "theta-JA is measured on a JEDEC test board; a real board with less copper runs hotter. Use the datasheet's theta-JA for the package and copper area closest to yours." +accuracy = "exact for the model; theta-JA uncertainty 20 to 50 %" +[[calculator.vector]] +inputs = { vin = 5.0, vout = 3.3, iout = 0.5, iq = 5e-3, theta_ja = 65, ambient = 25 } +expect = { power = 0.875, rise = 56.875, tj = 81.875 } +tolerance = 1e-6 +crosscheck = "1.7 V * 0.5 A + 5 V * 5 mA = 0.875 W" +[[calculator.vector]] +inputs = { vin = 12, vout = 5, iout = 0.3, iq = 1e-3, theta_ja = 50, ambient = 40 } +expect = { power = 2.112, tj = 145.6 } +tolerance = 1e-6 +crosscheck = "over 125 C: the panel flags it" +[[calculator.vector]] +inputs = { vin = 3.6, vout = 1.8, iout = 0.1, iq = 100e-6, theta_ja = 250, ambient = 25 } +expect = { power = 0.18036, tj = 70.09 } +tolerance = 1e-6 +crosscheck = "hand arithmetic" + +[[calculator]] +id = "battery_life" +name = "Battery life" +group = "components" +summary = "Run time from capacity and a duty-cycled load." +inputs = [ + { name = "capacity", unit = "mAh", range = [1.0, 1.0e6] }, + { name = "active_current", unit = "mA", range = [0.0, 1.0e5] }, + { name = "sleep_current", unit = "mA", range = [0.0, 1.0e5], default = 0 }, + { name = "active_fraction", unit = "", range = [0.0, 1.0], default = 1.0 }, + { name = "usable_fraction", unit = "", range = [0.1, 1.0], default = 0.85, description = "self-discharge, cutoff voltage and temperature derating" }, +] +outputs = ["average_current mA", "hours h", "days d"] +formula = "Iavg = Ia d + Is (1 - d); hours = capacity * usable_fraction / Iavg." +source = "Charge balance; derating guidance from any cell datasheet (for example Energizer CR2032 datasheet, Panasonic NCR18650B)." +validity = "Ignores Peukert and the cell's voltage curve; for a regulator between cell and load, use the input current of the regulator." +accuracy = "+-20 % in practice" +[[calculator.vector]] +inputs = { capacity = 2000, active_current = 100, active_fraction = 1.0, usable_fraction = 0.85 } +expect = { average_current = 100, hours = 17 } +tolerance = 1e-9 +crosscheck = "2000 * 0.85 / 100" +[[calculator.vector]] +inputs = { capacity = 2000, active_current = 20, sleep_current = 0.01, active_fraction = 0.01, usable_fraction = 0.85 } +expect = { average_current = 0.2099, hours = 8099.09, days = 337.462 } +tolerance = 1e-5 +crosscheck = "0.2 + 0.0099 = 0.2099 mA" +[[calculator.vector]] +inputs = { capacity = 220, active_current = 30, sleep_current = 0.005, active_fraction = 0.001, usable_fraction = 0.85 } +expect = { average_current = 0.034995, days = 222.651 } +tolerance = 1e-5 +crosscheck = "CR2032 class cell, beacon duty" + +[[calculator]] +id = "wire_gauge" +name = "Wire gauge ampacity" +group = "components" +summary = "Diameter, area, resistance and the usual current limits for an AWG size, or the AWG for a current." +inputs = [ + { name = "awg", unit = "", range = [0, 40], integer = true, optional = true }, + { name = "current", unit = "A", range = [0.01, 200.0], optional = true }, + { name = "insulation_rating", unit = "enum", values = ["60C", "75C", "90C"], default = "75C" }, +] +outputs = ["diameter mm", "area mm2", "resistance ohm/km", "ampacity A", "awg (for current)"] +formula = """ +d = 0.127 * 92^((36 - n)/39) mm; A = pi d^2 / 4; R/km = RHO_CU / A * 1e9 (A in mm2). +Ampacity table (A) for 60C/75C/90C insulation, NEC 310.16 single conductors in free air not used; enclosed values: + 10: 30/35/40 12: 20/25/30 14: 15/20/25 16: 12/16/18 18: 10/14/16 20: 5/11/- 22: 3/7/- 24: 2.1/3.5/- 26: 1.3/2.2/- 28: 0.83/1.4/- 30: 0.52/0.86/- +awg for current: smallest gauge number whose ampacity at the rating >= current. +""" +source = "Wikipedia, 'American wire gauge' (formula, table rows and NEC-derived ampacity columns; checked 2026-10-28); ampacity ultimately NFPA 70 (NEC) table 310.16." +validity = "Solid copper at 20 C. Ampacity depends on bundling, ambient and insulation; the NEC columns are for building wire. For PCB wire-to-board use the connector's rating." +accuracy = "Diameter and area exact from the AWG definition; resistance within 0.3 % of the published table (resistivity rounding)." +[[calculator.vector]] +inputs = { awg = 10 } +expect = { diameter = 2.58819, area = 5.26115, resistance = 3.26924, ampacity = 35 } +tolerance = 1e-5 +crosscheck = "Wikipedia: 2.588 mm, 5.26 mm2, 3.277 ohm/km, 35 A at 75 C" +[[calculator.vector]] +inputs = { awg = 18 } +expect = { diameter = 1.02369, area = 0.823047, resistance = 20.898, ampacity = 14 } +tolerance = 1e-5 +crosscheck = "Wikipedia: 1.024 mm, 0.823 mm2, 20.95 ohm/km, 14 A at 75 C" +[[calculator.vector]] +inputs = { awg = 24 } +expect = { diameter = 0.510559, area = 0.20473, resistance = 84.013, ampacity = 3.5 } +tolerance = 1e-5 +crosscheck = "Wikipedia: 0.511 mm, 0.205 mm2, 84.22 ohm/km, 3.5 A at 75 C" +[[calculator.vector]] +inputs = { current = 4, insulation_rating = "75C" } +expect = { awg = 22 } +tolerance = 0 +crosscheck = "22 AWG carries 7 A at 75 C, 24 AWG only 3.5 A" + +[[calculator]] +id = "resistor_code" +name = "Resistor colour code and SMD code" +group = "components" +summary = "Decode colour bands (4, 5 or 6) and SMD markings (3-digit, 4-digit, R-notation, EIA-96), or encode a value." +inputs = [ + { name = "bands", unit = "colour names", array = [3, 6], optional = true }, + { name = "smd_code", unit = "text", pattern = "^[0-9R]{3,4}$|^[0-9]{2}[A-Z]$", optional = true }, + { name = "value", unit = "ohm", range = [1.0e-3, 1.0e12], optional = true, description = "encode mode" }, +] +outputs = ["resistance ohm", "tolerance %", "tempco ppm/K", "bands", "smd_3digit", "smd_eia96"] +formula = """ +Colour digits: black 0 brown 1 red 2 orange 3 yellow 4 green 5 blue 6 violet 7 grey 8 white 9. +Multiplier: same digit as power of ten; gold 0.1, silver 0.01, pink 0.001. +Tolerance: brown 1 % (F), red 2 % (G), green 0.5 % (D), blue 0.25 % (C), violet 0.1 % (B), grey 0.01 % (L), gold 5 % (J), silver 10 % (K), none 20 % (M). +Tempco (6th band): brown 100, red 50, orange 15, yellow 25, blue 10, violet 5 ppm/K. +4 bands = 2 digits + multiplier + tolerance; 5 bands = 3 digits + multiplier + tolerance; 6 = 5 + tempco. +SMD: 3-digit "ABC" = AB * 10^C; 4-digit "ABCD" = ABC * 10^D; "R" marks the decimal point (4R7 = 4.7, R10 = 0.10). +EIA-96 "NNL": NN is the 1-based index into E96 (01 = 1.00 ... 96 = 9.76, three significant digits), L is the multiplier letter: + Z 0.001, Y or R 0.01, X or S 0.1, A 1, B or H 10, C 100, D 1000, E 10000, F 100000. +""" +source = "Wikipedia, 'Electronic color code' (IEC 60062:2016 table; checked 2026-10-28). EIA-96 letters: xdevs resistor SMD code guide https://xdevs.com/guide/rescode/ and pimylifeup SMD resistor guide https://pimylifeup.com/smd-resistor/ (both agree on Z Y/R X/S A B/H C D E F)." +validity = "Manufacturers deviate; the decoder shows 'check the datasheet' for grey or white multipliers and for codes with unusual letters." +accuracy = "exact decoding" +[[calculator.vector]] +inputs = { bands = ["yellow", "violet", "red", "gold"] } +expect = { resistance = 4700, tolerance = 5 } +tolerance = 1e-9 +crosscheck = "the classic 4.7 k" +[[calculator.vector]] +inputs = { bands = ["brown", "black", "black", "red", "brown"] } +expect = { resistance = 10000, tolerance = 1 } +tolerance = 1e-9 +crosscheck = "100 * 100" +[[calculator.vector]] +inputs = { bands = ["orange", "orange", "gold", "gold"] } +expect = { resistance = 3.3, tolerance = 5 } +tolerance = 1e-9 +crosscheck = "33 * 0.1" +[[calculator.vector]] +inputs = { smd_code = "472" } +expect = { resistance = 4700 } +tolerance = 1e-9 +crosscheck = "47 * 10^2" +[[calculator.vector]] +inputs = { smd_code = "4R7" } +expect = { resistance = 4.7 } +tolerance = 1e-9 +crosscheck = "R as decimal point" +[[calculator.vector]] +inputs = { smd_code = "68X" } +expect = { resistance = 49.9 } +tolerance = 1e-9 +crosscheck = "xdevs guide: 68X = 49.9 ohm (index 68 = 499, X = 0.1)" +[[calculator.vector]] +inputs = { smd_code = "01A" } +expect = { resistance = 100 } +tolerance = 1e-9 +crosscheck = "xdevs guide: 01A = 100 ohm" +[[calculator.vector]] +inputs = { smd_code = "34C" } +expect = { resistance = 22100 } +tolerance = 1e-9 +crosscheck = "index 34 = 221, C = 100" + +[[calculator]] +id = "e_series" +name = "E-series nearest value" +group = "components" +summary = "Nearest standard value in E6, E12, E24, E48, E96 or E192, the neighbours either side, and the error." +inputs = [ + { name = "value", unit = "ohm | F | H", range = [1.0e-15, 1.0e15] }, + { name = "series", unit = "enum", values = ["E6", "E12", "E24", "E48", "E96", "E192"], default = "E24" }, +] +outputs = ["nearest", "below", "above", "error %"] +formula = """ +Base values: v_i = round(10^(i/N)) to 2 significant digits for N <= 24, 3 for N >= 48, i = 0..N-1. +E24 overrides (IEC 60063 keeps the historic values): 2.6->2.7 2.9->3.0 3.2->3.3 3.5->3.6 3.8->3.9 4.2->4.3 4.6->4.7 8.3->8.2. +E6 and E12 are every 4th and every 2nd E24 value. E192 override: index 185 is 9.20 (formula gives 9.19). +Nearest: minimise |ln(candidate / value)| over the decade's values plus 10 x the first of the next decade. +""" +source = "Wikipedia, 'E series of preferred numbers' (IEC 60063 lists, formula, the eight E24 exceptions and the E192 9.20 exception; checked 2026-10-28)." +validity = "Any unit; the series is dimensionless." +accuracy = "exact against IEC 60063" +[[calculator.vector]] +inputs = { value = 4500, series = "E24" } +expect = { nearest = 4700 } +tolerance = 1e-9 +crosscheck = "4.3 is 4.5 % low, 4.7 is 4.4 % high; log distance picks 4.7" +[[calculator.vector]] +inputs = { value = 4500, series = "E96" } +expect = { nearest = 4530 } +tolerance = 1e-9 +crosscheck = "E96 has 4.42 and 4.53" +[[calculator.vector]] +inputs = { value = 123, series = "E12" } +expect = { nearest = 120 } +tolerance = 1e-9 +crosscheck = "E12 neighbours 120 and 150" +[[calculator.vector]] +inputs = { value = 123, series = "E96" } +expect = { nearest = 124 } +tolerance = 1e-9 +crosscheck = "E96 has 1.21 and 1.24" +[[calculator.vector]] +inputs = { value = 0.47, series = "E6" } +expect = { nearest = 0.47 } +tolerance = 1e-9 +crosscheck = "exact member" +[[calculator.vector]] +inputs = { value = 9.9, series = "E24" } +expect = { nearest = 10 } +tolerance = 1e-9 +crosscheck = "decade wrap: 9.1 vs 10" + +[[calculator]] +id = "unit_converter" +name = "Unit converter" +group = "utilities" +summary = "mil, mm, inch, micron and copper weight in oz/ft2." +inputs = [ + { name = "value", unit = "", range = [-1.0e9, 1.0e9] }, + { name = "from", unit = "enum", values = ["mm", "mil", "inch", "um", "oz"] }, + { name = "to", unit = "enum", values = ["mm", "mil", "inch", "um", "oz"] }, +] +outputs = ["value"] +formula = "1 inch = 25.4 mm exactly; 1 mil = 0.0254 mm; 1 oz/ft2 copper = 34.79 um (fabs round to 35 um; 0.5 oz = 17.4 um, 2 oz = 69.6 um). oz converts only to and from length units as a thickness." +source = "Inch definition: NIST SP 811. Copper weight: 1 oz over 1 ft2 of copper (density 8.96 g/cm3) is 34.79 um; stated in IPC-4562 and every fab capability page (sources/standards/jlcpcb-pcb-capabilities.txt, eurocircuits-copper-layers.txt)." +validity = "Exact conversions." +accuracy = "exact" +[[calculator.vector]] +inputs = { value = 10, from = "mil", to = "mm" } +expect = { value = 0.254 } +tolerance = 1e-12 +crosscheck = "definition" +[[calculator.vector]] +inputs = { value = 1, from = "mm", to = "mil" } +expect = { value = 39.3701 } +tolerance = 1e-5 +crosscheck = "1/0.0254" +[[calculator.vector]] +inputs = { value = 2, from = "oz", to = "um" } +expect = { value = 69.58 } +tolerance = 1e-9 +crosscheck = "2 * 34.79" +[[calculator.vector]] +inputs = { value = 35, from = "um", to = "oz" } +expect = { value = 1.00604 } +tolerance = 1e-5 +crosscheck = "35 / 34.79" + +[[calculator]] +id = "thermal_via_count" +name = "Thermal via count" +group = "utilities" +summary = "How many plated vias under a hot pad reach a target thermal resistance to the plane on the other side." +inputs = [ + { name = "drill", unit = "mm", range = [0.1, 1.0] }, + { name = "plating", unit = "um", range = [10.0, 50.0], default = 25 }, + { name = "length", unit = "mm", range = [0.1, 5.0], default = 1.6 }, + { name = "target_rth", unit = "K/W", range = [0.1, 100.0] }, + { name = "filled", unit = "bool", default = false, description = "solder or copper filled barrel: counts the full drill area" }, +] +outputs = ["rth_one_via K/W", "count", "array_hint (square side)"] +formula = """ +A = pi/4 ((drill + 2 plating)^2 - drill^2) (filled: pi/4 (drill + 2 plating)^2) +Rth_via = length / (K_CU A); count = ceil(Rth_via / target_rth); array_hint = ceil(sqrt(count)). +""" +source = "Series thermal resistance of a cylinder, k_copper = 385 W/(m K) (CRC Handbook). Context: TI SLVA959 motor driver layout and SLYT614 buck layout notes on thermal vias (sources/netrules/ti-slva959-*.txt, ti-slyt614-*.txt)." +validity = "Conduction through the barrel only; ignores the FR-4 in parallel (negligible), the spreading resistance in the pad and the plane, and solder wicking. Real packages see 2 to 3 times the ideal count's benefit tail off after about 9 to 16 vias." +accuracy = "order of magnitude" +[[calculator.vector]] +inputs = { drill = 0.3, plating = 25, length = 1.6, target_rth = 5 } +expect = { rth_one_via = 162.812, count = 33 } +tolerance = 1e-4 +crosscheck = "1.6e-3 / (385 * 2.5525e-8) = 162.8 K/W" +[[calculator.vector]] +inputs = { drill = 0.3, plating = 25, length = 1.6, target_rth = 2 } +expect = { rth_one_via = 162.812, count = 82 } +tolerance = 1e-4 +crosscheck = "ceil(162.8/2)" +[[calculator.vector]] +inputs = { drill = 0.2, plating = 20, length = 1.0, target_rth = 10 } +expect = { rth_one_via = 187.904, count = 19 } +tolerance = 1e-4 +crosscheck = "A = 0.013823 mm2" diff --git a/crates/calc/src/basic.rs b/crates/calc/src/basic.rs new file mode 100644 index 000000000..bff064eb3 --- /dev/null +++ b/crates/calc/src/basic.rs @@ -0,0 +1,527 @@ +//! Basic circuit calculators: ohms_law, series_parallel, voltage_divider, +//! led_resistor, rc_rl_time_constant, lc_resonance, reactance, decibel. +//! +//! Formulas, ranges and vectors come from `crates/calc/data/calculators.toml` +//! (ee-thesaurus research). Everything here is ideal-element arithmetic at +//! DC or RMS; validity text in the metadata says where that stops holding. + +use crate::{Error, finite, num, opt_num}; + +/// Input for [`ohms_law`]: exactly two of the three must be present. +#[derive(Debug, Clone, Copy, Default)] +pub struct OhmsLaw { + /// Voltage in volts, 0 to 1e6. + pub voltage: Option, + /// Current in amperes, 0 to 1e6. + pub current: Option, + /// Resistance in ohms, 1e-9 to 1e12. + pub resistance: Option, +} + +/// Solved quantities from [`ohms_law`]. +#[derive(Debug, Clone, Copy)] +pub struct OhmsLawOut { + /// Voltage in volts. + pub voltage: f64, + /// Current in amperes. + pub current: f64, + /// Resistance in ohms. + pub resistance: f64, + /// Power in watts. + pub power: f64, +} + +/// Ohm's law and Joule heating from any two of voltage, current, resistance. +/// +/// # Rules +/// - Exactly two inputs must be present; the third and the power follow. +/// - A zero denominator (0 V with 0 A, or 0 V with 0 ohm style pairs) +/// comes back as `Error::Invalid`, never as an infinite value. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::opt_num`, `crate::finite`. +/// # Do not +/// - Use for reactive loads; reach for `reactance` instead. +pub fn ohms_law(a: OhmsLaw) -> Result { + let v = opt_num("voltage", a.voltage, 0.0, 1.0e6)?; + let i = opt_num("current", a.current, 0.0, 1.0e6)?; + let r = opt_num("resistance", a.resistance, 1.0e-9, 1.0e12)?; + let given = v.is_some() as u8 + i.is_some() as u8 + r.is_some() as u8; + if given != 2 { + return Err(Error::Invalid( + "give exactly two of voltage, current and resistance".to_string(), + )); + } + let (v, i, r) = match (v, i, r) { + (Some(v), None, Some(r)) => (v, finite("current", v / r)?, r), + (None, Some(i), Some(r)) => (finite("voltage", i * r)?, i, r), + (Some(v), Some(i), None) => (v, i, finite("resistance", v / i)?), + _ => return Err(Error::Invalid("internal pairing".to_string())), + }; + Ok(OhmsLawOut { + voltage: v, + current: i, + resistance: r, + power: v * i, + }) +} + +/// Which kind of lumped element `series_parallel` combines. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ComponentKind { + /// Resistor, ohms. + Resistor, + /// Capacitor, farads. + Capacitor, + /// Inductor, henries. + Inductor, +} + +/// Input for [`series_parallel`]. +#[derive(Debug, Clone)] +pub struct SeriesParallel { + /// Element kind; capacitors combine in the reverse direction. + pub kind: ComponentKind, + /// Two to 16 values in the kind's unit, each 1e-15 to 1e12. + pub values: Vec, +} + +/// Series and parallel combination from [`series_parallel`]. +#[derive(Debug, Clone, Copy)] +pub struct SeriesParallelOut { + /// Combined value in series. + pub series: f64, + /// Combined value in parallel. + pub parallel: f64, +} + +/// Combine 2 to 16 ideal resistors, capacitors or inductors. +/// +/// # Rules +/// - R and L: series is the sum, parallel is the reciprocal sum. +/// C is the reverse. Values must be inside 1e-15 to 1e12. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::Error`. +/// # Do not +/// - Pass fewer than two or more than 16 values; the call is refused. +pub fn series_parallel(a: SeriesParallel) -> Result { + if a.values.len() < 2 || a.values.len() > 16 { + return Err(Error::Invalid(format!( + "values must hold 2 to 16 entries, got {}", + a.values.len() + ))); + } + let mut vals = Vec::with_capacity(a.values.len()); + for v in &a.values { + vals.push(num("values", *v, 1.0e-15, 1.0e12)?); + } + let sum: f64 = vals.iter().sum(); + let recip: f64 = vals.iter().map(|v| 1.0 / v).sum(); + let inv = finite("parallel", 1.0 / recip)?; + let (series, parallel) = match a.kind { + ComponentKind::Resistor | ComponentKind::Inductor => (sum, inv), + ComponentKind::Capacitor => (inv, sum), + }; + Ok(SeriesParallelOut { series, parallel }) +} + +/// Input for [`voltage_divider`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct VoltageDivider { + /// Input voltage in volts, 0 to 1e5. + pub vin: f64, + /// Top resistor in ohms, 1e-3 to 1e12. + pub r1: f64, + /// Bottom resistor in ohms, 1e-3 to 1e12. + pub r2: f64, + /// Optional load resistor across the output, 1e-3 to 1e12. + pub load: Option, +} + +/// Solved quantities from [`voltage_divider`]. +#[derive(Debug, Clone, Copy)] +pub struct VoltageDividerOut { + /// Output voltage in volts. + pub vout: f64, + /// Current through r1 in amperes. + pub current: f64, + /// r2 in parallel with the load, ohms. + pub r2_effective: f64, + /// Power in r1, watts. + pub power_r1: f64, + /// Power in the effective bottom resistor, watts. + pub power_r2: f64, +} + +/// Two-resistor divider with Thevenin loading from an optional load. +/// +/// # Rules +/// - With a load, r2 is replaced by r2 || load before dividing. +/// - Power in r2 is computed with the effective bottom resistance. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::opt_num`, `crate::finite`. +/// # Do not +/// - Model a non-resistive load; the model is a resistor to ground. +pub fn voltage_divider(a: VoltageDivider) -> Result { + let vin = num("vin", a.vin, 0.0, 1.0e5)?; + let r1 = num("r1", a.r1, 1.0e-3, 1.0e12)?; + let r2 = num("r2", a.r2, 1.0e-3, 1.0e12)?; + let load = opt_num("load", a.load, 1.0e-3, 1.0e12)?; + let r2e = match load { + Some(rl) => finite("r2_effective", 1.0 / (1.0 / r2 + 1.0 / rl))?, + None => r2, + }; + let i = finite("current", vin / (r1 + r2e))?; + Ok(VoltageDividerOut { + vout: i * r2e, + current: i, + r2_effective: r2e, + power_r1: i * i * r1, + power_r2: i * i * r2e, + }) +} + +/// E-series used by [`led_resistor`] for its nearest standard value. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ESeries { + /// 6 values per decade. + E6, + /// 12 values per decade. + E12, + /// 24 values per decade. + #[default] + E24, + /// 96 values per decade. + E96, +} + +impl ESeries { + /// Values per decade for this series. + pub fn count(self) -> usize { + match self { + ESeries::E6 => 6, + ESeries::E12 => 12, + ESeries::E24 => 24, + ESeries::E96 => 96, + } + } +} + +/// Input for [`led_resistor`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct LedResistor { + /// Supply voltage in volts, 0.1 to 1000. + pub supply: f64, + /// Total LED forward voltage in volts, 0.1 to 50. + pub forward_voltage: f64, + /// Wanted current in amperes, 1e-6 to 10. + pub current: f64, + /// Series for the nearest standard value; defaults to E24. + pub series: ESeries, +} + +/// Resistor, power and nearest standard value from [`led_resistor`]. +#[derive(Debug, Clone, Copy)] +pub struct LedResistorOut { + /// Exact resistor value in ohms. + pub resistance: f64, + /// Resistor power in watts. + pub power: f64, + /// Nearest value in the chosen E-series, ohms. + pub nearest_standard: f64, + /// Current actually flowing with the standard value, amperes. + pub current_with_standard: f64, +} + +/// Series resistor for an LED from supply, forward drop and current. +/// +/// # Rules +/// - Refuses when forward_voltage is at or above supply (no headroom). +/// - The nearest standard value uses log distance in `e_series`. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::finite`, `crate::components::nearest_e_series`. +/// # Do not +/// - Treat the result as final; forward voltage moves with current. +pub fn led_resistor(a: LedResistor) -> Result { + let vs = num("supply", a.supply, 0.1, 1000.0)?; + let vf = num("forward_voltage", a.forward_voltage, 0.1, 50.0)?; + let i = num("current", a.current, 1.0e-6, 10.0)?; + if vf >= vs { + return Err(Error::Invalid(format!( + "forward_voltage {vf} must be below supply {vs} or no resistor value works" + ))); + } + let drop = vs - vf; + let r = finite("resistance", drop / i)?; + let std = crate::components::nearest_e_series(r, a.series.count()); + Ok(LedResistorOut { + resistance: r, + power: drop * i, + nearest_standard: std, + current_with_standard: drop / std, + }) +} + +/// Which first-order network `rc_rl_time_constant` solves. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum RcRlKind { + /// Resistor and capacitor. + #[default] + Rc, + /// Resistor and inductor. + Rl, +} + +/// Input for [`rc_rl_time_constant`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct RcRl { + /// Network kind. + pub kind: RcRlKind, + /// Resistance in ohms, 1e-3 to 1e12. + pub resistance: f64, + /// Capacitance in farads, 1e-15 to 1; required for rc. + pub capacitance: Option, + /// Inductance in henries, 1e-12 to 1e3; required for rl. + pub inductance: Option, +} + +/// Time constant and corner frequency from [`rc_rl_time_constant`]. +#[derive(Debug, Clone, Copy)] +pub struct RcRlOut { + /// Time constant in seconds. + pub tau: f64, + /// Minus 3 dB corner frequency in hertz. + pub cutoff: f64, + /// Time to 63 percent, one tau, seconds. + pub t_63: f64, + /// Time to 95 percent, three tau, seconds. + pub t_95: f64, + /// Time to 99 percent, five tau, seconds. + pub t_99: f64, +} + +/// Single-pole time constant and cutoff for an rc or rl network. +/// +/// # Rules +/// - rc needs capacitance, rl needs inductance; the other is ignored. +/// - tau = R C or L / R; cutoff = 1 / (2 pi tau). +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::opt_num`, `crate::finite`. +/// # Do not +/// - Apply to multi-pole networks; only the single-pole corner is modelled. +pub fn rc_rl_time_constant(a: RcRl) -> Result { + let r = num("resistance", a.resistance, 1.0e-3, 1.0e12)?; + let tau = match a.kind { + RcRlKind::Rc => { + let c = opt_num("capacitance", a.capacitance, 1.0e-15, 1.0)? + .ok_or_else(|| Error::Invalid("rc needs a capacitance".to_string()))?; + r * c + } + RcRlKind::Rl => { + let l = opt_num("inductance", a.inductance, 1.0e-12, 1.0e3)? + .ok_or_else(|| Error::Invalid("rl needs an inductance".to_string()))?; + l / r + } + }; + let tau = finite("tau", tau)?; + let cutoff = finite("cutoff", 1.0 / (2.0 * std::f64::consts::PI * tau))?; + Ok(RcRlOut { + tau, + cutoff, + t_63: tau, + t_95: 3.0 * tau, + t_99: 5.0 * tau, + }) +} + +/// Input for [`lc_resonance`]: exactly two of the three. +#[derive(Debug, Clone, Copy, Default)] +pub struct LcResonance { + /// Inductance in henries, 1e-12 to 1e3. + pub inductance: Option, + /// Capacitance in farads, 1e-15 to 1. + pub capacitance: Option, + /// Resonant frequency in hertz, 1e-3 to 1e12. + pub frequency: Option, +} + +/// Solved quantities from [`lc_resonance`]. +#[derive(Debug, Clone, Copy)] +pub struct LcResonanceOut { + /// Resonant frequency in hertz. + pub frequency: f64, + /// Inductance in henries. + pub inductance: f64, + /// Capacitance in farads. + pub capacitance: f64, + /// sqrt(L / C) in ohms, present only when both L and C are known. + pub characteristic_impedance: Option, +} + +/// Lossless LC resonance; solves whichever of L, C, f is missing. +/// +/// # Rules +/// - Exactly two inputs must be present. +/// - characteristic_impedance is Some only when both L and C are known. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::opt_num`, `crate::finite`. +/// # Do not +/// - Expect the real part's self-resonance or parasitics here. +pub fn lc_resonance(a: LcResonance) -> Result { + let l = opt_num("inductance", a.inductance, 1.0e-12, 1.0e3)?; + let c = opt_num("capacitance", a.capacitance, 1.0e-15, 1.0)?; + let f = opt_num("frequency", a.frequency, 1.0e-3, 1.0e12)?; + let given = l.is_some() as u8 + c.is_some() as u8 + f.is_some() as u8; + if given != 2 { + return Err(Error::Invalid( + "give exactly two of inductance, capacitance and frequency".to_string(), + )); + } + let pi2 = 2.0 * std::f64::consts::PI; + let (l, c, f, z0) = match (l, c, f) { + (Some(l), Some(c), None) => { + let f = finite("frequency", 1.0 / (pi2 * (l * c).sqrt()))?; + ( + l, + c, + f, + Some(finite("characteristic_impedance", (l / c).sqrt())?), + ) + } + (Some(l), None, Some(f)) => { + let c = finite("capacitance", 1.0 / (pi2 * f * (pi2 * f) * l))?; + (l, c, f, None) + } + (None, Some(c), Some(f)) => { + let l = finite("inductance", 1.0 / (pi2 * f * (pi2 * f) * c))?; + (l, c, f, None) + } + _ => return Err(Error::Invalid("internal pairing".to_string())), + }; + Ok(LcResonanceOut { + frequency: f, + inductance: l, + capacitance: c, + characteristic_impedance: z0, + }) +} + +/// Input for [`reactance`]: frequency plus at least one of C and L. +#[derive(Debug, Clone, Copy, Default)] +pub struct Reactance { + /// Frequency in hertz, 1e-3 to 1e12. + pub frequency: f64, + /// Capacitance in farads, 1e-15 to 1. + pub capacitance: Option, + /// Inductance in henries, 1e-12 to 1e3. + pub inductance: Option, +} + +/// Reactances from [`reactance`]; absent parts come back as None. +#[derive(Debug, Clone, Copy)] +pub struct ReactanceOut { + /// Capacitive reactance in ohms, negative in the phasor convention. + pub xc: Option, + /// Inductive reactance in ohms. + pub xl: Option, +} + +/// Ideal reactance of a capacitor or inductor at one frequency. +/// +/// # Rules +/// - Xc = 1 / (2 pi f C); Xl = 2 pi f L. Magnitudes are reported. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::opt_num`, `crate::finite`. +/// # Do not +/// - Use near a part's self-resonance; ESR and SRF are not modelled. +pub fn reactance(a: Reactance) -> Result { + let f = num("frequency", a.frequency, 1.0e-3, 1.0e12)?; + let c = opt_num("capacitance", a.capacitance, 1.0e-15, 1.0)?; + let l = opt_num("inductance", a.inductance, 1.0e-12, 1.0e3)?; + if c.is_none() && l.is_none() { + return Err(Error::Invalid( + "give a capacitance or an inductance".to_string(), + )); + } + let pi2 = 2.0 * std::f64::consts::PI; + Ok(ReactanceOut { + xc: c.map(|c| finite("xc", 1.0 / (pi2 * f * c))).transpose()?, + xl: l.map(|l| finite("xl", pi2 * f * l)).transpose()?, + }) +} + +/// Which conversion `decibel` performs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DecibelMode { + /// Power ratio to dB. + PowerRatio, + /// Voltage ratio to dB (equal impedances). + VoltageRatio, + /// Watts to dBm. + WToDbm, + /// dBm to watts. + DbmToW, +} + +/// Input for [`decibel`]. +#[derive(Debug, Clone, Copy)] +pub struct Decibel { + /// Conversion to run. + pub mode: DecibelMode, + /// Input: a ratio, watts or dBm depending on the mode. + pub value: f64, +} + +/// Converted quantities from [`decibel`]; irrelevant fields are None. +#[derive(Debug, Clone, Copy, Default)] +pub struct DecibelOut { + /// Decibels, for the ratio modes. + pub db: Option, + /// Linear ratio, for the ratio modes. + pub ratio: Option, + /// dBm, for the dBm modes. + pub dbm: Option, + /// Watts, for the dBm modes. + pub watts: Option, +} + +/// Convert between ratios, dB, dBm and watts. +/// +/// # Rules +/// - Ratio modes need a positive value; dBm modes accept down to -300. +/// - dBm = 10 log10(P / 1 mW); P = 1 mW times 10^(dBm / 10). +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::finite`, `crate::Error`. +/// # Do not +/// - Mix the voltage form with unequal source and load impedances. +pub fn decibel(a: Decibel) -> Result { + let v = num("value", a.value, -300.0, 1.0e12)?; + match a.mode { + DecibelMode::PowerRatio | DecibelMode::VoltageRatio => { + if v <= 0.0 { + return Err(Error::Invalid(format!( + "value must be above 0 for a ratio, got {v}" + ))); + } + let factor = if a.mode == DecibelMode::PowerRatio { + 10.0 + } else { + 20.0 + }; + Ok(DecibelOut { + db: Some(finite("db", factor * v.log10())?), + ratio: Some(v), + ..DecibelOut::default() + }) + } + DecibelMode::WToDbm => Ok(DecibelOut { + dbm: Some(finite("dbm", 10.0 * (v * 1.0e3).log10())?), + watts: Some(v), + ..DecibelOut::default() + }), + DecibelMode::DbmToW => Ok(DecibelOut { + watts: Some(finite("watts", 1.0e-3 * 10.0f64.powf(v / 10.0))?), + dbm: Some(v), + ..DecibelOut::default() + }), + } +} diff --git a/crates/calc/src/components.rs b/crates/calc/src/components.rs new file mode 100644 index 000000000..5b0ad37e8 --- /dev/null +++ b/crates/calc/src/components.rs @@ -0,0 +1,1223 @@ +//! Component calculators: decoupling, I2C pull-ups, crystal load caps, +//! the 555 timer, op-amp gain, LDO thermal, battery life, wire gauge, +//! resistor colour and SMD codes, and the E-series lookup everything +//! else leans on for "nearest standard value". +//! +//! `nearest_e_series` replicates the reference tables exactly (the +//! eight historic E24 overrides and the E192 9.20 exception included), +//! because the golden vectors were generated from those tables. + +use crate::{Error, finite, int_num, num, opt_num}; + +/// E-series selector for [`e_series`] and [`nearest_e_series`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Series { + /// 6 values per decade. + E6, + /// 12 values per decade. + E12, + /// 24 values per decade. + #[default] + E24, + /// 48 values per decade. + E48, + /// 96 values per decade. + E96, + /// 192 values per decade. + E192, +} + +impl Series { + /// Values per decade for this series. + pub fn count(self) -> usize { + match self { + Series::E6 => 6, + Series::E12 => 12, + Series::E24 => 24, + Series::E48 => 48, + Series::E96 => 96, + Series::E192 => 192, + } + } + + /// Parse a name like "E96"; None for anything else. + pub fn parse(name: &str) -> Option { + match name { + "E6" => Some(Series::E6), + "E12" => Some(Series::E12), + "E24" => Some(Series::E24), + "E48" => Some(Series::E48), + "E96" => Some(Series::E96), + "E192" => Some(Series::E192), + _ => None, + } + } + + /// Canonical name. + pub fn name(self) -> &'static str { + match self { + Series::E6 => "E6", + Series::E12 => "E12", + Series::E24 => "E24", + Series::E48 => "E48", + Series::E96 => "E96", + Series::E192 => "E192", + } + } +} + +/// Round `v` to `digits` decimals with round-half-to-even, matching +/// Python's built-in `round` used by the reference tables. +fn round_to(v: f64, digits: usize) -> f64 { + let scale = 10f64.powi(digits as i32); + let scaled = v * scale; + let floor = scaled.floor(); + let diff = scaled - floor; + let picked = if diff > 0.5 { + floor + 1.0 + } else if diff < 0.5 { + floor + } else if floor % 2.0 != 0.0 { + floor + 1.0 + } else { + floor + }; + picked / scale +} + +/// Generate one decade of an E-series, matching IEC 60063 and the +/// reference tables: banker's rounding to 2 significant digits for +/// N <= 24 and 3 for N >= 48, the eight E24 overrides, E6 / E12 as +/// every 4th / 2nd E24 value, and the E192 index 185 exception. +pub fn e_series_values(count: usize) -> Vec { + let digits = if count <= 24 { 1 } else { 2 }; + let mut vals: Vec = (0..count) + .map(|i| round_to(10.0f64.powf(i as f64 / count as f64), digits)) + .collect(); + if count == 24 { + let fixes: [(f64, f64); 8] = [ + (2.6, 2.7), + (2.9, 3.0), + (3.2, 3.3), + (3.5, 3.6), + (3.8, 3.9), + (4.2, 4.3), + (4.6, 4.7), + (8.3, 8.2), + ]; + for v in vals.iter_mut() { + for (from, to) in fixes { + if (*v - from).abs() < 1e-9 { + *v = to; + } + } + } + } + if count == 6 || count == 12 { + let e24 = e_series_values(24); + let step = 24 / count; + vals = (0..count).map(|i| e24[i * step]).collect(); + } + if count == 192 { + for v in vals.iter_mut() { + if (*v - 9.19).abs() < 1e-9 { + *v = 9.20; + } + } + } + vals +} + +/// Nearest standard value in the series with `count` values per decade. +/// +/// # Rules +/// - Work on the mantissa inside the value's decade and minimise the +/// absolute log distance; also offer 10 x the first value, so +/// 9.9 -> 10 in E24 (decade wrap). +/// - Deterministic: ties keep the earlier candidate (`min` on the +/// first strictly smaller distance). +/// # Dependencies +/// - `crates/calc/src/lib.rs` for [`e_series_values`]. +/// # Do not +/// - Feed non-positive values; the logarithm needs value > 0. +pub fn nearest_e_series(value: f64, count: usize) -> f64 { + let series = e_series_values(count); + nearest_from(&series, value) +} + +/// Nearest of an explicit series list (shared by the calculators). +fn nearest_from(series: &[f64], value: f64) -> f64 { + let dec = 10f64.powf(value.log10().floor()); + let m = value / dec; + let mut best = (f64::MAX, 10.0 * dec); + for v in series { + let d = (v / m).ln().abs(); + if d < best.0 { + best = (d, v * dec); + } + } + let d = (10.0 / m).ln().abs(); + if d < best.0 { + best.1 = 10.0 * dec; + } + best.1 +} + +/// Input for [`e_series`]. +#[derive(Debug, Clone, Copy)] +pub struct ESeriesInput { + /// Target value, 1e-15 to 1e15, any unit. + pub value: f64, + /// Series to search; default E24. + pub series: Series, +} + +impl Default for ESeriesInput { + fn default() -> Self { + ESeriesInput { + value: 4500.0, + series: Series::E24, + } + } +} + +/// Answer from [`e_series`]. +#[derive(Debug, Clone, Copy)] +pub struct ESeriesOut { + /// Closest standard value to the target. + pub nearest: f64, + /// Largest standard value not above the target. + pub below: f64, + /// Smallest standard value not below the target. + pub above: f64, + /// (nearest - value) / value, as a fraction. + pub error: f64, +} + +/// Nearest standard E-series value plus its neighbours and error. +/// +/// # Rules +/// - `below` scans the decade down from the target's, `above` scans +/// up, both by log distance like [`nearest_e_series`]. +/// - An exact member returns itself for all three and error 0. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for [`e_series_values`], `nearest_from`, `crate::num`. +/// # Do not +/// - Mix series between the three outputs; one series per call. +pub fn e_series(a: ESeriesInput) -> Result { + let v = num("value", a.value, 1.0e-15, 1.0e15)?; + let series = e_series_values(a.series.count()); + let nearest = nearest_from(&series, v); + let dec = 10f64.powf(v.log10().floor()); + let below = if v >= series[0] * dec { + nearest_below(&series, v, dec) + } else { + nearest_below(&series, v, dec / 10.0) + }; + let above = nearest_above(&series, v, dec); + Ok(ESeriesOut { + nearest, + below, + above, + error: (nearest - v) / v, + }) +} + +/// Largest series value (in decade `dec` or the one below) <= v. +fn nearest_below(series: &[f64], v: f64, dec: f64) -> f64 { + let mut best = f64::MIN; + for scale in [dec, dec / 10.0] { + for s in series { + let c = s * scale; + if c <= v * (1.0 + 1e-12) && c > best { + best = c; + } + } + } + best +} + +/// Smallest series value (in decade `dec` or the one above) >= v. +fn nearest_above(series: &[f64], v: f64, dec: f64) -> f64 { + let mut best = f64::MAX; + for scale in [dec, dec * 10.0] { + for s in series { + let c = s * scale; + if c >= v * (1.0 - 1e-12) && c < best { + best = c; + } + } + } + best +} + +/// Input for [`decoupling_capacitor`]. +#[derive(Debug, Clone, Copy)] +pub struct Decoupling { + /// Current step the rail must source, amperes, 1e-6 to 1000. + pub current_step: f64, + /// Rise time of the step, seconds, 1e-12 to 1. + pub step_time: f64, + /// Allowed ripple, volts, 1e-4 to 10. + pub ripple: f64, + /// Capacitor plus mounting inductance, henries, 1e-12 to 1e-6. + pub esl: f64, + /// A chosen part, farads, 1e-12 to 1, for its self-resonance. + pub capacitance: Option, +} + +impl Default for Decoupling { + fn default() -> Self { + Decoupling { + current_step: 1.0, + step_time: 5.0e-9, + ripple: 0.05, + esl: 1.0e-9, + capacitance: None, + } + } +} + +/// Answer from [`decoupling_capacitor`]. +#[derive(Debug, Clone, Copy)] +pub struct DecouplingOut { + /// Charge-balance capacitance in farads. + pub capacitance_needed: f64, + /// Self-resonance of the chosen part, when one was given. + pub self_resonance: Option, + /// Ripple divided by current step, ohms. + pub impedance_target: f64, +} + +/// Bulk decoupling from a charge balance, plus a part's self-resonance. +/// +/// # Rules +/// - C = I dt / dV; f_srf = 1 / (2 pi sqrt(ESL C)); Ztarget = dV / I. +/// - First-order starting point; several values in parallel widen the +/// useful band. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::opt_num`, `crate::finite`. +/// # Do not +/// - Read the SRF as the place the capacitor stops working; the +/// mounting inductance takes over near it. +pub fn decoupling_capacitor(a: Decoupling) -> Result { + let i = num("current_step", a.current_step, 1.0e-6, 1000.0)?; + let dt = num("step_time", a.step_time, 1.0e-12, 1.0)?; + let dv = num("ripple", a.ripple, 1.0e-4, 10.0)?; + let esl = num("esl", a.esl, 1.0e-12, 1.0e-6)?; + let c = opt_num("capacitance", a.capacitance, 1.0e-12, 1.0)?; + let srf = c + .map(|c| { + finite( + "self_resonance", + 1.0 / (2.0 * std::f64::consts::PI * (esl * c).sqrt()), + ) + }) + .transpose()?; + Ok(DecouplingOut { + capacitance_needed: finite("capacitance_needed", i * dt / dv)?, + self_resonance: srf, + impedance_target: finite("impedance_target", dv / i)?, + }) +} + +/// Input for [`i2c_pullup`]. +#[derive(Debug, Clone, Copy)] +pub struct I2cPullup { + /// Supply voltage, 1 to 6 V. + pub vcc: f64, + /// Maximum low-level output voltage, 0 to 1 V; default 0.4. + pub vol_max: f64, + /// Sink current the low transistor must handle, amperes; default 3 mA. + pub iol: f64, + /// Rise-time budget 10 % to 90 %, seconds, 1e-9 to 1e-5. + pub rise_time: f64, + /// Total bus capacitance, farads, 1e-12 to 1e-9. + pub bus_capacitance: f64, +} + +impl Default for I2cPullup { + fn default() -> Self { + I2cPullup { + vcc: 3.3, + vol_max: 0.4, + iol: 3.0e-3, + rise_time: 300.0e-9, + bus_capacitance: 100.0e-12, + } + } +} + +/// Answer from [`i2c_pullup`]. +#[derive(Debug, Clone, Copy)] +pub struct I2cPullupOut { + /// Smallest usable pull-up in ohms (sink limit). + pub rp_min: f64, + /// Largest usable pull-up in ohms (rise-time limit). + pub rp_max: f64, + /// Nearest E24 value to the geometric mean of the limits. + pub suggested: f64, +} + +/// I2C pull-up bounds from sink current and rise time (TI SLVA689). +/// +/// # Rules +/// - Rp_min = (Vcc - VOL) / IOL; Rp_max = tr / (0.8473 Cb), the +/// 0.8473 being ln(0.7 / 0.3) for the 30 % to 70 % edge. +/// - `suggested` is the nearest E24 value to sqrt(Rp_min Rp_max). +/// # Dependencies +/// - `crates/calc/src/lib.rs` for [`nearest_e_series`], `crate::num`, `crate::finite`. +/// # Do not +/// - Exceed the bus-capacitance limits of the I2C specification; +/// Rp_max assumes the budget and capacitance you supplied are legal. +pub fn i2c_pullup(a: I2cPullup) -> Result { + let vcc = num("vcc", a.vcc, 1.0, 6.0)?; + let vol = num("vol_max", a.vol_max, 0.0, 1.0)?; + let iol = num("iol", a.iol, 1.0e-4, 0.03)?; + let tr = num("rise_time", a.rise_time, 1.0e-9, 1.0e-5)?; + let cb = num("bus_capacitance", a.bus_capacitance, 1.0e-12, 1.0e-9)?; + let rp_min = finite("rp_min", (vcc - vol) / iol)?; + let rp_max = finite("rp_max", tr / (0.8473 * cb))?; + if rp_min > rp_max { + return Err(Error::Invalid(format!( + "no usable pull-up: rp_min {rp_min:.1} ohm exceeds rp_max {rp_max:.1} ohm; \ + raise the rise time or lower the bus capacitance" + ))); + } + Ok(I2cPullupOut { + rp_min, + rp_max, + suggested: nearest_e_series((rp_min * rp_max).sqrt(), 24), + }) +} + +/// Input for [`crystal_load_capacitors`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct CrystalCaps { + /// Crystal load capacitance, 4 to 40 pF. + pub load_capacitance: f64, + /// Stray capacitance per side, 0 to 15 pF; default 3. + pub stray_capacitance: f64, + /// Check mode: capacitor you fitted, 1 to 100 pF. + pub c1: Option, + /// Check mode: second capacitor, 1 to 100 pF. + pub c2: Option, +} + +/// Answer from [`crystal_load_capacitors`]. +#[derive(Debug, Clone, Copy)] +pub struct CrystalCapsOut { + /// Equal pair value in pF, when not in check mode. + pub c1_c2: Option, + /// Effective load of the fitted pair in pF, check mode. + pub effective_load: Option, + /// Nearest E24 value to the pair, in pF. + pub nearest_e24: Option, +} + +/// Pierce-oscillator load capacitors for a specified crystal CL. +/// +/// # Rules +/// - CL = C1 C2 / (C1 + C2) + Cstray; the equal pair is +/// C1 = C2 = 2 (CL - Cstray). Give c1 and c2 together for check mode. +/// - Check mode returns the effective load of the fitted pair instead +/// of a pair suggestion. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for [`nearest_e_series`], `crate::num`, `crate::opt_num`. +/// # Do not +/// - Forget the stray estimate; 2 to 5 pF is typical and it shifts CL +/// one-for-one. +pub fn crystal_load_capacitors(a: CrystalCaps) -> Result { + let cl = num("load_capacitance", a.load_capacitance, 4.0, 40.0)?; + let cs = num("stray_capacitance", a.stray_capacitance, 0.0, 15.0)?; + let c1 = opt_num("c1", a.c1, 1.0, 100.0)?; + let c2 = opt_num("c2", a.c2, 1.0, 100.0)?; + match (c1, c2) { + (Some(c1), Some(c2)) => Ok(CrystalCapsOut { + c1_c2: None, + effective_load: Some(finite("effective_load", c1 * c2 / (c1 + c2) + cs)?), + nearest_e24: None, + }), + _ => { + let pair = 2.0 * (cl - cs); + if pair < 1.0 { + return Err(Error::Invalid(format!( + "stray capacitance {cs} pF leaves no room for the pair at CL {cl} pF" + ))); + } + Ok(CrystalCapsOut { + c1_c2: Some(pair), + effective_load: None, + nearest_e24: Some(nearest_e_series(pair, 24)), + }) + } + } +} + +/// Astable or monostable operation of the 555 timer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Timer555Mode { + /// Free-running square-wave oscillator. + #[default] + Astable, + /// One-shot triggered pulse. + Monostable, +} + +/// Input for [`timer_555`]. +#[derive(Debug, Clone, Copy)] +pub struct Timer555 { + /// Which circuit to solve; astable unless set otherwise. + pub mode: Timer555Mode, + /// R1 in ohms, 1e3 to 1e7 (R for the monostable). + pub r1: f64, + /// R2 in ohms, 1e3 to 1e7; required for astable. + pub r2: Option, + /// Timing capacitor in farads, 1e-12 to 1e-2. + pub c: f64, +} + +impl Default for Timer555 { + fn default() -> Self { + Timer555 { + mode: Timer555Mode::Astable, + r1: 8200.0, + r2: Some(68000.0), + c: 10.0e-9, + } + } +} + +/// Answer from [`timer_555`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct Timer555Out { + /// Oscillation frequency in hertz, astable. + pub frequency: Option, + /// Duty cycle in percent, astable. + pub duty_cycle: Option, + /// High time in seconds, astable. + pub t_high: Option, + /// Low time in seconds, astable. + pub t_low: Option, + /// Output pulse width in seconds, monostable. + pub pulse_width: Option, +} + +/// 555 timer astable frequency and duty, or monostable pulse width. +/// +/// # Rules +/// - Astable: t_high = ln2 (R1 + R2) C, t_low = ln2 R2 C, +/// f = 1 / (t_high + t_low), duty = (R1 + R2) / (R1 + 2 R2). +/// - Monostable: t = ln3 R C (the usual 1.1 R C rounded). +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::opt_num`, `crate::finite`. +/// # Do not +/// - Expect duty below 50 % from the basic astable; the discharge +/// diode mod is a different circuit. +pub fn timer_555(a: Timer555) -> Result { + let r1 = num("r1", a.r1, 1000.0, 1.0e7)?; + let c = num("c", a.c, 1.0e-12, 1.0e-2)?; + if a.mode == Timer555Mode::Monostable { + return Ok(Timer555Out { + pulse_width: Some(finite("pulse_width", 3.0f64.ln() * r1 * c)?), + ..Timer555Out::default() + }); + } + let r2 = num( + "r2", + a.r2.ok_or_else(|| Error::Invalid("astable needs r2".to_string()))?, + 1000.0, + 1.0e7, + )?; + let th = std::f64::consts::LN_2 * (r1 + r2) * c; + let tl = std::f64::consts::LN_2 * r2 * c; + Ok(Timer555Out { + frequency: Some(finite("frequency", 1.0 / (th + tl))?), + duty_cycle: Some(finite("duty_cycle", (r1 + r2) / (r1 + 2.0 * r2) * 100.0)?), + t_high: Some(th), + t_low: Some(tl), + pulse_width: None, + }) +} + +/// Feedback topology for [`opamp_gain`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OpampTopology { + /// Inverting amplifier, gain -Rf / Rin. + #[default] + Inverting, + /// Non-inverting amplifier, gain 1 + Rf / Rg. + NonInverting, +} + +/// Input for [`opamp_gain`]. +#[derive(Debug, Clone, Copy)] +pub struct OpampGain { + /// Which amplifier to solve; inverting unless set otherwise. + pub topology: OpampTopology, + /// Feedback resistor Rf, 1 ohm to 1e9. + pub rf: f64, + /// Input resistor (inverting) or ground resistor, 1 ohm to 1e9. + pub rin: f64, +} + +impl Default for OpampGain { + fn default() -> Self { + OpampGain { + topology: OpampTopology::Inverting, + rf: 100000.0, + rin: 10000.0, + } + } +} + +/// Answer from [`opamp_gain`]. +#[derive(Debug, Clone, Copy)] +pub struct OpampGainOut { + /// Closed-loop gain, signed for the inverting case. + pub gain: f64, + /// Gain magnitude in decibels. + pub gain_db: f64, + /// Input impedance in ohms, inverting topology only. + pub input_impedance: Option, +} + +/// Resistor-feedback op-amp gain in ratio and dB. +/// +/// # Rules +/// - Inverting G = -Rf / Rin with input impedance Rin; +/// non-inverting G = 1 + Rf / Rg. +/// - dB always uses |G|. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::finite`. +/// # Do not +/// - Push the closed-loop gain near the open-loop gain at the frequency +/// of interest; the ideal model stops holding there. +pub fn opamp_gain(a: OpampGain) -> Result { + let rf = num("rf", a.rf, 1.0, 1.0e9)?; + let rin = num("rin", a.rin, 1.0, 1.0e9)?; + let (gain, zin) = match a.topology { + OpampTopology::Inverting => (-rf / rin, Some(rin)), + OpampTopology::NonInverting => (1.0 + rf / rin, None), + }; + let gain = finite("gain", gain)?; + Ok(OpampGainOut { + gain, + gain_db: finite("gain_db", 20.0 * gain.abs().log10())?, + input_impedance: zin, + }) +} + +/// Input for [`ldo_thermal`]. +#[derive(Debug, Clone, Copy)] +pub struct LdoThermal { + /// Input voltage, 0.5 to 100 V. + pub vin: f64, + /// Output voltage, 0.1 to 100 V. + pub vout: f64, + /// Load current, 0 to 20 A. + pub iout: f64, + /// Quiescent current, 0 to 0.1 A; default 0. + pub iq: f64, + /// Junction-to-ambient thermal resistance, 1 to 500 K/W. + pub theta_ja: f64, + /// Ambient temperature, -55 to 125 C; default 25. + pub ambient: f64, + /// Maximum rated junction temperature, 85 to 175 C; default 125. + pub tj_max: f64, +} + +impl Default for LdoThermal { + fn default() -> Self { + LdoThermal { + vin: 5.0, + vout: 3.3, + iout: 0.5, + iq: 0.0, + theta_ja: 65.0, + ambient: 25.0, + tj_max: 125.0, + } + } +} + +/// Answer from [`ldo_thermal`]. +#[derive(Debug, Clone, Copy)] +pub struct LdoThermalOut { + /// Total dissipation in watts. + pub power: f64, + /// Temperature rise over ambient in kelvin. + pub rise: f64, + /// Junction temperature in degrees Celsius. + pub tj: f64, + /// Margin to tj_max in kelvin. + pub headroom: f64, + /// Load current that reaches tj_max, None if already over. + pub max_iout_at_tj_max: Option, +} + +/// Linear-regulator dissipation and junction temperature. +/// +/// # Rules +/// - P = (Vin - Vout) Iout + Vin Iq; Tj = Ta + P theta_JA; +/// Imax = (((Tjmax - Ta) / theta_JA) - Vin Iq) / (Vin - Vout). +/// - Vin must exceed Vout; equal voltages give no dissipation model. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::finite`. +/// # Do not +/// - Trust theta_JA across copper areas; take the datasheet value for +/// the package and copper closest to the real board. +pub fn ldo_thermal(a: LdoThermal) -> Result { + let vin = num("vin", a.vin, 0.5, 100.0)?; + let vout = num("vout", a.vout, 0.1, 100.0)?; + let iout = num("iout", a.iout, 0.0, 20.0)?; + let iq = num("iq", a.iq, 0.0, 0.1)?; + let theta = num("theta_ja", a.theta_ja, 1.0, 500.0)?; + let ta = num("ambient", a.ambient, -55.0, 125.0)?; + let tj_max = num("tj_max", a.tj_max, 85.0, 175.0)?; + if vin <= vout { + return Err(Error::Invalid(format!( + "vin {vin} V must exceed vout {vout} V for an LDO" + ))); + } + let p = (vin - vout) * iout + vin * iq; + let rise = p * theta; + let tj = ta + rise; + let imax = ((tj_max - ta) / theta - vin * iq) / (vin - vout); + Ok(LdoThermalOut { + power: finite("power", p)?, + rise: finite("rise", rise)?, + tj: finite("tj", tj)?, + headroom: tj_max - tj, + max_iout_at_tj_max: if imax > 0.0 { Some(imax) } else { None }, + }) +} + +/// Input for [`battery_life`]. +#[derive(Debug, Clone, Copy)] +pub struct BatteryLife { + /// Cell capacity, 1 to 1e6 mAh. + pub capacity: f64, + /// Active-mode current, 0 to 1e5 mA. + pub active_current: f64, + /// Sleep current, 0 to 1e5 mA; default 0. + pub sleep_current: f64, + /// Fraction of time active, 0 to 1; default 1. + pub active_fraction: f64, + /// Usable fraction of capacity, 0.1 to 1; default 0.85. + pub usable_fraction: f64, +} + +impl Default for BatteryLife { + fn default() -> Self { + BatteryLife { + capacity: 2000.0, + active_current: 100.0, + sleep_current: 0.0, + active_fraction: 1.0, + usable_fraction: 0.85, + } + } +} + +/// Answer from [`battery_life`]. +#[derive(Debug, Clone, Copy)] +pub struct BatteryLifeOut { + /// Duty-averaged current draw in milliamps. + pub average_current: f64, + /// Run time in hours. + pub hours: f64, + /// Run time in days. + pub days: f64, +} + +/// Duty-cycled battery run time from capacity and average current. +/// +/// # Rules +/// - Iavg = Ia d + Is (1 - d); hours = capacity times usable_fraction +/// divided by Iavg. +/// - A zero average current has no finite run time. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::finite`. +/// # Do not +/// - Use the cell's terminal voltage curve or Peukert effects; this +/// is a charge balance with a derating knob. +pub fn battery_life(a: BatteryLife) -> Result { + let cap = num("capacity", a.capacity, 1.0, 1.0e6)?; + let ia = num("active_current", a.active_current, 0.0, 1.0e5)?; + let is = num("sleep_current", a.sleep_current, 0.0, 1.0e5)?; + let d = num("active_fraction", a.active_fraction, 0.0, 1.0)?; + let eff = num("usable_fraction", a.usable_fraction, 0.1, 1.0)?; + let iavg = ia * d + is * (1.0 - d); + if iavg <= 0.0 { + return Err(Error::Invalid( + "average current is zero; the battery never drains in this model".to_string(), + )); + } + let hours = cap * eff / iavg; + Ok(BatteryLifeOut { + average_current: iavg, + hours: finite("hours", hours)?, + days: hours / 24.0, + }) +} + +/// Insulation temperature rating selecting the ampacity column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum InsulationRating { + /// 60 C building-wire column. + C60, + /// 75 C building-wire column. + #[default] + C75, + /// 90 C building-wire column. + C90, +} + +/// Ampacity table, amperes per AWG for 60 C / 75 C / 90 C columns; +/// None where the published table has no value. +const AMPACITY: &[(i64, [Option; 3])] = &[ + (10, [Some(30.0), Some(35.0), Some(40.0)]), + (12, [Some(20.0), Some(25.0), Some(30.0)]), + (14, [Some(15.0), Some(20.0), Some(25.0)]), + (16, [Some(12.0), Some(16.0), Some(18.0)]), + (18, [Some(10.0), Some(14.0), Some(16.0)]), + (20, [Some(5.0), Some(11.0), None]), + (22, [Some(3.0), Some(7.0), None]), + (24, [Some(2.1), Some(3.5), None]), + (26, [Some(1.3), Some(2.2), None]), + (28, [Some(0.83), Some(1.4), None]), + (30, [Some(0.52), Some(0.86), None]), +]; + +/// Input for [`wire_gauge`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct WireGauge { + /// AWG size, 0 to 40, integer. + pub awg: Option, + /// Current to carry, 0.01 to 200 A, to find a gauge. + pub current: Option, + /// Insulation rating selecting the ampacity column; default 75C. + pub insulation_rating: InsulationRating, +} + +/// Answer from [`wire_gauge`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct WireGaugeOut { + /// Conductor diameter in millimetres. + pub diameter: Option, + /// Copper cross-section in square millimetres. + pub area: Option, + /// DC resistance in ohms per kilometre at 20 C. + pub resistance: Option, + /// Ampacity in amperes for the chosen rating, when tabulated. + pub ampacity: Option, + /// Smallest gauge (largest ampacity) meeting the current, when one + /// was asked for. + pub awg: Option, +} + +/// AWG diameter, area, resistance and ampacity, or the AWG for a current. +/// +/// # Rules +/// - d = 0.127 * 92^((36 - n) / 39) mm; A = pi d^2 / 4; +/// R per km = RHO_CU / A * 1e9 with A in mm^2. +/// - For a current, scan gauges 30 up to 10 and take the first whose +/// tabulated ampacity at the rating reaches it. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (RHO_CU), `AMPACITY`, `crate::num`, +/// `crate::int_num`. +/// # Do not +/// - Treat the ampacity as a PCB trace limit; these are building-wire +/// figures and bundling or ambient changes them. +pub fn wire_gauge(a: WireGauge) -> Result { + let cur = opt_num("current", a.current, 0.01, 200.0)?; + let col = match a.insulation_rating { + InsulationRating::C60 => 0, + InsulationRating::C75 => 1, + InsulationRating::C90 => 2, + }; + let n = match (a.awg, cur) { + (Some(n), _) => int_num("awg", n, 0, 40)?, + (None, Some(_)) => { + let goal = cur.unwrap_or(0.0); + let mut found = None; + for (gauge, cols) in AMPACITY.iter().rev() { + if let Some(cap) = cols[col] + && cap >= goal + { + found = Some(*gauge); + break; + } + } + match found { + Some(g) => g, + None => { + return Err(Error::Invalid(format!( + "no tabulated gauge to 30 carries {goal} A at this rating" + ))); + } + } + } + (None, None) => { + return Err(Error::Invalid( + "give an awg size or a current to carry".to_string(), + )); + } + }; + let d = 0.127 * 92.0f64.powf((36.0 - n as f64) / 39.0); + let area = std::f64::consts::FRAC_PI_4 * d * d; + let ampacity = AMPACITY + .iter() + .find(|(g, _)| *g == n) + .and_then(|(_, cols)| cols[col]); + Ok(WireGaugeOut { + diameter: Some(d), + area: Some(area), + resistance: Some(crate::consts::RHO_CU / (area * 1.0e-6) * 1000.0), + ampacity, + awg: Some(n), + }) +} + +/// Digit value of a colour name, IEC 60062. +fn colour_digit(name: &str) -> Option { + match name { + "black" => Some(0), + "brown" => Some(1), + "red" => Some(2), + "orange" => Some(3), + "yellow" => Some(4), + "green" => Some(5), + "blue" => Some(6), + "violet" => Some(7), + "grey" | "gray" => Some(8), + "white" => Some(9), + _ => None, + } +} + +/// Multiplier of a colour band; None for tolerance-only colours. +fn colour_multiplier(name: &str) -> Option { + match name { + "gold" => Some(0.1), + "silver" => Some(0.01), + "pink" => Some(0.001), + other => colour_digit(other).map(|d| 10.0f64.powi(d as i32)), + } +} + +/// Tolerance percent of a tolerance band. +fn colour_tolerance(name: &str) -> Option { + match name { + "brown" => Some(1.0), + "red" => Some(2.0), + "green" => Some(0.5), + "blue" => Some(0.25), + "violet" => Some(0.1), + "grey" | "gray" => Some(0.01), + "gold" => Some(5.0), + "silver" => Some(10.0), + "none" => Some(20.0), + _ => None, + } +} + +/// Temperature coefficient ppm/K of a sixth band. +fn colour_tempco(name: &str) -> Option { + match name { + "brown" => Some(100.0), + "red" => Some(50.0), + "orange" => Some(15.0), + "yellow" => Some(25.0), + "blue" => Some(10.0), + "violet" => Some(5.0), + _ => None, + } +} + +/// EIA-96 multiplier letter to its factor. +fn eia96_multiplier(letter: char) -> Option { + match letter { + 'Z' => Some(0.001), + 'Y' | 'R' => Some(0.01), + 'X' | 'S' => Some(0.1), + 'A' => Some(1.0), + 'B' | 'H' => Some(10.0), + 'C' => Some(100.0), + 'D' => Some(1000.0), + 'E' => Some(10_000.0), + 'F' => Some(100_000.0), + _ => None, + } +} + +/// Decode one SMD marking: 3 or 4 digits, R notation, or NN plus letter. +fn decode_smd(code: &str) -> Result { + let bytes: Vec = code.chars().collect(); + let bad = Error::Invalid(format!( + "smd_code {code}: expected 3 or 4 digits, R notation like 4R7, or EIA-96 like 68X" + )); + if bytes.len() < 3 || bytes.len() > 4 { + return Err(bad); + } + let all_ok = bytes.iter().enumerate().all(|(k, c)| { + c.is_ascii_digit() + || *c == 'R' + || *c == 'r' + || (bytes.len() == 3 && k == 2 && c.is_ascii_alphabetic()) + }); + if !all_ok { + return Err(bad); + } + // EIA-96: two digits then a multiplier letter. + if bytes.len() == 3 && bytes[0].is_ascii_digit() && bytes[1].is_ascii_digit() { + let letter = match bytes[2].to_uppercase().next() { + Some(c) => c, + None => return Err(bad), + }; + if letter.is_ascii_alphabetic() { + let mult = match eia96_multiplier(letter) { + Some(m) => m, + None => { + return Err(Error::Invalid(format!( + "smd_code {code}: unknown EIA-96 multiplier letter" + ))); + } + }; + let idx = (as_digit_lossy(bytes[0]) * 10 + as_digit_lossy(bytes[1])) as usize; + if idx == 0 || idx > 96 { + return Err(Error::Invalid(format!( + "smd_code {code}: EIA-96 index must be 01 to 96" + ))); + } + let e96 = e_series_values(96); + let base = (e96[idx - 1] * 100.0).round(); + return Ok(base * mult); + } + } + let r_count = bytes.iter().filter(|c| **c == 'R' || **c == 'r').count(); + if r_count > 1 { + return Err(Error::Invalid(format!( + "smd_code {code}: only one R is allowed" + ))); + } + if r_count == 1 { + let pos = match bytes.iter().position(|c| *c == 'R' || *c == 'r') { + Some(p) => p, + None => { + return Err(Error::Invalid(format!( + "smd_code {code}: expected 3 or 4 digits, R notation like 4R7, or EIA-96 like 68X" + ))); + } + }; + let before: String = bytes[..pos].iter().collect(); + let after: String = bytes[pos + 1..].iter().collect(); + if after.is_empty() || before.len() + after.len() < 2 { + return Err(bad); + } + let whole: f64 = before.parse().unwrap_or(0.0); + let frac: f64 = after.parse().unwrap_or(0.0); + return Ok(whole + frac / 10f64.powi(after.len() as i32)); + } + if bytes[bytes.len() - 1].is_ascii_digit() + && bytes[..bytes.len() - 1].iter().all(|c| c.is_ascii_digit()) + { + let exp = as_digit_lossy(bytes[bytes.len() - 1]); + let mantissa: String = bytes[..bytes.len() - 1].iter().collect(); + let base: f64 = match mantissa.parse() { + Ok(v) => v, + Err(_) => return Err(bad), + }; + return Ok(base * 10f64.powi(exp)); + } + Err(bad) +} + +/// ASCII digit value of a character (input checked by the caller). +fn as_digit_lossy(c: char) -> i32 { + if c.is_ascii_digit() { + c as i32 - '0' as i32 + } else { + 0 + } +} + +/// Input for [`resistor_code`]. +#[derive(Debug, Clone, Default)] +pub struct ResistorCode { + /// Colour band names, 4, 5 or 6 bands, lower case. + pub bands: Vec, + /// SMD marking: "472", "4R7", "68X"... + pub smd_code: Option, + /// Encode mode: a resistance in ohms, 1e-3 to 1e12. + pub value: Option, +} + +/// Answer from [`resistor_code`]. +#[derive(Debug, Clone, Default)] +pub struct ResistorCodeOut { + /// Decoded or encoded resistance in ohms. + pub resistance: Option, + /// Tolerance percent, colour-band decode only. + pub tolerance: Option, + /// Temperature coefficient ppm/K, 6-band decode only. + pub tempco: Option, + /// 3-digit SMD marking of the encoded value. + pub smd_3digit: Option, + /// EIA-96 marking of the encoded value. + pub smd_eia96: Option, + /// Caveat for unusual markings, for display. + pub warning: Option, +} + +/// Encode a resistance as a 3-digit SMD marking and an EIA-96 code. +fn encode_resistor(value: f64) -> (String, String) { + let e24 = e_series_values(24); + let e96 = e_series_values(96); + let nearest24 = nearest_from(&e24, value); + let mut exp = (value.log10().floor() - 1.0).round() as i32; + if exp < 0 { + exp = 0; + } + let scaled = nearest24 / 10f64.powi(exp); + let digits = scaled.round() as i64; + let marking = if exp == 0 && nearest24 < 10.0 { + let t = (nearest24 * 10.0).round() as i64; + format!("{t}R") + } else { + format!("{digits}{exp}") + }; + let dec = 10f64.powf(value.log10().floor()); + let m = value / dec; + let mut best = (f64::MAX, 0usize); + for (i, v) in e96.iter().enumerate() { + let d = (v / m).ln().abs(); + if d < best.0 { + best = (d, i); + } + } + let d10 = (10.0 / m).ln().abs(); + let (idx, letter) = if d10 < best.0 { + (0usize, 'A') + } else { + let letter = match exp { + -3 => 'Z', + -2 => 'Y', + -1 => 'X', + 0 => 'A', + 1 => 'B', + 2 => 'C', + 3 => 'D', + 4 => 'E', + 5 => 'F', + _ => 'A', + }; + (best.1 + 1, letter) + }; + (marking, format!("{idx:02}{letter}")) +} + +/// Decode resistor colour bands and SMD markings, or encode a value. +/// +/// # Rules +/// - Priority bands, then smd_code, then value (encode). Four or five +/// bands give digits, multiplier and tolerance; six add the tempco. +/// - Grey and white multipliers are unusual: the result carries a +/// warning to check the datasheet. +/// - Encode mode rounds to E24 and emits the 3-digit and EIA-96 +/// markings. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `colour_digit`, `decode_smd`, `encode_resistor`, +/// [`e_series_values`], `nearest_from`. +/// # Do not +/// - Accept band counts other than 4, 5 or 6; 3-band parts are not a +/// standard code. +pub fn resistor_code(a: ResistorCode) -> Result { + if !a.bands.is_empty() { + let bands: Vec = a.bands.iter().map(|b| b.trim().to_lowercase()).collect(); + let n = bands.len(); + if !(4..=6).contains(&n) { + return Err(Error::Invalid(format!( + "bands: expected 4, 5 or 6 names, got {n}" + ))); + } + let digits = n - if n == 6 { 3 } else { 2 }; + let mut mantissa = 0i64; + for b in &bands[..digits] { + mantissa = mantissa * 10 + + match colour_digit(b) { + Some(d) => d as i64, + None => { + return Err(Error::Invalid(format!("bands: {b} is not a digit colour"))); + } + }; + } + let mult_name = &bands[digits]; + let mult = match colour_multiplier(mult_name) { + Some(m) => m, + None => { + return Err(Error::Invalid(format!( + "bands: {mult_name} is not a multiplier colour" + ))); + } + }; + let tol_name = &bands[n - if n == 6 { 2 } else { 1 }]; + let tolerance = match colour_tolerance(tol_name) { + Some(t) => t, + None => { + return Err(Error::Invalid(format!( + "bands: {tol_name} is not a tolerance colour" + ))); + } + }; + let mut warning = None; + if mult_name == "grey" || mult_name == "gray" || mult_name == "white" { + warning = Some(format!( + "{mult_name} multiplier is unusual; check the datasheet" + )); + } + let tempco = if n == 6 { + match colour_tempco(&bands[n - 1]) { + Some(t) => Some(t), + None => { + return Err(Error::Invalid(format!( + "bands: {} is not a tempco colour", + bands[n - 1] + ))); + } + } + } else { + None + }; + return Ok(ResistorCodeOut { + resistance: Some(mantissa as f64 * mult), + tolerance: Some(tolerance), + tempco, + warning, + ..ResistorCodeOut::default() + }); + } + if let Some(code) = &a.smd_code { + let r = decode_smd(code.trim())?; + return Ok(ResistorCodeOut { + resistance: Some(r), + ..ResistorCodeOut::default() + }); + } + match a.value { + Some(v) => { + let v = num("value", v, 1.0e-3, 1.0e12)?; + let (smd3, eia) = encode_resistor(v); + Ok(ResistorCodeOut { + resistance: Some(v), + smd_3digit: Some(smd3), + smd_eia96: Some(eia), + ..ResistorCodeOut::default() + }) + } + None => Err(Error::Invalid( + "give bands, an smd_code, or a value to encode".to_string(), + )), + } +} diff --git a/crates/calc/src/consts.rs b/crates/calc/src/consts.rs new file mode 100644 index 000000000..347e6a087 --- /dev/null +++ b/crates/calc/src/consts.rs @@ -0,0 +1,31 @@ +//! Physical and unit constants shared by the calculators. +//! +//! Values and their sources are listed in the header of +//! `crates/calc/data/calculators.toml`. Nothing here is a design rule; +//! these are material and unit facts the formulas assume, stated so a +//! reader can trace a number back to a handbook. +//! +//! Local rule: only add a constant here when at least two calculators +//! use it; single-use constants stay in the calculator's own module. + +/// Resistivity of annealed copper at 20 C, ohm metres (CRC Handbook). +pub const RHO_CU: f64 = 1.72e-8; + +/// Temperature coefficient of copper resistance, per kelvin (CRC Handbook). +pub const ALPHA_CU: f64 = 0.00393; + +/// Thermal conductivity of copper, W per metre kelvin (CRC Handbook). +pub const K_CU: f64 = 385.0; + +/// Copper thickness per ounce per square foot, micrometres. Fab shops +/// round this to 35 um; keep the exact 34.79 so tables interpolate. +pub const OZ_UM: f64 = 34.79; + +/// One thousandth of an inch, in millimetres (exact by definition). +pub const MIL_MM: f64 = 0.0254; + +/// Speed of light in vacuum, metres per second (SI definition). +pub const C0: f64 = 299_792_458.0; + +/// Impedance of free space, ohms. +pub const ZF0: f64 = 376.730_313_668_57; diff --git a/crates/calc/src/copper.rs b/crates/calc/src/copper.rs new file mode 100644 index 000000000..3a0052150 --- /dev/null +++ b/crates/calc/src/copper.rs @@ -0,0 +1,288 @@ +//! Copper and current calculators: trace_width, via_current_resistance, +//! trace_resistance_drop. +//! +//! IPC-2221 constants and the public IPC-2152 1 oz table come from the +//! source trail in `crates/calc/data/calculators.toml`. The standards +//! themselves are paywalled; only the reproduced public tables are quoted. + +use crate::consts::{ALPHA_CU, MIL_MM, OZ_UM, RHO_CU}; +use crate::{Error, finite, num, opt_num}; + +/// Which copper the current rules apply to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CopperLayer { + /// Outer layer, more exposed to air. + #[default] + External, + /// Inner layer; IPC-2221 halves the current. + Internal, +} + +/// Which current rule to use. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum TraceMethod { + /// IPC-2152 table when its published range covers the request, + /// IPC-2221 otherwise. + #[default] + Auto, + /// The published IPC-2152 1 oz external table. + Ipc2152, + /// The IPC-2221 closed-form curve. + Ipc2221, +} + +/// Published IPC-2152 1 oz, 10 K, external table: (ampere, mil). +const T2152: [(f64, f64); 10] = [ + (1.0, 10.0), + (2.0, 30.0), + (3.0, 50.0), + (4.0, 80.0), + (5.0, 110.0), + (6.0, 150.0), + (7.0, 180.0), + (8.0, 220.0), + (9.0, 260.0), + (10.0, 300.0), +]; + +/// Log-log interpolation in the published IPC-2152 table. +fn ipc2152_width_mil(current: f64) -> Result { + for ((i0, w0), (i1, w1)) in T2152.iter().zip(T2152.iter().skip(1)) { + if current >= *i0 && current <= *i1 { + let f = (current.ln() - i0.ln()) / (i1.ln() - i0.ln()); + return Ok(w0 * (w1 / w0).powf(f)); + } + } + Err(Error::Invalid(format!( + "the published IPC-2152 table covers 1 to 10 A, got {current}" + ))) +} + +/// Input for [`trace_width`]. +#[derive(Debug, Clone, Copy)] +pub struct TraceWidth { + /// Current in amperes, 0.001 to 100. + pub current: f64, + /// Allowed temperature rise in kelvin, 1 to 100; default 10. + pub temperature_rise: f64, + /// Copper weight in oz per square foot, 0.25 to 6; default 1. + pub copper_weight: f64, + /// External or internal copper; default external. + pub layer: CopperLayer, + /// Which rule to apply; default auto. + pub method: TraceMethod, +} + +impl Default for TraceWidth { + fn default() -> Self { + TraceWidth { + current: 1.0, + temperature_rise: 10.0, + copper_weight: 1.0, + layer: CopperLayer::default(), + method: TraceMethod::default(), + } + } +} + +/// Width answer from [`trace_width`], naming the method that produced it. +#[derive(Debug, Clone, Copy)] +pub struct TraceWidthOut { + /// Minimum width in millimetres. + pub width_mm: f64, + /// Minimum width in mils. + pub width_mil: f64, + /// Cross-section in square mils. + pub cross_section: f64, + /// Which rule was used: ipc2152 or ipc2221. + pub method_used: &'static str, + /// True when the notes must warn about a table approximation. + pub scaled_from_1oz: bool, +} + +/// Minimum width for a current and a temperature rise. +/// +/// # Rules +/// - IPC-2221: I = k dT^0.44 A^0.725, k 0.048 external, 0.024 internal. +/// - The IPC-2152 table applies only to external copper at a 10 K rise +/// and 1 to 10 A; other weights scale the width by 1/oz and set +/// `scaled_from_1oz`. auto picks the table inside its range. +/// - `method_used` states which rule answered; callers must show it. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (OZ_UM, MIL_MM), `crate::num`, `crate::finite`. +/// # Do not +/// - Quote paywalled IPC text; only the reproduced public table is used. +pub fn trace_width(a: TraceWidth) -> Result { + let i = num("current", a.current, 0.001, 100.0)?; + let dt = num("temperature_rise", a.temperature_rise, 1.0, 100.0)?; + let oz = num("copper_weight", a.copper_weight, 0.25, 6.0)?; + let external = a.layer == CopperLayer::External; + let table_ok = external && dt == 10.0 && (1.0..=10.0).contains(&i); + let use_2152 = match a.method { + TraceMethod::Ipc2152 => external && dt == 10.0, + TraceMethod::Ipc2221 => false, + TraceMethod::Auto => table_ok, + }; + let t_mil = oz * OZ_UM / 25.4; + if use_2152 { + let w_mil = ipc2152_width_mil(i)? / oz; + let a_mil2 = w_mil * t_mil; + return Ok(TraceWidthOut { + width_mm: w_mil * MIL_MM, + width_mil: w_mil, + cross_section: a_mil2, + method_used: "ipc2152", + scaled_from_1oz: oz != 1.0, + }); + } + let k = if external { 0.048 } else { 0.024 }; + let a_mil2 = finite("cross_section", (i / (k * dt.powf(0.44))).powf(1.0 / 0.725))?; + let w_mil = finite("width_mil", a_mil2 / t_mil)?; + Ok(TraceWidthOut { + width_mm: w_mil * MIL_MM, + width_mil: w_mil, + cross_section: a_mil2, + method_used: "ipc2221", + scaled_from_1oz: false, + }) +} + +/// Input for [`via_current_resistance`]. +#[derive(Debug, Clone, Copy)] +pub struct ViaCurrent { + /// Drill diameter in millimetres, 0.05 to 10. + pub drill: f64, + /// Barrel plating thickness in micrometres, 5 to 100; default 25. + pub plating: f64, + /// Barrel length in millimetres, 0.1 to 10; default 1.6. + pub length: f64, + /// Allowed temperature rise in kelvin, 1 to 100; default 10. + pub temperature_rise: f64, + /// Optional target current in amperes for the parallel count. + pub target_current: Option, +} + +impl Default for ViaCurrent { + fn default() -> Self { + ViaCurrent { + drill: 0.3, + plating: 25.0, + length: 1.6, + temperature_rise: 10.0, + target_current: None, + } + } +} + +/// Via answer from [`via_current_resistance`]. +#[derive(Debug, Clone, Copy)] +pub struct ViaCurrentOut { + /// Barrel copper cross-section in square millimetres. + pub barrel_area: f64, + /// Current for the temperature rise, amperes. + pub current: f64, + /// Barrel DC resistance in ohms. + pub resistance: f64, + /// Vias needed for the target current, when one was given. + pub count: Option, +} + +/// Current, resistance and parallel count for a plated via. +/// +/// # Rules +/// - Barrel area is the plating annulus; current uses the IPC-2221 +/// internal constant, the usual via convention. +/// - count = ceil(target_current / current), present only when asked. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (RHO_CU, MIL_MM), `crate::num`, `crate::finite`. +/// # Do not +/// - Add pad-to-barrel spreading resistance; the model is a cylinder. +pub fn via_current_resistance(a: ViaCurrent) -> Result { + let drill = num("drill", a.drill, 0.05, 10.0)?; + let plating = num("plating", a.plating, 5.0, 100.0)?; + let length = num("length", a.length, 0.1, 10.0)?; + let dt = num("temperature_rise", a.temperature_rise, 1.0, 100.0)?; + let target = opt_num("target_current", a.target_current, 0.001, 100.0)?; + let d_out = drill + 2.0 * plating / 1000.0; + let area = finite( + "barrel_area", + std::f64::consts::FRAC_PI_4 * (d_out * d_out - drill * drill), + )?; + let current = finite( + "current", + 0.024 * dt.powf(0.44) * (area / MIL_MM.powi(2)).powf(0.725), + )?; + let resistance = finite("resistance", RHO_CU * (length / 1000.0) / (area * 1.0e-6))?; + Ok(ViaCurrentOut { + barrel_area: area, + current, + resistance, + count: target.map(|t| (t / current).ceil()), + }) +} + +/// Input for [`trace_resistance_drop`]. +#[derive(Debug, Clone, Copy)] +pub struct TraceResistance { + /// Width in millimetres, 0.01 to 100. + pub width: f64, + /// Copper weight in oz per square foot, 0.25 to 6; default 1. + pub copper_weight: f64, + /// Length in millimetres, 0.1 to 10000. + pub length: f64, + /// Current in amperes for drop and heat, 0 to 100; default 0. + pub current: f64, + /// Temperature in degrees Celsius, -55 to 200; default 20. + pub temperature: f64, +} + +impl Default for TraceResistance { + fn default() -> Self { + TraceResistance { + width: 0.25, + copper_weight: 1.0, + length: 100.0, + current: 0.0, + temperature: 20.0, + } + } +} + +/// Resistance, drop and heat from [`trace_resistance_drop`]. +#[derive(Debug, Clone, Copy)] +pub struct TraceResistanceOut { + /// DC resistance at the temperature, ohms. + pub resistance: f64, + /// Voltage drop at the current, volts. + pub voltage_drop: f64, + /// Heat at the current, watts. + pub power: f64, +} + +/// DC resistance of a trace with the copper temperature coefficient. +/// +/// # Rules +/// - t = oz times 34.79 um; R = RHO_CU L / (w t) scaled by +/// 1 + ALPHA_CU (T - 20). +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (RHO_CU, ALPHA_CU, OZ_UM), `crate::num`, `crate::finite`. +/// # Do not +/// - Trust it above about 1 MHz; skin effect thins the effective copper. +pub fn trace_resistance_drop(a: TraceResistance) -> Result { + let w = num("width", a.width, 0.01, 100.0)?; + let oz = num("copper_weight", a.copper_weight, 0.25, 6.0)?; + let l = num("length", a.length, 0.1, 10000.0)?; + let i = num("current", a.current, 0.0, 100.0)?; + let t = num("temperature", a.temperature, -55.0, 200.0)?; + let thickness = oz * OZ_UM / 1000.0; + let r20 = finite( + "resistance", + RHO_CU * (l / 1000.0) / ((w * thickness) * 1.0e-6), + )?; + let r = r20 * (1.0 + ALPHA_CU * (t - 20.0)); + Ok(TraceResistanceOut { + resistance: r, + voltage_drop: i * r, + power: i * i * r, + }) +} diff --git a/crates/calc/src/impedance.rs b/crates/calc/src/impedance.rs new file mode 100644 index 000000000..b3454bcbf --- /dev/null +++ b/crates/calc/src/impedance.rs @@ -0,0 +1,526 @@ +//! Impedance and signal-integrity calculators: microstrip, +//! embedded_microstrip, stripline, coplanar_waveguide, differential_pair, +//! propagation_delay, crosstalk. +//! +//! The microstrip family is one Hammerstad-Jensen formula, continuous in +//! w / h, replacing the old two-branch estimate that jumped about 12 ohm +//! at w = h (see research-283-length-impedance.md). Models are labelled +//! exact, model or estimate in the metadata; the UI must show that label. + +use crate::consts::{C0, ZF0}; +use crate::{Error, finite, num, opt_num}; + +/// Hammerstad-Jensen zero-thickness transmission line function ZL1(u). +fn zl1(u: f64) -> f64 { + let f = 6.0 + (2.0 * std::f64::consts::PI - 6.0) * (-(30.666 / u).powf(0.7528)).exp(); + ZF0 / (2.0 * std::f64::consts::PI) * (f / u + (1.0 + (2.0 / u).powi(2)).sqrt()).ln() +} + +/// Hammerstad-Jensen effective permittivity at ratio u for er. +fn eeff(u: f64, er: f64) -> f64 { + let a = 1.0 + + ((u.powi(4) + (u / 52.0).powi(2)) / (u.powi(4) + 0.432)).ln() / 49.0 + + (1.0 + (u / 18.1).powi(3)).ln() / 18.7; + let b = 0.564 * ((er - 0.9) / (er + 3.0)).powf(0.053); + (er + 1.0) / 2.0 + (er - 1.0) / 2.0 * (1.0 + 10.0 / u).powf(-a * b) +} + +/// Core Hammerstad-Jensen result: (z0, eeff with the thickness correction). +fn hj(w: f64, h: f64, er: f64, t: f64) -> (f64, f64) { + let u = w / h; + let (u1, ur) = if t > 0.0 { + let tn = t / h; + let th = (6.517 * u).sqrt().tanh(); + let du1 = tn / std::f64::consts::PI * (1.0 + 4.0 * std::f64::consts::E / tn * th * th).ln(); + let dur = du1 * (1.0 + 1.0 / (er - 1.0).sqrt().cosh()) / 2.0; + (u + du1, u + dur) + } else { + (u, u) + }; + let e = eeff(ur, er); + let z = zl1(ur) / e.sqrt(); + let e_t = e * (zl1(u1) / zl1(ur)).powi(2); + (z, e_t) +} + +/// Delay in ps per mm for an effective permittivity. +fn delay_ps_mm(eeff: f64) -> f64 { + eeff.sqrt() / C0 * 1.0e9 +} + +/// Input for [`microstrip`]. +#[derive(Debug, Clone, Copy)] +pub struct Microstrip { + /// Trace width in millimetres, 0.01 to 100; omit only for a target solve. + pub width: Option, + /// Dielectric height in millimetres, 0.01 to 10. + pub height: f64, + /// Relative permittivity, 1 to 20. + pub er: f64, + /// Copper thickness in millimetres, 0 to 0.5; default 0.035. + pub thickness: f64, + /// Optional target impedance in ohms, 1 to 1000. + pub target: Option, +} + +impl Default for Microstrip { + fn default() -> Self { + Microstrip { + width: None, + height: 1.6, + er: 4.5, + thickness: 0.035, + target: None, + } + } +} + +/// Answer from [`microstrip`]. +#[derive(Debug, Clone, Copy)] +pub struct MicrostripOut { + /// Characteristic impedance in ohms, when a width was given. + pub z0: Option, + /// Effective permittivity including the thickness correction. + pub eeff: Option, + /// Delay in picoseconds per millimetre, when a width was given. + pub delay: Option, + /// Width meeting the target, when a target was given. + pub width_for_target: Option, +} + +/// Surface microstrip impedance, one formula continuous across w / h = 1. +/// +/// # Rules +/// - Needs a width, a target, or both; the target solves width by +/// bisection on 0.01 to 100 mm, 80 steps. +/// - Hammerstad-Jensen 1980 with the Hammerstad thickness correction. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (C0, ZF0), `crate::num`, `crate::finite`. +/// # Do not +/// - Add solder mask; it lowers Z0 by 1 to 3 ohm and is not modelled. +pub fn microstrip(a: Microstrip) -> Result { + let w = opt_num("width", a.width, 0.01, 100.0)?; + let h = num("height", a.height, 0.01, 10.0)?; + let er = num("er", a.er, 1.0, 20.0)?; + let t = num("thickness", a.thickness, 0.0, 0.5)?; + let target = opt_num("target", a.target, 1.0, 1000.0)?; + if w.is_none() && target.is_none() { + return Err(Error::Invalid( + "give a width, a target impedance, or both".to_string(), + )); + } + let (z0, eeff, delay) = match w { + Some(w) => { + let (z, e) = hj(w, h, er, t); + (Some(finite("z0", z)?), Some(e), Some(delay_ps_mm(e))) + } + None => (None, None, None), + }; + let width_for_target = match target { + Some(goal) => { + let (mut lo, mut hi) = (0.01f64, 100.0f64); + for _ in 0..80 { + let mid = (lo + hi) / 2.0; + if hj(mid, h, er, t).0 > goal { + lo = mid; + } else { + hi = mid; + } + } + Some((lo + hi) / 2.0) + } + None => None, + }; + Ok(MicrostripOut { + z0, + eeff, + delay, + width_for_target, + }) +} + +/// Input for [`embedded_microstrip`]. +#[derive(Debug, Clone, Copy)] +pub struct EmbeddedMicrostrip { + /// Trace width in millimetres, 0.01 to 100. + pub width: f64, + /// Dielectric height below the trace in millimetres, 0.01 to 10. + pub height: f64, + /// Dielectric covering the trace top in millimetres, 0 to 10. + pub cover: f64, + /// Relative permittivity, 1 to 20. + pub er: f64, + /// Copper thickness in millimetres, 0 to 0.5; default 0.035. + pub thickness: f64, +} + +impl Default for EmbeddedMicrostrip { + fn default() -> Self { + EmbeddedMicrostrip { + width: 1.0, + height: 1.6, + cover: 0.0, + er: 4.5, + thickness: 0.035, + } + } +} + +/// Impedance and effective permittivity from [`embedded_microstrip`]. +#[derive(Debug, Clone, Copy)] +pub struct EmbeddedMicrostripOut { + /// Characteristic impedance in ohms. + pub z0: f64, + /// Effective permittivity with the cover. + pub eeff: f64, +} + +/// Surface microstrip impedance corrected for a dielectric cover layer. +/// +/// # Rules +/// - Start from the surface Hammerstad-Jensen result, then blend the +/// effective permittivity toward er with weight 1 - exp(-2 cover / h). +/// - Engineering estimate, about 5 %; the metadata accuracy label says +/// so and the UI must repeat it. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for [`microstrip`]'s helpers `hj` and `crate::num`. +/// # Do not +/// - Use for cover >= 2 h; a stripline model is better there. +pub fn embedded_microstrip(a: EmbeddedMicrostrip) -> Result { + let w = num("width", a.width, 0.01, 100.0)?; + let h = num("height", a.height, 0.01, 10.0)?; + let cover = num("cover", a.cover, 0.0, 10.0)?; + let er = num("er", a.er, 1.0, 20.0)?; + let t = num("thickness", a.thickness, 0.0, 0.5)?; + let (z_s, e_s) = hj(w, h, er, t); + let f = (-2.0 * cover / h).exp(); + let e_e = finite("eeff", e_s * f + er * (1.0 - f))?; + let z0 = finite("z0", z_s * (e_s / e_e).sqrt())?; + Ok(EmbeddedMicrostripOut { z0, eeff: e_e }) +} + +/// Input for [`stripline`]. +#[derive(Debug, Clone, Copy)] +pub struct Stripline { + /// Trace width in millimetres, 0.01 to 100. + pub width: f64, + /// Plane-to-plane distance in millimetres, 0.02 to 20. + pub spacing: f64, + /// Relative permittivity, 1 to 20. + pub er: f64, + /// Copper thickness in millimetres, 0 to 0.5; default 0.018. + pub thickness: f64, +} + +impl Default for Stripline { + fn default() -> Self { + Stripline { + width: 0.2, + spacing: 0.6, + er: 4.2, + thickness: 0.018, + } + } +} + +/// Impedance and delay from [`stripline`]. +#[derive(Debug, Clone, Copy)] +pub struct StriplineOut { + /// Characteristic impedance in ohms. + pub z0: f64, + /// Delay in picoseconds per millimetre (eeff = er, fully embedded). + pub delay: f64, +} + +/// Stripline impedance, Steer's closed form with trace thickness. +/// +/// # Rules +/// - Trace centred between two planes; W = w / b, T = t / b. +/// - Effective width shrinks by (0.35 - W)^2 / (1 + 12 T) only for +/// W < 0.35; the flat-plate term Cf corrects the finite thickness. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (C0), `crate::num`, `crate::finite`. +/// # Do not +/// - Use for an offset stripline; the symmetric form is all this models. +pub fn stripline(a: Stripline) -> Result { + let w = num("width", a.width, 0.01, 100.0)?; + let b = num("spacing", a.spacing, 0.02, 20.0)?; + let er = num("er", a.er, 1.0, 20.0)?; + let t = num("thickness", a.thickness, 0.0, 0.5)?; + let (big_w, tt) = (w / b, t / b); + let weff = if big_w < 0.35 { + big_w - (0.35 - big_w).powi(2) / (1.0 + 12.0 * tt) + } else { + big_w + }; + let one_m_t = 1.0 - tt; + let cf = 2.0 / std::f64::consts::PI * (1.0 / one_m_t + 1.0).ln() + - tt / std::f64::consts::PI * ((1.0 / one_m_t).powi(2) - 1.0).ln(); + let z0 = finite( + "z0", + 30.0 * std::f64::consts::PI / er.sqrt() * one_m_t / (weff + cf), + )?; + Ok(StriplineOut { + z0, + delay: delay_ps_mm(er), + }) +} + +/// Elliptic integral ratio K(k) / K'(k) by the Hilberg approximation. +fn kk(k: f64) -> f64 { + let kp = (1.0 - k * k).sqrt(); + if k <= std::f64::consts::FRAC_1_SQRT_2 { + std::f64::consts::PI / (2.0 * (1.0 + kp.sqrt()) / (1.0 - kp.sqrt())).ln() + } else { + (2.0 * (1.0 + k.sqrt()) / (1.0 - k.sqrt())).ln() / std::f64::consts::PI + } +} + +/// Input for [`coplanar_waveguide`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct CoplanarWaveguide { + /// Centre trace width in millimetres, 0.01 to 100. + pub width: f64, + /// Gap from trace edge to side ground in millimetres, 0.01 to 100. + pub gap: f64, + /// Substrate height in millimetres, 0.01 to 10. + pub height: f64, + /// Relative permittivity, 1 to 20. + pub er: f64, + /// True for ground-backed CPW (a plane under the substrate, + /// side grounds tied to it with vias). + pub ground_backed: bool, +} + +/// Impedance, permittivity and delay from [`coplanar_waveguide`]. +#[derive(Debug, Clone, Copy)] +pub struct CoplanarWaveguideOut { + /// Characteristic impedance in ohms. + pub z0: f64, + /// Effective permittivity. + pub eeff: f64, + /// Delay in picoseconds per millimetre. + pub delay: f64, +} + +/// Coplanar waveguide impedance, quasi-static conformal mapping. +/// +/// # Rules +/// - Zero-thickness model; copper thickness is deliberately ignored. +/// - Ground-backed mode uses the tanh ratio k3 and adds its weight q +/// to the permittivity; ungrounded mode uses the sinh ratio k2. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `kk` (Hilberg ratio), `delay_ps_mm`, `crate::num`. +/// # Do not +/// - Assume narrow side grounds; the formula needs grounds much wider +/// than w + 2s. +pub fn coplanar_waveguide(a: CoplanarWaveguide) -> Result { + let w = num("width", a.width, 0.01, 100.0)?; + let s = num("gap", a.gap, 0.01, 100.0)?; + let h = num("height", a.height, 0.01, 10.0)?; + let er = num("er", a.er, 1.0, 20.0)?; + let pi = std::f64::consts::PI; + let k1 = w / (w + 2.0 * s); + let (z0, eeff) = if a.ground_backed { + let k3 = (pi * w / (4.0 * h)).tanh() / (pi * (w + 2.0 * s) / (4.0 * h)).tanh(); + let q = kk(k3) / (kk(k1) + kk(k3)); + let e = 1.0 + q * (er - 1.0); + (60.0 * pi / e.sqrt() / (kk(k1) + kk(k3)), e) + } else { + let k2 = (pi * w / (4.0 * h)).sinh() / (pi * (w + 2.0 * s) / (4.0 * h)).sinh(); + let e = 1.0 + (er - 1.0) / 2.0 * kk(k2) / kk(k1); + (30.0 * pi / e.sqrt() / kk(k1), e) + }; + Ok(CoplanarWaveguideOut { + z0: finite("z0", z0)?, + eeff: finite("eeff", eeff)?, + delay: delay_ps_mm(eeff), + }) +} + +/// Input for [`differential_pair`]. +#[derive(Debug, Clone, Copy)] +pub struct DifferentialPair { + /// Trace width in millimetres, 0.01 to 100. + pub width: f64, + /// Edge-to-edge gap in millimetres, 0.01 to 100. + pub gap: f64, + /// Dielectric height in millimetres, 0.01 to 10. + pub height: f64, + /// Relative permittivity, 1 to 20. + pub er: f64, + /// Copper thickness in millimetres, 0 to 0.5; default 0.035. + pub thickness: f64, + /// Optional target differential impedance in ohms, 10 to 1000. + pub target: Option, +} + +impl Default for DifferentialPair { + fn default() -> Self { + DifferentialPair { + width: 0.2, + gap: 0.2, + height: 0.2, + er: 4.2, + thickness: 0.035, + target: None, + } + } +} + +/// Results from [`differential_pair`]. +#[derive(Debug, Clone, Copy)] +pub struct DifferentialPairOut { + /// Differential impedance in ohms. + pub zdiff: f64, + /// Single-ended impedance of one trace in ohms. + pub z0_single: f64, + /// Width meeting the target with the gap fixed, when asked. + pub width_for_target: Option, + /// Edge-coupling factor 2 (1 - 0.48 exp(-0.96 s / h)). + pub coupling_factor: f64, +} + +/// Differential impedance of two equal coupled surface traces. +/// +/// # Rules +/// - Single-ended Hammerstad-Jensen Z0 times the edge-coupling factor +/// 2 (1 - 0.48 exp(-0.96 s / h)); the factor is an unverified +/// IPC-2141 attribution, so the result is labelled an estimate. +/// - `target` solves width by bisection with the gap fixed. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for [`microstrip`]'s helper `hj`, `crate::num`, `crate::opt_num`. +/// # Do not +/// - Trust it for s < w; loosely coupled pairs (s >= w) are the model's +/// range. +pub fn differential_pair(a: DifferentialPair) -> Result { + let w = num("width", a.width, 0.01, 100.0)?; + let s = num("gap", a.gap, 0.01, 100.0)?; + let h = num("height", a.height, 0.01, 10.0)?; + let er = num("er", a.er, 1.0, 20.0)?; + let t = num("thickness", a.thickness, 0.0, 0.5)?; + let target = opt_num("target", a.target, 10.0, 1000.0)?; + let factor = 2.0 * (1.0 - 0.48 * (-0.96 * s / h).exp()); + let z0_single = hj(w, h, er, t).0; + let zdiff = finite("zdiff", z0_single * factor)?; + let width_for_target = match target { + Some(goal) => { + let (mut lo, mut hi) = (0.01f64, 100.0f64); + for _ in 0..80 { + let mid = (lo + hi) / 2.0; + if 2.0 * hj(mid, h, er, t).0 * factor > goal { + lo = mid; + } else { + hi = mid; + } + } + Some((lo + hi) / 2.0) + } + None => None, + }; + Ok(DifferentialPairOut { + zdiff, + z0_single, + width_for_target, + coupling_factor: factor, + }) +} + +/// Input for [`propagation_delay`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct PropagationDelay { + /// Effective permittivity, 1 to 20; from an impedance calculator + /// or er for a buried trace. + pub eeff: f64, + /// Optional trace length in millimetres, 0 to 10000. + pub length: Option, + /// Optional skew budget in picoseconds, 0 to 1e6. + pub skew_budget: Option, +} + +/// Delays and length budget from [`propagation_delay`]. +#[derive(Debug, Clone, Copy)] +pub struct PropagationDelayOut { + /// Delay in picoseconds per millimetre. + pub delay: f64, + /// Delay in picoseconds per inch. + pub delay_inch: f64, + /// Delay over the given length, when a length was given. + pub total_delay: Option, + /// Length a skew budget allows, when a budget was given. + pub allowed_mismatch: Option, +} + +/// Signal speed from effective permittivity, and a skew budget in mm. +/// +/// # Rules +/// - tpd = sqrt(eeff) / C0, exact for the given eeff; inch values use +/// the 25.4 mm definition. +/// - `length` and `skew_budget` are independent extras; give neither. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (C0), `delay_ps_mm`, `crate::opt_num`. +/// # Do not +/// - Reuse a stripline eeff for a microstrip of the same stackup; +/// take eeff from the matching impedance calculator. +pub fn propagation_delay(a: PropagationDelay) -> Result { + let e = num("eeff", a.eeff, 1.0, 20.0)?; + let len = opt_num("length", a.length, 0.0, 10_000.0)?; + let skew = opt_num("skew_budget", a.skew_budget, 0.0, 1.0e6)?; + let tpd = delay_ps_mm(e); + Ok(PropagationDelayOut { + delay: tpd, + delay_inch: tpd * 25.4, + total_delay: len.map(|l| finite("total_delay", tpd * l)).transpose()?, + allowed_mismatch: skew + .map(|s| finite("allowed_mismatch", s / tpd)) + .transpose()?, + }) +} + +/// Input for [`crosstalk`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct Crosstalk { + /// Edge-to-edge gap in millimetres, 0.01 to 100. + pub gap: f64, + /// Dielectric height in millimetres, 0.01 to 10. + pub height: f64, + /// Trace width in millimetres, 0.01 to 100, for the 3W gap. + pub width: f64, +} + +/// Coupling estimates from [`crosstalk`]. +#[derive(Debug, Clone, Copy)] +pub struct CrosstalkOut { + /// Fraction of the aggressor swing coupled into the victim. + pub coupling: f64, + /// Same coupling in dB. + pub coupling_db: f64, + /// 3W rule gap in millimetres (edge to edge, centre spacing 3 w). + pub three_w_gap: f64, + /// Gap for -20 dB, 3 h, in millimetres. + pub spacing_for_minus_20db: f64, +} + +/// Order-of-magnitude near-end crosstalk for parallel surface traces. +/// +/// # Rules +/// - coupling = 1 / (1 + (s/h)^2); dB = 20 log10 of that; the 3W gap +/// is 2 w edge to edge; -20 dB needs s = 3 h. +/// - Rule of thumb, real values land within a factor of 2. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::num`, `crate::finite`. +/// # Do not +/// - Apply to stripline (couples less) or to long coupled lengths +/// comparable with the rise time. +pub fn crosstalk(a: Crosstalk) -> Result { + let s = num("gap", a.gap, 0.01, 100.0)?; + let h = num("height", a.height, 0.01, 10.0)?; + let w = num("width", a.width, 0.01, 100.0)?; + let coupling = 1.0 / (1.0 + (s / h).powi(2)); + Ok(CrosstalkOut { + coupling, + coupling_db: finite("coupling_db", 20.0 * coupling.log10())?, + three_w_gap: 2.0 * w, + spacing_for_minus_20db: 3.0 * h, + }) +} diff --git a/crates/calc/src/lib.rs b/crates/calc/src/lib.rs new file mode 100644 index 000000000..561fd8da5 --- /dev/null +++ b/crates/calc/src/lib.rs @@ -0,0 +1,116 @@ +//! Pure calculator engine for the Help reference (#394) and the user +//! calculators (#350). One function per calculator, no UI, no design +//! state: the command layer, the MCP server and the Help panel all read +//! formulas, ranges and labels from this crate instead of holding copies. +//! +//! Layer 0, beside geom: depends on no other pcbcraft crate and on no +//! external crates. The `toml` crate is a dev dependency only, used by +//! `tests/golden.rs` to replay the vectors. +//! +//! Local rules: +//! - `data/calculators.toml` is the single source of truth for inputs, +//! ranges, formulas, sources, accuracy labels and golden vectors. +//! `meta::CALCULATORS` mirrors it and the golden test checks both. +//! - Every calculator takes one input struct and returns +//! `Result`. Out-of-range inputs come back as +//! `Error::OutOfRange` naming the closed interval; nothing panics. +//! - Result labels (exact, model or estimate) live in the metadata +//! `accuracy` field; callers must show them next to results. +pub mod basic; +pub mod components; +pub mod consts; +pub mod copper; +pub mod impedance; +pub mod meta; +pub mod spacing; +pub mod utilities; + +/// Why a calculator refused its inputs. +#[derive(Debug, Clone, PartialEq)] +pub enum Error { + /// A numeric input fell outside the closed interval the calculator + /// accepts. The message states the interval, as the ticket requires. + OutOfRange { + /// Name of the offending input, as the metadata lists it. + input: String, + /// Lowest accepted value. + min: f64, + /// Highest accepted value. + max: f64, + /// Value that was rejected. + given: f64, + }, + /// Inputs were individually in range but do not form a case the + /// calculator can solve (missing pair, contradictory pair, zero + /// denominator, or a result that overflowed). + Invalid(String), +} + +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Error::OutOfRange { + input, + min, + max, + given, + } => write!(f, "{input} must be between {min} and {max}, got {given}"), + Error::Invalid(message) => write!(f, "{message}"), + } + } +} + +impl std::error::Error for Error {} + +/// Check a required numeric input against its closed interval. +pub(crate) fn num(name: &str, value: f64, min: f64, max: f64) -> Result { + if !value.is_finite() { + return Err(Error::Invalid(format!("{name} must be a finite number"))); + } + if value < min || value > max { + return Err(Error::OutOfRange { + input: name.to_string(), + min, + max, + given: value, + }); + } + Ok(value) +} + +/// Check an optional numeric input; absent passes through. +pub(crate) fn opt_num( + name: &str, + value: Option, + min: f64, + max: f64, +) -> Result, Error> { + match value { + None => Ok(None), + Some(v) => num(name, v, min, max).map(Some), + } +} + +/// Accept an integer input only inside the given closed interval. +pub(crate) fn int_num(name: &str, value: i64, min: i64, max: i64) -> Result { + if value < min || value > max { + return Err(Error::OutOfRange { + input: name.to_string(), + min: min as f64, + max: max as f64, + given: value as f64, + }); + } + Ok(value) +} + +/// Guard a computed value: a non-finite result means the inputs, though +/// individually in range, produced an overflow or a zero denominator. +pub(crate) fn finite(name: &str, value: f64) -> Result { + if !value.is_finite() { + return Err(Error::Invalid(format!( + "{name} is not finite for these inputs; check for a zero denominator" + ))); + } + Ok(value) +} diff --git a/crates/calc/src/meta.rs b/crates/calc/src/meta.rs new file mode 100644 index 000000000..7a0d7b783 --- /dev/null +++ b/crates/calc/src/meta.rs @@ -0,0 +1,625 @@ +//! Declarative metadata for every calculator, mirroring `data/calculators.toml`. +//! +//! The data file is the source of truth; `tests/golden.rs` cross-checks this +//! table against it. The table exists so the engine and MCP layers can +//! discover ids, input ranges and formulas at runtime without pulling in +//! `toml` as a runtime dependency. +//! +//! This file is generated from the data file by a one-off script; regenerate +//! it whenever the data file changes. + +/// One input of a calculator: name, unit label, inclusive range, and +/// whether the input may be omitted. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct InputMeta { + /// Input name, identical to the data file and the input struct field. + pub name: &'static str, + /// Unit label for UI display; empty when dimensionless. + pub unit: &'static str, + /// Inclusive lower bound, when the input is bounded. + pub min: Option, + /// Inclusive upper bound, when the input is bounded. + pub max: Option, + /// True when the calculator accepts the input being absent. + pub optional: bool, + /// Choice labels, empty for plain numeric inputs. + pub values: &'static [&'static str], +} + +impl InputMeta { + /// Numeric input with a closed range. + const fn num(name: &'static str, unit: &'static str, min: f64, max: f64) -> Self { + Self { + name, + unit, + min: Some(min), + max: Some(max), + optional: false, + values: &[], + } + } + + /// Optional numeric input with a closed range. + const fn opt(name: &'static str, unit: &'static str, min: f64, max: f64) -> Self { + Self { + name, + unit, + min: Some(min), + max: Some(max), + optional: true, + values: &[], + } + } + + /// Choice input (enum or boolean) with labels and no numeric range. + const fn choice(name: &'static str, values: &'static [&'static str]) -> Self { + Self { + name, + unit: "enum", + min: None, + max: None, + optional: false, + values, + } + } + + /// Free-form text input that may be omitted. + const fn text(name: &'static str, unit: &'static str) -> Self { + Self { + name, + unit, + min: None, + max: None, + optional: true, + values: &[], + } + } +} + +/// Metadata describing one calculator: identity, provenance and inputs. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CalculatorMeta { + /// Stable id, identical to the data file. + pub id: &'static str, + /// Human readable name. + pub name: &'static str, + /// Module group: basic, copper, impedance, spacing, components or utilities. + pub group: &'static str, + /// One sentence summary. + pub summary: &'static str, + /// Formula text, copied from the data file. + pub formula: &'static str, + /// Sources backing the numbers. + pub source: &'static str, + /// Applicability limits in prose. + pub validity: &'static str, + /// Accuracy statement in prose. + pub accuracy: &'static str, + /// Inputs in declaration order. + pub inputs: &'static [InputMeta], +} + +/// Every calculator, in data file order. +pub static CALCULATORS: [CalculatorMeta; 32] = [ + CalculatorMeta { + id: "ohms_law", + name: "Ohm's law and power", + group: "basic", + summary: "Give any two of voltage, current and resistance; get the third and the power.", + formula: "V = I R; P = V I = I^2 R = V^2 / R. Exactly two inputs must be given.", + source: "Ohm's law and Joule heating, any introductory circuits text (Horowitz and Hill, The Art of Electronics, 3rd ed., ch. 1).", + validity: "Linear resistors at DC or RMS AC. Not for reactive loads (use reactance).", + accuracy: "exact", + inputs: &[ + InputMeta::opt("voltage", "V", 0.0, 1000000.0), + InputMeta::opt("current", "A", 0.0, 1000000.0), + InputMeta::opt("resistance", "ohm", 1e-09, 1000000000000.0), + ], + }, + CalculatorMeta { + id: "series_parallel", + name: "Series and parallel R, C, L", + group: "basic", + summary: "Combine up to 16 resistors, capacitors or inductors in series or in parallel.", + formula: "R, L series = sum; parallel = 1 / sum(1/x). C is the reverse: parallel = sum, series = 1 / sum(1/x).", + source: "Kirchhoff's laws; any introductory text.", + validity: "Ideal components.", + accuracy: "exact", + inputs: &[ + InputMeta::choice("kind", &["resistor", "capacitor", "inductor"]), + InputMeta::num("values", "ohm | F | H", 1e-15, 1000000000000.0), + ], + }, + CalculatorMeta { + id: "voltage_divider", + name: "Voltage divider with load", + group: "basic", + summary: "Output voltage of two resistors, with an optional load resistor across the output.", + formula: "R2e = load given ? R2 || load : R2; Vout = Vin R2e / (R1 + R2e); I = Vin / (R1 + R2e).", + source: "Horowitz and Hill, The Art of Electronics, 3rd ed., section 1.2.3 (voltage dividers) and Thevenin loading.", + validity: "Linear resistors; load modelled as a resistor to ground.", + accuracy: "exact", + inputs: &[ + InputMeta::num("vin", "V", 0.0, 100000.0), + InputMeta::num("r1", "ohm", 0.001, 1000000000000.0), + InputMeta::num("r2", "ohm", 0.001, 1000000000000.0), + InputMeta::opt("load", "ohm", 0.001, 1000000000000.0), + ], + }, + CalculatorMeta { + id: "led_resistor", + name: "LED series resistor", + group: "basic", + summary: "Resistor for an LED from supply voltage, forward voltage and wanted current, with the resistor's power and the nearest E-series value.", + formula: "R = (Vs - Vf) / I; P = (Vs - Vf) I. Refuse when Vf >= Vs.", + source: "Ohm's law; typical Vf: red 1.8 to 2.2 V, green or blue or white 2.8 to 3.4 V (any LED datasheet).", + validity: "One LED or a series string whose total Vf is entered. Vf is current dependent, so the result is a starting point.", + accuracy: "exact for the given Vf", + inputs: &[ + InputMeta::num("supply", "V", 0.1, 1000.0), + InputMeta::num("forward_voltage", "V", 0.1, 50.0), + InputMeta::num("current", "A", 1e-06, 10.0), + InputMeta::choice("series", &["E6", "E12", "E24", "E96"]), + ], + }, + CalculatorMeta { + id: "rc_rl_time_constant", + name: "RC and RL time constant and cutoff", + group: "basic", + summary: "Time constant and the -3 dB corner frequency of a first-order RC or RL network.", + formula: "RC: tau = R C. RL: tau = L / R. fc = 1 / (2 pi tau).", + source: "First-order response; Horowitz and Hill, 3rd ed., section 1.4.2 and 1.7.1.", + validity: "Single-pole networks only.", + accuracy: "exact", + inputs: &[ + InputMeta::choice("kind", &["rc", "rl"]), + InputMeta::num("resistance", "ohm", 0.001, 1000000000000.0), + InputMeta::opt("capacitance", "F", 1e-15, 1.0), + InputMeta::opt("inductance", "H", 1e-12, 1000.0), + ], + }, + CalculatorMeta { + id: "lc_resonance", + name: "Resonant frequency", + group: "basic", + summary: "Resonant frequency of an inductor and capacitor, or the L or C needed for a target frequency.", + formula: "f0 = 1 / (2 pi sqrt(L C)); solve for the missing one of the three.", + source: "Thomson's formula; any circuits text.", + validity: "Lossless LC. Real parts shift f0 by their parasitics.", + accuracy: "exact", + inputs: &[ + InputMeta::opt("inductance", "H", 1e-12, 1000.0), + InputMeta::opt("capacitance", "F", 1e-15, 1.0), + InputMeta::opt("frequency", "Hz", 0.001, 1000000000000.0), + ], + }, + CalculatorMeta { + id: "reactance", + name: "Reactance", + group: "basic", + summary: "Reactance of a capacitor or inductor at a frequency.", + formula: "Xc = 1 / (2 pi f C); Xl = 2 pi f L.", + source: "Any circuits text.", + validity: "Ideal components; ignores ESR and self resonance.", + accuracy: "exact", + inputs: &[ + InputMeta::num("frequency", "Hz", 0.001, 1000000000000.0), + InputMeta::opt("capacitance", "F", 1e-15, 1.0), + InputMeta::opt("inductance", "H", 1e-12, 1000.0), + ], + }, + CalculatorMeta { + id: "decibel", + name: "Decibel conversions", + group: "basic", + summary: "Convert between power ratio, voltage ratio, dB, dBm and watts.", + formula: "dB(power) = 10 log10(P2/P1); dB(voltage, equal impedance) = 20 log10(V2/V1); dBm = 10 log10(P / 1 mW); P = 1 mW * 10^(dBm/10).", + source: "IEEE Std 100 definitions; any RF text.", + validity: "Voltage form assumes equal source and load impedance.", + accuracy: "exact", + inputs: &[ + InputMeta::choice( + "mode", + &["power_ratio", "voltage_ratio", "dbm_to_w", "w_to_dbm"], + ), + InputMeta::num("value", "ratio | dB | dBm | W", -300.0, 1000000000000.0), + ], + }, + CalculatorMeta { + id: "trace_width", + name: "Trace width for current", + group: "copper", + summary: "Minimum copper width for a current and allowed temperature rise. IPC-2152 table lookup when inside its published range, IPC-2221 formula otherwise, both stated.", + formula: "IPC-2221 (closed form, both layers): I = k dT^0.44 A^0.725, A in mil^2, k = 0.048 external, 0.024 internal.\n A = (I / (k dT^0.44))^(1/0.725); width_mil = A / thickness_mil; thickness_mil = oz * 34.79 / 25.4.\nIPC-2152 (table, used by `auto` only when layer = external, copper_weight = 1 and 1 A <= I <= 10 A and dT = 10 K):\n log-log interpolation in the published 1 oz / 10 K external table\n (A, mil): (1,10) (2,30) (3,50) (4,80) (5,110) (6,150) (7,180) (8,220) (9,260) (10,300).\n Other copper weights scale width by 1/oz as a stated approximation (constant cross-section), flagged in notes.\n", + source: "IPC-2221 constants: Sierra Circuits, \"How to optimize your PCB trace using IPC-2152\" (sources/standards/ipc2152-protoexpress.txt) and Altium IPC-2221 calculator page (sources/standards/ipc2221-trace-calc-altium.txt); the standard itself is paywalled (IPC-2221C, shop.ipc.org).\nIPC-2152 table: Altium, \"PCB trace width vs current table\" (sources/standards/ipc2152-altium-width-table.txt), a secondary reproduction of one IPC-2152 chart; the standard is paywalled (shop.ipc.org/ipc-2152).\nCross-check table: Philip McGaw trace width vs current table (sources/standards/trace-width-philipmcgaw.txt).\n", + validity: "IPC-2221 curves come from 1950s test boards; the standard describes them as conservative. Assumptions stated to the user: still air, no adjacent copper planes, trace length much longer than width, FR-4.\nIPC-2152 published chart only covers 1 oz external copper at 10 K rise here; anything else falls back to IPC-2221 and the notes say so.\nInternal layers: IPC-2152 found internal and external traces behave about the same when a plane is nearby; IPC-2221 halves internal current. The notes mention this.\n", + accuracy: "IPC-2221: matches the published 10 K table within 1 % (the 1 % is the 34.79 vs 35 um copper rounding). IPC-2152: interpolation of a secondary reproduction; treat as +-10 %.", + inputs: &[ + InputMeta::num("current", "A", 0.001, 100.0), + InputMeta::num("temperature_rise", "K", 1.0, 100.0), + InputMeta::num("copper_weight", "oz/ft2", 0.25, 6.0), + InputMeta::choice("layer", &["external", "internal"]), + InputMeta::choice("method", &["auto", "ipc2152", "ipc2221"]), + ], + }, + CalculatorMeta { + id: "via_current_resistance", + name: "Via current and resistance", + group: "copper", + summary: "Current a plated via carries for a temperature rise, its DC resistance, and how many vias in parallel reach a target current.", + formula: "A = pi/4 ((drill + 2 plating)^2 - drill^2) [mm^2]; A_mil2 = A / 0.0254^2.\nI = 0.024 dT^0.44 A_mil2^0.725 (IPC-2221 internal-conductor constant, the usual via convention).\nR = RHO_CU length / A. count = ceil(target_current / I).\n", + source: "IPC-2221 formula as for trace_width; via convention (barrel area with internal k) as described in Altium 'PCB via size and pad size guidelines' (sources/standards/via-pad-size-altium.txt). Copper resistivity 1.72e-8 ohm m (CRC Handbook).", + validity: "Plating thickness is what the fab actually deposits (IPC-6012 Class 2 average 20 um, Class 3 25 um); barrel resistance ignores the pad to barrel transition.", + accuracy: "same as IPC-2221; resistance exact for the modelled cylinder", + inputs: &[ + InputMeta::num("drill", "mm", 0.05, 10.0), + InputMeta::num("plating", "um", 5.0, 100.0), + InputMeta::num("length", "mm", 0.1, 10.0), + InputMeta::num("temperature_rise", "K", 1.0, 100.0), + InputMeta::opt("target_current", "A", 0.001, 100.0), + ], + }, + CalculatorMeta { + id: "trace_resistance_drop", + name: "Trace resistance and voltage drop", + group: "copper", + summary: "DC resistance of a copper trace at a temperature, and the voltage drop and heat at a current.", + formula: "t = oz * 34.79e-6 m; R20 = RHO_CU L / (w t); R = R20 (1 + ALPHA_CU (T - 20)); V = I R; P = I^2 R.", + source: "Resistivity and temperature coefficient of copper, CRC Handbook of Chemistry and Physics (1.72e-8 ohm m, 0.00393 /K).", + validity: "DC and low frequency. Above about 1 MHz skin depth (66 um at 1 MHz for copper) makes the effective thickness smaller; a note says so when the user enters a frequency in the future.", + accuracy: "exact for the model; real copper is 2 to 10 % thinner than nominal after etching", + inputs: &[ + InputMeta::num("width", "mm", 0.01, 100.0), + InputMeta::num("copper_weight", "oz/ft2", 0.25, 6.0), + InputMeta::num("length", "mm", 0.1, 10000.0), + InputMeta::num("current", "A", 0.0, 100.0), + InputMeta::num("temperature", "C", -55.0, 200.0), + ], + }, + CalculatorMeta { + id: "microstrip", + name: "Microstrip impedance", + group: "impedance", + summary: "Characteristic impedance and effective permittivity of a surface trace over one plane, or the width for a target impedance.", + formula: "u = w/h, ZF0 = 376.730313668.\nZL1(u) = ZF0/(2 pi) ln( f(u)/u + sqrt(1 + (2/u)^2) ), f(u) = 6 + (2 pi - 6) exp( -(30.666/u)^0.7528 )\neeff(u, er) = (er+1)/2 + (er-1)/2 (1 + 10/u)^(-a b)\na(u) = 1 + ln( (u^4 + (u/52)^2) / (u^4 + 0.432) )/49 + ln( 1 + (u/18.1)^3 )/18.7\nb(er) = 0.564 ((er - 0.9)/(er + 3))^0.053\nthickness (tn = t/h): du1 = tn/pi ln( 1 + 4e/tn tanh^2( sqrt(6.517 u) ) ); dur = du1 (1 + sech( sqrt(er - 1) ))/2; u1 = u + du1; ur = u + dur\nZ0 = ZL1(ur) / sqrt(eeff(ur, er)); eeff_t = eeff(ur, er) (ZL1(u1)/ZL1(ur))^2\ndelay = sqrt(eeff_t) / C0.\nwidth_for_target: bisection of Z0(w) on [0.01, 100] mm, 80 steps (Z0 is monotonic in w).\n", + source: "Qucs technical documentation, microstrip line, https://qucs.sourceforge.net/tech/node75.html (transcription checked in pcbcraft-research/research-283-length-impedance.md); independent implementation scikit-rf MLine (BSD-3) https://scikit-rf.readthedocs.io/en/latest/_modules/skrf/media/mline.html. Original: E. Hammerstad and O. Jensen, 'Accurate models for microstrip computer-aided design', IEEE MTT-S 1980.", + validity: "0.01 <= w/h <= 100, er < 128 (fit range). Quasi-static: no dispersion, fine below a few GHz on FR-4. Solder mask not modelled (lowers Z0 by 1 to 3 ohm).", + accuracy: "Fit error 0.01 % (w/h <= 1) and 0.03 % (w/h <= 1000) for Z0 against the zero-thickness quasi-static solution; eeff within 0.2 %. Fabrication tolerance on h and er dominates (5 to 10 %).", + inputs: &[ + InputMeta::opt("width", "mm", 0.01, 100.0), + InputMeta::num("height", "mm", 0.01, 10.0), + InputMeta::num("er", "", 1.0, 20.0), + InputMeta::num("thickness", "mm", 0.0, 0.5), + InputMeta::opt("target", "ohm", 1.0, 1000.0), + ], + }, + CalculatorMeta { + id: "embedded_microstrip", + name: "Embedded microstrip impedance", + group: "impedance", + summary: "Microstrip whose trace is covered by a dielectric layer (prepreg or thick mask), lowering the impedance.", + formula: "(Z0s, eeff_s) = microstrip(w, h, er, t)\nf = exp(-2 cover / h); eeff_e = eeff_s f + er (1 - f)\nZ0 = Z0s sqrt(eeff_s / eeff_e)\n", + source: "The cover correction appears on calculator pages and in Wadell, 'Transmission Line Design Handbook' (Artech, 1991) ch. 3 as the usual engineering estimate; the IPC-2141 embedded form (paragraph 4.2.3) is paywalled and was criticised as wrong in the source trail (see Altium, 'Clearing trace impedance calculators and formulas', https://resources.altium.com/p/clearing-trace-impedance-calculators-and-formulas).", + validity: "cover <= 2 h. With cover >= 2 h the result approaches a fully buried line (eeff -> er) and a stripline model is better.", + accuracy: "Engineering estimate, about 5 %. The UI labels it 'estimate; confirm with a field solver or the fab's stackup tool'.", + inputs: &[ + InputMeta::num("width", "mm", 0.01, 100.0), + InputMeta::num("height", "mm", 0.01, 10.0), + InputMeta::num("cover", "mm", 0.0, 10.0), + InputMeta::num("er", "", 1.0, 20.0), + InputMeta::num("thickness", "mm", 0.0, 0.5), + ], + }, + CalculatorMeta { + id: "stripline", + name: "Stripline impedance", + group: "impedance", + summary: "Trace centred between two planes (inner layer).", + formula: "W = w/b, T = t/b\nWeff = W - (0.35 - W)^2 / (1 + 12 T) if W < 0.35, else W\nCf = (2/pi) ln(1/(1-T) + 1) - (T/pi) ln(1/(1-T)^2 - 1)\nZ0 = (30 pi / sqrt(er)) (1 - T) / (Weff + Cf)\ndelay = sqrt(er) / C0 (fully embedded: eeff = er)\n", + source: "Wikipedia, 'Stripline', formula section citing M. Steer, Microwave and RF Design (LibreTexts 3.7, 2020); original S. B. Cohn, IRE Trans. MTT-2, 1954. Cross-check: IPC-2141 form Z0 = 60/sqrt(er) ln(4 b / (0.67 pi (0.8 w + t))) as printed by NextPCB, https://www.nextpcb.com/blog/pcb-impedance-calculator-microstrip-stripline-guide (that page's variable definition for h is inconsistent; b plane-to-plane makes its example agree).", + validity: "W/(1-T) > 0.05 and T < 0.025 for the stated accuracy; symmetric only. Offset (asymmetric) stripline is a follow-up.", + accuracy: "At least 1 % against the exact conformal mapping (Steer). The IPC-2141 cross-check agrees within 1.2 % on the three vectors.", + inputs: &[ + InputMeta::num("width", "mm", 0.01, 100.0), + InputMeta::num("spacing", "mm", 0.02, 20.0), + InputMeta::num("er", "", 1.0, 20.0), + InputMeta::num("thickness", "mm", 0.0, 0.5), + ], + }, + CalculatorMeta { + id: "coplanar_waveguide", + name: "Coplanar waveguide impedance", + group: "impedance", + summary: "Trace with ground copper on both sides on the same layer, with or without a plane underneath.", + formula: "K/K'(k): for 0 <= k <= 1/sqrt2: pi / ln( 2 (1 + sqrt(k')) / (1 - sqrt(k')) ), k' = sqrt(1 - k^2);\n for 1/sqrt2 <= k <= 1: ln( 2 (1 + sqrt(k)) / (1 - sqrt(k)) ) / pi.\nk1 = w / (w + 2 s)\nCPW, finite substrate h: k2 = sinh(pi w / 4h) / sinh(pi (w + 2s) / 4h)\n eeff = 1 + (er - 1)/2 * [K/K'(k2)] / [K/K'(k1)]; Z0 = 30 pi / (sqrt(eeff) K/K'(k1))\nGround-backed CPW: k3 = tanh(pi w / 4h) / tanh(pi (w + 2s) / 4h)\n q = K/K'(k3) / (K/K'(k1) + K/K'(k3)); eeff = 1 + q (er - 1); Z0 = 60 pi / (sqrt(eeff) (K/K'(k1) + K/K'(k3)))\nThickness ignored (Qucs eq. 12.14 to 12.18 is the optional refinement).\n", + source: "Qucs technical documentation, coplanar waveguides, https://qucs.sourceforge.net/tech/node86.html, eq. 12.4 to 12.13; scikit-rf CPW media (same equations) https://scikit-rf.readthedocs.io/en/latest/_modules/skrf/media/cpw.html.", + validity: "Quasi-static; ground copper much wider than w + 2s; no thickness. Ground-backed form assumes the side grounds are tied to the plane by vias within a small fraction of a wavelength.", + accuracy: "Hilberg ratio accurate to about 3e-6 (Qucs citing Gupta); formulas 'effectively exact' for the quasi-static zero-thickness case. Thickness and etch factor add a few percent.", + inputs: &[ + InputMeta::num("width", "mm", 0.01, 100.0), + InputMeta::num("gap", "mm", 0.01, 100.0), + InputMeta::num("height", "mm", 0.01, 10.0), + InputMeta::num("er", "", 1.0, 20.0), + InputMeta::choice("ground_backed", &["true", "false"]), + ], + }, + CalculatorMeta { + id: "differential_pair", + name: "Differential pair impedance", + group: "impedance", + summary: "Differential impedance of two equal surface traces side by side, and the gap or width for a target.", + formula: "Zdiff = 2 Z0(w, h, er, t) (1 - 0.48 exp(-0.96 s / h)); width_for_target by bisection with s fixed.", + source: "Coupling factor as printed by NextPCB differential microstrip calculator https://www.nextpcb.com/differential-microstrip-impedance-calculator and many others, attributed to IPC-2141 (paywalled; TOC at https://www.ipc.org/TOC/IPC-2141A.pdf lists 4.4.1 edge-coupled surface microstrip). Not confirmed against the standard text (pcbcraft-research/research-283-length-impedance.md). Upgrade path: Hammerstad-Jensen coupled microstrip even/odd modes, Qucs https://qucs.sourceforge.net/tech/node77.html, odd-mode error under 0.3 %.", + validity: "0.1 <= w/h <= 10, s/h >= 0.1, loosely coupled pairs (s >= w). For s < w the factor underestimates coupling.", + accuracy: "Unverified against the standard; treat as +-10 %. The UI shows the word 'estimate' and the follow-up issue swaps in the coupled H-J model.", + inputs: &[ + InputMeta::num("width", "mm", 0.01, 100.0), + InputMeta::num("gap", "mm", 0.01, 100.0), + InputMeta::num("height", "mm", 0.01, 10.0), + InputMeta::num("er", "", 1.0, 20.0), + InputMeta::num("thickness", "mm", 0.0, 0.5), + InputMeta::opt("target", "ohm", 10.0, 1000.0), + ], + }, + CalculatorMeta { + id: "propagation_delay", + name: "Propagation delay and length matching", + group: "impedance", + summary: "Signal speed on a trace from its effective permittivity, and the copper length a skew budget allows.", + formula: "tpd = sqrt(eeff) / C0; total = tpd L; allowed_mismatch = skew_budget / tpd.", + source: "Johnson and Graham, High-Speed Digital Design (1993), ch. 1 (velocity of propagation); C0 = 299792458 m/s (SI).", + validity: "Quasi-TEM; use the eeff the impedance calculator gave for the same trace.", + accuracy: "exact for the given eeff", + inputs: &[ + InputMeta::num("eeff", "", 1.0, 20.0), + InputMeta::opt("length", "mm", 0.0, 10000.0), + InputMeta::opt("skew_budget", "ps", 0.0, 1000000.0), + ], + }, + CalculatorMeta { + id: "crosstalk", + name: "Crosstalk rule of thumb", + group: "impedance", + summary: "Rough near-end coupling between two parallel surface traces from their edge gap and dielectric height, plus the 3W spacing.", + formula: "coupling = 1 / (1 + (s/h)^2); dB = 20 log10(coupling); 3W gap = 2 w (centre to centre 3 w); s for -20 dB: s = 3 h.", + source: "Johnson and Graham, High-Speed Digital Design (1993), section 5.4 crosstalk estimate (the 1/(1+(D/H)^2) form); 3W rule, Mark Montrose, Printed Circuit Board Design Techniques for EMC Compliance (IEEE Press, 2000).", + validity: "Order of magnitude only; microstrip over one plane; coupled length short against the rise time. Stripline couples less.", + accuracy: "Rule of thumb; typical real values within a factor of 2.", + inputs: &[ + InputMeta::num("gap", "mm", 0.01, 100.0), + InputMeta::num("height", "mm", 0.01, 10.0), + InputMeta::num("width", "mm", 0.01, 100.0), + ], + }, + CalculatorMeta { + id: "conductor_spacing_ipc2221", + name: "Conductor spacing by voltage (IPC-2221)", + group: "spacing", + summary: "Minimum copper to copper spacing for a peak voltage, by board location class B1 to A7.", + formula: "Table lookup (V peak, mm) by column B1 internal | B2 external uncoated to 3050 m | B3 external uncoated above 3050 m | B4 external polymer coated | A5 assembly conformal coated | A6 component lead uncoated | A7 component lead coated:\n <=15: 0.05 0.1 0.1 0.05 0.13 0.13 0.13\n <=30: 0.05 0.1 0.1 0.05 0.13 0.25 0.13\n <=50: 0.1 0.6 0.6 0.13 0.13 0.4 0.13\n <=100: 0.1 0.6 1.5 0.13 0.13 0.5 0.13\n <=150: 0.2 0.6 3.2 0.4 0.4 0.8 0.4\n <=170: 0.2 1.25 3.2 0.4 0.4 0.8 0.4\n <=250: 0.2 1.25 6.4 0.4 0.4 0.8 0.4\n <=300: 0.2 2.5 12.5 0.4 0.4 0.8 0.8\n <=500: 0.25 2.5 12.5 0.8 0.8 1.5 0.8\n >500: per volt 0.0025 0.005 0.025 0.00305 0.00305 0.00305 0.00305 (spacing = V * slope)\n", + source: "Reproductions of IPC-2221B table 6-1: Philip McGaw, 'Creepage and clearance' (sources/standards/ipc2221-spacing-philipmcgaw.txt), SFCircuits PCB School (sources/standards/ipc2221-spacing-sfcircuits.txt), Altium high-voltage calculator page (sources/standards/ipc2221-spacing-altium.txt); the standard is paywalled (IPC-2221C, shop.ipc.org).", + validity: "IPC-2221 is a design standard, not a safety standard; for mains or anything a person can touch use creepage_clearance_iec60664 and the product safety standard. Solder mask does not count as the B4 coating.", + accuracy: "Table values reproduced identically by three secondary sources; the >500 V slopes are the standard's own linear extension.", + inputs: &[ + InputMeta::num("voltage", "V peak", 0.0, 100000.0), + InputMeta::choice("location", &["B1", "B2", "B3", "B4", "A5", "A6", "A7"]), + ], + }, + CalculatorMeta { + id: "creepage_clearance_iec60664", + name: "Creepage and clearance (IEC 60664-1 lookup)", + group: "spacing", + summary: "Minimum clearance through air for the impulse voltage and creepage along the surface for the working voltage, pollution degree and material group.", + formula: "1. Rated impulse voltage (Table F.1), by mains voltage ceiling (V) and overvoltage category I/II/III/IV in kV:\n <=50: 0.33 0.5 0.8 1.5 | <=100: 0.5 0.8 1.5 2.5 | <=150: 0.8 1.5 2.5 4.0 | <=300: 1.5 2.5 4.0 6.0 | <=600: 2.5 4.0 6.0 8.0 | <=1000: 4.0 6.0 8.0 12.0\n2. Clearance (Table F.2, inhomogeneous field, up to 2000 m) by impulse kV -> mm:\n 0.33: 0.01 | 0.5: 0.04 | 0.8: 0.1 | 1.5: 0.5 | 2.5: 1.5 | 4.0: 3.0 | 6.0: 5.5 | 8.0: 8.0 | 12: 14\n pollution degree 2 floor 0.2 mm, degree 3 floor 0.8 mm. Altitude above 2000 m: multiply by the F.8 factor (2000 m 1.00, 3000 m 1.14, 4000 m 1.29, 5000 m 1.48).\n reinforced: use the impulse voltage one step higher in the F.1 ladder.\n3. Creepage (Table F.5) by working voltage ceiling, pollution degree 1 (all groups) | degree 2 group I, II, III | degree 3 group I, II, III in mm:\n 50: 0.18 | 0.6 0.85 1.2 | 1.5 1.7 1.9\n 63: 0.2 | 0.63 0.9 1.25 | 1.6 1.8 2.0\n 80: 0.22 | 0.67 0.95 1.3 | 1.7 1.9 2.1\n 100: 0.25 | 0.71 1.0 1.4 | 1.8 2.0 2.2\n 125: 0.28 | 0.75 1.05 1.5 | 1.9 2.1 2.4\n 160: 0.32 | 0.8 1.1 1.6 | 2.0 2.2 2.5\n 200: 0.42 | 1.0 1.4 2.0 | 2.5 2.8 3.2\n 250: 0.56 | 1.25 1.8 2.5 | 3.2 3.6 4.0\n 320: 0.75 | 1.6 2.2 3.2 | 4.0 4.5 5.0\n 400: 1.0 | 2.0 2.8 4.0 | 5.0 5.6 6.3\n 500: 1.3 | 2.5 3.6 5.0 | 6.3 7.1 8.0\n 630: 1.8 | 3.2 4.5 6.3 | 8.0 9.0 10.0\n 800: 2.4 | 4.0 5.6 8.0 | 10.0 11.0 12.5\n 1000: 3.2 | 5.0 7.1 10.0 | 12.5 14.0 16.0\n reinforced creepage = 2 x basic. Creepage is never less than clearance: result = max(creepage, clearance).\n", + source: "IEC 60664-1:2020 (paywalled, https://webstore.iec.ch/en/publication/59671). Table values from secondary reproductions: PTR Hartmann (sources/standards/creepage-ptr-hartmann.txt), Wurth Elektronik creepage and clearance of connectors PDF, Battery Design creepage calculator, VIOX IEC 60664-1 calculator (sources/standards/creepage-viox-calc.txt), Elektor parts 1 to 3 (sources/standards/creepage-elektor-part*.txt), TI SLUP421 and SLUAAR5 (sources/standards/iec60664-ti-*.pdf). Material group thresholds from IEC 60664-1 clause 4.8.1.3 as quoted by TI SLUAAR5.", + validity: "Low-voltage equipment up to 1000 V RMS, frequency to 30 kHz. Product standards (IEC 62368-1, 60335, 61010, 60601) override these with their own tables. Secondary reproductions: the implementer must verify every row against the standard before the panel drops the 'verify' label.", + accuracy: "Lookup; values are the standard's own. The panel shows 'reproduced from secondary sources, verify against IEC 60664-1' until a licensed copy has been checked.", + inputs: &[ + InputMeta::num("working_voltage", "V RMS", 10.0, 1000.0), + InputMeta::num("mains_voltage", "V RMS", 50.0, 1000.0), + InputMeta::choice("overvoltage_category", &["I", "II", "III", "IV"]), + InputMeta::choice("pollution_degree", &["1", "2", "3"]), + InputMeta::choice("material_group", &["I", "II", "IIIa", "IIIb"]), + InputMeta::choice("insulation", &["functional", "basic", "reinforced"]), + InputMeta::num("altitude", "m", 0.0, 5000.0), + ], + }, + CalculatorMeta { + id: "decoupling_capacitor", + name: "Decoupling capacitor sizing", + group: "components", + summary: "Bulk capacitance for a current step within a ripple budget, and the self-resonant frequency above which a capacitor stops being one.", + formula: "C = I dt / dV; f_srf = 1 / (2 pi sqrt(ESL C)); Ztarget = dV / I.", + source: "Analog Devices MT-101 'Decoupling Techniques' (manifest: https://www.analog.com/media/en/training-seminars/tutorials/MT-101.pdf); the charge-balance form is in any power integrity text (Bogatin, Signal and Power Integrity Simplified, ch. 13).", + validity: "First-order. Below the SRF the part is a capacitor; above it the mounting inductance dominates, so several values in parallel cover a wider band. Place small ones nearest the pin.", + accuracy: "Order of magnitude starting point.", + inputs: &[ + InputMeta::num("current_step", "A", 1e-06, 1000.0), + InputMeta::num("step_time", "s", 1e-12, 1.0), + InputMeta::num("ripple", "V", 0.0001, 10.0), + InputMeta::num("esl", "H", 1e-12, 1e-06), + InputMeta::opt("capacitance", "F", 1e-12, 1.0), + ], + }, + CalculatorMeta { + id: "i2c_pullup", + name: "I2C pull-up resistor", + group: "components", + summary: "Smallest and largest pull-up for an I2C bus from supply, sink current, rise time budget and bus capacitance.", + formula: "Rp_min = (Vcc - VOL_max) / IOL; Rp_max = tr / (0.8473 Cb) (tr measured 30 % to 70 %, 0.8473 = ln(0.7/0.3)).", + source: "Texas Instruments SLVA689, 'I2C Bus Pull-Up Resistor Calculation', equations 1 and 6 (sources/netrules/ti-slva689-i2c-pullup-sizing.txt). Bus limits from the NXP I2C-bus specification UM10204 (public).", + validity: "Open-drain bus; VOL and IOL from the weakest device on the bus.", + accuracy: "exact for the model", + inputs: &[ + InputMeta::num("vcc", "V", 1.0, 6.0), + InputMeta::num("vol_max", "V", 0.0, 1.0), + InputMeta::num("iol", "A", 0.0001, 0.03), + InputMeta::num("rise_time", "s", 1e-09, 1e-05), + InputMeta::num("bus_capacitance", "F", 1e-12, 1e-09), + ], + }, + CalculatorMeta { + id: "crystal_load_capacitors", + name: "Crystal load capacitors", + group: "components", + summary: "The two external capacitors for a Pierce oscillator from the crystal's specified load capacitance and the board stray capacitance.", + formula: "CL = C1 C2 / (C1 + C2) + Cstray. For C1 = C2: C1 = C2 = 2 (CL - Cstray). Check mode returns CL for the fitted pair.", + source: "Microchip AN826, 'Crystal Oscillator Basics and Crystal Selection', load capacitance section (sources/netrules/microchip-an826-crystal-oscillator-basics.txt); Raspberry Pi 'Hardware design with RP2040' crystal section (sources/netrules/rpi-hardware-design-with-rp2040.txt) as a worked example.", + validity: "Pierce oscillator with the crystal between two pins. Cstray is a guess until measured; trim by checking frequency.", + accuracy: "exact for the model; stray guess dominates", + inputs: &[ + InputMeta::num("load_capacitance", "pF", 4.0, 40.0), + InputMeta::num("stray_capacitance", "pF", 0.0, 15.0), + InputMeta::opt("c1", "pF", 1.0, 100.0), + InputMeta::opt("c2", "pF", 1.0, 100.0), + ], + }, + CalculatorMeta { + id: "timer_555", + name: "555 timer", + group: "components", + summary: "Astable frequency and duty cycle, or monostable pulse width, for the classic timer.", + formula: "Astable: t_high = ln2 (R1 + R2) C; t_low = ln2 R2 C; f = 1 / (t_high + t_low); D = (R1 + R2) / (R1 + 2 R2). Monostable: t = ln3 R C (1.0986 R C, often rounded to 1.1 R C).", + source: "Wikipedia, '555 timer IC', design formulas section and worked tables (checked 2026-10-28); any 555 datasheet (TI NE555).", + validity: "Bipolar or CMOS 555 with R1 >= 1 k; duty cycle is always above 50 % in the basic astable.", + accuracy: "exact for the model; the chip's comparator thresholds add a few percent", + inputs: &[ + InputMeta::choice("mode", &["astable", "monostable"]), + InputMeta::num("r1", "ohm", 1000.0, 10000000.0), + InputMeta::opt("r2", "ohm", 1000.0, 10000000.0), + InputMeta::num("c", "F", 1e-12, 0.01), + ], + }, + CalculatorMeta { + id: "opamp_gain", + name: "Op-amp gain", + group: "components", + summary: "Gain of the inverting and non-inverting resistor-feedback amplifiers, in ratio and dB.", + formula: "Inverting: G = -Rf / Rin. Non-inverting: G = 1 + Rf / Rg. dB = 20 log10 |G|.", + source: "Horowitz and Hill, 3rd ed., sections 4.2.1 and 4.2.2.", + validity: "Ideal op-amp, closed-loop gain well below the open-loop gain at the frequency of interest.", + accuracy: "exact for the model", + inputs: &[ + InputMeta::choice("topology", &["inverting", "non_inverting"]), + InputMeta::num("rf", "ohm", 1.0, 1000000000.0), + InputMeta::num("rin", "ohm", 1.0, 1000000000.0), + ], + }, + CalculatorMeta { + id: "ldo_thermal", + name: "LDO dissipation and junction temperature", + group: "components", + summary: "Heat in a linear regulator and its junction temperature from theta-JA.", + formula: "P = (Vin - Vout) Iout + Vin Iq; Tj = Ta + P theta_JA; Imax = (((Tj_max - Ta)/theta_JA) - Vin Iq) / (Vin - Vout).", + source: "Any LDO datasheet thermal section, for example TI TLV1117 or the TI application report SLVA118 'Understanding thermal dissipation and design of a heatsink'; theta-JA definition JEDEC JESD51-2.", + validity: "theta-JA is measured on a JEDEC test board; a real board with less copper runs hotter. Use the datasheet's theta-JA for the package and copper area closest to yours.", + accuracy: "exact for the model; theta-JA uncertainty 20 to 50 %", + inputs: &[ + InputMeta::num("vin", "V", 0.5, 100.0), + InputMeta::num("vout", "V", 0.1, 100.0), + InputMeta::num("iout", "A", 0.0, 20.0), + InputMeta::num("iq", "A", 0.0, 0.1), + InputMeta::num("theta_ja", "K/W", 1.0, 500.0), + InputMeta::num("ambient", "C", -55.0, 125.0), + InputMeta::num("tj_max", "C", 85.0, 175.0), + ], + }, + CalculatorMeta { + id: "battery_life", + name: "Battery life", + group: "components", + summary: "Run time from capacity and a duty-cycled load.", + formula: "Iavg = Ia d + Is (1 - d); hours = capacity * usable_fraction / Iavg.", + source: "Charge balance; derating guidance from any cell datasheet (for example Energizer CR2032 datasheet, Panasonic NCR18650B).", + validity: "Ignores Peukert and the cell's voltage curve; for a regulator between cell and load, use the input current of the regulator.", + accuracy: "+-20 % in practice", + inputs: &[ + InputMeta::num("capacity", "mAh", 1.0, 1000000.0), + InputMeta::num("active_current", "mA", 0.0, 100000.0), + InputMeta::num("sleep_current", "mA", 0.0, 100000.0), + InputMeta::num("active_fraction", "", 0.0, 1.0), + InputMeta::num("usable_fraction", "", 0.1, 1.0), + ], + }, + CalculatorMeta { + id: "wire_gauge", + name: "Wire gauge ampacity", + group: "components", + summary: "Diameter, area, resistance and the usual current limits for an AWG size, or the AWG for a current.", + formula: "d = 0.127 * 92^((36 - n)/39) mm; A = pi d^2 / 4; R/km = RHO_CU / A * 1e9 (A in mm2).\nAmpacity table (A) for 60C/75C/90C insulation, NEC 310.16 single conductors in free air not used; enclosed values:\n 10: 30/35/40 12: 20/25/30 14: 15/20/25 16: 12/16/18 18: 10/14/16 20: 5/11/- 22: 3/7/- 24: 2.1/3.5/- 26: 1.3/2.2/- 28: 0.83/1.4/- 30: 0.52/0.86/-\nawg for current: smallest gauge number whose ampacity at the rating >= current.\n", + source: "Wikipedia, 'American wire gauge' (formula, table rows and NEC-derived ampacity columns; checked 2026-10-28); ampacity ultimately NFPA 70 (NEC) table 310.16.", + validity: "Solid copper at 20 C. Ampacity depends on bundling, ambient and insulation; the NEC columns are for building wire. For PCB wire-to-board use the connector's rating.", + accuracy: "Diameter and area exact from the AWG definition; resistance within 0.3 % of the published table (resistivity rounding).", + inputs: &[ + InputMeta::opt("awg", "", 0.0, 40.0), + InputMeta::opt("current", "A", 0.01, 200.0), + InputMeta::choice("insulation_rating", &["60C", "75C", "90C"]), + ], + }, + CalculatorMeta { + id: "resistor_code", + name: "Resistor colour code and SMD code", + group: "components", + summary: "Decode colour bands (4, 5 or 6) and SMD markings (3-digit, 4-digit, R-notation, EIA-96), or encode a value.", + formula: "Colour digits: black 0 brown 1 red 2 orange 3 yellow 4 green 5 blue 6 violet 7 grey 8 white 9.\nMultiplier: same digit as power of ten; gold 0.1, silver 0.01, pink 0.001.\nTolerance: brown 1 % (F), red 2 % (G), green 0.5 % (D), blue 0.25 % (C), violet 0.1 % (B), grey 0.01 % (L), gold 5 % (J), silver 10 % (K), none 20 % (M).\nTempco (6th band): brown 100, red 50, orange 15, yellow 25, blue 10, violet 5 ppm/K.\n4 bands = 2 digits + multiplier + tolerance; 5 bands = 3 digits + multiplier + tolerance; 6 = 5 + tempco.\nSMD: 3-digit \"ABC\" = AB * 10^C; 4-digit \"ABCD\" = ABC * 10^D; \"R\" marks the decimal point (4R7 = 4.7, R10 = 0.10).\nEIA-96 \"NNL\": NN is the 1-based index into E96 (01 = 1.00 ... 96 = 9.76, three significant digits), L is the multiplier letter:\n Z 0.001, Y or R 0.01, X or S 0.1, A 1, B or H 10, C 100, D 1000, E 10000, F 100000.\n", + source: "Wikipedia, 'Electronic color code' (IEC 60062:2016 table; checked 2026-10-28). EIA-96 letters: xdevs resistor SMD code guide https://xdevs.com/guide/rescode/ and pimylifeup SMD resistor guide https://pimylifeup.com/smd-resistor/ (both agree on Z Y/R X/S A B/H C D E F).", + validity: "Manufacturers deviate; the decoder shows 'check the datasheet' for grey or white multipliers and for codes with unusual letters.", + accuracy: "exact decoding", + inputs: &[ + InputMeta::text("bands", "colour names"), + InputMeta::text("smd_code", "text"), + InputMeta::opt("value", "ohm", 0.001, 1000000000000.0), + ], + }, + CalculatorMeta { + id: "e_series", + name: "E-series nearest value", + group: "components", + summary: "Nearest standard value in E6, E12, E24, E48, E96 or E192, the neighbours either side, and the error.", + formula: "Base values: v_i = round(10^(i/N)) to 2 significant digits for N <= 24, 3 for N >= 48, i = 0..N-1.\nE24 overrides (IEC 60063 keeps the historic values): 2.6->2.7 2.9->3.0 3.2->3.3 3.5->3.6 3.8->3.9 4.2->4.3 4.6->4.7 8.3->8.2.\nE6 and E12 are every 4th and every 2nd E24 value. E192 override: index 185 is 9.20 (formula gives 9.19).\nNearest: minimise |ln(candidate / value)| over the decade's values plus 10 x the first of the next decade.\n", + source: "Wikipedia, 'E series of preferred numbers' (IEC 60063 lists, formula, the eight E24 exceptions and the E192 9.20 exception; checked 2026-10-28).", + validity: "Any unit; the series is dimensionless.", + accuracy: "exact against IEC 60063", + inputs: &[ + InputMeta::num("value", "ohm | F | H", 1e-15, 1000000000000000.0), + InputMeta::choice("series", &["E6", "E12", "E24", "E48", "E96", "E192"]), + ], + }, + CalculatorMeta { + id: "unit_converter", + name: "Unit converter", + group: "utilities", + summary: "mil, mm, inch, micron and copper weight in oz/ft2.", + formula: "1 inch = 25.4 mm exactly; 1 mil = 0.0254 mm; 1 oz/ft2 copper = 34.79 um (fabs round to 35 um; 0.5 oz = 17.4 um, 2 oz = 69.6 um). oz converts only to and from length units as a thickness.", + source: "Inch definition: NIST SP 811. Copper weight: 1 oz over 1 ft2 of copper (density 8.96 g/cm3) is 34.79 um; stated in IPC-4562 and every fab capability page (sources/standards/jlcpcb-pcb-capabilities.txt, eurocircuits-copper-layers.txt).", + validity: "Exact conversions.", + accuracy: "exact", + inputs: &[ + InputMeta::num("value", "", -1000000000.0, 1000000000.0), + InputMeta::choice("from", &["mm", "mil", "inch", "um", "oz"]), + InputMeta::choice("to", &["mm", "mil", "inch", "um", "oz"]), + ], + }, + CalculatorMeta { + id: "thermal_via_count", + name: "Thermal via count", + group: "utilities", + summary: "How many plated vias under a hot pad reach a target thermal resistance to the plane on the other side.", + formula: "A = pi/4 ((drill + 2 plating)^2 - drill^2) (filled: pi/4 (drill + 2 plating)^2)\nRth_via = length / (K_CU A); count = ceil(Rth_via / target_rth); array_hint = ceil(sqrt(count)).\n", + source: "Series thermal resistance of a cylinder, k_copper = 385 W/(m K) (CRC Handbook). Context: TI SLVA959 motor driver layout and SLYT614 buck layout notes on thermal vias (sources/netrules/ti-slva959-*.txt, ti-slyt614-*.txt).", + validity: "Conduction through the barrel only; ignores the FR-4 in parallel (negligible), the spreading resistance in the pad and the plane, and solder wicking. Real packages see 2 to 3 times the ideal count's benefit tail off after about 9 to 16 vias.", + accuracy: "order of magnitude", + inputs: &[ + InputMeta::num("drill", "mm", 0.1, 1.0), + InputMeta::num("plating", "um", 10.0, 50.0), + InputMeta::num("length", "mm", 0.1, 5.0), + InputMeta::num("target_rth", "K/W", 0.1, 100.0), + InputMeta::choice("filled", &["true", "false"]), + ], + }, +]; + +/// Look up a calculator by id. +pub fn calculator(id: &str) -> Option<&'static CalculatorMeta> { + CALCULATORS.iter().find(|c| c.id == id) +} diff --git a/crates/calc/src/spacing.rs b/crates/calc/src/spacing.rs new file mode 100644 index 000000000..a60f4bbd7 --- /dev/null +++ b/crates/calc/src/spacing.rs @@ -0,0 +1,385 @@ +//! Clearance and creepage calculators: `conductor_spacing_ipc2221` +//! (board-level copper to copper spacing) and +//! `creepage_clearance_iec60664` (safety insulation coordination). +//! +//! IPC-2221 is a design standard, not a safety standard; anything a +//! person can touch goes through the IEC 60664-1 lookup instead. Both +//! tables here are reproduced from secondary sources and the metadata +//! carries the verify labels the UI must show. + +use crate::{Error, num}; + +/// Where the conductors sit, IPC-2221B table 6-1 column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SpacingLocation { + /// Internal conductors, hermetically sealed. + B1, + /// External uncoated, up to 3050 m altitude. + #[default] + B2, + /// External uncoated, above 3050 m altitude. + B3, + /// External with polymer coating. + B4, + /// Assembly conformal coated. + A5, + /// Component lead, uncoated. + A6, + /// Component lead, coated. + A7, +} + +/// Rows of IPC-2221B table 6-1: (voltage ceiling V peak, seven columns). +const SPACING_ROWS: [(f64, [f64; 7]); 9] = [ + (15.0, [0.05, 0.1, 0.1, 0.05, 0.13, 0.13, 0.13]), + (30.0, [0.05, 0.1, 0.1, 0.05, 0.13, 0.25, 0.13]), + (50.0, [0.1, 0.6, 0.6, 0.13, 0.13, 0.4, 0.13]), + (100.0, [0.1, 0.6, 1.5, 0.13, 0.13, 0.5, 0.13]), + (150.0, [0.2, 0.6, 3.2, 0.4, 0.4, 0.8, 0.4]), + (170.0, [0.2, 1.25, 3.2, 0.4, 0.4, 0.8, 0.4]), + (250.0, [0.2, 1.25, 6.4, 0.4, 0.4, 0.8, 0.4]), + (300.0, [0.2, 2.5, 12.5, 0.4, 0.4, 0.8, 0.8]), + (500.0, [0.25, 2.5, 12.5, 0.8, 0.8, 1.5, 0.8]), +]; + +/// Above 500 V, millimetres per volt, one entry per column. +const SPACING_SLOPES: [f64; 7] = [0.0025, 0.005, 0.025, 0.00305, 0.00305, 0.00305, 0.00305]; + +/// Column index of a location. +fn column(loc: SpacingLocation) -> usize { + match loc { + SpacingLocation::B1 => 0, + SpacingLocation::B2 => 1, + SpacingLocation::B3 => 2, + SpacingLocation::B4 => 3, + SpacingLocation::A5 => 4, + SpacingLocation::A6 => 5, + SpacingLocation::A7 => 6, + } +} + +/// Input for [`conductor_spacing_ipc2221`]. +#[derive(Debug, Clone, Copy)] +pub struct ConductorSpacing { + /// Peak working voltage, 0 to 100000 V. + pub voltage: f64, + /// Board location class; default B2. + pub location: SpacingLocation, +} + +impl Default for ConductorSpacing { + fn default() -> Self { + ConductorSpacing { + voltage: 50.0, + location: SpacingLocation::B2, + } + } +} + +/// Answer from [`conductor_spacing_ipc2221`]. +#[derive(Debug, Clone, Copy)] +pub struct ConductorSpacingOut { + /// Minimum copper to copper spacing in millimetres. + pub spacing: f64, + /// Table row that applied, for display. + pub row_label: &'static str, + /// Plain-language description of the location class. + pub location_description: &'static str, +} + +/// Minimum IPC-2221B spacing for a peak voltage and location class. +/// +/// # Rules +/// - Pick the first table row whose ceiling is at least the voltage; +/// above 500 V use spacing = voltage times the column's slope. +/// - Table values are the standard's own, reproduced by three sources. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `SPACING_ROWS`, `SPACING_SLOPES`, `column`, `crate::num`. +/// # Do not +/// - Treat this as a safety answer; mains and touchable circuits use +/// [`creepage_clearance_iec60664`]. +pub fn conductor_spacing_ipc2221(a: ConductorSpacing) -> Result { + let v = num("voltage", a.voltage, 0.0, 100_000.0)?; + let col = column(a.location); + let mut spacing = v * SPACING_SLOPES[col]; + let mut row_label = ">500"; + for (ceiling, row) in SPACING_ROWS { + if v <= ceiling { + spacing = row[col]; + row_label = if ceiling <= 15.0 { + "<=15" + } else { + match ceiling as i64 { + 30 => "<=30", + 50 => "<=50", + 100 => "<=100", + 150 => "<=150", + 170 => "<=170", + 250 => "<=250", + 300 => "<=300", + _ => "<=500", + } + }; + break; + } + } + Ok(ConductorSpacingOut { + spacing, + row_label, + location_description: location_description(a.location), + }) +} + +/// Plain-language description of a location class. +fn location_description(loc: SpacingLocation) -> &'static str { + match loc { + SpacingLocation::B1 => "internal conductors, hermetically sealed", + SpacingLocation::B2 => "external uncoated, up to 3050 m", + SpacingLocation::B3 => "external uncoated, above 3050 m", + SpacingLocation::B4 => "external, polymer coated", + SpacingLocation::A5 => "assembly, conformal coated", + SpacingLocation::A6 => "component lead, uncoated", + SpacingLocation::A7 => "component lead, coated", + } +} + +/// Overvoltage (installation) category, IEC 60664-1 table F.1 column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OvervoltageCategory { + /// Equipment not connected to the mains. + I, + /// Ordinary appliances. + #[default] + II, + /// Fixed distribution equipment. + III, + /// Equipment at the service entrance. + IV, +} + +/// Pollution degree of the micro-environment, table F.4 / F.5 selector. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum PollutionDegree { + /// No conductive dust (sealed). + D1, + /// Non-conductive dust, occasional condensation. + #[default] + D2, + /// Conductive dust or frequent condensation. + D3, +} + +/// Insulating material group by CTI, table F.5 column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum MaterialGroup { + /// CTI 600 and above. + G1, + /// CTI 400 to 599. + G2, + /// CTI 175 to 399. + #[default] + G3A, + /// CTI 100 to 174. + G3B, +} + +/// Kind of insulation to size. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Insulation { + /// Circuits with no protection against shock. + Functional, + /// Basic protection. + #[default] + Basic, + /// Double or reinforced protection. + Reinforced, +} + +/// Table F.1: (mains voltage ceiling V RMS, impulse kV for OVC I..IV). +const IMPULSE_ROWS: [(f64, [f64; 4]); 6] = [ + (50.0, [0.33, 0.5, 0.8, 1.5]), + (100.0, [0.5, 0.8, 1.5, 2.5]), + (150.0, [0.8, 1.5, 2.5, 4.0]), + (300.0, [1.5, 2.5, 4.0, 6.0]), + (600.0, [2.5, 4.0, 6.0, 8.0]), + (1000.0, [4.0, 6.0, 8.0, 12.0]), +]; + +/// The F.1 impulse ladder, used to step reinforced insulation up. +const IMPULSE_LADDER: [f64; 9] = [0.33, 0.5, 0.8, 1.5, 2.5, 4.0, 6.0, 8.0, 12.0]; + +/// Table F.2: clearance mm (inhomogeneous field, to 2000 m) per impulse kV. +const CLEARANCE_TABLE: [(f64, f64); 9] = [ + (0.33, 0.01), + (0.5, 0.04), + (0.8, 0.1), + (1.5, 0.5), + (2.5, 1.5), + (4.0, 3.0), + (6.0, 5.5), + (8.0, 8.0), + (12.0, 14.0), +]; + +/// Table F.8 altitude factors applied above 2000 m. +fn altitude_factor(altitude_m: f64) -> f64 { + if altitude_m > 4000.0 { + 1.48 + } else if altitude_m > 3000.0 { + 1.29 + } else if altitude_m > 2000.0 { + 1.14 + } else { + 1.0 + } +} + +/// Table F.5: (working voltage ceiling, d1, d2 I II III, d3 I II III) mm. +const CREEPAGE_ROWS: [(f64, [f64; 7]); 14] = [ + (50.0, [0.18, 0.6, 0.85, 1.2, 1.5, 1.7, 1.9]), + (63.0, [0.2, 0.63, 0.9, 1.25, 1.6, 1.8, 2.0]), + (80.0, [0.22, 0.67, 0.95, 1.3, 1.7, 1.9, 2.1]), + (100.0, [0.25, 0.71, 1.0, 1.4, 1.8, 2.0, 2.2]), + (125.0, [0.28, 0.75, 1.05, 1.5, 1.9, 2.1, 2.4]), + (160.0, [0.32, 0.8, 1.1, 1.6, 2.0, 2.2, 2.5]), + (200.0, [0.42, 1.0, 1.4, 2.0, 2.5, 2.8, 3.2]), + (250.0, [0.56, 1.25, 1.8, 2.5, 3.2, 3.6, 4.0]), + (320.0, [0.75, 1.6, 2.2, 3.2, 4.0, 4.5, 5.0]), + (400.0, [1.0, 2.0, 2.8, 4.0, 5.0, 5.6, 6.3]), + (500.0, [1.3, 2.5, 3.6, 5.0, 6.3, 7.1, 8.0]), + (630.0, [1.8, 3.2, 4.5, 6.3, 8.0, 9.0, 10.0]), + (800.0, [2.4, 4.0, 5.6, 8.0, 10.0, 11.0, 12.5]), + (1000.0, [3.2, 5.0, 7.1, 10.0, 12.5, 14.0, 16.0]), +]; + +/// Creepage column index for a pollution degree and material group. +fn creepage_column(pollution: PollutionDegree, group: MaterialGroup) -> usize { + match pollution { + PollutionDegree::D1 => 0, + PollutionDegree::D2 => match group { + MaterialGroup::G1 => 1, + MaterialGroup::G2 => 2, + _ => 3, + }, + PollutionDegree::D3 => match group { + MaterialGroup::G1 => 4, + MaterialGroup::G2 => 5, + _ => 6, + }, + } +} + +/// Input for [`creepage_clearance_iec60664`]. +#[derive(Debug, Clone, Copy)] +pub struct CreepageClearance { + /// Working voltage RMS, 10 to 1000 V. + pub working_voltage: f64, + /// Nominal mains voltage line to neutral RMS, 50 to 1000 V. + pub mains_voltage: f64, + /// Overvoltage category; default II. + pub overvoltage_category: OvervoltageCategory, + /// Pollution degree; default 2. + pub pollution_degree: PollutionDegree, + /// Material group from CTI; default IIIa. + pub material_group: MaterialGroup, + /// Insulation kind; default basic. + pub insulation: Insulation, + /// Altitude in metres, 0 to 5000; default 2000. + pub altitude: f64, +} + +impl Default for CreepageClearance { + fn default() -> Self { + CreepageClearance { + working_voltage: 230.0, + mains_voltage: 230.0, + overvoltage_category: OvervoltageCategory::II, + pollution_degree: PollutionDegree::D2, + material_group: MaterialGroup::G3A, + insulation: Insulation::Basic, + altitude: 2000.0, + } + } +} + +/// Answer from [`creepage_clearance_iec60664`]. +#[derive(Debug, Clone, Copy)] +pub struct CreepageClearanceOut { + /// Rated impulse voltage in kilovolts. + pub impulse_voltage: f64, + /// Minimum clearance through air in millimetres. + pub clearance: f64, + /// Minimum creepage along the surface in millimetres. + pub creepage: f64, +} + +/// IEC 60664-1 clearance and creepage lookup for low-voltage designs. +/// +/// # Rules +/// - Impulse voltage comes from the mains ceiling and category; the +/// reinforced case takes the next step up the F.1 ladder. +/// - Clearance = F.2 value, raised to the pollution floor (0.2 mm +/// degree 2, 0.8 mm degree 3) and scaled by the F.8 altitude factor. +/// - Final creepage is max(table creepage, reinforced doubling, +/// clearance); creepage is never below clearance. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `IMPULSE_ROWS`, `CLEARANCE_TABLE`, `CREEPAGE_ROWS`, +/// `altitude_factor`, `creepage_column`, `crate::num`. +/// # Do not +/// - Use for anything a product safety standard (IEC 62368-1 class of +/// protection) governs without checking that standard's tables. +pub fn creepage_clearance_iec60664(a: CreepageClearance) -> Result { + let vw = num("working_voltage", a.working_voltage, 10.0, 1000.0)?; + let vm = num("mains_voltage", a.mains_voltage, 50.0, 1000.0)?; + let alt = num("altitude", a.altitude, 0.0, 5000.0)?; + let cat = match a.overvoltage_category { + OvervoltageCategory::I => 0, + OvervoltageCategory::II => 1, + OvervoltageCategory::III => 2, + OvervoltageCategory::IV => 3, + }; + let mut impulse = IMPULSE_ROWS[IMPULSE_ROWS.len() - 1].1[cat]; + for (ceiling, row) in IMPULSE_ROWS { + if vm <= ceiling { + impulse = row[cat]; + break; + } + } + if a.insulation == Insulation::Reinforced { + for step in IMPULSE_LADDER { + if step > impulse + 1e-12 { + impulse = step; + break; + } + } + } + let mut clearance = CLEARANCE_TABLE[CLEARANCE_TABLE.len() - 1].1; + for (kv, mm) in CLEARANCE_TABLE { + if (kv - impulse).abs() < 1e-12 { + clearance = mm; + break; + } + } + clearance = match a.pollution_degree { + PollutionDegree::D1 => clearance, + PollutionDegree::D2 => clearance.max(0.2), + PollutionDegree::D3 => clearance.max(0.8), + }; + clearance *= altitude_factor(alt); + let col = creepage_column(a.pollution_degree, a.material_group); + let mut creepage = CREEPAGE_ROWS[CREEPAGE_ROWS.len() - 1].1[col]; + for (ceiling, row) in CREEPAGE_ROWS { + if vw <= ceiling { + creepage = row[col]; + break; + } + } + if a.insulation == Insulation::Reinforced { + creepage *= 2.0; + } + Ok(CreepageClearanceOut { + impulse_voltage: impulse, + clearance, + creepage: creepage.max(clearance), + }) +} diff --git a/crates/calc/src/utilities.rs b/crates/calc/src/utilities.rs new file mode 100644 index 000000000..33807ad15 --- /dev/null +++ b/crates/calc/src/utilities.rs @@ -0,0 +1,179 @@ +//! Utility calculators: the unit converter (length plus copper weight +//! as a thickness) and the thermal via count estimate. +//! +//! Conversions here are exact by definition; the thermal model is an +//! order-of-magnitude conduction estimate and its metadata says so. + +use crate::consts::{K_CU, MIL_MM, OZ_UM}; +use crate::{Error, finite, num}; + +/// Length or copper-weight unit for [`unit_converter`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum LengthUnit { + /// Millimetre. + #[default] + Mm, + /// Thousandth of an inch. + Mil, + /// Inch. + Inch, + /// Micrometre. + Um, + /// Copper weight, ounces per square foot, as a thickness. + Oz, +} + +impl LengthUnit { + /// Parse a unit name; None for anything else. + pub fn parse(name: &str) -> Option { + match name { + "mm" => Some(LengthUnit::Mm), + "mil" => Some(LengthUnit::Mil), + "inch" => Some(LengthUnit::Inch), + "um" => Some(LengthUnit::Um), + "oz" => Some(LengthUnit::Oz), + _ => None, + } + } + + /// Canonical name. + pub fn name(self) -> &'static str { + match self { + LengthUnit::Mm => "mm", + LengthUnit::Mil => "mil", + LengthUnit::Inch => "inch", + LengthUnit::Um => "um", + LengthUnit::Oz => "oz", + } + } + + /// Millimetres per unit; 1 oz of copper is 34.79 um thick. + fn to_mm(self) -> f64 { + match self { + LengthUnit::Mm => 1.0, + LengthUnit::Mil => MIL_MM, + LengthUnit::Inch => 25.4, + LengthUnit::Um => 0.001, + LengthUnit::Oz => OZ_UM * 0.001, + } + } +} + +/// Input for [`unit_converter`]. +#[derive(Debug, Clone, Copy)] +pub struct UnitConvert { + /// Value to convert, -1e9 to 1e9. + pub value: f64, + /// Unit it is given in. + pub from: LengthUnit, + /// Unit to produce. + pub to: LengthUnit, +} + +impl Default for UnitConvert { + fn default() -> Self { + UnitConvert { + value: 1.0, + from: LengthUnit::Mil, + to: LengthUnit::Mm, + } + } +} + +/// Answer from [`unit_converter`]. +#[derive(Debug, Clone, Copy)] +pub struct UnitConvertOut { + /// The converted value in the requested unit. + pub value: f64, +} + +/// Exact conversion between mil, mm, inch, um and oz/ft2 copper. +/// +/// # Rules +/// - Go through millimetres; oz is accepted as a copper thickness +/// (1 oz = 34.79 um) and converts only to and from length units. +/// - Same-unit input returns the value unchanged. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (MIL_MM, OZ_UM), `LengthUnit::to_mm`. +/// # Do not +/// - Convert oz to a mass or a sheet area; this table only knows the +/// equivalent copper thickness. +pub fn unit_converter(a: UnitConvert) -> Result { + let v = num("value", a.value, -1.0e9, 1.0e9)?; + if a.from == a.to { + return Ok(UnitConvertOut { value: v }); + } + Ok(UnitConvertOut { + value: finite("value", v * a.from.to_mm() / a.to.to_mm())?, + }) +} + +/// Input for [`thermal_via_count`]. +#[derive(Debug, Clone, Copy)] +pub struct ThermalVias { + /// Via drill diameter, 0.1 to 1.0 mm. + pub drill: f64, + /// Barrel plating thickness, 10 to 50 um; default 25. + pub plating: f64, + /// Via length (board thickness), 0.1 to 5.0 mm; default 1.6. + pub length: f64, + /// Target thermal resistance, 0.1 to 100 K/W. + pub target_rth: f64, + /// Filled barrel: count the full drill area, not the annulus. + pub filled: bool, +} + +impl Default for ThermalVias { + fn default() -> Self { + ThermalVias { + drill: 0.3, + plating: 25.0, + length: 1.6, + target_rth: 5.0, + filled: false, + } + } +} + +/// Answer from [`thermal_via_count`]. +#[derive(Debug, Clone, Copy)] +pub struct ThermalViasOut { + /// Conduction resistance of one via in K/W. + pub rth_one_via: f64, + /// Vias needed in parallel to reach the target. + pub count: i64, + /// Side of the square array that holds the count. + pub array_hint: i64, +} + +/// How many plated vias under a pad reach a target thermal resistance. +/// +/// # Rules +/// - Copper area A is the barrel annulus, or the full outer circle +/// when filled; Rth = length / (K_CU A), count = ceil(Rth / target), +/// array hint = ceil(sqrt(count)). +/// - Order of magnitude; spreading resistance is ignored. +/// # Dependencies +/// - `crates/calc/src/lib.rs` for `crate::consts` (K_CU), `crate::num`, `crate::finite`. +/// # Do not +/// - Stack more than about 16 vias expecting linear gains; the pad +/// spreading resistance flattens the curve. +pub fn thermal_via_count(a: ThermalVias) -> Result { + let d = num("drill", a.drill, 0.1, 1.0)?; + let p = num("plating", a.plating, 10.0, 50.0)?; + let l = num("length", a.length, 0.1, 5.0)?; + let target = num("target_rth", a.target_rth, 0.1, 100.0)?; + let outer = d + 2.0 * p * 0.001; + let area_mm2 = if a.filled { + std::f64::consts::FRAC_PI_4 * outer * outer + } else { + std::f64::consts::FRAC_PI_4 * (outer * outer - d * d) + }; + let rth = finite("rth_one_via", (l / 1000.0) / (K_CU * area_mm2 * 1.0e-6))?; + let count = (rth / target).ceil() as i64; + Ok(ThermalViasOut { + rth_one_via: rth, + count, + array_hint: (count.max(1) as f64).sqrt().ceil() as i64, + }) +} diff --git a/crates/calc/tests/golden.rs b/crates/calc/tests/golden.rs new file mode 100644 index 000000000..0695062c6 --- /dev/null +++ b/crates/calc/tests/golden.rs @@ -0,0 +1,859 @@ +//! Replays every golden vector in `data/calculators.toml` through the +//! calculators and cross-checks `meta::CALCULATORS` against the data +//! file. Tolerances come from the vectors themselves; a tolerance of +//! 0 means the expected value must match exactly. +use pcbcraft_calc::basic; +use pcbcraft_calc::components; +use pcbcraft_calc::copper; +use pcbcraft_calc::impedance; +use pcbcraft_calc::meta; +use pcbcraft_calc::spacing; +use pcbcraft_calc::utilities; +use serde::Deserialize; +use toml::Table; +use toml::Value; + +#[derive(Deserialize)] +struct Doc { + calculator: Vec, +} + +#[derive(Deserialize)] +struct Calc { + id: String, + name: String, + group: String, + summary: String, + formula: String, + source: String, + validity: String, + accuracy: String, + inputs: Vec, + #[serde(default)] + vector: Vec, +} + +#[derive(Deserialize)] +struct InputDef { + name: String, + #[serde(default)] + unit: String, + #[serde(default)] + range: Option<[f64; 2]>, + #[serde(default)] + optional: bool, + #[serde(default)] + values: Option>, +} + +#[derive(Deserialize)] +struct Vector { + inputs: Table, + expect: Table, + #[serde(default)] + tolerance: Option, +} + +fn doc() -> Result { + let text = include_str!("../data/calculators.toml"); + toml::from_str(text).map_err(|e| format!("data/calculators.toml: {e}")) +} + +fn num_of(v: &Value) -> Option { + match v { + Value::Float(x) => Some(*x), + Value::Integer(x) => Some(*x as f64), + _ => None, + } +} + +fn need(inputs: &Table, key: &str) -> Result { + inputs + .get(key) + .and_then(num_of) + .ok_or_else(|| format!("{key}: missing or not a number")) +} + +/// Required numeric input with the default the data file declares. +fn need_or(inputs: &Table, key: &str, default: f64) -> Result { + match inputs.get(key) { + None => Ok(default), + Some(_) => need(inputs, key), + } +} + +fn maybe(inputs: &Table, key: &str) -> Result, String> { + match inputs.get(key) { + None => Ok(None), + Some(v) => num_of(v) + .map(Some) + .ok_or_else(|| format!("{key}: not a number")), + } +} + +fn need_i64(inputs: &Table, key: &str) -> Result { + match inputs.get(key) { + Some(Value::Integer(i)) => Ok(*i), + Some(Value::Float(x)) if x.fract() == 0.0 => Ok(*x as i64), + _ => Err(format!("{key}: missing or not an integer")), + } +} + +fn maybe_i64(inputs: &Table, key: &str) -> Result, String> { + if inputs.contains_key(key) { + need_i64(inputs, key).map(Some) + } else { + Ok(None) + } +} + +fn flag(inputs: &Table, key: &str) -> Result { + match inputs.get(key) { + None => Ok(false), + Some(Value::Boolean(b)) => Ok(*b), + _ => Err(format!("{key}: not a boolean")), + } +} + +fn text(inputs: &Table, key: &str) -> Result { + match inputs.get(key) { + Some(Value::String(s)) => Ok(s.clone()), + _ => Err(format!("{key}: missing or not text")), + } +} + +/// Required text input with the default the data file declares. +fn text_or(inputs: &Table, key: &str, default: &str) -> Result { + match inputs.get(key) { + None => Ok(default.to_string()), + Some(_) => text(inputs, key), + } +} + +fn maybe_text(inputs: &Table, key: &str) -> Result, String> { + match inputs.get(key) { + None => Ok(None), + Some(Value::String(s)) => Ok(Some(s.clone())), + _ => Err(format!("{key}: not text")), + } +} + +fn list(inputs: &Table, key: &str) -> Result, String> { + match inputs.get(key) { + Some(Value::Array(a)) => a + .iter() + .map(num_of) + .collect::>>() + .ok_or_else(|| format!("{key}: array has a non-numeric entry")), + _ => Err(format!("{key}: missing or not an array")), + } +} + +fn close(name: &str, got: f64, want: f64, tol: f64) -> Result<(), String> { + let margin = tol.max(1e-4 * want.abs()); + if got.is_finite() && (got - want).abs() <= margin { + Ok(()) + } else { + Err(format!( + "{name}: got {got}, expected {want} (margin {margin})" + )) + } +} + +fn ck(expect: &Table, name: &str, got: f64, tol: f64) -> Result<(), String> { + match expect.get(name).and_then(num_of) { + Some(want) => close(name, got, want, tol), + None => Ok(()), + } +} + +fn ck_opt(expect: &Table, name: &str, got: Option, tol: f64) -> Result<(), String> { + match expect.get(name) { + None => Ok(()), + Some(w) => { + let want = num_of(w).ok_or_else(|| format!("{name}: expectation not a number"))?; + let got = got.ok_or_else(|| format!("{name}: calculator produced no value"))?; + close(name, got, want, tol) + } + } +} + +fn ck_i64(expect: &Table, name: &str, got: i64) -> Result<(), String> { + match expect.get(name).and_then(num_of) { + Some(want) => close(name, got as f64, want, 0.0), + None => Ok(()), + } +} + +fn parse_component_kind(inputs: &Table) -> Result { + match text(inputs, "kind")?.as_str() { + "resistor" => Ok(basic::ComponentKind::Resistor), + "capacitor" => Ok(basic::ComponentKind::Capacitor), + "inductor" => Ok(basic::ComponentKind::Inductor), + other => Err(format!("kind: unknown {other}")), + } +} + +fn parse_rc_rl_kind(inputs: &Table) -> Result { + match text(inputs, "kind")?.as_str() { + "rc" => Ok(basic::RcRlKind::Rc), + "rl" => Ok(basic::RcRlKind::Rl), + other => Err(format!("kind: unknown {other}")), + } +} + +fn parse_decibel_mode(inputs: &Table) -> Result { + match text(inputs, "mode")?.as_str() { + "power_ratio" => Ok(basic::DecibelMode::PowerRatio), + "voltage_ratio" => Ok(basic::DecibelMode::VoltageRatio), + "dbm_to_w" => Ok(basic::DecibelMode::DbmToW), + "w_to_dbm" => Ok(basic::DecibelMode::WToDbm), + other => Err(format!("mode: unknown {other}")), + } +} + +fn parse_layer(inputs: &Table) -> Result { + match text(inputs, "layer")?.as_str() { + "external" => Ok(copper::CopperLayer::External), + "internal" => Ok(copper::CopperLayer::Internal), + other => Err(format!("layer: unknown {other}")), + } +} + +fn parse_method(inputs: &Table) -> Result { + match text(inputs, "method")?.as_str() { + "auto" => Ok(copper::TraceMethod::Auto), + "ipc2152" => Ok(copper::TraceMethod::Ipc2152), + "ipc2221" => Ok(copper::TraceMethod::Ipc2221), + other => Err(format!("method: unknown {other}")), + } +} + +fn parse_location(inputs: &Table) -> Result { + match text(inputs, "location")?.as_str() { + "B1" => Ok(spacing::SpacingLocation::B1), + "B2" => Ok(spacing::SpacingLocation::B2), + "B3" => Ok(spacing::SpacingLocation::B3), + "B4" => Ok(spacing::SpacingLocation::B4), + "A5" => Ok(spacing::SpacingLocation::A5), + "A6" => Ok(spacing::SpacingLocation::A6), + "A7" => Ok(spacing::SpacingLocation::A7), + other => Err(format!("location: unknown {other}")), + } +} + +fn parse_ovc(inputs: &Table) -> Result { + match text(inputs, "overvoltage_category")?.as_str() { + "I" => Ok(spacing::OvervoltageCategory::I), + "II" => Ok(spacing::OvervoltageCategory::II), + "III" => Ok(spacing::OvervoltageCategory::III), + "IV" => Ok(spacing::OvervoltageCategory::IV), + other => Err(format!("overvoltage_category: unknown {other}")), + } +} + +fn parse_pollution(inputs: &Table) -> Result { + match text(inputs, "pollution_degree")?.as_str() { + "1" => Ok(spacing::PollutionDegree::D1), + "2" => Ok(spacing::PollutionDegree::D2), + "3" => Ok(spacing::PollutionDegree::D3), + other => Err(format!("pollution_degree: unknown {other}")), + } +} + +fn parse_material(inputs: &Table) -> Result { + match text(inputs, "material_group")?.as_str() { + "I" => Ok(spacing::MaterialGroup::G1), + "II" => Ok(spacing::MaterialGroup::G2), + "IIIa" => Ok(spacing::MaterialGroup::G3A), + "IIIb" => Ok(spacing::MaterialGroup::G3B), + other => Err(format!("material_group: unknown {other}")), + } +} + +fn parse_insulation(inputs: &Table) -> Result { + match text(inputs, "insulation")?.as_str() { + "functional" => Ok(spacing::Insulation::Functional), + "basic" => Ok(spacing::Insulation::Basic), + "reinforced" => Ok(spacing::Insulation::Reinforced), + other => Err(format!("insulation: unknown {other}")), + } +} + +fn parse_timer_mode(inputs: &Table) -> Result { + match text(inputs, "mode")?.as_str() { + "astable" => Ok(components::Timer555Mode::Astable), + "monostable" => Ok(components::Timer555Mode::Monostable), + other => Err(format!("mode: unknown {other}")), + } +} + +fn parse_topology(inputs: &Table) -> Result { + match text(inputs, "topology")?.as_str() { + "inverting" => Ok(components::OpampTopology::Inverting), + "non_inverting" => Ok(components::OpampTopology::NonInverting), + other => Err(format!("topology: unknown {other}")), + } +} + +fn parse_rating(inputs: &Table) -> Result { + match text_or(inputs, "insulation_rating", "75C")?.as_str() { + "60C" => Ok(components::InsulationRating::C60), + "75C" => Ok(components::InsulationRating::C75), + "90C" => Ok(components::InsulationRating::C90), + other => Err(format!("insulation_rating: unknown {other}")), + } +} + +fn check_one(id: &str, i: &Table, e: &Table, t: f64) -> Result<(), String> { + match id { + "ohms_law" => { + let out = basic::ohms_law(basic::OhmsLaw { + voltage: maybe(i, "voltage")?, + current: maybe(i, "current")?, + resistance: maybe(i, "resistance")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "voltage", out.voltage, t)?; + ck(e, "current", out.current, t)?; + ck(e, "resistance", out.resistance, t)?; + ck(e, "power", out.power, t) + } + "series_parallel" => { + let out = basic::series_parallel(basic::SeriesParallel { + kind: parse_component_kind(i)?, + values: list(i, "values")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "series", out.series, t)?; + ck(e, "parallel", out.parallel, t) + } + "voltage_divider" => { + let out = basic::voltage_divider(basic::VoltageDivider { + vin: need(i, "vin")?, + r1: need(i, "r1")?, + r2: need(i, "r2")?, + load: maybe(i, "load")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "vout", out.vout, t)?; + ck(e, "current", out.current, t) + } + "led_resistor" => { + let out = basic::led_resistor(basic::LedResistor { + supply: need(i, "supply")?, + forward_voltage: need(i, "forward_voltage")?, + current: need(i, "current")?, + series: basic::ESeries::E24, + }) + .map_err(|err| err.to_string())?; + ck(e, "resistance", out.resistance, t)?; + ck(e, "power", out.power, t)?; + ck(e, "nearest_standard", out.nearest_standard, t) + } + "rc_rl_time_constant" => { + let out = basic::rc_rl_time_constant(basic::RcRl { + kind: parse_rc_rl_kind(i)?, + resistance: need(i, "resistance")?, + capacitance: maybe(i, "capacitance")?, + inductance: maybe(i, "inductance")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "tau", out.tau, t)?; + ck(e, "cutoff", out.cutoff, t) + } + "lc_resonance" => { + let out = basic::lc_resonance(basic::LcResonance { + inductance: maybe(i, "inductance")?, + capacitance: maybe(i, "capacitance")?, + frequency: maybe(i, "frequency")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "frequency", out.frequency, t) + } + "reactance" => { + let out = basic::reactance(basic::Reactance { + frequency: need(i, "frequency")?, + capacitance: maybe(i, "capacitance")?, + inductance: maybe(i, "inductance")?, + }) + .map_err(|err| err.to_string())?; + ck_opt(e, "xc", out.xc, t)?; + ck_opt(e, "xl", out.xl, t) + } + "decibel" => { + let out = basic::decibel(basic::Decibel { + mode: parse_decibel_mode(i)?, + value: need(i, "value")?, + }) + .map_err(|err| err.to_string())?; + ck_opt(e, "db", out.db, t)?; + ck_opt(e, "dbm", out.dbm, t)?; + ck_opt(e, "watts", out.watts, t) + } + "trace_width" => { + let out = copper::trace_width(copper::TraceWidth { + current: need(i, "current")?, + temperature_rise: need(i, "temperature_rise")?, + copper_weight: need(i, "copper_weight")?, + layer: parse_layer(i)?, + method: parse_method(i)?, + }) + .map_err(|err| err.to_string())?; + ck(e, "width_mm", out.width_mm, t)?; + ck(e, "width_mil", out.width_mil, t)?; + ck(e, "cross_section", out.cross_section, t) + } + "via_current_resistance" => { + let out = copper::via_current_resistance(copper::ViaCurrent { + drill: need(i, "drill")?, + plating: need(i, "plating")?, + length: need(i, "length")?, + temperature_rise: need(i, "temperature_rise")?, + target_current: maybe(i, "target_current")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "barrel_area", out.barrel_area, t)?; + ck(e, "current", out.current, t)?; + ck(e, "resistance", out.resistance, t)?; + ck_opt(e, "count", out.count, t) + } + "trace_resistance_drop" => { + let out = copper::trace_resistance_drop(copper::TraceResistance { + width: need(i, "width")?, + copper_weight: need(i, "copper_weight")?, + length: need(i, "length")?, + current: need(i, "current")?, + temperature: need(i, "temperature")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "resistance", out.resistance, t)?; + ck(e, "voltage_drop", out.voltage_drop, t)?; + ck(e, "power", out.power, t) + } + "microstrip" => { + let out = impedance::microstrip(impedance::Microstrip { + width: maybe(i, "width")?, + height: need(i, "height")?, + er: need(i, "er")?, + thickness: need(i, "thickness")?, + target: maybe(i, "target")?, + }) + .map_err(|err| err.to_string())?; + ck_opt(e, "z0", out.z0, t)?; + ck_opt(e, "eeff", out.eeff, t)?; + ck_opt(e, "delay", out.delay, t)?; + ck_opt(e, "width_for_target", out.width_for_target, t) + } + "embedded_microstrip" => { + let out = impedance::embedded_microstrip(impedance::EmbeddedMicrostrip { + width: need(i, "width")?, + height: need(i, "height")?, + cover: need(i, "cover")?, + er: need(i, "er")?, + thickness: need(i, "thickness")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "z0", out.z0, t)?; + ck(e, "eeff", out.eeff, t) + } + "stripline" => { + let out = impedance::stripline(impedance::Stripline { + width: need(i, "width")?, + spacing: need(i, "spacing")?, + er: need(i, "er")?, + thickness: need(i, "thickness")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "z0", out.z0, t) + } + "coplanar_waveguide" => { + let out = impedance::coplanar_waveguide(impedance::CoplanarWaveguide { + width: need(i, "width")?, + gap: need(i, "gap")?, + height: need(i, "height")?, + er: need(i, "er")?, + ground_backed: flag(i, "ground_backed")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "z0", out.z0, t)?; + ck(e, "eeff", out.eeff, t) + } + "differential_pair" => { + let out = impedance::differential_pair(impedance::DifferentialPair { + width: need(i, "width")?, + gap: need(i, "gap")?, + height: need(i, "height")?, + er: need(i, "er")?, + thickness: need(i, "thickness")?, + target: maybe(i, "target")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "zdiff", out.zdiff, t)?; + ck(e, "z0_single", out.z0_single, t) + } + "propagation_delay" => { + let out = impedance::propagation_delay(impedance::PropagationDelay { + eeff: need(i, "eeff")?, + length: maybe(i, "length")?, + skew_budget: maybe(i, "skew_budget")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "delay", out.delay, t)?; + ck(e, "delay_inch", out.delay_inch, t)?; + ck_opt(e, "total_delay", out.total_delay, t)?; + ck_opt(e, "allowed_mismatch", out.allowed_mismatch, t) + } + "crosstalk" => { + let out = impedance::crosstalk(impedance::Crosstalk { + gap: need(i, "gap")?, + height: need(i, "height")?, + width: need(i, "width")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "coupling", out.coupling, t)?; + ck(e, "coupling_db", out.coupling_db, t)?; + ck(e, "three_w_gap", out.three_w_gap, t) + } + "conductor_spacing_ipc2221" => { + let out = spacing::conductor_spacing_ipc2221(spacing::ConductorSpacing { + voltage: need(i, "voltage")?, + location: parse_location(i)?, + }) + .map_err(|err| err.to_string())?; + ck(e, "spacing", out.spacing, t) + } + "creepage_clearance_iec60664" => { + let out = spacing::creepage_clearance_iec60664(spacing::CreepageClearance { + working_voltage: need(i, "working_voltage")?, + mains_voltage: need(i, "mains_voltage")?, + overvoltage_category: parse_ovc(i)?, + pollution_degree: parse_pollution(i)?, + material_group: parse_material(i)?, + insulation: parse_insulation(i)?, + altitude: 0.0, + }) + .map_err(|err| err.to_string())?; + ck(e, "impulse_voltage", out.impulse_voltage, t)?; + ck(e, "clearance", out.clearance, t)?; + ck(e, "creepage", out.creepage, t) + } + "decoupling_capacitor" => { + let out = components::decoupling_capacitor(components::Decoupling { + current_step: need(i, "current_step")?, + step_time: need(i, "step_time")?, + ripple: need(i, "ripple")?, + esl: need_or(i, "esl", 1.0e-9)?, + capacitance: maybe(i, "capacitance")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "capacitance_needed", out.capacitance_needed, t)?; + ck(e, "impedance_target", out.impedance_target, t)?; + ck_opt(e, "self_resonance", out.self_resonance, t) + } + "i2c_pullup" => { + let out = components::i2c_pullup(components::I2cPullup { + vcc: need(i, "vcc")?, + vol_max: need(i, "vol_max")?, + iol: need(i, "iol")?, + rise_time: need(i, "rise_time")?, + bus_capacitance: need(i, "bus_capacitance")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "rp_min", out.rp_min, t)?; + ck(e, "rp_max", out.rp_max, t) + } + "crystal_load_capacitors" => { + let out = components::crystal_load_capacitors(components::CrystalCaps { + load_capacitance: need(i, "load_capacitance")?, + stray_capacitance: need(i, "stray_capacitance")?, + c1: maybe(i, "c1")?, + c2: maybe(i, "c2")?, + }) + .map_err(|err| err.to_string())?; + ck_opt(e, "c1_c2", out.c1_c2, t) + } + "timer_555" => { + let out = components::timer_555(components::Timer555 { + mode: parse_timer_mode(i)?, + r1: need(i, "r1")?, + r2: maybe(i, "r2")?, + c: need(i, "c")?, + }) + .map_err(|err| err.to_string())?; + ck_opt(e, "frequency", out.frequency, t)?; + ck_opt(e, "duty_cycle", out.duty_cycle, t)?; + ck_opt(e, "pulse_width", out.pulse_width, t) + } + "opamp_gain" => { + let out = components::opamp_gain(components::OpampGain { + topology: parse_topology(i)?, + rf: need(i, "rf")?, + rin: need(i, "rin")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "gain", out.gain, t)?; + ck(e, "gain_db", out.gain_db, t) + } + "ldo_thermal" => { + let out = components::ldo_thermal(components::LdoThermal { + vin: need(i, "vin")?, + vout: need(i, "vout")?, + iout: need(i, "iout")?, + iq: need(i, "iq")?, + theta_ja: need(i, "theta_ja")?, + ambient: need(i, "ambient")?, + tj_max: 125.0, + }) + .map_err(|err| err.to_string())?; + ck(e, "power", out.power, t)?; + ck(e, "rise", out.rise, t)?; + ck(e, "tj", out.tj, t) + } + "battery_life" => { + let out = components::battery_life(components::BatteryLife { + capacity: need(i, "capacity")?, + active_current: need(i, "active_current")?, + sleep_current: need_or(i, "sleep_current", 0.0)?, + active_fraction: need(i, "active_fraction")?, + usable_fraction: need(i, "usable_fraction")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "average_current", out.average_current, t)?; + ck(e, "hours", out.hours, t)?; + ck(e, "days", out.days, t) + } + "wire_gauge" => { + let out = components::wire_gauge(components::WireGauge { + awg: maybe_i64(i, "awg")?, + current: maybe(i, "current")?, + insulation_rating: parse_rating(i)?, + }) + .map_err(|err| err.to_string())?; + ck_opt(e, "diameter", out.diameter, t)?; + ck_opt(e, "area", out.area, t)?; + ck_opt(e, "resistance", out.resistance, t)?; + ck_opt(e, "ampacity", out.ampacity, t)?; + match (e.get("awg"), out.awg) { + (Some(want), Some(got)) => match num_of(want) { + Some(w) => close("awg", got as f64, w, t), + None => Err("awg: expectation not a number".to_string()), + }, + (Some(_), None) => Err("awg: calculator produced no value".to_string()), + (None, _) => Ok(()), + } + } + "resistor_code" => { + let bands: Vec = match i.get("bands") { + None => Vec::new(), + Some(Value::Array(a)) => a + .iter() + .map(|b| match b { + Value::String(s) => Some(s.clone()), + _ => None, + }) + .collect::>>() + .ok_or_else(|| "bands: non-text entry".to_string())?, + _ => return Err("bands: not an array".to_string()), + }; + let out = components::resistor_code(components::ResistorCode { + bands, + smd_code: maybe_text(i, "smd_code")?, + value: maybe(i, "value")?, + }) + .map_err(|err| err.to_string())?; + ck_opt(e, "resistance", out.resistance, t)?; + ck_opt(e, "tolerance", out.tolerance, t) + } + "e_series" => { + let series = components::Series::parse(&text(i, "series")?) + .ok_or_else(|| "series: unknown name".to_string())?; + let out = components::e_series(components::ESeriesInput { + value: need(i, "value")?, + series, + }) + .map_err(|err| err.to_string())?; + ck(e, "nearest", out.nearest, t) + } + "unit_converter" => { + let from = utilities::LengthUnit::parse(&text(i, "from")?) + .ok_or_else(|| "from: unknown unit".to_string())?; + let to = utilities::LengthUnit::parse(&text(i, "to")?) + .ok_or_else(|| "to: unknown unit".to_string())?; + let out = utilities::unit_converter(utilities::UnitConvert { + value: need(i, "value")?, + from, + to, + }) + .map_err(|err| err.to_string())?; + ck(e, "value", out.value, t) + } + "thermal_via_count" => { + let out = utilities::thermal_via_count(utilities::ThermalVias { + drill: need(i, "drill")?, + plating: need(i, "plating")?, + length: need(i, "length")?, + target_rth: need(i, "target_rth")?, + filled: flag(i, "filled")?, + }) + .map_err(|err| err.to_string())?; + ck(e, "rth_one_via", out.rth_one_via, t)?; + ck_i64(e, "count", out.count) + } + other => Err(format!("no dispatch for calculator {other}")), + } +} + +fn replay(id: &str) -> Result<(), String> { + let d = doc()?; + let calc = d + .calculator + .iter() + .find(|c| c.id == id) + .ok_or_else(|| format!("no calculator {id} in the data file"))?; + let mut failures: Vec = Vec::new(); + for (n, v) in calc.vector.iter().enumerate() { + let tol = v.tolerance.unwrap_or(1e-9); + if let Err(err) = check_one(id, &v.inputs, &v.expect, tol) { + failures.push(format!("#{n}: {err}")); + } + } + if failures.is_empty() { + Ok(()) + } else { + Err(failures.join("; ")) + } +} + +macro_rules! golden_test { + ($name:ident, $id:literal) => { + #[test] + fn $name() -> Result<(), String> { + replay($id) + } + }; +} + +golden_test!(ohms_law_vectors, "ohms_law"); +golden_test!(series_parallel_vectors, "series_parallel"); +golden_test!(voltage_divider_vectors, "voltage_divider"); +golden_test!(led_resistor_vectors, "led_resistor"); +golden_test!(rc_rl_time_constant_vectors, "rc_rl_time_constant"); +golden_test!(lc_resonance_vectors, "lc_resonance"); +golden_test!(reactance_vectors, "reactance"); +golden_test!(decibel_vectors, "decibel"); +golden_test!(trace_width_vectors, "trace_width"); +golden_test!(via_current_resistance_vectors, "via_current_resistance"); +golden_test!(trace_resistance_drop_vectors, "trace_resistance_drop"); +golden_test!(microstrip_vectors, "microstrip"); +golden_test!(embedded_microstrip_vectors, "embedded_microstrip"); +golden_test!(stripline_vectors, "stripline"); +golden_test!(coplanar_waveguide_vectors, "coplanar_waveguide"); +golden_test!(differential_pair_vectors, "differential_pair"); +golden_test!(propagation_delay_vectors, "propagation_delay"); +golden_test!(crosstalk_vectors, "crosstalk"); +golden_test!( + conductor_spacing_ipc2221_vectors, + "conductor_spacing_ipc2221" +); +golden_test!( + creepage_clearance_iec60664_vectors, + "creepage_clearance_iec60664" +); +golden_test!(decoupling_capacitor_vectors, "decoupling_capacitor"); +golden_test!(i2c_pullup_vectors, "i2c_pullup"); +golden_test!(crystal_load_capacitors_vectors, "crystal_load_capacitors"); +golden_test!(timer_555_vectors, "timer_555"); +golden_test!(opamp_gain_vectors, "opamp_gain"); +golden_test!(ldo_thermal_vectors, "ldo_thermal"); +golden_test!(battery_life_vectors, "battery_life"); +golden_test!(wire_gauge_vectors, "wire_gauge"); +golden_test!(resistor_code_vectors, "resistor_code"); +golden_test!(e_series_vectors, "e_series"); +golden_test!(unit_converter_vectors, "unit_converter"); +golden_test!(thermal_via_count_vectors, "thermal_via_count"); + +#[test] +fn data_file_has_every_vector_replayed() -> Result<(), String> { + let d = doc()?; + let total: usize = d.calculator.iter().map(|c| c.vector.len()).sum(); + if total != 119 { + return Err(format!("data file carries {total} vectors, expected 119")); + } + if d.calculator.len() != meta::CALCULATORS.len() { + return Err(format!( + "{} calculators in the data file, {} in meta", + d.calculator.len(), + meta::CALCULATORS.len() + )); + } + for c in &d.calculator { + if c.vector.is_empty() { + return Err(format!("{} has no vectors", c.id)); + } + if meta::calculator(&c.id).is_none() { + return Err(format!("{} missing from meta", c.id)); + } + } + Ok(()) +} + +#[test] +fn metadata_mirrors_the_data_file() -> Result<(), String> { + let d = doc()?; + for c in &d.calculator { + let m = meta::calculator(&c.id).ok_or_else(|| format!("{} missing from meta", c.id))?; + for (field, got, want) in [ + ("name", m.name, c.name.as_str()), + ("group", m.group, c.group.as_str()), + ("summary", m.summary, c.summary.as_str()), + ("formula", m.formula, c.formula.as_str()), + ("source", m.source, c.source.as_str()), + ("validity", m.validity, c.validity.as_str()), + ("accuracy", m.accuracy, c.accuracy.as_str()), + ] { + if got != want { + return Err(format!("{}: meta {field} differs from the data file", c.id)); + } + } + if m.inputs.len() != c.inputs.len() { + return Err(format!( + "{}: {} meta inputs, {} data inputs", + c.id, + m.inputs.len(), + c.inputs.len() + )); + } + for (mi, di) in m.inputs.iter().zip(&c.inputs) { + if mi.name != di.name || mi.optional != di.optional { + return Err(format!("{}: input {} mismatched", c.id, di.name)); + } + let want_unit = if di.values.is_some() || di.unit == "bool" { + "enum" + } else { + di.unit.as_str() + }; + if mi.unit != want_unit { + return Err(format!("{}: input {} unit mismatched", c.id, di.name)); + } + let (dmin, dmax) = match di.range { + Some([lo, hi]) => (Some(lo), Some(hi)), + None => (None, None), + }; + if mi.min != dmin || mi.max != dmax { + return Err(format!("{}: input {} range mismatched", c.id, di.name)); + } + let want_values: Vec<&str> = match &di.values { + Some(vs) => vs.iter().map(String::as_str).collect(), + None if di.unit == "bool" => vec!["true", "false"], + None => vec![], + }; + if mi.values.len() != want_values.len() + || mi.values.iter().zip(&want_values).any(|(a, b)| a != b) + { + return Err(format!("{}: input {} values mismatched", c.id, di.name)); + } + } + } + Ok(()) +} diff --git a/crates/doc/src/fab.rs b/crates/doc/src/fab.rs new file mode 100644 index 000000000..e0fc48b6e --- /dev/null +++ b/crates/doc/src/fab.rs @@ -0,0 +1,285 @@ +//! Fabrication rule minimums and named capability presets. +use crate::Id; +use serde::{Deserialize, Serialize}; +use std::sync::LazyLock; + +fn fab_bound(v: f64) -> bool { + v.is_finite() && (0.001..=100.0).contains(&v) +} + +/// Project fabrication minimums and preset metadata. Absent on a board means +/// no fab floor is recorded beyond the default copper clearance. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +pub struct FabRules { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min_track: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min_space: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min_drill: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min_npth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min_ring_via: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min_ring_pth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hole_to_hole_via: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hole_to_hole_pad: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hole_to_copper_via: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hole_to_copper_pth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hole_to_copper_npth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub edge_routed: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub edge_vscore: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub silk_line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub silk_text_height: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub silk_to_pad: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mask_dam: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_aspect_ratio: Option, + /// Finished-hole diameter added when measuring annular ring against the + /// drill tool, when the preset records one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plating_allowance: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preset: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retrieved: Option, +} + +impl FabRules { + pub fn valid(&self) -> bool { + let ok = |v: Option| v.is_none_or(fab_bound); + ok(self.min_track) + && ok(self.min_space) + && ok(self.min_drill) + && ok(self.min_npth) + && ok(self.min_ring_via) + && ok(self.min_ring_pth) + && ok(self.hole_to_hole_via) + && ok(self.hole_to_hole_pad) + && ok(self.hole_to_copper_via) + && ok(self.hole_to_copper_pth) + && ok(self.hole_to_copper_npth) + && ok(self.edge_routed) + && ok(self.edge_vscore) + && ok(self.silk_line) + && ok(self.silk_text_height) + && ok(self.silk_to_pad) + && ok(self.mask_dam) + && self + .max_aspect_ratio + .is_none_or(|r| r.is_finite() && (1.0..=50.0).contains(&r)) + && self + .plating_allowance + .is_none_or(|p| p.is_finite() && (0.0..=0.5).contains(&p)) + && self + .preset + .as_ref() + .is_none_or(|s| !s.is_empty() && s.len() <= 64) + && self + .source_url + .as_ref() + .is_none_or(|s| !s.is_empty() && s.len() <= 512) + && self + .retrieved + .as_ref() + .is_none_or(|s| !s.is_empty() && s.len() <= 32) + } + + pub fn drill_tool(&self, finished_drill: f64) -> f64 { + finished_drill + self.plating_allowance.unwrap_or(0.0) + } +} + +/// Clearance between every net in one class and every net in another. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct ClassPairRule { + pub class_a: Id, + pub class_b: Id, + pub clearance: f64, +} + +impl ClassPairRule { + pub fn valid(&self) -> bool { + self.class_a != self.class_b + && self.class_a != 0 + && self.class_b != 0 + && fab_bound(self.clearance) + } + + pub fn key(&self) -> (Id, Id) { + ( + self.class_a.min(self.class_b), + self.class_a.max(self.class_b), + ) + } +} + +pub const FAB_PRESET_NAMES: &[&str] = &[ + "JLCPCB 1-2L", + "OSH Park 2L", + "AISLER 2L HASL 35um", + "Eurocircuits class 6", +]; + +#[derive(Clone, Debug)] +pub struct FabPreset { + pub name: &'static str, + pub rules: FabRules, +} + +pub fn fab_preset(name: &str) -> Option { + fab_presets().iter().find(|p| p.name == name).cloned() +} + +pub fn fab_preset_list() -> Vec<&'static str> { + FAB_PRESET_NAMES.to_vec() +} + +fn fab_presets() -> &'static [FabPreset] { + FAB_PRESETS.as_slice() +} + +fn preset_rules( + preset: &'static str, + source_url: &'static str, + retrieved: &'static str, + body: FabRules, +) -> FabRules { + FabRules { + preset: Some(preset.into()), + source_url: Some(source_url.into()), + retrieved: Some(retrieved.into()), + ..body + } +} + +static FAB_PRESETS: LazyLock> = LazyLock::new(|| { + vec![ + FabPreset { + name: "JLCPCB 1-2L", + rules: preset_rules( + "JLCPCB 1-2L", + "https://jlcpcb.com/capabilities/Capabilities", + "2026-03-28", + FabRules { + min_track: Some(0.127), + min_space: Some(0.127), + min_drill: Some(0.3), + min_npth: Some(0.3), + min_ring_via: Some(0.075), + min_ring_pth: Some(0.075), + hole_to_hole_via: Some(0.3), + hole_to_hole_pad: Some(0.3), + hole_to_copper_via: Some(0.2), + hole_to_copper_pth: Some(0.2), + hole_to_copper_npth: Some(0.2), + edge_routed: Some(0.3), + silk_line: Some(0.15), + silk_text_height: Some(1.0), + silk_to_pad: Some(0.15), + max_aspect_ratio: Some(20.0), + plating_allowance: Some(0.025), + ..FabRules::default() + }, + ), + }, + FabPreset { + name: "OSH Park 2L", + rules: preset_rules( + "OSH Park 2L", + "https://docs.oshpark.com/design-rules/2-layer-design-rules/", + "2026-03-28", + FabRules { + min_track: Some(0.1524), + min_space: Some(0.1524), + min_drill: Some(0.254), + min_npth: Some(0.254), + min_ring_via: Some(0.1524), + min_ring_pth: Some(0.1524), + hole_to_hole_via: Some(0.254), + hole_to_hole_pad: Some(0.254), + hole_to_copper_via: Some(0.254), + hole_to_copper_pth: Some(0.254), + hole_to_copper_npth: Some(0.254), + edge_routed: Some(0.254), + silk_line: Some(0.1524), + silk_text_height: Some(1.016), + silk_to_pad: Some(0.1524), + max_aspect_ratio: Some(16.0), + plating_allowance: Some(0.025), + ..FabRules::default() + }, + ), + }, + FabPreset { + name: "AISLER 2L HASL 35um", + rules: preset_rules( + "AISLER 2L HASL 35um", + "https://aisler.net/pcb-specs", + "2026-03-28", + FabRules { + min_track: Some(0.15), + min_space: Some(0.15), + min_drill: Some(0.3), + min_npth: Some(0.3), + min_ring_via: Some(0.075), + min_ring_pth: Some(0.075), + hole_to_hole_via: Some(0.3), + hole_to_hole_pad: Some(0.3), + hole_to_copper_via: Some(0.2), + hole_to_copper_pth: Some(0.2), + hole_to_copper_npth: Some(0.2), + edge_routed: Some(0.3), + silk_line: Some(0.15), + silk_text_height: Some(1.0), + silk_to_pad: Some(0.15), + max_aspect_ratio: Some(20.0), + plating_allowance: Some(0.035), + ..FabRules::default() + }, + ), + }, + FabPreset { + name: "Eurocircuits class 6", + rules: preset_rules( + "Eurocircuits class 6", + "https://www.eurocircuits.com/pcb-design-guidelines/", + "2026-03-28", + FabRules { + min_track: Some(0.1), + min_space: Some(0.1), + min_drill: Some(0.25), + min_npth: Some(0.25), + min_ring_via: Some(0.05), + min_ring_pth: Some(0.075), + hole_to_hole_via: Some(0.25), + hole_to_hole_pad: Some(0.25), + hole_to_copper_via: Some(0.15), + hole_to_copper_pth: Some(0.15), + hole_to_copper_npth: Some(0.15), + edge_routed: Some(0.25), + silk_line: Some(0.125), + silk_text_height: Some(0.8), + silk_to_pad: Some(0.125), + max_aspect_ratio: Some(25.0), + plating_allowance: Some(0.025), + ..FabRules::default() + }, + ), + }, + ] +}); diff --git a/crates/doc/src/fill.rs b/crates/doc/src/fill.rs new file mode 100644 index 000000000..dafb41dd1 --- /dev/null +++ b/crates/doc/src/fill.rs @@ -0,0 +1,708 @@ +//! Poured copper: the fill that a zone actually becomes. +//! +//! A [`CopperZone`] stores an outline and the cutouts a designer drew. The fill +//! is computed from that and the rest of the board: keepouts first, then +//! foreign copper grown by its required clearance, then the board edge, then +//! same-net pads joined solid or through thermal spokes, then a morphological +//! opening that removes necks narrower than the minimum copper width, and +//! finally the island policy. Computing on demand keeps the document free of +//! derived copper that could go stale. +//! +//! Every step is bounded: a zone may carry [`MAX_OUTLINE_VERTICES`] vertices +//! and a layer may carry [`MAX_FILL_ITEMS`] copper items before the fill +//! refuses with a plain error rather than grinding on a pathological board. + +use crate::{ + CopperZone, Footprint, Id, Keepout, Layer, Pad, Project, RuleArea, ZoneConnect, ZonePour, +}; +use pcbcraft_geom::poly::{self, Piece, Region, Ring}; +use pcbcraft_geom::{Point, polygon_area}; + +/// Most vertices a poured outline may carry before the fill gives up. +pub const MAX_OUTLINE_VERTICES: usize = 256; +/// Most copper items the fill considers on one copper layer. +pub const MAX_FILL_ITEMS: usize = 2048; +/// Fewest spokes a pad needs for the pour to count as connected to it. +const MIN_SPOKES: usize = 2; + +/// The outcome of pouring one zone. +#[derive(Clone, Debug)] +pub struct ZoneFill { + /// The zone this fill belongs to. + pub zone: Id, + /// Net the poured copper carries. + pub net: Id, + /// Copper side the pour sits on. + pub layer: Layer, + /// The copper that ships, one piece per connected area, holes included. + pub pieces: Region, + /// Narrowest copper the pour kept, in millimetres. + pub min_width: f64, + /// Detached pieces the fill found. + pub islands: usize, + /// Detached pieces the policy dropped. + pub removed: usize, + /// True when the zone touches none of its own net and was therefore kept + /// whole as a deliberate shield or heatsink. + pub unconnected: bool, + /// Spokes that reach the poured copper. + pub spokes: usize, + /// Same-net pads or vias left with fewer than two spokes. + pub starved: Vec, +} +impl ZoneFill { + /// Total poured copper area in square millimetres. + pub fn area(&self) -> f64 { + poly::region_area(&self.pieces) + } + /// True when a point falls on poured copper. + pub fn contains(&self, point: Point) -> bool { + poly::region_contains(&self.pieces, point) + } +} + +/// One piece of copper on a layer, seen the way the pour sees it. +struct Item { + id: Id, + net: Id, + kind: Kind, + piece: Piece, + at: Point, + /// Rotation of the part, used to line thermal spokes up with a pad. + rotation: f64, +} +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Pad, + Via, + Track, + Zone, + Hole, +} + +/// Poured copper for every zone on the board, in zone order. +pub fn zone_fills(project: &Project) -> Result, String> { + project + .board + .zones + .iter() + .map(|zone| zone_fill(project, zone)) + .collect() +} + +/// The poured copper of one zone, after knockouts, reliefs, the width opening +/// and the island policy. +pub fn zone_fill(project: &Project, zone: &CopperZone) -> Result { + let settings = zone.pour_settings(); + let layer = zone.layer; + let mut fill = ZoneFill { + zone: zone.id, + net: zone.net, + layer, + pieces: Vec::new(), + min_width: settings + .min_width + .unwrap_or_else(|| default_min_width(project)), + islands: 0, + removed: 0, + unconnected: false, + spokes: 0, + starved: Vec::new(), + }; + if !zone.filled { + return Ok(fill); + } + if zone.outline.len() > MAX_OUTLINE_VERTICES { + return Err(format!( + "zone {} outline needs at most {MAX_OUTLINE_VERTICES} vertices to pour", + zone.id + )); + } + let Some(outline) = ring(&zone.outline) else { + return Ok(fill); + }; + let items = items(project, layer)?; + if items.len() > MAX_FILL_ITEMS { + return Err(format!( + "zone {} sits on a layer with more than {MAX_FILL_ITEMS} copper items to pour around", + zone.id + )); + } + + // Keepouts go first: subtracting them after the knockouts leaves ragged + // copper along their edges. + let keepouts: Vec = project + .board + .rule_areas + .iter() + .filter(|area| keepout_blocks(area, KeepoutKind::Zones, layer, zone.net)) + .map(|area| rectangle(area.keepout_rect())) + .collect(); + let mut copper = poly::difference(&[vec![outline]], &keepouts); + + // Foreign copper, manual cutouts, drilled holes and circular cutouts, each + // grown by the clearance the rules demand of it. + let mut knockout: Vec = Vec::new(); + for item in &items { + if item.net == zone.net && item.net != 0 { + continue; + } + let clearance = + project.required_clearance_at(zone.net, item.net, item.at, item.at, layer, layer); + let grown = + poly::offset(std::slice::from_ref(&item.piece), clearance).ok_or_else(|| { + format!( + "zone {} clearance growth left the coordinate range", + zone.id + ) + })?; + knockout.extend(grown); + } + for cutout in &zone.cutouts { + if let Some(hole) = ring(cutout) { + knockout.push(vec![hole]); + } + } + for cutout in &project.board.cutouts { + knockout.push(poly::circle( + cutout.center, + cutout.radius + project.board.clearance, + )); + } + copper = poly::difference(&copper, &knockout); + + // Copper never reaches the board edge, and never grows outside the board. + if let Some(inset) = poly::offset(&[board_piece(project)], -project.board.clearance) { + copper = poly::intersect(&copper, &inset); + } + + // Same-net pads and vias either join solid, join through spokes, or keep + // out of the pour entirely. + let before_relief = copper.clone(); + let mut gap: Vec = Vec::new(); + let mut relief: Vec = Vec::new(); + for item in &items { + if item.net != zone.net || item.net == 0 || item.id == zone.id { + continue; + } + let connect = match item.kind { + Kind::Pad => settings.pad_connect, + Kind::Via => settings.via_connect, + _ => continue, + }; + if connect == ZoneConnect::Solid { + continue; + } + if poly::intersect(std::slice::from_ref(&item.piece), &copper).is_empty() { + continue; + } + let grown = poly::offset(std::slice::from_ref(&item.piece), settings.relief_gap) + .ok_or_else(|| format!("zone {} relief growth left the coordinate range", zone.id))?; + if connect == ZoneConnect::None { + gap.extend(grown); + continue; + } + gap.extend(poly::difference(&grown, std::slice::from_ref(&item.piece))); + relief.push(Relief { + grown: poly::offset(std::slice::from_ref(&item.piece), settings.relief_gap) + .unwrap_or_default(), + id: item.id, + center: item.at, + piece: item.piece.clone(), + rotation: item.rotation, + }); + } + copper = poly::difference(&copper, &gap); + + // A neck narrower than the minimum copper width is not manufacturable, so + // the opening removes it before the fill ships. + let mut opened = open(&copper, fill.min_width); + opened.retain(|piece| poly::piece_area(piece) >= 3.0 * fill.min_width * fill.min_width); + + // Spokes survive only when their far end lands on copper the opening kept. + let mut spokes: Vec = Vec::new(); + let mut kept_spokes = 0; + for target in &relief { + let reach = target.reach(); + let mut kept = 0; + // Poured copper outside the cleared disc: a spoke only counts when it + // lands there, not on the pad it starts from. + let beyond = poly::difference(&opened, &target.grown); + let count = f64::from(settings.spokes); + let first = if settings.spokes == 2 { 0.0 } else { 45.0 }; + for step in 0..settings.spokes { + let angle = first + 360.0 * f64::from(step) / count + target.rotation; + let direction = Point::new(1.0, 0.0).rotate(angle); + let far = Point::new( + target.center.x + direction.x * (reach + settings.relief_gap + 1.0), + target.center.y + direction.y * (reach + settings.relief_gap + 1.0), + ); + let bar = poly::capsule(target.center, far, settings.spoke_width / 2.0); + let clipped = poly::intersect(&[bar], &before_relief); + if clipped.is_empty() { + continue; + } + if poly::intersect(&clipped, &beyond).is_empty() { + continue; + } + spokes.extend(clipped); + kept += 1; + } + kept_spokes += kept; + if kept < MIN_SPOKES { + fill.starved.push(target.id); + } + } + fill.spokes = kept_spokes; + let mut pieces = poly::union(&opened, &spokes); + + // Islands: a piece that touches no same-net copper has nothing holding it + // down in the etch bath. + let copper_of_net: Vec = if zone.is_generated() { + Vec::new() + } else { + items + .iter() + .filter(|item| item.net == zone.net && item.net != 0 && item.id != zone.id) + .map(|item| item.piece.clone()) + .collect() + }; + let touches = |piece: &Piece| { + zone.is_generated() + || !poly::intersect(std::slice::from_ref(piece), &copper_of_net).is_empty() + }; + let connected = pieces.iter().filter(|piece| touches(piece)).count(); + let all_detached = connected == 0; + fill.unconnected = all_detached && !pieces.is_empty(); + let mut kept: Region = Vec::with_capacity(pieces.len()); + for piece in pieces.drain(..) { + if touches(&piece) { + kept.push(piece); + continue; + } + fill.islands += 1; + if all_detached { + // A zone that touches nothing is a deliberate shield or heatsink, + // not debris: keep it whole and report it once. + kept.push(piece); + continue; + } + let drop = match settings.islands { + crate::ZoneIslands::Keep => false, + crate::ZoneIslands::Remove => true, + crate::ZoneIslands::RemoveBelow(area) => poly::piece_area(&piece) < area, + }; + if drop { + fill.removed += 1; + } else { + kept.push(piece); + } + } + fill.pieces = kept; + Ok(fill) +} + +/// A pad or via that joins the pour through thermal spokes. +struct Relief { + /// The pad copper grown by the relief gap: the cleared disc that spokes cross. + grown: Region, + id: Id, + center: Point, + piece: Piece, + rotation: f64, +} + +impl Relief { + /// How far the pad copper reaches from its centre. + fn reach(&self) -> f64 { + self.piece + .iter() + .flatten() + .map(|point| point.distance(self.center)) + .fold(0.0, f64::max) + } +} + +/// Shrink by half the minimum width, grow back with round corners, and keep +/// only what the original copper still covers. +fn open(region: &[Piece], width: f64) -> Region { + if !width.is_finite() || width <= 0.0 { + return region.to_vec(); + } + let half = width / 2.0; + let Some(shrunk) = poly::offset(region, -half) else { + return region.to_vec(); + }; + let Some(grown) = poly::offset(&shrunk, half) else { + return region.to_vec(); + }; + poly::intersect(&grown, region) +} + +/// Narrowest copper the board already uses: the thinnest track or class +/// minimum, never below a fab-friendly 0.05 mm, never above 1 mm. +fn default_min_width(project: &Project) -> f64 { + let tracks = project + .board + .tracks + .iter() + .map(|track| track.width) + .fold(f64::INFINITY, f64::min); + let classes = project + .net_classes + .iter() + .map(|class| class.min_width.unwrap_or(class.width)) + .fold(f64::INFINITY, f64::min); + let narrowest = tracks.min(classes); + if narrowest.is_finite() { + narrowest.clamp(0.05, 1.0) + } else { + 0.2 + } +} + +/// True when a keepout area forbids one kind of copper on a layer for a net. +pub fn keepout_blocks(area: &RuleArea, kind: KeepoutKind, layer: Layer, net: Id) -> bool { + let Some(keepout) = area.keepout else { + return false; + }; + keepout.forbids(kind) && area.keepout_applies(layer, net) +} + +/// The copper kinds a keepout can name. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeepoutKind { + /// Tracks and other routed copper. + Tracks, + /// Vias. + Vias, + /// Pads. + Pads, + /// Poured zones and other copper regions. + Zones, +} + +impl Keepout { + /// Whether this keepout forbids one kind of copper. + pub fn forbids(&self, kind: KeepoutKind) -> bool { + match kind { + KeepoutKind::Tracks => self.tracks, + KeepoutKind::Vias => self.vias, + KeepoutKind::Pads => self.pads, + KeepoutKind::Zones => self.zones, + } + } +} + +/// Ids of the pads' footprints, vias, holes, tracks and zones the pour has to +/// consider on one copper layer, in board order. +/// +/// # Rules +/// - Same list `zone_fill` and `keepout_hits` walk, so a test of this list is a +/// test of both. +/// +/// # Dependencies +/// - `crates/doc/src/fill.rs` (`items`) builds the list; `crates/doc/src/lib.rs` +/// (`Project::via_span_layers`) decides which vias reach the layer. +/// +/// # Do not +/// - Use this to edit the board; it reports, it never changes the document. +pub fn layer_obstacles(project: &Project, layer: Layer) -> Result, String> { + Ok(items(project, layer)?.iter().map(|item| item.id).collect()) +} + +/// Copper shapes on one layer, each with the net and rotation the pour needs. +fn items(project: &Project, layer: Layer) -> Result, String> { + let mut items = Vec::new(); + for footprint in &project.board.footprints { + for (id, pad, rotation, at, piece) in pad_items(footprint) { + if !pad_reaches(project, footprint, &pad, layer) { + continue; + } + items.push(Item { + id, + net: pad.net.unwrap_or(0), + kind: Kind::Pad, + piece, + at, + rotation, + }); + } + } + for via in &project.board.vias { + // A via is copper only on the layers of its span: outside it, the + // layer neither clears an antipad nor joins the via. + if !project.via_span_layers(via).contains(&layer) { + continue; + } + items.push(Item { + id: via.id, + net: via.net, + kind: Kind::Via, + piece: poly::circle(via.position, via.diameter / 2.0), + at: via.position, + rotation: 0.0, + }); + } + for hole in &project.board.holes { + items.push(Item { + id: hole.id, + net: 0, + kind: Kind::Hole, + piece: poly::circle(hole.position, hole.diameter / 2.0), + at: hole.position, + rotation: 0.0, + }); + } + for track in project + .board + .tracks + .iter() + .filter(|track| track.layer == layer) + { + let piece = match track.curve() { + None => poly::capsule(track.start, track.end, track.width / 2.0), + Some(arc) => { + let mut bars = Vec::new(); + let chords = 16; + for step in 0..chords { + let start = arc.point_at(f64::from(step) / f64::from(chords)); + let end = arc.point_at(f64::from(step + 1) / f64::from(chords)); + bars.push(poly::capsule(start, end, track.width / 2.0)); + } + poly::union(&bars, &[]) + .into_iter() + .next() + .unwrap_or_default() + } + }; + items.push(Item { + id: track.id, + net: track.net, + kind: Kind::Track, + piece, + at: Point::new( + (track.start.x + track.end.x) / 2.0, + (track.start.y + track.end.y) / 2.0, + ), + rotation: 0.0, + }); + } + for zone in project + .board + .zones + .iter() + .filter(|zone| zone.layer == layer) + { + let Some(outline) = ring(&zone.outline) else { + continue; + }; + let mut piece = vec![outline]; + piece.extend(zone.cutouts.iter().filter_map(|cutout| ring(cutout))); + let at = zone + .outline + .iter() + .fold(Point::default(), |sum, point| sum.offset(*point)); + let count = zone.outline.len().max(1) as f64; + items.push(Item { + id: zone.id, + net: zone.net, + kind: Kind::Zone, + piece, + at: Point::new(at.x / count, at.y / count), + rotation: 0.0, + }); + } + Ok(items) +} + +/// Whether a pad has copper on `layer` of this board: a through-hole pad on +/// every copper layer, a surface pad only on the face its part sits on, where +/// the bottom face is the last copper layer of the stackup. +/// +/// # Rules +/// - Never compare against `Layer::Back`: on a board with inner copper that +/// constant is the second layer, not the bottom. +/// +/// # Dependencies +/// - `crates/doc/src/lib.rs` for `Footprint::board_side` and `Project::copper_layer_count`. +fn pad_reaches(project: &Project, footprint: &Footprint, pad: &Pad, layer: Layer) -> bool { + let through = match pad.geometry.as_ref() { + None => false, + Some(g) => g.pad_type == "thru_hole" || g.layers.iter().any(|l| l == "*.Cu"), + }; + if through { + return true; + } + let face = if footprint.board_side() == Layer::Front { + Layer::Front + } else { + Layer::from_index(project.copper_layer_count().saturating_sub(1)).unwrap_or(Layer::Back) + }; + face == layer +} + +/// A footprint's pads as world-space copper, with the combined part and pad +/// rotation that thermal spokes line up with. +fn pad_items(footprint: &Footprint) -> Vec<(Id, Pad, f64, Point, Piece)> { + let mut result = Vec::new(); + for pad in &footprint.pads { + let Some(piece) = piece_of(&pad.outline_points(), |point| { + footprint.position.offset(point.rotate(-footprint.rotation)) + }) else { + continue; + }; + let at = footprint + .pad_position(&pad.number) + .unwrap_or_else(|| centroid(&piece)); + let rotation = + footprint.rotation + pad.geometry.as_ref().map(|g| g.rotation).unwrap_or(0.0); + result.push((footprint.id, pad.clone(), rotation, at, piece)); + } + result +} + +fn centroid(piece: &Piece) -> Point { + let points = piece.first().map(Vec::as_slice).unwrap_or(&[]); + if points.is_empty() { + return Point::default(); + } + let sum = points + .iter() + .fold(Point::default(), |sum, point| sum.offset(*point)); + Point::new(sum.x / points.len() as f64, sum.y / points.len() as f64) +} + +fn piece_of(points: &[Point], map: impl Fn(Point) -> Point) -> Option { + let world: Ring = points.iter().map(|point| map(*point)).collect(); + ring(&world).map(|ring| vec![ring]) +} + +/// A closed ring from a vertex list, or none when it is degenerate. +pub(crate) fn ring(points: &[Point]) -> Option { + let mut ring: Ring = points + .iter() + .copied() + .filter(|point| point.valid()) + .collect(); + if ring.first() == ring.last() { + ring.pop(); + } + if ring.len() < 3 || polygon_area(&ring).abs() < 1e-12 { + return None; + } + if let Some(first) = ring.first().copied() { + ring.push(first); + } + Some(ring) +} + +/// The board surface as a piece: the traced outline, or the plain rectangle. +fn board_piece(project: &Project) -> Piece { + let board = &project.board; + if let Some(outline) = &board.outline + && let Some(ring) = ring(outline) + { + return vec![ring]; + } + vec![vec![ + Point::new(0.0, 0.0), + Point::new(board.width, 0.0), + Point::new(board.width, board.height), + Point::new(0.0, board.height), + Point::new(0.0, 0.0), + ]] +} + +/// A rule area rectangle as a piece. +fn rectangle(region: crate::RuleRegion) -> Piece { + vec![vec![ + Point::new(region.x, region.y), + Point::new(region.x + region.width, region.y), + Point::new(region.x + region.width, region.y + region.height), + Point::new(region.x, region.y + region.height), + Point::new(region.x, region.y), + ]] +} + +/// True when a zone's settings are all inside their bounds. +pub fn pour_is_valid(pour: &ZonePour) -> bool { + pour.valid() +} + +/// One object that enters a keepout area. +#[derive(Clone, Copy, Debug)] +pub struct KeepoutHit { + /// The rule area that forbids it. + pub area: Id, + /// The track, via, pad or zone that entered. + pub object: Id, + /// Net the object carries. + pub net: Id, + /// What kind of copper the object is. + pub kind: KeepoutKind, +} + +impl KeepoutKind { + /// Plain word for a finding message. + pub fn label(self) -> &'static str { + match self { + Self::Tracks => "track", + Self::Vias => "via", + Self::Pads => "pad", + Self::Zones => "zone", + } + } +} + +/// Every track, via, pad and zone that enters a keepout area, on every copper +/// layer of the board. One hit per object and area, so a via that crosses on +/// several layers is reported once. +pub fn keepout_hits(project: &Project) -> Result, String> { + let mut hits: Vec = Vec::new(); + for layer in project.copper_layers() { + let items = items(project, layer)?; + for area in &project.board.rule_areas { + let Some(keepout) = area.keepout else { + continue; + }; + if area.layer.is_some_and(|only| only != layer) { + continue; + } + let rect = rectangle(area.keepout_rect()); + for item in &items { + let kind = match item.kind { + Kind::Pad => KeepoutKind::Pads, + Kind::Via => KeepoutKind::Vias, + Kind::Track => KeepoutKind::Tracks, + Kind::Zone => KeepoutKind::Zones, + Kind::Hole => continue, + }; + if !keepout.forbids(kind) || !area.keepout_applies(layer, item.net) { + continue; + } + if poly::intersect( + std::slice::from_ref(&item.piece), + std::slice::from_ref(&rect), + ) + .is_empty() + { + continue; + } + if hits + .iter() + .any(|hit| hit.area == area.id && hit.object == item.id) + { + continue; + } + hits.push(KeepoutHit { + area: area.id, + object: item.id, + net: item.net, + kind, + }); + } + } + } + Ok(hits) +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 84ed23186..e8a57f870 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1,11 +1,44 @@ //! Canonical project data. No UI or protocol dependencies. +mod machine_profile; +mod outline; +pub use machine_profile::*; +pub use outline::{ + MIN_ARC_SAGITTA, VALIDATION_CHORD_ERROR, arc_sagitta, flatten_outline, outline_extent, + segment_arc, validate_outline_arcs, +}; +mod panel; +pub use panel::{ + PanelCopy, PanelGrid, PanelLayout, PanelSeparation, PanelSettings, board_copy_size, + panel_layout, panel_layout_from_grid, panel_layout_with_settings, +}; +mod fab; +pub use fab::{ClassPairRule, FAB_PRESET_NAMES, FabPreset, FabRules, fab_preset, fab_preset_list}; use pcbcraft_geom::{Point, positive}; -use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; +use pcbcraft_library::PadShape; +use serde::de::{self, Visitor}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; pub type Id = u64; pub const MAX_ITEMS: usize = 2048; +mod material; +pub use material::{MATERIALS, Material, material}; +mod net_members; +pub use net_members::{LayerMembers, NetMembers, PadMember, PinMember, ViaMember}; +pub mod fill; +pub use fill::{ + KeepoutHit, KeepoutKind, ZoneFill, keepout_hits, layer_obstacles, zone_fill, zone_fills, +}; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct PinAppearance { + pub unit: u32, + pub offset: Point, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub direction: Option, +} #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Pin { pub number: String, @@ -18,10 +51,29 @@ pub struct Pin { pub direction: Option, #[serde(default = "first_unit")] pub unit: u32, + /// Extra schematic copies of this physical pin on other units. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub appearances: Vec, +} +impl Pin { + /// Local offset and facing for one schematic unit copy of this pin. + pub fn geometry_at(&self, unit: u32) -> Option<(Point, Option)> { + if self.unit == unit { + Some((self.offset, self.direction)) + } else { + self.appearances + .iter() + .find(|a| a.unit == unit) + .map(|a| (a.offset, a.direction)) + } + } } fn first_unit() -> u32 { 1 } +fn poured() -> bool { + true +} #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct SymbolUnitPlacement { pub unit: u32, @@ -31,6 +83,80 @@ pub struct SymbolUnitPlacement { fn passive() -> String { "passive".into() } +/// Pin electrical types recognised by ERC and schematic validation. +pub const PIN_ELECTRICAL_TYPES: [&str; 12] = [ + "bidirectional", + "free", + "input", + "no_connect", + "open_collector", + "open_emitter", + "output", + "passive", + "power_in", + "power_out", + "tri_state", + "unspecified", +]; +/// Sorted pair key for one cell of the pin-type connection matrix. +pub fn pin_matrix_key(type_a: &str, type_b: &str) -> String { + if type_a <= type_b { + format!("{type_a}|{type_b}") + } else { + format!("{type_b}|{type_a}") + } +} +/// Default ERC level for a pin-type pair: `"ok"`, `"warning"`, or `"error"`. +pub fn default_pin_matrix_level(type_a: &str, type_b: &str) -> &'static str { + let (a, b) = if type_a <= type_b { + (type_a, type_b) + } else { + (type_b, type_a) + }; + if a == "no_connect" || b == "no_connect" { + return "error"; + } + match (a, b) { + ("output", "output") => "error", + ("output", "power_out") => "error", + ("power_out", "power_out") => "error", + ("open_emitter", "power_out") => "error", + ("input", "input") => "warning", + ("output", "tri_state") => "warning", + ("open_collector", "power_out") => "warning", + ("bidirectional", "power_out") => "warning", + _ => "ok", + } +} +/// Default matrix cells whose level is not `"ok"`, for display beside overrides. +pub const DEFAULT_PIN_MATRIX_OVERRIDES: &[(&str, &str, &str)] = &[ + ("bidirectional", "no_connect", "error"), + ("bidirectional", "power_out", "warning"), + ("free", "no_connect", "error"), + ("input", "input", "warning"), + ("input", "no_connect", "error"), + ("no_connect", "no_connect", "error"), + ("no_connect", "open_collector", "error"), + ("no_connect", "open_emitter", "error"), + ("no_connect", "output", "error"), + ("no_connect", "passive", "error"), + ("no_connect", "power_in", "error"), + ("no_connect", "power_out", "error"), + ("no_connect", "tri_state", "error"), + ("no_connect", "unspecified", "error"), + ("open_collector", "power_out", "warning"), + ("open_emitter", "power_out", "error"), + ("output", "no_connect", "error"), + ("output", "output", "error"), + ("output", "power_out", "error"), + ("output", "tri_state", "warning"), + ("passive", "no_connect", "error"), + ("power_in", "no_connect", "error"), + ("power_out", "no_connect", "error"), + ("power_out", "power_out", "error"), + ("tri_state", "no_connect", "error"), + ("unspecified", "no_connect", "error"), +]; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct LibrarySymbol { pub library: String, @@ -57,8 +183,112 @@ pub struct Component { pub library_symbol: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub library_footprint: Option, + /// Free-form component properties, such as a datasheet link, a manufacturer + /// or an orderable part number. Keys are unique per component. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub fields: Vec, + /// The schematic sheet this component belongs to. Sheet 0 is the implicit + /// root page that every design starts with. + #[serde(default, skip_serializing_if = "is_root_sheet")] + pub sheet: Id, +} +fn is_root_sheet(id: &Id) -> bool { + *id == 0 +} +/// A named schematic page. Every component belongs to exactly one sheet; +/// sheet 0 is the implicit root page and is not listed here. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct Sheet { + pub id: Id, + pub name: String, + /// Parent page in the hierarchy, when this page is shown as a child box. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, + /// Where the child page box sits on the parent page, in millimetres. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub entry: Option, +} +/// The settings of one schematic page that are not drawn objects: its title +/// block fields, whether the title block shows, and the defaults new graphics +/// on the page start with. A page with no record uses the defaults of +/// [`PageSettings::new`] and the project metadata for its title block. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct PageSettings { + /// The page these settings belong to; 0 is the Main page. + pub sheet: Id, + /// Empty falls back to the project metadata `title`, then the project name. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub title: String, + /// The version of this sheet, such as `B` or `2.1`; printed in the title block. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub revision: String, + /// Empty falls back to the project metadata `date`, then today. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub date: String, + /// A standard paper size such as `A4`; empty picks the smallest that fits. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub size: String, + /// The company or person the design belongs to. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub company: String, + /// Who drew this sheet. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub drawn_by: String, + /// True when the page draws no title block. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub title_hidden: bool, + /// Stroke width in millimetres new graphics on this page start with. + #[serde(default = "default_page_line_width")] + pub line_width: f64, + /// Stroke colour `#rrggbb` new graphics start with; empty is the theme ink. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub line_color: String, +} +fn default_page_line_width() -> f64 { + 0.25 +} +impl PageSettings { + /// Settings with every field at its default for page `sheet`. + pub fn new(sheet: Id) -> Self { + Self { + sheet, + title: String::new(), + revision: String::new(), + date: String::new(), + size: String::new(), + company: String::new(), + drawn_by: String::new(), + title_hidden: false, + line_width: default_page_line_width(), + line_color: String::new(), + } + } } +/// One named property on a component. A blank value is still a real property: +/// it says the key applies to this component and has not been filled in. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct ComponentField { + pub key: String, + pub value: String, +} +/// The component property that keeps a part out of the bill of materials. +/// Set it to `yes` with `component.field`; clear it to put the part back. +pub const BOM_EXCLUDE_FIELD: &str = "Exclude from BOM"; impl Component { + /// True unless the part carries `BOM_EXCLUDE_FIELD` set to `yes`. + pub fn in_bom(&self) -> bool { + !self + .field(BOM_EXCLUDE_FIELD) + .is_some_and(|v| v.eq_ignore_ascii_case("yes")) + } + /// Value of a named component property, if the component carries it. + pub fn field(&self, key: &str) -> Option<&str> { + self.fields + .iter() + .find(|f| f.key == key) + .map(|f| f.value.as_str()) + } pub fn unit_placement(&self, unit: u32) -> Option<(Point, f64)> { if unit == self.library_symbol.as_ref().map(|s| s.unit).unwrap_or(1) { Some((self.position, self.rotation)) @@ -79,7 +309,7 @@ impl Component { let mut view = self.clone(); view.position = position; view.rotation = rotation; - view.pins.retain(|p| p.unit == unit); + view.pins = self.pins_for_schematic_unit(unit); view.units.clear(); if let Some(s) = &mut view.library_symbol { s.unit = unit; @@ -99,14 +329,44 @@ impl Component { } views } + fn pins_for_schematic_unit(&self, unit: u32) -> Vec { + self.pins + .iter() + .filter_map(|p| { + if p.unit == unit { + let mut copy = p.clone(); + copy.appearances.clear(); + Some(copy) + } else { + p.geometry_at(unit).map(|(offset, direction)| Pin { + number: p.number.clone(), + name: p.name.clone(), + offset, + net: p.net, + electrical_type: p.electrical_type.clone(), + direction, + unit, + appearances: vec![], + }) + } + }) + .collect() + } + /// World position of a physical pin, optionally on one schematic unit copy. + pub fn pin_world_position(&self, number: &str, unit: Option) -> Option { + let pin = self.pins.iter().find(|p| p.number == number)?; + let unit = unit.unwrap_or(pin.unit); + let (offset, _) = pin.geometry_at(unit)?; + self.unit_placement(unit) + .map(|(position, rotation)| position.offset(offset.rotate(-rotation))) + } /// Local drawing extents used for selection and labels, independent of the renderer. pub fn drawing_points(&self) -> Vec { let unit = self.library_symbol.as_ref().map(|s| s.unit).unwrap_or(1); let mut points: Vec = self .pins .iter() - .filter(|p| p.unit == unit) - .map(|p| p.offset) + .filter_map(|p| p.geometry_at(unit).map(|(offset, _)| offset)) .collect(); if let Some(library) = &self.library_symbol { for graphic in library @@ -123,21 +383,301 @@ impl Component { points } pub fn pin_position(&self, number: &str) -> Option { - self.pins.iter().find(|p| p.number == number).and_then(|p| { - self.unit_placement(p.unit) - .map(|(position, rotation)| position.offset(p.offset.rotate(-rotation))) - }) + self.pin_world_position(number, None) } } -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct Net { pub id: Id, pub name: String, + /// Target total routed length for this net, in millimetres. Only checked + /// when the net belongs to no net class; classified nets follow their + /// class target. + #[serde(default)] + pub target_length: Option, + /// How far this net may deviate from its target length, in millimetres. + /// Defaults to zero, and requires a target. + #[serde(default)] + pub length_tolerance: Option, +} +/// A check the designer wrote themselves: one plain measurement with one +/// limit, re-run with the built-in checks after every edit. The measure is +/// one of a fixed list (a wire thinner than, a wire longer than, more parts, +/// more vias, or more wires on one net than the limit), so a check stays +/// readable without any query language. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct CustomCheck { + pub id: Id, + /// Plain words for what this check means, shown wherever it reports. + pub name: String, + /// One of: "track width below", "track length above", "part count above", + /// "via count above", "net track count above". + pub measure: String, + /// The number the measure is compared against: millimetres for wire + /// measures, a plain count otherwise. + pub limit: f64, + /// "error" or "warning", how loudly a breach is reported. + pub severity: String, +} +/// A named group of nets sharing one clearance requirement and one default +/// track width. A net belongs to at most one class; nets in no class follow +/// the board default. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct NetClass { + pub id: Id, + pub name: String, + /// Minimum copper clearance between members of this class and other + /// copper, in millimetres. + pub clearance: f64, + /// Default track width for members of this class, in millimetres. + pub width: f64, + /// Smallest track width this class allows, in millimetres. Set to turn + /// narrower member tracks into a design rule finding. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min_width: Option, + /// Largest track width this class allows, in millimetres. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_width: Option, + /// Target total routed length for member nets, in millimetres. Nets in + /// this class whose copper totals fall outside target ± tolerance are + /// reported as length findings. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub target_length: Option, + /// How far a member net may deviate from the target length, in + /// millimetres. Defaults to zero, an exact match. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub length_tolerance: Option, + /// Longest dead-end copper branch allowed on member nets, in millimetres. + /// Absent means no stub check; zero means no stubs at all. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_stub: Option, + /// Default outer via pad diameter for member nets, in millimetres. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub via_diameter: Option, + /// Default drilled hole for member vias, in millimetres. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub via_drill: Option, + /// Default track width for differential pairs on member nets. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pair_width: Option, + /// Default coupling gap for differential pairs on member nets. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pair_gap: Option, + /// Nets belonging to this class. + #[serde(default)] + pub nets: Vec, + /// Built-in or custom rule profile that last applied these values, when set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, +} +/// A clearance requirement between two named nets, stricter than either +/// class or the board default when it is larger. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct NetPairRule { + /// Ids of the two nets the rule sits between. + pub a: Id, + pub b: Id, + /// Minimum copper separation between the two nets, in millimetres. + pub clearance: f64, + /// Rule profile that last applied this pair clearance, when set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, +} +impl NetPairRule { + fn valid(&self) -> bool { + self.a != self.b + && self.a != 0 + && self.b != 0 + && self.clearance.is_finite() + && self.clearance > 0.0 + && self.clearance <= 100.0 + } +} +/// A differential pair: two named nets that carry one signal, routed side by +/// side with a fixed coupling gap and, optionally, matched total lengths. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct DiffPair { + pub id: Id, + /// Pair name, for example "USB_D". + pub name: String, + /// The positive-side net. + pub net_p: Id, + /// The negative-side net; must differ from the positive side. + pub net_n: Id, + /// Distance the two sides should keep from each other, in millimetres. + /// Copper closer than this reports a coupling finding. + pub gap: f64, + /// How far the two routed lengths may differ, in millimetres; absent + /// means length matching is not checked for this pair. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub length_tolerance: Option, + /// Rule profile that last applied this differential pair, when set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, +} +impl DiffPair { + fn valid(&self) -> bool { + !self.name.trim().is_empty() + && self.name.len() <= 64 + && self.net_p != self.net_n + && self.net_p != 0 + && self.net_n != 0 + && self.gap.is_finite() + && (0.02..=10.0).contains(&self.gap) + && self + .length_tolerance + .is_none_or(|t| t.is_finite() && (0.0..=100.0).contains(&t)) + } +} +/// Which kinds of copper a keepout keeps out. Every kind is forbidden unless +/// its flag is turned off, so a plain keepout excludes all copper. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct Keepout { + /// Tracks may not enter the area. + #[serde(default = "forbidden")] + pub tracks: bool, + /// Vias may not enter the area. + #[serde(default = "forbidden")] + pub vias: bool, + /// Pads may not enter the area. + #[serde(default = "forbidden")] + pub pads: bool, + /// Poured zones and other copper regions may not enter the area. + #[serde(default = "forbidden")] + pub zones: bool, +} +fn forbidden() -> bool { + true +} +impl Default for Keepout { + fn default() -> Self { + Self { + tracks: true, + vias: true, + pads: true, + zones: true, + } + } +} +/// A length-match group: several nets whose routed lengths must stay within +/// one tolerance of each other, such as the data lines of a parallel bus. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct LengthGroup { + pub id: Id, + /// Group name, for example "DDR_DATA0". + pub name: String, + /// Two to 32 distinct nets. + pub nets: Vec, + /// Largest allowed difference between the longest and shortest routed + /// net, in millimetres. + pub tolerance: f64, +} +impl LengthGroup { + fn valid(&self) -> bool { + let distinct: BTreeSet<&Id> = self.nets.iter().collect(); + !self.name.trim().is_empty() + && self.name.len() <= 64 + && (2..=32).contains(&self.nets.len()) + && distinct.len() == self.nets.len() + && !self.nets.contains(&0) + && self.tolerance.is_finite() + && (0.0..=100.0).contains(&self.tolerance) + } +} +/// A rectangular board area that demands a stricter minimum copper +/// separation: copper lying wholly inside the rectangle, on the matching +/// layer and net when those filters are set, must clear by at least the +/// area's gap. The area raises the required clearance; it never lowers the +/// net-pair requirement. +/// +/// With [`RuleArea::keepout`] set the area instead forbids copper: nothing of +/// a kind the keepout names may come within `clearance` of the rectangle. The +/// layer filter narrows a keepout to one copper side, and the net filter lets +/// that one net through, which is how a ground pour is allowed under a part +/// while every trace stays out. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct RuleArea { + pub id: Id, + /// Optional note describing the area, such as a sensor or high-voltage + /// zone. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// When set, the area only constrains copper of this net on one side of + /// each pair. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub net: Option, + /// When set, the area only constrains copper on this copper layer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layer: Option, + /// Minimum copper separation demanded inside the area, in millimetres. + pub clearance: f64, + /// When set, the area is a keepout: copper of the kinds it names may not + /// come within `clearance` of the rectangle. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub keepout: Option, + /// When set, components inside the area may not stand taller than this, + /// in millimetres: a height restriction for boards that must fit under a + /// cover or past another board. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_height: Option, + /// The rectangle itself. + pub region: RuleRegion, + /// Rule profile that last applied this area, when set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, +} +fn profile_tag_valid(tag: &Option) -> bool { + tag.as_ref().is_none_or(|s| !s.is_empty() && s.len() <= 64) +} +impl RuleArea { + /// True when this area keeps copper out on `layer` for `net`. A keepout + /// with a net filter lets that one net through; a keepout with a layer + /// filter only bites on that side of the board. + pub fn keepout_applies(&self, layer: Layer, net: Id) -> bool { + self.keepout.is_some() + && self.net.is_none_or(|n| n != net) + && self.layer.is_none_or(|l| l == layer) + } + /// The rectangle grown outward by the keepout clearance, which is the + /// copper-free margin a keepout demands. + pub fn keepout_rect(&self) -> RuleRegion { + let margin = self.clearance.max(0.0); + RuleRegion { + x: self.region.x - margin, + y: self.region.y - margin, + width: self.region.width + margin * 2.0, + height: self.region.height + margin * 2.0, + } + } + fn valid(&self) -> bool { + self.id != 0 + && self.clearance.is_finite() + && self.clearance > 0.0 + && self.clearance <= 100.0 + && self + .name + .as_ref() + .is_none_or(|n| !n.is_empty() && n.len() <= 64) + && self.region.width.is_finite() + && self.region.height.is_finite() + && self.region.width > 0.0 + && self.region.height > 0.0 + && self.region.width <= 1000.0 + && self.region.height <= 1000.0 + && self.region.x >= -1000.0 + && self.region.y >= -1000.0 + && self.region.x + self.region.width <= 1000.0 + && self.region.y + self.region.height <= 1000.0 + && self.max_height.is_none_or(|h| (0.1..=100.0).contains(&h)) + } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct PinRef { pub component: Id, pub pin: String, + /// Schematic unit copy when the same physical pin repeats on several units. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unit: Option, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Wire { @@ -146,12 +686,232 @@ pub struct Wire { pub from: PinRef, pub to: PinRef, } +/// A named annotation attached to a logical net: a local, global, +/// hierarchical or power label. Connectivity stays explicit: the label names a +/// net that a command already assigned; it never creates a net by matching names. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Label { + pub id: Id, + /// `label`, `global`, `hierarchical`, `power` or `junction`. + pub kind: String, + /// Logical net the label names. + pub net: Id, + /// Anchor position in millimetres. A junction stores its point on a wire. + pub position: Point, + /// Text rotation in degrees, ignored for junctions. + pub rotation: f64, + /// Bus notation carried by a bus label, like DB*8; empty for every other + /// kind. A bus label names a group of nets, so it carries no single net. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub text: String, +} +impl Label { + pub const KINDS: [&'static str; 6] = [ + "label", + "global", + "hierarchical", + "power", + "junction", + "bus", + ]; +} +/// A flag marking a pin intentionally unconnected, that +/// suppresses its unconnected-pin violation. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct NoConnectFlag { + pub id: Id, + pub pin: PinRef, +} +/// A named hierarchy port placed on a schematic page, declaring that a net +/// enters or leaves that page here. Ports sharing a name on different pages +/// carry the same net; the engine enforces that when placing them. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct Port { + pub id: Id, + pub name: String, + pub net: Id, + /// The page the port sits on; 0 is the root page. + pub sheet: Id, + pub position: Point, +} +/// Free-form schematic wire drawn by the user with explicit vertices. +/// Connectivity stays explicit: `net` is assigned by a command, never inferred from crossings. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct DrawnWire { + pub id: Id, + /// Logical net carried by this wire, or none until it is assigned. + pub net: Option, + /// Vertices in draw order, in millimetres. + pub points: Vec, +} +/// A free-standing drawing primitive for schematic annotations and board +/// graphics. Shapes are explicit; nothing is inferred from geometry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Graphic { + pub id: Id, + /// `schematic` or `board`. + pub layer: String, + /// `line`, `rect`, `circle`, `arc`, `polygon` or `text`. + pub shape: String, + /// Vertices in draw order, in millimetres. A circle stores its centre first, + /// an arc stores start, middle and end, and text stores its anchor. + pub points: Vec, + /// Stroke width in millimetres, circle and arc radius, or text size. + pub width: f64, + /// Text content for the text shape, empty for every other shape. + pub text: String, + /// Fabrication sublayer for a board graphic: `F.SilkS`, `B.SilkS`, + /// `F.Mask` or `B.Mask`. Empty keeps the legacy behaviour (front + /// artwork only, no mask meaning). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub sublayer: String, + /// Stroke colour as `#rrggbb`; empty draws in the theme's default ink. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub color: String, +} +/// Fabrication sublayer names a board graphic may carry. +pub const GRAPHIC_SUBLAYERS: [&str; 4] = ["F.SilkS", "B.SilkS", "F.Mask", "B.Mask"]; +impl Graphic { + /// Required vertex count for each shape, or none for an unknown shape. + pub fn vertex_rule(shape: &str) -> Option<(usize, usize)> { + match shape { + "line" | "rect" => Some((2, 2)), + "arc" => Some((3, 3)), + "circle" | "text" => Some((1, 1)), + "polygon" => Some((3, 256)), + _ => None, + } + } + /// Polyline used to render the shape, or none for text. + pub fn outline(&self) -> Option> { + let (min, _) = Self::vertex_rule(self.shape.as_str())?; + if self.points.len() < min { + return None; + } + let first = self.points.first().copied()?; + match self.shape.as_str() { + "line" => Some(self.points.clone()), + "rect" => { + let opposite = self.points.get(1).copied()?; + Some(vec![ + first, + Point::new(opposite.x, first.y), + opposite, + Point::new(first.x, opposite.y), + first, + ]) + } + "polygon" => { + let mut points = self.points.clone(); + points.push(first); + Some(points) + } + "circle" => { + let start = Point::new(first.x + self.width, first.y); + Some(self.arc_points(first, start, start, self.width, 0.0, 360.0)) + } + "arc" => { + let middle = self.points.get(1).copied()?; + let last = self.points.get(2).copied()?; + let (centre, radius) = circle_through(first, middle, last)?; + let angle = |p: Point| (p.y - centre.y).atan2(p.x - centre.x).to_degrees(); + let (start, mid, end) = (angle(first), angle(middle), angle(last)); + // The middle point decides which way the arc sweeps. + let counter_clockwise = on_arc(start, end, mid); + let sweep = if counter_clockwise { + wrap_360(end - start) + } else { + wrap_360(end - start) - 360.0 + }; + Some(self.arc_points(centre, first, last, radius, start, sweep)) + } + _ => None, + } + } + /// Samples a circular path without any trigonometric discontinuity at the ends: + /// the first and last samples are the exact supplied endpoints. + fn arc_points( + &self, + centre: Point, + start: Point, + end: Point, + radius: f64, + start_degrees: f64, + sweep_degrees: f64, + ) -> Vec { + if !radius.is_finite() || radius <= 0.0 || !sweep_degrees.is_finite() { + return vec![start]; + } + let steps = (sweep_degrees.abs() / 15.0).ceil() as usize; + let steps = steps.clamp(1, 256); + let mut points = Vec::with_capacity(steps + 1); + points.push(start); + for step in 1..steps { + let angle = start_degrees + sweep_degrees * step as f64 / steps as f64; + let (sin, cos) = angle.to_radians().sin_cos(); + points.push(Point::new(centre.x + radius * cos, centre.y + radius * sin)); + } + points.push(end); + points + } +} +/// Centre and radius of the unique circle through three points, or none when the +/// points are collinear. +pub fn circle_through(a: Point, b: Point, c: Point) -> Option<(Point, f64)> { + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + if !d.is_finite() || d.abs() < 1e-9 { + return None; + } + let (a2, b2, c2) = ( + a.x * a.x + a.y * a.y, + b.x * b.x + b.y * b.y, + c.x * c.x + c.y * c.y, + ); + let centre = Point::new( + (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, + (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d, + ); + if !centre.valid() { + return None; + } + let radius = centre.distance(a); + if !positive(radius) { + return None; + } + Some((centre, radius)) +} +/// Wraps degrees into 0..360 so a sweep length can be computed. +fn wrap_360(degrees: f64) -> f64 { + let value = degrees % 360.0; + if value < 0.0 { value + 360.0 } else { value } +} +/// Whether an angle lies on the counter-clockwise arc from start to end. +fn on_arc(start: f64, end: f64, test: f64) -> bool { + wrap_360(test - start) <= wrap_360(end - start) +} +/// A pad's drilled hole as a capsule: end centres, radius and plating. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PadDrill { + /// One end centre of the hole, in footprint coordinates. + pub start: Point, + /// The other end centre; the same point for a round hole. + pub end: Point, + /// Hole radius in millimetres. + pub radius: f64, + /// True when the hole wall is plated. + pub plated: bool, +} #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Pad { pub number: String, pub offset: Point, pub diameter: f64, pub net: Option, + /// True when this pad is castellated: plated and cut at a board edge so + /// another board can be soldered onto it. Absent means not castellated. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub castellated: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub geometry: Option, } @@ -165,12 +925,15 @@ impl Pad { hole.size = drill.size; hole.shape = "oval".into(); hole.roundrect_ratio = None; + hole.chamfer = None; + hole.polygon.clear(); hole.position = self.offset.offset(drill.offset.rotate(-g.rotation)); Pad { number: String::new(), offset: hole.position, diameter: drill.size.x.min(drill.size.y), net: None, + castellated: None, geometry: Some(hole), } .outline_points() @@ -189,81 +952,302 @@ impl Pad { }) .unwrap_or(0.0) } - /// Closed convex copper outline in footprint-local coordinates. + /// Closed copper outline in footprint-local coordinates. Every shape except + /// `custom` is convex; custom outlines are simple polygons. pub fn outline_points(&self) -> Vec { - let (size, rotation, shape, ratio) = self - .geometry - .as_ref() - .map(|p| { - ( - p.size, - p.rotation, - p.shape.as_str(), - p.roundrect_ratio.unwrap_or(0.0), - ) - }) - .unwrap_or((Point::new(self.diameter, self.diameter), 0.0, "circle", 0.0)); - let hx = size.x / 2.0; - let hy = size.y / 2.0; - let radius = match shape { - "circle" | "oval" => hx.min(hy), - "roundrect" => size.x.min(size.y) * ratio, - _ => 0.0, + let Some(g) = &self.geometry else { + return self.finish_outline(rounded_rect( + Point::new(self.diameter, self.diameter), + self.diameter / 2.0, + )); }; - let mut points = vec![]; - if radius <= 1e-9 { - points.extend([ - Point::new(-hx, -hy), - Point::new(hx, -hy), - Point::new(hx, hy), - Point::new(-hx, hy), - ]); - } else { - for (x, y, start) in [ - (hx - radius, hy - radius, 0.0), - (-hx + radius, hy - radius, 90.0), - (-hx + radius, -hy + radius, 180.0), - (hx - radius, -hy + radius, 270.0), - ] { - for i in 0..=16 { - let angle = (start + i as f64 * 90.0 / 16.0).to_radians(); - points.push(Point::new( - x + radius * angle.cos(), - y + radius * angle.sin(), - )); - } - } + let points = match g.shape_kind() { + PadShape::Circle | PadShape::Oval => rounded_rect(g.size, g.size.x.min(g.size.y) / 2.0), + PadShape::RoundRect { ratio } => rounded_rect(g.size, g.size.x.min(g.size.y) * ratio), + PadShape::Rect | PadShape::Unsupported => rounded_rect(g.size, 0.0), + PadShape::Chamfered(chamfer) => chamfered_rect(g.size, chamfer), + PadShape::Custom { polygon } => polygon.to_vec(), + }; + let mut points = self.finish_outline(points); + for p in &mut points { + *p = self.offset.offset(p.rotate(-g.rotation)); + } + points + } + /// The drilled hole of this pad as a capsule in footprint coordinates + /// before the footprint is placed: its two end centres, its radius, and + /// whether the wall is plated. A round hole has equal ends. `None` when the + /// pad has no drill. + /// + /// # Rules + /// The hole centre includes the drill offset, turned with the pad, the same + /// way the copper snapshot in `crates/rules/src/lib.rs` places it. + /// + /// # Dependencies + /// `pcbcraft_library::Drill` in `crates/library/src/lib.rs`. + /// + /// # Do not + /// Do not apply the footprint position or rotation here; callers do. + pub fn drill_capsule(&self) -> Option { + let g = self.geometry.as_ref()?; + let d = g.drill.as_ref()?; + let radius = d.size.x.min(d.size.y) / 2.0; + let axis = Point::new( + (d.size.x / 2.0 - radius).max(0.0), + (d.size.y / 2.0 - radius).max(0.0), + ); + let at = |local: Point| self.offset.offset(local.rotate(-g.rotation)); + Some(PadDrill { + start: at(d.offset.offset(axis)), + end: at(d.offset.offset(Point::new(-axis.x, -axis.y))), + radius, + plated: g.pad_type != "np_thru_hole" && g.pad_type != "unplated", + }) + } + /// Thinnest copper ring left around the plated hole of this pad, in + /// millimetres, after adding `allowance` to the finished drill to get the + /// tool size. `None` for a pad with no plated hole. + /// + /// # Rules + /// The ring is measured to the nearest pad edge from the hole's true + /// centre, so an offset or oval drill reports its thin side. A round pad + /// uses its exact radius rather than the sampled outline. + /// + /// # Dependencies + /// `Pad::drill_capsule` and `Pad::outline_points` in this file. + /// + /// # Do not + /// Do not use the larger pad side; that hides a thin ring. + pub fn min_annular_ring(&self, allowance: f64) -> Option { + let hole = self.drill_capsule().filter(|h| h.plated)?; + let tool_radius = hole.radius + allowance / 2.0; + if let Some(g) = &self.geometry + && matches!(g.shape_kind(), PadShape::Circle) + { + let reach = self + .offset + .distance(hole.start) + .max(self.offset.distance(hole.end)); + return Some(g.size.x.min(g.size.y) / 2.0 - reach - tool_radius); } + let outline = self.outline_points(); + outline + .windows(2) + .map(|edge| pcbcraft_geom::segment_distance(hole.start, hole.end, edge[0], edge[1])) + .reduce(f64::min) + .map(|d| d - tool_radius) + } + fn finish_outline(&self, mut points: Vec) -> Vec { if let Some(first) = points.first().copied() { points.push(first); } + if self.geometry.is_none() { + for p in &mut points { + *p = self.offset.offset(*p); + } + } points - .into_iter() - .map(|p| self.offset.offset(p.rotate(-rotation))) - .collect() + } + /// True when the outline can be filled as one convex polygon. + pub fn outline_is_convex(&self) -> bool { + !self + .geometry + .as_ref() + .is_some_and(|g| matches!(g.shape_kind(), PadShape::Custom { .. })) + } + /// Radius of a disc about the pad origin that is certainly copper; used for + /// conservative connectivity. + pub fn contact_radius(&self) -> f64 { + let Some(g) = &self.geometry else { + return self.diameter / 2.0; + }; + match g.shape_kind() { + PadShape::Chamfered(chamfer) => { + let (hx, hy) = (g.size.x / 2.0, g.size.y / 2.0); + let cut = g.size.x.min(g.size.y) * chamfer.ratio; + hx.min(hy) + .min((hx + hy - cut) / std::f64::consts::SQRT_2) + .max(0.0) + } + _ => self.diameter / 2.0, + } } pub fn bounding_radius(&self) -> f64 { self.geometry .as_ref() - .map(|p| { - if p.shape == "circle" { - p.size.x / 2.0 - } else { - p.size.x.hypot(p.size.y) / 2.0 - } + .map(|p| match p.shape_kind() { + PadShape::Circle => p.size.x / 2.0, + PadShape::Custom { polygon } => polygon + .iter() + .map(|v| v.x.hypot(v.y)) + .fold(p.size.x.hypot(p.size.y) / 2.0, f64::max), + _ => p.size.x.hypot(p.size.y) / 2.0, }) .unwrap_or(self.diameter / 2.0) } } +/// Open vertex ring of a rectangle with circular corners of the given radius. +fn rounded_rect(size: Point, radius: f64) -> Vec { + let hx = size.x / 2.0; + let hy = size.y / 2.0; + if radius <= 1e-9 { + return vec![ + Point::new(-hx, -hy), + Point::new(hx, -hy), + Point::new(hx, hy), + Point::new(-hx, hy), + ]; + } + let mut points = Vec::with_capacity(68); + for (x, y, start) in [ + (hx - radius, hy - radius, 0.0), + (-hx + radius, hy - radius, 90.0), + (-hx + radius, -hy + radius, 180.0), + (hx - radius, -hy + radius, 270.0), + ] { + for i in 0..=16 { + let angle = (start + i as f64 * 90.0 / 16.0_f64).to_radians(); + points.push(Point::new( + x + radius * angle.cos(), + y + radius * angle.sin(), + )); + } + } + points +} +/// Open vertex ring of a rectangle with straight cuts at the selected corners. +/// Corner names are pad-local with y pointing down. +pub fn chamfered_rect(size: Point, chamfer: pcbcraft_library::PadChamfer) -> Vec { + let hx = size.x / 2.0; + let hy = size.y / 2.0; + let cut = size.x.min(size.y) * chamfer.ratio; + let c = chamfer.corners; + let mut points = Vec::with_capacity(8); + let mut corner = |cut_it: bool, square: Point, before: Point, after: Point| { + if cut_it { + points.extend([before, after]); + } else { + points.push(square); + } + }; + corner( + c.bottom_right, + Point::new(hx, hy), + Point::new(hx, hy - cut), + Point::new(hx - cut, hy), + ); + corner( + c.bottom_left, + Point::new(-hx, hy), + Point::new(-hx + cut, hy), + Point::new(-hx, hy - cut), + ); + corner( + c.top_left, + Point::new(-hx, -hy), + Point::new(-hx, -hy + cut), + Point::new(-hx + cut, -hy), + ); + corner( + c.top_right, + Point::new(hx, -hy), + Point::new(hx - cut, -hy), + Point::new(hx, -hy + cut), + ); + // A 0.5 ratio on a square side makes neighbouring cuts meet; drop the + // repeated meeting vertices so the ring stays simple. + points.dedup_by(|a, b| a.distance(*b) < 1e-12); + if points.len() > 1 + && points + .first() + .zip(points.last()) + .is_some_and(|(a, b)| a.distance(*b) < 1e-12) + { + points.pop(); + } + points +} #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Footprint { pub id: Id, pub component: Id, pub position: Point, pub rotation: f64, + /// True when this footprint is locked in place so placement commands refuse + /// to move it. Absent means unlocked. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + /// Which board side the footprint is soldered on. Absent means the top. + #[serde(default, skip_serializing_if = "Option::is_none")] + /// Board side the part is mounted on; absent means the top. Pad copper and + /// the silk, mask and paste layers are derived from it, never stored per pad. + pub side: Option, pub pads: Vec, } +/// Swap `F.` and `B.` layer name prefixes; other names are unchanged. +/// A library pad as it sits when its part is mounted on the bottom: x offset, +/// rotation and drill offset turned about the part's local vertical axis. +/// +/// # Rules +/// - Layer names stay as authored; `Footprint::pad_geometry_layers` swaps them. +/// +/// # Do not +/// - Write the result back to the library; packages stay authored on the top. +pub fn mirrored_pad_for_bottom( + source: &pcbcraft_library::FootprintPad, +) -> pcbcraft_library::FootprintPad { + let mut pad = source.clone(); + pad.position = Point::new(-pad.position.x, pad.position.y); + pad.rotation = -pad.rotation; + if let Some(drill) = &mut pad.drill { + drill.offset = Point::new(-drill.offset.x, drill.offset.y); + } + pad +} +/// Swap the `F.` and `B.` prefix of a board layer name; other names such as +/// `*.Cu` pass through unchanged. +pub fn swap_board_side_layer(name: &str) -> String { + if let Some(rest) = name.strip_prefix("F.") { + return format!("B.{rest}"); + } + if let Some(rest) = name.strip_prefix("B.") { + return format!("F.{rest}"); + } + name.to_string() +} impl Footprint { + /// The copper side the part is mounted on: the top unless `side` is set. + pub fn board_side(&self) -> Layer { + self.side.unwrap_or(Layer::Front) + } + /// Copper layer for a surface-mount pad; through-hole pads are handled on + /// both layers by callers that iterate copper. + /// + /// # Rules + /// - Derived from `board_side`; pads carry no side of their own. + pub fn pad_layer(&self, _pad: &Pad) -> Layer { + self.board_side() + } + /// Whether the pad has copper on `layer`: through-hole pads on both outer + /// layers, surface pads only on the part's own side. + pub fn pad_on_copper(&self, pad: &Pad, layer: Layer) -> bool { + match pad.geometry.as_ref() { + None => layer == Layer::Front, + Some(g) if g.pad_type == "thru_hole" || g.layers.iter().any(|l| l == "*.Cu") => true, + Some(_) => self.board_side() == layer, + } + } + /// The pad's geometry layer names as placed: as authored on the top, with + /// the `F.` and `B.` prefixes swapped on the bottom. + pub fn pad_geometry_layers(&self, pad: &Pad) -> Vec { + let Some(g) = pad.geometry.as_ref() else { + return vec!["F.Cu".into(), "F.Mask".into()]; + }; + if self.board_side() == Layer::Front { + return g.layers.clone(); + } + g.layers.iter().map(|l| swap_board_side_layer(l)).collect() + } pub fn drawing_points(&self, project: &Project) -> Vec { let mut points: Vec = self.pads.iter().flat_map(|p| p.outline_points()).collect(); if let Some(library) = project @@ -282,25 +1266,120 @@ impl Footprint { self.pads .iter() .find(|p| p.number == number) - .map(|p| self.position.offset(p.offset.rotate(-self.rotation))) + .map(|p| self.pad_world_position(p)) + } + /// World position of a placed pad, including mechanical pads with no number. + pub fn pad_world_position(&self, pad: &Pad) -> Point { + self.position.offset(pad.offset.rotate(-self.rotation)) } } -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] -pub enum Layer { - #[serde(rename = "F.Cu")] - Front, - #[serde(rename = "B.Cu")] - Back, -} +/// Index of a copper layer: 0 is top, the highest index is bottom. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Layer(u8); + +/// Maximum copper layers the document model supports. +pub const MAX_COPPER_LAYERS: u8 = 32; + impl Layer { + #[allow(clippy::upper_case_acronyms, non_upper_case_globals)] + pub const Front: Layer = Layer(0); + #[allow(clippy::upper_case_acronyms, non_upper_case_globals)] + pub const Back: Layer = Layer(1); + + pub fn from_index(index: u8) -> Result { + if index >= MAX_COPPER_LAYERS { + Err(format!( + "copper layer index must be below {MAX_COPPER_LAYERS}" + )) + } else { + Ok(Layer(index)) + } + } + + pub fn index(self) -> u8 { + self.0 + } + + /// Legacy two-layer shorthand; prefer [`Project::layer_name`] when the + /// stackup may carry inner copper. pub fn name(self) -> &'static str { - match self { - Self::Front => "F.Cu", - Self::Back => "B.Cu", + match self.0 { + 0 => "F.Cu", + 1 => "B.Cu", + _ => "F.Cu", } } -} -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] + + /// Plain-English layer name for people who have never seen copper-layer + /// shorthand; file formats keep using stackup-aware names from the project. + pub fn label(self) -> &'static str { + match self.0 { + 0 => "Top", + 1 => "Bottom", + _ => "Inner", + } + } + + fn from_file_str(s: &str) -> Result { + let s = s.trim(); + if s.is_empty() { + return Err("copper layer name is empty".into()); + } + if s == "F.Cu" { + return Ok(Layer::Front); + } + if s == "B.Cu" { + return Ok(Layer::Back); + } + if let Some(rest) = s.strip_prefix('L') + && let Ok(n) = rest.parse::() + && (1..=MAX_COPPER_LAYERS as u32).contains(&n) + { + return Layer::from_index((n - 1) as u8); + } + if let Some(rest) = s.strip_prefix("In").and_then(|r| r.strip_suffix(".Cu")) + && let Ok(n) = rest.parse::() + && n > 0 + && n < MAX_COPPER_LAYERS + { + return Layer::from_index(n); + } + Err(format!("unknown copper layer {s:?}")) + } + + fn to_file_str(self) -> String { + if self.0 == 0 { + "F.Cu".into() + } else if self.0 == 1 { + "B.Cu".into() + } else { + format!("In{}.Cu", self.0) + } + } +} + +impl Serialize for Layer { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.to_file_str()) + } +} + +impl<'de> Deserialize<'de> for Layer { + fn deserialize>(deserializer: D) -> Result { + struct LayerVisitor; + impl Visitor<'_> for LayerVisitor { + type Value = Layer; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a copper layer name such as F.Cu, B.Cu, In1.Cu or L1") + } + fn visit_str(self, v: &str) -> Result { + Layer::from_file_str(v).map_err(de::Error::custom) + } + } + deserializer.deserialize_str(LayerVisitor) + } +} +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Track { pub id: Id, pub net: Id, @@ -308,6 +1387,291 @@ pub struct Track { pub end: Point, pub width: f64, pub layer: Layer, + /// Midpoint of a circular arc through start and end; absent means a + /// straight segment. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub arc: Option, +} +impl Track { + /// The circular arc if the track stores a usable midpoint. + pub fn curve(&self) -> Option { + pcbcraft_geom::arc_through(self.start, self.arc?, self.end) + } + /// Routed length in millimetres: the arc if curved, the chord otherwise. + pub fn length(&self) -> f64 { + self.curve() + .map_or_else(|| self.start.distance(self.end), |arc| arc.length()) + } +} +/// A plated via. With no span it joins the top and bottom copper layers; a +/// span limits it to the copper layers from `from_layer` down to `to_layer` +/// (blind when one end is an outer layer, buried when neither is). It +/// conducts only on the layers in its span. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Via { + pub id: Id, + pub net: Id, + /// Centre position in millimetres. + pub position: Point, + /// Outer copper pad diameter in millimetres. + pub diameter: f64, + /// Drilled hole diameter in millimetres; zero keeps an unplated blind hole. + pub drill: f64, + /// Upper end of the copper span; none means the top layer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_layer: Option, + /// Lower end of the copper span; none means the bottom layer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_layer: Option, + /// How this via is protected from the board face, or `None` to follow the + /// board default. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub covering: Option, +} +/// How a via hole is protected, named after the seven types of the via +/// protection standard (IPC-4761). The types that close the hole under the +/// solder mask lose their mask opening on fabrication plots. +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum ViaCovering { + /// No protection: the mask opens around the hole. + #[default] + Open, + /// Type I: mask tents the hole. + Tented, + /// Type II: mask tents and covers the hole. + TentedCovered, + /// Type III: the hole is plugged. + Plugged, + /// Type IV: the hole is plugged and covered. + PluggedCovered, + /// Type V: the hole is filled. + Filled, + /// Type VI: the hole is filled and covered. + FilledCovered, + /// Type VII: the hole is filled and capped with copper. + FilledCapped, +} +impl ViaCovering { + /// Every covering, in the order the standard lists them. + pub const ALL: [ViaCovering; 8] = [ + ViaCovering::Open, + ViaCovering::Tented, + ViaCovering::TentedCovered, + ViaCovering::Plugged, + ViaCovering::PluggedCovered, + ViaCovering::Filled, + ViaCovering::FilledCovered, + ViaCovering::FilledCapped, + ]; + /// Short text for fabrication notes, for example `tented` or `filled and capped`. + pub fn label(self) -> &'static str { + match self { + ViaCovering::Open => "open", + ViaCovering::Tented => "tented", + ViaCovering::TentedCovered => "tented and covered", + ViaCovering::Plugged => "plugged", + ViaCovering::PluggedCovered => "plugged and covered", + ViaCovering::Filled => "filled", + ViaCovering::FilledCovered => "filled and covered", + ViaCovering::FilledCapped => "filled and capped", + } + } + /// Command token, for example `tented_covered`. + pub fn token(self) -> &'static str { + match self { + ViaCovering::Open => "open", + ViaCovering::Tented => "tented", + ViaCovering::TentedCovered => "tented_covered", + ViaCovering::Plugged => "plugged", + ViaCovering::PluggedCovered => "plugged_covered", + ViaCovering::Filled => "filled", + ViaCovering::FilledCovered => "filled_covered", + ViaCovering::FilledCapped => "filled_capped", + } + } + /// Whether the solder mask keeps an opening around the hole. + pub fn keeps_mask_opening(self) -> bool { + self == ViaCovering::Open + } +} +impl Via { + /// The covering that applies to this via: its own, else the board default. + pub fn effective_covering(&self, board: &Board) -> ViaCovering { + self.covering.unwrap_or(board.via_covering_default) + } +} +/// What a via is, derived from its span and the stackup. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ViaKind { + /// Top to bottom. + Through, + /// One end on an outer layer. + Blind, + /// Both ends on inner layers. + Buried, + /// A short, shallow blind or buried via that a laser can drill. + Micro, +} +impl ViaKind { + /// Plain-language name. + pub fn label(self) -> &'static str { + match self { + ViaKind::Through => "Through", + ViaKind::Blind => "Blind", + ViaKind::Buried => "Buried", + ViaKind::Micro => "Micro", + } + } +} +/// Deepest span a via can have and still count as a micro via, in millimetres. +pub const MICRO_VIA_MAX_DEPTH: f64 = 0.25; +/// A solid copper region on one layer, bounded by a closed polygon and +/// belonging to a net. Same-net copper that falls inside the outline conducts +/// to the zone; the zone keeps its clearance from copper of other nets. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct CopperZone { + pub id: Id, + pub net: Id, + pub layer: Layer, + /// Closed outline in millimetres: at least three distinct vertices with the + /// first vertex repeated last. + pub outline: Vec, + /// Closed outlines removed from this zone: copper of other nets, or empty + /// board, inside a cutout never conducts through the zone. + #[serde(default)] + pub cutouts: Vec>, + /// Whether the zone is poured. An unfilled zone is drawn as a bare + /// outline and carries no copper: it neither conducts to net copper + /// inside it nor demands clearance from it until it is filled again. + #[serde(default = "poured")] + pub filled: bool, + /// Optional tag naming the tool that generated this copper, such as + /// "teardrop", so the pass can find and redo its own shapes. Absent for + /// hand-drawn zones. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option, + /// How the poured copper meets same-net copper inside the outline. Absent + /// means the defaults: solid to vias, four spokes to plated pads, islands + /// removed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pour: Option, +} +/// How a poured zone meets one kind of same-net copper that sits inside its +/// outline. +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ZoneConnect { + /// Copper joins the zone directly, with no gap around it. + #[default] + Solid, + /// Copper keeps a gap all round and joins through narrow spokes, so a + /// soldering iron can heat the joint without draining the whole pour. + Relief, + /// Copper keeps a gap all round and does not join the zone at all. + None, +} +impl ZoneConnect { + /// Whether copper of this kind joins the pour through thermal spokes. + pub fn relief(self) -> bool { + matches!(self, Self::Relief) + } +} +/// What a pour does with copper that touches nothing of its own net: a +/// detached piece that a fab etch bath can lift off the board. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ZoneIslands { + /// Keep every detached piece and report it. + Keep, + /// Drop every detached piece from the fill. + #[default] + Remove, + /// Keep detached pieces at least this many square millimetres, so a large + /// deliberate shield stays and crumbs go. + RemoveBelow(f64), +} +/// Per-zone pour settings: how the fill meets same-net copper, how narrow a +/// neck may survive, and what happens to detached copper. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ZonePour { + /// How plated through-hole pads inside the zone join the pour. + #[serde(default)] + pub pad_connect: ZoneConnect, + /// How vias inside the zone join the pour. + #[serde(default)] + pub via_connect: ZoneConnect, + /// Gap between pad copper and the pour, in millimetres, when a pad joins + /// through spokes or not at all. + #[serde(default = "pour_gap")] + pub relief_gap: f64, + /// Width of each thermal spoke, in millimetres. + #[serde(default = "pour_spoke")] + pub spoke_width: f64, + /// Spokes per pad: two or four, aligned to the pad rotation. + #[serde(default = "pour_spokes")] + pub spokes: u8, + /// Narrowest copper the pour keeps, in millimetres: narrower necks are + /// removed before the fill ships. Absent means the narrowest track already + /// on the board, so a pour is never thinner than allowed copper. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min_width: Option, + /// What happens to copper that touches nothing of its own net. + #[serde(default)] + pub islands: ZoneIslands, +} +fn pour_gap() -> f64 { + 0.25 +} +fn pour_spoke() -> f64 { + 0.3 +} +fn pour_spokes() -> u8 { + 4 +} +impl Default for ZonePour { + fn default() -> Self { + Self { + pad_connect: ZoneConnect::Relief, + via_connect: ZoneConnect::Solid, + relief_gap: pour_gap(), + spoke_width: pour_spoke(), + spokes: pour_spokes(), + min_width: None, + islands: ZoneIslands::Remove, + } + } +} +impl ZonePour { + /// True when every setting is finite and inside the bounds a pour accepts. + pub fn valid(&self) -> bool { + self.relief_gap.is_finite() + && (0.05..=2.0).contains(&self.relief_gap) + && self.spoke_width.is_finite() + && (0.05..=5.0).contains(&self.spoke_width) + && matches!(self.spokes, 2 | 4) + && self + .min_width + .is_none_or(|w| w.is_finite() && (0.05..=5.0).contains(&w)) + && match self.islands { + ZoneIslands::Keep | ZoneIslands::Remove => true, + ZoneIslands::RemoveBelow(area) => { + area.is_finite() && (0.0..=10_000.0).contains(&area) + } + } + } +} +impl CopperZone { + /// The pour settings in force: the zone's own, or the defaults when it + /// carries none. + pub fn pour_settings(&self) -> ZonePour { + self.pour.unwrap_or_default() + } + /// True when this zone is generated copper, such as a teardrop, rather + /// than an area the designer drew. + pub fn is_generated(&self) -> bool { + self.kind.as_deref() == Some("teardrop") + } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Cutout { @@ -315,143 +1679,1909 @@ pub struct Cutout { pub center: Point, pub radius: f64, } -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct Board { +/// A rectangular area that silences one check code for objects inside it. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)] +pub struct RuleRegion { + /// Lower-left corner in millimetres. + pub x: f64, + pub y: f64, + /// Extent in millimetres; must be positive. pub width: f64, pub height: f64, - pub thickness: f64, - pub clearance: f64, - pub footprints: Vec, - pub tracks: Vec, - pub cutouts: Vec, } +/// A text label drawn on the board, such as an assembly note or a marking. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct Project { - pub format: String, - pub version: u32, - pub name: String, - pub components: Vec, - pub nets: Vec, - pub wires: Vec, - pub board: Board, +pub struct BoardText { + pub id: Id, + /// The exact string to draw. + pub text: String, + /// Anchor position in millimetres: the lower-left of the first glyph. + pub position: Point, + /// Glyph height in millimetres. + pub size: f64, + /// Board side the label belongs to. + pub layer: Layer, + /// Text rotation in degrees about the anchor. #[serde(default)] - pub library: ProjectLibrary, + pub rotation: f64, + /// The component whose reference, value, footprint name and field keys + /// resolve `${...}` tokens in this text at draw and export time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub component: Option, } -#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct ProjectLibrary { - #[serde(default)] - pub notices: Vec, - pub symbols: Vec, - pub footprints: Vec, +/// Settings for a UV flatbed printer that registers artwork on a camera photo. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct UvPrinterProfile { + pub name: String, + pub bed_width_mm: f64, + pub bed_height_mm: f64, + #[serde(default = "default_uv_dpi_options")] + pub dpi_options: Vec, + #[serde(default = "default_uv_white_choke")] + pub white_choke_mm: f64, + #[serde(default = "default_uv_bleed")] + pub default_bleed_mm: f64, + #[serde(default = "default_uv_pad_clearance")] + pub pad_clearance_mm: f64, + pub min_text_height_mm: f64, + pub min_stroke_mm: f64, + #[serde(default = "default_uv_channels")] + pub channels: Vec, + pub max_substrate_height_mm: f64, + #[serde(default = "default_uv_registration")] + pub registration: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mask_colour: Option, } -impl ProjectLibrary { + +fn default_uv_dpi_options() -> Vec { + vec![720, 1440] +} + +fn default_uv_white_choke() -> f64 { + 0.2 +} + +fn default_uv_bleed() -> f64 { + 0.3 +} + +fn default_uv_pad_clearance() -> f64 { + 0.15 +} + +fn default_uv_channels() -> Vec { + vec!["cmyk".into(), "white".into(), "gloss".into()] +} + +fn default_uv_registration() -> String { + "camera_photo".into() +} + +impl UvPrinterProfile { pub fn validate(&self) -> Result<(), String> { - if self.notices.len() > 256 || self.notices.iter().any(|s| s.len() > 128 * 1024) { - return Err("library provenance notice limit exceeded".into()); + if self.name.trim().is_empty() || self.name.len() > 64 { + return Err("uv printer profile name must be 1 to 64 bytes".into()); } - if self.symbols.len() > 256 || self.footprints.len() > 256 { - return Err("project library supports at most 256 symbols and 256 footprints".into()); + if !(50.0..=2000.0).contains(&self.bed_width_mm) + || !(50.0..=2000.0).contains(&self.bed_height_mm) + { + return Err("uv printer bed size is out of range".into()); } - let mut names = BTreeSet::new(); - for s in &self.symbols { - s.validate().map_err(|e| e.to_string())?; - if !names.insert(&s.name) { - return Err("duplicate library symbol name".into()); - } + if self.dpi_options.is_empty() || self.dpi_options.len() > 8 { + return Err("uv printer needs one to eight dpi choices".into()); } - names.clear(); - for f in &self.footprints { - f.validate().map_err(|e| e.to_string())?; - if !names.insert(&f.name) { - return Err("duplicate library footprint name".into()); - } + if self.dpi_options.iter().any(|d| *d < 300 || *d > 4800) { + return Err("uv printer dpi choices must be between 300 and 4800".into()); + } + if !(0.0..=2.0).contains(&self.white_choke_mm) { + return Err("white underbase choke must be between 0 and 2 mm".into()); + } + if !(0.0..=5.0).contains(&self.default_bleed_mm) { + return Err("default bleed must be between 0 and 5 mm".into()); + } + if !(0.0..=1.0).contains(&self.pad_clearance_mm) { + return Err("pad clearance must be between 0 and 1 mm".into()); + } + if !(0.2..=5.0).contains(&self.min_text_height_mm) { + return Err("minimum text height is out of range".into()); + } + if !(0.05..=1.0).contains(&self.min_stroke_mm) { + return Err("minimum stroke width is out of range".into()); + } + if self.channels.is_empty() || self.channels.len() > 8 { + return Err("uv printer channel list is out of range".into()); + } + if !(1.0..=200.0).contains(&self.max_substrate_height_mm) { + return Err("max substrate height is out of range".into()); + } + if self.registration.len() > 64 { + return Err("registration method name is too long".into()); } Ok(()) } + + pub fn allows_dpi(&self, dpi: u32) -> bool { + self.dpi_options.contains(&dpi) + } + + pub fn has_gloss_channel(&self) -> bool { + self.channels.iter().any(|c| c == "gloss") + } } -impl Default for Project { - fn default() -> Self { - Self { - library: ProjectLibrary::default(), - format: "pcbcraft".into(), - version: 1, - name: "Untitled circuit".into(), - components: vec![], - nets: vec![], - wires: vec![], - board: Board { - width: 60.0, - height: 40.0, - thickness: 1.6, - clearance: 0.2, - footprints: vec![], - tracks: vec![], - cutouts: vec![], - }, - } + +/// Default profile for the eufyMake E1 UV flatbed (330 by 420 mm bed). +pub fn eufymake_e1_uv_printer() -> UvPrinterProfile { + UvPrinterProfile { + name: "eufyMake E1".into(), + bed_width_mm: 330.0, + bed_height_mm: 420.0, + dpi_options: default_uv_dpi_options(), + white_choke_mm: default_uv_white_choke(), + default_bleed_mm: default_uv_bleed(), + pad_clearance_mm: default_uv_pad_clearance(), + min_text_height_mm: 1.0, + min_stroke_mm: 0.12, + channels: default_uv_channels(), + max_substrate_height_mm: 60.0, + registration: default_uv_registration(), + mask_colour: None, } } +/// Settings for a galvo laser job handed to the shop laser program. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct LaserJobSettings { + /// Copper side to process: `front` or `back`. + pub side: String, + /// Subset of operation group ids (at most six). + #[serde(default)] + pub operations: Vec, + /// Output container: `svg` or `lcproj`. + pub format: String, + /// Mirror axis when exporting the bottom side: `x` or `y` (default `y`). + #[serde(default = "laser_job_mirror_default")] + pub mirror_axis: String, + /// Frame margin around the board bounding box, in millimetres. + #[serde(default)] + pub margin_mm: f64, + /// Clearance offset for isolation rings, in millimetres. + #[serde(default = "laser_job_isolation_default")] + pub isolation_width_mm: f64, + /// When true, emit copper rubout fill groups for kept copper regions. + #[serde(default)] + pub rubout: bool, + /// Percent shrink applied to paste stencil apertures (0 to 50). + #[serde(default)] + pub stencil_reduction_pct: f64, + /// Id of a `MachineProfile` with kind `laser_galvo` (see issue #389). + pub profile_id: String, +} -pub struct Template { - pub kind: &'static str, - pub label: &'static str, - pub prefix: &'static str, - pub value: &'static str, +fn laser_job_mirror_default() -> String { + "y".into() } -pub const TEMPLATES: &[Template] = &[ - Template { - kind: "resistor", - label: "Resistor", - prefix: "R", - value: "1k", - }, - Template { - kind: "led", - label: "LED", - prefix: "D", - value: "LED", - }, - Template { - kind: "capacitor", - label: "Capacitor", - prefix: "C", - value: "100nF", - }, - Template { - kind: "connector", - label: "2-pin connector", - prefix: "J", - value: "Power", - }, + +fn laser_job_isolation_default() -> f64 { + 0.05 +} + +impl LaserJobSettings { + pub const OPERATION_IDS: [&'static str; 6] = [ + "fiducials", + "isolation-cut", + "copper-rubout", + "mask-open", + "legend", + "stencil-cut", + ]; + + pub fn valid(&self) -> bool { + let side_ok = matches!(self.side.as_str(), "front" | "back"); + let format_ok = matches!(self.format.as_str(), "svg" | "lcproj"); + let mirror_ok = matches!(self.mirror_axis.as_str(), "x" | "y"); + let margin_ok = self.margin_mm.is_finite() && (0.0..=50.0).contains(&self.margin_mm); + let iso_ok = + self.isolation_width_mm.is_finite() && (0.01..=2.0).contains(&self.isolation_width_mm); + let stencil_ok = self.stencil_reduction_pct.is_finite() + && (0.0..=50.0).contains(&self.stencil_reduction_pct); + let profile_ok = !self.profile_id.trim().is_empty() && self.profile_id.len() <= 64; + let ops_ok = !self.operations.is_empty() + && self.operations.len() <= 6 + && self + .operations + .iter() + .all(|id| Self::OPERATION_IDS.contains(&id.as_str())); + side_ok + && format_ok + && mirror_ok + && margin_ok + && iso_ok + && stencil_ok + && profile_ok + && ops_ok + } +} + +/// Every export kind a saved output job may name, in the order the UI lists +/// them. This is the one list; validation, the engine schema and the job +/// runner all read it. +pub const OUTPUT_KINDS: [&str; 29] = [ + "gerbers", + "netlist", + "bom", + "placement", + "dxf", + "cmp", + "idf", + "vrml", + "step", + "pdf", + "svg", + "ipc2581", + "dsn", + "ipc356", + "gencad", + "hyperlynx", + "plot", + "report", + "ps", + "odb", + "hpgl", + "stackup", + "drill_chart", + "stats", + "layer_plots", + "panel", + "raster", + "laser_job", + "uv_print", ]; -pub fn component_template( - kind: &str, - id: Id, - reference: String, - position: Point, -) -> Option { - let t = TEMPLATES.iter().find(|t| t.kind == kind)?; - let names = if kind == "led" { - ["A", "K"] - } else if kind == "connector" { - ["+", "−"] - } else { - ["1", "2"] - }; - Some(Component { - units: vec![], - id, - reference, - value: t.value.into(), - kind: kind.into(), - position, - rotation: 0.0, - library_symbol: None, - library_footprint: None, - pins: names - .iter() - .enumerate() +/// How many export kinds one output job may hold. It is larger than the kind +/// list so a single job can still ask for every file a board needs. +pub const MAX_OUTPUT_KINDS: usize = 32; +/// A named fabrication output recipe: the export kinds a job writes when it +/// runs. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct OutputJob { + pub name: String, + /// Export kinds, each one of [`OUTPUT_KINDS`]. + pub kinds: Vec, +} +impl OutputJob { + fn valid(&self) -> bool { + !self.name.trim().is_empty() + && self.name.len() <= 64 + && !self.kinds.is_empty() + && self.kinds.len() <= MAX_OUTPUT_KINDS + && self + .kinds + .iter() + .all(|k| OUTPUT_KINDS.contains(&k.as_str())) + } +} +/// A single fabrication or assembly output file the design can regenerate and +/// mark stale when the board changes. +/// +/// Each record names one output the design can regenerate, where it lands +/// under the make folder, and the revision and hash it was last made at. The +/// hash is how the engine tells a stale file from a current one. +/// +/// # Rules +/// - `kind` is one of `ARTIFACT_KINDS`; `path` is relative with no `..`. +/// - `settings` stays within 4096 serialized bytes. +/// +/// # Dependencies +/// - `crates/io/src/generate.rs` turns a record into bytes. +/// - `crates/engine/src/artifacts.rs` owns the commands that edit it. +/// +/// # Do not +/// - Store absolute paths or generated bytes in the record. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Artifact { + /// Stable id of the artifact record. + pub id: Id, + /// Name shown in the list of outputs. + pub name: String, + /// Artifact kind, one of the names in the kind table below. + pub kind: String, + /// Layers the output covers; empty means the kind's default set. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub layers: Vec, + /// Kind-specific settings, checked when the output is generated. + #[serde(default)] + pub settings: serde_json::Value, + /// Machine profile id for outputs that target a machine. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub machine: Option, + /// Where the output is written, relative to the project folder. + pub path: String, + /// Design revision the output was last generated at. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub generated_at_revision: Option, + /// Hash of the last generated output, used to tell when it is stale. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub generated_hash: Option, + /// Name of the older output job this record was migrated from. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub job: Option, +} +/// The artifact kinds a record may name. Some have no writer yet; `generate` +/// refuses those with the issue that tracks them. +/// +/// # Rules +/// - Exact lowercase strings; saved files depend on them. +/// +/// # Dependencies +/// - `crates/io/src/generate.rs` dispatches on these. +/// +/// # Do not +/// - Rename or remove a kind that saved projects may hold. +pub const ARTIFACT_KINDS: &[&str] = &[ + "copper_plot", + "mask_plot", + "silk_plot", + "paste_plot", + "profile_plot", + "drill_plated", + "drill_unplated", + "drill_map", + "placement", + "bom", + "assembly_drawing", + "fab_drawing", + "raster_image", + "isolation_gcode", + "drill_gcode", + "outline_gcode", + "stencil", + "laser_path", + "package", +]; +const ARTIFACT_SETTINGS_MAX: usize = 4096; +impl Artifact { + /// True when `kind` is one of `ARTIFACT_KINDS`. + pub fn kind_valid(kind: &str) -> bool { + ARTIFACT_KINDS.contains(&kind) + } + /// Serialized size of `settings`, used for the 4096 byte limit. + pub fn settings_bytes(settings: &serde_json::Value) -> usize { + match serde_json::to_vec(settings) { + Ok(bytes) => bytes.len(), + Err(_) => usize::MAX, + } + } + /// True for a relative path of 1 to 256 bytes with no backslash, no leading + /// slash and no `..` segment, so an export cannot leave the make folder. + pub fn path_valid(path: &str) -> bool { + if path.is_empty() || path.len() > 256 || path.contains('\\') { + return false; + } + if path.starts_with('/') || path.starts_with("//") { + return false; + } + for segment in path.split('/') { + if segment == ".." { + return false; + } + } + true + } + fn hash_valid(hash: &str) -> bool { + hash.len() == 64 + && hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + } + /// True when every field is within its bound: name, kind, layers, + /// settings, machine, path, hash and job. `Project::validate` and the + /// engine commands both rely on it. + pub fn valid(&self) -> bool { + !self.name.trim().is_empty() + && self.name.len() <= 128 + && Self::kind_valid(&self.kind) + && self.layers.len() <= 32 + && self.layers.iter().all(|l| !l.is_empty() && l.len() <= 64) + && Self::settings_bytes(&self.settings) <= ARTIFACT_SETTINGS_MAX + && self + .machine + .as_ref() + .is_none_or(|m| !m.is_empty() && m.len() <= 64) + && Self::path_valid(&self.path) + && self + .generated_hash + .as_ref() + .is_none_or(|h| Self::hash_valid(h)) + && self + .job + .as_ref() + .is_none_or(|j| !j.is_empty() && j.len() <= 64) + } +} +/// Maps a legacy output job kind to its artifact kind and default path. +/// Returns `None` for a kind with no artifact equivalent. +/// +/// # Rules +/// - Paths match the table in issue #387 so migrated jobs write familiar files. +/// +/// # Dependencies +/// - `crates/doc/src/lib.rs` for `Project::migrate_output_jobs_to_artifacts` below. +/// +/// # Do not +/// - Use it for new outputs; add an artifact kind instead. +pub fn legacy_output_kind_to_artifact(job_kind: &str) -> Option<(&'static str, &'static str)> { + Some(match job_kind { + "gerbers" => ("package", "gerber/"), + "bom" => ("bom", "bom.csv"), + "placement" => ("placement", "placement.txt"), + "drill_chart" => ("drill_map", "board-drill-tools.csv"), + "pdf" => ("fab_drawing", "board.pdf"), + "svg" => ("raster_image", "board.svg"), + "odb" => ("package", "board.odb.zip"), + "ipc2581" => ("package", "board.xml"), + "netlist" => ("package", "pcb-netlist.net"), + "dxf" => ("package", "pcb.dxf"), + "cmp" => ("package", "pcb.cmp"), + "idf" => ("package", "board.idf"), + "vrml" => ("package", "board.wrl"), + "step" => ("package", "board.step"), + "dsn" => ("package", "pcb.dsn"), + "ipc356" => ("package", "test.brd"), + "gencad" => ("package", "board.gencad"), + "hyperlynx" => ("package", "netlist.csv"), + "plot" => ("package", "plot-report.csv"), + "report" => ("package", "board-report.txt"), + "ps" => ("package", "pcb.ps"), + "hpgl" => ("package", "board.hpgl"), + "stackup" => ("package", "board-stackup.txt"), + "stats" => ("package", "board-stats.csv"), + _ => return None, + }) +} +impl Project { + /// Creates one artifact per entry of each output job when the project has + /// jobs but no artifacts. Generated fields stay unset so each starts stale. + /// + /// # Rules + /// - A no-op once any artifact exists; ids are taken from `next_id`. + /// + /// # Dependencies + /// - `crates/io/src/generate.rs` `migrate_loaded_project` calls it on load. + /// + /// # Do not + /// - Remove the legacy `output_jobs`; they stay until retired. + pub fn migrate_output_jobs_to_artifacts(&mut self, next_id: &mut Id) -> Result<(), String> { + if !self.artifacts.is_empty() || self.output_jobs.is_empty() { + return Ok(()); + } + for job in &self.output_jobs { + for kind in &job.kinds { + let Some((artifact_kind, path)) = legacy_output_kind_to_artifact(kind) else { + continue; + }; + let name = if job.kinds.len() == 1 { + job.name.clone() + } else { + format!("{} {}", job.name, kind) + }; + if name.len() > 128 { + return Err("migrated artifact name exceeds 128 bytes".into()); + } + if self.artifacts.len() >= MAX_ITEMS { + return Err("artifact limit reached (2048)".into()); + } + let id = *next_id; + if id == 0 || id > u32::MAX as u64 { + return Err("artifact id out of range".into()); + } + *next_id = next_id.saturating_add(1); + self.artifacts.push(Artifact { + id, + name, + kind: artifact_kind.into(), + layers: vec![], + settings: serde_json::Value::Object(Default::default()), + machine: None, + path: path.into(), + generated_at_revision: None, + generated_hash: None, + job: Some(job.name.clone()), + }); + } + } + Ok(()) + } +} +/// An unplated through hole: a drill that passes through the board without +/// plating or a net. +/// A net tie: two touching round pads that bridge exactly two nets at one +/// point, used to split a plane while keeping a single controlled crossing. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct NetTie { + pub id: Id, + /// The two nets this tie bridges; they must differ. + pub net_a: Id, + pub net_b: Id, + /// Centre of the bridge, midway between the two pads, in millimetres. + pub position: Point, + /// Angle of the pad-to-pad axis in degrees from the x axis. + #[serde(default)] + pub rotation: f64, + /// Diameter of each of the two round pads, in millimetres. + pub diameter: f64, +} +impl NetTie { + fn valid(&self) -> bool { + self.position.valid() + && (0.3..=20.0).contains(&self.diameter) + && self.rotation.is_finite() + && self.net_a != self.net_b + } +} +/// A named reference point on the board, usually a mounting hole centre, that +/// is written into the mechanical outputs so an enclosure can be aligned to it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Datum { + pub id: Id, + pub name: String, + /// Position in millimetres; ignored while `hole` is set, because the + /// datum then sits at the centre of that hole. + pub position: Point, + /// Hole whose centre this datum follows. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hole: Option, +} +impl Datum { + /// Most datums one board carries. + pub const MAX: usize = 64; + /// A datum name is 1 to 32 characters from letters, digits, `_` and `-`. + pub fn name_valid(name: &str) -> bool { + (1..=32).contains(&name.len()) + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') + } +} +/// An optical assembly mark: a bare copper circle, usually 1 mm, that the +/// pick-and-place camera uses to locate and orient the board. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Fiducial { + pub id: Id, + /// Centre of the mark, in millimetres. + pub position: Point, + /// Diameter of the copper disc, in millimetres. + pub diameter: f64, + /// Copper layer the mark sits on. + #[serde(default = "front_layer")] + pub layer: Layer, +} +impl Fiducial { + fn valid(&self) -> bool { + self.position.valid() && (0.2..=10.0).contains(&self.diameter) + } +} +fn front_layer() -> Layer { + Layer::Front +} +/// An unplated through hole: a drill that passes through the board without +/// plating or a net. A round drill carries one centre; a slot carries a +/// second centre in `end` and is routed as a capsule of `diameter` width +/// between the two. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Hole { + pub id: Id, + pub position: Point, + /// Drill diameter in millimetres; for a slot this is its width. + pub diameter: f64, + /// Second centre of a slotted hole in millimetres, at least 0.01 mm from + /// `position`. Absent for a round drill, so old designs keep loading. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end: Option, +} +impl Hole { + /// The near centre of the drill: the circle centre for a round hole, or + /// one end of a slot. + pub fn start(&self) -> Point { + self.position + } + /// The far centre of the drill: the same point for a round hole, the + /// other end of the capsule for a slot. + pub fn finish(&self) -> Point { + self.end.unwrap_or(self.position) + } + /// True when the drill is a slot rather than a round hole. + pub fn is_slot(&self) -> bool { + self.end.is_some() + } + /// Centre of the drill: the circle centre, or the midpoint of a slot. + pub fn center(&self) -> Point { + let end = self.finish(); + Point::new( + (self.position.x + end.x) / 2.0, + (self.position.y + end.y) / 2.0, + ) + } + /// Overall length along the drill axis in millimetres: the diameter for a + /// round hole, and the capsule length for a slot. + pub fn length(&self) -> f64 { + self.position.distance(self.finish()) + self.diameter + } + /// Longest span a slot may cover between its two centres, in millimetres. + pub const MAX_SPAN: f64 = 50.0; + fn valid(&self) -> bool { + if !self.position.valid() || !(0.05..=25.0).contains(&self.diameter) { + return false; + } + match self.end { + None => true, + Some(end) => { + end.valid() && (0.01..=Self::MAX_SPAN).contains(&self.position.distance(end)) + } + } + } +} +/// One physical layer of the board, in stack order: its role, thickness and, +/// where known, the facts a fab and the impedance estimate need. +/// +/// Every field after `copper_role` is optional and skipped when empty, so a +/// project saved before they existed loads and saves byte for byte. The +/// accessors (`function`, `dk`, `df`) answer with the stated value or a value +/// derived from `kind` and the material table, so old designs need no rewrite. +/// +/// # Rules +/// - A stated `dk` or `df` always wins over the named material's table value. +/// - `linked_copper` names the copper row a mask, silk or paste row sits on. +/// +/// # Dependencies +/// - `crates/doc/src/material.rs` for the built-in table. +/// +/// # Do not +/// - Store derived values back into the record; derive them at read time. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +pub struct LayerRecord { + /// Display name, for example "F.Cu", "Core" or "L2". + pub name: String, + /// Layer role: copper, core, prepreg, soldermask, silkscreen, paste or custom. + pub kind: String, + /// Layer thickness in millimetres. + pub thickness: f64, + /// Copper plane style for fabrication output: signal, plane, mixed or hatched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub copper_role: Option, + /// Layer function when it differs from the one implied by `kind`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub function: Option, + /// Face the layer belongs to: top, bottom, internal, both or none. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side: Option, + /// Polarity of the layer artwork: positive or negative. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub polarity: Option, + /// Name of a row in the built-in material table. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub material: Option, + /// Relative permittivity stated on this row (1 to 20). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dk: Option, + /// Loss tangent stated on this row (0 to 1). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub df: Option, + /// Thickness tolerance in percent (0 to 50). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thickness_tol_pct: Option, + /// Copper weight in ounces per square foot (0.1 to 10). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub copper_weight_oz: Option, + /// Copper foil type: rolled or electrodeposited. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub foil: Option, + /// The copper row this mask, silk or paste row sits on. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub linked_copper: Option, +} +/// Layer functions a record may state. +pub const LAYER_FUNCTIONS: [&str; 10] = [ + "signal", + "plane", + "mixed", + "dielectric_core", + "dielectric_prepreg", + "soldermask", + "silkscreen", + "paste", + "other", + "none", +]; +impl LayerRecord { + fn valid(&self) -> bool { + let in_set = + |v: &Option, set: &[&str]| v.as_ref().is_none_or(|x| set.contains(&x.as_str())); + let in_range = |v: Option, lo: f64, hi: f64| { + v.is_none_or(|x| x.is_finite() && (lo..=hi).contains(&x)) + }; + !self.name.trim().is_empty() + && self.name.len() <= 64 + && matches!( + self.kind.as_str(), + "copper" | "core" | "prepreg" | "soldermask" | "silkscreen" | "paste" | "custom" + ) + && self.thickness.is_finite() + && (0.0..=100.0).contains(&self.thickness) + && in_set(&self.copper_role, &["signal", "plane", "mixed", "hatched"]) + && in_set(&self.function, &LAYER_FUNCTIONS) + && in_set(&self.side, &["top", "bottom", "internal", "both", "none"]) + && in_set(&self.polarity, &["positive", "negative"]) + && in_set(&self.foil, &["rolled", "electrodeposited"]) + && self + .material + .as_ref() + .is_none_or(|m| !m.trim().is_empty() && m.len() <= 64) + && self + .linked_copper + .as_ref() + .is_none_or(|m| !m.trim().is_empty() && m.len() <= 64) + && in_range(self.dk, 1.0, 20.0) + && in_range(self.df, 0.0, 1.0) + && in_range(self.thickness_tol_pct, 0.0, 50.0) + && in_range(self.copper_weight_oz, 0.1, 10.0) + } + /// Layer function: the stated one, else the one the role implies. + pub fn function(&self) -> &str { + if let Some(f) = &self.function { + return f; + } + match self.kind.as_str() { + "copper" => match self.copper_role.as_deref() { + Some("plane") => "plane", + Some("mixed") => "mixed", + _ => "signal", + }, + "core" => "dielectric_core", + "prepreg" => "dielectric_prepreg", + "soldermask" => "soldermask", + "silkscreen" => "silkscreen", + "paste" => "paste", + _ => "other", + } + } + /// True for a core or prepreg row. + pub fn is_dielectric(&self) -> bool { + matches!(self.kind.as_str(), "core" | "prepreg") + } + /// Polarity: the stated one, else negative for a plane and positive otherwise. + pub fn polarity(&self) -> &str { + match (&self.polarity, self.function()) { + (Some(p), _) => p, + (None, "plane") => "negative", + _ => "positive", + } + } + /// Relative permittivity: the value stated on the row, else the named + /// material's table value. + pub fn dk(&self) -> Option { + self.dk + .or_else(|| self.material.as_deref().and_then(material).map(|m| m.dk)) + } + /// Loss tangent: the value stated on the row, else the named material's + /// table value. + pub fn df(&self) -> Option { + self.df + .or_else(|| self.material.as_deref().and_then(material).map(|m| m.df)) + } +} +/// What a drawn layer tells a machine to do: a cutter follows cut and +/// perforation layers, a UV printer prints silk and mask layers, and "other" +/// layers are reference or documentation art. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub enum ArtKind { + #[serde(rename = "cut")] + Cut, + #[serde(rename = "perforation")] + Perforation, + #[serde(rename = "silk")] + Silk, + #[serde(rename = "mask")] + Mask, + #[serde(rename = "other")] + Other, +} +impl ArtKind { + /// Plain-English name of the job this layer gives a machine. + pub fn label(self) -> &'static str { + match self { + Self::Cut => "cut line", + Self::Perforation => "perforation", + Self::Silk => "silk screen", + Self::Mask => "solder mask", + Self::Other => "drawing", + } + } +} +/// One figure drawn on a user layer, in board millimetres. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub enum ArtShape { + /// A straight stroke between two points. + Line { start: Point, end: Point }, + /// A rectangle outline, optionally rotated about its centre. + Rect { + x: f64, + y: f64, + width: f64, + height: f64, + /// Turn in degrees about the rectangle centre. + #[serde(default)] + rotate: f64, + }, + /// A circle outline. + Circle { center: Point, radius: f64 }, + /// A closed outline through these points. + Poly { points: Vec }, + /// Text drawn with the machine's pen. + Text { + at: Point, + text: String, + /// Cap height in millimetres. + #[serde(default = "art_text_size")] + size: f64, + /// Turn in degrees about the anchor point. + #[serde(default)] + rotate: f64, + }, +} +impl ArtShape { + /// The true circle this figure draws, when it is one, so a format with + /// arcs or circle entities can keep it round instead of sampling it. + pub fn circle(&self) -> Option<(Point, f64)> { + match self { + Self::Circle { center, radius } => Some((*center, *radius)), + _ => None, + } + } + + /// A point that represents the figure for navigation and region tests. + pub fn anchor(&self) -> Point { + match self { + Self::Line { start, .. } => *start, + Self::Rect { + x, + y, + width, + height, + .. + } => Point::new(x + width / 2.0, y + height / 2.0), + Self::Circle { center, .. } => *center, + Self::Poly { points } => points.first().copied().unwrap_or_default(), + Self::Text { at, .. } => *at, + } + } + + /// The straight-line paths this figure draws, in board millimetres. + pub fn paths(&self) -> Vec { + match self { + Self::Line { start, end } => vec![ArtPath { + points: vec![*start, *end], + closed: false, + }], + Self::Rect { + x, + y, + width, + height, + rotate, + } => { + let center = Point::new(x + width / 2.0, y + height / 2.0); + let points = [ + Point::new(*x, *y), + Point::new(x + width, *y), + Point::new(x + width, y + height), + Point::new(*x, y + height), + ] + .into_iter() + .map(|c| center.offset(Point::new(c.x - center.x, c.y - center.y).rotate(*rotate))) + .collect(); + vec![ArtPath { + points, + closed: true, + }] + } + Self::Circle { center, radius } => vec![ArtPath { + points: art_circle_points(*center, *radius), + closed: true, + }], + Self::Poly { points } => { + if points.len() < 2 { + return vec![]; + } + vec![ArtPath { + points: points.clone(), + closed: true, + }] + } + Self::Text { .. } => vec![], + } + } + + fn valid(&self) -> bool { + match self { + Self::Line { start, end } => start.valid() && end.valid(), + Self::Rect { + x, + y, + width, + height, + rotate, + } => { + x.is_finite() + && y.is_finite() + && (0.001..=1000.0).contains(width) + && (0.001..=1000.0).contains(height) + && rotate.is_finite() + && *x >= -1000.0 + && *y >= -1000.0 + && *x + *width <= 2000.0 + && *y + *height <= 2000.0 + } + Self::Circle { center, radius } => center.valid() && (0.001..=500.0).contains(radius), + Self::Poly { points } => { + (2..=64).contains(&points.len()) && points.iter().all(|pt| pt.valid()) + } + Self::Text { + at, + text, + size, + rotate, + } => { + at.valid() + && !text.trim().is_empty() + && text.len() <= 128 + && (0.2..=50.0).contains(size) + && rotate.is_finite() + } + } + } +} +/// One polyline of a drawn figure, in board millimetres. Plotters, macros +/// and the screen all read figures through this so they agree on corners, +/// closure and circle sampling. +#[derive(Clone, Debug, PartialEq)] +pub struct ArtPath { + /// The points to travel through, in order. + pub points: Vec, + /// True when the path returns to its first point. + pub closed: bool, +} +impl ArtPath { + /// Every point along this path, walking each segment at a physical step + /// and placing the first mark at the start. Closed paths include the + /// closing segment. Used to turn a perforation line into real holes. + pub fn dots(&self, pitch: f64) -> Vec { + const SAMPLES: usize = 100_000; + let mut out = Vec::new(); + if !(pitch.is_finite() && pitch > 0.0) { + return out; + } + let Some(first) = self.points.first().copied() else { + return out; + }; + out.push(first); + let mut ring = self.points.clone(); + if self.closed { + ring.push(first); + } + let mut next = pitch; + let mut travelled = 0.0; + for pair in ring.windows(2) { + let (a, b) = (pair[0], pair[1]); + let len = ((b.x - a.x).powi(2) + (b.y - a.y).powi(2)).sqrt(); + if !len.is_finite() || len <= 0.0 { + continue; + } + while travelled + len >= next { + let t = (next - travelled) / len; + out.push(Point::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)); + if out.len() >= SAMPLES { + return out; + } + next += pitch; + } + travelled += len; + } + out + } +} +/// Sample a circle into a ring of points, without repeating the first point. +fn art_circle_points(center: Point, radius: f64) -> Vec { + const SEGMENTS: usize = 64; + (0..SEGMENTS) + .map(|i| { + let a = std::f64::consts::TAU * i as f64 / SEGMENTS as f64; + Point::new(center.x + radius * a.cos(), center.y + radius * a.sin()) + }) + .collect() +} +/// A layer the designer draws: card outlines to cut, perforations to snap +/// along, custom silk screens, masks or reference art. Copper stays where it +/// is; these layers sit beside it and are plotted for laser, mill and +/// printer output. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct ArtLayer { + pub id: Id, + /// Display name, unique per board, for example "Card Outline". + pub name: String, + /// What this layer tells a machine to do. + pub kind: ArtKind, + /// True draws the layer as evenly spaced dots: a perforation the board + /// snaps along, or a light print guide. + #[serde(default)] + pub dotted: bool, + /// Centre-to-centre distance between the dots of a dotted layer, in + /// millimetres. Machines need a physical pitch; the screen dashes are a + /// preview of this. + #[serde(default = "art_dot_pitch")] + pub dot_pitch: f64, + /// Diameter of each dot of a dotted layer, in millimetres. A laser marks + /// it, a mill drills it. + #[serde(default = "art_dot_size")] + pub dot_size: f64, + /// False hides the layer everywhere on screen. + #[serde(default = "art_visible")] + pub visible: bool, + /// The figures on this layer, in draw order. + #[serde(default)] + pub shapes: Vec, +} +impl ArtLayer { + fn valid(&self) -> bool { + !self.name.trim().is_empty() + && self.name.len() <= 64 + && self.shapes.len() <= 512 + && self.shapes.iter().all(ArtShape::valid) + && self.dot_pitch.is_finite() + && (0.1..=20.0).contains(&self.dot_pitch) + && self.dot_size.is_finite() + && (0.05..=10.0).contains(&self.dot_size) + } +} +fn art_visible() -> bool { + true +} +fn art_dot_pitch() -> f64 { + 1.0 +} +fn art_dot_size() -> f64 { + 0.5 +} +fn art_text_size() -> f64 { + 1.0 +} +fn board_finish() -> String { + "HASL".into() +} +fn board_er() -> f64 { + 4.4 +} +fn board_origin() -> Point { + Point::default() +} +/// Machining notes recorded for fabrication: whether the board edges are +/// plated and the tolerances the mill and drill are held to. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] +pub struct MachiningNotes { + /// True when board edges are plated. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub edge_plating: Option, + /// Drill hole diameter tolerance in millimetres, plus or minus. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub drill_tolerance: Option, + /// Rout/edge dimension tolerance in millimetres, plus or minus. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub edge_tolerance: Option, +} +impl MachiningNotes { + fn valid(&self) -> bool { + self.drill_tolerance + .is_none_or(|t| t.is_finite() && (0.0..=1.0).contains(&t)) + && self + .edge_tolerance + .is_none_or(|t| t.is_finite() && (0.0..=1.0).contains(&t)) + } +} +impl Board { + /// The outline as a plain polygon with arcs cut into chords that stay + /// within `max_chord_error` millimetres of the true edge; empty when the + /// board has no traced outline. + /// + /// # Dependencies + /// - crates/doc/src/outline.rs#flatten_outline + /// + /// # Do not + /// - Do not use the vertex list directly in a reader: it draws arcs as chords. + pub fn edge_ring(&self, max_chord_error: f64) -> Vec { + match &self.outline { + Some(points) => flatten_outline(points, &self.outline_arcs, max_chord_error), + None => Vec::new(), + } + } +} +fn is_open_covering(c: &ViaCovering) -> bool { + *c == ViaCovering::Open +} +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Board { + pub width: f64, + pub height: f64, + pub thickness: f64, + pub clearance: f64, + /// Recorded fabrication minimums and preset metadata. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rules: Option, + /// Surface finish applied to exposed copper, for example HASL or ENIG. + #[serde(default = "board_finish")] + pub finish: String, + /// Relative permittivity of the substrate, used by impedance estimates. + #[serde(default = "board_er")] + pub er: f64, + /// Origin that drill file coordinates are measured from, in millimetres. + #[serde(default = "board_origin")] + pub drill_origin: Point, + /// Covering applied to every via that has no covering of its own. + #[serde(default, skip_serializing_if = "is_open_covering")] + pub via_covering_default: ViaCovering, + /// Recorded per-layer fabrication notes in physical stack order (top to bottom). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub layer_records: Vec, + /// Extra via spans (upper, lower copper layer index) the build allows + /// beyond the generic ones, for example a buried span. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub via_spans: Vec<(u8, u8)>, + /// Machining notes for fabrication, absent when none were recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub machining: Option, + /// Clearance rules between specific pairs of nets, ordered by net ids. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub pair_rules: Vec, + /// Differential pairs: named net couples that route together with a + /// coupling gap and, when set, matched lengths. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub diff_pairs: Vec, + /// Length-match groups: nets whose routed lengths must agree within a + /// tolerance. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub length_groups: Vec, + /// Rectangular board areas that demand a stricter minimum copper + /// separation for copper whose midpoints lie inside them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub rule_areas: Vec, + /// Free-form closed board outline in millimetres, ordered around the + /// perimeter and implicitly closed. Absent means the plain rectangle. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outline: Option>, + /// Arc midpoints for the outline, one entry per segment (vertex i to + /// vertex i + 1, the last closing to vertex 0). `None` is a straight + /// segment. Empty means the whole outline is straight. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub outline_arcs: Vec>, + pub footprints: Vec, + pub tracks: Vec, + /// Plated through-hole vias joining front and back copper. + #[serde(default)] + pub vias: Vec, + /// Optical assembly marks: bare copper circles the pick-and-place camera + /// finds the board by. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub fiducials: Vec, + /// Net-tie pads: two touching round pads bridging exactly two nets, + /// ordered by id. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub netties: Vec, + /// Unplated through holes drilled for mounting or clearance; they carry + /// no copper and belong to no net. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub holes: Vec, + /// Named mounting datums an enclosure tool can consume. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub datums: Vec, + /// Layers the designer draws for machines: cuts, perforations, custom + /// silk and mask art, plotted alongside the copper. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub user_layers: Vec, + /// Poured copper zones, one polygon per zone on a single layer. + #[serde(default)] + pub zones: Vec, + pub cutouts: Vec, + /// Text labels drawn on the board. + #[serde(default)] + pub texts: Vec, +} +/// One extra bill-of-materials column defined by the project: which +/// component property to read and the header to print for it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct BomField { + /// Component property key to read, for example "MPN". + pub key: String, + /// Column header to print; falls back to the key when empty. + #[serde(default)] + pub label: String, +} +impl BomField { + fn valid(&self) -> bool { + !self.key.trim().is_empty() && self.key.len() <= 64 && self.label.len() <= 64 + } +} +/// A text file attached to the project, for example a licence note or a +/// datasheet excerpt, stored verbatim so it travels with the design. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct EmbeddedFile { + pub name: String, + pub data: String, + /// `text` (the default) or `base64` for binary attachments such as PNG + /// images, stored as standard base64 text. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub encoding: String, +} +/// Largest base64 text held for one binary attachment (about 2 MiB decoded). +pub const MAX_BINARY_ATTACHMENT_BASE64: usize = 2_796_204; +/// Binary attachments a project may carry. +pub const MAX_BINARY_ATTACHMENTS: usize = 8; +impl EmbeddedFile { + /// True when the file holds base64 text for a binary payload. + pub fn is_binary(&self) -> bool { + self.encoding == "base64" + } + fn valid(&self) -> bool { + let cap = match self.encoding.as_str() { + "" | "text" => 262_144, + "base64" => MAX_BINARY_ATTACHMENT_BASE64, + _ => return false, + }; + !self.name.trim().is_empty() && self.name.len() <= 128 && self.data.len() <= cap + } +} +/// A picture shown under the schematic or the board for tracing. It points at +/// a base64 PNG attachment and never reaches any fabrication or image export. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct ReferenceImage { + pub id: Id, + /// Name of the attached PNG file. + pub file: String, + /// `schematic` or `pcb`. + pub view: String, + /// Top-left corner of the picture, in millimetres; the picture extends + /// right and down like the canvas does. + pub x: f64, + pub y: f64, + /// Millimetres per image pixel. + pub scale: f64, + /// Paint opacity from 0 (invisible) to 1. + pub opacity: f64, + pub visible: bool, +} +impl ReferenceImage { + fn valid(&self) -> bool { + (self.view == "schematic" || self.view == "pcb") + && !self.file.is_empty() + && self.x.is_finite() + && self.y.is_finite() + && self.x.abs() <= 100_000.0 + && self.y.abs() <= 100_000.0 + && self.scale.is_finite() + && (0.001..=100.0).contains(&self.scale) + && self.opacity.is_finite() + && (0.0..=1.0).contains(&self.opacity) + } +} +/// A set of drawn graphics that translate together as one unit, so a +/// multi-graphic annotation can be repositioned in a single step. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct GraphicGroup { + pub id: Id, + pub graphics: Vec, +} +impl GraphicGroup { + fn valid(&self) -> bool { + self.graphics.len() >= 2 && self.graphics.len() <= 512 && { + let unique: BTreeSet = self.graphics.iter().copied().collect(); + unique.len() == self.graphics.len() + } + } +} +/// A set of objects of any kind (parts, footprints, copper, text, graphics) +/// that move together, so a block of a design can be repositioned in one step. +/// +/// # Rules +/// - Two to 512 distinct members; a member belongs to at most one object group. +/// - Ids that no longer name an object are dropped by `Project::prune_object_refs`. +/// +/// # Dependencies +/// - crates/engine/src/lib.rs#object.group +/// +/// # Do not +/// - Store the same id in two object groups. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct ObjectGroup { + /// Stable id of the group. + pub id: Id, + /// Ids of the grouped objects, in the order they were grouped. + pub members: Vec, +} +impl ObjectGroup { + fn valid(&self) -> bool { + self.members.len() >= 2 && self.members.len() <= 512 && { + let unique: BTreeSet = self.members.iter().copied().collect(); + unique.len() == self.members.len() + } + } +} +/// An assembly variant of the design: a named alternate build in which a +/// chosen set of components is marked do not populate. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Variant { + /// Variant name, unique within the project. + pub name: String, + /// Optional note describing what this variant changes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, + /// Ids of components this variant leaves unpopulated. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub dnp: Vec, + /// Components this variant populates with a different package, ordered by + /// component id. A variant bill of materials skips unpopulated parts and + /// prints these swaps in place of the footprints the design places. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub footprints: Vec, +} +impl Variant { + fn valid(&self) -> bool { + !self.name.trim().is_empty() + && self.name.len() <= 64 + && self.note.as_ref().is_none_or(|n| n.len() <= 256) + && self.dnp.len() <= 2048 + && self.footprints.len() <= 512 + && self.footprints.iter().all(|o| { + !o.footprint.trim().is_empty() && o.footprint.len() <= 128 && o.component != 0 + }) + } +} +/// One component's package swap inside an assembly variant: this build +/// populates that component position with the named footprint instead of the +/// one the design places. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct FootprintOverride { + pub component: Id, + pub footprint: String, +} +fn default_project_unit() -> String { + "mm".into() +} +/// One row of the project library table: a nickname mapped to the folder +/// that holds library files, so library commands can address +/// `nickname/file.kicad_mod` without a machine-specific folder. +/// One named, reusable pad cross-section: the shape, size and optional drill +/// a footprint pad takes on when the stack is applied to it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Padstack { + /// Name used by commands to pick this stack. + pub name: String, + /// Copper shape: "circle", "rect", "oval" or "roundrect". + pub shape: String, + /// Copper extent in millimetres, x by y. + pub size: Point, + /// Drill diameter in millimetres; absent means an un-drilled surface pad. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub drill: Option, + /// Corner rounding ratio for roundrect copper, 0 to 0.5. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub roundrect_ratio: Option, +} +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct LibraryLink { + /// Nickname used as the first path segment by library commands. + pub name: String, + /// Folder that holds the library files for this nickname. + pub path: String, +} +/// V-score cut lines across the panel when separation is V-score; empty for tab routing. +pub fn panel_score_lines(project: &Project) -> Result, String> { + let settings = &project.panel; + if !settings.enabled { + return Err("panel checks need enabled panel settings".into()); + } + if settings.separation != PanelSeparation::VScore { + return Ok(Vec::new()); + } + let layout = panel_layout(project)?; + let mut lines = Vec::new(); + for column in 0..layout.columns.saturating_sub(1) { + let x = layout.rail + + (column + 1) as f64 * layout.board_width + + column as f64 * layout.pitch_x + + layout.pitch_x / 2.0; + lines.push((Point::new(x, 0.0), Point::new(x, layout.panel_height))); + } + for row in 0..layout.rows.saturating_sub(1) { + let y = layout.rail + + (row + 1) as f64 * layout.board_height + + row as f64 * layout.pitch_y + + layout.pitch_y / 2.0; + lines.push((Point::new(0.0, y), Point::new(layout.panel_width, y))); + } + Ok(lines) +} +/// Tab-routing cut paths between copies when tab separation is active. +pub fn panel_tab_segments(project: &Project) -> Result, String> { + let settings = &project.panel; + if !settings.enabled { + return Err("panel checks need enabled panel settings".into()); + } + if settings.separation != PanelSeparation::Tab { + return Ok(Vec::new()); + } + let layout = panel_layout(project)?; + let mut segments = Vec::new(); + for column in 0..layout.columns.saturating_sub(1) { + let x = layout.rail + + (column + 1) as f64 * layout.board_width + + column as f64 * layout.pitch_x + + layout.pitch_x / 2.0; + segments.push(( + Point::new(x, layout.rail), + Point::new(x, layout.panel_height - layout.rail), + )); + } + for row in 0..layout.rows.saturating_sub(1) { + let y = layout.rail + + (row + 1) as f64 * layout.board_height + + row as f64 * layout.pitch_y + + layout.pitch_y / 2.0; + segments.push(( + Point::new(layout.rail, y), + Point::new(layout.panel_width - layout.rail, y), + )); + } + Ok(segments) +} +/// Tab-routing channel width in millimetres when tab separation is active. +pub fn panel_tab_channel_width(project: &Project) -> Option { + let settings = &project.panel; + if settings.enabled && settings.separation == PanelSeparation::Tab { + Some(settings.tab_channel) + } else { + None + } +} +/// Default assembler panel limit until a fabrication profile supplies shop values. +pub const PANEL_ASSEMBLER_MAX_MM: f64 = 250.0; +/// Minimum copper clearance from a V-score line (standards default). +pub const PANEL_SCORE_COPPER_MIN_MM: f64 = 0.40; +/// Minimum component body clearance from a V-score line (standards default). +pub const PANEL_SCORE_COMPONENT_MIN_MM: f64 = 1.0; +/// Minimum routed tab channel width (standards default). +pub const PANEL_TAB_CHANNEL_MIN_MM: f64 = 1.6; +/// Panel fiducial count expected in the rails. +pub const PANEL_FIDUCIAL_COUNT: usize = 3; +/// Most named numeric parameters one project may carry. +pub const MAX_PARAMETERS: usize = 128; +/// Largest absolute parameter value a project records, in millimetres. +pub const MAX_PARAMETER_VALUE: f64 = 10_000.0; +/// Longest parameter note a project records, in bytes. +pub const MAX_PARAMETER_NOTE: usize = 256; +/// Most object fields one project may bind to a parameter. +pub const MAX_BINDINGS: usize = 1024; +/// A named numeric value that commands reference by name instead of +/// retyping a number, so one edit moves everything that depends on it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct Parameter { + /// The number every reference to this name resolves to, in millimetres. + pub value: f64, + /// Free-form reminder of what the number means, carried with the design. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub note: String, +} +/// One numeric field of one object recorded as following a named parameter: +/// setting the parameter writes this field again and re-runs its range checks. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct Binding { + /// The object whose field follows the parameter. + pub object: Id, + /// The field that follows it; a closed set, one variant per numeric + /// field a command accepts a parameter name for. + pub field: Field, + /// The parameter the field follows. + pub parameter: String, +} +/// The closed set of numeric object fields a named parameter can drive. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum Field { + /// Drill diameter, or slot width, of an unplated hole. + HoleDiameter, + /// X coordinate of an unplated hole's near centre. + HoleX, + /// Y coordinate of an unplated hole's near centre. + HoleY, + /// Outer copper pad diameter of a plated via. + ViaDiameter, + /// Drilled diameter of a plated via. + ViaDrill, + /// X coordinate of a plated via's centre. + ViaX, + /// Y coordinate of a plated via's centre. + ViaY, +} +impl Field { + /// True when this field belongs to an unplated hole. + pub fn is_hole(&self) -> bool { + matches!(self, Field::HoleDiameter | Field::HoleX | Field::HoleY) + } + /// True when this field belongs to a plated via. + pub fn is_via(&self) -> bool { + matches!( + self, + Field::ViaDiameter | Field::ViaDrill | Field::ViaX | Field::ViaY + ) + } +} +/// True when `name` is a usable parameter name: one to 32 bytes starting with +/// a letter or underscore, then letters, digits or underscores. +pub fn valid_parameter_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 32 + && name + .bytes() + .next() + .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_') + && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +} +/// True when `note` fits the parameter note limit. +pub fn valid_parameter_note(note: &str) -> bool { + note.len() <= MAX_PARAMETER_NOTE +} +/// True when `value` is a finite number a parameter may hold. +pub fn valid_parameter_value(value: f64) -> bool { + value.is_finite() && value.abs() <= MAX_PARAMETER_VALUE +} +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Project { + pub format: String, + pub version: u32, + pub name: String, + /// The unit this design is read in: "mm", "mil" or "inch". Stored + /// coordinates stay millimetres; inch fabrication output is converted, + /// while mil is a reading and reporting convention. + #[serde(default = "default_project_unit")] + pub unit: String, + pub components: Vec, + pub nets: Vec, + /// Named net classes carrying clearance and default width rules. + #[serde(default)] + pub net_classes: Vec, + /// Clearance overrides between net classes, stricter than either class alone. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub class_pairs: Vec, + /// Named schematic pages, ordered by id; sheet 0 is the implicit root. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub sheets: Vec, + /// Per-page title block fields and drawing defaults; a page without a + /// record uses [`PageSettings::new`]. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub page_settings: Vec, + /// Named hierarchy ports, ordered by id. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub ports: Vec, + /// Extra bill-of-materials columns, in print order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub bom_fields: Vec, + /// Text files attached to the project, ordered by name. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub files: Vec, + /// Reference pictures under the canvases, ordered by id; editor-only. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub reference_images: Vec, + /// Assembly variants, ordered by name. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub variants: Vec, + /// Groups of drawn graphics that translate together, ordered by id. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub graphic_groups: Vec, + /// Groups of objects of any kind that move together, ordered by id. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub object_groups: Vec, + /// Ids of locked objects other than footprints (a footprint stores its own + /// lock in `Footprint::locked`); locked objects refuse moves. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub locked_objects: Vec, + /// Named fabrication output recipes, ordered by name, re-runnable after + /// any edit. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub output_jobs: Vec, + /// Regenerable fabrication outputs, ordered by id. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub artifacts: Vec, + /// Manufacturing panel grid; disabled until the designer enables it. + #[serde(default)] + pub panel: PanelSettings, + /// Checks the designer wrote themselves, in the order they were made. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub custom_checks: Vec, + /// Pin-type connection matrix overrides keyed `"|"` with + /// sorted types; values are `"ok"`, `"warning"` or `"error"`. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub pin_matrix: BTreeMap, + /// Free-form project metadata such as title, revision, company or notes, + /// keyed by lower-case name and carried with the saved design. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub meta: BTreeMap, + /// Named numeric values commands may reference by name instead of + /// retyping a number, keyed by name and carried with the saved design. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub parameters: BTreeMap, + /// Object fields that follow a named parameter, so changing the parameter + /// moves everything that depends on it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub bindings: Vec, + /// Per-check-code severity overrides: "error", "warning" or "off" to + /// silence a check whose findings this design accepts as normal. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub rule_severity: BTreeMap, + /// Per-check-code object exclusions: a finding for one of these codes is + /// dropped when every object it names is on that code's exclusion list. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub rule_exclusions: BTreeMap>, + /// Per-check-code rectangular areas: a finding for one of these codes is + /// dropped when every object it names sits inside one of its rectangles. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub rule_regions: BTreeMap>, + /// Named library folders that library commands resolve through: a path + /// whose first segment matches a nickname is rewritten to the mapped + /// folder, so the design opens on another machine without retyping it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub library_table: Vec, + /// Named reusable pad shapes that footprint pads can adopt, so one + /// fabrication decision (a part's copper and drill) is defined once and + /// applied to many pads instead of retyped per footprint. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub padstacks: Vec, + /// Shop machine profiles copied from presets or imported from TOML. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub machine_profiles: Vec, + pub wires: Vec, + #[serde(default)] + pub drawn_wires: Vec, + /// Free-standing drawing primitives for schematic and board graphics. + #[serde(default)] + pub graphics: Vec, + /// Named net annotations placed on the schematic. + #[serde(default)] + pub labels: Vec