diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 08ccd93c..369ff6a9 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -2,3 +2,10 @@ self-hosted-runner: labels: - github-ubuntu-16core # org 16-core larger runner, used by the FreeBSD VM jobs (release.yml, freebsd.yml) + +# actionlint 1.7.12 predates GitHub's queue key. Only this exact false positive is +# suppressed; nightly-release-tests.py enforces the exact concurrency block contract. +paths: + .github/workflows/nightly-sign.yml: + ignore: + - '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 00000000..a1c1f31e --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -0,0 +1,16 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C +bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA +OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL +AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf +PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz +BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56 +er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT +oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ +AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo +9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo +SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A +ga/qCA== +=3wGQ +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 00000000..5eb66057 --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,112 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/anicraft", + "repository_id": 1419518094, + "producer_workflow_id": null, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea", + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", + "release_branch": "release", + "manual_actors": [ + "bflatastic", + "dylanmtaylor", + "echelon", + "FredApps", + "skylartaylor" + ], + "max_age_seconds": 86400, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": "anicraft-nightly-20261124", + "repository": "storytold/anicraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 409994922, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + }, + { + "name": "Licences, bans and sources (cargo deny)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_anicraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_anicraft&branch=main", + "issue_types": [ + "VULNERABILITY" + ], + "accepted_conditions": [ + { + "metric": "new_security_rating", + "comparator": "GT", + "error_threshold": "1", + "maximum": "5" + } + ], + "required_conditions": [ + { + "metric": "new_reliability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_maintainability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_coverage", + "comparator": "LT", + "error_threshold": "80" + }, + { + "metric": "new_duplicated_lines_density", + "comparator": "GT", + "error_threshold": "3" + }, + { + "metric": "new_security_hotspots_reviewed", + "comparator": "LT", + "error_threshold": "100" + } + ], + "debt": [] + } + }, + "max_artifact_bytes": 2147483648, + "automatic_signer_actors": [], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + } + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/.github/workflows/nightly-builds.yml b/.github/workflows/nightly-builds.yml new file mode 100644 index 00000000..27dcf258 --- /dev/null +++ b/.github/workflows/nightly-builds.yml @@ -0,0 +1,273 @@ +name: Nightly builds + +# Builds the unsigned Nightly flavor on all three platforms with the app's own scripts and checks +# each artifact as the Launcher unpacks it: packaging/windows/nightly.ps1 (via +# package.ps1 -Nightly -BuildOnly), packaging/linux/nightly.sh and packaging/macos/nightly.sh + +# nightly-verify.sh --expect unsigned. No secrets, no signing and no environment: the real Nightly +# is signed by the shared release-ref signer (craft-common-actions), which calls +# packaging/windows/sign.ps1 -Required, packaging/macos/nightly-sign.sh and the Linux key. +# +# This check is how the three scripts stay exercised before the producer runs exist. The macOS leg +# spends hosted Mac minutes, which are capped: it runs only with the `full-ci` label (as the other +# expensive legs do), one app at a time, or when dispatched by hand. +on: + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: nightly-builds-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + lint: + name: Synthetic suites and script syntax + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-ci') && + (github.event.action != 'labeled' || github.event.label.name == 'full-ci')) + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: The synthetic suites (archive, launcher, release contract, plist, Apple stand-ins) + run: python3 packaging/nightly-tests.py + - name: Shell syntax of every Nightly script + run: | + set -euo pipefail + for script in packaging/nightly-common.sh packaging/linux/nightly.sh \ + packaging/linux/nightly-launch.sh packaging/linux/nightly-arch-tar.sh \ + packaging/macos/nightly-lib.sh packaging/macos/nightly.sh \ + packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh; do + bash -n "$script" + done + - name: The Arch handoff, staged and started as the packager ships it + run: bash packaging/linux/nightly-arch-tar-test.sh + + windows: + name: Nightly GUI (x86_64, unsigned) + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-ci') && + (github.event.action != 'labeled' || github.event.label.name == 'full-ci')) + runs-on: windows-latest + timeout-minutes: 120 + env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The release's pin (release.yml craft-fonts-ref), so the ZIP's notices match a shipped build. + - name: Check out craft-fonts + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main + with: + ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + # The i18n catalogs the interface is built with (ADR 0040). + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main + - name: The Nightly signer and compiler guards + shell: pwsh + run: | + $fixtures = Join-Path $env:RUNNER_TEMP 'nightly-fixtures' + New-Item -ItemType Directory -Force -Path $fixtures | Out-Null + ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $fixtures + ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $fixtures + ./packaging/windows/test-sign.ps1 + # A version of the prepared Nightly form for this commit; the real one comes from the feed's + # identity job. Only nightly.ps1's input checks read it. + - name: Prepare a Nightly identity for this commit + shell: pwsh + run: | + $base = ((Select-String -Path Cargo.toml -Pattern '^version = "([^"]+)"' | Select-Object -First 1).Matches.Groups[1].Value -split '-')[0] + $sha = (git rev-parse HEAD).Trim() + $date = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') + $run = "$env:GITHUB_RUN_NUMBER.$env:GITHUB_RUN_ATTEMPT" + "ANICRAFT_BUILD_SHA=$sha" >> $env:GITHUB_ENV + "ANICRAFT_BUILD_DATE=$date" >> $env:GITHUB_ENV + "ANICRAFT_VERSION=$base-nightly.$($date.Replace('-','')).$run.g$($sha.Substring(0,12))" >> $env:GITHUB_ENV + - name: Build the unsigned Nightly GUI + shell: pwsh + env: + ANICRAFT_BUILD_CHANNEL: nightly-v1 + CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets + DIST: ${{ runner.temp }}/nightly-dist + CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts + CRAFT_FONTS_REQUIRED: "1" + run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly + - name: Check the ZIP payload and the version query + shell: pwsh + run: | + $zip = Join-Path $env:RUNNER_TEMP "nightly-dist\anicraft-$env:ANICRAFT_VERSION-windows-x86_64-nightly.unsigned.zip" + if (-not (Test-Path -LiteralPath $zip)) { throw "missing $zip" } + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + if ('anicraft.exe' -notin $names) { throw 'the ZIP has no anicraft.exe' } + foreach ($forbidden in @('anicraft-cli.exe', 'portable.txt')) { + if ($forbidden -in $names) { throw "the Nightly ZIP must not ship $forbidden" } + } + } finally { $archive.Dispose() } + $stage = Join-Path $env:RUNNER_TEMP 'nightly-targets\windows-package\nightly-v1-x86_64\anicraft.exe' + $plain = (& $stage --version | Out-String).Trim() + if ($plain -cne "AniCraft $env:ANICRAFT_VERSION (nightly-v1)") { throw "the version query reports '$plain'" } + $launcher = (& $stage --launch-profile nightly-v1 --profile-root (Join-Path $env:RUNNER_TEMP 'profile') --version | Out-String).Trim() + if ($launcher -cne $plain) { throw "the Launcher's query reports '$launcher', not '$plain'" } + - name: Keep the unsigned ZIP + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: anicraft-nightly-windows-x86_64-unsigned + path: ${{ runner.temp }}/nightly-dist/anicraft-${{ env.ANICRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip + if-no-files-found: error + retention-days: 7 + compression-level: 0 + + linux: + name: Nightly tar (x86_64, unsigned) + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-ci') && + (github.event.action != 'labeled' || github.event.label.name == 'full-ci')) + runs-on: ubuntu-24.04 + timeout-minutes: 120 + env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Check out craft-fonts + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main + with: + ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main + # The dev packages the crate needs to link (cpal's ALSA, winit's X11/Wayland, rfd's GTK). + - name: Install the build packages + run: sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev libasound2-dev + - name: Prepare a Nightly identity for this commit + run: | + set -euo pipefail + base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')" + sha="$(git rev-parse HEAD)" + date="$(date -u +%Y-%m-%d)" + { + echo "ANICRAFT_BUILD_SHA=$sha" + echo "ANICRAFT_BUILD_DATE=$date" + echo "ANICRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}" + } >>"$GITHUB_ENV" + - name: Build the unsigned Nightly tar + env: + ANICRAFT_BUILD_CHANNEL: nightly-v1 + CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets + DIST: ${{ runner.temp }}/nightly-dist + CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts + CRAFT_FONTS_REQUIRED: "1" + run: bash packaging/linux/nightly.sh --arch x86_64 + - name: Check the tar as the Launcher unpacks it, and the version query + run: | + set -euo pipefail + tar="$RUNNER_TEMP/nightly-dist/anicraft-$ANICRAFT_VERSION-linux-x86_64-nightly.tar.gz" + out="$RUNNER_TEMP/unpacked" + mkdir -p "$out" + tar -xzf "$tar" -C "$out" + # The standard layout: `anicraft` is the launcher and `anicraft-bin` the GUI it starts. + test -x "$out/anicraft" + test -x "$out/anicraft-bin" + test -f "$out/anicraft-nightly.png" + for notice in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do test -f "$out/$notice"; done + test "$(find "$out" -mindepth 1 -maxdepth 1 | wc -l)" -le 12 + head -c 4 "$out/anicraft-bin" | od -An -tx1 | tr -d ' \n' | grep -qx 7f454c46 + expected="AniCraft $ANICRAFT_VERSION (nightly-v1)" + # The entry point is the launcher: it starts the GUI in its own profile, before any profile + # exists and exactly as every installed format does. + plain="$("$out/anicraft" --version)" + test "$plain" = "$expected" + grep -q -- '--launch-profile nightly-v1 --profile-root' "$out/anicraft" + profile="$RUNNER_TEMP/does-not-exist/profile" + test ! -e "$profile" + launched="$("$out/anicraft" --launch-profile nightly-v1 --profile-root "$profile" --version)" + test "$launched" = "$expected" + test ! -e "$profile" + echo "tar: $plain" + - name: Keep the unsigned tar + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: anicraft-nightly-linux-x86_64-unsigned + path: ${{ runner.temp }}/nightly-dist/anicraft-${{ env.ANICRAFT_VERSION }}-linux-x86_64-nightly.tar.gz + if-no-files-found: error + retention-days: 7 + compression-level: 0 + + macos: + name: Nightly .app (aarch64, unsigned) + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-ci') && + (github.event.action != 'labeled' || github.event.label.name == 'full-ci')) + runs-on: macos-15 + timeout-minutes: 90 + env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Check out craft-fonts + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main + with: + ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main + - name: Add the Apple-silicon target + run: rustup target add aarch64-apple-darwin + - name: Prepare a Nightly identity for this commit + run: | + set -euo pipefail + base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')" + sha="$(git rev-parse HEAD)" + date="$(date -u +%Y-%m-%d)" + { + echo "ANICRAFT_BUILD_SHA=$sha" + echo "ANICRAFT_BUILD_DATE=$date" + echo "ANICRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}" + } >>"$GITHUB_ENV" + - name: Build the unsigned Nightly bundle + env: + ANICRAFT_BUILD_CHANNEL: nightly-v1 + CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets + DIST: ${{ runner.temp }}/nightly-dist + CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts + CRAFT_FONTS_REQUIRED: "1" + run: bash packaging/macos/nightly.sh --arch aarch64 + - name: Check the archive and the bundle's version + run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/anicraft-$ANICRAFT_VERSION-macos-aarch64-nightly.zip" + - name: Keep the unsigned archive + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: anicraft-nightly-macos-aarch64-unsigned + path: ${{ runner.temp }}/nightly-dist/anicraft-${{ env.ANICRAFT_VERSION }}-macos-aarch64-nightly.zip + if-no-files-found: error + retention-days: 7 + compression-level: 0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 00000000..d6807441 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,43 @@ +name: AniCraft release-ref nightly signer + +# Enabled for supervised manual dispatch on release. Main/release contents must match. +# A reusable callee does not change context; this must be a real top-level release dispatch. +on: + workflow_dispatch: + inputs: + producer_run_id: + description: Exact untrusted producer Actions run ID + required: true + type: string + producer_run_attempt: + description: Exact untrusted producer Actions run attempt + required: true + type: string + +permissions: {} + +concurrency: + group: anicraft-nightly-release + cancel-in-progress: false + queue: max + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/anicraft' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/release' && github.ref_type == 'branch' + permissions: + contents: write + actions: read + checks: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea + with: + tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + producer_run_id: ${{ inputs.producer_run_id }} + producer_run_attempt: ${{ inputs.producer_run_attempt }} + # No secrets: inherit or raw platform values in this caller. Only the isolated native + # callee job may bind the existing release environment and export keys in its signing step. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 00000000..a337ca1e --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: AniCraft unsigned nightly + +# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet. +# A later explicit opt-in may add a cadence (and a scheduled dispatch transport with it). +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/anicraft' && + github.ref == 'refs/heads/main' && github.ref_type == 'branch' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + # Maximum for the reusable workflow. Its compiler narrows to contents/actions read; + # no OIDC, attestation write, release environment or platform secrets in compilation. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea + with: + tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + app-name: anicraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + # One producer run builds every listed platform for one all-or-nothing release. The pin is the + # craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the + # Linux/macOS signer (#342). + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/.gitignore b/.gitignore index ac809ee4..c715bdf6 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,13 @@ Thumbs.db # parallel milestone worktrees (AGENTS.md › Milestone tracks) /.worktrees/ + +# Python bytecode from the Nightly packaging suites (packaging/nightly-tests.py). +__pycache__/ + +# Nightly packaging (packaging/nightly-common.sh): the shared workflow checks these out into the +# workspace, and `nightly_init` refuses a dirty tree, so they must never be committed. +/.nightly-tools +/.nightly-input +/craft-i18n +/craft-fonts diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 5b359d4f..89b314a5 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -48,9 +48,9 @@ shaders or SDK code). | File | Use | Author | Source | Licence | |---|---|---|---|---| -| `crates/xfl/tests/corpus/` (12 XFL packages: XML, `.xfl` proxies, a publish-settings file in `scripts/`, `bitmaps/LIBRARY/art/checker.png` and `sunset.jpg`) | XFL import corpus (never shipped in the app) | AniCraft contributors | Original work, written by hand from the public description of the XFL format; the two images made for it (a 16×16 checker drawn in a script, and a 32×16 ramp encoded to JPEG with ffmpeg) | MIT OR Apache-2.0 | +| `crates/xfl/tests/corpus/` (13 XFL packages: XML, `.xfl` proxies, a publish-settings file in `scripts/`, `bitmaps/LIBRARY/art/checker.png` and `sunset.jpg`) | XFL import corpus (never shipped in the app) | AniCraft contributors | Original work, written by hand from the public description of the XFL format; the two images made for it (a 16×16 checker drawn in a script, and a 32×16 ramp encoded to JPEG with ffmpeg) | MIT OR Apache-2.0 | | `crates/xfl/tests/corpus/sounds/` and `video/` media (`beep.wav`, `theme.aif`, `voice.wav`, `bin/M 3 1.dat`, `screen.flv`, `bin/M 4 2.dat`; `tone.mp3` is a copy of the audio crate's fixture below) | XFL sound and video import corpus (never shipped in the app) | AniCraft contributors | Original work, made by a script for these tests: an 880 Hz beep, an AIFF header, one block of silent IMA ADPCM, bytes in no known format, a 64×48 four-colour Screen Video key frame, an FLV header naming On2 VP6 (ADR 0086) | MIT OR Apache-2.0 | -| `crates/xfl/tests/corpus/*/golden/*.png` (20 frames, 160×90) | Golden renders of the corpus | AniCraft contributors | Original work: AniCraft's own CPU renders of the corpus (`UPDATE_GOLDENS=1`) | MIT OR Apache-2.0 | +| `crates/xfl/tests/corpus/*/golden/*.png` (21 frames, 160×90) | Golden renders of the corpus | AniCraft contributors | Original work: AniCraft's own CPU renders of the corpus (`UPDATE_GOLDENS=1`) | MIT OR Apache-2.0 | | Not committed: the legacy `.fla` corpus pinned in `crates/fla/tests/corpus.tsv` (9 sample rigs and templates, each as a Flash 8–CS6 binary `.fla` and as an Animate `.fla`) | Env-gated legacy Flash import tests (`ANICRAFT_FLA_CORPUS`; never committed or shipped) | EDAP Tools | https://flash-powertools.com/downloads/, each file pinned by URL and sha256 in the manifest and fetched by `scripts/fetch-fla-corpus.sh` | CC BY-NC-SA 3.0 | | `crates/audio/tests/data/tone.ogg`, `tone.mp3` | Decoder tests (never shipped in the app) | AniCraft contributors | Generated for these tests: half a second of a 440 Hz sine made by ffmpeg's `sine` source, encoded with libvorbis and libmp3lame | MIT OR Apache-2.0 | diff --git a/CHANGELOG.md b/CHANGELOG.md index 49f80f85..7bb3fe88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,49 @@ * Animate's own lossless bitmaps and uncompressed sounds (`bin/*.dat`) now decode in modern `.fla` and XFL files too, instead of being reported as unreadable. +* **An Animate drawing no longer loses lines without a word** (M4, ADR 0133, #498, #347, + backlog P-006). + * A stroke in a style AniCraft doesn't know was dropped, and the report still said + "Imported everything in the file". It is now drawn as a solid line with its weight, colour, + caps and joints, and counted. + * One unreadable command in a shape's outline lost everything after it on that edge. An + outline is written as runs, each starting at its own point: the command now costs the + rest of its own run only, the runs after it are drawn, and the report counts the run that + was cut short. + * The report also counts fills whose outline has a gap (they are closed straight across, + which can fill in more than the fill covered), fills of a kind AniCraft doesn't know, and + lines and fills in a style their shape doesn't have. + * The corpus has a package for these (`unknowns`), with its report, a golden frame and + probes. + * #498 came without a file, so which of these its drawing runs into is not confirmed: the + report line it now gets, or the file, will say. The merge of raw shapes on opening and the + GPU stage were ruled out with generated sketches. + * #347 (a `.fla` refused on macOS with the system's "cannot open files in this format"): + v0.2.1 did not take documents the system hands over; `main` has since ADR 0062. Not + re-tested on a Mac here. + * Not yet: the same recovery in the shared reader (storytold/craft-libs#3282). +* **Memory and frame time stay flat** (M8, P-004, ADR 0132; + [#314](https://github.com/storytold/anicraft/issues/314), + [#477](https://github.com/storytold/anicraft/issues/477)). + * **Memory follows what is on screen, not how long you have been editing.** Dragging + something made a new picture of the stage on every pointer move, and each one stayed in + memory until hundreds of megabytes were in use (the "900 MB for a 24-frame move" of #314). + AniCraft now keeps the pictures of the document as it is and as it was one step ago, at + the zoom on screen and the one before, plus the frames you have played; a long drag or a + long zoom ends with the memory it started with. + * **Zooming with Ctrl+wheel or a pinch no longer redraws the stage for every step of the + zoom.** The picture on screen is scaled while the zoom changes and drawn sharp once it + rests. In the web version, which draws on the interface's own thread, this was the + stutter of #477; there, moving around the stage now also draws for at most 8 ms of a + frame and fills in the rest over the next frames. + * **Zoomed far into a large drawing, a stage tile no longer goes through the whole + drawing.** The parts of a filled shape above, below and to the right of the tile are left + out before drawing. The pictures are the same to the last bit (tests compare them). + * **What is on screen is drawn before look-ahead.** A visible tile used to wait for up to + 31 tiles being drawn ahead around the view or along the timeline. + * One step further back in the undo history is redrawn when you return to it (a few + milliseconds) instead of being found in memory. + * **Timeline and panel bugs from the tracker** (M8, backlog P-009 and P-010, ADR 0131). * **Several layers selected at once** (#512). **Ctrl**-click a layer's name to add it or take it out, **Shift**-click for every layer from the active one, or **Shift+Up** and diff --git a/Cargo.lock b/Cargo.lock index 6a88ad8a..f65fdb47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -261,6 +261,7 @@ dependencies = [ "web-time", "winreg", "winresource", + "winsafe", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index f7ad55d7..d12f470d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -162,6 +162,10 @@ pollster.workspace = true # through craft-update. [target.'cfg(windows)'.dependencies] winreg = "0.55" +# The Nightly build's explicit AppUserModelID, set before any window exists so the taskbar, the +# Start menu and Alt-Tab keep Nightly apart from Stable (src/process_identity.rs). MIT, the same +# version and features PhotoCraft pins; both modules are already in the tree through craft-update. +winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] } # The web build (ADR 0036, docs/web.md). The window draws with WebGL2 (glow): every current # browser has it, the stage is drawn on the CPU there, and leaving wgpu out keeps the download diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 13bafc11..b0af014a 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -34,6 +34,11 @@ canonical artwork. Licence: see `LICENSE.txt`. | `hicolor//apps/ai.storyteller.anicraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime icon on Windows and Linux, the 128 one the mark in Help › About (`src/app.rs`) | Linux packaging, the Crafting Apps tables | | `hicolor/scalable/apps/ai.storyteller.anicraft.svg` | Linux scalable icon | as above | | `trace.py` | traces the 2000 px source drawing into the master SVG | regenerating the vectors | +| `anicraft-nightly.png` | the Nightly tile, 256 px, deeper field | Windows and Linux runtime and taskbar icon (`src/platform.rs`) | +| `anicraft-nightly-1024.png` | the Nightly tile on Apple's margin, 1024 px | macOS Dock icon of AniCraft Nightly | +| `anicraft-nightly.ico` | Windows Nightly icon, 16 to 256 px | `build.rs` (`AniCraft Nightly.exe` resources) | +| `anicraft-nightly.icns` | macOS Nightly bundle icon | `packaging/macos/nightly.sh` | +| `nightly-provenance.json` | input and output hashes, the palette recipe, the container members | the Nightly art's record | ## How it reaches each OS @@ -51,3 +56,21 @@ python trace.py rabbit.webp small.svg 1000 4 1960 && npx svgo@3.3.2 -p 1 small.s # Every render (needs resvg on PATH and Python with Pillow): scripts/icons.sh ``` + +## Nightly channel + +The Nightly derivatives keep the foreground artwork, alpha and Mac padding unchanged. Only the +background contribution changes, from the stable yellow (`#dac604`) to the deeper gold +(`#8a7c03`); every pixel is unmixed into field, paper and ink and re-rendered with the new field, +so line work and antialiasing stay sharp. There is no letter badge or crescent: the window title, +About and the Launcher also name the channel. + +`anicraft-nightly.png` and the nine-frame ICO use the existing native sizes, each recoloured at +its own resolution (the 20 and 40 px frames are averaged down from the 256 px master, which the +theme folder has no render of). `anicraft-nightly-1024.png` and the eleven-slot ICNS come from the +real padded Mac 1024 master, not an upscale. The stable files are never recoloured. + +`nightly-provenance.json` records the input and output hashes, the palette recipe, the generator's +hash and the container members. The generator is not committed: it writes all four files from the +committed masters in one pass (`python3 anicraft-nightly-icons.py `), and re-running it on +unchanged inputs reproduces the recorded hashes byte for byte. diff --git a/assets/app-icon/anicraft-nightly-1024.png b/assets/app-icon/anicraft-nightly-1024.png new file mode 100644 index 00000000..a66d0931 Binary files /dev/null and b/assets/app-icon/anicraft-nightly-1024.png differ diff --git a/assets/app-icon/anicraft-nightly.icns b/assets/app-icon/anicraft-nightly.icns new file mode 100644 index 00000000..a559701b Binary files /dev/null and b/assets/app-icon/anicraft-nightly.icns differ diff --git a/assets/app-icon/anicraft-nightly.ico b/assets/app-icon/anicraft-nightly.ico new file mode 100644 index 00000000..c0c75715 Binary files /dev/null and b/assets/app-icon/anicraft-nightly.ico differ diff --git a/assets/app-icon/anicraft-nightly.png b/assets/app-icon/anicraft-nightly.png new file mode 100644 index 00000000..cad10d63 Binary files /dev/null and b/assets/app-icon/anicraft-nightly.png differ diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 00000000..d7f1f317 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,76 @@ +{ + "title": "AniCraft nightly deep-background icons", + "author": "@skylartaylor", + "license": "MIT OR Apache-2.0", + "inputs": { + "assets/app-icon/hicolor/16x16/apps/ai.storyteller.anicraft.png": { + "sha256": "bfe66259f05e7f0036630d1c42843035e388cfa38c9d98f58fbe6d9679bac7d1" + }, + "assets/app-icon/hicolor/24x24/apps/ai.storyteller.anicraft.png": { + "sha256": "c77ef8abd7af110a2c559c054fc3b993fb2f42db6607a66451f6dc0d3211fe4b" + }, + "assets/app-icon/hicolor/32x32/apps/ai.storyteller.anicraft.png": { + "sha256": "9376dee658a6bcd5a7954528fe969797123a2b8176259170292ba66ec3a4d032" + }, + "assets/app-icon/hicolor/48x48/apps/ai.storyteller.anicraft.png": { + "sha256": "41ed3edaed4a88946bc6fa7796a021eee34bc88bc8813092d767971995d5cd40" + }, + "assets/app-icon/hicolor/64x64/apps/ai.storyteller.anicraft.png": { + "sha256": "2c416a39d7a1944d9733c77839b3354741049dbce52791c22bf5faffa7881074" + }, + "assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png": { + "sha256": "e6754980d8a2a4acd429f6e3e3ba5569c4a761a45102a81d7edc0ef35210ce47" + }, + "assets/app-icon/hicolor/256x256/apps/ai.storyteller.anicraft.png": { + "sha256": "fccf659e67a5c271a1089b566d95f339af97aa1309b209399c01d1f913e46159" + }, + "assets/app-icon/hicolor/512x512/apps/ai.storyteller.anicraft.png": { + "sha256": "4db02045d783e5b6ca5c7747a526ac9f6fc3a525a21fdbae09d81eae8116ddda" + }, + "assets/app-icon/anicraft-padded-1024.png": { + "sha256": "0fecc6e74052136de33d88964e26cae3b36adfdc0df2648f0572e02919c28153" + } + }, + "method": { + "kind": "code-generated derivative of the project-owned icon", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#f2f1ee", + "background": "#dac604" + }, + "nightly_background": "#8a7c03", + "transform": "Express every pixel as a barycentric mix of the three palette colours (field, paper, ink) and re-render it with only the field changed; alpha (so the Mac padding), paper and ink are unchanged. Each committed native size is recoloured at its own resolution; 20 px and 40 px ICO frames are area-averaged from the 256 px master, and the ICNS slots from the padded Mac 1024 master. No crescent, letter or badge.", + "generator_sha256": "546813e47d754f940bf2854a7fdd3eed9db46254cc57a5e57caaa32030696095" + }, + "outputs": { + "assets/app-icon/anicraft-nightly.png": "ffeec033901af322ae44f11aa338f2a985a25bd55f9e50ac464f41c1e2ab8a11", + "assets/app-icon/anicraft-nightly-1024.png": "c03e1fcbb3fd9f3afb34fc194cdd9daab5968fd48b2069dcbc331d32aed20c1c", + "assets/app-icon/anicraft-nightly.ico": "c86bdc3f065e9b5a12fbba9f52e593fd90aeefcfd8e1c3495dfac3831ce69e51", + "assets/app-icon/anicraft-nightly.icns": "ab9c90f4505dba082613526c00a96f2b3c011e9487e043a02b8ac0ab2134b27d" + }, + "ico_frame_sizes": [ + 16, + 20, + 24, + 32, + 40, + 48, + 64, + 128, + 256 + ], + "icns_png_slots": { + "icp4": 16, + "icp5": 32, + "ic11": 32, + "icp6": 64, + "ic12": 64, + "ic07": 128, + "ic08": 256, + "ic13": 256, + "ic09": 512, + "ic14": 512, + "ic10": 1024 + }, + "validation": "Input and output hashes, PNG header/colour type, ICO entry table and ICNS slot table checked; the field colour is #8a7c03 inside the tile and every source alpha is unchanged. Native Explorer, Finder and iconutil qualification remains for CI and a real Mac." +} diff --git a/build.rs b/build.rs index 3e0ec4cb..d213bc7d 100644 --- a/build.rs +++ b/build.rs @@ -14,6 +14,54 @@ use std::path::{Path, PathBuf}; +#[path = "src/build_channel.rs"] +mod build_channel; + +/// The release channel: `_BUILD_CHANNEL=nightly-v1` compiles the Nightly flavour in, and +/// `_VERSION` must then carry the exact prepared feed identity (`X.Y.Z-nightly... +/// .g`). Unset, empty or `stable` is a stable build; anything else is an error. +/// Returns whether this is Nightly and the version the binary reports. +fn build_channel() -> (bool, String) { + println!("cargo:rerun-if-env-changed=ANICRAFT_BUILD_CHANNEL"); + println!("cargo:rerun-if-env-changed=ANICRAFT_VERSION"); + println!("cargo:rerun-if-env-changed=ANICRAFT_BUILD_SHA"); + println!("cargo:rustc-check-cfg=cfg(anicraft_nightly_v1)"); + let nightly = match std::env::var("ANICRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=anicraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("error: unsupported ANICRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; + let built_version = if nightly { + match std::env::var("ANICRAFT_VERSION") { + Ok(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("error: nightly-v1 requires an explicit ANICRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + let sha = std::env::var("ANICRAFT_BUILD_SHA").unwrap_or_default(); + if nightly { + let exact = sha.len() == 40 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + if !exact || !built_version.ends_with(&format!(".g{sha:.12}")) { + eprintln!("error: nightly-v1 requires ANICRAFT_BUILD_SHA, the 40-hex commit the version names"); + std::process::exit(1); + } + } + println!("cargo:rustc-env=ANICRAFT_BUILD_SHA={sha}"); + println!("cargo:rustc-env=ANICRAFT_BUILT_VERSION={built_version}"); + (nightly, built_version) +} + /// Files we look for, and the generated constant each fills. const FONTS: [(&str, &str); 4] = [ ("Inter-Regular.ttf", "UI_FONT"), @@ -74,16 +122,24 @@ fn fail(message: &str) -> ! { std::process::exit(1); } -/// Windows only: embed the app icon into `anicraft.exe` (taskbar, Start menu, Explorer, Alt-Tab). +/// Windows only: embed the app icon and version resource into `anicraft.exe` (taskbar, Start +/// menu, Explorer, Alt-Tab). The Nightly build gets its own icon, `ProductName` "AniCraft +/// Nightly" and its exact feed version as `ProductVersion`, which the ArtCraft Launcher checks. /// A missing resource compiler is a warning, so a cross-compile still links, unless -/// `ANICRAFT_REQUIRE_WINRES=1` (packaging/windows/package.ps1). -fn windows_icon() { +/// `ANICRAFT_REQUIRE_WINRES=1` (packaging/windows/package.ps1, the Nightly producer). +fn windows_icon(nightly: bool, built_version: &str) { println!("cargo:rerun-if-changed=assets/app-icon/anicraft.ico"); + println!("cargo:rerun-if-changed=assets/app-icon/anicraft-nightly.ico"); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } let mut res = winresource::WindowsResource::new(); - res.set_icon("assets/app-icon/anicraft.ico").set("ProductName", "AniCraft").set("FileDescription", "AniCraft 2D vector animation studio"); + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "AniCraft Nightly" } else { "AniCraft" }) + .set("FileDescription", if nightly { "AniCraft Nightly animation studio" } else { "AniCraft 2D vector animation studio" }); + if nightly { + res.set("ProductVersion", built_version); + } if let Err(e) = res.compile() { if required("ANICRAFT_REQUIRE_WINRES") { fail(&format!("ANICRAFT_REQUIRE_WINRES=1 but anicraft.exe's icon and version resource could not be embedded: {e}")); @@ -108,7 +164,8 @@ fn native_features() { fn main() { native_features(); - windows_icon(); + let (nightly, built_version) = build_channel(); + windows_icon(nightly, &built_version); println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR"); println!("cargo:rerun-if-changed=build.rs"); let dir = discover(); diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index b04d10a1..945c84dc 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -130,12 +130,32 @@ impl Args { /// [`USAGE_EXIT`] (AGENTS.md rule 18, ADR 0124). pub const ROOTS_REQUIRED: &str = "mcp needs --automation-read-root and --automation-write-root "; +/// How the error starts when the Nightly window's launch protocol is given to this tool. +pub const NIGHTLY_PROTOCOL: &str = "--launch-profile and --profile-root belong to the AniCraft Nightly window"; + /// The exit code of a refused start: the command line is missing something. pub const USAGE_EXIT: i32 = 2; /// The exit code for an error from [`run`]. pub fn exit_code(error: &str) -> i32 { - if error.starts_with(ROOTS_REQUIRED) || error.starts_with("--automation-") || error.starts_with("flag --automation-") { USAGE_EXIT } else { 1 } + if error.starts_with(ROOTS_REQUIRED) + || error.starts_with(NIGHTLY_PROTOCOL) + || error.starts_with("--automation-") + || error.starts_with("flag --automation-") + { + USAGE_EXIT + } else { + 1 + } +} + +/// The Nightly launcher's two arguments, if the command line carries either (also as `=` forms): +/// this headless tool has no launch profile and no window to put in one, so it refuses them before +/// any subcommand is read. +pub fn nightly_protocol_argument(argv: &[String]) -> Option<&str> { + argv.iter() + .find(|a| *a == "--launch-profile" || *a == "--profile-root" || a.starts_with("--launch-profile=") || a.starts_with("--profile-root=")) + .map(String::as_str) } /// The folders given with `--automation-read-root` (once or more) and `--automation-write-root` @@ -251,6 +271,11 @@ pub fn subcommand_usage(cmd: &str) -> Option { /// Runs the CLI; returns the text to print on success. pub fn run(argv: &[String]) -> Result { + if let Some(argument) = nightly_protocol_argument(argv) { + return Err(format!( + "{NIGHTLY_PROTOCOL} (`{argument}`); anicraft-cli is the stable headless front end. Run `anicraft --launch-profile nightly-v1 --profile-root --` instead." + )); + } let Some((cmd, rest)) = argv.split_first() else { return Ok(USAGE.to_string()) }; if cmd == "help" || cmd == "--help" || cmd == "-h" { if let Some(sub) = rest.first().filter(|s| *s != "--help" && *s != "-h") { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6c1644f8..e6d7e45b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1533,3 +1533,5 @@ mod group_tests; mod swatch_tests; #[cfg(test)] mod parity_tests; +#[cfg(test)] +mod render_budget_tests; diff --git a/crates/engine/src/render_budget_tests.rs b/crates/engine/src/render_budget_tests.rs new file mode 100644 index 00000000..9eca0224 --- /dev/null +++ b/crates/engine/src/render_budget_tests.rs @@ -0,0 +1,271 @@ +//! Memory and frame time stay flat (P-004, ADR 0132; #314, #477): what the picture cache holds +//! doesn't grow with how long a document is edited or played, what the screen needs is drawn +//! before look-ahead, and with no render thread a view fills in a bounded step at a time. +//! These check relations, not timings; `stage_timings` prints the timings. + +use crate::Session; +use crate::render_service::{FrameJob, KEEP_SETS, Raster, Rasterizer, RenderService, lookahead_batch, make_job, render_batch, render_job}; +use anicraft_doc::{DisplayList, Document, sample}; +use anicraft_geom::Affine; +use anicraft_render::{RenderStats, View}; +use serde_json::json; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; +use std::time::Duration; + +/// The stage's tile edge. +const TILE: u32 = 512; +/// Most tiles a 1600 × 900 view can touch, wherever the tile grid falls: 5 across, 3 down. +const VIEW_TILES: usize = 15; + +/// The tiles a `vw × vh` px view centred on the stage's centre needs at device scale `z`, cut +/// as the stage cuts them. +fn view_tiles(doc: &Document, state: u64, frame: u32, z: f32, (vw, vh): (f32, f32), tile: u32) -> Vec { + let (sw, sh) = ((doc.stage.width as f32 * z).ceil() as i64, (doc.stage.height as f32 * z).ceil() as i64); + let (cx, cy) = (doc.stage.width as f32 * z / 2.0, doc.stage.height as f32 * z / 2.0); + let t = i64::from(tile); + let lo = |c: f32, half: f32| ((c - half).floor() as i64).max(0) / t; + let hi = |c: f32, half: f32, len: i64| (((c + half).ceil() as i64).min(len) - 1) / t; + let mut out = Vec::new(); + for ty in lo(cy, vh / 2.0)..=hi(cy, vh / 2.0, sh) { + for tx in lo(cx, vw / 2.0)..=hi(cx, vw / 2.0, sw) { + let view = View { transform: Affine::translate(-((tx * t) as f32), -((ty * t) as f32)).mul(&Affine::scale(z, z)), width: t.min(sw - tx * t) as u32, height: t.min(sh - ty * t) as u32, background: Some(doc.stage.background) }; + out.push(make_job(state, doc, frame, view, None)); + } + } + out +} + +/// A rasterizer that hands back blank pictures of the right size at once: what the cache keeps +/// doesn't depend on who drew it. +fn blank() -> Rasterizer { + Arc::new(|_: &DisplayList, v: &View| Ok((Raster::Premul8(vec![0; v.width as usize * v.height as usize * 4]), RenderStats::default()))) +} + +/// The stage's frame: say which set is shown, then draw what is missing. +fn show(svc: &RenderService, jobs: Vec) -> usize { + if let Some(j) = jobs.first() { + svc.show(j.set); + } + let raster = svc.raster_id(); + // Keyed for the rasterizer in use, as `RenderService::job` keys them. + let jobs: Vec = jobs.into_iter().map(|j| FrameJob { raster, ..j }).collect(); + svc.render_now_batch(jobs).len() +} + +/// #314: a drag makes a new document state on every pointer move, and each state's pictures +/// used to stay until the whole budget was full (768 MB; "900 MB for a 24-frame move"). Now +/// the cache holds the state on screen and the one before it, however long the drag. +#[test] +fn a_long_drag_holds_no_more_pictures_than_a_short_one() { + let doc = sample::demo(); + let svc = RenderService::new(1 << 30, None); + svc.set_rasterizer(Some(blank())); + let view = (1600.0, 900.0); + let mut held = Vec::new(); + for step in 0..120u64 { + let tiles = show(&svc, view_tiles(&doc, 1000 + step, 0, 1.0, view, TILE)); + let (images, bytes, ..) = svc.cache_stats(); + assert!(images <= KEEP_SETS * tiles, "step {step}: {images} pictures for {tiles} tiles on screen"); + held.push(bytes); + } + assert_eq!(held.get(10), held.last(), "the cache after 120 moves holds what it held after 10"); + // Undo: the state before is still there, so nothing is drawn again. + let back = view_tiles(&doc, 1000 + 118, 0, 1.0, view, TILE); + svc.show(back[0].set); + let raster = svc.raster_id(); + let (_, _, _, misses) = svc.cache_stats(); + assert!(svc.request_batch(back.into_iter().map(|j| FrameJob { raster, ..j }).collect()).iter().all(Option::is_some), "the state before the last is kept"); + assert_eq!(svc.cache_stats().3, misses); + // A zoom gesture is the same: every frame a new scale, two of them kept. + let mut held = Vec::new(); + for step in 0..80 { + let z = 1.0 * 1.05f32.powi(step); + let tiles = show(&svc, view_tiles(&doc, 5000, 0, z, view, TILE)); + let (images, bytes, ..) = svc.cache_stats(); + assert!(tiles <= VIEW_TILES && images <= KEEP_SETS * VIEW_TILES, "zoom step {step}: {images} pictures, {tiles} tiles on screen"); + held.push(bytes); + } + let most = held.iter().copied().max().unwrap_or(0); + assert!(most <= KEEP_SETS * VIEW_TILES * (TILE as usize * TILE as usize * 4 + 1024), "two views' worth of pictures at most: {most} bytes"); + // A picture that finishes after its set has gone (the worker was still drawing it) is not + // kept either. + let late = view_tiles(&doc, 1000, 0, 1.0, view, TILE); + let keys: Vec = late.iter().map(|j| j.key).collect(); + svc.prefetch(late.into_iter().map(|j| FrameJob { raster, ..j }).collect()); + for _ in 0..60_000 { + if !svc.busy() { + break; + } + std::thread::sleep(Duration::from_millis(1)); + } + assert!(!svc.busy()); + assert!(keys.iter().all(|k| svc.wait_for(*k, 0).is_none()), "pictures of a set long gone came back"); +} + +/// Playing a movie fills the cache with its frames once; playing it again and again adds +/// nothing, whether the budget holds the whole movie or only part of it. +#[test] +fn playing_longer_does_not_grow_the_cache() { + let doc = sample::demo(); + let frames = 24u32; + let one_frame = 6 * (TILE as usize * TILE as usize * 4); + for budget in [1usize << 30, 5 * one_frame] { + let svc = RenderService::new(budget, None); + svc.set_rasterizer(Some(blank())); + let mut after = Vec::new(); + for _lap in 0..4 { + for f in 0..frames { + show(&svc, view_tiles(&doc, 7, f, 1.0, (1600.0, 900.0), TILE)); + } + after.push(svc.cache_stats().1); + } + assert_eq!(after.first(), after.last(), "budget {budget}: four laps hold what one lap held"); + assert!(after.iter().all(|b| *b <= budget + one_frame), "budget {budget}: {after:?}"); + if budget > frames as usize * one_frame { + let (_, _, hits, misses) = svc.cache_stats(); + assert!(hits >= 3 * misses, "the laps after the first are cache hits: {hits} hits, {misses} misses"); + } + } +} + +/// A visible tile used to be drawn in the same pass as up to 31 look-ahead tiles, and shown +/// when the last of them was done. Now what the screen asks for is drawn next and alone. +#[test] +fn what_the_screen_needs_is_drawn_before_look_ahead() { + let doc = sample::demo(); + let svc = RenderService::new(64 << 20, None); + // Records each picture as its drawing starts, and waits there until the test says go. + let order: Arc>> = Arc::default(); + let go: Arc<(Mutex, Condvar)> = Arc::default(); + let (o, g) = (order.clone(), go.clone()); + let raster: Rasterizer = Arc::new(move |_: &DisplayList, v: &View| { + o.lock().unwrap_or_else(PoisonError::into_inner).push(v.width); + let mut open = g.0.lock().unwrap_or_else(PoisonError::into_inner); + while !*open { + open = g.1.wait(open).unwrap_or_else(PoisonError::into_inner); + } + Ok((Raster::Premul8(vec![0; v.width as usize * v.height as usize * 4]), RenderStats::default())) + }); + svc.set_rasterizer(Some(raster)); + let view = |w: u32| View { transform: Affine::scale(0.1, 0.1), width: w, height: 4, background: None }; + // Look-ahead (5 px wide) for many frames; the worker starts on it and is held there. + let pass = lookahead_batch(); + svc.prefetch((0..(4 * pass as u32 + 8)).map(|f| svc.job(1, &doc, f, view(5), None)).collect()); + let started = |n: usize| { + for _ in 0..60_000 { + if order.lock().unwrap_or_else(PoisonError::into_inner).len() >= n { + return true; + } + std::thread::sleep(Duration::from_millis(1)); + } + false + }; + assert!(started(1), "the worker began the look-ahead"); + // Now the screen asks for three pictures (7 px wide). + let urgent: Vec = (100..103).map(|f| svc.job(1, &doc, f, view(7), None)).collect(); + let keys: Vec = urgent.iter().map(|j| j.key).collect(); + assert!(svc.request_batch(urgent).iter().all(Option::is_none)); + *go.0.lock().unwrap_or_else(PoisonError::into_inner) = true; + go.1.notify_all(); + for k in keys { + assert!(svc.wait_for(k, 60_000).is_some()); + } + let order = order.lock().unwrap_or_else(PoisonError::into_inner).clone(); + let last = order.iter().rposition(|w| *w == 7).unwrap_or(usize::MAX); + assert!(last < pass + 3, "the screen's pictures came after {last} others; one look-ahead pass is {pass} ({order:?})"); +} + +/// The browser has no render thread (ADR 0036): a view that needs many tiles used to draw them +/// all inside one frame. Within a budget it draws what fits (at least one) and the rest over +/// the next frames, nearest first, and the pictures are the oracle's. +#[test] +fn without_a_thread_a_view_fills_in_a_step_at_a_time() { + let doc = sample::demo(); + let svc = RenderService::without_thread(64 << 20); + assert!(!svc.has_thread()); + let jobs = view_tiles(&doc, 3, 9, 0.25, (320.0, 180.0), 64); + assert!(jobs.len() >= 12, "{} tiles", jobs.len()); + let mut frames = 0; + loop { + frames += 1; + let got = svc.request_batch_within(jobs.clone(), Duration::ZERO); + let ready = got.iter().filter(|g| g.is_some()).count(); + assert_eq!(ready, frames, "one more picture each frame, and the earlier ones from the cache"); + assert!(got.iter().take(ready).all(Option::is_some), "in the order asked for"); + if ready == jobs.len() { + for (j, img) in jobs.iter().zip(&got) { + assert_eq!(img.as_ref().map(|i| &i.rgba_premul), Some(&render_job(j).rgba_premul)); + } + break; + } + } + // With all the time it needs, or asked the plain way (an edit, a frame of playback: one + // whole picture), everything comes at once. + let other = view_tiles(&doc, 4, 9, 0.25, (320.0, 180.0), 64); + assert!(svc.request_batch_within(other, Duration::from_secs(3600)).iter().all(Option::is_some)); + assert!(svc.request_batch(view_tiles(&doc, 5, 9, 0.25, (320.0, 180.0), 64)).iter().all(Option::is_some)); +} + +/// A drawing made with the Brush tool: `n` wavy strokes across the stage, merged into the +/// drawing as the tool does off Object Drawing. +fn brush_drawing(n: u32) -> Session { + let mut s = Session::new(Document::default()); + for k in 0..n { + let pts: Vec<[f32; 2]> = (0..=120) + .map(|i| { + let t = i as f32 / 120.0; + [60.0 + t * 1100.0, 80.0 + (k % 8) as f32 * 70.0 + (k / 8) as f32 * 9.0 + (t * 14.0 + k as f32).sin() * 40.0] + }) + .collect(); + s.execute("draw.brush", &json!({"points": pts, "size": 12, "object": false})).expect("a brush stroke"); + } + s +} + +/// #477, through the stage's own path: zoomed all the way into a brush drawing, the tiles of a +/// view together walk fewer edges than the view of the whole drawing at 100 %. +#[test] +fn a_view_at_the_deepest_zoom_walks_fewer_edges_than_the_whole_drawing() { + let s = brush_drawing(12); + let edges = |z: f32| render_batch(&view_tiles(&s.doc, 1, 0, z, (800.0, 450.0), 256)).iter().map(|i| i.stats.edges).sum::(); + let (normal, deep) = (edges(1.0), edges(64.0)); + assert!(deep > 0 && deep < normal, "{deep} edges at 6400 %, {normal} at 100 %"); +} + +/// What a 1600 × 900 stage view costs at each zoom, on the CPU oracle, in the stage's tiles: +/// `cargo test --release -p anicraft-engine --lib stage_timings -- --ignored --nocapture`. +#[test] +#[ignore = "a measurement, not a check"] +fn stage_timings() { + for (name, s) in [("8 brush strokes", brush_drawing(8)), ("64 brush strokes, merged", brush_drawing(64)), ("512 brush strokes, merged", brush_drawing(512))] { + let doc = &s.doc; + println!("-- {name}: {} items", s.display_list().items.len()); + println!("zoom tiles ms/view edges prepare ms one thread ms"); + for z in [1.0f32, 4.0, 16.0, 64.0] { + let jobs = view_tiles(doc, 1, 0, z, (1600.0, 900.0), TILE); + let _ = render_batch(&jobs); + let t = std::time::Instant::now(); + let mut edges = 0; + for _ in 0..5 { + edges = render_batch(&jobs).iter().map(|i| i.stats.edges).sum::(); + } + let ms = t.elapsed().as_secs_f64() * 1000.0 / 5.0; + let dl = jobs[0].display_list(); + let t = std::time::Instant::now(); + for j in &jobs { + let _ = anicraft_render::prepare_scene(&dl, &j.view); + } + let prep = t.elapsed().as_secs_f64() * 1000.0; + // As the browser draws: one thread, a tile after another. + let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("a pool"); + let t = std::time::Instant::now(); + pool.install(|| { + for j in &jobs { + let _ = crate::render_service::render_job_with(j, &dl); + } + }); + let single = t.elapsed().as_secs_f64() * 1000.0; + println!("{z:>4} {:>5} {ms:>7.2} {edges:>6} {prep:>10.2} {single:>13.2}", jobs.len()); + } + } +} diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs index abf5c53b..9e7a159d 100644 --- a/crates/engine/src/render_service.rs +++ b/crates/engine/src/render_service.rs @@ -13,6 +13,21 @@ //! the picture is always complete. Keys include which rasterizer drew them. A rasterizer may //! keep its pictures on the GPU ([`Raster::Native`], ADR 0029): the cache then holds them, under //! a budget of their own, and only the shell knows what they are. +//! +//! **What the cache keeps (ADR 0132).** Every picture belongs to a *picture set*: one document +//! state at one scale ([`set_key`]). The stage says which set it shows +//! ([`RenderService::show`]); the cache keeps that set and the one shown before it, and lets the +//! others go at once. A drag makes a new state on every pointer move and a zoom gesture a new +//! scale on every frame: their pictures can never be asked for again, so memory follows what is +//! on screen and the frames played, not how long the document has been edited. The byte budgets +//! still bound the sets that are kept. +//! +//! **Order of work.** What the screen needs is drawn before any look-ahead, in batches of its +//! own, so a visible tile never waits for a tile nobody sees yet. +//! +//! **Without a render thread** (the browser, ADR 0036) a request draws on the caller's thread. +//! [`RenderService::request_batch_within`] stops after a time budget, so moving around the stage +//! costs a bounded part of each frame and the rest arrives over the next frames. use crate::editing::Front; use crate::history::StateId; @@ -32,6 +47,8 @@ pub struct FrameJob { pub key: u64, /// Which rasterizer the key was made for (0: the CPU oracle); see [`RenderService::job`]. pub raster: u64, + /// The picture set the image belongs to ([`set_key`]): the cache keeps the newest sets. + pub set: u64, /// Identity of the evaluated scene (`scene_key`): tiles of one frame share it. pub scene: u64, pub doc: Document, @@ -169,6 +186,8 @@ fn parent_onion(doc: &Document, p: &crate::editing::Around, front: &Front, skin: /// already on the GPU. pub struct FrameImage { pub key: u64, + /// The picture set it belongs to ([`set_key`]). + pub set: u64, pub frame: u32, pub width: u32, pub height: u32, @@ -213,6 +232,18 @@ pub fn scene_key(state: StateId, frame: u32, onion: Option<&OnionSkin>) -> u64 { h.finish() } +/// Identity of a **picture set** (ADR 0132): every picture of document state `state` at `view`'s +/// scale and turn, whatever the frame, the tile or the overlays. Where the view is doesn't +/// count, so every tile of a stage view is in one set, and so are the frames played at it. +pub fn set_key(state: StateId, view: &View) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (state, "set").hash(&mut h); + for v in view.transform.m.iter().take(4) { + v.to_bits().hash(&mut h); + } + h.finish() +} + /// Cache key for a scene seen through a view (a frame or a tile). pub fn frame_key(state: StateId, frame: u32, view: &View, onion: Option<&OnionSkin>) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); @@ -233,7 +264,7 @@ pub fn frame_key(state: StateId, frame: u32, view: &View, onion: Option<&OnionSk /// A job whose `scene` is derived from the same inputs as its key. pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob { let onion = onion.filter(|o| o.shows()).copied(); - FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false, front: None, reference: None } + FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, set: set_key(state, &view), scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false, front: None, reference: None } } /// A job for rasterizer `raster` (from [`RenderService::raster_id`]; 0 is the CPU oracle, and @@ -275,7 +306,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>) let (w, h) = (job.view.width, job.view.height); let done = |rgba_premul: Vec, native: Option, stats: RenderStats| { let ms = t0.elapsed().as_secs_f32() * 1000.0; - FrameImage { key: job.key, frame: job.frame, width: w, height: h, rgba_premul, native, ms, stats, error: None, gpu: true, fallback: None } + FrameImage { key: job.key, set: job.set, frame: job.frame, width: w, height: h, rgba_premul, native, ms, stats, error: None, gpu: true, fallback: None } }; match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| r(dl, &job.view))) { Ok(Ok((Raster::Premul8(rgba), stats))) if rgba.len() == w as usize * h as usize * 4 => return done(rgba, None, stats), @@ -292,7 +323,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>) Err(_) => (Vec::new(), RenderStats::default(), Some("the renderer failed on this frame".into())), }; let (width, height) = if error.is_none() { (job.view.width, job.view.height) } else { (0, 0) }; - FrameImage { key: job.key, frame: job.frame, width, height, rgba_premul: rgba, native: None, ms: t0.elapsed().as_secs_f32() * 1000.0, stats, error, gpu: false, fallback } + FrameImage { key: job.key, set: job.set, frame: job.frame, width, height, rgba_premul: rgba, native: None, ms: t0.elapsed().as_secs_f32() * 1000.0, stats, error, gpu: false, fallback } } /// Renders a job synchronously, evaluating its scene. @@ -305,13 +336,24 @@ pub fn render_batch(jobs: &[FrameJob]) -> Vec { render_batch_by(jobs, &RasterSlot::default()) } +/// Evaluated scenes by [`FrameJob::scene`]. +type Scenes = HashMap>; + /// [`render_batch`] with the service's rasterizer for the jobs made for it. fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec { - let mut scenes: HashMap> = HashMap::new(); + render_batch_from(jobs, slot, &Scenes::new()).0 +} + +/// [`render_batch_by`], taking the scenes it needs from `known` when they are there (the pass +/// before: a view and the look-ahead around it are several passes of one scene). The pictures, +/// and this batch's scenes for the next. +fn render_batch_from(jobs: &[FrameJob], slot: &RasterSlot, known: &Scenes) -> (Vec, Scenes) { + let mut scenes = Scenes::new(); for j in jobs { - scenes.entry(j.scene).or_insert_with(|| Arc::new(j.display_list())); + scenes.entry(j.scene).or_insert_with(|| known.get(&j.scene).cloned().unwrap_or_else(|| Arc::new(j.display_list()))); } - jobs.par_iter() + let imgs = jobs + .par_iter() .map(|j| { // A job made for another rasterizer (queued before a switch) is drawn by the oracle. let raster = slot.raster.as_ref().filter(|_| j.raster != 0 && j.raster == slot.id); @@ -320,7 +362,8 @@ fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec { None => render_job_by(j, &j.display_list(), raster), } }) - .collect() + .collect(); + (imgs, scenes) } /// The rasterizer in use and its id (0 and `None`: the oracle). @@ -344,8 +387,15 @@ pub struct FrameCache { /// How many times the cache was cleared: a picture whose drawing began before a clear /// belongs to the document that was put aside, and is not kept. cleared: u64, + /// The picture sets kept, the one on screen first (ADR 0132); empty until + /// [`FrameCache::show`] is first called, and then every set is kept. + recent: VecDeque, } +/// Picture sets the cache keeps: the one on screen and the one before it, so undo then redo, +/// or a zoom there and back, finds its pictures. +pub const KEEP_SETS: usize = 2; + /// `(bytes in memory, bytes on the GPU)` an image holds. fn cost(img: &FrameImage) -> (usize, usize) { let gpu = if img.native.is_some() { img.width as usize * img.height as usize * 4 } else { 0 }; @@ -354,7 +404,7 @@ fn cost(img: &FrameImage) -> (usize, usize) { impl FrameCache { pub fn new(budget_bytes: usize) -> Self { - FrameCache { map: HashMap::new(), tick: 0, bytes: 0, native_bytes: 0, budget_bytes, native_budget_bytes: DEFAULT_NATIVE_CACHE_BYTES, hits: 0, misses: 0, cleared: 0 } + FrameCache { map: HashMap::new(), tick: 0, bytes: 0, native_bytes: 0, budget_bytes, native_budget_bytes: DEFAULT_NATIVE_CACHE_BYTES, hits: 0, misses: 0, cleared: 0, recent: VecDeque::new() } } pub fn get(&mut self, key: u64) -> Option> { self.tick += 1; @@ -374,7 +424,39 @@ impl FrameCache { pub fn contains(&self, key: u64) -> bool { self.map.contains_key(&key) } + /// The stage shows picture set `set` from now on: it and the set shown before it are kept, + /// and the pictures of every other set go. How many went. + pub fn show(&mut self, set: u64) -> usize { + if self.recent.front() == Some(&set) { + return 0; + } + // Shown again (undo then redo): it moves to the front and nothing goes. + if let Some(at) = self.recent.iter().position(|s| *s == set) { + self.recent.remove(at); + self.recent.push_front(set); + return 0; + } + self.recent.push_front(set); + self.recent.truncate(KEEP_SETS); + let gone: Vec = self.map.iter().filter(|(_, (i, _))| !self.recent.contains(&i.set)).map(|(&k, _)| k).collect(); + for k in &gone { + if let Some((old, _)) = self.map.remove(k) { + self.forget(&old); + } + } + gone.len() + } + + /// Whether pictures of `set` are kept (all are until a set is shown). + pub fn keeps(&self, set: u64) -> bool { + self.recent.is_empty() || self.recent.contains(&set) + } + pub fn insert(&mut self, img: Arc) { + // Drawn for a set that is no longer kept (it finished late): nobody will ask for it. + if !self.keeps(img.set) { + return; + } self.tick += 1; let (cpu, gpu) = cost(&img); if let Some((old, _)) = self.map.insert(img.key, (img, self.tick)) { @@ -407,6 +489,7 @@ impl FrameCache { self.bytes = 0; self.native_bytes = 0; self.cleared += 1; + self.recent.clear(); } pub fn len(&self) -> usize { self.map.len() @@ -439,6 +522,9 @@ struct Shared { wake: Condvar, cache: Mutex, notify: Option>, + /// The scene last evaluated on the caller's thread (no render thread): the frames a view + /// takes to fill in share it. + scene: Mutex)>>, } /// Default image-cache budget. @@ -448,6 +534,12 @@ pub const DEFAULT_NATIVE_CACHE_BYTES: usize = 384 * 1024 * 1024; /// Most jobs the worker renders in one parallel pass. const BATCH: usize = 32; +/// Most look-ahead jobs in one pass: one per thread, so a pass takes about as long as one +/// picture and what the screen asks for meanwhile starts that soon. +pub fn lookahead_batch() -> usize { + rayon::current_num_threads().clamp(1, BATCH) +} + /// A render thread plus its cache. pub struct RenderService { shared: Arc, @@ -458,12 +550,35 @@ impl RenderService { /// Starts the worker. `notify` runs on the worker after each finished batch (the UI passes /// "request a repaint"). If no thread can be spawned, requests render synchronously. pub fn new(cache_bytes: usize, notify: Option>) -> RenderService { - let shared = Arc::new(Shared { queue: Mutex::new(Queue::default()), raster: Mutex::new(RasterSlot::default()), wake: Condvar::new(), cache: Mutex::new(FrameCache::new(cache_bytes)), notify }); + let shared = Self::shared(cache_bytes, notify); let s = shared.clone(); let worker = std::thread::Builder::new().name("anicraft-render".into()).spawn(move || worker_loop(&s)).ok(); RenderService { shared, worker } } + /// A service with no render thread, as in the browser (ADR 0036): requests draw on the + /// caller's thread. On builds that have threads, this is how that way of working is + /// measured and tested. + pub fn without_thread(cache_bytes: usize) -> RenderService { + RenderService { shared: Self::shared(cache_bytes, None), worker: None } + } + + fn shared(cache_bytes: usize, notify: Option>) -> Arc { + Arc::new(Shared { queue: Mutex::new(Queue::default()), raster: Mutex::new(RasterSlot::default()), wake: Condvar::new(), cache: Mutex::new(FrameCache::new(cache_bytes)), notify, scene: Mutex::new(None) }) + } + + /// Whether pictures are drawn on a render thread (not in the browser). + pub fn has_thread(&self) -> bool { + self.worker.is_some() + } + + /// The stage shows picture set `set` (a job's [`FrameJob::set`]) from now on: the cache + /// keeps it and the set before it and lets the rest go (ADR 0132). Cheap when nothing + /// changed, so the stage calls it every frame. + pub fn show(&self, set: u64) { + self.cache().show(set); + } + fn cache(&self) -> std::sync::MutexGuard<'_, FrameCache> { self.shared.cache.lock().unwrap_or_else(PoisonError::into_inner) } @@ -504,6 +619,18 @@ impl RenderService { /// Images that are ready, in order; the missing ones become the new urgent batch /// (replacing any older pending batch). pub fn request_batch(&self, jobs: Vec) -> Vec>> { + self.request_some(jobs, None) + } + + /// [`RenderService::request_batch`] for moving around a picture (a pan, a zoom that has + /// come to rest): with no render thread, drawing stops once `budget` is spent (after at + /// least one picture), and the rest come back `None` to be asked for again next frame, in + /// the order given. With a render thread nothing is drawn here and the budget is not used. + pub fn request_batch_within(&self, jobs: Vec, budget: std::time::Duration) -> Vec>> { + self.request_some(jobs, Some(budget)) + } + + fn request_some(&self, jobs: Vec, budget: Option) -> Vec>> { let mut out = Vec::with_capacity(jobs.len()); let mut missing = Vec::new(); { @@ -523,11 +650,15 @@ impl RenderService { } if self.worker.is_none() { // No thread available: render here, so the caller still gets pictures. - let imgs: Vec> = render_batch_by(&missing, &self.slot()).into_iter().map(Arc::new).collect(); + let imgs: Vec> = match budget { + None => render_batch_by(&missing, &self.slot()).into_iter().map(Arc::new).collect(), + Some(budget) => self.render_within(&missing, budget), + }; let mut cache = self.cache(); for img in &imgs { cache.insert(img.clone()); } + // In order: the ones the budget left out stay `None`. let mut it = imgs.into_iter(); for slot in out.iter_mut().filter(|s| s.is_none()) { *slot = it.next(); @@ -543,6 +674,33 @@ impl RenderService { out } + /// The first of `jobs`, one after another on this thread, until `budget` is spent (always + /// at least one). Their scene is evaluated once and kept for the next call. + fn render_within(&self, jobs: &[FrameJob], budget: std::time::Duration) -> Vec> { + let started = Instant::now(); + let slot = self.slot(); + let mut out = Vec::new(); + for j in jobs { + if !out.is_empty() && started.elapsed() >= budget { + break; + } + let dl = { + let mut memo = self.shared.scene.lock().unwrap_or_else(PoisonError::into_inner); + match memo.as_ref().filter(|(k, _)| *k == j.scene) { + Some((_, dl)) => dl.clone(), + None => { + let dl = Arc::new(j.display_list()); + *memo = Some((j.scene, dl.clone())); + dl + } + } + }; + let raster = slot.raster.as_ref().filter(|_| j.raster != 0 && j.raster == slot.id); + out.push(Arc::new(render_job_by(j, &dl, raster))); + } + out + } + /// Single-image form of [`RenderService::request_batch`]. pub fn request(&self, job: FrameJob) -> Option> { self.request_batch(vec![job]).into_iter().next().flatten() @@ -582,10 +740,10 @@ impl RenderService { /// Single-image form of [`RenderService::render_now_batch`]. pub fn render_now(&self, job: FrameJob) -> Arc { - let key = job.key; + let (key, set) = (job.key, job.set); let frame = job.frame; self.render_now_batch(vec![job]).into_iter().next().unwrap_or_else(|| { - Arc::new(FrameImage { key, frame, width: 0, height: 0, rgba_premul: Vec::new(), native: None, ms: 0.0, stats: RenderStats::default(), error: Some("render failed".into()), gpu: false, fallback: None }) + Arc::new(FrameImage { key, set, frame, width: 0, height: 0, rgba_premul: Vec::new(), native: None, ms: 0.0, stats: RenderStats::default(), error: Some("render failed".into()), gpu: false, fallback: None }) }) } @@ -624,6 +782,7 @@ impl RenderService { q.prefetch.clear(); } self.cache().clear(); + *self.shared.scene.lock().unwrap_or_else(PoisonError::into_inner) = None; } /// `(images, bytes, hits, misses)`. @@ -661,6 +820,8 @@ impl Drop for RenderService { } fn worker_loop(s: &Shared) { + // The scenes of the pass before, for the passes of one view. + let mut scenes = Scenes::new(); loop { // Take a whole batch: urgent first, topped up with prefetch work. let jobs: Vec = { @@ -670,9 +831,14 @@ fn worker_loop(s: &Shared) { return; } if !q.urgent.is_empty() || !q.prefetch.is_empty() { + // What the screen needs, alone: a visible tile never waits for look-ahead + // drawn in the same pass. Look-ahead goes in short passes, so the next + // urgent batch starts soon (ADR 0132). + let urgent = !q.urgent.is_empty(); + let most = if urgent { BATCH } else { lookahead_batch() }; let mut batch = Vec::new(); - while batch.len() < BATCH { - let Some(j) = q.urgent.pop_front().or_else(|| q.prefetch.pop_front()) else { break }; + while batch.len() < most { + let Some(j) = (if urgent { q.urgent.pop_front() } else { q.prefetch.pop_front() }) else { break }; batch.push(j); } for j in &batch { @@ -685,10 +851,12 @@ fn worker_loop(s: &Shared) { }; let (todo, cleared): (Vec, u64) = { let cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner); - (jobs.iter().filter(|j| !cache.contains(j.key)).cloned().collect(), cache.cleared) + // Not what is cached already, nor what the cache would not keep (its set went). + (jobs.iter().filter(|j| !cache.contains(j.key) && cache.keeps(j.set)).cloned().collect(), cache.cleared) }; let slot = s.raster.lock().unwrap_or_else(PoisonError::into_inner).clone(); - let imgs = render_batch_by(&todo, &slot); + let (imgs, evaluated) = render_batch_from(&todo, &slot, &scenes); + scenes = evaluated; { let mut cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner); // Cleared meanwhile (`forget_pictures`): these show a document put aside. @@ -703,6 +871,10 @@ fn worker_loop(s: &Shared) { for j in &jobs { q.busy.remove(&j.key); } + // Nothing more to draw: an idle worker holds no document's scene. + if q.urgent.is_empty() && q.prefetch.is_empty() { + scenes.clear(); + } } if let Some(n) = &s.notify { n(); @@ -879,7 +1051,7 @@ mod tests { fn cache_respects_budget_lru() { let mut c = FrameCache::new(3 * 1000); for k in 0..10u64 { - c.insert(Arc::new(FrameImage { key: k, frame: 0, width: 0, height: 0, rgba_premul: vec![0; 800], native: None, ms: 0.0, stats: RenderStats::default(), error: None, gpu: false, fallback: None })); + c.insert(Arc::new(FrameImage { key: k, set: 0, frame: 0, width: 0, height: 0, rgba_premul: vec![0; 800], native: None, ms: 0.0, stats: RenderStats::default(), error: None, gpu: false, fallback: None })); } assert!(c.bytes() <= 3000); assert!(c.contains(9) && !c.contains(0)); @@ -893,7 +1065,7 @@ mod tests { c.native_budget_bytes = 1000; let img = |k: u64, native: bool| { let n: Option = native.then(|| Arc::new(k) as NativeImage); - Arc::new(FrameImage { key: k, frame: 0, width: 10, height: 10, rgba_premul: if native { Vec::new() } else { vec![0; 400] }, native: n, ms: 0.0, stats: RenderStats::default(), error: None, gpu: native, fallback: None }) + Arc::new(FrameImage { key: k, set: 0, frame: 0, width: 10, height: 10, rgba_premul: if native { Vec::new() } else { vec![0; 400] }, native: n, ms: 0.0, stats: RenderStats::default(), error: None, gpu: native, fallback: None }) }; c.insert(img(100, false)); for k in 0..5 { diff --git a/crates/engine/tests/wasm.rs b/crates/engine/tests/wasm.rs index ee0e7fbe..aeac8ca5 100644 --- a/crates/engine/tests/wasm.rs +++ b/crates/engine/tests/wasm.rs @@ -133,3 +133,64 @@ fn exports_and_reimports_svg_and_lottie_in_memory() { assert!(lottie["layers"].as_array().is_some_and(|l| !l.is_empty())); assert!(lottie_bytes.windows(5).any(|w| w == b"\"a\":1")); } + +/// Pages of this module's memory, which only ever grows: what a browser tab is charged for. +fn memory_mb() -> f64 { + core::arch::wasm32::memory_size(0) as f64 * 65536.0 / 1048576.0 +} + +/// #314 in the browser itself (P-004, ADR 0132): a long drag is a new document state on every +/// pointer move. The stage says which state it shows, so the pictures of the states before go +/// and the module's memory stops growing after the first moves; before, every state's pictures +/// stayed until the cache's whole budget was in use. A view also fills in a step at a time +/// when it is asked for within a budget, since there is no thread to draw it. +#[wasm_bindgen_test] +fn a_long_drag_does_not_grow_the_memory() { + use anicraft_engine::geom::Affine; + use anicraft_engine::render::View; + let mut s = Session::new(anicraft_engine::doc::sample::demo()); + s.execute("edit.select_all", &json!({})).unwrap(); + let svc = RenderService::new(256 << 20, None); + assert!(!svc.has_thread()); + // A 1024 × 512 view of the stage in two tiles, as the stage cuts it. + let tiles = |s: &Session| -> Vec<_> { + (0..2).map(|tx| svc.job(s.state, &s.doc, 0, View { transform: Affine::translate(-512.0 * tx as f32, 0.0), width: 512, height: 512, background: Some(s.doc.stage.background) }, None)).collect() + }; + let drag = |s: &mut Session, moves: u32, show: bool| { + let started = web_time::Instant::now(); + for i in 0..moves { + s.execute("element.translate", &json!({"dx": if i % 2 == 0 { 2 } else { -2 }, "dy": 0})).unwrap(); + let jobs = tiles(s); + if show { + svc.show(jobs[0].set); + } + assert!(svc.request_batch(jobs).iter().all(Option::is_some)); + } + started.elapsed().as_secs_f64() * 1000.0 / f64::from(moves) + }; + let start = memory_mb(); + drag(&mut s, 12, true); + let early = memory_mb(); + let ms = drag(&mut s, 120, true); + let late = memory_mb(); + wasm_bindgen_test::console_log!("drag, the shown state kept: {start:.0} MB at the start, {early:.0} MB after 12 moves, {late:.0} MB after 132; {ms:.1} ms a move; cache {:.0} MB", svc.cache_stats().1 as f64 / 1048576.0); + assert!(late <= early + 8.0, "memory grew from {early} MB to {late} MB over 120 more moves"); + assert!(svc.cache_stats().0 <= 4, "two states of two tiles"); + // Fills in a step at a time within a budget. + s.execute("element.translate", &json!({"dx": 1, "dy": 0})).unwrap(); + let jobs = tiles(&s); + svc.show(jobs[0].set); + let first = svc.request_batch_within(jobs.clone(), std::time::Duration::ZERO); + assert_eq!(first.iter().filter(|i| i.is_some()).count(), 1); + assert!(svc.request_batch_within(jobs, std::time::Duration::ZERO).iter().all(Option::is_some)); + // As it was before (every state's pictures kept): the same drag again without saying + // what is shown. Printed for docs/performance.md, not checked. + let svc_before = RenderService::new(256 << 20, None); + let before = memory_mb(); + for i in 0..120 { + s.execute("element.translate", &json!({"dx": if i % 2 == 0 { 2 } else { -2 }, "dy": 0})).unwrap(); + let jobs: Vec<_> = (0..2).map(|tx| svc_before.job(s.state, &s.doc, 0, View { transform: Affine::translate(-512.0 * tx as f32, 0.0), width: 512, height: 512, background: Some(s.doc.stage.background) }, None)).collect(); + svc_before.request_batch(jobs); + } + wasm_bindgen_test::console_log!("drag, every state kept (before): {before:.0} MB to {:.0} MB over 120 moves; cache {:.0} MB", memory_mb(), svc_before.cache_stats().1 as f64 / 1048576.0); +} diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index a90384fc..fc2ec214 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -45,6 +45,7 @@ const FRAMES: &[(&str, &[u32])] = &[ ("text", &[0]), ("textfields", &[0]), ("tweens", &[0, 6, 12]), + ("unknowns", &[0]), ("video", &[0]), ]; @@ -73,6 +74,19 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("video", 0, 100.0, 80.0, 0xE9C46A), ("video", 0, 200.0, 50.0, 0x264653), ("video", 0, 10.0, 150.0, 0xFFFFFF), + // ADR 0133: a stroke of an unknown kind is drawn; an outline run cut short keeps what came + // before the cut (to x 70) and loses the rest of that run only, so the run after it is + // drawn; a line in a style the shape lacks is not. Then the whole fill, the fill of an + // unknown kind (left out), and the fill missing a side (closed straight across). + ("unknowns", 0, 80.0, 30.0, 0x264653), + ("unknowns", 0, 45.0, 60.0, 0xE76F51), + ("unknowns", 0, 120.0, 60.0, 0xF4F1EA), + ("unknowns", 0, 230.0, 60.0, 0xE76F51), + ("unknowns", 0, 80.0, 80.0, 0xF4F1EA), + ("unknowns", 0, 50.0, 130.0, 0x2A9D8F), + ("unknowns", 0, 130.0, 130.0, 0xF4F1EA), + ("unknowns", 0, 210.0, 130.0, 0xE9C46A), + ("unknowns", 0, 280.0, 130.0, 0xF4F1EA), ("primitives", 0, 40.0, 50.0, 0xF2CC8F), ("primitives", 0, 210.0, 40.0, 0xE07A5F), // The nested group's square at half size (#411). diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 57d7e091..e47bc6e3 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -444,6 +444,14 @@ impl Path { /// Flattens under `m` into polylines whose deviation from the true curve is at most /// `tolerance` (in output units). Non-finite points are dropped. pub fn flatten(&self, m: &Affine, tolerance: f32) -> Vec { + self.flatten_with(m, tolerance, |_| false) + } + + /// [`Path::flatten`], except that a curve `chord` says yes to becomes one line to its end + /// point. `chord` is given the curve's control points under `m`, its start first (three for + /// a quadratic, four for a cubic); a curve lies inside their hull. For a caller that knows + /// where the shape of a curve can't matter (a renderer, far outside its surface). + pub fn flatten_with(&self, m: &Affine, tolerance: f32, chord: impl Fn(&[Vec2]) -> bool) -> Vec { let tol = if tolerance.is_finite() && tolerance > 1e-4 { tolerance } else { 0.1 }; let mut out: Vec = Vec::new(); let mut cur = Polyline::default(); @@ -480,7 +488,7 @@ impl Path { push_finite(&mut cur.points, last); } let dd = (last - c1 * 2.0 + p).length(); - let n = segments(0.25 * dd, tol); + let n = if chord(&[last, c1, p]) { 1 } else { segments(0.25 * dd, tol) }; for i in 1..=n { let t = i as f32 / n as f32; let mt = 1.0 - t; @@ -495,7 +503,7 @@ impl Path { push_finite(&mut cur.points, last); } let dd = (last - c1 * 2.0 + c2).length().max((c1 - c2 * 2.0 + p).length()); - let n = segments(0.75 * dd, tol); + let n = if chord(&[last, c1, c2, p]) { 1 } else { segments(0.75 * dd, tol) }; for i in 1..=n { let t = i as f32 / n as f32; let mt = 1.0 - t; diff --git a/crates/render/src/cut_tests.rs b/crates/render/src/cut_tests.rs new file mode 100644 index 00000000..e377b66c --- /dev/null +++ b/crates/render/src/cut_tests.rs @@ -0,0 +1,147 @@ +//! What the renderer leaves out far off the surface (ADR 0132) changes no pixel: every picture +//! here is drawn twice, cut and whole, and compared bit for bit. + +use super::*; +use anicraft_doc::{ElementId, GradientStop, LayerId, sample}; +use anicraft_geom::Path; +use std::sync::Arc; + +fn item(path: Path, fill: Paint, rule: FillRule) -> DisplayItem { + DisplayItem { + path: Arc::new(path), + transform: Affine::IDENTITY, + fill: Some(fill), + stroke: None, + fill_rule: rule, + color: ColorTransform::IDENTITY, + layer: LayerId(0), + element: ElementId(0), + outline: None, + clip: None, + masks: None, + guide: false, + group: None, + image: None, + smooth: true, + warp: None, + } +} + +/// A drawing as the Brush tool leaves one: `n` wavy ribbons across a 1280 × 720 stage, all +/// subpaths of one path (strokes merged into a shape), made of curves. +fn ribbons(n: u32) -> Path { + let mut p = Path::new(); + for k in 0..n { + let y = 30.0 + k as f32 * 660.0 / n as f32; + let wave = |i: u32, off: f32| Vec2::new(40.0 + i as f32 * 30.0, y + off + ((i + k) as f32 * 0.9).sin() * 18.0); + p.move_to(wave(0, 0.0)); + for i in 1..=40 { + let (a, b) = (wave(i - 1, 0.0), wave(i, 0.0)); + p.cubic_to(a + Vec2::new(10.0, -14.0), b + Vec2::new(-10.0, 14.0), b); + } + for i in (0..40).rev() { + let (a, b) = (wave(i + 1, 9.0), wave(i, 9.0)); + p.cubic_to(a + Vec2::new(-10.0, 14.0), b + Vec2::new(10.0, -14.0), b); + } + p.close(); + } + p +} + +fn drawing() -> DisplayList { + let gradient = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(1280.0, 720.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff3300) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0066ff) }]); + let mut over = item(ribbons(7), gradient, FillRule::EvenOdd); + over.transform = Affine::translate(15.0, 22.0); + // A stroked curve and a quadratic blob too: strokes are never cut, quadratics are. + let mut line = item(Path::ellipse(640.0, 360.0, 500.0, 300.0), Paint::Solid(Rgba::BLACK), FillRule::NonZero); + line.fill = None; + line.stroke = Some(anicraft_doc::Stroke::new(Rgba::hex(0x116633), 6.0)); + let mut blob = Path::new(); + blob.move_to(Vec2::new(100.0, 100.0)); + blob.quad_to(Vec2::new(640.0, -500.0), Vec2::new(1180.0, 100.0)); + blob.quad_to(Vec2::new(1900.0, 360.0), Vec2::new(1180.0, 620.0)); + blob.quad_to(Vec2::new(640.0, 1300.0), Vec2::new(100.0, 620.0)); + blob.quad_to(Vec2::new(-600.0, 360.0), Vec2::new(100.0, 100.0)); + blob.close(); + let items = vec![item(blob, Paint::Solid(Rgba::hex(0xffe9a8)), FillRule::NonZero), item(ribbons(24), Paint::Solid(Rgba::hex(0x202020)), FillRule::NonZero), over, line]; + DisplayList { items, ..Default::default() } +} + +/// A `size` px tile whose corner is at device pixel `(ox, oy)` of the stage at scale `z`. +fn tile(z: f32, ox: f32, oy: f32, size: u32) -> View { + View { transform: Affine::translate(-ox, -oy).mul(&Affine::scale(z, z)), width: size, height: size, background: Some(Rgba::hex(0xffffff)) } +} + +/// Tiles over the stage at `z`: the middle, each edge and corner (so shapes leave the surface +/// on every side), and one out on the pasteboard. +fn tiles(z: f32) -> Vec { + let (w, h) = (1280.0 * z, 720.0 * z); + let mut out = Vec::new(); + for fx in [0.0, 0.31, 0.5, 0.93] { + for fy in [0.0, 0.47, 0.9] { + out.push(tile(z, (w * fx).floor(), (h * fy).floor(), 96)); + } + } + out.push(tile(z, -40.0, -30.0, 96)); + out.push(tile(z, w - 50.0, h - 60.0, 96)); + out +} + +#[test] +fn what_is_left_out_changes_no_pixel() { + let demo = evaluate(&sample::demo(), 12); + for (name, dl) in [("the drawing", drawing()), ("the sample", demo)] { + let mut fewer = false; + for z in [0.4f32, 1.0, 3.7, 16.0, 64.0] { + for v in tiles(z) { + let (whole, all) = render_cut(&dl, &v, false).unwrap(); + let (cut, kept) = render_cut(&dl, &v, true).unwrap(); + assert!(whole.data == cut.data, "{name} at {z}×, {:?}: the pictures differ", v.transform.m); + assert_eq!((kept.drawn, kept.culled, kept.pixels_touched), (all.drawn, all.culled, all.pixels_touched), "{name} at {z}×: the same fills over the same pixels"); + assert!(kept.edges <= all.edges); + fewer |= kept.edges < all.edges; + } + } + assert!(fewer, "{name}: something was left out somewhere"); + } +} + +/// Masks are prepared the same way: a clipped drawing under a mask of curves, cut and whole. +#[test] +fn masks_are_cut_without_changing_a_pixel() { + let mut dl = drawing(); + let mut mask = item(Path::ellipse(640.0, 360.0, 560.0, 330.0), Paint::Solid(Rgba::BLACK), FillRule::NonZero); + mask.masks = Some(0); + for it in &mut dl.items { + it.clip = Some(0); + } + dl.items.insert(0, mask); + dl.clip_parents = vec![None]; + for z in [1.0f32, 16.0, 64.0] { + for v in tiles(z) { + let (whole, _) = render_cut(&dl, &v, false).unwrap(); + let (cut, _) = render_cut(&dl, &v, true).unwrap(); + assert!(whole.data == cut.data, "at {z}×, {:?}", v.transform.m); + } + } +} + +/// #477: zoomed far into a big merged drawing, a tile used to walk every edge of the whole +/// drawing, cut finer the deeper the zoom. Now it walks fewer than the whole drawing has at +/// 100 %, however deep. +#[test] +fn a_tile_deep_inside_a_drawing_walks_fewer_edges_than_the_drawing_has() { + let ink = item(ribbons(24), Paint::Solid(Rgba::BLACK), FillRule::NonZero); + let dl = DisplayList { items: vec![ink], ..Default::default() }; + let whole_stage = View { transform: Affine::IDENTITY, width: 1280, height: 720, background: None }; + let normal = render(&dl, &whole_stage).unwrap().1.edges; + let mut before = 0; + for z in [8.0f32, 64.0] { + let v = tile(z, (640.0 * z).floor(), (360.0 * z).floor(), 512); + let deep = render(&dl, &v).unwrap().1.edges; + let uncut = render_cut(&dl, &v, false).unwrap().1.edges; + assert!(deep > 0 && deep < normal, "{z}×: {deep} edges for one tile, {normal} for the stage at 100 %"); + assert!(uncut > normal && uncut > before, "{z}×: whole, the tile's edges grow with the zoom ({uncut})"); + before = uncut; + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6e7b0d34..a33a1940 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -143,6 +143,12 @@ pub fn render_frame(doc: &Document, frame: u32, scale: f32) -> Result Result<(Pixmap, RenderStats), RenderError> { + render_cut(dl, view, true) +} + +/// [`render`]; `cut` off prepares every item whole (see [`unseen`]), which draws the same +/// pixels more slowly: the tests compare the two. +fn render_cut(dl: &DisplayList, view: &View, cut: bool) -> Result<(Pixmap, RenderStats), RenderError> { let mut pm = Pixmap::new(view.width, view.height)?; // The background is filled band by band, in parallel, just before each band draws (a // serial fill of a 1080p float buffer cost as much as all the drawing). @@ -155,7 +161,7 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re // Phase 1 (parallel over items): cull, flatten, stroke and build shaders. Output keeps // display-list order. - let mut prepared: Vec> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface, soft_art(dl, item)) }).collect(); + let mut prepared: Vec> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface, soft_art(dl, item), cut) }).collect(); for r in &runs { if let (Some(op), Some(slot)) = (filtered_group(dl, r, view, surface)?, prepared.get_mut(r.start)) { slot.push(op); @@ -367,7 +373,7 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat let surface = IRect { x0: 0, y0: 0, x1: view.width as i32, y1: view.height as i32 }; let runs = filtered_runs(dl); let in_run = in_runs(dl, &runs); - let mut prepared: Vec> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface, soft_art(dl, item)) }).collect(); + let mut prepared: Vec> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface, soft_art(dl, item), true) }).collect(); let mut layers = Vec::new(); for r in &runs { if let (Some(setup), Some(slot)) = (filter_setup(dl, r, view, surface), prepared.get_mut(r.start)) { @@ -796,10 +802,86 @@ fn soft_art(dl: &DisplayList, item: &DisplayItem) -> bool { item.masks.is_some_and(|c| dl.clip_mode(c).is_soft()) } +/// Whether every point of `pts` is in one of the three places where an edge between two of them +/// adds nothing to any pixel of `surface`: above it, below it, or to its right (ADR 0132). +/// +/// The rasterizer skips an edge above or below the rows it fills, and what an edge at or past +/// the right end of a row deposits falls in cells no pixel reads. An edge to the *left* does +/// count (it carries the winding into the row), so the left is not one of the places. Above is +/// exact at the surface's first row; below and right start `far` pixels out, for a caller that +/// asks about points it has not computed (a curve's hull: its points are sums of the hull's, +/// rounded). +fn unseen(pts: &[Vec2], surface: IRect, far: f32) -> bool { + let (top, bottom, right) = (surface.y0 as f32, surface.y1 as f32 + far, surface.x1 as f32 + far); + pts.iter().all(|p| p.y <= top) || pts.iter().all(|p| p.y >= bottom) || pts.iter().all(|p| p.x >= right) +} + +/// How far past the surface's bottom and right a curve's hull must be for the curve to be left +/// as its chord: more than the rounding of its points' sums could be (a few parts in ten +/// million of the coordinates, which is under a pixel at any surface size the renderer takes). +fn far(surface: IRect) -> f32 { + 1.0 + surface.x1.max(surface.y1) as f32 * 1e-4 +} + +/// Whether the end points of `path`'s segments under `m` reach all four sides of `surface` or +/// beyond: then its pixel bounds are the whole surface whatever its curves do in between, and +/// the curves off the surface may be left as chords without moving them. +fn spans(path: &anicraft_geom::Path, m: &Affine, surface: IRect) -> bool { + use anicraft_geom::PathCmd; + let mut r = Rect::EMPTY; + let (mut start, mut last) = (Vec2::ZERO, Vec2::ZERO); + for c in &path.cmds { + match *c { + PathCmd::MoveTo(p) => { + start = m.apply(p); + last = start; + } + PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => { + let p = m.apply(p); + // Both ends of a drawn segment are among the flattened points. + if last.is_finite() && p.is_finite() { + r.include(last); + r.include(p); + } + last = p; + } + PathCmd::Close => last = start, + } + } + r.min.x <= surface.x0 as f32 && r.min.y <= surface.y0 as f32 && r.max.x >= surface.x1 as f32 && r.max.y >= surface.y1 as f32 +} + +/// Takes out of each closed polygon the points between two neighbours when all three are +/// above, below or to the right of `surface` ([`unseen`]): the two edges at such a point add +/// nothing to any pixel, and neither does the one edge that replaces them, so the pixels are +/// the same to the last bit with fewer edges to walk. One place at a time: a chord between two +/// points above the surface is above it, but not one from above it to its right. +fn drop_unseen(polys: &mut [Vec], surface: IRect) { + let (top, bottom, right) = (surface.y0 as f32, surface.y1 as f32, surface.x1 as f32); + let places: [&dyn Fn(&Vec2) -> bool; 3] = [&|p| p.y <= top, &|p| p.y >= bottom, &|p| p.x >= right]; + let mut inside: Vec = Vec::new(); + for poly in polys.iter_mut() { + for place in places { + inside.clear(); + inside.extend(poly.iter().map(place)); + if !inside.windows(3).any(|w| w.iter().all(|b| *b)) { + continue; + } + let mut i = 0usize; + poly.retain(|_| { + let at = i; + i += 1; + !(at > 0 && inside.get(at - 1..at + 2).is_some_and(|w| w.iter().all(|b| *b))) + }); + } + } +} + /// Turns a display item into fill operations (fill, then stroke), or none when culled. `soft`: /// the item is a soft mask's artwork, prepared with its paints like any artwork (still marked -/// as mask artwork). -fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool) -> Vec { +/// as mask artwork). `cut`: what can't reach a pixel is left out ([`unseen`]); off, the item is +/// prepared whole, for the tests that show the pixels are the same. +fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool, cut: bool) -> Vec { let mut out = Vec::new(); let m = view.mul(&item.transform); if !m.is_finite() { @@ -822,7 +904,19 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool) -> Vec if bounds.is_empty() || bounds.intersect(&surface_rect).is_empty() { return out; } - let lines = item.path.flatten(&m, TOLERANCE); + // Zoomed far into a large filled shape (a drawing merged from many brush strokes), nearly + // all of its curves are off the surface: those above, below or right of it become one line + // each instead of being cut into pieces nobody sees (ADR 0132). Only where that provably + // changes nothing: a fill alone (a stroke's dashes and width follow the length along the + // whole line), not a hairline, and a path that spans the surface (see `spans`). + let outlined = item.outline.is_some() && item.masks.is_none(); + let filled_only = !outlined && (is_mask || item.stroke.is_none()); + let lines = if cut && filled_only && spans(&item.path, &m, surface) { + let far = far(surface); + item.path.flatten_with(&m, TOLERANCE, |hull| hull.iter().all(|p| p.is_finite()) && unseen(hull, surface, far)) + } else { + item.path.flatten(&m, TOLERANCE) + }; if lines.is_empty() { return out; } @@ -851,11 +945,15 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool) -> Vec } return out; } - let mut push = |polys: Vec>, rule, shader: Shader| { + let mut push = |mut polys: Vec>, rule, shader: Shader| { if shader.is_solid().is_some_and(|c| c[3] <= 0.0) { return; } - if let Some(b) = pixel_bounds(&polys, surface) { + // The bounds first, from every point: they place the coverage buffer. + if let Some((b, beyond)) = pixel_bounds_of(&polys, surface) { + if cut && beyond { + drop_unseen(&mut polys, surface); + } out.push(Prepared { polys, rule, shader, bounds: b, clip, masks, group, layer: None, hairline: false }); } }; @@ -896,6 +994,12 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool) -> Vec } fn pixel_bounds(polys: &[Vec], surface: IRect) -> Option { + pixel_bounds_of(polys, surface).map(|(b, _)| b) +} + +/// The pixels of `surface` that `polys` can touch, and whether they reach above, below or +/// right of it (then some of their points may be [`unseen`]). +fn pixel_bounds_of(polys: &[Vec], surface: IRect) -> Option<(IRect, bool)> { let mut r = Rect::EMPTY; for p in polys.iter().flatten() { r.include(*p); @@ -909,7 +1013,8 @@ fn pixel_bounds(polys: &[Vec], surface: IRect) -> Option { x1: (r.max.x.ceil().min(surface.x1 as f32)) as i32, y1: (r.max.y.ceil().min(surface.y1 as f32)) as i32, }; - (!b.is_empty()).then_some(b) + let beyond = r.min.y <= surface.y0 as f32 || r.max.y >= surface.y1 as f32 || r.max.x >= surface.x1 as f32; + (!b.is_empty()).then_some((b, beyond)) } /// Composites coverage `cov` (over `b`) of `op` into the band whose first row is `band_y0`, @@ -954,6 +1059,8 @@ mod nine_slice_tests; #[cfg(test)] mod layer_opacity_tests; +#[cfg(test)] +mod cut_tests; #[cfg(test)] mod tests { diff --git a/crates/xfl/src/edges.rs b/crates/xfl/src/edges.rs index 95ac8383..12388b9d 100644 --- a/crates/xfl/src/edges.rs +++ b/crates/xfl/src/edges.rs @@ -6,6 +6,10 @@ //! are decimal, or `#` hex fixed point (signed 24.8). An edge names the fill style on its //! left (`fillStyle0`) and right (`fillStyle1`) and an optional stroke style. //! +//! An `edges` string holds one run of segments per `!`. A command the reader doesn't know ends +//! its own run only: the runs after it are read as usual and the damaged one is counted, so the +//! import can say that part of an outline is missing (ADR 0133). +//! //! Fill regions are rebuilt per fill style: its right-side edges as drawn, its left-side edges //! reversed, then chained end to start into closed loops. Strokes are the stroked edges in //! drawing order. Written from the public description of the format; no Animate code involved. @@ -36,15 +40,46 @@ pub struct Edge { pub segs: Vec, } -/// Decodes an `edges` attribute through craft-libs and maps its neutral geometry to AniCraft. +/// What an `edges` attribute decodes to. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Parsed { + pub segs: Vec, + /// Runs that stop before their end, at a command the reader doesn't know. + pub unread: usize, +} + +/// Decodes an `edges` attribute through craft-libs, run by run, and maps its neutral geometry to +/// AniCraft. The shared reader stops at the first command it doesn't know; a run starts at a +/// move and depends on nothing before it, so each is handed over on its own and only a damaged +/// run loses its end. +pub fn parse_runs(s: &str) -> Parsed { + let mut out = Parsed::default(); + let point = |p: craft_xfl::edges::Point| Vec2::new(p.x, p.y); + let mut rest = s; + while !rest.is_empty() { + // Up to the next move (`!` is ASCII, so the cut is on a character boundary). + let end = rest.bytes().skip(1).position(|b| b == b'!').map_or(rest.len(), |i| i + 1); + let (run, tail) = rest.split_at(end); + rest = tail; + let drawn = run.bytes().filter(|b| matches!(b, b'|' | b'/' | b'[' | b']')).count(); + let room = craft_xfl::edges::MAX_EDGE_SEGMENTS.saturating_sub(out.segs.len()); + if room == 0 { + // Full: what the runs still to come would draw is left out, and counted undecoded. + out.unread += usize::from(drawn > 0); + continue; + } + let read = craft_xfl::edges::parse_edge_segments(run); + if read.len() < drawn || read.len() > room { + out.unread += 1; + } + out.segs.extend(read.into_iter().take(room).map(|segment| Seg { from: point(segment.from), ctrl: segment.control.map(point), to: point(segment.to) })); + } + out +} + +/// The segments of an `edges` attribute (see [`parse_runs`]). pub fn parse(s: &str) -> Vec { - craft_xfl::edges::parse_edge_segments(s) - .into_iter() - .map(|segment| { - let point = |p: craft_xfl::edges::Point| Vec2::new(p.x, p.y); - Seg { from: point(segment.from), ctrl: segment.control.map(point), to: point(segment.to) } - }) - .collect() + parse_runs(s).segs } /// Hash key for an end point (to 1/100 px, which absorbs the format's rounding). @@ -61,6 +96,12 @@ fn push_seg(path: &mut Path, s: &Seg) { /// The region of fill style `style`, as closed loops. pub fn fill_path(edges: &[Edge], style: u32) -> Path { + fill_region(edges, style).0 +} + +/// [`fill_path`], and how many of its loops don't come back to their start: part of the outline +/// is missing there, and the loop is closed straight across the gap. +pub fn fill_region(edges: &[Edge], style: u32) -> (Path, usize) { let mut segs: Vec = Vec::new(); for e in edges { if e.fill_right == style { @@ -79,6 +120,7 @@ pub fn fill_path(edges: &[Edge], style: u32) -> Path { } let mut used = vec![false; segs.len()]; let mut path = Path::new(); + let mut gaps = 0; for first in 0..segs.len() { if used.get(first).copied().unwrap_or(true) || segs.get(first).is_some_and(|s| key(s.from) == key(s.to)) { continue; @@ -86,12 +128,14 @@ pub fn fill_path(edges: &[Edge], style: u32) -> Path { let Some(&start) = segs.get(first) else { continue }; path.move_to(start.from); let mut at = first; + let mut closed = false; while let Some(s) = segs.get(at).copied() { if let Some(u) = used.get_mut(at) { *u = true; } push_seg(&mut path, &s); if key(s.to) == key(start.from) { + closed = true; break; } let next = by_start.get(&key(s.to)).and_then(|v| v.iter().copied().find(|&j| !used.get(j).copied().unwrap_or(true))); @@ -100,9 +144,12 @@ pub fn fill_path(edges: &[Edge], style: u32) -> Path { None => break, } } + if !closed { + gaps += 1; + } path.close(); } - path + (path, gaps) } /// The stroked edges of stroke style `style`, in drawing order. @@ -139,6 +186,20 @@ mod tests { assert!(parse("!1 2|x").is_empty(), "stops at garbage, never panics"); } + /// A command the reader doesn't know costs its own run its end, and no other run anything. + #[test] + fn a_damaged_run_loses_only_its_own_end() { + let whole = parse_runs("!0 0|200 0!400 0|600 0[800 0 800 200"); + assert_eq!((whole.segs.len(), whole.unread), (3, 0)); + let cut = parse_runs("!0 0|200 0?7|300 0!400 0|600 0[800 0 800 200"); + assert_eq!(cut.unread, 1); + assert_eq!(cut.segs, whole.segs, "the first run up to the cut, and the run after it whole"); + // Before the first move too, and a run that is nothing but the unknown command. + let lead = parse_runs("|200 0?!400 0|600 0!?"); + assert_eq!((lead.segs.len(), lead.unread), (2, 0), "no drawing command was lost"); + assert_eq!(parse_runs("!0 0|x!0 0|200 0").unread, 1); + } + #[test] fn a_square_split_into_edges_with_fills_on_either_side() { // Top and right drawn clockwise with the fill on the right; bottom and left drawn the diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index fc91f571..f84f3799 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -105,7 +105,14 @@ const SHOWN_NAMES: usize = 3; impl Report { pub(crate) fn skip(&mut self, what: &str) { - *self.skipped.entry(what.to_string()).or_default() += 1; + self.skip_many(what, 1); + } + /// Counts `n` of `what` (none when `n` is 0). + pub(crate) fn skip_many(&mut self, what: &str, n: usize) { + if n > 0 { + let count = self.skipped.entry(what.to_string()).or_default(); + *count = count.saturating_add(n); + } } /// Counts `what` and keeps the item's `name` for the report. pub(crate) fn skip_named(&mut self, what: &str, name: String) { @@ -408,19 +415,23 @@ fn paint(def: &X, bitmaps: &HashMap, report: &mut Report) -> O // which AniCraft draws as the image shown once). Some(Paint::Bitmap { bitmap, repeat: !fill.bitmap_is_clipped().unwrap_or(false), matrix }) } - craft_xfl::shape::FillKind::Other => None, + // A paint AniCraft has no reading of: nothing says what colour it is, so the region is + // left empty and said (ADR 0133). + craft_xfl::shape::FillKind::Other => { + report.skip("fills of a kind AniCraft doesn't know (left out)"); + None + } } } /// A stroke definition (`SolidStroke` and friends) as a stroke: weight, its fill colour, caps, /// joints and miter limit, and the dashes of `DashedStroke` and dots of `DottedStroke` -/// (ADR 0046). Ragged, stipple and hatched strokes are drawn solid. +/// (ADR 0046). Ragged, stipple and hatched strokes are drawn solid, and so is a stroke of a kind +/// AniCraft doesn't know, with whatever weight, colour, caps and joints it gives (ADR 0133): a +/// line drawn plainer than it was is nearer the artwork than no line. pub(crate) fn stroke(def: &X, bitmaps: &HashMap, report: &mut Report) -> Option { let native = craft_xfl::shape::Stroke::new(def); use craft_xfl::shape::StrokeKind as NativeStroke; - if native.kind() == NativeStroke::Other { - return None; - } // Round caps and joints are the format's default, and a miter limit of 3. let cap = match native.caps().map(str::trim) { Some("none") => Cap::Butt, @@ -439,6 +450,10 @@ pub(crate) fn stroke(def: &X, bitmaps: &HashMap, report: &mut NativeStroke::Dashed => Dash::dashed(native.dash1().unwrap_or(6.0), native.dash2().unwrap_or(6.0)), NativeStroke::Dotted => Dash::dotted(native.dot_space().unwrap_or(3.0)), NativeStroke::Solid => None, + NativeStroke::Other => { + report.skip("strokes of a kind AniCraft doesn't know (drawn solid)"); + None + } _ => { report.skip("ragged, stipple and hatched strokes (drawn solid)"); None @@ -480,15 +495,27 @@ impl<'a> Builder<'a> { let stroke = style.definition().and_then(|definition| stroke(definition.element(), &self.bitmaps, &mut self.report)); (style.index().unwrap_or(0), stroke) }).collect(); - let edges: Vec = schema.edges().map(|edge| Edge { - fill_left: edge.fill_style0().unwrap_or(0), - fill_right: edge.fill_style1().unwrap_or(0), - stroke: edge.stroke_style().unwrap_or(0), - segs: edge.encoded_segments().map(edges::parse).unwrap_or_default(), + // Whatever of the outline doesn't come across is counted, never dropped quietly (ADR + // 0133): a run the reader can't follow to its end, and a style an edge names that the + // shape doesn't have. + let mut unread = 0usize; + let edges: Vec = schema.edges().map(|edge| { + let parsed = edge.encoded_segments().map(edges::parse_runs).unwrap_or_default(); + unread = unread.saturating_add(parsed.unread); + Edge { fill_left: edge.fill_style0().unwrap_or(0), fill_right: edge.fill_style1().unwrap_or(0), stroke: edge.stroke_style().unwrap_or(0), segs: parsed.segs } }).collect(); + self.report.skip_many("outline parts AniCraft couldn't read (left out)", unread); + let drawn = |e: &&Edge| !e.segs.is_empty(); + let stray_strokes: BTreeSet = edges.iter().filter(drawn).map(|e| e.stroke).filter(|i| *i > 0 && !strokes.iter().any(|(index, _)| index == i)).collect(); + self.report.skip_many("strokes in a style their shape doesn't have (left out)", stray_strokes.len()); + let stray_fills: BTreeSet = edges.iter().filter(drawn).flat_map(|e| [e.fill_left, e.fill_right]).filter(|i| *i > 0 && !fills.iter().any(|(index, _)| index == i)).collect(); + self.report.skip_many("fills in a style their shape doesn't have (left out)", stray_fills.len()); for (index, p) in fills { let (Some(p), true) = (p, index > 0) else { continue }; - let path = edges::fill_path(&edges, index); + let (path, gaps) = edges::fill_region(&edges, index); + // A fill's outline always closes in Animate's files; one that doesn't here has lost + // a part. It is closed straight across, which can cover more than the fill did. + self.report.skip_many("fills with a gap in their outline (closed straight across)", gaps); if !path.is_empty() { out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd, merge, warp: None }), m, ColorEffect::default())); } diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index 5843fdb9..25b9ca91 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -82,6 +82,18 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[ ("text", &[("text fields (no fonts on this computer)", 4)]), ("textfields", &[("text fields (no fonts on this computer)", 4)]), ("tweens", &[("motion tweens (kept as keyframes)", 1), ("tween spins (turned the shortest way)", 1)]), + // ADR 0133: nothing of an outline is dropped without a line here. + ( + "unknowns", + &[ + ("fills in a style their shape doesn't have (left out)", 1), + ("fills of a kind AniCraft doesn't know (left out)", 1), + ("fills with a gap in their outline (closed straight across)", 1), + ("outline parts AniCraft couldn't read (left out)", 1), + ("strokes in a style their shape doesn't have (left out)", 1), + ("strokes of a kind AniCraft doesn't know (drawn solid)", 1), + ], + ), ("video", &[("instances of videos AniCraft can't play", 1), ("videos (first frame kept as a still)", 1), ("videos AniCraft can't play", 2)]), ]; diff --git a/crates/xfl/tests/corpus/unknowns/DOMDocument.xml b/crates/xfl/tests/corpus/unknowns/DOMDocument.xml new file mode 100644 index 00000000..16d6e171 --- /dev/null +++ b/crates/xfl/tests/corpus/unknowns/DOMDocument.xml @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/unknowns/golden/frame-000.png b/crates/xfl/tests/corpus/unknowns/golden/frame-000.png new file mode 100644 index 00000000..e3e7720f Binary files /dev/null and b/crates/xfl/tests/corpus/unknowns/golden/frame-000.png differ diff --git a/crates/xfl/tests/corpus/unknowns/unknowns.xfl b/crates/xfl/tests/corpus/unknowns/unknowns.xfl new file mode 100644 index 00000000..860a820e --- /dev/null +++ b/crates/xfl/tests/corpus/unknowns/unknowns.xfl @@ -0,0 +1 @@ +PROXY-CS5 \ No newline at end of file diff --git a/docs/adr/0132-memory-and-frame-time-stay-flat.md b/docs/adr/0132-memory-and-frame-time-stay-flat.md new file mode 100644 index 00000000..764a3405 --- /dev/null +++ b/docs/adr/0132-memory-and-frame-time-stay-flat.md @@ -0,0 +1,146 @@ +# ADR 0132: Memory and frame time stay flat: picture sets, a zoom at rest, and edges nobody sees + +* Status: accepted (2026-11-23) +* Relates to: backlog item P-004 (`docs/roadmap.md`), issues + [#314](https://github.com/storytold/anicraft/issues/314) and + [#477](https://github.com/storytold/anicraft/issues/477), ADR 0002 (the render thread), + ADR 0006 (latency or throughput), ADR 0007 (stage tiles), ADR 0029 (pictures kept on the + GPU), ADR 0036 (the web build), ADR 0112 (several documents), `docs/performance.md` + +## Context + +Two reports: "a single symbol that moves across the screen with 24 frames takes up 900 MB" +in the web version (#314), and "the app stutters and lags when I try to zoom in very closely" +after drawing with the Brush (#477). An earlier fix cut the web build's picture cache from +768 MB to 256 MB, which lowered the ceiling without changing why it was reached. + +We measured before changing anything (`docs/performance.md` has the tables): + +* **On many threads, drawing a stage view costs about the same at every zoom.** A 1600 × 900 + view takes 6 to 9 ms on the CPU oracle from 100 % to 6400 % on a 32-thread machine, also for + a drawing of 64 merged brush strokes: there the cost is the pixels. +* **But the work per tile grew with the zoom and with the whole drawing.** A tile prepared + every edge of every item that touched it: 42,700 edges for the view at 100 %, 281,300 at + 6400 %, all but a few off the tile. On one thread, as the browser draws, the view took + 9.0 ms at 100 % and 33.5 ms at 6400 %. +* **The cache filled with pictures nobody could ask for again.** A drag makes a new document + state on every pointer move; each state's tiles were kept until the least recently used + fell out of a 768 MB budget (384 MB more on the GPU, 192 tile textures in the shell). A + zoom gesture did the same with zoom levels: 136 MB after 84 frames of Ctrl+wheel. That is + #314: the memory followed how long you had been editing, not what was on screen. +* **Every frame of a zoom gesture asked for a whole view** at a zoom level the next frame no + longer wanted. With a render thread the answers arrived too late to be shown; in the + browser, which has no thread (ADR 0036), they were drawn inside the frame. +* **A visible tile waited for look-ahead.** The render thread took up to 32 jobs a pass, the + urgent ones topped up with look-ahead, and put the pictures in the cache when the whole + pass was done. + +## Decision + +### 1. Picture sets: the cache keeps what is on screen + +Every picture belongs to a **picture set**: one document state at one scale +(`render_service::set_key`, in every `FrameJob` and `FrameImage`). The stage tells the render +service which set it shows (`RenderService::show`, each frame, cheap when nothing changed). +The cache keeps that set and the one shown before it (`KEEP_SETS = 2`) and drops the pictures +of every other set at once. A picture that finishes for a set that has gone is not kept, and +the render thread doesn't start one. + +Two, not one, so that undo then redo, or 100 % and back, finds its pictures. Not more: a +third state back is one redraw away (a few milliseconds), and each kept set is a view's worth +of memory. The frames of a movie played at one zoom are one set, so playback caching is as it +was, under the same byte budgets. A cache nobody has told what is shown (tests, tools) keeps +everything, as before. + +The shell does the same with its tile textures: when the view is whole, the textures of +other sets, which were only standing in for it, go. + +**Considered:** lowering the budgets (it moves the ceiling, as the earlier fix did); +keying tiles by their content so a drag only redraws the tiles the dragged thing touches (the +right next step for the browser, where a drag still redraws the view on the interface thread; +a much larger change, listed under P-004 as not yet). + +### 2. A zoom that is changing draws nothing + +While this frame's device scale differs from the last frame's, the stage asks for no tiles +and no look-ahead and paints the pictures it has, scaled (ADR 0007 already draws stale tiles +under missing ones). The first frame at rest asks once. No timer: egui smooths a wheel notch +over several frames, and each of those has a different zoom. + +### 3. What the screen needs is drawn first and alone + +The render thread takes urgent jobs in passes of their own. Look-ahead goes in passes of one +job per thread (`lookahead_batch`), so an urgent request arriving meanwhile waits about one +tile's time, not 32 tiles'. + +### 4. Without a render thread, moving around the stage has a time budget + +`RenderService::request_batch_within(jobs, budget)` draws, with no render thread, until the +budget is spent (at least one picture) and leaves the rest for the next call. The stage uses +it (8 ms) when the document state and frame are the ones on screen, that is for a pan or a +zoom come to rest: the tiles then agree with each other whatever order they arrive in. An +edit or another frame of the movie is still drawn whole in one call, because half of one +state beside half of another is worse than a late frame. + +### 5. Edges that add nothing are left out, and the pictures are the same to the last bit + +The oracle's rasterizer accumulates signed area per row. Reading its code: + +* an edge wholly above or below the rows being filled is skipped; +* an edge wholly at or right of the row's end deposits into cells past the last pixel, which + no pixel reads; +* an edge to the **left** does count: it carries the winding into the row. + +So `render::prepare` now + +* drops from each fill polygon every point whose two neighbours and itself are all above, all + below, or all right of the surface (`drop_unseen`; one place at a time, since a chord from + "above" to "right" can cross the surface). The two edges at such a point add nothing and + neither does the one that replaces them, and the edges that do add are walked in the same + order; +* flattens a curve whose control points are all in one of those places to its chord + (`Path::flatten_with`), with a margin below and right for the rounding of the curve's + points. Only for a fill alone (a stroke's dashes and width follow the length along the + whole line, and a hairline is not a filled polygon), and only when the path's segment ends + already reach all four sides of the surface, so that the fill's pixel bounds, which place + the coverage buffer, are the whole surface either way. + +The left side is deliberately not cut: a chord there has the same area mathematically, but +the sum of many small heights and one large one can differ in the last bit of a float, and +the oracle's output must not change (`docs/performance.md`). `cut_tests` draws a set of +scenes cut and whole at five zooms and fourteen tile positions each and compares the float +pixmaps for equality. The GPU stage starts from the same prepared fills (ADR 0019), so it +bins fewer edges too; its parity tests are unchanged. + +What is left is linear in the path per tile (transforming each segment and testing its hull): +preparing a view at 6400 % of a 64-stroke drawing went from 3.3 ms to 1.3 ms, and drawing it +on one thread from 33.5 ms to 13.0 ms. A spatial index over a path's segments would make it +follow the visible part alone; not yet. + +## Consequences + +* Editing, zooming or playing for a long time holds what a short session holds: a drag of 300 + moves ends with two views of pictures instead of the whole budget; the web build's memory + stops growing after the first moves of a drag (measured in Node, `tests/wasm.rs`). +* A tile deep inside a large drawing walks fewer edges than the whole drawing has at 100 %. +* Undo further back than one step redraws the view (it was a cache hit while the budget + lasted). +* A zoom gesture shows the old pictures scaled until it rests; it used to show the same on + the desktop (the answers came too late) and to stutter in the browser. +* `FrameJob` and `FrameImage` have a `set` field; `RenderService` gains `show`, `has_thread`, + `without_thread` and `request_batch_within`. + +## Tests (relations, not timings) + +* `render::cut_tests`: cut and whole pictures are equal bit for bit, masks too; a tile deep in + a drawing walks fewer edges than the stage at 100 %, where whole it walked more with every + zoom. +* `engine::render_budget_tests`: a drag of 120 states holds what it held after 10, and so + does a zoom of 80 levels; four laps of a movie hold what one lap held, with a budget above + and below the movie's size; urgent pictures come within one look-ahead pass; without a + thread a view fills in one picture a call and matches the oracle; the deepest zoom walks + fewer edges than 100 % through the stage's own tiles. +* `stage_budget_tests` (the shell, frame by frame): a zoom gesture asks for nothing until it + rests and then holds one view of textures; 40 edits hold what 5 held. +* `tests/wasm.rs` (in Node): the WebAssembly memory after 132 moves of a drag is what it was + after 12. diff --git a/docs/adr/0133-an-animate-shape-is-never-cut-down-quietly.md b/docs/adr/0133-an-animate-shape-is-never-cut-down-quietly.md new file mode 100644 index 00000000..fd2eb139 --- /dev/null +++ b/docs/adr/0133-an-animate-shape-is-never-cut-down-quietly.md @@ -0,0 +1,93 @@ +# ADR 0133: An Animate shape is never cut down quietly + +* Status: accepted (2026-11-23) +* Relates to: ADR 0009 (XFL import), ADR 0035 (the XFL corpus and golden renders), ADR 0042 + (raw shapes merge when a file opens), ADR 0046 (stroke styles), ADR 0062 (documents macOS + hands over), issues #498 and #347, backlog item P-006, storytold/craft-libs#3282 + +## Context + +Issue #498: an Animate document opened from its XFL folder "with all of the layers", but "many +lines are entirely missing or filled in". The report came with a screen recording of AniCraft +and no file. In the recording whole outlines are absent (a head without its contour, an arm +whose fill is there and whose line is not) while short strokes and fills beside them are +drawn, and the status bar is not shown. + +We may not ask for, or read, files made with Animate that their owner has not released (clean +room), so the cause was looked for with files written by hand: + +| Suspect | How it was checked | Result | +|---|---|---| +| The merge of raw shapes when a file opens (ADR 0042) | Generated sketches of up to 400 wobbly strokes, 400 brush-like fills and 18 filled, outlined blobs split over several edges, in decimal and hexadecimal coordinates; rendered as imported and as opened | The same picture: at most 90 of 32 000 inked pixels differ, on antialiased joints. Past 20 000 segments the merge declines and the shapes stay as imported | +| The GPU stage on a heavy frame | An 850-edge sketch opened in the app, drawn by the GPU stage and by the CPU oracle | The same stage | +| The importer | Read for every place that drops part of a shape without a word | Five found, listed below | + +The importer dropped, silently: + +1. **A stroke of a kind it doesn't know.** `stroke()` returned nothing for a stroke element + other than the six it names, so every line in that style vanished and the report said + "Imported everything in the file". A newer Animate version's stroke kinds would do exactly + what the recording shows. +2. **The rest of an edge after one unreadable command.** The shared edge reader + (`craft_xfl::edges`) ends at the first command it doesn't know. One `edges` attribute holds + many runs, each starting at its own move, so a single unknown command lost every later run + of that edge: lines missing, and fills whose outline no longer closed. +3. **A fill whose outline doesn't close** was closed with a straight line across the gap, + which can cover an area the fill never had ("filled in"), and nothing said so. +4. **A fill of a kind it doesn't know**, and +5. **edges that name a style their shape doesn't have.** + +Which of these, if any, the reporter's file runs into is not known. + +## Decision + +1. **Nothing of an outline is dropped without a line in the report.** Each of the five has its + own count, in the words an artist can act on, and `file.open` returns them in `skipped` as + every other count (so the CLI and MCP see them too). +2. **Drawn the nearest way where there is one.** + * A stroke of an unknown kind is drawn **solid**, with the weight, colour, caps and joints + its element gives ("strokes of a kind AniCraft doesn't know (drawn solid)"), as ragged, + stipple and hatched strokes already are. A plainer line is nearer the drawing than no + line. + * A fill of an unknown kind is **left out**: nothing says what colour it is, and a guess + would paint over artwork. + * A fill with a gap is still **closed straight across** (most gaps are short, and an empty + shape is further from the drawing), now counted as "fills with a gap in their outline + (closed straight across)". +3. **An unreadable command costs its own run only.** The importer hands the shared reader one + run at a time (`edges::parse_runs`: the attribute cut at each `!`), so the runs after a + damaged one are read as usual. A run that yields fewer segments than it has drawing + commands is counted as "outline parts AniCraft couldn't read (left out)". This is the + app's side of it; the same recovery belongs in the shared reader + (storytold/craft-libs#3282), and `parse_runs` goes back to one call when it is there. +4. **A corpus package for it** (`crates/xfl/tests/corpus/unknowns/`, ADR 0035): a stroke and a + fill of kinds that don't exist (their element names are made up for the file), a run cut + short with a whole run after it, edges in styles their shape lacks and a fill missing a + side, with the exact report, a golden frame and probes for what must and must not be drawn. + It goes through the hostile sweep and the `.fla` layouts like every package. + +### Issue #347, a `.fla` refused on macOS + +The message in the report ("AniCraft cannot open files in the “Animation Document” format") is +the system's own, shown when an app declares a document type and does not take the open +request. v0.2.1, the latest release when it was reported, did not: the handler of ADR 0062 is +not in the commit that release was built from, and no release has carried it since. On +`main` a `.fla` handed over by Finder, the Dock or **Open With** goes through `file.open` +like a drop on the window, and the tests drive that path with the corpus packed as `.fla`. +Nothing more is changed here; it needs a Mac and a build from `main` to confirm. + +## Consequences + +* A file that used to open with lines missing and a clean report now either shows them (kinds + AniCraft doesn't know, runs after a damaged one) or says what it left out. +* Reports get longer on files with unknown content. That is the point: the next report of + missing lines comes with the line that names the cause. +* An unknown stroke kind drawn solid may be heavier or plainer than the original (a tapered or + textured line becomes an even one). + +## Not decided here + +* What the unknown kinds are. A file that shows the problem, released by its owner under a + licence the corpus can take, or its import report from this version, would settle it. +* Edges that hold only cubic curves, hairlines and a minimum line width on screen, strokes with + a width profile: no public description or corpus evidence for them yet. diff --git a/docs/architecture.md b/docs/architecture.md index cb401883..8a30e8c7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -240,7 +240,9 @@ engine itself never depends on the GPU. state makes the document clean. See [ADR 0001](adr/0001-undo-persistent-snapshots.md). * `RenderService` renders frames on a worker thread with an LRU frame cache keyed by `(state, frame, view)`, and prefetches during playback. See - [ADR 0002](adr/0002-render-pipeline.md). + [ADR 0002](adr/0002-render-pipeline.md). The cache keeps the pictures of the document state + and zoom on screen and of the one before, within its byte budgets, and draws what the + screen needs before look-ahead ([ADR 0132](adr/0132-memory-and-frame-time-stay-flat.md)). * `CommandSpec { id, label, menu, shortcut, params, run }`. `run(&mut Session, &Value) -> Result`. The registry (`commands()`) is the single list the shell, CLI and agents read. `Session::execute(id, params)` handles undo snapshots for mutating commands. @@ -293,7 +295,9 @@ another language. The stage is drawn in tiles by the engine's `RenderService`: on the graphics card by default (section 4, "GPU stage"), and by the CPU renderer when there is no usable card, in the web -build, and for anything the GPU can't draw. Tiles are cached per `(state, frame, view)`. +build, and for anything the GPU can't draw. Tiles are cached per `(state, frame, view)`; a +zoom that is still changing scales the tiles on screen and draws new ones when it rests +([ADR 0132](adr/0132-memory-and-frame-time-stay-flat.md)). Overlays (selection boxes, drag previews, the stage frame) are drawn with the egui painter in screen space. diff --git a/docs/guide/opening-animate-files.md b/docs/guide/opening-animate-files.md index 42ecadf4..5c2542bc 100644 --- a/docs/guide/opening-animate-files.md +++ b/docs/guide/opening-animate-files.md @@ -91,6 +91,10 @@ These come across, but look a little different from Animate, and the report coun * gradient and bitmap strokes (drawn in one colour); * ragged, stipple and hatched strokes (drawn solid); +* strokes of a kind AniCraft doesn't know (drawn solid, with their weight and colour): a newer + version's brush or line style comes across as a plain line, not as nothing; +* fills with a gap in their outline (closed straight across). If an area looks filled in that + wasn't, this line says which import to look at; * reverse loop modes (played forward) and extra spins on classic tweens (turned the shortest way); * in text: justified text (drawn left-aligned), first-line indents, superscript and subscript, @@ -115,6 +119,10 @@ These come across, but look a little different from Animate, and the report coun * **Video playback.** Videos other than Screen Video (Sorenson H.263, On2 VP6, H.264, linked MPEG-4 files) are named in the report, not shown; their instances are left out. * Frame comments, and linkage classes on bitmaps and sounds. +* **Parts of a drawing AniCraft can't read**: "outline parts AniCraft couldn't read" (the rest + of that outline is drawn), fills of a kind AniCraft doesn't know, and lines or fills in a + style their shape doesn't have. If lines are missing after opening a file, these counts say + why; please include the report when you tell us. * Camera layers and bone armatures don't come across as a camera or an armature. * **Layer parenting** doesn't come across: parented layers open as plain layers. Parent them again in the timeline's [parenting view](timeline.md#layer-parenting). diff --git a/docs/nightly-builds.md b/docs/nightly-builds.md new file mode 100644 index 00000000..87a19cc8 --- /dev/null +++ b/docs/nightly-builds.md @@ -0,0 +1,115 @@ +# AniCraft Nightly builds + +The Nightly flavor is the preview channel the ArtCraft Launcher installs beside stable AniCraft: +one app, two channels, no shared state. Everything here is switched off in CI (no schedule, no +release branch, no signing); this page describes what exists and how to exercise it. + +## The contract + +| Item | Value | +|---|---| +| Build switch | `ANICRAFT_BUILD_CHANNEL=nightly-v1` makes `build.rs` emit `cfg(anicraft_nightly_v1)`. Unset, empty or `stable` is stable; anything else is a build error. | +| Version | `ANICRAFT_VERSION=X.Y.Z-nightly.YYYYMMDD...g`, with `ANICRAFT_BUILD_SHA` (40 hex) and `ANICRAFT_BUILD_DATE` (`YYYY-MM-DD`) that must match it. A nightly build without them fails in `build.rs`. | +| Version query | `--version`, `-V`, and the Launcher's `--launch-profile nightly-v1 --profile-root --version` print exactly `AniCraft (nightly-v1)` on stdout, nothing on stderr, exit 0 — before logging, the profile check, IPC or any window. `AniCraft Nightly` is the display name (window title, Windows ProductName, desktop `Name=`), never part of this line. | +| Launch | `--launch-profile nightly-v1 --profile-root -- [files…]`, as separate tokens. A nightly build without a profile is refused in a native dialog ("Open AniCraft Nightly from ArtCraft Launcher"); a stable build refuses the profile. | +| Identities | Package, macOS bundle and Launcher: `ai.storyteller.anicraft.nightly`. Window/Wayland app id and Windows AUMID: `ai.storyteller.anicraft.nightly-v1`. Two different strings; `src/platform.rs` keeps both. | +| Assets | `anicraft--windows-x86_64-nightly.unsigned.zip` (the compiler's intermediate), `anicraft--linux-x86_64-nightly.tar.gz` (`anicraft` the launcher, `anicraft-bin` the GUI, the icon and the notices), `anicraft--macos-aarch64-nightly.zip` holding `AniCraft Nightly.app`. GUI only: no `anicraft-cli`, portable marker, `.desktop`, DMG, associations or URL types. | + +## Data + +Nightly writes **everything** into the profile root the Launcher names, and nowhere else: + +| State | Path inside the profile | Source | +|---|---|---| +| Preferences | `prefs.json` | `platform::config_dir` | +| Recovery and autosave | `Recovery/` | `platform::recovery_dir` | +| Start-up log | `Logs/` | `platform::log_dir` | +| Plug-ins | `plugins/` | `platform::plugins_dir` | +| Templates, saved commands, themes | `Templates/`, `Commands/`, `themes/` | `platform::templates_dir`, `commands_dir`, `themes_dir` | +| Start-screen thumbnails | `Thumbnails/` | `platform::save_thumbnail` | +| User guide (cache) | `Cache/guide-/` | `platform::guide_dir` | +| Nightly session health | `nightly-session.json`, `nightly-session.lock` | `src/nightly_session.rs` | + +`platform::placement()` is the one switch: a validated profile replaces the portable and installed +layouts wholesale, so every folder above follows it and stable's is never read. The profile is +validated before the first folder is created (`src/profile_root.rs`): it must not overlap stable's +`%APPDATA%\AniCraft`, `%LOCALAPPDATA%\AniCraft`, `Library/{Application Support,Caches,Preferences}/ +AniCraft`, `$XDG_{CONFIG,DATA,CACHE,STATE}_HOME/anicraft`, the Flatpak folder +`~/.var/app/ai.storyteller.anicraft`, `/usr/bin/anicraft`, `/usr/local/bin/anicraft`, +`/opt/anicraft`, or the installation (the `.app` on macOS); it must not be inside a portable copy +(`anicraft-portable`) or one of its `data` folders; every entry in the profile must resolve inside +it (no symlinked `Recovery`); and it is refused when `ANICRAFT_RECOVERY_DIR`, +`ANICRAFT_TEMPLATES_DIR`, `ANICRAFT_COMMANDS_DIR`, `ANICRAFT_THEMES_DIR`, `ANICRAFT_LOG_DIR` or +`ANICRAFT_PLUGINS` is inherited, or when a native build inherits another app's `FLATPAK_ID` +(the Nightly Flatpak itself is allowed, and its profile must stay in its own home). + +No single-instance socket exists in AniCraft (a second launch is a second window); the control +port's `control.json` is not written either, because Nightly never opens the control port. + +## Building + +```sh +# Windows (PowerShell; the unsigned intermediate the signer consumes) +$env:ANICRAFT_BUILD_CHANNEL='nightly-v1'; $env:ANICRAFT_VERSION='0.3.0-nightly.20261124.17.1.gabcdef012345' +$env:ANICRAFT_BUILD_SHA='abcdef0123456789abcdef0123456789abcdef01'; $env:ANICRAFT_BUILD_DATE='2026-11-24' +pwsh packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly + +# Linux +bash packaging/linux/nightly.sh --arch x86_64 + +# macOS (Apple silicon) +bash packaging/macos/nightly.sh --arch aarch64 +bash packaging/macos/nightly-verify.sh --expect unsigned --input dist/anicraft--macos-aarch64-nightly.zip +``` + +All three read the same four `ANICRAFT_*` values plus an absolute `CARGO_TARGET_DIR` and `DIST` +(`packaging/nightly-common.sh`), build only the GUI crate `anicraft` with its default features, +refuse a dirty tree, and never accept signing material. `packaging/nightly-tests.py` runs the +synthetic suites (archive policy, the launcher in all five layouts, plist rendering, the Apple +scripts against stand-in tools); a +three-platform hosted check runs the real scripts with the `full-ci` label +(`.github/workflows/nightly-builds.yml`). + +Signing is the trusted step's: `packaging/windows/sign.ps1 -Required`, +`packaging/macos/nightly-sign.sh`, and the Linux key `.github/nightly-linux-signing-key.asc` +(byte-identical to `release-signing-key.asc` in the stable release assets; fingerprint +`2B76741B414AAD6CD33E631213A005C0B9D7C3ED`). + +## Distribution wrappers + +Every Linux nightly format starts the program the flavor's way, through the one launcher +`packaging/linux/nightly-launch.sh`: + +```sh +exec --launch-profile nightly-v1 --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/anicraft-nightly/profile" -- "$@" +``` + +| Format | Installs the launcher as | Real program | +|---|---|---| +| `.deb` / `.rpm` | `/usr/bin/anicraft-nightly` | `/usr/lib/anicraft-nightly/anicraft` | +| AppImage | `$APPDIR/AppRun` (a script, not a symlink) | `$APPDIR/usr/bin/anicraft` | +| Arch handoff | `bin/anicraft` (shipped) | `bin/.anicraft-nightly/anicraft` | +| Flatpak | `/app/bin/anicraft-nightly` (the bundle's `command:`) | `/app/bin/anicraft-bin` | +| nightly `.tar.gz` | `anicraft` (the standard layout: the launcher keeps the app's name) | `anicraft-bin` beside it | + +The profile is a sibling of stable's data folder, never inside it and never containing it, and +`anicraft --version` from the tar (or `anicraft-nightly --version` from a package) answers the +Launcher's own query form. A command line that already carries `--launch-profile` goes straight to +the program instead of being wrapped twice, and only the deb/rpm layout looks in +`/usr/lib/anicraft-nightly`; a bundle never trusts a folder beside its mount. A package whose +launcher cannot put arguments in front of the person's own may name the root in +`ANICRAFT_PROFILE_ROOT` instead; nothing here uses it, only a nightly build reads it, it is +validated exactly like the Launcher's root, and it may not be combined with +`--launch-profile`/`--profile-root`. + +## Callers and policy + +The enabled callers `nightly.yml` (producer) and `nightly-sign.yml` (release-ref signer), the +installed policy `.github/nightly-signing-policy.json` and their contract tests +(`packaging/nightly-release-tests.py`) are dylanmtaylor's, kept exactly as he wrote them; this +change adds only the Linux public key they require. They are inert until the shared generalization +lands in `craft-common-actions`, so two properties hold instead of dormancy: neither caller has a +`schedule:` trigger (a run is an explicit manual dispatch), and the manual actors are the five +release managers (`bflatastic`, `dylanmtaylor`, `echelon`, `FredApps`, `skylartaylor`). +`nightly.yml` is registered only once it lands on `main`, which is when the policy's +`producer_workflow_id` can be filled in. diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 00000000..c99193be --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,93 @@ +# Windows, Linux and macOS release-ref nightly: supervised manual go-live + +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the +signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed +manual actors dispatches them. There is no schedule yet. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 +policy for `storytold/anicraft`. Once `nightly.yml` lands on `main`, populate `producer_workflow_id` +before promoting the policy to `release`, read with: + +```bash +gh api repos/storytold/anicraft/actions/workflows/nightly.yml --jq .id +``` + +The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation +permissions are for its isolated attester; its compiler narrows to contents and Actions read +only, with no OIDC, attestation write, release environment or platform signing secrets. +Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions +main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded +lineage compares and an issue reread at the end of candidate admission) on top of +[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input +and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed +source availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. + +**The shared-workflow port is a prerequisite.** At this pin both reusable workflows admit only +PhotoCraft: `nightly-unsigned.yml` requires `inputs.app-name == 'photocraft'` and +`github.repository == 'storytold/photocraft'` on its build jobs, and `nightly-release.yml` requires the +same repository in `validate` and every signing job (its concurrency group is +`craft-release-ref-signer-photocraft`). A AniCraft dispatch therefore builds and signs nothing until +`storytold/craft-common-actions` admits `storytold/anicraft`. No dispatch can produce a release before +that port, and both callers' `uses`, `tooling-revision` and the policy pins must move to the same +reviewed revision together. The port is craft-common-actions #363 ("run the shared nightly pipeline for +any reviewed registry app"); until it merges these callers are inert. + +**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on `main` (only a +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that +producer run ID and attempt, by a listed manual actor. + +**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the +producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers +team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes. + +**Admission timing.** The candidate check reads the newest CI run on the candidate commit and +main's latest finished Sonar analysis, so pick a quiet `main`, wait for its CI and SonarCloud +analysis to finish green, then dispatch the producer and, once it succeeds, the signer, before +another `main` push lands a newer analysis. + +**Platform rows.** The producer caller lists +`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer +run builds every listed platform for one all-or-nothing release (one failed or +skipped platform stops that night's release, Windows included), and the release-ref signer admits +platforms only from the protected policy, so there is no separate Linux or macOS caller job and +the signer caller has no platform input. + +## Installed policy values and their sources + +Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` once +`nightly.yml` is registered on `main`, plus any Sonar `debt` if needed) before the policy is promoted +to `release`. + +| Field | Value | Source | +|---|---|---| +| `repository_id` | `1419518094` | `gh api repos/storytold/anicraft --jq .id` | +| `producer_workflow_id` | `null` (pending `nightly.yml` on `main`) | `gh api repos/storytold/anicraft/actions/workflows/nightly.yml --jq .id` after `nightly.yml` reaches `main` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | +| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | +| `platforms` | three rows | Storytold stable signing identities (`Learning Machines Inc`, Linux OpenPGP fingerprint `2B76741B414AAD6CD33E631213A005C0B9D7C3ED`, Apple Team ID `DJ6XS33FX8`) | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `409994922`), 2 jobs | Workflow list API; jobs that succeeded on recent `main` push runs | +| `candidate_policy.sonar` | `storytold` / `storytold_anicraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on `main` commits | + +## Ownership and interface + +- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named + `AniCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets + may be passed or inherited. +- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch, + and identical on `main` and `release` after reviewed promotion. It rejects wrong repository/event/actual + branch, including same-name tags. Its constant whole-run concurrency is distinct from stable, + cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no + credentials; only the shared callee's sign jobs bind the `release` environment. +- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in + `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable + commit**; the defining workflow SHA and tooling input must match. +- `.github/nightly-linux-signing-key.asc` must be committed with the stable Linux public key + (`2B76741B414AAD6CD33E631213A005C0B9D7C3ED`) before Linux signing runs on `release`. + +## Local regression checks + +`python3 packaging/nightly-release-tests.py` verifies the nightly workflow contracts, exact context +guards, manual actor lists, signer serialization (`anicraft-nightly-release`, `queue: max`, +`cancel-in-progress: false`), no-cache/no-platform-secret boundaries, shared tooling pin consistency, +and `.github/nightly-signing-policy.json` schema and field invariants. diff --git a/docs/parity.md b/docs/parity.md index d9694bbc..94b4fb44 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -434,7 +434,7 @@ not this table, says what matters most. | Feature | Status | Notes | |---|---|---| -| `.fla` (zipped, CS5 and later) and XFL folders | **partial** | [ADR 0009](adr/0009-xfl-import.md), [ADR 0054](adr/0054-fla-packages-and-a-hardened-zip-reader.md); [opening Animate files](guide/opening-animate-files.md). Missing: motion tweens (P-023), armatures, camera, parenting, sound in and out points (P-043). Open reports: [#498](https://github.com/storytold/anicraft/issues/498), [#347](https://github.com/storytold/anicraft/issues/347) (P-006). | +| `.fla` (zipped, CS5 and later) and XFL folders | **partial** | [ADR 0009](adr/0009-xfl-import.md), [ADR 0054](adr/0054-fla-packages-and-a-hardened-zip-reader.md); [opening Animate files](guide/opening-animate-files.md). Missing: motion tweens (P-023), armatures, camera, parenting, sound in and out points (P-043). A stroke of a kind AniCraft doesn't know is drawn solid; a fill of an unknown kind, and the rest of an outline run after a command it can't read, are left out (the runs after it are drawn); each is counted in the report ([ADR 0133](adr/0133-an-animate-shape-is-never-cut-down-quietly.md)). Open reports, cause not confirmed: [#498](https://github.com/storytold/anicraft/issues/498), [#347](https://github.com/storytold/anicraft/issues/347) (P-006). | | Binary `.fla` (Flash 8 to CS4) | **partial** | [ADR 0120](adr/0120-legacy-fla-compound-binary-import.md); [opening Animate files](guide/opening-animate-files.md). Scenes, layers and folders, keyframes, shapes with gradients and dashed and dotted strokes, groups, symbol instances, classic and shape tweens, text, bitmaps, sounds on frames, frame scripts (kept, not run) and library folders ([#163](https://github.com/storytold/anicraft/issues/163); outside PRs [#478](https://github.com/storytold/anicraft/issues/478) and [#481](https://github.com/storytold/anicraft/issues/481)). Missing: filters, movie clip component settings, bitmap fills, sound in and out points; Flash MX 2004 and earlier (P-039; [#289](https://github.com/storytold/anicraft/issues/289)). | | Saving `.fla` or XFL | **missing** | AniCraft saves `.anicraft`. Not planned before import is complete (P-043). | | SWF artwork | **missing** | Needs a clean-room and licence decision first (P-048; [#172](https://github.com/storytold/anicraft/issues/172)). | diff --git a/docs/performance.md b/docs/performance.md index e7169d6c..b4f78b8e 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -47,6 +47,51 @@ The default `bench` scenario: 50 layers × 200 shapes × 240 frames, 200k elemen | GPU stage, 50k shapes at 4K, one texture | < 33.3 ms | 22.5–23.8 ms ✅ | `gpu_bench --check` | | GPU stage, onion ±5 outlines / tinted at 1080p, stage tiles | ≤ 1.25 | 1.03–1.06 ✅ | `gpu_bench --check` | +**Memory and frame time stay flat (2026-11-23, P-004, ADR 0132; #314, #477).** Measured +before changing anything, then after, on the same machine (release, 32 threads). + +*What the picture cache holds.* A drag makes a new document state on every pointer move, a +zoom gesture a new zoom level on every frame, and each one's tiles used to stay until the +768 MB budget (256 MB in the web build) was full. + +| Scenario | Before | After | +|---|---|---| +| Web build in Node (`tests/wasm.rs`): WebAssembly memory over a drag of 120 moves, a 1024 × 512 view | 27 MB to 255 MB (the cache at 240 MB) | 27 MB throughout (the cache at 4 MB) | +| Desktop, Ctrl+wheel from fit to 6400 % (84 frames): pictures cached | 147 pictures, 136 MB | 44 pictures, 44 MB (the view and the ring around it, at this zoom and the one before) | +| Desktop, a drag of 300 moves in a 1600 × 940 window: pictures cached, textures, process memory | not run; by the sizes below a move adds a view of about 12 MB, so the 768 MB budget is full after some 60 moves | 42 pictures (38 MB), 12 textures, the process at 102 MB | +| Desktop, the sample's 48 frames played five times in that window | the budget | the same: 768 MB of pictures after the first lap and after the fifth (the movie at this size is larger than the budget), 192 textures, the process at 814 to 826 MB | + +*A stage view at each zoom*, 1600 × 900 in 512 px tiles on the CPU oracle, a drawing of 64 +brush strokes merged into three shapes +(`cargo test --release -p anicraft-engine --lib stage_timings -- --ignored --nocapture`): + +| Zoom | Tiles | Edges walked, before | after | Prepare, before | after | One thread (as the browser draws), before | after | 32 threads, before | after | +|---|---|---|---|---|---|---|---|---|---| +| 100 % | 6 | 42,708 | 21,935 | 1.27 ms | 1.41 ms | 9.0 ms | 8.1 ms | 2.8 ms | 2.9 ms | +| 400 % | 12 | 133,288 | 31,317 | 2.94 ms | 2.08 ms | 31.7 ms | 23.3 ms | 8.0 ms | 8.3 ms | +| 1600 % | 12 | 226,884 | 22,901 | 3.67 ms | 2.14 ms | 34.4 ms | 20.1 ms | 8.7 ms | 7.9 ms | +| 6400 % | 8 | 281,304 | 13,416 | 3.34 ms | 1.32 ms | 33.5 ms | 13.0 ms | 6.7 ms | 6.2 ms | + +Before, a tile walked every edge of every shape that touched it, cut finer the deeper the +zoom; now the parts of a fill above, below and right of the tile are left out, and the +pictures are the same to the last bit (`render::cut_tests` compares the float pixmaps). On one +thread a tile at 6400 % costs what a tile at 100 % costs (1.6 ms against 1.4 ms; it was 4.2 ms +against 1.5 ms). With 512 strokes the same view went from 25.1 ms to 12.0 ms on one thread. + +*Frame time during a zoom gesture.* The stage asks for nothing while the zoom is changing, so +a frame of the gesture costs the interface alone (0.7 ms on the desktop, at every zoom up to 6400 %). In the +browser each of those frames used to draw the whole view on the interface's thread: 9 to +34 ms for the drawing above. + +Playing is bounded by the budget, not by this change: uncompressed, a 1600 × 940 view is +about 12 MB a frame, so a movie of some 60 frames fills 768 MB. Storing flat and repeated +tiles once is the next step (P-004 in the roadmap). + +The checks are relations, not timings (`engine::render_budget_tests`, +`stage_budget_tests`, `render::cut_tests`, `tests/wasm.rs`): a long drag or zoom holds what a +short one holds, playing longer adds nothing, a deep tile walks fewer edges than the whole +drawing has at 100 %, and what the screen needs is drawn before look-ahead. + **1080p render, back under budget (2026-11-06).** It had drifted to 19.4–20.2 ms (v0.1.0 measured 18.0–18.9 ms on the same machine; the 16.5 ms of 2026-10-28 didn't reproduce). Timing each step of a frame showed the time was outside the drawing itself: diff --git a/docs/roadmap.md b/docs/roadmap.md index 453aa997..614926fd 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -46,9 +46,9 @@ the changelog. | P-001 | AniCraft starts on every supported machine: the launch failures on Windows and Linux graphics drivers ([#164](https://github.com/storytold/anicraft/issues/164), [#158](https://github.com/storytold/anicraft/issues/158), [#207](https://github.com/storytold/anicraft/issues/207), [#268](https://github.com/storytold/anicraft/issues/268), [#421](https://github.com/storytold/anicraft/issues/421), [#342](https://github.com/storytold/anicraft/issues/342); duplicates [#488](https://github.com/storytold/anicraft/issues/488), [#448](https://github.com/storytold/anicraft/issues/448), [#412](https://github.com/storytold/anicraft/issues/412), [#313](https://github.com/storytold/anicraft/issues/313), [#286](https://github.com/storytold/anicraft/issues/286), [#285](https://github.com/storytold/anicraft/issues/285)) each end in a window or a message that says what to do | Preferences, platforms | M | reports' logs | platform | | P-002 | Nested symbols can't exhaust memory or hang: a work budget on evaluation and bounds (outside PR [#13](https://github.com/storytold/anicraft/issues/13)) | Symbols | S | | doc | | P-003 | What is left of "a long Brush stroke never freezes the app" ([#519](https://github.com/storytold/anicraft/issues/519)) after [ADR 0129](adr/0129-a-long-brush-stroke-never-holds-the-window.md) bounded the trace, took it off the window's thread and fixed the selection overlay: on one raw shape of ten thousand points and more, the Subselection tool's click (seconds, once), the Paint Bucket in a gap (about a second) and the shape tools' snapping (slow frames); and the merge of such a shape (75 to 220 ms) still runs on the window's thread | Tools | S each | | stage | -| P-004 | Memory and frame time stay flat: 900 MB for a 24-frame move in the web build ([#314](https://github.com/storytold/anicraft/issues/314)), stutter when zoomed in ([#477](https://github.com/storytold/anicraft/issues/477)); a budget test for each | Workspace | M | | render | +| P-004 | Memory and frame time stay flat, what is left ([ADR 0132](adr/0132-memory-and-frame-time-stay-flat.md) did the picture cache, zoom gestures, look-ahead order and off-tile edges for [#314](https://github.com/storytold/anicraft/issues/314) and [#477](https://github.com/storytold/anicraft/issues/477), each with a budget test): in the web build a drag still redraws the whole view on every pointer move (key tiles by what they show, so only the tiles the dragged thing touches are drawn again); a tile's preparation still visits every segment of a path it touches (a spatial index); played frames are kept uncompressed, about 12 MB a frame of a 1600 × 940 view, so a short movie fills the 768 MB budget (store flat and repeated tiles once, and decide the budget); deep-zoom timings of the GPU stage on more graphics cards | Workspace | M | | render | | P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), which did not reproduce on Windows 10 (the curved pointer shows outside a corner in the real window; the headless press-and-drag tests pass) and needs the reporter's build number and steps. Done: handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117), tested end to end), and [#193](https://github.com/storytold/anicraft/issues/193) decided by [ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md) with the rule in the guide | Tools | S | the reporter's answer | stage | -| P-006 | Animate files open right: lines missing or filled in ([#498](https://github.com/storytold/anicraft/issues/498)), a `.fla` refused on macOS ([#347](https://github.com/storytold/anicraft/issues/347)); each fixed file joins the corpus | Import | M | the reporters' files | xfl | +| P-006 | Animate files open right. Left: confirm the cause of the lines missing or filled in ([#498](https://github.com/storytold/anicraft/issues/498)) with the reporter's file or its import report, and confirm on a Mac that a `.fla` opens ([#347](https://github.com/storytold/anicraft/issues/347): the release it was reported on did not take documents the system hands over, `main` does since [ADR 0062](adr/0062-test-movie-window-and-macos-document-opening.md)); the same recovery in the shared reader (storytold/craft-libs#3282). Done ([ADR 0133](adr/0133-an-animate-shape-is-never-cut-down-quietly.md)): strokes of an unknown kind are drawn solid, an unreadable outline command costs only its own run, and everything left out of a shape is counted in the report; the `unknowns` corpus package. Each fixed file joins the corpus | Import | S | the reporters' files or reports | xfl | | P-007 | The web build is usable: import, export and save ([#55](https://github.com/storytold/anicraft/issues/55)), preferences kept ([#56](https://github.com/storytold/anicraft/issues/56)), a web asset on each release ([#316](https://github.com/storytold/anicraft/issues/316), [#210](https://github.com/storytold/anicraft/issues/210)), a run in a real browser in CI | Preferences, platforms | M | | platform | | P-008 | Text reads right: mixed directions (outside PR [#39](https://github.com/storytold/anicraft/issues/39)), then letters from a fallback face (outside PR [#40](https://github.com/storytold/anicraft/issues/40)) | Text | M | [#39](https://github.com/storytold/anicraft/issues/39) before [#40](https://github.com/storytold/anicraft/issues/40) | text | | P-010 | Panel bugs still open: a side dock that grows under the pointer ([#159](https://github.com/storytold/anicraft/issues/159): not reproduced on `main`, which a test now pins at the reported interface scales; needs the reporters to retest a current build) and the flicker in [#255](https://github.com/storytold/anicraft/issues/255) (needs the machine; Preferences › Window graphics is the way round it). Fixed: [#513](https://github.com/storytold/anicraft/issues/513), [#246](https://github.com/storytold/anicraft/issues/246) | Workspace | S each | the reporters | shell | diff --git a/packaging/README.md b/packaging/README.md index ee340646..40af2fd8 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -41,3 +41,21 @@ locally (it skips tools that aren't installed). It validates; it never submits. Flathub, winget and the Microsoft Store are made by the team. winget manifests go in `windows/winget/*.yaml` and an MSIX manifest in `windows/msix/AppxManifest.xml`; the check reads their required fields once they exist. + +## Nightly + +The preview channel the ArtCraft Launcher installs beside stable AniCraft has its own scripts, +which the stable ones never source: `nightly-common.sh` (the four `ANICRAFT_*` values and the +frozen, clean tree), `linux/nightly.sh` with `linux/nightly-launch.sh` (the one launcher every +Linux nightly format installs; the plain tar is the standard layout, `anicraft` the launcher and +`anicraft-bin` the GUI it starts), `macos/nightly.{sh,sh-sign,sh-verify}` with +`macos/nightly-lib.sh` and `macos/nightly_plist.py`, and `windows/nightly.ps1` behind +`windows/package.ps1 -Nightly -BuildOnly`. Every artifact is GUI only: no `anicraft-cli`, portable +marker, `.desktop`, DMG, association or URL type. Signing is the trusted step's +(`windows/sign.ps1 -Required`, `macos/nightly-sign.sh`, the Linux key in `.github/`). + +`nightly-tests.py` runs the synthetic suites (archive policy, the launcher in each format's +layout, icon/plist rendering, and the Apple scripts against stand-in tools), and `windows/nightly-{package,signing}-tests.ps1` check the +spec, the source identity, the flavor binding and the compiler/signer boundary. The three +platforms are built for real, unsigned, by `.github/workflows/nightly-builds.yml` behind the +`full-ci` label. See `docs/nightly-builds.md` for the contract and the data root. diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 2c762bfb..5c3d9852 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -17,6 +17,12 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.anicraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${ANICRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + FLATPAK_ID="$APP_ID.nightly" +fi FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 @@ -52,29 +58,75 @@ rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 [[ -x "$WORK/stage/bin/anicraft" ]] || { echo "error: $TARBALL has no bin/anicraft" >&2; exit 1; } -cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + sed -e "s#^Exec=anicraft\([[:space:]]\|$\)#Exec=anicraft-nightly\1#" \ + -e "s|^TryExec=anicraft$|TryExec=anicraft-nightly|" \ + -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=AniCraft$|Name=AniCraft Nightly|" \ + -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.anicraft.nightly-v1|' \ + -e '/^MimeType=/d' \ + "$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop" + rm -f "$WORK/stage/share/applications/$APP_ID.desktop" + sed -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|AniCraft|AniCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|anicraft|anicraft-nightly|g" \ + -e '//d' \ + "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml" + rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" + # Nightly registers no file associations (its desktop entry drops MimeType= too). + rm -rf "$WORK/stage/share/mime" + NIGHTLY_ICON="$ROOT/assets/app-icon/anicraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$WORK/stage/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + # The sandbox keeps its own home, but the program still needs the flavor's profile protocol: the + # bundle runs the same launcher every other format installs (packaging/linux/nightly-launch.sh). + install -Dm755 "$HERE/nightly-launch.sh" "$WORK/stage/bin/anicraft-nightly" + # The sandbox installs the GUI as `anicraft-bin`, the name the launcher looks for: a stable + # program called `anicraft` is never a candidate, in the sandbox or anywhere else. + sed -e "s|ai\.storyteller\.anicraft|$FLATPAK_ID|g" \ + -e "s|^command: anicraft$|command: anicraft-nightly|" \ + -e "s|^ - install -Dm755 bin/anicraft /app/bin/anicraft$| - install -Dm755 bin/anicraft /app/bin/anicraft-bin\\n - install -Dm755 bin/anicraft-nightly /app/bin/anicraft-nightly|" \ + -e '/install -Dm644 share\/mime\/packages\//d' \ + "$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml" +else + cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml" +fi flatpak remote-add --user --if-not-exists flathub "$FLATHUB" # --disable-rofiles-fuse: no FUSE in containers and CI runners. flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \ - --default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml" + --default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml" OUT="$DIST/$BASENAME.flatpak" # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. -flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable +flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH" echo "wrote $OUT" if [[ "$OCI" = 1 ]]; then OUT_OCI="$DIST/$BASENAME-oci" rm -rf "$OUT_OCI" - flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH" echo "wrote OCI layout to $OUT_OCI" fi if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" - flatpak info --user "$APP_ID" - flatpak run --command=anicraft-cli "$APP_ID" --version - flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps' + flatpak info --user "$FLATPAK_ID" + flatpak run --command=anicraft-cli "$FLATPAK_ID" --version + SHARE_PATHS='/app/share/applications /app/share/metainfo /app/share/icons/hicolor/*/apps' + if [[ "$FLATPAK_ID" = "$APP_ID" ]]; then + SHARE_PATHS='/app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps' + else + # Nightly ships no MIME database (its metadata declares no association), so asking for that + # folder would end the run under `set -e`; the launcher answers its version query instead. + flatpak run --command=anicraft-nightly "$FLATPAK_ID" --version | grep -qxF "AniCraft $VERSION (nightly-v1)" + fi + flatpak run --command=sh "$FLATPAK_ID" -c "ls $SHARE_PATHS" fi echo "==> done" ls -lh "$OUT" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 27afa595..42efbb6f 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -3,7 +3,7 @@ # glibc the binaries need for @GLIBC_FLOOR@, and exports VERSION and NFPM_ARCH. # # nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: anicraft +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -72,12 +72,15 @@ overrides: - (pipewire-alsa or alsa-plugins-pulseaudio) contents: - - src: ${STAGE}/usr/bin/anicraft - dst: /usr/bin/anicraft + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/anicraft-cli - dst: /usr/bin/anicraft-cli + - src: ${STAGE}/usr/bin/${NFPM_CLI} + dst: /usr/bin/${NFPM_CLI} file_info: { mode: 0755 } + - src: ${STAGE}/usr/lib/ + dst: /usr/lib/ + type: tree - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 00000000..cd8aa13e --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# Validate the staged Arch handoff without building or opening AniCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=anicraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" "$stage/share/applications" "$stage/share/metainfo" + +# A local argv recorder stands in for the compiled binaries. It never opens a UI. +cat >"$stage/bin/anicraft" <<'RECORDER' +#!/bin/sh +for arg in "$@"; do + printf '<%s>\n' "$arg" +done +RECORDER +chmod 755 "$stage/bin/anicraft" +cp "$stage/bin/anicraft" "$stage/bin/anicraft-cli" +# The stage package.sh builds, as far as the handoff reads it. +cp "$HERE/ai.storyteller.anicraft.desktop" "$stage/share/applications/ai.storyteller.anicraft.desktop" +sed -e 's/@VERSION@/0.0.1/' -e 's/@DATE@/2026-11-24/' \ + "$HERE/ai.storyteller.anicraft.metainfo.xml.in" >"$stage/share/metainfo/ai.storyteller.anicraft.metainfo.xml" +mkdir -p "$stage/share/mime/packages" +cp "$HERE/ai.storyteller.anicraft.mime.xml" "$stage/share/mime/packages/ai.storyteller.anicraft.xml" + +bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base" +tar -xzf "$dst/$base.tar.gz" -C "$work/extract" +pack="$work/extract/$base" +# The launcher is the shared one, byte for byte, and the real program hides beside it. +cmp "$HERE/nightly-launch.sh" "$pack/bin/anicraft" +bash -n "$pack/bin/anicraft" +# Simulate the existing Arch bin-tree copy and public launcher rename. +mkdir -p "$work/installed" +cp -R "$pack/bin" "$work/installed/bin" +bin="$work/installed/bin" +mv "$bin/anicraft" "$bin/anicraft-nightly" +mv "$bin/anicraft-cli" "$bin/anicraft-nightly-cli" +cmp "$stage/bin/anicraft" "$bin/.anicraft-nightly/anicraft" +cmp "$stage/bin/anicraft-cli" "$bin/anicraft-nightly-cli" + +# No stable desktop entry, AppStream id, icon or MIME package can reach an Arch Nightly install. +apps="$pack/share/applications" +nightly_id=ai.storyteller.anicraft.nightly-v1 +[[ -f "$apps/$nightly_id.desktop" && ! -e "$apps/ai.storyteller.anicraft.desktop" ]] +for line in 'Name=AniCraft Nightly' 'Exec=anicraft-nightly %f' 'TryExec=anicraft-nightly' \ + "Icon=$nightly_id" "StartupWMClass=$nightly_id"; do + grep -qxF "$line" "$apps/$nightly_id.desktop" || { echo "missing desktop line: $line" >&2; exit 1; } +done +# `! grep` is not a condition: errexit skips it, so a match would pass. Fail explicitly. +if grep -q '^MimeType=' "$apps/$nightly_id.desktop"; then + echo 'FAIL: the Nightly desktop entry still declares MimeType' >&2 + exit 1 +fi +meta="$pack/share/metainfo/$nightly_id.metainfo.xml" +[[ -f "$meta" && ! -e "$pack/share/metainfo/ai.storyteller.anicraft.metainfo.xml" ]] +grep -qF "$nightly_id" "$meta" +grep -qF 'AniCraft Nightly' "$meta" +grep -qF 'anicraft-nightly' "$meta" +if grep -qF '' "$meta"; then + echo 'FAIL: the Nightly AppStream file still declares a mediatype' >&2 + exit 1 +fi +[[ ! -e "$pack/share/mime" ]] +[[ -f "$pack/share/icons/hicolor/256x256/apps/$nightly_id.png" ]] + +export HOME="$work/home with space" +unset XDG_DATA_HOME +expect() { + expected="$1" + shift + actual=$(PATH="$bin:$PATH" anicraft-nightly "$@") + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} +profile="$HOME/.local/share/anicraft-nightly/profile" +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" --)" # no arguments +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- 'scene with spaces.anicraft' '--other-name.anicraft')" \ + 'scene with spaces.anicraft' '--other-name.anicraft' +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" --version)" --version +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -V)" -V +export XDG_DATA_HOME="$work/xdg with space" +profile="$XDG_DATA_HOME/anicraft-nightly/profile" +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- 'scene with spaces.anicraft')" 'scene with spaces.anicraft' +# The Launcher's own command line is passed through, not wrapped a second time. +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher-profile" -- 'scene.anicraft')" \ + --launch-profile nightly-v1 --profile-root "$work/launcher-profile" -- 'scene.anicraft' + +# The handoff can be unpacked under a folder another local user may write, so a program planted in +# a sibling lib folder is never run in place of the packaged one. +planted="$work/planted" +mkdir -p "$planted/lib/anicraft-nightly" "$planted/bin/.anicraft-nightly" +cp "$pack/bin/anicraft" "$planted/bin/anicraft" +cp "$stage/bin/anicraft" "$planted/bin/.anicraft-nightly/anicraft" +printf '#!/bin/sh\necho PLANTED-BY-ANOTHER-USER\n' >"$planted/lib/anicraft-nightly/anicraft" +chmod 755 "$planted/lib/anicraft-nightly/anicraft" +[[ "$("$planted/bin/anicraft" walk.anicraft)" != PLANTED* ]] + +echo "PASS: Arch Nightly handoff starts through the shared launcher in its own profile" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 00000000..aa419f49 --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Stage the AniCraft Nightly-only handoff for the Arch packager. +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +source_tree="$1" +work="$2" +destination="$3" +basename="$4" +stage="$work/$basename" +app_id=ai.storyteller.anicraft +nightly_id=$app_id.nightly-v1 + +mkdir -p "$work" +cp -R "$source_tree" "$stage" +mkdir "$stage/bin/.anicraft-nightly" +mv "$stage/bin/anicraft" "$stage/bin/.anicraft-nightly/anicraft" +# The launcher every Nightly format installs: it starts the real program with +# --launch-profile nightly-v1 --profile-root -- +# (packaging/linux/nightly-launch.sh). +cp "$here/nightly-launch.sh" "$stage/bin/anicraft" +chmod 755 "$stage/bin/anicraft" + +# The packager ships bin/ and share/ as they are, so Arch Nightly must not land on stable's +# desktop entry, AppStream id, icons or MIME package: ship the Nightly ones. Their +# StartupWMClass is the window class the Nightly build sets (src/platform.rs APP_ID_NIGHTLY). +if [[ -d "$stage/share" ]]; then + if [[ -f "$stage/share/applications/$app_id.desktop" ]]; then + sed -e "s#^Exec=anicraft\([[:space:]]\|$\)#Exec=anicraft-nightly\1#" \ + -e "s|^TryExec=anicraft$|TryExec=anicraft-nightly|" \ + -e "s|^Icon=$app_id$|Icon=$nightly_id|" \ + -e "s|^Name=AniCraft$|Name=AniCraft Nightly|" \ + -e "s|^StartupWMClass=.*|StartupWMClass=$nightly_id|" \ + -e '/^MimeType=/d' \ + "$stage/share/applications/$app_id.desktop" >"$stage/share/applications/$nightly_id.desktop" + rm -f "$stage/share/applications/$app_id.desktop" + fi + if [[ -f "$stage/share/metainfo/$app_id.metainfo.xml" ]]; then + sed -e "s|$app_id|$nightly_id|g" \ + -e "s|AniCraft|AniCraft Nightly|g" \ + -e "s|$app_id.desktop|$nightly_id.desktop|g" \ + -e "s|$app_id|$nightly_id|g" \ + -e "s|anicraft|anicraft-nightly|g" \ + -e "s|anicraft-cli|anicraft-nightly-cli|g" \ + -e '//d' \ + "$stage/share/metainfo/$app_id.metainfo.xml" >"$stage/share/metainfo/$nightly_id.metainfo.xml" + rm -f "$stage/share/metainfo/$app_id.metainfo.xml" + fi + rm -rf "$stage/share/mime" + if [[ -f "$here/../../assets/app-icon/anicraft-nightly.png" ]]; then + rm -rf "$stage/share/icons/hicolor" + install -Dm644 "$here/../../assets/app-icon/anicraft-nightly.png" \ + "$stage/share/icons/hicolor/256x256/apps/$nightly_id.png" + fi +fi + +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh new file mode 100755 index 00000000..7ae05c39 --- /dev/null +++ b/packaging/linux/nightly-launch.sh @@ -0,0 +1,77 @@ +#!/bin/sh +# AniCraft Nightly's launcher: one private profile and the flavor's launch protocol, for every +# Linux nightly format. The real program never starts without +# +# --launch-profile nightly-v1 --profile-root -- +# +# so nothing can move Nightly's preferences, Recovery, Logs, plug-ins, Templates, Commands, +# themes, thumbnails and guide cache (src/platform.rs) into stable's folders. The profile is a +# sibling of stable's data folder, never inside it and never containing it (src/profile_root.rs). +# +# The same file is installed as: +# deb/rpm /usr/bin/anicraft-nightly (the real program in /usr/lib/anicraft-nightly/) +# AppImage $APPDIR/AppRun (the real program in $APPDIR/usr/bin/) +# Arch bin/anicraft (the real program in bin/.anicraft-nightly/) +# Flatpak /app/bin/anicraft-nightly (the real program in /app/bin/anicraft-bin) +# nightly tar anicraft (the real program in anicraft-bin beside it) +set -eu +case "$0" in + */*) self=$0 ;; + *) self=$(command -v -- "$0" 2>/dev/null || printf '%s' "$0") ;; +esac +# Physical, so a merged-`/usr` system's `/bin/` is still the system install (/usr/bin). +here=$(CDPATH='' cd -P -- "$(dirname -- "$self")" && pwd -P) +self="$here/$(basename -- "$self")" + +# Picks the first candidate that is a regular program of the bundle (never this script itself). +find_program() { + for candidate in "$@"; do + if [ -f "$candidate" ] && [ ! -L "$candidate" ] && ! [ "$candidate" -ef "$self" ]; then + printf '%s' "$candidate" + return 0 + fi + done + return 1 +} + +# Every candidate is either inside the bundle this launcher came with or the one fixed system path +# a package installs into: no path is computed from a parent of `$here`, because an AppImage mount, +# an extracted tar and the Arch handoff can sit under a folder another local user can write. +# A stable program is never a candidate either (`/usr/bin/anicraft` is stable's, and the packages +# are co-installable), so a co-installed Stable copy can never be started in Nightly's place. +real_bin= +if [ "$here" = /usr/bin ]; then + # The deb/rpm puts the program in its own lib folder beside the system bin directory. + real_bin=$(find_program /usr/lib/anicraft-nightly/anicraft "$here/anicraft-bin" \ + "$here/.anicraft-nightly/anicraft" "$here/usr/bin/anicraft") || : +else + real_bin=$(find_program "$here/anicraft-bin" "$here/.anicraft-nightly/anicraft" \ + "$here/usr/bin/anicraft") || : +fi +if [ -z "$real_bin" ]; then + echo 'anicraft-nightly: the AniCraft Nightly program is not where this launcher was installed' >&2 + exit 2 +fi + +# A relative XDG_DATA_HOME is ignored, as the XDG spec and the app's own data_home_for do: the +# profile root must be absolute, so a relative one would only make the program refuse to start. +case "${XDG_DATA_HOME:-}" in + /*) data_home=$XDG_DATA_HOME ;; + *) data_home="${HOME:?HOME is required to place the AniCraft Nightly profile}/.local/share" ;; +esac +profile_root="$data_home/anicraft-nightly/profile" + +# The Launcher already speaks this protocol: pass it through rather than wrap it a second time. +case "${1:-}" in + --launch-profile | --profile-root) exec "$real_bin" "$@" ;; +esac +# A delimiter the caller supplied is never doubled. +if [ "${1:-}" = "--" ]; then + shift + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" +fi +# `anicraft-nightly --version` answers the Launcher's own query form, before any profile exists. +if [ "$#" -eq 1 ] && { [ "$1" = "--version" ] || [ "$1" = "-V" ]; }; then + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$1" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 00000000..db75a7a2 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +# +# $DIST/anicraft--linux-x86_64-nightly.tar.gz +# +# Usage: packaging/linux/nightly.sh --arch x86_64 +# +# The optional distribution formats stay the stable scripts' (packaging/linux/package.sh, +# flatpak-oci.sh), which take ANICRAFT_BUILD_CHANNEL for a co-installable nightly package. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) sed -n '2,10p' "$0"; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/anicraft-$VERSION-linux-x86_64-nightly.tar.gz" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_refuse_signing_env +nightly_build_gui +STAGE="$NIGHTLY_WORK/stage" +mkdir -p "$STAGE" +# The standard Nightly tar layout: `anicraft` is the launcher (the app's own name) and +# `anicraft-bin` the GUI it starts, so an extracted tar is isolated exactly as the packages are and +# the shared smoke can query the entry point by the app's name. +install -m755 "$NIGHTLY_GUI" "$STAGE/anicraft-bin" +"${CROSS_COMPILE:-}strip" "$STAGE/anicraft-bin" 2>/dev/null || true +# The same launcher the deb/rpm, AppImage, Arch and Flatpak nightly formats install. +install -m755 "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/anicraft" +cp "$ROOT/assets/app-icon/anicraft-nightly.png" "$STAGE/anicraft-nightly.png" +nightly_copy_notices "$STAGE" +# The staged launcher answers the Launcher's version query from the staged binary, exactly as an +# extracted copy does (no profile is created by a query). +[[ "$("$STAGE/anicraft" --version)" == "AniCraft $VERSION (nightly-v1)" ]] || + nightly_die 'the archive launcher does not answer the prepared nightly version' +# The private mktemp cwd is the helper authority root, not a CLI path parent. +(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz) +nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT" diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 9551f318..672071d7 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -10,7 +10,7 @@ # Every format installs the desktop entry, the AppStream metainfo, the hicolor icons and the # MIME types (.anicraft is AniCraft's; .fla and .xfl open as an untitled import). # -# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY] # # Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com). AppImage tooling is downloaded # at verified pins into $CARGO_TARGET_DIR. Build on an old distro (CI: Ubuntu 22.04, glibc 2.35) @@ -28,10 +28,16 @@ HERE="$ROOT/packaging/linux" SKIP_BUILD=0 FORMATS="appimage deb rpm tar" +ARCH_TAR_DIR= while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; + --arch-tar-dir) + [[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; } + ARCH_TAR_DIR="$2" + shift 2 + ;; -h | --help) sed -n '2,21p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -45,9 +51,24 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export ANICRAFT_MAINTAINER="${ANICRAFT_MAINTAINER:-AniCraft maintainers }" -BASENAME="anicraft-$VERSION-linux-$ARCH" +IS_NIGHTLY=0 +BASENAME_VERSION="$VERSION" +if [[ "${ANICRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export ANICRAFT_BUILD_CHANNEL=nightly-v1 + export ANICRAFT_OVERRIDE_VERSION="$VERSION" + if [[ "$BASENAME_VERSION" != *-nightly* ]]; then + BASENAME_VERSION="$VERSION-nightly" + fi +fi +BASENAME="anicraft-$BASENAME_VERSION-linux-$ARCH" -echo "==> AniCraft $VERSION for Linux $ARCH ($FORMATS)" +if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then + echo "error: --arch-tar-dir is only for Nightly builds" >&2 + exit 2 +fi + +echo "==> AniCraft $VERSION for Linux $ARCH ($FORMATS, channel=${ANICRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p anicraft -p anicraft-cli --bins ${CROSS_TARGET:+--target "$CROSS_TARGET"}) @@ -62,6 +83,11 @@ install -Dm755 "$BIN/anicraft" "$STAGE/usr/bin/anicraft" install -Dm755 "$BIN/anicraft-cli" "$STAGE/usr/bin/anicraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/anicraft" "$STAGE/usr/bin/anicraft-cli" 2>/dev/null || true install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" +if [[ "$IS_NIGHTLY" = 1 ]]; then + sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.anicraft.nightly-v1|' \ + "$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp" + mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop" +fi install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml" mkdir -p "$STAGE/usr/share/metainfo" sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$ANICRAFT_BUILD_DATE/g" \ @@ -94,13 +120,85 @@ if has tar; then echo "wrote $DIST/$BASENAME.tar.gz" fi +# The Arch handoff keeps the same basename as the plain tarball in a separate directory. +# Flatpak, OCI and direct tar consumers still get the original binary, not this launcher. +if [[ -n "$ARCH_TAR_DIR" ]]; then + mkdir -p "$ARCH_TAR_DIR" + if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then + echo "error: the Arch tar directory must differ from the release directory" >&2 + exit 2 + fi + bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME" +fi + # ---- .deb / .rpm -------------------------------------------------------------------------------- if has deb || has rpm; then command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; } export VERSION export NFPM_ARCH="$DEB_ARCH" + NFPM_STAGE="$STAGE" + export NFPM_NAME="anicraft" + export NFPM_BIN="anicraft" + export NFPM_CLI="anicraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + export NFPM_NAME="anicraft-nightly" + export NFPM_BIN="anicraft-nightly" + export NFPM_CLI="anicraft-nightly-cli" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + install -Dm755 "$NFPM_STAGE/usr/bin/anicraft" "$NFPM_STAGE/usr/lib/anicraft-nightly/anicraft" + # The shared nightly launcher (packaging/linux/nightly-launch.sh): the real program in + # usr/lib/anicraft-nightly, started with --launch-profile nightly-v1 --profile-root -- , so no format can start it without a private profile. + install -Dm755 "$HERE/nightly-launch.sh" "$NFPM_STAGE/usr/bin/$NFPM_BIN" + rm -f "$NFPM_STAGE/usr/bin/anicraft" + install -Dm755 "$NFPM_STAGE/usr/bin/anicraft-cli" "$NFPM_STAGE/usr/lib/anicraft-nightly/anicraft-cli" + cat >"$NFPM_STAGE/usr/bin/$NFPM_CLI" <<'CLI_WRAPPER' +#!/bin/sh +set -eu +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec /usr/lib/anicraft-nightly/anicraft-cli "$@" +fi +profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}" +export XDG_CONFIG_HOME="$profile_base/anicraft-nightly" +exec /usr/lib/anicraft-nightly/anicraft-cli "$@" +CLI_WRAPPER + chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_CLI" + rm -f "$NFPM_STAGE/usr/bin/anicraft-cli" + mv "$NFPM_STAGE/usr/share/doc/anicraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=anicraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=anicraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=AniCraft$|Name=AniCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop" + rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" + sed -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|AniCraft|AniCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|anicraft|$NFPM_BIN|g" \ + -e "s|anicraft-cli|$NFPM_CLI|g" \ + -e '//d' \ + "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$NFPM_STAGE/usr/share/mime" + NIGHTLY_ICON="$ROOT/assets/app-icon/anicraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + fi # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed -e "s|\${STAGE}|$STAGE|g" -e "s|@GLIBC_FLOOR@|${GLIBC_FLOOR:-2.35}|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + DROP_LIB_TREE= + # shellcheck disable=SC2016 + [[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;' + # shellcheck disable=SC2016 + sed "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g;s|@GLIBC_FLOOR@|${GLIBC_FLOOR:-2.35}|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done @@ -110,10 +208,32 @@ fi if has appimage; then APPDIR="$WORK/AniCraft.AppDir" cp -R "$STAGE" "$APPDIR" - ln -s usr/bin/anicraft "$APPDIR/AppRun" - cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" - cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" - ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + if [[ "$IS_NIGHTLY" = 1 ]]; then + APPIMAGE_ID="$APP_ID.nightly-v1" + # AppRun is the shared launcher (not a symlink): from $APPDIR it finds usr/bin/anicraft and + # starts it with the flavor's protocol and a profile of its own. + install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/AppRun" + sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=AniCraft$|Name=AniCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" + rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop" + cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop" + NIGHTLY_ICON="$ROOT/assets/app-icon/anicraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$APPDIR/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png" + cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png" + ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon" + else + ln -s usr/bin/anicraft "$APPDIR/AppRun" + cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" + cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" + ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + fi # Digests from the official GitHub release asset metadata (the same pins as the other Craft apps): # https://github.com/AppImage/appimagetool/releases/tag/1.9.1 @@ -156,11 +276,20 @@ if has appimage; then # blocks that changed in a newer release, through the .zsync published next to each AppImage. # A fork's builds point at its own releases through GITHUB_REPOSITORY. REPO="${GITHUB_REPOSITORY:-storytold/AniCraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|anicraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|anicraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + else + # Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point + # zsync update metadata at pre-release tags matching `-nightly` rather than stable `latest`. + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|anicraft-*-nightly*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + fi # Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime, # so users don't need libfuse2 either. (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream \ - --runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT") + --runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT") echo "wrote $OUT" if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" diff --git a/packaging/macos/nightly-lib.sh b/packaging/macos/nightly-lib.sh new file mode 100644 index 00000000..966beb3b --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,110 @@ +# shellcheck shell=bash +# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh). +# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output +# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS. + +MAC_NIGHTLY_APP='AniCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.anicraft.nightly' +# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh). +MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID) + +mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +# The exact prepared version from the feed asset name, or failure. +mac_nightly_version_from_asset() { + local name="$1" version + [[ "$name" =~ ^anicraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1 + version="${BASH_REMATCH[1]}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1 + printf '%s\n' "$version" +} + +# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback. +mac_nightly_require_secrets() { + local name + for name in "${MAC_NIGHTLY_SECRETS[@]}"; do + [[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback" + done + [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID' + if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then + mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)' + fi +} + +# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team. +mac_nightly_identity_is_team() { + local line="$1" identity="$2" team="$3" + [[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]] +} + +# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the +# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict). +mac_nightly_check_signature() { + local details="$1" team="$2" ok=0 + grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; } + grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; } + grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; } + grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; } + grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; } + return "$ok" +} + +# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized. +mac_nightly_check_assessment() { + grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1" +} + +# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly +# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file. +mac_nightly_check_zip_entries() { + python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file' +import stat, sys, zipfile +archive, app = sys.argv[1:] +with zipfile.ZipFile(archive) as z: + for info in z.infolist(): + name = info.filename + parts = name.rstrip("/").split("/") + mode = info.external_attr >> 16 + if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app + or any(part in ("", ".", "..") for part in parts) + or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)): + sys.exit(f"refused entry: {name!r}") +PY +} + +# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 AniCraft +# executable, the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special +# files, no document or URL types. +mac_nightly_check_bundle() { + local payload="$1" version="$2" app entries plist key value + app="$payload/$MAC_NIGHTLY_APP" + entries="$(ls -A "$payload")" + [[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP" + [[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files' + [[ "$(ls -A "$app/Contents/MacOS")" == AniCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the AniCraft GUI (no CLI)' + [[ -f "$app/Contents/MacOS/AniCraft" && -x "$app/Contents/MacOS/AniCraft" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/AniCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable AniCraftVersion; do + value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key" + case "$key" in + CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;; + CFBundleExecutable) [[ "$value" == AniCraft ]] ;; + AniCraftVersion) [[ "$value" == "$version" ]] ;; + esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity" + done + for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do + if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi + done +} + +# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68) +# though the ticket is there (verify.sh). +mac_nightly_validate_staple() { + local target="$1" attempt + for attempt in 1 2 3 4 5; do + xcrun stapler validate "$target" && return 0 + [[ "$attempt" = 5 ]] || sleep $((attempt * 20)) + done + return 1 +} diff --git a/packaging/macos/nightly-sign.sh b/packaging/macos/nightly-sign.sh new file mode 100644 index 00000000..573869e0 --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route +# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps): +# +# nightly-sign.sh --arch aarch64 --input /abs/anicraft--macos-aarch64-nightly.zip \ +# --output /abs//anicraft--macos-aarch64-nightly.zip +# +# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and +# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended +# attributes. Writes only that file, never replacing one; the temporary keychain and work directory +# are removed on every exit. +# +# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD, +# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must +# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base). +# +# Never compiles, and never runs anything from the payload: the version query runs on the signed +# bundle in a job without secrets (nightly-verify.sh). +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" + +ARCH='' INPUT='' OUTPUT='' +while [[ $# -gt 0 ]]; do + case "$1" in + --arch | --input | --output) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,18p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported' +[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths' +NAME="$(basename -- "$INPUT")" +VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name' +[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file' +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output' +[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist' +mac_nightly_require_secrets +[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)' + +BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" +WORK="$(mktemp -d "${BASE%/}/anicraft-nightly-sign.XXXXXX")" +KEYCHAIN="$WORK/anicraft-signing.keychain-db" +cleanup() { + if [[ -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi + rm -rf -- "$WORK" +} +trap cleanup EXIT + +# ---- identity: import-cert.sh, into this run's private directory ------------------------------ +# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps. +imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")" +IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")" +[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ && "$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" == "$KEYCHAIN" ]] \ + || mac_nightly_die 'import-cert.sh did not import a signing identity' +mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \ + || mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID" +echo "==> AniCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY" + +# ---- the unsigned bundle --------------------------------------------------------------------------- +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +# ---- package.sh's signing and notarization, with a required Developer ID --------------------------- +sign() { + codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@" +} + +notarize() { + local file="$1" out id status + echo "==> notarizing $(basename "$file") (this can take a few minutes)" + out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \ + --team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true + echo "$out" + id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" + status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then + # Capped: the shared signer bounds a step's output at 256 KiB. + xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true + fi + echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 + exit 1 + fi +} + +# Stapling and validating both look the ticket up in Apple's CloudKit service, which can drop the +# connection right after notarization (error 68), so retry the pair (package.sh). +staple() { + local file="$1" attempt + for attempt in 1 2 3 4 5; do + if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then + return + fi + if [[ "$attempt" = 5 ]]; then + echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2 + exit 1 + fi + echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2 + sleep $((attempt * 20)) + done +} + +# Inside-out: the executable, then the bundle (no --deep on the final signature). +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/AniCraft" +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" +codesign --verify --strict --deep --verbose=2 "$APP" +ditto -c -k --keepParent "$APP" "$WORK/notarize.zip" +notarize "$WORK/notarize.zip" +# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs. +staple "$APP" + +# ---- the final archive, checked as the Launcher unpacks it ----------------------------------------- +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip" +ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check" +mac_nightly_check_bundle "$WORK/check" "$VERSION" +CHECK="$WORK/check/$MAC_NIGHTLY_APP" +codesign --verify --strict --deep --verbose=2 "$CHECK" +mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \ + || mac_nightly_die 'the signed bundle is not the required Developer ID signature' +mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle' +# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh). +for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 +done +printf '%s\n' "$assessment" +mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' + +nightly_publish_archive "$WORK/final.zip" "$OUTPUT" diff --git a/packaging/macos/nightly-verify.sh b/packaging/macos/nightly-verify.sh new file mode 100644 index 00000000..2019c165 --- /dev/null +++ b/packaging/macos/nightly-verify.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version. +# For a job without signing material (it refuses to run with any), after nightly-sign.sh: +# +# nightly-verify.sh --input /abs/anicraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/anicraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact AniCraftVersion, unpacked +# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else +# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as +# notarized. `unsigned` (nightly.sh's compile output, e.g. pull-request CI) checks no signature. +# Last, the bundle's GUI answers its version query with an empty environment, both plainly and in the +# Launcher's form `--launch-profile nightly-v1 --profile-root --version` (the shared producer +# smoke): each must exit 0 within 15 seconds, print exactly `AniCraft (nightly-v1)` and +# write nothing to standard error. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" + +INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}" +while [[ $# -gt 0 ]]; do + case "$1" in + --input | --expect | --team) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do + [[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)" +done +[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned' +[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)' +[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file' +VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac' + +WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/anicraft-nightly-verify.XXXXXX")" +trap 'rm -rf -- "$WORK"' EXIT +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +if [[ "$EXPECT" == signed ]]; then + codesign --verify --strict --deep --verbose=2 "$APP" + mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \ + || mac_nightly_die 'the bundle is not the required Developer ID signature' + mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle' + for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 + done + printf '%s\n' "$assessment" + mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' +fi + +# macOS has no timeout(1): perl's alarm survives its exec and ends a query that hangs (a dialog, say). +query() { + local out + out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \ + /usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/AniCraft" "$@" 2>"$WORK/stderr")" \ + || mac_nightly_die "the version query ($*) failed or did not finish within 15 s" + [[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")" + [[ "$out" == "AniCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not AniCraft $VERSION (nightly-v1)" +} +mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile" +query --version +query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version +echo "==> verified ($EXPECT): AniCraft $VERSION (nightly-v1), plain and in the Launcher's profile form" diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh new file mode 100644 index 00000000..e50471f6 --- /dev/null +++ b/packaging/macos/nightly.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material): +# +# $DIST/anicraft--macos-aarch64-nightly.zip AniCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): ANICRAFT_BUILD_CHANNEL=nightly-v1, ANICRAFT_VERSION, +# ANICRAFT_BUILD_SHA, ANICRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional. +# +# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI, +# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query +# runs on the signed bundle (nightly-verify.sh). +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) sed -n '2,13p' "$0"; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; } +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +. "$HERE/../nightly-common.sh" +. "$HERE/nightly-lib.sh" +nightly_refuse_signing_env +nightly_init macos "$ARCH" aarch64-apple-darwin +# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh). +export MACOSX_DEPLOYMENT_TARGET=11.0 +OUTPUT="$DIST/anicraft-$VERSION-macos-aarch64-nightly.zip" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_compile_gui + +APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/AniCraft" +chmod 755 "$APP/Contents/MacOS/AniCraft" +cp "$ROOT/assets/app-icon/anicraft-nightly.icns" "$APP/Contents/Resources/anicraft-nightly.icns" +nightly_copy_notices "$APP/Contents/Resources" +# The private mktemp cwd is the helper authority root: stage the template inside it. +cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in" +(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \ + --output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$ANICRAFT_BUILD_SHA") +plutil -lint "$APP/Contents/Info.plist" +printf 'APPL????' >"$APP/Contents/PkgInfo" +mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION" + +# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them. +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip" +nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT" diff --git a/packaging/macos/nightly_plist.py b/packaging/macos/nightly_plist.py new file mode 100644 index 00000000..203dfcc3 --- /dev/null +++ b/packaging/macos/nightly_plist.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Nightly metadata: run from a private owned build cwd with a staged template. + +All file arguments must stay beneath that cwd; this is not native/signing acceptance. +""" +import argparse +import datetime +import os +from pathlib import Path +import plistlib +import re +import sys + +# The shared helper location is fixed by this script, not by CLI file arguments. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from nightly_paths import OwnedBuildRoot + +MAX_TEMPLATE_BYTES = 256 * 1024 + +IDENTIFIER = "ai.storyteller.anicraft.nightly" +ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations") +VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z") + + +def render(template: bytes, version: str, commit: str) -> bytes: + match = VERSION.fullmatch(version) + if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]: + raise ValueError("exact prepared Nightly version and matching source commit are required") + datetime.datetime.strptime(match[2], "%Y%m%d") + data = plistlib.loads(template) + if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL": + raise ValueError("expected the app-owned application plist template") + for key in ASSOCIATIONS: + data.pop(key, None) + data.update( + CFBundleDisplayName="AniCraft Nightly", + CFBundleName="AniCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="AniCraft", + CFBundleIconFile="anicraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + AniCraftVersion=version, + AniCraftBuildCommit=commit, + ) + return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False) + + +def write_plist(template: Path, destination: Path, version: str, commit: str) -> None: + with OwnedBuildRoot() as root: + content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit) + with root.create(destination) as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--template", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--source-commit", required=True) + args = parser.parse_args() + write_plist(args.template, args.output, args.version, args.source_commit) + + +if __name__ == "__main__": + main() diff --git a/packaging/macos/nightly_plist_tests.py b/packaging/macos/nightly_plist_tests.py new file mode 100644 index 00000000..d111ee1a --- /dev/null +++ b/packaging/macos/nightly_plist_tests.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network.""" +import importlib.util +import os +from pathlib import Path +import plistlib +import runpy +import sys +from unittest import mock +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py") +POLICY = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(POLICY) +COMMIT = "a" * 40 +VERSION = "0.3.0-nightly.20261121.12345.1.g" + COMMIT[:12] + + +class NightlyMetadata(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.template = self.root / "Info.plist.in" + self.original = (HERE / "Info.plist.in").read_bytes() + self.template.write_bytes(self.original) + self.output = self.root / "Info.plist" + + def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self): + stable = plistlib.loads(self.original) + stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}] + prepared = plistlib.dumps(stable) + self.template.write_bytes(prepared) + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + rendered = plistlib.loads(self.output.read_bytes()) + for key in POLICY.ASSOCIATIONS: + self.assertNotIn(key, rendered) + self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"]) + self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.anicraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "AniCraft") + self.assertEqual(rendered["AniCraftVersion"], VERSION) + self.assertEqual(rendered["AniCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + # The keys the stable template keeps for the platform (AniCraft declares no localizations). + for key in ("LSMinimumSystemVersion", "NSHighResolutionCapable", "NSHumanReadableCopyright", "LSApplicationCategoryType", "NSSupportsAutomaticGraphicsSwitching"): + self.assertEqual(rendered[key], stable[key]) + self.assertEqual(self.template.read_bytes(), prepared) + self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original) + + def test_bad_identity_or_template_refuses_before_creating_output(self): + for version, commit in (("0.3.0", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)): + with self.subTest(version=version, commit=commit): + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, version, commit) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_cli_writes_the_requested_identity_without_replacing_the_template(self): + helper = HERE / "nightly_plist.py" + argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT] + with mock.patch.object(sys, "argv", argv): + runpy.run_path(str(helper), run_name="__main__") + result = plistlib.loads(self.output.read_bytes()) + self.assertEqual(result["AniCraftVersion"], VERSION) + self.assertEqual(result["AniCraftBuildCommit"], COMMIT) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_template_alias_or_nonfile_refuses_before_output(self): + alias = self.root / "template-alias" + alias.symlink_to(self.template) + for template in (alias, self.root, self.root / "missing-template"): + with self.subTest(template=template), self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self): + sentinel = b"generated replacement artifact" + for disposition in ("owned", "missing", "replacement"): + with self.subTest(disposition=disposition): + if self.output.exists(): + self.output.unlink() + + def fail_sync(_descriptor): + # macOS/Linux allow unlink of an open file: exercise the real + # cleanup ownership check, not a mocked inode comparison. + if disposition != "owned": + self.output.unlink() + if disposition == "replacement": + self.output.write_bytes(sentinel) + raise OSError("generated fsync failure") + + with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + if disposition == "replacement": + self.assertEqual(self.output.read_bytes(), sentinel) + else: + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self): + sentinel = b"generated owned sentinel, not an existing app or user file" + self.output.write_bytes(sentinel) + with self.assertRaises(FileExistsError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(self.output.read_bytes(), sentinel) + self.output.unlink() + external = self.root / "sentinel" + external.write_bytes(sentinel) + self.output.symlink_to(external) + with self.assertRaisesRegex(ValueError, "symlinks or aliases"): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(external.read_bytes(), sentinel) + self.assertTrue(self.output.is_symlink()) + + + def test_template_outside_build_root_refuses_before_output(self): + with tempfile.TemporaryDirectory() as external: + template = Path(external) / "Info.plist.in" + template.write_bytes(self.original) + with self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(template.read_bytes(), self.original) + + def test_output_outside_build_root_refuses_before_write(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse(output.exists()) + + def test_parent_traversal_refuses_even_to_an_owned_sibling(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_symlinked_output_parent_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_template_read_is_bounded_before_output(self): + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_nonprivate_build_root_refuses(self): + self.root.chmod(0o755) + try: + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + finally: + self.root.chmod(0o700) + + + def test_output_keeps_normal_new_file_permissions_inside_private_root(self): + previous = os.umask(0o022) + try: + reference = self.root / "reference" + reference.write_bytes(b"generated ordinary output") + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + finally: + os.umask(previous) + self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777) + + def test_open_parent_anchor_prevents_a_later_alias_redirect(self): + parent = self.root / "stage" + parent.mkdir() + retained = self.root / "retained-stage" + destination = parent / "Info.plist" + original = POLICY.OwnedBuildRoot._parent + with tempfile.TemporaryDirectory() as external: + def swap_after_parent_open(root, path): + descriptor, name = original(root, path) + if Path(path) == destination: + parent.rename(retained) + parent.symlink_to(external, target_is_directory=True) + return descriptor, name + with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open): + POLICY.write_plist(self.template, destination, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["AniCraftVersion"], VERSION) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py new file mode 100644 index 00000000..df6ad20e --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,425 @@ +#!/usr/bin/env python3 +"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated +fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil, +lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a +real signature, notarization or Mac run.""" +import base64 +import importlib.util +import json +import os +from pathlib import Path +import plistlib +import shutil +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +import zipfile + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py") +PLIST = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(PLIST) +COMMIT = "b" * 40 +VERSION = "0.3.0-nightly.20261123.4567.1.g" + COMMIT[:12] +ASSET = f"anicraft-{VERSION}-macos-aarch64-nightly.zip" +APP = "AniCraft Nightly.app" +TEAM = "ABCDE12345" +IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567" +SECRETS = { + "APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(), + "APPLE_CERTIFICATE_PASSWORD": "generated-fixture", + "KEYCHAIN_PASSWORD": "generated-fixture", + "APPLE_ID": "fixture@example.invalid", + "APPLE_PASSWORD": "generated-fixture", + "APPLE_TEAM_ID": TEAM, +} + +# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line. +SHIM = r""" +import json, os, plistlib, sys, zipfile +from pathlib import Path +name = Path(sys.argv[0]).name +args = sys.argv[1:] +with open(os.environ["SHIM_LOG"], "a") as log: + log.write(json.dumps([name] + args) + "\n") +team = os.environ.get("SHIM_TEAM", "") +if name == "uname": + print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin")) +elif name == "lipo": + print("arm64") +elif name == "ditto": + paths = [a for a in args if not a.startswith("-")] + src, dst = paths + if "-x" in args: + with zipfile.ZipFile(src) as z: + for info in z.infolist(): + target = Path(dst) / info.filename + if info.is_dir(): + target.mkdir(parents=True, exist_ok=True) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(z.read(info)) + mode = (info.external_attr >> 16) & 0o777 + if mode: + target.chmod(mode) + else: + root = Path(src) + with zipfile.ZipFile(dst, "x") as z: + for path in sorted([root] + list(root.rglob("*"))): + arc = (Path(root.name) / path.relative_to(root)).as_posix() + if path.is_dir(): + z.writestr(zipfile.ZipInfo(arc + "/"), b"") + else: + info = zipfile.ZipInfo(arc) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, path.read_bytes()) +elif name == "plutil": + if args[0] == "-lint": + sys.exit(0) + key, fmt, source = args[1], args[2], args[-1] + data = sys.stdin.read() if source == "-" else Path(source).read_bytes() + value = json.loads(data) if source == "-" else plistlib.loads(data) + if key not in value: + sys.exit(1) + print(value[key] if fmt == "raw" else "") +elif name == "security": + verb = args[0] + if verb == "create-keychain": + Path(args[-1]).write_bytes(b"keychain") + elif verb == "find-identity": + print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team)) + print(" 1 valid identities found") + elif verb == "delete-keychain": + Path(args[-1]).unlink() +elif name == "codesign": + target = Path(args[-1]) + if "--sign" in args and target.suffix == ".app": + (target / "Contents/_CodeSignature").mkdir(exist_ok=True) + (target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed") + if "-d" in args: + sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.anicraft.nightly\n" + "CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n" + "Authority=Developer ID Application: Generated Fixture (%s)\n" + "Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team)) +elif name == "xcrun": + if args[:2] == ["notarytool", "submit"]: + print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")})) + elif args[:2] == ["stapler", "staple"]: + (Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket") + elif args[:2] == ["stapler", "validate"]: + sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1) +elif name == "spctl": + sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1]) +elif name == "cargo": + sys.exit(1) +# sleep: the retry waits pass at once. +""" + +TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep") + + +class Fixture: + def __init__(self, test): + self.directory = tempfile.TemporaryDirectory() + test.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + self.bin = self.root / "bin" + self.bin.mkdir() + shim = self.bin / "shim.py" + shim.write_text(SHIM) + for tool in TOOLS: + path = self.bin / tool + path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n") + path.chmod(0o755) + self.log = self.root / "tools.log" + self.ran = self.root / "payload-ran" + self.temp = self.root / "runner-temp" + self.temp.mkdir() + self.dist = self.root / "unsigned" + self.dist.mkdir() + self.signed = self.root / "signed" + self.signed.mkdir() + self.input = self.dist / ASSET + self.output = self.signed / ASSET + # Every script runs from a directory with modules a Python helper must not import (-I). + self.cwd = self.root / "cwd" + self.cwd.mkdir() + self.hijacked = self.root / "hijacked" + for module in ("shutil", "zipfile", "stat"): + (self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n") + + def add_entry(self, info, data=b""): + """Append one raw entry to the input archive.""" + with zipfile.ZipFile(self.input, "a") as z: + z.writestr(info, data) + + def bundle(self, version=VERSION, extra=None, gui=None): + """The archive nightly.sh makes: the real template through the real plist helper.""" + stage = self.root / "stage" + shutil.rmtree(stage, ignore_errors=True) + app = stage / APP + (app / "Contents/MacOS").mkdir(parents=True) + (app / "Contents/Resources").mkdir() + exe = app / "Contents/MacOS/AniCraft" + exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'AniCraft {version} (nightly-v1)'\n") + exe.chmod(0o755) + (app / "Contents/Resources/anicraft-nightly.icns").write_bytes(b"generated icon") + rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT) + (app / "Contents/Info.plist").write_bytes(rendered) + for relative, data in (extra or {}).items(): + (app / relative).write_bytes(data) + (app / relative).chmod(0o755) + if self.input.exists(): + self.input.unlink() + with zipfile.ZipFile(self.input, "x") as z: + for path in sorted([app] + list(app.rglob("*"))): + arc = (Path(APP) / path.relative_to(app)).as_posix() + info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else "")) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, b"" if path.is_dir() else path.read_bytes()) + return self.input + + def env(self, **changes): + env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log), + "SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS} + env.update(changes) + return {key: value for key, value in env.items() if value is not None} + + def run(self, script, *args, **env): + if self.log.exists(): + self.log.unlink() + return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + + def sign(self, **env): + return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env) + + def calls(self): + if not self.log.exists(): + return [] + return [json.loads(line) for line in self.log.read_text().splitlines()] + + +def lib(function, *args): + """Run one nightly-lib.sh function; returns (exit status, stdout).""" + script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"' + result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + return result.returncode, result.stdout.strip() + + +DETAILS = (f"Identifier=ai.storyteller.anicraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n" + f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n" + f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n") + + +class Checks(unittest.TestCase): + def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self): + self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION)) + for name in (f"anicraft-0.23.1-macos-aarch64.zip", f"anicraft-{VERSION}-macos-universal-nightly.zip", + f"anicraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET): + with self.subTest(name=name): + self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0) + + def test_signature_needs_every_part_of_the_developer_id_signature(self): + self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0) + for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"), + DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"), + "Identifier=anicraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n", + DETAILS.replace("ai.storyteller.anicraft.nightly", "ai.storyteller.anicraft"), + DETAILS.replace("ai.storyteller.anicraft.nightly", "aiXstorytellerXanicraftXnightly")): + with self.subTest(broken=broken): + self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team") + + def test_gatekeeper_must_accept_the_bundle_as_notarized(self): + self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0) + for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"): + with self.subTest(text=text): + self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0) + + def test_the_imported_identity_must_be_a_developer_id_of_the_team(self): + line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"' + self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0) + + +class Sign(unittest.TestCase): + def setUp(self): + self.f = Fixture(self) + self.f.bundle() + self.unsigned = self.f.input.read_bytes() + + def assert_refused_untouched(self, result, signed=False): + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertFalse(self.f.output.exists()) + self.assertEqual(self.f.input.read_bytes(), self.unsigned) + self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step") + names = [call[0] for call in self.f.calls()] + self.assertNotIn("cargo", names) + if not signed: + self.assertNotIn("codesign", names) + self.assertNotIn("xcrun", names) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + + def test_signs_notarizes_and_staples_without_running_the_payload(self): + result = self.f.sign() + self.assertEqual(result.returncode, 0, result.stdout) + self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets") + calls = self.f.calls() + names = [call[0] for call in calls] + self.assertNotIn("cargo", names) + self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step") + self.assertEqual(self.f.input.read_bytes(), self.unsigned) + signs = [call for call in calls if call[0] == "codesign" and "--sign" in call] + self.assertEqual([Path(call[-1]).name for call in signs], ["AniCraft", APP], "inside-out: executable, then bundle") + for call in signs: + for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY): + self.assertIn(flag, call) + order = [" ".join(call[:3]) for call in calls] + submit = order.index("xcrun notarytool submit") + staple = order.index("xcrun stapler staple") + self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit) + self.assertLess(submit, staple) + final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1] + self.assertLess(staple, final, "the final archive carries the stapled ticket") + self.assertIn("--noextattr", calls[final]) + self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls]) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + with zipfile.ZipFile(self.f.output) as z: + names = set(z.namelist()) + self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle") + self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names) + self.assertTrue(all(name.startswith(APP) for name in names)) + mode = z.getinfo(f"{APP}/Contents/MacOS/AniCraft").external_attr >> 16 + self.assertTrue(mode & stat.S_IXUSR) + + def test_every_signing_and_notarization_secret_is_required(self): + for name in SECRETS: + with self.subTest(missing=name): + self.assert_refused_untouched(self.f.sign(**{name: None})) + self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete") + self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999")) + self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team")) + + def test_refuses_another_team_s_identity(self): + self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999")) + + def test_never_replaces_an_output_or_renames_the_asset(self): + self.f.output.write_bytes(b"generated existing artifact") + result = self.f.sign() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact") + self.f.output.unlink() + renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip") + self.assertNotEqual(renamed.returncode, 0) + relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output) + self.assertNotEqual(relative.returncode, 0) + self.assertEqual(list(self.f.signed.iterdir()), []) + + def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self): + cases = { + "cli": dict(extra={"Contents/MacOS/anicraft-cli": b"generated cli"}), + "version": dict(version=VERSION.replace("4567", "4568")), + } + for label, change in cases.items(): + with self.subTest(label=label): + self.f.bundle(**change) + self.unsigned = self.f.input.read_bytes() + self.assert_refused_untouched(self.f.sign()) + + def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self): + link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link") + link.external_attr = (stat.S_IFLNK | 0o777) << 16 + fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo") + fifo.external_attr = (stat.S_IFIFO | 0o644) << 16 + for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")), + ("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))): + with self.subTest(label=label): + self.f.bundle() + self.f.add_entry(info, b"/etc/passwd") + self.unsigned = self.f.input.read_bytes() + result = self.f.sign() + self.assert_refused_untouched(result) + self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking") + + def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self): + result = self.f.sign(SHIM_NOTARY="Invalid") + self.assert_refused_untouched(result, signed=True) + self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()]) + self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()]) + + +class Verify(unittest.TestCase): + def setUp(self): + self.f = Fixture(self) + + def verify(self, *args, **env): + return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env) + + def test_asks_the_gui_its_version_with_an_empty_environment(self): + self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'AniCraft {VERSION} (nightly-v1)'\n") + result = self.verify("--expect", "unsigned", INHERITED="generated") + self.assertEqual(result.returncode, 0, result.stdout) + self.f.bundle(gui="#!/bin/sh\necho 'AniCraft 0.23.1 (stable)'\n") + self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0) + + def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self): + answer = f"echo 'AniCraft {VERSION} (nightly-v1)'" + # The shared producer smoke's exact form, with a fresh profile directory. + exact = ('#!/bin/sh\nif [ "$1" = --launch-profile ]; then\n' + ' [ "$#" = 5 ] && [ "$2" = nightly-v1 ] && [ "$3" = --profile-root ] && [ -d "$4" ] && [ "$5" = --version ] || exit 7\n' + f'fi\n{answer}\n') + self.f.bundle(gui=exact) + result = self.verify("--expect", "unsigned") + self.assertEqual(result.returncode, 0, result.stdout) + hangs = f'#!/bin/sh\n[ "$1" != --launch-profile ] || exec /bin/sleep 60\n{answer}\n' + self.f.bundle(gui=hangs) + started = time.monotonic() + result = self.verify("--expect", "unsigned") + self.assertNotEqual(result.returncode, 0) + self.assertIn("within 15 s", result.stdout) + self.assertLess(time.monotonic() - started, 45, "a hanging query is ended, not waited for") + noisy = f'#!/bin/sh\n[ "$1" != --launch-profile ] || echo refusal >&2\n{answer}\n' + self.f.bundle(gui=noisy) + result = self.verify("--expect", "unsigned") + self.assertNotEqual(result.returncode, 0) + self.assertIn("standard error", result.stdout) + + def test_a_signed_check_needs_the_signature_ticket_and_team(self): + self.f.bundle() + self.assertNotEqual(self.verify("--expect", "signed").returncode, 0, "no team to check against") + self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0, "no stapled ticket") + self.f.bundle(extra={"Contents/CodeResources": b"ticket"}) + self.assertEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0) + self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM, SHIM_TEAM="ZZZZZ99999").returncode, 0) + + def test_refuses_to_run_the_payload_beside_signing_material(self): + self.f.bundle() + for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN"): + with self.subTest(name=name): + result = self.f.run("nightly-verify.sh", "--input", self.f.input, "--expect", "unsigned", + **{**{key: None for key in SECRETS}, name: "generated"}) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.f.ran.exists()) + self.assertEqual(self.f.calls(), []) + + +class Build(unittest.TestCase): + def test_compilation_refuses_signing_material_before_building(self): + f = Fixture(self) + for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"): + with self.subTest(name=name): + result = f.run("nightly.sh", "--arch", "aarch64", **{**{key: None for key in SECRETS}, name: "generated"}, + ANICRAFT_BUILD_CHANNEL="nightly-v1", ANICRAFT_VERSION=VERSION) + self.assertNotEqual(result.returncode, 0) + self.assertIn(name, result.stdout) + self.assertNotIn("cargo", [call[0] for call in f.calls()]) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100644 index 00000000..cf8dad4c --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +import runpy +import sys +from unittest import mock +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + self.required = { + # The standard Nightly layout: `anicraft` is the launcher and `anicraft-bin` the GUI. + "anicraft", + "anicraft-bin", + "anicraft-nightly.png", + "README.md", + "LICENSE-MIT", + "LICENSE-APACHE", + "NOTICE", + "ATTRIBUTION.md", + } + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + (self.stage / "anicraft").chmod(0o755) + (self.stage / "anicraft-bin").chmod(0o755) + + def test_flat_regular_ustar_with_all_notices(self): + (self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8") + ARCHIVE.linux_archive(self.stage, self.output) + with tarfile.open(self.output) as archive: + self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"}) + self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive)) + self.assertEqual(archive.extractfile("anicraft").read(), (self.stage / "anicraft").read_bytes()) + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + # The old launcher name is not the layout either: `anicraft` is the launcher now. + for name in ["anicraft-cli", "portable.txt", "anicraft.desktop", "anicraft-launch", "nightly-launch.sh", "anicraft-nightly"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "anicraft-nightly.png" + icon.unlink() + icon.symlink_to(self.stage / "README.md") + with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_directory_refuses_before_output(self): + icon = self.stage / "anicraft-nightly.png" + icon.unlink() + icon.mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_long_notice_refuses_before_output(self): + (self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "short regular"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_case_colliding_notices_refuse_before_output(self): + for name in ["OFL-Font.txt", "OFL-font.txt"]: + (self.stage / name).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "case-colliding"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_cli_dispatches_only_the_supported_archive_kind(self): + helper = HERE / "nightly-archive.py" + with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]): + runpy.run_path(str(helper), run_name="__main__") + with tarfile.open(self.output) as archive: + self.assertEqual({member.name for member in archive}, self.required) + refused = self.root / "refused.tar.gz" + for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]): + with self.subTest(args=args), mock.patch.object(sys, "argv", args): + with self.assertRaises(SystemExit): + runpy.run_path(str(helper), run_name="__main__") + self.assertFalse(refused.exists()) + + def test_existing_archive_is_unchanged(self): + self.output.write_bytes(b"owned earlier artifact") + with self.assertRaises(FileExistsError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertEqual(self.output.read_bytes(), b"owned earlier artifact") + + + def test_archive_output_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse(output.exists()) + + def test_archive_stage_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + stage = Path(external) + for name in self.required: + (stage / name).write_bytes(b"generated external fixture") + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(stage, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_stage_alias_refuses(self): + alias = self.root / "stage-alias" + alias.symlink_to(self.stage, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(alias, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_output_parent_alias_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "output-alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz") + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_archive_parent_traversal_refuses(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_nonflat_member_name_refuses(self): + stage_root = os.path.realpath(self.stage) + with open(self.stage / "README.md", "rb") as incoming: + for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."): + with self.subTest(name=bad), self.assertRaises(ValueError): + ARCHIVE.member_info(stage_root, bad, incoming) + + def test_member_header_matches_what_gettarinfo_records(self): + stage_root = os.path.realpath(self.stage) + for name in sorted(self.required): + with self.subTest(name=name), open(self.stage / name, "rb") as incoming: + ours = ARCHIVE.member_info(stage_root, name, incoming) + with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference: + theirs = reference.gettarinfo(fileobj=incoming, arcname=name) + self.assertEqual(ours.get_info(), theirs.get_info()) + + def test_member_read_budget_refuses_before_output(self): + (self.stage / "OFL-Large.txt").write_bytes(b"x" * 65) + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + + def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self): + growing = self.stage / "OFL-Growing.txt" + growing.write_bytes(b"x" * 32) + original = ARCHIVE.member_info + + def grow_before_stat(stage_root, name, incoming): + if name == growing.name: + growing.write_bytes(b"x" * 65) + return original(stage_root, name, incoming) + + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \ + mock.patch.object(ARCHIVE, "member_info", grow_before_stat): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + +class ExclusiveOutput(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.source = self.root / "input archive" + self.output = self.root / "final archive" + self.source.write_bytes(b"generated archive fixture" * 1024) + + def publish(self): + return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15) + + def test_success_copies_exact_bytes(self): + result = self.publish() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_bytes(), self.source.read_bytes()) + + def test_existing_output_is_never_replaced(self): + self.output.write_bytes(b"existing artifact") + self.assertNotEqual(self.publish().returncode, 0) + self.assertEqual(self.output.read_bytes(), b"existing artifact") + + def test_missing_source_does_not_leave_a_fake_empty_artifact(self): + self.source.unlink() + self.assertNotEqual(self.publish().returncode, 0) + self.assertFalse(self.output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100644 index 00000000..694719f4 --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Flat Linux archive policy, invoked from its private owned build cwd. + +The stage and archive must both remain under that independently chosen root. +No native build, platform signing, or malicious-same-UID sandbox is implied. +""" +import grp +import gzip +import os +import pathlib +import pwd +import re +import stat +import sys +import tarfile + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from nightly_paths import OwnedBuildRoot + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} +MAX_MEMBER_BYTES = 512 * 1024 * 1024 +MAX_TOTAL_BYTES = 1024 * 1024 * 1024 +MAX_MEMBERS = 128 + + +def notice(name): + return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None + + +def checked_entries(root, stage): + entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name) + folded = set() + total = 0 + for entry in entries: + name = entry.name + if name not in {"anicraft", "anicraft-bin", "anicraft-nightly.png"} and not notice(name): + raise ValueError(f"unexpected nightly member: {name}") + if len(name.encode("utf-8")) > 100: + raise ValueError(f"nightly member must be a short regular file: {name}") + with root.reader(entry, MAX_MEMBER_BYTES) as stream: + total += os.fstat(stream.fileno()).st_size + if total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage exceeds its read bound") + if name.casefold() in folded: + raise ValueError(f"case-colliding nightly member: {name}") + folded.add(name.casefold()) + required = { + "anicraft", + "anicraft-bin", + "anicraft-nightly.png", + "README.md", + "LICENSE-MIT", + "LICENSE-APACHE", + "NOTICE", + "ATTRIBUTION.md", + } + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + # The header keeps the validated stage name, not the resolved one: a stage symlink must + # never rename a member or leave a required name out of the archive. + info = tarfile.TarInfo(name) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 00000000..7f0c072f --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,104 @@ +# shellcheck shell=bash +# Shared setup for AniCraft's own native nightly archives; stable packaging does not source this +# file. PhotoCraft's `packaging/nightly-common.sh`, with this app's names and its GUI build. + +nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +nightly_init() { + local os="$1" arch="$2" target="$3" date_digits + [[ "${ANICRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'ANICRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${ANICRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required' + [[ "${ANICRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${ANICRAFT_VERSION##*.g}" == "${ANICRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${ANICRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${ANICRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${ANICRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch' + [[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required' + [[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required' + [[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal' + ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$ANICRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # env.sh keeps the established notice copier and reads ANICRAFT_VERSION into VERSION; the values + # required above prohibit its stable fallbacks. build.rs (src/build_channel.rs) compiles the + # channel and the prepared feed identity in, so the binary prints that exact version and never + # Cargo's 0.3.0. + export ANICRAFT_BUILD_CHANNEL ANICRAFT_VERSION ANICRAFT_BUILD_SHA ANICRAFT_BUILD_DATE + # shellcheck source=env.sh + . "$ROOT/packaging/env.sh" + [[ "$VERSION" == "$ANICRAFT_VERSION" ]] || nightly_die 'the prepared version and env.sh disagree' + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +# Compile only: macOS runs the version query after signing (packaging/macos/nightly-verify.sh). +# The GUI alone, with the default features of a stable build (sound output and the GPU stage): the +# nightly archive has no anicraft-cli. +nightly_compile_gui() { + (cd "$ROOT" && cargo build --release --locked -p anicraft --target "$NIGHTLY_RUST_TARGET") + # Not `$(... && printf)`: its status 1 on a non-Windows target would end the build under set -e. + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/anicraft" + if [[ "$NIGHTLY_RUST_TARGET" == *windows* ]]; then + NIGHTLY_GUI+=".exe" + fi + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$ANICRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + # The line the flavor prints: the contract's ` (nightly-v1)` (`src/main.rs`, + # `src/build_flavor.rs`). The Launcher and the shared producer parse this same line. + [[ "$actual" == "AniCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$ANICRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query' +} + +# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). +nightly_refuse_signing_env() { + local name + # The signing names release.yml passes, for every platform, and import-cert.sh's outputs. + for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \ + MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \ + AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do + [[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step" + done +} + +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" +} + +nightly_publish_archive() { + # Exclusive creation: never replace an existing artifact, even if another writer raced the preflight. + python3 -I - "$1" "$2" <<'PY' +import os, shutil, sys +source, destination = sys.argv[1:] +created = False +try: + # Open the input first: a missing source must not leave an empty final artifact. + with open(source, 'rb') as incoming: + with open(destination, 'xb') as output: + created = True + shutil.copyfileobj(incoming, output, length=1024 * 1024) + output.flush() + os.fsync(output.fileno()) +except BaseException: + if created: + os.unlink(destination) + raise +PY + printf 'Nightly artifact: %s\n' "$2" +} diff --git a/packaging/nightly-launch-tests.py b/packaging/nightly-launch-tests.py new file mode 100644 index 00000000..2afd8910 --- /dev/null +++ b/packaging/nightly-launch-tests.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +"""Synthetic tests for the one Nightly launcher every Linux nightly format installs. + +No app build: a recorder stands in for the real program, so each layout is exercised exactly as +packaging/linux/{package.sh,flatpak-bundle.sh,nightly-arch-tar.sh,nightly.sh} installs it. +""" +import os +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +LINUX = HERE / "linux" +LAUNCHER = LINUX / "nightly-launch.sh" +RECORDER = '#!/bin/sh\nfor arg in "$@"; do printf \'%s\\n\' "$arg"; done\n' + + +class Layout(unittest.TestCase): + """Each format's install layout, run through the shared launcher.""" + + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + self.home = self.root / "home with space" + self.home.mkdir() + + # -- building the five layouts ------------------------------------------------------------ + def script(self, path, text=RECORDER): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + path.chmod(0o755) + return path + + def launcher(self, path): + path.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(LAUNCHER, path) + path.chmod(0o755) + return path + + def layouts(self): + """The bundle layouts, each run in place. The deb/rpm is not among them: a test host cannot + install into /usr/bin, so that one arm is pinned by contract and by failing closed (below).""" + made = {} + base = self.root / "layouts" + # AppImage: AppRun at the AppDir root runs usr/bin/anicraft + appdir = base / "AniCraft.AppDir" + made["appimage"] = (self.launcher(appdir / "AppRun"), self.script(appdir / "usr/bin/anicraft")) + # Arch handoff: bin/anicraft runs bin/.anicraft-nightly/anicraft + arch = base / "arch" + made["arch"] = (self.launcher(arch / "bin/anicraft"), self.script(arch / "bin/.anicraft-nightly/anicraft")) + # Flatpak: /app/bin/anicraft-nightly runs /app/bin/anicraft-bin + flatpak = base / "app" + made["flatpak"] = (self.launcher(flatpak / "bin/anicraft-nightly"), self.script(flatpak / "bin/anicraft-bin")) + # nightly tar, the standard layout: the launcher `anicraft` runs `anicraft-bin` beside it + tar = base / "tar" + made["tar"] = (self.launcher(tar / "anicraft"), self.script(tar / "anicraft-bin")) + return made + + def run_launcher(self, command, *arguments, env=None, cwd=None): + environment = {"PATH": "/usr/bin:/bin", "HOME": str(self.home)} + environment.update(env or {}) + return subprocess.run( + [str(command), *arguments], capture_output=True, text=True, timeout=30, + env=None if environment is None else {k: v for k, v in environment.items() if v is not None}, + cwd=str(cwd or self.root), + ) + + def profile(self, data_home=None): + return str(Path(data_home or self.home / ".local/share") / "anicraft-nightly/profile") + + def protocol(self, *files, data_home=None): + return ["--launch-profile", "nightly-v1", "--profile-root", self.profile(data_home), "--", *files] + + def arguments(self, result): + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.splitlines() + + # -- the contract every format shares ----------------------------------------------------- + def test_every_format_starts_the_real_program_in_the_nightlys_own_profile(self): + files = ["scene with spaces.anicraft", "--other-name.anicraft"] + for name, (command, _) in self.layouts().items(): + with self.subTest(layout=name): + self.assertEqual(self.arguments(self.run_launcher(command, *files)), self.protocol(*files)) + + def test_the_system_install_is_one_absolute_path_behind_the_bin_check(self): + # A deb/rpm install is the only layout with the program in a lib folder, and there it is one + # fixed absolute path, reached only when the launcher really is in /usr/bin. No candidate is + # ever computed from `..`, so no bundle can plant one beside itself. + launcher = LAUNCHER.read_text() + self.assertIn('[ "$here" = /usr/bin ]', launcher) + self.assertIn('/usr/lib/anicraft-nightly/anicraft ', launcher) + self.assertNotIn("..", launcher) + + def test_outside_usr_bin_a_co_installed_stable_program_and_a_planted_lib_are_both_refused(self): + # The deb/rpm launcher run from anywhere but /usr/bin: a stable `anicraft` beside it and a + # program planted in a sibling lib folder are not ours, so it refuses instead of running one. + prefix = self.root / "prefix" + command = self.launcher(prefix / "bin/anicraft-nightly") + self.script(prefix / "bin/anicraft", "#!/bin/sh\necho THE-STABLE-PROGRAM\n") + self.script(prefix / "lib/anicraft-nightly/anicraft", "#!/bin/sh\necho PLANTED-BY-ANOTHER-USER\n") + result = self.run_launcher(command, "walk.anicraft") + self.assertEqual(result.returncode, 2) + self.assertIn("not where this launcher was installed", result.stderr) + self.assertEqual(result.stdout, "") + + def test_a_planted_program_beside_a_bundle_is_never_run(self): + # An AppImage mount and an extracted tar sit under a folder another local user may own, so a + # `../lib/anicraft-nightly/anicraft` there must never stand in for the bundle's own program. + layouts = self.layouts() + for name in ("appimage", "tar", "arch", "flatpak"): + command, _ = layouts[name] + for planted in (command.parent.parent / "lib/anicraft-nightly/anicraft", + command.parent.parent / "lib/anicraft-nightly/anicraft-bin"): + self.script(planted, "#!/bin/sh\necho PLANTED-BY-ANOTHER-USER\n") + with self.subTest(layout=name): + result = self.run_launcher(command, "walk.anicraft") + self.assertEqual(self.arguments(result), self.protocol("walk.anicraft")) + self.assertNotIn("PLANTED", result.stdout) + + def test_a_launcher_command_line_is_passed_through_unwrapped(self): + # The Launcher starts a package this way already: wrapping it again would hide its root. + supplied = self.protocol("scene.anicraft", data_home=self.root / "launcher-data") + for name, (command, _) in self.layouts().items(): + with self.subTest(layout=name): + self.assertEqual(self.arguments(self.run_launcher(command, *supplied)), supplied) + + def test_a_supplied_delimiter_is_not_doubled(self): + for name, (command, _) in self.layouts().items(): + with self.subTest(layout=name): + self.assertEqual(self.arguments(self.run_launcher(command, "--", "scene.anicraft")), self.protocol("scene.anicraft")) + + def test_the_profile_follows_xdg_data_home(self): + data_home = self.root / "xdg with space" + for name, (command, _) in self.layouts().items(): + with self.subTest(layout=name): + result = self.run_launcher(command, "walk.anicraft", env={"XDG_DATA_HOME": str(data_home)}) + self.assertEqual(self.arguments(result), self.protocol("walk.anicraft", data_home=data_home)) + + def test_a_relative_xdg_data_home_is_ignored(self): + for name, (command, _) in self.layouts().items(): + with self.subTest(layout=name): + result = self.run_launcher(command, "walk.anicraft", env={"XDG_DATA_HOME": "relative/share"}) + self.assertEqual(self.arguments(result), self.protocol("walk.anicraft")) + + def test_a_version_query_answers_the_launchers_own_form(self): + for name, (command, _) in self.layouts().items(): + for flag in ("--version", "-V"): + with self.subTest(layout=name, flag=flag): + expected = ["--launch-profile", "nightly-v1", "--profile-root", self.profile(), flag] + self.assertEqual(self.arguments(self.run_launcher(command, flag)), expected) + + def test_a_file_named_like_a_flag_is_still_a_file(self): + for name, (command, _) in self.layouts().items(): + with self.subTest(layout=name): + files = ["--version", "--launch-profile", "nightly-v1"] + self.assertEqual(self.arguments(self.run_launcher(command, *files)), self.protocol(*files)) + + def test_no_arguments_is_a_bare_delimiter(self): + for name, (command, _) in self.layouts().items(): + with self.subTest(layout=name): + self.assertEqual(self.arguments(self.run_launcher(command)), self.protocol()) + + def test_the_launcher_works_when_it_is_found_on_path(self): + self.layouts() + arch = self.root / "layouts/arch/bin" + # The Arch packager installs the handoff's bin/anicraft as anicraft-nightly (or keeps it). + (arch / "anicraft").rename(arch / "anicraft-nightly") + result = subprocess.run( + ["sh", "-c", 'exec anicraft-nightly "$1"', "sh", "walk.anicraft"], + capture_output=True, text=True, timeout=30, + env={"PATH": f"{arch}:/usr/bin:/bin", "HOME": str(self.home)}, + ) + self.assertEqual(self.arguments(result), self.protocol("walk.anicraft")) + + def test_a_missing_or_symlinked_program_is_refused_without_recursing(self): + layouts = self.layouts() + for name, (command, program) in layouts.items(): + with self.subTest(layout=name, case="missing"): + moved = program.with_name(program.name + ".moved") + program.rename(moved) + try: + result = self.run_launcher(command, "walk.anicraft") + self.assertEqual(result.returncode, 2) + self.assertIn("not where this launcher was installed", result.stderr) + self.assertEqual(result.stdout, "") + finally: + moved.rename(program) + with self.subTest(layout=name, case="symlink"): + program.unlink() + program.symlink_to(self.root / "elsewhere") + try: + result = self.run_launcher(command, "walk.anicraft") + self.assertEqual(result.returncode, 2) + self.assertIn("not where this launcher was installed", result.stderr) + finally: + program.unlink() + program.write_text(RECORDER) + program.chmod(0o755) + + def test_home_is_required_before_anything_runs(self): + for name, (command, _) in self.layouts().items(): + with self.subTest(layout=name): + result = self.run_launcher(command, "walk.anicraft", env={"HOME": None}) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout, "") + self.assertIn("HOME", result.stderr) + + def test_the_profile_never_sits_in_or_above_stables_folders(self): + profile = Path(self.profile()) + parts = profile.parts + self.assertEqual(parts[-2:], ("anicraft-nightly", "profile")) + for stable in (".config", ".cache", ".local/state"): + self.assertNotIn(str(self.home / stable / "anicraft"), str(profile)) + + +class InstallContract(unittest.TestCase): + """Every Linux format must install the one launcher, not its own copy of the protocol.""" + + def read(self, name): + return (LINUX / name).read_text() + + def test_every_format_installs_the_shared_launcher(self): + package = self.read("package.sh") + # deb/rpm GUI command and the AppImage AppRun + self.assertIn('install -Dm755 "$HERE/nightly-launch.sh" "$NFPM_STAGE/usr/bin/$NFPM_BIN"', package) + self.assertIn('install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/AppRun"', package) + self.assertNotIn("<<'WRAPPER'", package) + self.assertIn('install -Dm755 "$HERE/nightly-launch.sh" "$WORK/stage/bin/anicraft-nightly"', self.read("flatpak-bundle.sh")) + self.assertIn('cp "$here/nightly-launch.sh" "$stage/bin/anicraft"', self.read("nightly-arch-tar.sh")) + self.assertIn('install -m755 "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/anicraft"', self.read("nightly.sh")) + self.assertFalse((LINUX / "nightly-arch-launch.sh").exists(), "the Arch launcher is the shared one now") + + def test_no_format_still_moves_the_settings_folder_through_the_environment(self): + for name in ("flatpak-bundle.sh", "nightly-arch-tar.sh", "nightly.sh", "nightly-launch.sh"): + with self.subTest(file=name): + self.assertNotIn("XDG_CONFIG_HOME", self.read(name)) + # package.sh keeps it only for the headless CLI, which has no profile protocol (the GUI + # command and AppRun are the launcher). + package = self.read("package.sh") + self.assertEqual(package.count("XDG_CONFIG_HOME"), 1) + self.assertGreater(package.index("XDG_CONFIG_HOME"), package.index("<<'CLI_WRAPPER'")) + + def test_the_nightly_launcher_passes_the_flavors_protocol(self): + launcher = LAUNCHER.read_text() + self.assertIn('exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@"', launcher) + self.assertIn('"$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$1"', launcher) + + def test_the_formats_that_ship_a_desktop_entry_point_it_at_the_launcher(self): + package = self.read("package.sh") + self.assertIn("Exec=$NFPM_BIN\\1", package) + self.assertRegex(package, r"StartupWMClass=ai\.storyteller\.anicraft\.nightly-v1") + flatpak = self.read("flatpak-bundle.sh") + self.assertIn("Exec=anicraft-nightly", flatpak) + self.assertIn("s|^command: anicraft$|command: anicraft-nightly|", flatpak) + arch = self.read("nightly-arch-tar.sh") + self.assertIn("Exec=anicraft-nightly", arch) + self.assertIn("StartupWMClass=$nightly_id", arch) + + def test_the_tar_is_the_standard_launcher_and_bin_layout(self): + # `` is the launcher and `-bin` the GUI it starts, as in every app in the batch, + # so an unpacked tar starts in its own profile and the shared smoke can query the entry. + nightly = self.read("nightly.sh") + self.assertIn('install -m755 "$NIGHTLY_GUI" "$STAGE/anicraft-bin"', nightly) + self.assertIn('install -m755 "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/anicraft"', nightly) + self.assertIn('[[ "$("$STAGE/anicraft" --version)" == "AniCraft $VERSION (nightly-v1)"', nightly) + archive = (HERE / "nightly-archive.py").read_text() + self.assertIn('"anicraft-bin"', archive) + self.assertNotIn('"anicraft-nightly",\n', archive) + + def test_the_flatpak_runs_its_own_gui_and_never_asks_for_a_mime_database_it_drops(self): + flatpak = self.read("flatpak-bundle.sh") + # The sandbox's GUI is `anicraft-bin`, which is what the launcher looks for there. + self.assertIn("/app/bin/anicraft-bin", flatpak) + # Nightly deletes share/mime, so the default test must not list it (ls exits 2 under set -e). + self.assertIn("SHARE_PATHS='/app/share/applications /app/share/metainfo /app/share/icons/hicolor/*/apps'", flatpak) + self.assertIn("if [[ \"$FLATPAK_ID\" = \"$APP_ID\" ]]; then", flatpak) + + def test_nightly_metadata_declares_no_file_associations(self): + for name in ("package.sh", "flatpak-bundle.sh", "nightly-arch-tar.sh"): + with self.subTest(file=name): + self.assertIn("//d", self.read(name)) + + def test_the_nightly_build_uses_the_apps_default_features(self): + common = (HERE / "nightly-common.sh").read_text() + # `-p anicraft` with its default features is the GUI a stable build ships (sound output and + # the GPU stage); a --features/--no-default-features here would ship a different app. + self.assertIn("cargo build --release --locked -p anicraft --target", common) + self.assertNotIn("--no-default-features", common) + self.assertNotIn("--features", common) + + def test_the_prepared_identity_reaches_build_rs(self): + common = (HERE / "nightly-common.sh").read_text() + self.assertIn("export ANICRAFT_BUILD_CHANNEL ANICRAFT_VERSION ANICRAFT_BUILD_SHA ANICRAFT_BUILD_DATE", common) + self.assertNotIn("OVERRIDE_VERSION", common) + + def test_every_platform_checks_the_line_the_flavor_prints(self): + # The contract's line is ` (nightly-v1)`: the display name is not in it. + expected = 'AniCraft $VERSION (nightly-v1)' + self.assertIn(f'"{expected}"', (HERE / "nightly-common.sh").read_text()) + self.assertIn(f'"{expected}"', (HERE / "linux/nightly.sh").read_text()) + self.assertIn('"AniCraft $VERSION (nightly-v1)"', (HERE / "macos/nightly-verify.sh").read_text()) + self.assertIn("AniCraft $ExpectedVersion (nightly-v1)", (HERE / "windows/nightly.ps1").read_text()) + workflow = (HERE.parent / ".github/workflows/nightly-builds.yml").read_text() + self.assertIn('"AniCraft $ANICRAFT_VERSION (nightly-v1)"', workflow) + self.assertIn('"AniCraft $env:ANICRAFT_VERSION (nightly-v1)"', workflow) + for name in ("nightly-common.sh", "macos/nightly-verify.sh", "windows/nightly.ps1"): + self.assertNotIn("AniCraft Nightly $", (HERE / name).read_text(), name) + + def test_the_expected_line_is_the_one_the_flavor_composes(self): + root = HERE.parent + self.assertIn('BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)")', (root / "src/build_flavor.rs").read_text()) + # Both queries use the same form: the prepared version, never the display name. + self.assertIn('writeln!(std::io::stdout(), "AniCraft {}", version_line())', (root / "src/main.rs").read_text()) + self.assertIn('println!("AniCraft {}", version_line())', (root / "src/main.rs").read_text()) + # The window title and the Windows ProductName keep the channel's display name. + self.assertIn('LaunchIdentity::NightlyV1 => tr_noop!("AniCraft Nightly")', (root / "src/platform.rs").read_text()) + self.assertIn("if ($ProductName -ne 'AniCraft Nightly'", (HERE / "windows/nightly.ps1").read_text()) + + def test_the_window_class_is_the_desktop_entry_class(self): + platform = (HERE.parent / "src/platform.rs").read_text() + match = re.search(r'pub const APP_ID_NIGHTLY: &str = "([^"]+)";', platform) + self.assertIsNotNone(match) + nightly_id = match[1] + self.assertEqual(nightly_id, "ai.storyteller.anicraft.nightly-v1") + for name in ("package.sh", "flatpak-bundle.sh"): + with self.subTest(file=name): + self.assertIn(nightly_id, self.read(name)) + # the Arch handoff builds the same id from the stable one it rewrites. + arch = self.read("nightly-arch-tar.sh") + self.assertIn("app_id=ai.storyteller.anicraft", arch) + self.assertIn("nightly_id=$app_id.nightly-v1", arch) + self.assertIn("StartupWMClass=$nightly_id", arch) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 00000000..f424b591 --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,413 @@ +#!/usr/bin/env python3 +"""Nightly workflow and signing-policy contract regression tests.""" +import copy +import json +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] +INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" + +NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +# Each platform's one trust field in policy v3, and the public stable identity it must name. +NIGHTLY_TRUST = { + "windows-x86_64": ("publisher_subject", + "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"), + "linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"), + "macos-aarch64": ("apple_team_id", "DJ6XS33FX8"), +} + +# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot. +# Update by PR, in the caller and the policy, when the team changes. +RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"] + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract. + + This is a deliberately narrow source guard, not a general YAML parser; actionlint + still checks all other syntax. Expressions, aliases and alternate block shapes + refuse rather than delegating queue-value validation to the old linter. + """ + lines = source.splitlines() + roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(roots) != 1 or lines[roots[0]] != "concurrency:": + raise ValueError("one plain root concurrency block is required") + values = {} + for line in lines[roots[0] + 1:]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line[0].isspace(): + break + row = re.fullmatch(r" (group|cancel-in-progress|queue): ([^#]+?)(?: +#.*)?", line) + if row is None or row[1] in values: + raise ValueError("malformed or duplicate nightly concurrency entry") + values[row[1]] = row[2].rstrip() + if values != {"group": "anicraft-nightly-release", "cancel-in-progress": "false", "queue": "max"}: + raise ValueError("nightly serialization must use its stable group, max queue and no cancellation") + + +def literal_off(condition): + expression = " ".join(condition.split()) + if expression.startswith("${{") and expression.endswith("}}"): + expression = expression[3:-2].strip() + if expression == "false": + return True + if not expression.startswith("false && "): + return False + # A top-level OR could override the leading false; parentheses must balance. + expression = re.sub(r"'(?:''|[^'])*'", "''", expression) + depth = 0 + for token in re.findall(r"\(|\)|\|\|", expression): + if token == "(": + depth += 1 + elif token == ")": + depth -= 1 + if depth < 0: + return False + elif depth == 0: + return False + return depth == 0 + + +def job_conditions(jobs): + """Each job-level `if:` as (block indicator or None, the whole expression YAML would read). + + A narrow source reader, not a YAML parser: every following line indented deeper than the + job keys continues the value, for block scalars and plain multi-line scalars alike, so a + continuation line can never hide from the guard checks. + """ + lines = jobs.splitlines() + found = [] + for index, line in enumerate(lines): + head = re.fullmatch(r" if:(?: (.*))?", line) + if head is None: + continue + value = (head[1] or "").strip() + continuation = [] + for follow in lines[index + 1:]: + if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4: + break + continuation.append(follow.strip()) + indicator = value if re.fullmatch(r"[>|][+-]?", value) else None + parts = continuation if indicator else [value] + continuation + found.append((indicator, " ".join(part for part in parts if part))) + return found + + +def producer_platforms(source): + """Read the one producer job's literal platform list; a narrow source guard, not YAML. + + One producer run builds every listed platform for one all-or-nothing release, so the + list must be a compact JSON list of distinct known platforms that keeps Windows. + """ + rows = re.findall(r"(?m)^ platforms: (.*)$", source) + if len(rows) != 1: + raise ValueError("exactly one producer platform list is required") + literal = re.fullmatch(r"'(\[[^']*\])'", rows[0]) + if literal is None: + raise ValueError("the platform list must be one single-quoted literal") + platforms = json.loads(literal[1]) + if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]: + raise ValueError("the platform list must be compact JSON") + if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS): + raise ValueError("platforms must be distinct known nightly targets") + if "windows-x86_64" not in platforms: + raise ValueError("the Windows row stays in the producer") + return platforms + + +def reviewed_manual_actors(caller_source, policy): + """The one reviewed manual-actor list, identical in the producer caller and the policy.""" + rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source) + if len(rows) != 1: + raise ValueError("exactly one literal manual-actors list is required") + caller = json.loads(rows[0]) + if caller != policy["manual_actors"]: + raise ValueError("caller and policy must grant the same actors in the same order") + if caller != RELEASE_MANAGERS: + raise ValueError("manual actors must be exactly the reviewed release managers") + if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller): + raise ValueError("manual actors must be distinct and sorted case-insensitively") + if set(caller) & {login for login in policy["automatic_signer_actors"]}: + raise ValueError("manual and automatic actors overlap") + return caller + + +def caller_pin(name): + return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0] + + +class TrustedSourcePreparation(unittest.TestCase): + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job], + "a platform is a list entry, not a separately activatable job") + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'" + self.assertIn(current, source) + for new in ("platforms: '[\"linux-x86_64\"]'", + "platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-arm64\"]'", + "platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'", + "platforms: [\"windows-x86_64\",\"linux-x86_64\"]", + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + "platforms: '{\"windows-x86_64\":1}'", + current + "\n " + current): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): + for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")): + source = (ROOT / ".github/workflows" / workflow).read_text() + expected = NightlyEnabledCallers.GUARDS[name] + guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0] + for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"): + jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1] + with self.subTest(workflow=name, replacement=replacement[-30:]): + (indicator, expression), = job_conditions(jobs) + self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) + + def test_dormancy_guard_rejects_activation_and_top_level_or(self): + for condition in ("true", "vars.ENABLE_NIGHTLY", "false || true", "false && true || true", + "false && (true || true", "false && true) || true"): + with self.subTest(condition=condition): + self.assertFalse(literal_off(condition)) + self.assertTrue(literal_off("${{ false }}")) + self.assertTrue(literal_off("false && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')")) + + def test_no_nightly_schedule_is_registered(self): + for name, event in (("nightly.yml", "workflow_dispatch"), + ("nightly-sign.yml", "workflow_dispatch")): + source = (ROOT / ".github/workflows" / name).read_text() + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + triggers = [line for line in events.splitlines() if line.startswith(" ") + and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] + with self.subTest(workflow=name): + self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + + def test_signer_serialization_contract_is_enforced(self): + assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) + + def test_weakened_or_malformed_serialization_is_rejected(self): + source = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + for old, new in ( + ("queue: max", "queue: single"), + ("queue: max", "queue: invalid"), + ("queue: max", "queue: ${{ github.run_id }}"), + ("queue: max", "queue:"), + ("queue: max", "queue: max\n queue: single"), + ("cancel-in-progress: false", "cancel-in-progress: true"), + ("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"), + ("cancel-in-progress: false\n", ""), + ("group: anicraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: anicraft-nightly-release", "group: release-${{ github.ref }}"), + ("concurrency:\n", "concurrency: ${{ github.run_id }}\n"), + ("concurrency:\n", " concurrency:\n"), + ): + with self.subTest(change=new), self.assertRaises(ValueError): + assert_nightly_serialization(source.replace(old, new)) + + def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + executable = "\n".join(line for line in source.splitlines() + if not line.lstrip().startswith("#")) + with self.subTest(workflow=name): + self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") + self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") + self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") + self.assertNotIn("secrets.", executable) + + +class NightlyTrustAnchors(unittest.TestCase): + """The public stable identities each platform's signed nightly must carry (all three platforms).""" + + def setUp(self): + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self): + self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}", + "the artifact kind is fixed by platform, never a caller pattern") + self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity") + + def test_trust_values_have_the_shapes_the_shared_signer_accepts(self): + rows = self.policy["platforms"] + self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$") + self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$") + subject = rows["windows-x86_64"]["trust"]["publisher_subject"] + self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"}) + + def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self): + pins = set() + for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")): + source = (ROOT / ".github/workflows" / name).read_text() + uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/" + + re.escape(callee) + r"@(\S+)$", source) + tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source) + with self.subTest(workflow=name): + self.assertEqual(len(uses), 1) + self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") + pins.update(uses) + self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") + self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + + +class NightlyEnabledCallers(unittest.TestCase): + """Producer and signer run only in their exact context, for the reviewed manual actors.""" + + GUARDS = { + "nightly.yml": "github.repository == 'storytold/anicraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/anicraft' && github.event_name == 'workflow_dispatch' && " + "github.ref == 'refs/heads/release' && github.ref_type == 'branch'", + } + + def test_enabled_jobs_keep_exact_context_guards(self): + for name, expected in self.GUARDS.items(): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + guards = job_conditions(jobs) + with self.subTest(workflow=name): + self.assertEqual(len(guards), 1) + indicator, expression = guards[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review") + + def test_manual_actors_are_the_release_managers_in_caller_and_policy(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) + self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + + def test_an_actor_outside_the_release_managers_is_refused(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":")) + widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower) + for change in ("caller", "policy", "both", "order", "case"): + mutated_source, mutated_policy = source, copy.deepcopy(policy) + if change in ("caller", "both"): + mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":"))) + if change in ("policy", "both"): + mutated_policy["manual_actors"] = widened + if change == "order": + mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS)) + if change == "case": + mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS] + with self.subTest(change=change), self.assertRaises(ValueError): + reviewed_manual_actors(mutated_source, mutated_policy) + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + def setUp(self): + self.assertFalse(INSTALLED_POLICY.is_symlink()) + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_exact_v3_fields_and_repository_identity(self): + expected = {"schema", "repository", "repository_id", "producer_workflow_id", + "producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref", + "signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors", + "automatic_signer_actors", "max_age_seconds", "candidate_policy", + "max_artifact_bytes", "platforms"} + self.assertEqual(set(self.policy), expected) + self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(self.policy["repository"], "storytold/anicraft") + self.assertEqual(self.policy["release_branch"], "release") + self.assertIs(type(self.policy["repository_id"]), int) + self.assertGreater(self.policy["repository_id"], 0) + # producer_workflow_id is null until nightly.yml is registered on main; once set it must be a positive int. + if self.policy["producer_workflow_id"] is not None: + self.assertIs(type(self.policy["producer_workflow_id"]), int) + self.assertGreater(self.policy["producer_workflow_id"], 0) + self.assertNotEqual(self.policy["producer_workflow_id"], + self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"], + "the producer is not its own quality workflow") + + def test_paths_and_tooling_match_the_callers(self): + pin = caller_pin("nightly.yml") + self.assertEqual(caller_pin("nightly-sign.yml"), pin) + self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml") + self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml") + self.assertEqual(self.policy["producer_tooling_revision"], pin) + self.assertEqual(self.policy["signer_tooling_revision"], pin) + self.assertEqual(self.policy["producer_workflow_ref"], + "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin) + + def test_platforms_equal_the_producer(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS), "one release carries Windows, Linux and macOS") + self.assertEqual(set(self.policy["platforms"]), set(built)) + + def test_bounds(self): + self.assertIs(type(self.policy["max_age_seconds"]), int) + self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800) + self.assertIs(type(self.policy["max_artifact_bytes"]), int) + self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3) + + def test_candidate_workflows_run_on_every_main_push(self): + candidate = self.policy["candidate_policy"] + self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"}) + self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3") + self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/anicraft", "main")) + self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128) + rows = candidate["required_workflows"] + self.assertTrue(rows) + for row in rows: + with self.subTest(workflow=row["workflow_path"]): + self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"}) + self.assertIs(type(row["workflow_id"]), int) + self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"]) + source = (ROOT / row["workflow_path"]).read_text() + push = re.search(r"(?m)^ push:\n((?: .*\n)+)", source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn(" branches: [main]\n", push[1]) + self.assertNotRegex(push[1], r"paths", "a path filter would leave candidates without a run") + names = [job["name"] for job in row["jobs"]] + self.assertEqual(len(names), len(set(names))) + for job in row["jobs"]: + self.assertEqual(set(job), {"name", "app_id", "applicability"}) + self.assertEqual((job["app_id"], job["applicability"]), (15368, "required")) + + def test_sonar_identity_and_reviewed_scope(self): + sonar = self.policy["candidate_policy"]["sonar"] + properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines() + if line and not line.startswith("#")) + self.assertEqual(sonar["organization"], properties["sonar.organization"]) + self.assertEqual(sonar["project"], properties["sonar.projectKey"]) + self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis")) + self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main") + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"])) + metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]] + self.assertEqual(len(metrics), len(set(metrics))) + keys = [item["key"] for item in sonar["debt"]] + self.assertEqual(len(keys), len(set(keys))) + for item in sonar["debt"]: + with self.subTest(issue=item["key"]): + self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"}) + self.assertTrue(item["component"].startswith(sonar["project"] + ":")) + self.assertIn(item["type"], sonar["issue_types"]) + self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100644 index 00000000..0c283926 --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Run the synthetic nightly packaging suites together; no app build or signing. + +`nightly-release-tests.py` is dylanmtaylor's contract suite for the enabled callers and the +installed policy (`nightly.yml`, `nightly-sign.yml`, `.github/nightly-signing-policy.json`); it +runs here too, so one command covers everything the PR adds. +""" +import importlib.util +from pathlib import Path +import unittest + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + for name, relative in ( + ("anicraft_archive_suite", "nightly-archive-tests.py"), + ("anicraft_launch_suite", "nightly-launch-tests.py"), + ("anicraft_release_suite", "nightly-release-tests.py"), + ("anicraft_plist_suite", "macos/nightly_plist_tests.py"), + ("anicraft_mac_sign_suite", "macos/nightly_sign_tests.py"), + ): + spec = importlib.util.spec_from_file_location(name, here / relative) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 00000000..79219858 --- /dev/null +++ b/packaging/nightly_paths.py @@ -0,0 +1,139 @@ +"""POSIX packaging I/O rooted at a caller-owned private working directory. + +The build launcher chooses cwd independently of file arguments (Linux uses its +mktemp directory). This is not a sandbox against root or a malicious same-UID +caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive. +""" +import contextlib +import os +from pathlib import Path +import stat + + +def _component(name): + # A descriptor-relative open must name exactly one entry in its directory. + if not name or name in (".", "..") or os.path.basename(name) != name: + raise ValueError("build path components must be single names") + return os.path.basename(name) + + +class OwnedBuildRoot: + def __enter__(self): + self.directory = Path.cwd() + self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(self.fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: + os.close(self.fd) + raise ValueError("packaging cwd must be an owned private build directory") + return self + + def __exit__(self, *_error): + os.close(self.fd) + + def _relative(self, path): + path = Path(path) + try: + relative = path.relative_to(self.directory) if path.is_absolute() else path + except ValueError as error: + raise ValueError("path is outside the owned build directory") from error + if not relative.parts or ".." in relative.parts: + raise ValueError("empty or parent-traversing build path") + # Check an independently selected root, never the supplied filename's parent. + try: + parent = (self.directory / relative).parent.resolve(strict=True) + except OSError as error: + raise ValueError("build path parent must exist") from error + if not parent.is_relative_to(self.directory): + raise ValueError("resolved path escapes the owned build directory") + return relative + + def _checked_parts(self, path): + relative = self._relative(path) + root = os.path.realpath(self.directory) + lexical = os.path.join(root, *relative.parts) + target = os.path.realpath(lexical) + if target == root or os.path.commonpath([root, target]) != root: + raise ValueError("resolved path escapes the owned build directory") + if target != lexical: + raise ValueError("build path must not pass through symlinks or aliases") + return [_component(part) for part in os.path.relpath(target, root).split(os.sep)] + + def _parent(self, path): + parts = self._checked_parts(path) + current = os.dup(self.fd) + try: + for part in parts[:-1]: + next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current) + os.close(current) + current = next_fd + return current, parts[-1] + except OSError as error: + os.close(current) + raise ValueError("build path parents must be non-symlink directories") from error + + @contextlib.contextmanager + def reader(self, path, limit): + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except OSError as error: + raise ValueError("build input must be a regular file without aliases") from error + finally: + os.close(parent) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + os.close(descriptor) + raise ValueError("build input must be a regular file within its read bound") + with os.fdopen(descriptor, "rb") as stream: + yield stream + + def read_bytes(self, path, limit): + with self.reader(path, limit) as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError("build input grew beyond its read bound") + return data + + def children(self, path, limit): + relative = self._relative(path) + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError as error: + raise ValueError("build stage must be a non-symlink directory") from error + finally: + os.close(parent) + try: + entries = [] + with os.scandir(descriptor) as iterator: + for entry in iterator: + if len(entries) >= limit: + raise ValueError("too many build stage members") + entries.append(self.directory / relative / entry.name) + return entries + finally: + os.close(descriptor) + + @contextlib.contextmanager + def create(self, path): + parent, name = self._parent(path) + name = _component(name) + try: + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent) + info = os.fstat(descriptor) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(descriptor, "wb") as stream: + yield stream + except BaseException: + try: + current = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) == identity: + os.unlink(_component(name), dir_fd=parent) + except FileNotFoundError: + pass + raise + finally: + os.close(parent) diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 00000000..5f8245a7 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.3.0-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'anicraft-0.3.0-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'anicraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.anicraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.3.0' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.3.0', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'AniCraft Nightly' 'AniCraft 0.3.0-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.3.0-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('AniCraft', 'AniCraft 0.23.1 (nightly-v1)'), @('AniCraft Nightly', 'AniCraft 0.23.1'), @('AniCraft Nightly', 'AniCraft Nightly 0.23.1 (nightly-v1)'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.3.0-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +$sha = 'abcdef0123456789abcdef0123456789abcdef01' +$good = '0.3.0-nightly.20261120.17.1.gabcdef012345' +Assert-NightlySource $good $sha '2026-11-20' $sha '' +$cases = @( + @('missing commit', $good, '', '2026-11-20', $sha, ''), + @('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''), + @('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''), + @('version names another commit', '0.3.0-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''), + @('missing date', $good, $sha, '', $sha, ''), + @('date differs from version', $good, $sha, '2026-11-21', $sha, ''), + @('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''), + @('dirty tree', $good, $sha, '2026-11-20', $sha, ' M src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'anicraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.3.0-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 00000000..d799f460 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,90 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +# The fixture mocks Cargo, but nightly.ps1 checks the same source identity a packaging run does: +# the version names this checkout's commit and the run's UTC date, and the tree is clean. Deriving +# them here keeps the fixture reaching the mocked compiler instead of failing in source validation. +$sha = "$(git -C $PSScriptRoot rev-parse HEAD)".Trim() +$runDate = (Get-Date).ToUniversalTime().ToString('yyyyMMdd') +$version = "0.3.0-nightly.$runDate.12345.1.g$($sha.Substring(0, 12))" +$env:ANICRAFT_VERSION = $version +$env:ANICRAFT_BUILD_SHA = $sha +$env:ANICRAFT_BUILD_DATE = "$($runDate.Substring(0, 4))-$($runDate.Substring(4, 2))-$($runDate.Substring(6, 2))" +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + Clear-SigningFixtures + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 00000000..02f704fb --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,134 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "anicraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "anicraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('anicraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.anicraft.nightly-v1' + } +} + +# The same source identity the Linux helper enforces (nightly-common.sh): the version names the +# commit being built, the date is the original run's, and the tree is clean. +function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) { + if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (ANICRAFT_BUILD_SHA)' } + if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' } + if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (ANICRAFT_BUILD_DATE)' } + $versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8) + if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' } + if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' } + if ($Status) { throw 'nightly packaging requires the frozen clean source' } +} + +function Get-NightlySourceState([string] $RepositoryRoot) { + $head = git -C $RepositoryRoot rev-parse HEAD + if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' } + $status = git -C $RepositoryRoot status --porcelain + if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' } + return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() } +} + +function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) { + # The line the flavor prints: the contract's ` (nightly-v1)` (src/main.rs, + # src/build_flavor.rs), which the Launcher and the shared producer parse. The product name, a + # separate resource field, is `AniCraft Nightly`. + if ($ProductName -ne 'AniCraft Nightly' -or $VersionOutput -cne "AniCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:ANICRAFT_VERSION -or $Version -cne $env:ANICRAFT_VERSION) { throw 'nightly-v1 requires explicit ANICRAFT_VERSION, not the Cargo version fallback' } +$Spec = Get-NightlyArchiveSpec $Version $Arch +if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' } +if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' } +if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' } +# No key values may enter compilation. This produces an internal intermediate, not a feed artifact. +& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment +$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$Source = Get-NightlySourceState $Root +Assert-NightlySource $Version $env:ANICRAFT_BUILD_SHA $env:ANICRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:ANICRAFT_BUILD_CHANNEL +try { + # build.rs reads ANICRAFT_CHANNEL, ANICRAFT_VERSION and ANICRAFT_BUILD_SHA from the caller. + $env:ANICRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:ANICRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + cargo build --release --locked -p anicraft --target $Target + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:ANICRAFT_BUILD_CHANNEL = $oldChannel +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:ANICRAFT_BUILD_SHA $env:ANICRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\anicraft.exe" +$pe = [System.IO.File]::ReadAllBytes($Exe) +if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } +$offset = [BitConverter]::ToInt32($pe, 0x3C) +if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' } +if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) { + throw 'nightly executable must be x86_64 Windows GUI' +} +$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo +$ProductName = $VersionInfo.ProductName +if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' } +# Check the embedded build flavor before invoking even the side-effect-free version query. +if ($ProductName -ne 'AniCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' } +$VersionOutput = (& $Exe --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' } +Assert-NightlyFlavor $ProductName $VersionOutput $Version +$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64' +if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force } +New-Item -ItemType Directory -Force -Path $Stage | Out-Null +Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'anicraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate's filename cannot satisfy the feed-ready archive contract. +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.UnsignedArchive +if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('anicraft.exe' -notin $Names -or 'anicraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index b370625c..3293115f 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -22,12 +22,20 @@ pwsh packaging/windows/package.ps1 -Arch x64 pwsh packaging/windows/package.ps1 -Arch x64 -SkipBuild pwsh packaging/windows/package.ps1 -Arch arm64 # cross-compiled; needs the MSVC ARM64 build tools + pwsh packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly + + -Nightly builds the GUI-only Nightly flavor instead (nightly.ps1): that head is not an MSI, a + portable zip or a symbols download, must be compiled with -BuildOnly, and is signed by the + separate trusted step (sign.ps1 -Required), never here. #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly, + [switch] $BuildOnly ) $ErrorActionPreference = 'Stop' +if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path $AppId = 'ai.storyteller.anicraft' @@ -58,7 +66,15 @@ New-Item -ItemType Directory -Force -Path $Dist | Out-Null Write-Output "AniCraft $Version for Windows $Arch ($Target)" +# The Nightly head is the app-owned GUI ZIP from nightly.ps1: no MSI, portable zip, symbols or +# association, and no signing here (the trusted step signs it with sign.ps1 -Required). +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly + return +} + if (-not $SkipBuild) { + $env:ANICRAFT_BUILD_CHANNEL = 'stable' # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' @@ -86,6 +102,11 @@ foreach ($check in @(@('anicraft.exe', 2), @('anicraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +# A Nightly executable carries its own identity and version (build.rs): packaging it as stable +# would ship a window id and a version the Launcher cannot match, so refuse before staging. +if ((Get-Item -LiteralPath (Join-Path $Bin 'anicraft.exe')).VersionInfo.ProductName -eq 'AniCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable; use nightly.ps1 (package.ps1 -Nightly)' +} $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index e4799e0b..e843c968 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -9,17 +9,25 @@ AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net), AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds - still produce installers. + still produce installers. A Nightly caller requires signing with -Required, can check that the + configuration is there with -Required -CheckOnly, and keeps signing material away from + compilation with -CheckBuildEnvironment. This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe). .EXAMPLE - pwsh packaging/windows/sign.ps1 dist/anicraft.exe dist/Photocraft.msi + pwsh packaging/windows/sign.ps1 dist/anicraft.exe dist/AniCraft.msi + pwsh packaging/windows/sign.ps1 -Required dist/anicraft.exe + pwsh packaging/windows/sign.ps1 -Required -CheckOnly + pwsh packaging/windows/sign.ps1 -CheckBuildEnvironment #> param( - [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)] - [string[]] $Files + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]] $Files, + [switch] $Required, + [switch] $CheckOnly, + [switch] $CheckBuildEnvironment ) $ErrorActionPreference = 'Stop' @@ -37,6 +45,13 @@ function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } +# A file this step signed must carry a complete, valid Authenticode signature. +function Assert-AuthenticodeSignature($Signature) { + if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) { + throw 'Required signing must produce a valid Authenticode signature and signer certificate' + } +} + function Find-SignTool { if ($env:SIGNTOOL) { return $env:SIGNTOOL } $onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue @@ -54,11 +69,29 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path -LiteralPath $_).Path } -$haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' +# Compilation runs this instead of signing: no key may reach a build, and no file is touched. +if ($CheckBuildEnvironment) { + if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' } + $names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars + if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) { + throw 'Compilation must not receive signing credentials; use a separate trusted signing step' + } + return +} +$haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) +if ($Required -and -not $haveCert -and -not $haveAzure) { + throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration' +} +if ($CheckOnly) { + if ($Files) { throw '-CheckOnly does not sign files' } + return +} +if (-not $Files) { throw 'At least one file is required for signing' } +$Files = $Files | ForEach-Object { (Resolve-Path -LiteralPath $_).Path } + if (-not $haveCert -and -not $haveAzure) { Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" exit 0 @@ -104,6 +137,9 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties index b0aa5244..04f9e3a2 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -3,4 +3,10 @@ sonar.organization=storytold # CI only publishes the Rust lcov report, so JS, PowerShell and Python never # appear covered. Same idea as filmcraft and lightcraft excluding tools/docs. -sonar.coverage.exclusions=**/*.js,**/*.ps1,**/*.py +sonar.coverage.exclusions=**/*.js,**/*.ps1,**/*.py,packaging/** + +# Declaring test files turns off Sonar's default sources: state them, or the analysis indexes +# only the packaging tests and the gate means nothing. +sonar.sources=. +sonar.tests=packaging,tests,src +sonar.test.inclusions=packaging/*-tests.py,packaging/macos/*_tests.py,packaging/**/*-tests.ps1,**/*_tests.rs,**/tests/** diff --git a/src/app.rs b/src/app.rs index c2915fe7..45bece2c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -684,6 +684,11 @@ pub struct App { pub templates: crate::templates::Templates, /// Saved commands (ADR 0097): the folder's list, the History panel's picks, their windows. pub macros: crate::macros_ui::Macros, + /// Runs once when the window closes, inside `on_exit`: on macOS every quit ends the process + /// inside AppKit's terminate, so code after `run_native` never runs there (the Nightly + /// session record is finished here; `src/nightly_session.rs`). + #[cfg(not(target_arch = "wasm32"))] + pub at_exit: Option>, } /// How often (seconds) the system's contrast and light or dark setting are asked again (ADR 0064). @@ -969,6 +974,8 @@ impl App { thumbs: Default::default(), templates: Default::default(), macros: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + at_exit: None, }; // Your themes (ADR 0117), before the look is first applied. Tests and screenshot runs // read no folder of the computer's unless one is named. @@ -4548,16 +4555,25 @@ impl App { fn about_window(&mut self, ctx: &egui::Context) { let mut open = self.show_about; - let shown = crate::windows::new(ctx, tr!("About AniCraft")).id(egui::Id::new("about_window")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { + let nightly = !crate::platform::stable_services_allowed(); + let title = if nightly { tr!("About AniCraft Nightly") } else { tr!("About AniCraft") }; + let shown = crate::windows::new(ctx, title).id(egui::Id::new("about_window")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { ui.add(egui::Image::new((app_mark(ctx).id(), egui::vec2(64.0, 64.0)))); - ui.heading("AniCraft"); - ui.label(tr!("Version {version} · {stage}", version = env!("CARGO_PKG_VERSION"), stage = crate::i18n::t(RELEASE_STAGE))); + ui.heading(crate::platform::name()); + if nightly { + ui.label(tr!("Version {version}", version = env!("ANICRAFT_BUILT_VERSION"))); + let commit = env!("ANICRAFT_BUILD_SHA"); + ui.label(tr!("Built from commit {commit}", commit = &commit[..12.min(commit.len())])); + ui.label(tr!("This preview build is managed by ArtCraft Launcher; its updates come from there.")); + } else { + ui.label(tr!("Version {version} · {stage}", version = env!("ANICRAFT_BUILT_VERSION"), stage = crate::i18n::t(RELEASE_STAGE))); + } ui.label(tr!("Open-source 2D vector animation studio, written in Rust.")); ui.label(trn!("{n} engine command — all available headless via anicraft-cli.", "{n} engine commands — all available headless via anicraft-cli.", commands().len())); ui.colored_label(T.text_dim, "MIT OR Apache-2.0"); // i18n-exempt: licence identifiers ui.label(theme::text(theme::Type::Caption, tr!("Typefaces: {fonts}", fonts = theme::font_summary()))); }); - crate::a11y::name_title_bar(&shown, tr!("About AniCraft")); + crate::a11y::name_title_bar(&shown, title); self.show_about = open; } @@ -4757,9 +4773,17 @@ impl eframe::App for App { let clean = self.allow_close || self.shot.is_some(); crate::tabs::finish_all(self, clean); #[cfg(not(target_arch = "wasm32"))] - self.updates.finish(); + if crate::platform::stable_services_allowed() { + self.updates.finish(); + } #[cfg(not(target_arch = "wasm32"))] crate::remote::finish(self); + // Last, and once: macOS has no code path after `run_native`, so a clean quit is finished + // here. Elsewhere `main`'s return path calls the same hook, which by then is a no-op. + #[cfg(not(target_arch = "wasm32"))] + if let Some(hook) = self.at_exit.take() { + hook(); + } } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { diff --git a/src/build_channel.rs b/src/build_channel.rs new file mode 100644 index 00000000..ec157187 --- /dev/null +++ b/src/build_channel.rs @@ -0,0 +1,57 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} + +/// The Windows icon embedded in `anicraft.exe`: the Nightly tile has its own, so Explorer and the +/// taskbar never show the stable icon for it. +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "assets/app-icon/anicraft-nightly.ico" } else { "assets/app-icon/anicraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "assets/app-icon/anicraft.ico"); + assert_eq!(windows_icon_path(true), "assets/app-icon/anicraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.3.0-nightly.20261120.17.1.gabcdef012345")); + for invalid in [ + "", + "0.3.0", + "0.3.0-nightly", + "0.3.0-nightly.20261120", + "0.3.0-nightly.20261120.17.1.gABCDEF012345", + "0.3.0-nightly.20261120.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.3.0-nightly.20261120.1.1.gabcdef012345", + "0.3.0-nightly.20261120.1.1.gabcdef012345/other", + "0.3.0-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/src/build_flavor.rs b/src/build_flavor.rs new file mode 100644 index 00000000..a9ffaf7f --- /dev/null +++ b/src/build_flavor.rs @@ -0,0 +1,77 @@ +//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a +//! stable build. +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +pub const COMPILED: BuildFlavor = if cfg!(anicraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err(tr!("Open AniCraft Nightly from ArtCraft Launcher").into()), + (BuildFlavor::Stable, true) => Err(tr!("This is a stable AniCraft build; nightly-v1 requires the nightly build").into()), + _ => Ok(()), + } +} + +/// Whether a refusal should be shown in a native dialog: only a nightly desktop launch has no +/// console to print it on. +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +/// `--version` / `-V` on their own. +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +/// The line `--version` prints; the Nightly build answers in the Launcher's own form. +pub fn version(flavor: BuildFlavor, stable: &str) -> String { + match flavor { + BuildFlavor::Stable => stable.to_owned(), + BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"), // i18n-exempt: a version suffix, not prose + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_build_without_a_profile_is_refused_before_startup() { + let started = std::cell::Cell::new(false); + let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); + assert!(result.unwrap_err().contains("ArtCraft Launcher")); + assert!(!started.get()); + } + + #[test] + fn stable_and_nightly_flavors_accept_only_their_own_profile() { + let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); + assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); + assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); + assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + } + + #[test] + fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + assert_eq!(version(BuildFlavor::Stable, "0.3.0"), "0.3.0"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.3.0"), "0.3.0 (nightly-v1)"); + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/src/desktop_ui.rs b/src/desktop_ui.rs index 30967f97..74d4d2ea 100644 --- a/src/desktop_ui.rs +++ b/src/desktop_ui.rs @@ -58,7 +58,9 @@ fn read_entry(app: &mut App, d: &Desktop) -> Entry { /// user said yes once. Otherwise, the first time only, offer to add it, unless this copy is /// portable (portable copies leave no trace on the computer). pub fn at_start(app: &mut App) { - if app.shot.is_some() { + // Nightly keeps everything in its own profile and writes no applications-menu entry, even + // when it was started from an AppImage (`src/profile_root.rs`). + if app.shot.is_some() || !crate::platform::stable_services_allowed() { return; } let (Some(appimage), Some(data_home)) = (crate::platform::appimage(), crate::platform::data_home()) else { return }; @@ -162,12 +164,14 @@ pub fn about(app: &App, ui: &mut egui::Ui, label_w: f32) -> Option { let mut act = None; let place = crate::platform::placement(); form_row(ui, label_w, tr!("Version"), |ui| { - ui.label(text(Type::Data, env!("CARGO_PKG_VERSION"))); + ui.label(text(Type::Data, env!("ANICRAFT_BUILT_VERSION"))); ui.label(text(Type::Caption, crate::platform::OS.name())); }); form_row(ui, label_w, tr!("This copy"), |ui| { let mode = if crate::platform::WEB { tr!("In the browser: settings are kept in this site's storage") + } else if place.profile.is_some() { + tr!("Nightly: everything is kept in this preview's own profile, apart from AniCraft") } else if place.portable.is_some() { tr!("Portable: everything is kept in the data folder beside AniCraft") } else { diff --git a/src/launch_profile.rs b/src/launch_profile.rs new file mode 100644 index 00000000..8fc2e064 --- /dev/null +++ b/src/launch_profile.rs @@ -0,0 +1,272 @@ +//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state. +//! Stable launches retain their original arguments and directory policy. No environment mutation. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::OnceLock; + +pub const VERSION: &str = "nightly-v1"; + +/// Where a distribution wrapper names the profile root when it cannot add arguments in front of +/// the person's own. Every format this app ships adds the two arguments through +/// `packaging/linux/nightly-launch.sh` instead, so nothing here uses the variable today; it stays +/// as the one door for a packager whose launcher can only set an environment, is read only by a +/// nightly build, is validated exactly like the Launcher's root, and may not be combined with the +/// Launcher's two arguments. +pub const ROOT_ENV: &str = "ANICRAFT_PROFILE_ROOT"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + Stable, + NightlyV1(PathBuf), +} + +impl Profile { + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } + + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(root) => Some(root), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Launch { + pub profile: Profile, + pub args: Vec, +} + +static PROFILE: OnceLock = OnceLock::new(); + +pub fn current() -> &'static Profile { + PROFILE.get().unwrap_or(&Profile::Stable) +} + +pub fn install(profile: Profile) -> Result<(), String> { + PROFILE.set(profile).map_err(|_| tr!("the launch profile was already selected").into()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is +/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here. +pub fn parse(args: Vec) -> Result { + let mut selector = None; + let mut root = None; + let mut other = Vec::new(); + let mut files = Vec::new(); + let mut iter = args.iter(); + let mut delimiter = false; + while let Some(arg) = iter.next() { + if arg == "--" { + delimiter = true; + files.extend(iter.cloned()); + break; + } + if arg == "--launch-profile" || arg == "--profile-root" { + let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; + if slot.is_some() { + return Err(tr!("the profile selector and root must each occur exactly once").into()); + } + let value = iter.next().filter(|v| !v.is_empty()).ok_or_else(|| tr!("the profile selector/root needs a value").to_string())?; + if value.to_string_lossy().starts_with("--") { + return Err(tr!("the profile selector/root needs a value").into()); + } + *slot = Some(value.clone()); + } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { + return Err(tr!("the nightly protocol requires separate literal selector/root argument tokens").into()); + } else { + other.push(arg.clone()); + } + } + match (selector, root) { + (None, None) => Ok(Launch { profile: Profile::Stable, args }), + (Some(version), Some(root)) if version == VERSION => { + if !delimiter || !other.is_empty() { + return Err(tr!("nightly-v1 accepts only its selector/root followed by -- and file names").into()); + } + let root = nightly_root(&root)?; + Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) + } + (Some(_), Some(_)) => Err(tr!("unsupported launch profile (expected nightly-v1)").into()), + _ => Err(tr!("--launch-profile and --profile-root must be supplied together").into()), + } +} + +/// A root is lexical here: absolute, no `..`. Whether it is a safe place for Nightly's data is +/// [`crate::profile_root::validate`]'s decision, taken before the first startup effect. +fn nightly_root(value: &std::ffi::OsStr) -> Result { + let root = PathBuf::from(value); + if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(tr!("the nightly profile root must be absolute and contain no parent traversal").into()); + } + Ok(root) +} + +/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), +/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never +/// validated or touched, and `-- --version` stays a file name. +pub fn version_query(args: &[OsString]) -> bool { + let Some((last, pair)) = args.split_last() else { return false }; + if last != "--version" && last != "-V" { + return false; + } + let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); + matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) +} + +/// [`parse`], plus the wrapper's root for a distribution package that cannot add arguments. A +/// build passes `wrapper_root` only for the nightly channel, so a stable build never sees it. +pub fn parse_startup(args: Vec, wrapper_root: Option) -> Result { + // Only the tokens before `--`: after it everything is a file name, even `--profile-root`. + let launcher_form = args.iter().take_while(|a| *a != "--").any(|a| { + a == "--launch-profile" + || a == "--profile-root" + || a.to_string_lossy().starts_with("--launch-profile=") + || a.to_string_lossy().starts_with("--profile-root=") + }); + let wrapper = wrapper_root.filter(|v| !v.is_empty()); + match (launcher_form, wrapper) { + (true, Some(_)) => Err(tr!("nightly-v1 takes its profile from the Launcher or {name}, not both", name = ROOT_ENV)), + (true, None) => parse(args), + (false, Some(root)) => Ok(Launch { profile: Profile::NightlyV1(nightly_root(&root)?), args }), + // Stable's argument order and parser remain unchanged. + (false, None) => Ok(Launch { profile: Profile::Stable, args }), + } +} + +/// Validation finishes before the caller's first startup effect. Stable never calls the nightly +/// root validator, so its old portable/config resolution stays unchanged. +pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { + if let Profile::NightlyV1(root) = &launch.profile { + launch.profile = Profile::NightlyV1(validate(root)?); + } + Ok(launch) +} + +/// Resolve the selected private root before the caller's first startup effect. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::profile_root::probe_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\anicraft" } else { "/nightly-data/profiles/anicraft" } + } + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["walk.anicraft"]), args(&["--", "--launch-profile", "shot.png"])] { + let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); + assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + } + // Without the wrapper variable a start is stable, whatever it was given. + let launch = parse_startup(args(&["walk.anicraft"]), None).unwrap(); + assert_eq!((launch.profile, launch.args), (Profile::Stable, args(&["walk.anicraft"]))); + } + + #[test] + fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "scene with spaces.anicraft"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "scene with spaces.anicraft"])); + } + + #[test] + fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + let equals_form = format!("--profile-root={}", absolute()); + for argv in [ + args(&["--launch-profile", VERSION]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "../escaping", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + args(&[&equals_form[..], "--launch-profile", VERSION, "--"]), + ] { + assert!(parse(argv).is_err()); + } + } + + #[test] + fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { + let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; + let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + for flag in ["--version", "-V"] { + for form in [pair, reversed] { + let mut argv = args(form); + argv.push(flag.into()); + assert!(version_query(&argv), "{argv:?}"); + } + } + for argv in [ + args(&["--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--screenshot", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), + args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), + args(&["--launch-profile", VERSION, "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + ] { + assert!(!version_query(&argv), "{argv:?}"); + } + // Outside the query the strict protocol still refuses the version flag. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + } + + #[test] + fn the_wrapper_root_is_the_same_profile_and_cannot_be_mixed_with_the_launcher_form() { + let launch = parse_startup(args(&["walk cycle.anicraft"]), Some(absolute().into())).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["walk cycle.anicraft"])); + // An empty value is no value, as a shell's `VAR=` sets it. + assert_eq!(parse_startup(args(&[]), Some(OsString::new())).unwrap().profile, Profile::Stable); + // After `--` every token is a file name, so a file called `--profile-root` is not the Launcher's. + let after_delimiter = parse_startup(args(&["--", "--profile-root"]), Some(absolute().into())).unwrap(); + assert_eq!((after_delimiter.profile, after_delimiter.args), (Profile::NightlyV1(PathBuf::from(absolute())), args(&["--", "--profile-root"]))); + // Both at once is ambiguous about which root the window would use, so neither is used. + assert!(parse_startup(nightly(), Some(absolute().into())).is_err()); + assert!(parse_startup(args(&[]), Some("relative".into())).is_err()); + assert!(parse_startup(args(&[]), Some("../escaping".into())).is_err()); + // One half of the Launcher's pair on its own is refused (a reserved token, never a file), + // and so is a profile the build cannot honour. + assert!(parse_startup(args(&["--profile-root"]), None).is_err()); + assert!(parse_startup(args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), None).is_err()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/src/main.rs b/src/main.rs index 83705f8f..4cc9728c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,6 +29,8 @@ mod audio_keys; mod autosave; mod brush_panel; mod brushtool; +#[cfg(not(target_arch = "wasm32"))] +mod build_flavor; mod colour; mod colour_panel; mod envelope; @@ -59,6 +61,8 @@ mod gpu_watch; mod gradient_tool; mod icons; mod keymap; +#[cfg(not(target_arch = "wasm32"))] +mod launch_profile; mod library; mod menus; #[cfg(not(target_arch = "wasm32"))] @@ -66,6 +70,8 @@ mod updates; mod mixed; mod motion_editor; mod movie_explorer; +#[cfg(not(target_arch = "wasm32"))] +mod nightly_session; mod panels; mod parenting; mod motion_path; @@ -82,6 +88,10 @@ mod macros_ui_tests; mod macros_ui; mod plugins_ui; mod prefs; +#[cfg(not(target_arch = "wasm32"))] +mod process_identity; +#[cfg(not(target_arch = "wasm32"))] +mod profile_root; mod recent; #[cfg(not(target_arch = "wasm32"))] mod remote; @@ -115,6 +125,8 @@ mod workspaces_window; #[cfg(not(target_arch = "wasm32"))] use anicraft_engine::Session; #[cfg(not(target_arch = "wasm32"))] +use std::io::Write as _; +#[cfg(not(target_arch = "wasm32"))] use std::path::{Path, PathBuf}; /// What opening the command line's file said, for the status bar. @@ -169,10 +181,25 @@ struct Look { shot_width: Option, } +/// This run's Nightly session record, shared with the window's exit hook, and what the first +/// window says about it. `session` is read by the exit hook, which only macOS has. #[cfg(not(target_arch = "wasm32"))] -fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option, open: Option, look: Look, control: Option) -> eframe::Result { +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +#[derive(Clone)] +struct Nightly { + session: nightly_session::Shared, + /// The record of a session that did not finish (shown once, then cleared). + previous_unclean: bool, + /// The record could not be taken: a secondary window, or a profile that refused it. + health_warning: bool, + /// Set once a window showed the interruption, so the record is not cleared before it is. + notice_shown: std::sync::Arc, +} + +#[cfg(not(target_arch = "wasm32"))] +fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option, open: Option, look: Look, control: Option, nightly: Nightly) -> eframe::Result { let options = attempt.options(eframe::NativeOptions { - viewport: platform::viewport(egui::ViewportBuilder::default().with_title("AniCraft").with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])), + viewport: platform::viewport(egui::ViewportBuilder::default().with_title(platform::name()).with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])), ..Default::default() }); // The embedded interface font joins the text library before anything lays text out: @@ -183,7 +210,7 @@ fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option, op let (session, report) = open_session(file); let file_given = file.map(Path::to_path_buf); eframe::run_native( - "AniCraft", + platform::name(), options, Box::new(move |cc| { // A document the system hands over while AniCraft is idle wakes it (ADR 0062). @@ -191,6 +218,27 @@ fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option, op startup::log_adapter(cc.wgpu_render_state.as_ref()); let starting_fresh = file_given.is_none() && shot.is_none(); let mut a = app::App::new(cc, session, shot); + // The previous Nightly session did not finish, or this window cannot record its own: + // said once, in the status bar, as the recovery notes are. + if nightly.previous_unclean { + a.status_err(tr!("The previous AniCraft Nightly session did not finish normally. The start-up log in Preferences › About says what it did last; no report has been sent.")); + // The status bar holds one line, and a document's own report below replaces this one + // before the first frame: only a start with nothing to add counts as having said it. + if matches!(report, Opened::Quiet) { + nightly.notice_shown.store(true, std::sync::atomic::Ordering::Relaxed); + } + } else if nightly.health_warning { + a.status_err(tr!( + "AniCraft Nightly could not record its session health in its profile. You can still edit, but an abnormal exit is not noticed." + )); + } + // macOS has no code path after `run_native`: a clean quit finishes here. + #[cfg(target_os = "macos")] + { + let shared = nightly.session.clone(); + let shown = nightly.notice_shown.clone(); + a.at_exit = Some(Box::new(move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed)))); + } // A file named on the command line keeps its tab, even an imported one (ADR 0112). if file_given.is_some() { a.tabs.keep_first(); @@ -198,7 +246,7 @@ fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option, op if let Some(s) = a.shot.as_mut() { s.width = look.shot_width; } - if a.shot.is_none() { + if a.shot.is_none() && platform::stable_services_allowed() { a.show_update_outcome_on_start(); } // No document to open: the start screen, unless it was switched off (ADR 0059). @@ -293,6 +341,14 @@ fn parse_args(args: impl IntoIterator) -> Result { "--version" | "-V" => out.print = Some(Print::Version), "--help" | "-h" => out.print = Some(Print::Help), "--check-theme" => out.print = Some(Print::CheckTheme(PathBuf::from(args.next().ok_or("--check-theme needs a theme file")?))), // i18n-exempt: a console message + // End of the options: everything after it is a file, even a name that reads like one + // of the flags above. A Nightly start arrives that way from the Launcher + // (`launch_profile::parse`), so its documents are never taken for flags. + "--" => { + for rest in args.by_ref() { + out.file = Some(PathBuf::from(rest)); + } + } // Not a file: what older macOS added when Finder started an app. other if platform::is_system_argument(other) => {} other => out.file = Some(PathBuf::from(other)), @@ -318,16 +374,133 @@ const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--sc (also ANICRAFT_CONTROL_PORT; 9878 by convention; see docs/control-protocol.md)\n\ Headless use: anicraft-cli --help"; +/// The version `--version`, About and the Launcher's check print. +#[cfg(not(target_arch = "wasm32"))] +fn version_line() -> String { + let built = env!("ANICRAFT_BUILT_VERSION"); + match build_flavor::COMPILED { + build_flavor::BuildFlavor::NightlyV1 => build_flavor::version(build_flavor::BuildFlavor::NightlyV1, built), + build_flavor::BuildFlavor::Stable => format!("{built} ({})", app::RELEASE_STAGE), + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, platform::APP_ID_NIGHTLY) +} + +/// Says why the launch profile was refused, on the console and (nightly, with a desktop) in a +/// dialog: a windowed build has no console to show it on. +#[cfg(not(target_arch = "wasm32"))] +fn report_launch_profile_error(error: &str) { + eprintln!("AniCraft launch profile: {error}"); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if let Err(error) = initialize_nightly_process_identity() { + eprintln!("AniCraft launch profile: {error}"); + return; + } + let _ = rfd::MessageDialog::new() + .set_title(tr!("AniCraft Nightly")) + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Selects the launch profile before any startup effect: no log line, no folder, no window, no +/// update check. Returns the arguments the rest of the start reads, or `None` once `--version` +/// has been answered (the only answer that comes before the profile is validated). +#[cfg(not(target_arch = "wasm32"))] +fn prepare_launch() -> Option> { + let argv: Vec = std::env::args_os().skip(1).collect(); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: answered before root validation, process identity, IPC or any window. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) + { + let _ = writeln!(std::io::stdout(), "AniCraft {}", version_line()); // i18n-exempt: console text + return None; + } + // Only a nightly build reads the wrapper's root, so a stable copy never sees the variable. + let wrapper_root = if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { std::env::var_os(launch_profile::ROOT_ENV) } else { None }; + let early = launch_profile::parse_startup(argv, wrapper_root) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity().map_err(|error| error.to_string())?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| { + launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) + }) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + let identity = if early.profile.is_nightly() { platform::LaunchIdentity::NightlyV1 } else { platform::LaunchIdentity::Stable }; + if let Err(error) = launch_profile::install(early.profile).and_then(|()| platform::select_identity(identity)) { + report_launch_profile_error(&error); + std::process::exit(2); + } + Some(early.args) +} + +/// `--control ` or `ANICRAFT_CONTROL_PORT`; a bad port stops the start, before a window. +#[cfg(not(target_arch = "wasm32"))] +fn control_port(flag: Option) -> Option { + match flag { + Some(p) => Some(p), + None => match std::env::var(anicraft_cli::control::PORT_ENV).ok().filter(|v| !v.trim().is_empty()) { + Some(v) => match anicraft_cli::control::parse_port(&v) { + Ok(p) => Some(p), + Err(e) => { + eprintln!("{}: {e}", anicraft_cli::control::PORT_ENV); + std::process::exit(2); + } + }, + None => None, + }, + } +} + #[cfg(not(target_arch = "wasm32"))] fn main() -> eframe::Result { - if let Some(result) = updates::finish_helper() { + let Some(arguments) = prepare_launch() else { return Ok(()) }; + // Nightly has no updater: the Launcher owns its version (`docs/nightly-release-preparation.md`). + if platform::stable_services_allowed() + && let Some(result) = updates::finish_helper() + { let failed = result.is_err(); if let Err(error) = result { eprintln!("Update failed: {error}"); } std::process::exit(i32::from(failed)); } - let args = match parse_args(std::env::args().skip(1)) { + // A file name that is not Unicode cannot be opened; it is said rather than dropped silently + // (the launcher's arguments themselves were read as bytes in `prepare_launch`). + let mut words = Vec::with_capacity(arguments.len()); + let mut after_delimiter = false; + for argument in arguments { + match argument.into_string() { + Ok(word) => { + after_delimiter |= word == "--"; + words.push(word); + } + // After `--` every word is a file: one that is not Unicode is said and skipped. + Err(what) if after_delimiter => eprintln!("AniCraft could not read a file name on the command line: {what:?}"), // i18n-exempt: a console message + // Before it the word could be an option or its value: dropping it would hand the next + // word to the wrong option (a file name read as `--screenshot`'s output, say). + Err(what) => { + eprintln!("AniCraft cannot read an option or its value that is not Unicode: {what:?}"); // i18n-exempt: a console message + std::process::exit(2); + } + } + } + let args = match parse_args(words) { Ok(a) => a, Err(e) => { eprintln!("{e}"); @@ -336,7 +509,7 @@ fn main() -> eframe::Result { }; match args.print { Some(Print::Version) => { - println!("AniCraft {} ({})", env!("CARGO_PKG_VERSION"), app::RELEASE_STAGE); + println!("AniCraft {}", version_line()); return Ok(()); } Some(Print::Help) => { @@ -363,20 +536,9 @@ fn main() -> eframe::Result { None => {} } let Args { shot, file, open, renderer, look, control, .. } = args; - // ANICRAFT_CONTROL_PORT when there is no --control; a bad port stops here, before a window. - let control = match control { - Some(p) => Some(p), - None => match std::env::var(anicraft_cli::control::PORT_ENV).ok().filter(|v| !v.trim().is_empty()) { - Some(v) => match anicraft_cli::control::parse_port(&v) { - Ok(p) => Some(p), - Err(e) => { - eprintln!("{}: {e}", anicraft_cli::control::PORT_ENV); - std::process::exit(2); - } - }, - None => None, - }, - }; + // The control port is a stable service: Nightly never opens one, nor reads a port left in the + // environment by a launch that forwarded its variables. + let control = if platform::stable_services_allowed() { control_port(control) } else { None }; // macOS hands documents over as Apple Events, the one that launched the app included: listen // from before the event loop starts until it ends (ADR 0062). let _documents = platform::listen_for_documents(); @@ -385,40 +547,64 @@ fn main() -> eframe::Result { // fails or panics before the window is up falls through to the next; a start that died // inside a driver last time tries that way last (#207, `startup`). let mut last = startup::begin(platform::log_dir()); + // Nightly's own health record (`src/nightly_session.rs`): no document names or diagnostics, + // just whether the last session finished. Stable passes no root and touches nothing. + let (nightly_record, health_warning) = match nightly_session::Session::begin_with_health( + launch_profile::current().root(), + env!("ANICRAFT_BUILT_VERSION"), + Some(env!("ANICRAFT_BUILD_SHA")), + ) { + Ok(state) => state, + Err(error) => { + startup::line(&format!("Nightly session health is unavailable: {error}")); + (None, true) + } + }; + let previous_unclean = nightly_record.as_ref().is_some_and(nightly_session::Session::previous_unclean); + let notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_record)); + let nightly = Nightly { session: nightly_session.clone(), previous_unclean, health_warning, notice_shown: notice_shown.clone() }; let mut file = file; let mut reopened = 0; let mut why = String::from("no attempt"); // i18n-exempt: log text // Once, and again each time the window closed to reopen another way. let mut opening = true; + // Set when a window that had drawn then unwound with a panic: the next start reports it. + let mut ended_in_panic = false; // What the command line asks for is tried first, until a session loses its device on it. let mut forced = platform::forced_backend(renderer.as_deref()); - while opening { - opening = false; - let attempts = startup::plan(forced, prefs::Prefs::load().window_backend, &platform::window_attempts(platform::OS), &last); - for (n, attempt) in attempts.iter().enumerate() { - startup::trying(attempt, n + 1, attempts.len()); - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone(), control))); - why = match result { - Ok(Ok(())) => { - // The window's graphics device was lost mid-session (ADR 0092): it closed - // with the work autosaved, to open again another way, which offers it back. - if let Some(reopen) = startup::take_reopen() - && reopened < MAX_REOPENS - { - reopened += 1; - startup::line(&format!("opening the window again, {} last", attempt.label())); - last.retain(|l| *l != attempt.label()); - last.push(attempt.label()); - forced = None; - file = reopen; - opening = true; - break; + let result: eframe::Result = 'attempts: { + while opening { + opening = false; + let attempts = startup::plan(forced, prefs::Prefs::load().window_backend, &platform::window_attempts(platform::OS), &last); + for (n, attempt) in attempts.iter().enumerate() { + startup::trying(attempt, n + 1, attempts.len()); + let mut unwound = false; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone(), control, nightly.clone()))); + why = match result { + Ok(Ok(())) => { + // The window's graphics device was lost mid-session (ADR 0092): it closed + // with the work autosaved, to open again another way, which offers it back. + if let Some(reopen) = startup::take_reopen() + && reopened < MAX_REOPENS + { + reopened += 1; + startup::line(&format!("opening the window again, {} last", attempt.label())); + last.retain(|l| *l != attempt.label()); + last.push(attempt.label()); + forced = None; + file = reopen; + opening = true; + break; + } + startup::line("closed"); + break 'attempts Ok(()); } - startup::line("closed"); - return Ok(()); - } Ok(Err(e)) => e.to_string(), - Err(p) => format!("{} panicked: {}", attempt.label(), startup::panic_text(p.as_ref())), // i18n-exempt: a log line + Err(p) => { + unwound = true; + format!("{} panicked: {}", attempt.label(), startup::panic_text(p.as_ref())) // i18n-exempt: a log line + } }; startup::line(&format!("{} failed: {why}", attempt.label())); // It ran and then stopped: not a start-up problem, and opening a second window would @@ -428,7 +614,8 @@ fn main() -> eframe::Result { if startup::is_graphics_failure(&why) { startup::lost_mid_session(); } - return Err(eframe::Error::AppCreation(why.into())); + ended_in_panic = unwound; + break 'attempts Err(eframe::Error::AppCreation(why.into())); } // It never came up: the next starts try it last, as one that died in a driver. startup::failed_to_open(); @@ -436,6 +623,17 @@ fn main() -> eframe::Result { } startup::give_up(&why); Err(eframe::Error::AppCreation(why.into())) + }; + // A controlled return, even for a handled startup error. A renderer failure before the window + // (and so before any notice) has not shown an earlier interruption: the record stays, so the + // retry or the next start still reports it. On macOS a window that was created has already + // finished in its exit hook, so this is a no-op there. + // A window that drew and then panicked is not a controlled return: the record stays so the next + // start reports the interruption (a panic before the first frame was retried or reported above). + if !ended_in_panic { + nightly_session::finish_once(&nightly_session, notice_shown.load(std::sync::atomic::Ordering::Relaxed)); + } + result } /// Times one run opens the window again after its graphics device was lost (ADR 0092); past @@ -473,6 +671,16 @@ mod args_tests { assert!(parse_args(["--theme".to_string(), "plum".to_string()]).is_err()); assert_eq!(parse(&["--check-theme", "plum.json"]).print, Some(Print::CheckTheme(PathBuf::from("plum.json")))); assert!(parse_args(["--check-theme".to_string()]).is_err()); + // `--` ends the options: everything after it is a file, even a name that reads like a flag + // (the Launcher hands a Nightly start its documents over the same delimiter). + assert_eq!((parse(&["--"]).file, parse(&["--"]).print), (None, None)); + let flag_named_file = parse(&["--", "--version"]); + assert_eq!((flag_named_file.file, flag_named_file.print), (Some(PathBuf::from("--version")), None)); + assert_eq!(parse(&["--", "a.anicraft"]).file, Some(PathBuf::from("a.anicraft"))); + // Files on both sides of the delimiter open in the order the plain arguments always took: + // the last one named is the one that is opened. + assert_eq!(parse(&["--", "a.anicraft", "--other.anicraft"]).file, Some(PathBuf::from("--other.anicraft"))); + assert_eq!(parse(&["--screenshot", "shot.png", "--"]).file, None); // `--control ` (ADR 0104): a port from 1 to 65535, or an error before any window. assert_eq!(parse(&["--control", "9878"]).control, Some(9878)); for bad in [&["--control"][..], &["--control", "0"], &["--control", "99999"], &["--control", "port"]] { @@ -529,3 +737,5 @@ mod long_stroke_tests; mod ink; #[cfg(test)] mod zoom_tests; +#[cfg(test)] +mod stage_budget_tests; diff --git a/src/nightly_session.rs b/src/nightly_session.rs new file mode 100644 index 00000000..fbea2efe --- /dev/null +++ b/src/nightly_session.rs @@ -0,0 +1,269 @@ +//! App-private Nightly session health, not telemetry or a Launcher protocol. +//! A live owner holds a separate persistent lease; secondary launches never rewrite its record. +//! Dropping the guard does not clear the marker. Only the app's controlled return path does. + +use std::fs::File; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + // i18n-exempt: the start-up log's text (English, for bug reports) + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// A new file beside the destination, flushed to disk and renamed over it: a link left under the +/// destination's name is replaced, never written through. +fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + // i18n-exempt: the start-up log's text (English, for bug reports) + let directory = path.parent().ok_or_else(|| io::Error::other("Nightly session state needs a folder"))?; + let staged = directory.join(format!(".{}.{}.new", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id())); + let _ = std::fs::remove_file(&staged); + let written = (|| { + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&staged)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + std::fs::rename(&staged, path) + })(); + if written.is_err() { + let _ = std::fs::remove_file(&staged); + } + written +} + +/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop. +/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and +/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path +/// still runs for a start that created no window. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + crate::startup::line(&format!("Nightly session state was left intact: {error}")); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, + /// while Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is stable or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { + // i18n-exempt: the start-up log's text (English, for bug reports) + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit.filter(|value| !value.is_empty()), + }))?; + atomic_write_no_follow(&path, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + /// Controlled return. If an earlier session's interruption was detected but no window showed + /// it yet (a renderer failure before the app callback), the record is left for the next owner + /// to report; otherwise this is [`Self::complete`]. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// Controlled event-loop completion includes a handled startup error, not only exit 0. + /// Clear before releasing the lease so a successor cannot miss record ownership. + /// An unwind, abort, forced exit or killed process never calls this method. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + // i18n-exempt: the start-up log's text (English, for bug reports) + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = + std::env::temp_dir().join(format!("anicraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap()); + // Renderer initialization failed before the app callback: no notice was shown. + let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + // The CPU retry (or the next start) still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + // Without an earlier interruption, a handled failure still clears normally. + let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_hook_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap())); + // The exit hook (macOS quit: the only path that runs there). + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit"); + // Elsewhere the return path runs too, by then possibly after a successor took the profile. + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["channel", "commit", "schema_version", "version"].into_iter().collect()); + assert!(data["commit"].is_null(), "missing provenance must not be invented"); + watch.complete().unwrap(); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } +} diff --git a/src/platform.rs b/src/platform.rs index 6ceed0d8..7c6d09a4 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -299,11 +299,15 @@ pub fn portable_root_for(os: Os, exe: &Path, appimage: Option<&Path>, is_file: & /// Where this copy keeps its data, decided once at start. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Placement { - /// The portable data folder, when this copy is portable and the folder can be written. + /// The portable data folder, when this copy is portable and the folder can be written; the + /// Nightly profile root when this process was launched for one. pub portable: Option, /// A portable copy whose data folder can't be written (a read-only disc or share): the /// folder and why. The user's settings folder is used instead, and Preferences says so. pub unwritable: Option<(PathBuf, String)>, + /// The Nightly profile the Launcher selected: every folder below is inside it (portable, so + /// [`config_dir_for`] returns it too) and nothing of stable's is read or written. + pub profile: Option, } /// Whether `dir` can be made and written to (a small probe file, removed again). @@ -321,8 +325,8 @@ fn writable(dir: &Path) -> Result<(), String> { pub fn placement_for(root: Option<&Path>, can_write: &dyn Fn(&Path) -> Result<(), String>) -> Placement { let Some(data) = root.map(|r| r.join(PORTABLE_DATA)) else { return Placement::default() }; match can_write(&data) { - Ok(()) => Placement { portable: Some(data), unwritable: None }, - Err(e) => Placement { portable: None, unwritable: Some((data, e)) }, + Ok(()) => Placement { portable: Some(data), unwritable: None, profile: None }, + Err(e) => Placement { portable: None, unwritable: Some((data, e)), profile: None }, } } @@ -335,6 +339,12 @@ pub fn placement() -> &'static Placement { return Placement::default(); #[cfg(not(target_arch = "wasm32"))] { + // A Nightly profile replaces the portable and installed layouts wholesale: its root + // was validated before the first folder below was opened (`profile_root`, which also + // probed that it is writable), so nothing of stable's is consulted. + if let Some(root) = crate::launch_profile::current().root() { + return Placement { portable: Some(root.to_path_buf()), unwritable: None, profile: Some(root.to_path_buf()) }; + } let Ok(exe) = std::env::current_exe() else { return Placement::default() }; let root = portable_root_for(OS, &exe, appimage().as_deref(), &|p| p.is_file()); placement_for(root.as_deref(), &writable) @@ -690,13 +700,81 @@ pub fn plugins_dir() -> Option { /// Linux desktop entry, AppStream and MIME package names, the Flatpak id and the macOS bundle id. pub const APP_ID: &str = "ai.storyteller.anicraft"; +/// The Nightly window identity: the Wayland app_id / X11 class and the Windows AUMID +/// (`src/process_identity.rs`), so docks, taskbars and window rules keep Nightly apart from +/// Stable. The package and bundle use `APP_ID_NIGHTLY` instead; they are two different strings. +pub const APP_ID_NIGHTLY: &str = "ai.storyteller.anicraft.nightly-v1"; + +/// The package, macOS bundle and Launcher identity of the Nightly flavor. The artifacts carry it +/// (`packaging/nightly-common.sh`, `packaging/macos/nightly-lib.sh`, `nightly_plist.py`, the +/// policy), not this binary, so it is kept here only beside the window id: two strings, never one. +#[allow(dead_code)] +pub const APP_ID_NIGHTLY_PACKAGE: &str = "ai.storyteller.anicraft.nightly"; + +/// Which channel this process is: `Stable`, or the Nightly column selected before the window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LaunchIdentity { + Stable, + NightlyV1, +} + +static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Set once, before the first icon, window or folder is touched. +pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> { + let value = match identity { + LaunchIdentity::Stable => 1, + LaunchIdentity::NightlyV1 => 2, + }; + IDENTITY + .compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire) + .map(|_| ()) + .map_err(|_| tr!("the window launch identity was already selected").into()) +} + +pub fn identity() -> LaunchIdentity { + if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable } +} + +/// The window's app id for a channel: stable keeps its implicit one where Windows needs it. +pub const fn app_id_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => APP_ID, + LaunchIdentity::NightlyV1 => APP_ID_NIGHTLY, + } +} + +pub fn app_id() -> &'static str { + app_id_for(identity()) +} + +/// The name the window, the About box and the taskbar show. A product name, so it is not +/// translated (the channel is said in text, never only in the art). +pub const fn name_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => tr_noop!("AniCraft"), + LaunchIdentity::NightlyV1 => tr_noop!("AniCraft Nightly"), + } +} + +pub fn name() -> &'static str { + name_for(identity()) +} + +/// Whether the services that belong to one installed copy may run: the updater, the control +/// port, the agent link and the applications-menu entry. Nightly has none of them. +pub fn stable_services_allowed() -> bool { + identity() == LaunchIdentity::Stable +} + /// Main-window chrome. Keep the native title bar on macOS so it cannot cover the egui menu row. /// Windows and Linux use their native frames too. #[cfg(not(target_arch = "wasm32"))] pub fn viewport(b: egui::ViewportBuilder) -> egui::ViewportBuilder { // The Wayland app_id / X11 class: docks match it to the installed desktop entry - // (packaging/linux/ai.storyteller.anicraft.desktop) for the icon and the launcher. - chrome(OS, b.with_app_id(APP_ID).with_icon(app_icon())) + // (packaging/linux/ai.storyteller.anicraft.desktop) for the icon and the launcher. Nightly + // has its own id, so window rules and docks never group the two. + chrome(OS, b.with_app_id(app_id()).with_icon(app_icon())) } /// The window chrome for `os`. The egui menu row is ordinary window content, below the native @@ -711,7 +789,7 @@ fn chrome(_os: Os, b: egui::ViewportBuilder) -> egui::ViewportBuilder { /// it with the editor, and the same icon. Native frames everywhere. pub fn secondary_window(b: egui::ViewportBuilder) -> egui::ViewportBuilder { #[cfg(not(target_arch = "wasm32"))] - return b.with_app_id(APP_ID).with_icon(app_icon()); + return b.with_app_id(app_id()).with_icon(app_icon()); #[cfg(target_arch = "wasm32")] b } @@ -720,11 +798,19 @@ pub fn secondary_window(b: egui::ViewportBuilder) -> egui::ViewportBuilder { /// the tile on Apple's grid (with its transparent margin); elsewhere the full-bleed tile. #[cfg(not(target_arch = "wasm32"))] fn app_icon() -> egui::IconData { - #[cfg(target_os = "macos")] - let png: &[u8] = include_bytes!("../assets/app-icon/anicraft-macos-512.png"); - #[cfg(not(target_os = "macos"))] - let png: &[u8] = include_bytes!("../assets/app-icon/hicolor/256x256/apps/ai.storyteller.anicraft.png"); - eframe::icon_data::from_png_bytes(png).unwrap_or_default() + eframe::icon_data::from_png_bytes(icon_png(identity(), OS == Os::Mac)).unwrap_or_default() +} + +/// The icon bytes for a channel and platform: the Nightly tiles keep the artwork and its Mac +/// padding, with the deeper field (`assets/app-icon/README.md`). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn icon_png(identity: LaunchIdentity, macos: bool) -> &'static [u8] { + match (identity, macos) { + (LaunchIdentity::NightlyV1, true) => include_bytes!("../assets/app-icon/anicraft-nightly-1024.png"), + (LaunchIdentity::NightlyV1, false) => include_bytes!("../assets/app-icon/anicraft-nightly.png"), + (LaunchIdentity::Stable, true) => include_bytes!("../assets/app-icon/anicraft-macos-512.png"), + (LaunchIdentity::Stable, false) => include_bytes!("../assets/app-icon/hicolor/256x256/apps/ai.storyteller.anicraft.png"), + } } /// No extra inset is needed: the menu row sits below the native title bar. @@ -1230,6 +1316,45 @@ pub fn pointer_feel(ctx: &egui::Context) { ctx.options_mut(|o| o.input_options.max_double_click_delay = DOUBLE_CLICK_SECONDS); } +#[cfg(test)] +mod profile_tests { + use super::*; + + /// The package and the window identities are deliberately two different strings: the Launcher + /// matches bundles and assets by the first, and docks, taskbars and window rules by the second. + #[test] + fn the_nightly_package_and_window_identities_are_distinct_and_leave_stable_alone() { + assert_eq!(APP_ID, "ai.storyteller.anicraft"); + assert_eq!(APP_ID_NIGHTLY_PACKAGE, "ai.storyteller.anicraft.nightly"); + assert_eq!(app_id_for(LaunchIdentity::Stable), APP_ID); + assert_eq!(app_id_for(LaunchIdentity::NightlyV1), APP_ID_NIGHTLY); + assert_ne!(APP_ID_NIGHTLY, APP_ID); + assert_ne!(APP_ID_NIGHTLY_PACKAGE, APP_ID_NIGHTLY); + assert!(APP_ID_NIGHTLY_PACKAGE.starts_with(APP_ID)); + // The names differ too, so a window title or About pane always says the channel. + assert_eq!(name_for(LaunchIdentity::Stable), "AniCraft"); + assert_eq!(name_for(LaunchIdentity::NightlyV1), "AniCraft Nightly"); + // And the Nightly tiles are different art from stable's. + assert_ne!(icon_png(LaunchIdentity::NightlyV1, false), icon_png(LaunchIdentity::Stable, false)); + assert_ne!(icon_png(LaunchIdentity::NightlyV1, true), icon_png(LaunchIdentity::Stable, true)); + for identity in [LaunchIdentity::Stable, LaunchIdentity::NightlyV1] { + for macos in [false, true] { + assert!(eframe::icon_data::from_png_bytes(icon_png(identity, macos)).is_ok(), "{identity:?} {macos}"); + } + } + } + + /// A test binary runs its tests in one process, so the process-wide identity is only read + /// here (a test that selected Nightly would change what the other tests see). + #[test] + fn nothing_selects_a_profile_unless_main_does() { + assert_eq!(identity(), LaunchIdentity::Stable); + assert!(stable_services_allowed()); + assert_eq!(app_id(), APP_ID); + assert_eq!(name(), "AniCraft"); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/process_identity.rs b/src/process_identity.rs new file mode 100644 index 00000000..ec650c82 --- /dev/null +++ b/src/process_identity.rs @@ -0,0 +1,74 @@ +//! Set the immutable nightly Windows identity before any native window or COM service, so the +//! taskbar, the Start menu and the Alt-Tab switcher keep Nightly apart from Stable. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged. + +use std::sync::OnceLock; + +#[derive(Clone, Debug)] +pub struct IdentityError(pub String); + +impl std::fmt::Display for IdentityError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id) + .map_err(|error| tr!("cannot set the nightly Windows identity: {e}", e = error))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| tr!("cannot read back the nightly Windows identity: {e}", e = error))?; + if actual != id { + return Err(tr!("the native Windows identity did not match the selected nightly channel").into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } +} diff --git a/src/profile_root.rs b/src/profile_root.rs new file mode 100644 index 00000000..9a6742cb --- /dev/null +++ b/src/profile_root.rs @@ -0,0 +1,679 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! +//! Nightly keeps every piece of user state in one private folder the Launcher created for it: +//! `prefs.json`, `Recovery`, `Logs`, `plugins`, `Templates`, `Commands`, `themes`, `Thumbnails`, +//! the user guide's cache and the Nightly session record (`src/platform.rs`, +//! `src/nightly_session.rs`). This module decides whether a root the Launcher named is really a +//! private place, never an alias of the stable app's data or of the installation itself. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +/// The nightly archive names (`packaging/nightly-common.sh`, `packaging/macos/nightly.sh`). +const ARCHIVE_BINARIES: [&str; 2] = ["anicraft.exe", "anicraft"]; + +/// The environment variables that would move one of Nightly's folders somewhere else, and the +/// Windows/Linux/macOS install folders a profile must never sit in. +const FOLDER_ENV: [&str; 6] = + ["ANICRAFT_RECOVERY_DIR", "ANICRAFT_TEMPLATES_DIR", "ANICRAFT_COMMANDS_DIR", "ANICRAFT_THEMES_DIR", "ANICRAFT_LOG_DIR", "ANICRAFT_PLUGINS"]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Windows, + Linux, + Mac, +} + +impl Platform { + fn current() -> Result { + match std::env::consts::OS { + "windows" => Ok(Self::Windows), + "linux" => Ok(Self::Linux), + "macos" => Ok(Self::Mac), + _ => Err(tr!("nightly-v1 is not defined for this operating system").into()), + } + } + + fn ignores_case(self) -> bool { + self != Self::Linux + } +} + +fn absolute(path: PathBuf, label: &str) -> Result { + if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(tr!("{label} must be absolute and contain no parent traversal", label = label)); + } + Ok(path) +} + +fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { + let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| tr!("cannot establish the stable {key} boundary", key = key))?; + absolute(PathBuf::from(value), key) +} + +fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { + match env(key).filter(|v| !v.is_empty()) { + Some(value) => absolute(PathBuf::from(value), key), + None => Ok(required_base(env, "HOME")?.join(fallback)), + } +} + +/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor +/// is not a missing directory that may be replaced or followed later. +fn canonical_future(path: &Path) -> Result { + let mut parent = path; + let mut missing = Vec::new(); + loop { + match std::fs::symlink_metadata(parent) { + Ok(_) => break, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + missing.push(parent.file_name().ok_or_else(|| tr!("the profile root has no existing ancestor"))?.to_os_string()); + parent = parent.parent().ok_or_else(|| tr!("the profile root has no existing ancestor"))?; + } + Err(error) => return Err(tr!("cannot inspect the profile boundary: {e}", e = error)), + } + } + let mut resolved = std::fs::canonicalize(parent).map_err(|e| tr!("cannot resolve the profile boundary: {e}", e = e))?; + for part in missing.into_iter().rev() { + resolved.push(part); + } + Ok(resolved) +} + +fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { + let parts = |p: &Path| { + p.components() + .map(|c| { + let value = c.as_os_str().to_string_lossy().into_owned(); + if platform.ignores_case() { value.to_lowercase() } else { value } + }) + .collect::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +/// The folder a profile must not sit inside: the installation (a `.app` on macOS), since writing +/// beside the executable would land in a versioned install folder. +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + let parent = exe.parent().ok_or_else(|| tr!("cannot establish the installation boundary"))?; + if platform == Platform::Mac + && let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) + { + return Ok(bundle.to_path_buf()); + } + Ok(parent.to_path_buf()) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + let mut roots = ["APPDATA", "LOCALAPPDATA"] + .into_iter() + .map(|key| required_base(env, key).map(|p| p.join("AniCraft"))) + .collect::, _>>()?; + // The MSI's default folder (packaging/windows/anicraft.wxs): ProgramFiles64\ArtCraft\ + // AniCraft, which a per-user install makes %LOCALAPPDATA%\Programs\ArtCraft\AniCraft. + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("AniCraft")); // i18n-exempt: a path component + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { // i18n-exempt: environment variable names + if let Some(base) = env(key).filter(|v| !v.is_empty()) { + roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("AniCraft")); // i18n-exempt: a path component + } + } + roots + } + Platform::Linux => { + let mut roots = + [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] + .into_iter() + .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("anicraft"))) + .collect::, _>>()?; + roots.extend(["/usr/bin/anicraft", "/usr/local/bin/anicraft", "/opt/anicraft"].map(PathBuf::from)); + // The stable Flatpak keeps its data in its own per-app folder. + roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.anicraft")); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); // i18n-exempt: a path component + vec![ + library.join("Application Support").join("AniCraft"), // i18n-exempt: a path component + library.join("Caches").join("AniCraft"), // i18n-exempt: a path component + library.join("Preferences").join("AniCraft"), // i18n-exempt: a path component + library.join("Preferences").join("ai.storyteller.anicraft.plist"), // i18n-exempt: a path component + library.join("Saved Application State").join("ai.storyteller.anicraft.savedState"), // i18n-exempt: a path component + home.join("Applications").join("AniCraft.app"), // i18n-exempt: a path component + PathBuf::from("/Applications").join("AniCraft.app"), + ] + } + }; + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { + let chosen = canonical_future(&absolute(root.to_path_buf(), tr!("the nightly profile root"))?)?; + let child = canonical_future(&chosen.join(name))?; + if child == chosen || !child.starts_with(&chosen) { + return Err(tr!("the nightly {label} must stay inside its selected profile", label = label)); + } + Ok(child) +} + +/// Every existing entry in the profile, at any depth (prefs, logs, plug-ins, a template category +/// and so on), must resolve inside it, so a link there cannot point Nightly's reads, writes and +/// deletes at another app's data. Links are checked and never followed, so a link cycle cannot +/// loop; a folder that is really inside is walked once, by its own path. +fn entries_stay_inside(root: &Path) -> Result<(), String> { + let mut folders = vec![root.to_path_buf()]; + while let Some(folder) = folders.pop() { + let entries = match std::fs::read_dir(&folder) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound && folder.as_path() == root => return Ok(()), + Err(error) => return Err(tr!("cannot inspect the nightly profile: {e}", e = error)), + }; + for entry in entries { + let entry = entry.map_err(|e| tr!("cannot inspect the nightly profile: {e}", e = e))?; + let kind = entry.file_type().map_err(|e| tr!("cannot inspect the nightly profile: {e}", e = e))?; + if kind.is_symlink() || folder.as_path() == root { + let relative = entry.path().strip_prefix(root).map(Path::to_path_buf).unwrap_or_else(|_| entry.file_name().into()); + private_subdirectory(root, relative, tr!("profile entry"))?; + } + if kind.is_dir() { + folders.push(entry.path()); + } + } + } + Ok(()) +} + +/// Whether `path` is inside a portable copy: [`crate::platform::PORTABLE_MARKER`] beside an +/// AniCraft program, or the `data` folder directly inside such a copy, which is that copy's own +/// settings folder (ADR 0094) and never Nightly's. +fn is_portable_layout(path: &Path, platform: Platform) -> bool { + let marker = |dir: &Path| std::fs::symlink_metadata(dir.join(crate::platform::PORTABLE_MARKER)).is_ok_and(|m| m.is_file()); + for (depth, ancestor) in path.ancestors().enumerate() { + // Above the chosen folder itself, a marker only counts beside an AniCraft program, so an + // unrelated `anicraft-portable` higher up (a user folder, a drive root) refuses nothing. + if marker(ancestor) && (depth == 0 || ARCHIVE_BINARIES.iter().any(|exe| ancestor.join(exe).is_file())) { + return true; + } + } + let mut prefix = PathBuf::new(); + for component in path.components() { + prefix.push(component); + let is_data = match component { + Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(crate::platform::PORTABLE_DATA), + Component::Normal(name) => name == crate::platform::PORTABLE_DATA, + _ => false, + }; + if is_data && prefix.parent().is_some_and(marker) { + return true; + } + } + false +} + +/// The writable hook is the app's own exclusive probe (the one a portable copy uses). +pub fn probe_writable(dir: &Path) -> Result<(), String> { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let probe = dir.join(".anicraft-write-test"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe).map_err(|e| e.to_string())?; + drop(file); + let _ = std::fs::remove_file(&probe); + Ok(()) +} + +/// Whether the root is a private Nightly place. Anything else is refused before Nightly creates +/// a folder, writes a log line or opens a window: there is no fallback to stable's data. +pub fn validate( + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> Result<(), String>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> Result<(), String>, +) -> Result { + absolute(root.to_path_buf(), tr!("the nightly profile root"))?; + for key in FOLDER_ENV { + if env(key).is_some_and(|v| !v.is_empty()) { + return Err(tr!("nightly-v1 cannot be combined with {name}", name = key)); + } + } + let chosen = canonical_future(root)?; + // These rows are native tar/package launches, not a Flatpak package, and inheriting another + // app's runtime namespace could point this profile at its socket or data. The Nightly Flatpak + // is the one instance a Nightly build may run in, and there the profile stays in the app's own + // private home (`packaging/linux/flatpak-bundle.sh`). + if platform != Platform::Windows && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) { + if id != crate::platform::APP_ID_NIGHTLY_PACKAGE { + return Err(tr!("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher").into()); + } + let home = canonical_future(&required_base(&env, "HOME")?)?; + if !chosen.starts_with(&home) { + return Err(tr!("the Nightly Flatpak's profile must stay in its own home").into()); + } + } + if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { + return Err(tr!("the nightly root must not use a portable AniCraft installation or its data folder").into()); + } + let exe = absolute(exe.ok_or_else(|| tr!("cannot establish the installation boundary"))?.to_path_buf(), tr!("the executable"))?; + let forbidden = forbidden_roots(platform, &env, &exe)?; + if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { + return Err(tr!("the nightly root must not overlap stable data or an installation").into()); + } + entries_stay_inside(&chosen)?; + // Recovery can read, adopt, overwrite and sweep entries: never let its alias leave this + // private profile, including toward a stable portable data folder not in our known roots. + private_subdirectory(&chosen, "Recovery", tr!("recovery folder"))?; // i18n-exempt: the profile folder name + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| tr!("cannot create the nightly profile: {e}", e = e))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| tr!("cannot resolve the created nightly profile: {e}", e = e))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err(tr!("the nightly profile changed while it was being validated").into()); + } + private_subdirectory(&confirmed, "Recovery", tr!("recovery folder"))?; // i18n-exempt: the profile folder name + entries_stay_inside(&confirmed)?; + writable(&confirmed).map_err(|e| tr!("the nightly profile is not writable: {e}", e = e))?; + Ok(confirmed) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = loop { + let candidate = + std::env::temp_dir().join(format!("anicraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&candidate) { + Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + }; + let home = root.join("home"); + let exe = root.join("install/anicraft"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"fixture executable, never run").unwrap(); + let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] + .into_iter() + .map(|(key, value)| (key.into(), value.into_os_string())) + .collect(); + Self { root, env, exe } + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + validate_for(platform, root, |key| self.get(key), Some(&self.exe), probe) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + } + + /// An exclusive probe like the app's, without global state. + fn probe(dir: &Path) -> Result<(), String> { + let probe = dir.join("exclusive-test-probe"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe).map_err(|e| e.to_string())?; + drop(file); + std::fs::remove_file(probe).map_err(|e| e.to_string()) + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory successfully created by this fixture is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn portable_settings_from_another_install_are_refused_before_any_probe() { + let fixture = Fixture::new(); + let stable_install = fixture.root.join("stable portable install"); + let stable_data = stable_install.join(crate::platform::PORTABLE_DATA); + std::fs::create_dir_all(&stable_data).unwrap(); + std::fs::write(stable_install.join(crate::platform::PORTABLE_MARKER), b"owned portable fixture").unwrap(); + std::fs::write(stable_data.join("prefs.json"), b"stable settings must not change").unwrap(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + for candidate in [&stable_data, &stable_data.join("nested nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "a different portable install is not a private Nightly profile"); + assert!(!probed.get(), "reject portable data before a writable probe"); + assert!(!stable_data.join("nested nightly").exists()); + assert_eq!(std::fs::read(stable_data.join("prefs.json")).unwrap(), b"stable settings must not change"); + assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1); + } + } + let private = fixture.root.join("AniCraftData-backup-name/nightly"); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable data component"); + } + + #[cfg(unix)] + #[test] + fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".local/state/anicraft/Recovery"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap(); + for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() { + let private = fixture.root.join(format!("nightly-{index}")); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap(); + let probed = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &private, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias"); + assert!(!probed.get()); + } + let private = fixture.root.join("nightly-self"); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries"); + assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes"); + assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1); + } + + #[cfg(unix)] + #[test] + fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() { + let fixture = Fixture::new(); + let private = fixture.root.join("nightly-private"); + let recovery = private.join("private-recovery"); + std::fs::create_dir_all(&recovery).unwrap(); + std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok()); + assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery); + } + + #[test] + fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { + let fixture = Fixture::new(); + let root = fixture.home().join("nightly/profiles/anicraft"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(overlaps(&root, &root.join("Recovery"), platform)); + assert!(overlaps(&root.join("Recovery"), &root, platform)); + assert!(!overlaps(&root, &root.with_file_name("anicraft-other"), platform)); + } + } + + #[test] + fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() { + let mut fixture = Fixture::new(); + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + fixture.env.insert(key.into(), fixture.root.join(key).into_os_string()); + } + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("anicraft"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap(); + for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); + } + assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes"); + } + let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()); + let nightly = data.join("ArtCraftLauncher/nightly/profiles/anicraft"); + assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly); + assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0); + } + + #[test] + fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() { + let mut fixture = Fixture::new(); + fixture.exe = fixture.root.join("install/AniCraft Nightly.app/Contents/MacOS/AniCraft"); + std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap(); + std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap(); + let library = fixture.home().join("Library"); + for suffix in + ["Application Support/AniCraft", "Caches/AniCraft", "Preferences/AniCraft", "Saved Application State/ai.storyteller.anicraft.savedState"] + { + let stable = library.join(suffix); + assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap")); + assert!(!stable.exists()); + } + let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile"); + assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap")); + assert!(!inside_resources.exists()); + let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/anicraft"); + assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid); + } + + #[test] + fn windows_roaming_local_and_install_fences_remain_active() { + let fixture = Fixture::new(); + for key in ["APPDATA", "LOCALAPPDATA"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("AniCraft"); + assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap")); + assert!(!stable.exists()); + } + assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err()); + assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/anicraft")).is_ok()); + } + + #[test] + fn windows_default_msi_install_folders_are_fenced() { + let mut fixture = Fixture::new(); + let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()); + let per_user = local.join("Programs").join("ArtCraft").join("AniCraft"); + assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap")); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + let base = fixture.root.join(format!("machine {key}")); + fixture.env.insert(key.into(), base.clone().into_os_string()); + let machine = base.join("ArtCraft").join("AniCraft"); + assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap")); + assert!(!machine.exists()); + } + let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("anicraft"); + assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not AniCraft's install"); + } + + #[test] + fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() { + let fixture = Fixture::new(); + let portable = fixture.root.join("D/AC"); + std::fs::create_dir_all(&portable).unwrap(); + std::fs::write(portable.join(crate::platform::PORTABLE_MARKER), b"stable portable copy").unwrap(); + std::fs::write(portable.join("anicraft.exe"), b"stable portable executable, never run").unwrap(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.unwrap_err().contains("portable")); + assert!(!probed.get()); + assert!(!candidate.exists()); + } + } + // An `anicraft-portable` that no AniCraft executable sits beside is someone else's file. + let unrelated = fixture.root.join("user folder"); + std::fs::create_dir_all(&unrelated).unwrap(); + std::fs::write(unrelated.join(crate::platform::PORTABLE_MARKER), b"another app's marker").unwrap(); + assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/anicraft")).is_ok()); + } + + #[test] + fn linux_fences_the_stable_flatpak_data_folder() { + let fixture = Fixture::new(); + let flatpak = fixture.home().join(".var/app/ai.storyteller.anicraft"); + for candidate in [flatpak.clone(), flatpak.join("data/nightly")] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); + } + assert!(!flatpak.exists()); + assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); + } + + #[cfg(unix)] + #[test] + fn any_profile_entry_alias_must_stay_inside_the_profile() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".config/anicraft/Templates"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-template"), b"stable template bytes").unwrap(); + for name in ["Templates", "Logs", "prefs.json"] { + let private = fixture.root.join(format!("nightly-{name}")); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&stable, private.join(name)).unwrap(); + let probed = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &private, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "{name} must not lead outside the profile"); + assert!(!probed.get()); + } + // A link one level down is as dangerous as one in the profile's own folder: Templates is a + // real folder here, but its category leads into the stable app's templates. + let private = fixture.root.join("nightly-nested"); + std::fs::create_dir_all(private.join("Templates")).unwrap(); + std::os::unix::fs::symlink(&stable, private.join("Templates").join("Characters")).unwrap(); + let probed = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &private, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "a nested link must not lead outside the profile"); + assert!(!probed.get()); + let private = fixture.root.join("nightly-nested-inside"); + std::fs::create_dir_all(private.join("Templates/real")).unwrap(); + std::os::unix::fs::symlink(private.join("Templates/real"), private.join("Templates/Characters")).unwrap(); + std::os::unix::fs::symlink(&private, private.join("Templates/real/loop")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_err(), "a link back to the profile's own folder is refused, not looped on"); + std::fs::remove_file(private.join("Templates/real/loop")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "a nested link that stays inside is fine"); + let private = fixture.root.join("nightly-inside"); + std::fs::create_dir_all(private.join("real-templates")).unwrap(); + std::fs::write(private.join("prefs.json"), b"{}").unwrap(); + std::os::unix::fs::symlink(private.join("real-templates"), private.join("Templates")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine"); + assert_eq!(std::fs::read(stable.join("stable-template")).unwrap(), b"stable template bytes"); + } + + #[test] + fn inherited_folder_overrides_and_non_native_sandbox_are_refused_before_creation() { + let mut fixture = Fixture::new(); + let candidate = fixture.home().join("nightly/profiles/anicraft"); + fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); + fixture.env.remove("XDG_CACHE_HOME"); + for key in FOLDER_ENV { + fixture.env.insert(key.into(), fixture.home().join("moved").into_os_string()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains(key), "{key}"); + fixture.env.remove(key); + } + fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.anicraft".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); + // The Nightly Flatpak itself is a supported format, as long as its profile stays in the + // sandbox's own home; anything else keeps the inheritance refusal. + fixture.env.insert("FLATPAK_ID".into(), crate::platform::APP_ID_NIGHTLY_PACKAGE.into()); + let in_sandbox = fixture.home().join("sandbox-home/anicraft-nightly/profile"); + assert_eq!(fixture.check(Platform::Linux, &in_sandbox).unwrap(), std::fs::canonicalize(&in_sandbox).unwrap()); + let outside = fixture.root.join("outside-the-sandbox").join("anicraft-nightly"); + let probed = std::cell::Cell::new(false); + let result = validate_for(Platform::Linux, &outside, |key| fixture.get(key), Some(&fixture.exe), |_| { + probed.set(true); + Ok(()) + }); + assert!(result.unwrap_err().contains("own home")); + assert!(!probed.get() && !outside.exists()); + fixture.env.remove("FLATPAK_ID"); + fixture.env.remove("HOME"); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); + assert!(!candidate.exists()); + } + + #[test] + fn non_directory_and_failed_write_probe_never_fall_back_to_stable() { + let fixture = Fixture::new(); + let file = fixture.home().join("not-a-directory"); + std::fs::write(&file, b"a file where the profile should be").unwrap(); + assert!(fixture.check(Platform::Linux, &file).is_err()); + let candidate = fixture.home().join("nightly-profile"); + let result = validate_for(Platform::Linux, &candidate, |key| fixture.get(key), Some(&fixture.exe), |_| Err("read-only medium".into())); + assert!(result.unwrap_err().contains("not writable")); + assert!(candidate.is_dir(), "no fallback folder is created elsewhere"); + assert!(!fixture.home().join(".config/anicraft").exists(), "stable's settings folder is never made"); + } + + #[test] + fn windows_and_macos_compare_like_paths_case_insensitively() { + let fixture = Fixture::new(); + for (platform, stable) in [ + (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join("AniCraft")), + (Platform::Mac, fixture.home().join("Library").join("Application Support").join("AniCraft")), + ] { + let shouty = stable.with_file_name("ANICRAFT"); + assert!(fixture.check(platform, &shouty.join("Nightly")).unwrap_err().contains("overlap"), "{shouty:?}"); + } + // Linux paths are case-sensitive: a differently cased folder is another folder. + let linux = fixture.home().join(".config/AniCraft/nightly"); + assert!(fixture.check(Platform::Linux, &linux).is_ok()); + } +} diff --git a/src/stage.rs b/src/stage.rs index 2118cbe6..98c418c8 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -5,6 +5,13 @@ //! frame asks for the visible tiles as one batch (plus a one-tile margin as look-ahead), keeps //! finished tiles as textures, and draws any older tiles that cover a gap (previous zoom or //! state, scaled) underneath, so panning and zooming never reveal an empty stage. +//! +//! Memory and frame time stay flat (ADR 0132). The pictures of a document state and zoom that +//! are no longer on screen go as soon as the view is drawn again, here and in the render +//! service. While the zoom is changing (a pinch, Ctrl+wheel) nothing new is drawn: every frame +//! of it is a zoom level nobody will look at, so the pictures on screen are scaled until the +//! zoom rests. With no render thread (the browser) moving around the stage draws for at most +//! `INLINE_BUDGET` of a frame. use crate::app::{App, Drag, Tool, XfKind}; use crate::prefs::RenderMode; @@ -27,10 +34,15 @@ const IMMEDIATE_BUDGET_MS: f32 = 12.0; pub const TILE: u32 = 512; /// Tile textures kept on the GPU (≈ 1 MB each); least recently used ones are dropped. const MAX_TILE_TEXTURES: usize = 192; +/// With no render thread (the browser): the most of one frame spent drawing tiles while +/// moving around the stage. The rest of the view arrives over the next frames. +const INLINE_BUDGET: std::time::Duration = std::time::Duration::from_millis(8); /// A finished tile on the GPU. struct TileTex { key: u64, + /// The picture set it is of (a document state at a zoom, ADR 0132). + set: u64, /// Stage-space rectangle `[x0, y0, x1, y1]` this tile covers. rect: [f32; 4], tex: TileImage, @@ -65,6 +77,11 @@ pub struct Cache { pub service: Option, /// Document state of the picture on screen (an edit makes it differ). pub shown_state: Option, + /// Movie frame of the picture on screen (playing or scrubbing makes it differ). + shown_frame: Option, + /// The device scale the stage was laid out at last frame: while it differs from this + /// frame's the zoom is still changing, and no tiles are asked for. + last_scale: Option, /// The GPU stage (ADR 0019), when this build has it and Preferences ask for it. pub gpu: crate::gpu_stage::GpuStage, /// Who drew the newest visible tiles: the GPU, or the CPU and why (status bar). @@ -75,7 +92,7 @@ pub struct Cache { impl Default for Cache { fn default() -> Self { - Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), laid_out: false, service: None, shown_state: None, gpu: Default::default(), drawn_by: None, pattern: None } + Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), laid_out: false, service: None, shown_state: None, shown_frame: None, last_scale: None, gpu: Default::default(), drawn_by: None, pattern: None } } } @@ -95,6 +112,8 @@ impl Cache { pub fn forget_document(&mut self) { self.tiles.clear(); self.shown_state = None; + self.shown_frame = None; + self.last_scale = None; self.ready = (0, 0); if let Some(s) = &self.service { s.forget_pictures(); @@ -139,7 +158,7 @@ impl Cache { } }; self.tick += 1; - self.tiles.push(TileTex { key: img.key, rect, tex, used: self.tick }); + self.tiles.push(TileTex { key: img.key, set: img.set, rect, tex, used: self.tick }); // Evict least recently used tiles that are not on screen. while self.tiles.len() > MAX_TILE_TEXTURES { let victim = self.tiles.iter().enumerate().filter(|(_, t)| !keep.contains(&t.key)).min_by_key(|(_, t)| t.used).map(|(i, _)| i); @@ -1051,8 +1070,24 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview).inside(pic.front.clone()).with_reference(reference.clone()); (t, j) }).collect(); let keys: Vec = jobs.iter().map(|(_, j)| j.key).collect(); let missing: Vec = (0..jobs.len()).filter(|&i| !app.stage_cache.has(keys[i])).collect(); + let set = jobs.first().map(|(_, j)| j.set); + // A zoom that is still changing draws nothing new: this frame's zoom level is gone by + // the next, so its tiles would never be looked at (and in the browser they would be + // drawn inside this frame). The pictures on screen are scaled until the zoom rests, + // one frame from now at the soonest. + let zooming = app.stage_cache.last_scale.is_some_and(|was| was != z); + app.stage_cache.last_scale = Some(z); + if zooming { + ui.ctx().request_repaint(); + } else if let (Some(set), Some(svc)) = (set, &app.stage_cache.service) { + // The picture set on screen (this state at this zoom): the render service keeps it + // and the one before, and lets the pictures of every other go (ADR 0132). A zoom + // level passed through on the way is not one of them. + svc.show(set); + } if !missing.is_empty() + && !zooming && let Some(svc) = &app.stage_cache.service { // Latency vs throughput (ADR 0006): an edit (the document changed under the picture @@ -1069,8 +1104,18 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { RenderMode::Auto => app.stage_cache.ms <= IMMEDIATE_BUDGET_MS, }; let batch: Vec = missing.iter().map(|&i| jobs[i].1.clone()).collect(); + // Moving around the picture already on screen (a pan, a zoom come to rest): with + // no render thread the tiles come a few a frame, nearest the centre first, so the + // frame stays short. An edit or another frame is one whole picture, drawn at once. + let moving = app.stage_cache.shown_state == Some(state) && app.stage_cache.shown_frame == Some(pic.frame); let started = web_time::Instant::now(); - let results: Vec>> = if immediate { svc.render_now_batch(batch).into_iter().map(Some).collect() } else { svc.request_batch(batch) }; + let results: Vec>> = if immediate { + svc.render_now_batch(batch).into_iter().map(Some).collect() + } else if moving { + svc.request_batch_within(batch, INLINE_BUDGET) + } else { + svc.request_batch(batch) + }; let wall = started.elapsed().as_secs_f32() * 1000.0; let mut ms = 0.0f32; let mut error = None; @@ -1103,11 +1148,20 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.stage_cache.ready = (ready, keys.len()); if ready == keys.len() { app.stage_cache.shown_state = Some(state); + app.stage_cache.shown_frame = Some(pic.frame); + // The view is whole: tiles of other states and zooms were only standing in for + // it, so their textures go now instead of when 192 newer ones have pushed them out. + if let Some(set) = set { + app.stage_cache.tiles.retain(|t| t.set == set); + } + } else if !zooming && app.stage_cache.service.as_ref().is_some_and(|s| !s.has_thread()) { + // No render thread tells us when the rest is ready: it is drawn next frame. + ui.ctx().request_repaint(); } // Look-ahead: the ring of tiles around the view (a pan reveals them instantly) and, // during playback, the next frames' visible tiles. - if let Some(svc) = &app.stage_cache.service { + if let Some(svc) = app.stage_cache.service.as_ref().filter(|_| !zooming) { let mut ahead: Vec = Vec::new(); if app.playing && !editing { let n = app.s.frame_count().max(1); diff --git a/src/stage_budget_tests.rs b/src/stage_budget_tests.rs new file mode 100644 index 00000000..717ac897 --- /dev/null +++ b/src/stage_budget_tests.rs @@ -0,0 +1,165 @@ +//! The stage keeps memory and frame time flat (P-004, ADR 0132; #314, #477), driven frame by +//! frame through the real app: a zoom gesture draws nothing until it rests, and editing or +//! zooming for a long time holds no more pictures than the view on screen needs. +//! `stage_memory_and_frame_times` prints the numbers. + +use crate::app::App; +use egui::{Event, Pos2, Rect, vec2}; +use serde_json::json; + +fn frame(ctx: &egui::Context, app: &mut App, time: f64, events: Vec) -> f64 { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(time), events, ..Default::default() }; + let t = std::time::Instant::now(); + ctx.run_ui(input, |ui| app.frame(ui)).textures_delta.clear(); + t.elapsed().as_secs_f64() * 1000.0 +} + +/// The app showing the sample, the pointer over the stage, the view drawn. +fn sample_app(ctx: &egui::Context) -> (App, f64) { + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let mut app = App::with_context(ctx, session, Some(std::path::PathBuf::from("unused.png"))); + let mut t = 0.0; + for _ in 0..3 { + t += 0.016; + frame(ctx, &mut app, t, vec![]); + } + let at = app.stage_cache.canvas.center(); + frame(ctx, &mut app, t, vec![Event::PointerMoved(at)]); + assert!(drawn(ctx, &mut app, &mut t), "the first view was drawn"); + (app, t) +} + +/// Frames until every tile of the view is on screen and the render thread has nothing left to +/// draw (the look-ahead ring around the view too); whether that happened. +fn drawn(ctx: &egui::Context, app: &mut App, t: &mut f64) -> bool { + for _ in 0..30_000 { + *t += 0.016; + frame(ctx, app, *t, vec![]); + let (ready, needed) = app.stage_cache.ready; + if needed > 0 && ready == needed && app.stage_cache.service.as_ref().is_some_and(|s| !s.busy()) { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + false +} + +/// `(pictures, bytes, pictures asked for and not found)` of the render service's cache. +fn cache(app: &App) -> (usize, usize, u64) { + let (n, bytes, _, misses) = app.stage_cache.service.as_ref().map(|s| s.cache_stats()).unwrap_or_default(); + (n, bytes, misses) +} + +/// #477: every frame of a Ctrl+wheel or pinch zoom is a zoom level of its own. Each one's +/// tiles used to be asked for, drawn (in the browser, inside the frame) and kept, though the +/// next frame no longer wanted them. Now nothing is asked for until the zoom rests; then the +/// view is drawn once and the stand-in tiles of the old zoom go. +#[test] +fn a_zoom_gesture_draws_nothing_until_it_rests() { + let ctx = egui::Context::default(); + let (mut app, mut t) = sample_app(&ctx); + let (zoom, before) = (app.view.zoom, cache(&app)); + for _ in 0..40 { + t += 0.016; + frame(&ctx, &mut app, t, vec![Event::Zoom(1.05)]); + assert!(app.stage_cache.tile_count() > 0, "the pictures of the old zoom stand in"); + } + assert!(app.view.zoom > zoom * 4.0, "the view zoomed in: {} to {}", zoom, app.view.zoom); + assert_eq!(cache(&app), before, "nothing was asked for or drawn while the zoom was changing"); + // At rest: drawn, and only this view's tiles are held. + assert!(drawn(&ctx, &mut app, &mut t)); + let needed = app.stage_cache.ready.1; + assert!(cache(&app).2 > before.2, "the view at the new zoom was asked for"); + assert_eq!(app.stage_cache.tile_count(), needed, "the old zoom's textures are gone"); +} + +/// #314: a long drag is hundreds of document states. The textures and cached pictures after +/// many moves are what they were after a few: the view on screen and the state before it. +#[test] +fn editing_for_long_holds_no_more_pictures_than_editing_briefly() { + let ctx = egui::Context::default(); + let (mut app, mut t) = sample_app(&ctx); + app.run("edit.select_all", json!({})); + let mut held = Vec::new(); + for step in 0..40 { + assert!(app.run("element.translate", json!({"dx": 3, "dy": if step % 2 == 0 { 2 } else { -2 }})).is_some()); + assert!(drawn(&ctx, &mut app, &mut t), "move {step} was drawn"); + let needed = app.stage_cache.ready.1; + assert_eq!(app.stage_cache.tile_count(), needed, "move {step}: one view of textures"); + held.push(cache(&app).1); + } + // The view and the ring around it, for this state and the one before: reached after two + // moves, and never more however many follow. + let (early, late) = (held.iter().take(5).max(), held.iter().skip(5).max()); + assert!(late <= early, "the cache held {early:?} bytes within 5 moves and {late:?} after 40"); +} + +/// This process's memory in use (MB), where the system says (Windows, Linux). +fn resident_mb() -> Option { + let pid = std::process::id(); + if cfg!(windows) { + let out = std::process::Command::new("tasklist").args(["/FI", &format!("PID eq {pid}"), "/FO", "CSV", "/NH"]).output().ok()?; + let text = String::from_utf8_lossy(&out.stdout).to_string(); + let kb: String = text.trim().rsplit('"').nth(1)?.chars().filter(char::is_ascii_digit).collect(); + Some(kb.parse::().ok()? / 1024.0) + } else { + let text = std::fs::read_to_string("/proc/self/statm").ok()?; + Some(text.split_whitespace().nth(1)?.parse::().ok()? * 4096.0 / 1048576.0) + } +} + +/// Memory and frame times over a long session, on the CPU stage: +/// `cargo test --release --bin anicraft stage_memory_and_frame_times -- --ignored --nocapture`. +#[test] +#[ignore = "a measurement, not a check"] +fn stage_memory_and_frame_times() { + let ctx = egui::Context::default(); + let (mut app, mut t) = sample_app(&ctx); + let report = |what: &str, app: &App, ms: f64, worst: f64| { + let (n, bytes, _) = cache(app); + println!("{what:<34} {ms:>6.2} ms a frame (worst {worst:>6.2}) cache {n:>4} pictures {:>7.1} MB textures {:>3} process {:>7.1} MB", bytes as f64 / 1048576.0, app.stage_cache.tile_count(), resident_mb().unwrap_or(0.0)); + }; + report("at rest", &app, 0.0, 0.0); + // A drag of 300 pointer moves. + app.run("edit.select_all", json!({})); + let (mut sum, mut worst) = (0.0f64, 0.0f64); + for step in 0..300 { + app.run("element.translate", json!({"dx": if step % 2 == 0 { 2 } else { -2 }, "dy": 0})); + t += 0.016; + let ms = frame(&ctx, &mut app, t, vec![]); + sum += ms; + worst = worst.max(ms); + } + report("a drag of 300 moves", &app, sum / 300.0, worst); + // Playing the movie five times over. + app.run("edit.deselect", json!({})); + let frames = app.s.frame_count().max(1); + let (mut sum, mut worst, mut n) = (0.0f64, 0.0f64, 0u32); + for lap in 0..5 { + for f in 0..frames { + app.s.set_frame(f); + t += 0.016; + let ms = frame(&ctx, &mut app, t, vec![]); + if lap == 0 { + drawn(&ctx, &mut app, &mut t); + } else { + sum += ms; + worst = worst.max(ms); + n += 1; + } + } + report(&format!("played {} frames, lap {}", frames, lap + 1), &app, sum / f64::from(n.max(1)), worst); + } + // Zooming in to the limit, a notch a frame, resting every 12 frames. + while app.view.zoom < 63.0 { + let (mut sum, mut worst) = (0.0f64, 0.0f64); + for _ in 0..12 { + t += 0.016; + let ms = frame(&ctx, &mut app, t, vec![Event::Zoom(1.06)]); + sum += ms; + worst = worst.max(ms); + } + drawn(&ctx, &mut app, &mut t); + report(&format!("zoomed to {:.0} %", app.view.zoom * 100.0), &app, sum / 12.0, worst); + } +} diff --git a/src/start.rs b/src/start.rs index 2e870038..37b52468 100644 --- a/src/start.rs +++ b/src/start.rs @@ -101,8 +101,12 @@ fn header(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context) { ui.add(egui::Image::new((crate::app::app_mark(ctx).id(), vec2(44.0, 44.0)))); ui.add_space(8.0); ui.vertical(|ui| { - ui.label(text(Type::Title, "AniCraft")); // i18n-exempt: the product name - ui.label(text(Type::Caption, tr!("Version {version} · {stage}", version = env!("CARGO_PKG_VERSION"), stage = crate::i18n::t(crate::app::RELEASE_STAGE)))); + ui.label(text(Type::Title, crate::platform::name())); + if crate::platform::stable_services_allowed() { + ui.label(text(Type::Caption, tr!("Version {version} · {stage}", version = env!("ANICRAFT_BUILT_VERSION"), stage = crate::i18n::t(crate::app::RELEASE_STAGE)))); + } else { + ui.label(text(Type::Caption, tr!("Version {version}", version = env!("ANICRAFT_BUILT_VERSION")))); + } }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let back = ui.add(egui::Button::new(tr!("Back to the document")).shortcut_text(text(Type::Key, "Esc"))); // i18n-exempt: a key name diff --git a/src/startup.rs b/src/startup.rs index 52e559c0..db14fbcd 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -267,7 +267,7 @@ pub fn begin(dir: Option) -> Vec { previous(info); })); let unix = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); - line(&format!("AniCraft {} ({}), {} {}, started at {unix} (Unix time)", env!("CARGO_PKG_VERSION"), crate::app::RELEASE_STAGE, std::env::consts::OS, std::env::consts::ARCH)); + line(&format!("{} {} ({}), {} {}, started at {unix} (Unix time)", crate::platform::name(), env!("ANICRAFT_BUILT_VERSION"), crate::app::RELEASE_STAGE, std::env::consts::OS, std::env::consts::ARCH)); if let Some((l, left)) = &lost { line(&format!("a session lost its graphics device with {l}: trying it late ({left} more start(s) counting this one)")); } diff --git a/src/updates.rs b/src/updates.rs index 4d449999..72d4b92c 100644 --- a/src/updates.rs +++ b/src/updates.rs @@ -9,6 +9,11 @@ const VERSION: &str = env!("CARGO_PKG_VERSION"); /// A pinned, nightly, or unknown launcher choice must never be replaced by a stable update. fn stable_choice() -> Result<(), String> { + // The Nightly build's version is the Launcher's alone (`docs/nightly-release-preparation.md`), + // so its own updates are off whatever the pins say: it never reads the shared pins store. + if !crate::platform::stable_services_allowed() { + return Err(tr!("AniCraft Nightly is updated by ArtCraft Launcher. Change its version there.").into()); + } if Pins::load_default().choice(APP.id) == Choice::Stable { Ok(()) } else {