Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6693ad6c5 | ||
|
|
6dbad8d73f | ||
|
|
755e0ae1d0 | ||
|
|
244d3ef9a3 | ||
|
|
80ac2c61a5 | ||
|
|
d757bf455c | ||
|
|
40d42a4d99 | ||
|
|
7bb417c86c | ||
|
|
d3f85d3425 | ||
|
|
058ae8be0c | ||
|
|
e19fb2c761 | ||
|
|
2b4b9f9e37 | ||
|
|
c49c9b66ad | ||
|
|
004f813255 | ||
|
|
53f6395939 | ||
|
|
80518a9e93 | ||
|
|
6d2c43eb11 | ||
|
|
b75ca75b70 | ||
|
|
b1c8213e3e | ||
|
|
e93839b45b | ||
|
|
904183956c | ||
|
|
d2a2799180 | ||
|
|
f5f1f7500d | ||
|
|
e5a952f221 | ||
|
|
c7be52fd7b | ||
|
|
a0d7e69509 | ||
|
|
97f6465d27 | ||
|
|
4903caf607 | ||
|
|
6cbb364c47 | ||
|
|
e140792243 | ||
|
|
45bbb923ca | ||
|
|
e41df5dcc6 | ||
|
|
67d63c9cb6 | ||
|
|
55e654508d | ||
|
|
20edc6db9c | ||
|
|
f8426f7c73 | ||
|
|
09f2aa86c9 | ||
|
|
e8594214a6 | ||
|
|
e3481ba30f | ||
|
|
5841794413 | ||
|
|
549872d581 | ||
|
|
89d356040d | ||
|
|
02601a6696 | ||
|
|
9216224da7 | ||
|
|
70b05d585e | ||
|
|
2760ba162a | ||
|
|
3d5661f1a4 | ||
|
|
10feef0941 | ||
|
|
4e2119ac22 | ||
|
|
2e2bae31f3 | ||
|
|
7ccefe55da | ||
|
|
a76516a5d3 | ||
|
|
1b12719e11 | ||
|
|
3a62cd55b6 | ||
|
|
a0f8946692 | ||
|
|
fb5d8d0af8 | ||
|
|
37f11bfe0b | ||
|
|
f687a500e7 | ||
|
|
7d5789d34d | ||
|
|
732f28e025 | ||
|
|
f4725cbf21 | ||
|
|
f52111be88 | ||
|
|
cd64689a93 | ||
|
|
d53446a2a6 | ||
|
|
e6aa902016 | ||
|
|
bfd38fca73 | ||
|
|
0788c12f40 | ||
|
|
3c405887b8 | ||
|
|
0c747f2c49 | ||
|
|
bc5606e32c | ||
|
|
37a0d8b0a7 | ||
|
|
8452563b03 | ||
|
|
96932541db | ||
|
|
a442fe0621 | ||
|
|
d6ebf18af2 | ||
|
|
84b3fd552a | ||
|
|
1239df4855 | ||
|
|
476e38ca41 | ||
|
|
0b07d0d374 | ||
|
|
48d2216394 | ||
|
|
bd5f4a4ccb | ||
|
|
9d050ff20b | ||
|
|
6e835a5dad | ||
|
|
4592ce5d95 | ||
|
|
1889eff0b7 | ||
|
|
e4c52c82fe | ||
|
|
3fa55eb32f | ||
|
|
11fce1e7db | ||
|
|
3616bce66d | ||
|
|
de3144d420 | ||
|
|
34768b446a | ||
|
|
465a962f58 | ||
|
|
addc24b60c | ||
|
|
46113fc833 | ||
|
|
34cc6c7481 | ||
|
|
401181824c | ||
|
|
0770c94f84 | ||
|
|
df26351d07 | ||
|
|
98851c8ddd | ||
|
|
c4c7563c20 | ||
|
|
22da143027 | ||
|
|
a3a87aa868 | ||
|
|
9f7f8896f3 | ||
|
|
6e53534df7 | ||
|
|
63367ececb | ||
|
|
e9c6684b40 | ||
|
|
57dc367b73 | ||
|
|
09bd3db9a3 | ||
|
|
c6b9cdd3ce | ||
|
|
0e2bb2f835 | ||
|
|
ef2d78c7ff | ||
|
|
215992c6b3 | ||
|
|
fab417e5b1 | ||
|
|
a460ffb25c | ||
|
|
9929ecd025 | ||
|
|
df9e62322e | ||
|
|
d1552d1bd4 | ||
|
|
f82794763c | ||
|
|
14d223de5a | ||
|
|
e5be6cda81 | ||
|
|
6b2723e651 | ||
|
|
f83228f6d2 | ||
|
|
2ef86dc304 | ||
|
|
893041b7fc | ||
|
|
84f32dbeaa | ||
|
|
81f4c26f4c | ||
|
|
1b60ce62db | ||
|
|
73d4ba84de |
No files matched your search
@@ -0,0 +1,189 @@
|
||||
name: Android
|
||||
|
||||
# Arcade's own Android APKs, with the whole library for offline play, for an
|
||||
# Arcade release (node-arcade-VERSION). Game updates starts this on the new
|
||||
# release's tag; started by hand on master, it fills in the APKs of the
|
||||
# release master is at. Three signed editions are attached: arcade-VERSION.apk
|
||||
# and arcade-VERSION-fdroid.apk hold no Google library, arcade-VERSION-gplay.apk
|
||||
# is the only one with Play Billing.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: Arcade release version; empty uses VERSION at the chosen ref
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: arcade-android-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
version: ${{ steps.release.outputs.version }}
|
||||
due: ${{ steps.release.outputs.due }}
|
||||
toolchain: ${{ steps.release.outputs.toolchain }}
|
||||
shovey: ${{ steps.release.outputs.shovey }}
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
- name: Find the release and its locked dependencies
|
||||
id: release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
REQUESTED: ${{ inputs.version }}
|
||||
run: |
|
||||
set -eu
|
||||
version=$(cat VERSION)
|
||||
if [ -n "$REQUESTED" ] && [ "$REQUESTED" != "$version" ]; then
|
||||
echo "::error::$GITHUB_REF is at Arcade $version, not $REQUESTED"
|
||||
exit 1
|
||||
fi
|
||||
# The APKs carry exactly the release's catalog and games.
|
||||
gh release view "node-arcade-$version" --json name > /dev/null
|
||||
assets=$(gh release view "node-arcade-$version" --json assets --jq '.assets[].name')
|
||||
due=false
|
||||
for name in "arcade-$version.apk" "arcade-$version-fdroid.apk" "arcade-$version-gplay.apk"; do
|
||||
printf '%s\n' "$assets" | grep -qxF "$name" || due=true
|
||||
done
|
||||
if [ "$due" = false ]; then
|
||||
echo "::notice title=Android::Arcade $version already has its APKs"
|
||||
fi
|
||||
python3 - <<'PY' >> "$GITHUB_OUTPUT"
|
||||
import json
|
||||
lock = json.load(open('ziran.lock'))
|
||||
shovey = lock['root']['dependencies']['shovey']
|
||||
print('toolchain=' + lock['toolchain']['commit'])
|
||||
print('shovey=' + next(p['commit'] for p in lock['packages'] if p['id'] == shovey))
|
||||
PY
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "due=$due" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build:
|
||||
needs: release
|
||||
if: needs.release.outputs.due == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 90
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
edition: [direct, fdroid, gplay]
|
||||
defaults:
|
||||
run:
|
||||
working-directory: waozixyz/arcade
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
path: waozixyz/arcade
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
repository: ziranlang/ziran
|
||||
ref: ${{ needs.release.outputs.toolchain }}
|
||||
path: ziranlang/ziran
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
repository: waozixyz/shovey
|
||||
ref: ${{ needs.release.outputs.shovey }}
|
||||
path: waozixyz/shovey
|
||||
# Only the Google Play edition may name a Google library, in its build
|
||||
# files as in its APK.
|
||||
- name: Keep Google libraries out of the normal and F-Droid build files
|
||||
if: matrix.edition != 'gplay'
|
||||
uses: kryonlabs/kryon/.github/actions/google-free@7217475dfa7f462939e47e3f0bc918aef248b179
|
||||
with:
|
||||
source: waozixyz/arcade
|
||||
- name: Install build dependencies
|
||||
working-directory: .
|
||||
run: |
|
||||
sh ziranlang/ziran/scripts/ci_packages.sh build-essential cmake pkg-config python3-pil python3-numpy python3-cryptography
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- name: Install the Android SDK parts Kryon's Android host needs
|
||||
working-directory: .
|
||||
run: |
|
||||
sdkmanager="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
|
||||
yes | "$sdkmanager" --licenses > /dev/null
|
||||
"$sdkmanager" --install 'ndk;28.2.13676358' 'build-tools;36.0.0' 'platforms;android-36' 'cmake;3.22.1' > /dev/null
|
||||
- name: Build the locked toolchain and fetch packages
|
||||
run: |
|
||||
make -j2 -C ../../ziranlang/ziran
|
||||
echo "$GITHUB_WORKSPACE/ziranlang/ziran/build/bin" >> "$GITHUB_PATH"
|
||||
# The game is generated in its own checkout at the locked release.
|
||||
printf '[overrides]\nshovey = "../shovey"\nziran = "../../ziranlang/ziran"\n' > ziran.local.toml
|
||||
../../ziranlang/ziran/build/bin/ziran fetch
|
||||
- name: Build the APK
|
||||
env:
|
||||
EDITION: ${{ matrix.edition }}
|
||||
run: |
|
||||
make -C ../shovey levels landscape
|
||||
if [ "$EDITION" = direct ]; then make android; else make "android-$EDITION"; fi
|
||||
- name: Keep Google libraries out of the normal and F-Droid APK
|
||||
if: matrix.edition != 'gplay'
|
||||
uses: kryonlabs/kryon/.github/actions/google-free@7217475dfa7f462939e47e3f0bc918aef248b179
|
||||
with:
|
||||
packages: waozixyz/arcade/build/android/arcade*-unsigned.apk
|
||||
source: ''
|
||||
# The check must still recognise Play Billing, or its passes on the
|
||||
# other editions prove nothing.
|
||||
- name: Find Play Billing in the Google Play APK
|
||||
if: matrix.edition == 'gplay'
|
||||
uses: kryonlabs/kryon/.github/actions/google-free@7217475dfa7f462939e47e3f0bc918aef248b179
|
||||
with:
|
||||
packages: waozixyz/arcade/build/android/arcade-gplay-unsigned.apk
|
||||
source: ''
|
||||
expect-google: 'true'
|
||||
- name: Sign and check the APK
|
||||
env:
|
||||
KEYSTORE: ${{ secrets.ARCADE_ANDROID_KEYSTORE }}
|
||||
PASSWORD: ${{ secrets.ARCADE_ANDROID_KEYSTORE_PASSWORD }}
|
||||
VERSION: ${{ needs.release.outputs.version }}
|
||||
EDITION: ${{ matrix.edition }}
|
||||
run: |
|
||||
set -eu
|
||||
umask 077
|
||||
suffix=$([ "$EDITION" = direct ] && echo '' || echo "-$EDITION")
|
||||
printf '%s' "$KEYSTORE" | base64 -d > "$RUNNER_TEMP/arcade-release.p12"
|
||||
printf '%s\n' "$PASSWORD" > "$RUNNER_TEMP/password"
|
||||
python3 scripts/android-release.py sign "build/android/arcade$suffix-unsigned.apk" \
|
||||
--edition "$EDITION" --version "$VERSION" \
|
||||
--keystore "$RUNNER_TEMP/arcade-release.p12" --password-file "$RUNNER_TEMP/password" \
|
||||
--output "build/downloads/arcade-$VERSION$suffix.apk"
|
||||
rm -f "$RUNNER_TEMP/arcade-release.p12" "$RUNNER_TEMP/password"
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: arcade-android-${{ matrix.edition }}
|
||||
path: waozixyz/arcade/build/downloads/*.apk
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
publish:
|
||||
needs: [release, build]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: arcade-android-*
|
||||
path: build/downloads
|
||||
merge-multiple: true
|
||||
- name: Check and attach the APKs to the release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ needs.release.outputs.version }}
|
||||
run: |
|
||||
set -eu
|
||||
for edition in direct fdroid gplay; do
|
||||
suffix=$([ "$edition" = direct ] && echo '' || echo "-$edition")
|
||||
python3 scripts/android-release.py verify "build/downloads/arcade-$VERSION$suffix.apk" \
|
||||
--edition "$edition" --version "$VERSION"
|
||||
done
|
||||
gh release upload "node-arcade-$VERSION" "build/downloads/arcade-$VERSION.apk" \
|
||||
"build/downloads/arcade-$VERSION-fdroid.apk" "build/downloads/arcade-$VERSION-gplay.apk" --clobber
|
||||
@@ -0,0 +1,151 @@
|
||||
name: Game updates
|
||||
|
||||
# Arcade follows its games by itself. When a game package (Shovey, Apfelwurm)
|
||||
# publishes a GitHub release, this pins Arcade to that release, adds the
|
||||
# game's notes to Arcade's changelog, builds and checks the collection,
|
||||
# commits the new Arcade version and attaches its catalog and game archive to
|
||||
# the node-arcade-VERSION release. Inner Breeze's node follower then signs
|
||||
# that release and publishes it to Waozi's node, where Arcade downloads games.
|
||||
# A game's release workflow starts this at once; the timer is the fallback,
|
||||
# since GitHub runs scheduled workflows hours late.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '7,22,37,52 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
|
||||
concurrency:
|
||||
group: arcade-node-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
follow:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
defaults:
|
||||
run:
|
||||
working-directory: waozixyz/arcade
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
path: waozixyz/arcade
|
||||
- name: Check release following
|
||||
run: python3 tests/game_updates_test.py
|
||||
- name: Find newer game releases
|
||||
id: updates
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
python3 scripts/follow-game-releases.py check
|
||||
if [ "$(python3 -c 'import json; print(len(json.load(open("build/game-updates.json"))))')" = 0 ]; then
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Arcade already pins every game's latest release."
|
||||
exit 0
|
||||
fi
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
python3 - <<'PY' >> "$GITHUB_OUTPUT"
|
||||
import json
|
||||
lock = json.load(open('ziran.lock'))
|
||||
print('toolchain=' + lock['toolchain']['commit'])
|
||||
PY
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
with:
|
||||
repository: ziranlang/ziran
|
||||
ref: ${{ steps.updates.outputs.toolchain }}
|
||||
path: ziranlang/ziran
|
||||
- name: Install build dependencies
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
working-directory: .
|
||||
run: sh ziranlang/ziran/scripts/ci_packages.sh build-essential python3-pil python3-cryptography
|
||||
- name: Build the locked toolchain and pin game dependencies
|
||||
id: pin
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
make -j2 -C ../../ziranlang/ziran
|
||||
echo "$GITHUB_WORKSPACE/ziranlang/ziran/build/bin" >> "$GITHUB_PATH"
|
||||
python3 scripts/follow-game-releases.py pin --ziran ../../ziranlang/ziran/build/bin/ziran
|
||||
python3 - <<'PY' >> "$GITHUB_OUTPUT"
|
||||
import json
|
||||
lock = json.load(open('ziran.lock'))
|
||||
shovey = lock['root']['dependencies']['shovey']
|
||||
print('shovey=' + next(p['commit'] for p in lock['packages'] if p['id'] == shovey))
|
||||
PY
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
with:
|
||||
repository: waozixyz/shovey
|
||||
ref: ${{ steps.pin.outputs.shovey }}
|
||||
path: waozixyz/shovey
|
||||
- name: Fetch the updated packages
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
run: |
|
||||
# The game is generated in its own checkout at the pinned release.
|
||||
printf '[overrides]\nshovey = "../shovey"\nziran = "../../ziranlang/ziran"\n' > ziran.local.toml
|
||||
../../ziranlang/ziran/build/bin/ziran fetch
|
||||
- name: Write the Arcade release
|
||||
id: release
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
run: |
|
||||
python3 scripts/follow-game-releases.py changelog --ziran ../../ziranlang/ziran/build/bin/ziran
|
||||
sh update_version.sh
|
||||
python3 scripts/follow-game-releases.py art
|
||||
echo "version=$(cat VERSION)" >> "$GITHUB_OUTPUT"
|
||||
head -12 CHANGELOG.md
|
||||
- name: Build and check the collection
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
run: |
|
||||
make -C ../shovey levels landscape
|
||||
make collection
|
||||
python3 tests/collection_test.py
|
||||
python3 tests/publisher_test.py
|
||||
- name: Commit the release
|
||||
id: commit
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.release.outputs.version }}
|
||||
run: |
|
||||
git config user.name Waozi
|
||||
git config user.email [email protected]
|
||||
git add ziran.toml ziran.lock CHANGELOG.md VERSION apps/versions.json assets/arcade/library
|
||||
git commit -q -m "Release Arcade $VERSION with the latest game releases"
|
||||
git push origin HEAD:master
|
||||
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
- name: Attach the checked catalog and game archive
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ steps.release.outputs.version }}
|
||||
SHA: ${{ steps.commit.outputs.sha }}
|
||||
run: |
|
||||
set -eu
|
||||
gh release create "node-arcade-$VERSION" build/node-apps/arcade.zx build/node-apps/arcade.games.tar build/games/wurm.zx \
|
||||
--target "$SHA" --title "Arcade $VERSION" \
|
||||
--notes 'Arcade downloads the selected game separately and preserves earned progress.'
|
||||
echo "Arcade $VERSION is ready for the node: sha256 $(sha256sum build/node-apps/arcade.zx | cut -d' ' -f1)"
|
||||
# Arcade's own APKs build from the release's tag and join its release.
|
||||
- name: Start the Android build
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ steps.release.outputs.version }}
|
||||
run: gh workflow run android.yml -R "$GITHUB_REPOSITORY" --ref "node-arcade-$VERSION" -f version="$VERSION"
|
||||
# Breeze's node follower signs this release and publishes it to the
|
||||
# node now, not at its next timer. RELEASE_FOLLOW_TOKEN may only start
|
||||
# workflows in Arcade and Breeze; the follower takes no input and
|
||||
# checks Arcade's newest release itself. Without it the timer follows.
|
||||
- name: Start the node follower
|
||||
if: steps.updates.outputs.changed == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.RELEASE_FOLLOW_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$GH_TOKEN" ]; then
|
||||
echo "No RELEASE_FOLLOW_TOKEN: Breeze's node follower picks this release up on its timer."
|
||||
exit 0
|
||||
fi
|
||||
gh workflow run node-app-follow.yml -R waozixyz/breeze --ref master
|
||||
@@ -0,0 +1,110 @@
|
||||
name: Arcade node release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
sha256:
|
||||
description: SHA-256 of the locally verified node catalog
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
|
||||
concurrency:
|
||||
group: arcade-node-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
defaults:
|
||||
run:
|
||||
working-directory: waozixyz/arcade
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
path: waozixyz/arcade
|
||||
- name: Read the fixed dependency revisions
|
||||
id: dependencies
|
||||
env:
|
||||
EXPECTED_SHA256: ${{ inputs.sha256 }}
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import json, os, re
|
||||
if not re.fullmatch('[0-9a-f]{64}', os.environ['EXPECTED_SHA256']):
|
||||
raise SystemExit('Give the exact verified catalog SHA-256')
|
||||
lock = json.load(open('ziran.lock'))
|
||||
game = next(p['commit'] for p in lock['packages'] if p['url'] == 'https://github.com/waozixyz/shovey.git')
|
||||
with open(os.environ['GITHUB_OUTPUT'], 'a') as output:
|
||||
output.write('toolchain=' + lock['toolchain']['commit'] + '\nshovey=' + game + '\n')
|
||||
PY
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
repository: ziranlang/ziran
|
||||
ref: ${{ steps.dependencies.outputs.toolchain }}
|
||||
path: ziranlang/ziran
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
repository: waozixyz/shovey
|
||||
ref: ${{ steps.dependencies.outputs.shovey }}
|
||||
path: waozixyz/shovey
|
||||
- name: Install build dependencies
|
||||
working-directory: .
|
||||
run: sh ziranlang/ziran/scripts/ci_packages.sh build-essential python3-pil python3-cryptography
|
||||
- name: Build the locked toolchain and fetch packages
|
||||
run: |
|
||||
make -j2 -C ../../ziranlang/ziran
|
||||
echo "$GITHUB_WORKSPACE/ziranlang/ziran/build/bin" >> "$GITHUB_PATH"
|
||||
# These are the exact revisions read from the release lock above.
|
||||
# Generate the game in its own checkout, never in the package cache.
|
||||
printf '[overrides]\nshovey = "../shovey"\nziran = "../../ziranlang/ziran"\n' > ziran.local.toml
|
||||
../../ziranlang/ziran/build/bin/ziran fetch
|
||||
- name: Build and verify the node catalog
|
||||
env:
|
||||
EXPECTED_SHA256: ${{ inputs.sha256 }}
|
||||
run: |
|
||||
make -C ../shovey levels landscape
|
||||
make collection
|
||||
python3 tests/collection_test.py
|
||||
python3 tests/publisher_test.py
|
||||
# The candidate's digest, so a local check can compare the exact bytes.
|
||||
sha256sum build/node-apps/arcade.zx
|
||||
echo "$EXPECTED_SHA256 build/node-apps/arcade.zx" | sha256sum --check --strict
|
||||
# When the digest is not the expected one, keep the candidate for a local
|
||||
# check; nothing is published.
|
||||
- name: Keep the unpublished candidate
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: arcade-candidate
|
||||
path: |
|
||||
waozixyz/arcade/build/node-apps/arcade.zx
|
||||
waozixyz/arcade/build/node-apps/arcade.json
|
||||
waozixyz/arcade/build/node-apps/arcade.games.tar
|
||||
waozixyz/arcade/build/games/wurm.zx
|
||||
waozixyz/arcade/build/apps-ui/apps.zx
|
||||
if-no-files-found: ignore
|
||||
retention-days: 1
|
||||
- name: Publish the checked catalog and game archive
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -eu
|
||||
version=$(cat VERSION)
|
||||
tag="node-arcade-$version"
|
||||
if gh release view "$tag" >/dev/null 2>&1; then
|
||||
mkdir -p build/prior-node-release
|
||||
gh release download "$tag" --pattern arcade.zx --pattern arcade.games.tar --pattern wurm.zx --dir build/prior-node-release
|
||||
cmp build/prior-node-release/arcade.zx build/node-apps/arcade.zx
|
||||
cmp build/prior-node-release/arcade.games.tar build/node-apps/arcade.games.tar
|
||||
cmp build/prior-node-release/wurm.zx build/games/wurm.zx
|
||||
else
|
||||
gh release create "$tag" build/node-apps/arcade.zx build/node-apps/arcade.games.tar build/games/wurm.zx \
|
||||
--target "$GITHUB_SHA" --title "Arcade $version" \
|
||||
--notes 'Arcade downloads the selected game separately and preserves earned progress.'
|
||||
# Arcade's own APKs build from the release's tag and join its release.
|
||||
gh workflow run android.yml -R "$GITHUB_REPOSITORY" --ref "$tag" -f version="$version"
|
||||
fi
|
||||
@@ -0,0 +1,130 @@
|
||||
name: Website
|
||||
|
||||
# https://arcade.waozi.xyz runs Arcade in the browser: the latest published
|
||||
# arcade.zx, the same one Inner Breeze downloads, with Arcade's own host
|
||||
# compiled to WebAssembly. Every push to master and every Arcade release,
|
||||
# manual or automatic, rebuilds and publishes it.
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
workflow_run:
|
||||
workflows: [Arcade node release, Game updates]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A running build finishes; only the newest waiting one follows it.
|
||||
concurrency:
|
||||
group: arcade-site
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
defaults:
|
||||
run:
|
||||
working-directory: waozixyz/arcade
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
path: waozixyz/arcade
|
||||
ref: master
|
||||
fetch-depth: 0
|
||||
- name: Read the locked toolchain
|
||||
id: toolchain
|
||||
run: |
|
||||
python3 -c 'import json,os; open(os.environ["GITHUB_OUTPUT"],"a").write("commit="+json.load(open("ziran.lock"))["toolchain"]["commit"]+"\n")'
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
repository: ziranlang/ziran
|
||||
ref: ${{ steps.toolchain.outputs.commit }}
|
||||
path: ziranlang/ziran
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
- name: Install build dependencies
|
||||
working-directory: .
|
||||
run: sh ziranlang/ziran/scripts/ci_packages.sh build-essential cmake pkg-config python3-pil
|
||||
- uses: mymindstorm/setup-emsdk@v14
|
||||
with:
|
||||
version: '6.0.6'
|
||||
actions-cache-folder: emsdk-cache
|
||||
- name: Build the locked toolchain and fetch packages
|
||||
run: |
|
||||
make -j2 -C ../../ziranlang/ziran
|
||||
echo "$GITHUB_WORKSPACE/ziranlang/ziran/build/bin" >> "$GITHUB_PATH"
|
||||
printf '[overrides]\nziran = "../../ziranlang/ziran"\n' > ziran.local.toml
|
||||
../../ziranlang/ziran/build/bin/ziran fetch
|
||||
- name: Download the published Arcade
|
||||
id: published
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
tag=$(gh release list --repo waozixyz/arcade --limit 50 --json tagName,isDraft \
|
||||
-q '[.[] | select(.isDraft | not) | .tagName | select(startswith("node-arcade-"))][0]')
|
||||
test -n "$tag"
|
||||
mkdir -p build/published
|
||||
# Its game archive holds the library art the site serves itself.
|
||||
gh release download "$tag" --repo waozixyz/arcade --pattern arcade.zx \
|
||||
--pattern arcade.games.tar --dir build/published
|
||||
# The Apps library that release packs, by the digest its own commit trusts.
|
||||
git show "$tag:apps-controller.sha256" > build/published/apps-controller.sha256
|
||||
echo "version=${tag#node-arcade-}" >> "$GITHUB_OUTPUT"
|
||||
- name: Build the browser edition
|
||||
run: |
|
||||
python3 tests/web_library_art_test.py
|
||||
python3 scripts/build-entity.py
|
||||
python3 scripts/build-apps.py --output build/apps-ui
|
||||
python3 scripts/build-web.py --bundle build/published/arcade.zx \
|
||||
--controller-sha256 "$(cat build/published/apps-controller.sha256)" \
|
||||
--version '${{ steps.published.outputs.version }}'
|
||||
rm -f build/web-site/runtime.html
|
||||
- name: Wait for the published games the browser will download
|
||||
run: |
|
||||
python3 scripts/wait-published-games.py --deadline-seconds 900 --poll-seconds 30 \
|
||||
build/published/arcade.zx build/published/arcade.games.tar
|
||||
- name: Open Arcade in a private browser
|
||||
run: |
|
||||
export CHROMIUM="$(command -v google-chrome || command -v chromium)"
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS node tests/web_site_test.mjs build/web-site
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: arcade-site
|
||||
path: waozixyz/arcade/build/web-site
|
||||
retention-days: 1
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
environment:
|
||||
name: cloudflare-pages
|
||||
url: https://arcade.waozi.xyz
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: master
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: arcade-site
|
||||
path: build/web-site
|
||||
- name: Prepare the Pages project
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
run: python3 scripts/cloudflare-site.py prepare
|
||||
- name: Deploy to Cloudflare Pages
|
||||
uses: cloudflare/wrangler-action@v3
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
command: pages deploy build/web-site --project-name=arcade --branch=master --commit-hash=${{ github.sha }}
|
||||
- name: Connect arcade.waozi.xyz
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
run: python3 scripts/cloudflare-site.py connect
|
||||
@@ -1,5 +1,6 @@
|
||||
/build/
|
||||
/backup/
|
||||
/work/
|
||||
/ziran.local.toml
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
@@ -1,5 +1,257 @@
|
||||
# Arcade changelog
|
||||
|
||||
## 0.7.112
|
||||
|
||||
- Every library cover shows its declared app title, including Apfelwurm Editor.
|
||||
- Choano appears in Arcade and launches from its own game package.
|
||||
- Apfelwurm and Apfelwurm Editor open correctly in standalone Arcade.
|
||||
|
||||
## 0.7.111
|
||||
|
||||
- Apfelwurm 0.2.27: Earn coins for every level you clear and spend them on new skins.
|
||||
- Apfelwurm 0.2.27: Claim a daily reward from the chest on the title: 30 days of coins, two new skins and rare Dew on days 10 and 25.
|
||||
- Apfelwurm 0.2.27: The title has painted Shop, Profile, Leaderboard and Settings icons, with your coins and Dew beside the Shop.
|
||||
- Apfelwurm 0.2.27: The Shop has Skins, Coins and Dew tabs: buy coin packs with Dew and top up Dew without leaving it.
|
||||
- Apfelwurm 0.2.27: Browse thirteen skins with slimmer bodies, closer segments, clean edges and matching leaderboard pictures.
|
||||
- Apfelwurm 0.2.27: Open the level editor directly from the title. Settings previews both touch control styles, or shows the steering keys on a computer.
|
||||
- Apfelwurm 0.2.27: The level editor has its own title screen. Start a **New level** in any landscape you have reached, or copy one **From a level**.
|
||||
- Apfelwurm 0.2.27: Keep your levels in **My levels**, in collections you can name and reorder. They stay private to you.
|
||||
- Apfelwurm 0.2.27: Share a collection with your friends or everyone, and find other players' collections in **Community**. Added collections become your own private copies.
|
||||
- Apfelwurm 0.2.27: Campaign levels you changed before still play as you made them; **Campaign changes** lists them so you can reset each one.
|
||||
- Apfelwurm 0.2.27: Open the editor as its own **Apfelwurm Editor** app in Arcade.
|
||||
- Apfelwurm 0.2.27: Play local desktop rounds with two to four players, separate bottom entrances and four keyboard control sets.
|
||||
- Apfelwurm 0.2.27: Name each local player and pick their skin; start local rounds from Settings. Each open entrance has rock posts beside it.
|
||||
- Apfelwurm 0.2.27: Play every level in the same layout in portrait and landscape, shaped after the portrait, with roomier portrait boards.
|
||||
- Apfelwurm 0.2.27: Your own portrait level now also shapes its landscape until you save a landscape of your own.
|
||||
- Apfelwurm 0.2.27: On a computer, play starts without asking how to steer, also inside Breeze and Arcade, and the keyboard steers without an on-screen pad.
|
||||
- Apfelwurm 0.2.27: Level 19 is roomier: every side passage is wide enough to turn and come back out.
|
||||
|
||||
## 0.7.110
|
||||
|
||||
- Arcade is available as an Android app that plays every game offline, in normal, F-Droid and Google Play editions.
|
||||
- On arcade.waozi.xyz the game covers appear sooner, as smaller WebP pictures from the site itself.
|
||||
- Editors can share level collections through Arcade's signed-in Entity account.
|
||||
- Shovey 0.6.163: Keep named collections in the Editor, share them with friends or everyone, and add new private collections from Explore.
|
||||
- Shovey 0.6.163: Mirror and laser names and the level heading display correctly in every language.
|
||||
|
||||
## 0.7.109
|
||||
|
||||
- On a computer, games start without asking how to move, also inside Breeze.
|
||||
- Shovey 0.6.162: Coloured pits have new artwork.
|
||||
- Shovey 0.6.162: On a computer, play starts without asking how to move.
|
||||
|
||||
## 0.7.108
|
||||
|
||||
- Every game runs in Inner Breeze 2.1.61's smaller app format.
|
||||
- Shovey 0.6.160, Editor 0.2.145 and Island 0.4.8, and Apfelwurm 0.2.26 with newly painted skins that have calm, plain bodies.
|
||||
|
||||
## 0.7.107
|
||||
|
||||
- Apfelwurm 0.2.24: Keep the entrance area free of enemies: none start there or wander in, so nothing vanishes when you lose a life.
|
||||
- Apfelwurm 0.2.24: Restart Profile and Leaderboard by themselves if they stop, or say why instead of showing an empty page.
|
||||
|
||||
## 0.7.106
|
||||
|
||||
- Apfelwurm 0.2.23: Move a little faster throughout the campaign, with a consistent pace across Meadow.
|
||||
|
||||
## 0.7.105
|
||||
|
||||
- Apfelwurm 0.2.22: Keep the leaderboard visible when you or a friend uses a special Wurm skin.
|
||||
|
||||
## 0.7.104
|
||||
|
||||
- Apfelwurm 0.2.12: Download the Google Play edition as a separate `-gplay.apk`. The standard and F-Droid APKs exclude Google libraries and keep Monero top-ups.
|
||||
|
||||
## 0.7.103
|
||||
|
||||
- Apfelwurm 0.2.11: Buy a small 10 Dew pack in the Google Play edition and see each larger pack’s savings per Dew.
|
||||
|
||||
## 0.7.102
|
||||
|
||||
- Update Apfelwurm and Shovey with a small 10 Dew pack and visible larger-pack savings in their Google Play editions.
|
||||
|
||||
## 0.7.101
|
||||
|
||||
- Apfelwurm 0.2.10: Keep signed-in progress and unfinished runs after closing or updating Apfelwurm inside Arcade and Breeze.
|
||||
- Apfelwurm 0.2.10: Restore earned unlocks from older account saves without changing completed levels or the current run.
|
||||
- Apfelwurm 0.2.10: Give Apfelwurm its own Android launcher icon.
|
||||
|
||||
## 0.7.100
|
||||
|
||||
- Apfelwurm 0.2.9: More portal rooms in the mountains: five more boards have a walled corner room whose doorway closes, so a ring is the only way in, and boards there that bring portals use their room. Seven of the last twenty boards now have a portal room.
|
||||
|
||||
## 0.7.99
|
||||
|
||||
- Shovey 0.6.158: In the Google Play version, buy Dew in Profile through Google Play.
|
||||
- Shovey 0.6.158: Pip explains wooden doors when Shovey walks up to one, rather than when the level starts.
|
||||
- Apfelwurm 0.2.8: After the meadow, a new idea arrives every few dozen levels and keeps coming back: squirrels that dash and sit from level 45, hedgehogs that curl into a spiky ball as you come close from 85, keys that open a gate from 101, frogs that hop two tiles from 125, switch stones that open and close a gate from 141, rolling stones from 165 and portal rooms, reached only through a ring, from 181.
|
||||
- Apfelwurm 0.2.8: Each new idea takes every other board for ten levels. After that, the ideas you have met take turns, with no more than two plain boards in a row.
|
||||
- Apfelwurm 0.2.8: A gate closes a doorway up to four tiles wide. Its key opens it for good and is worth 2 points; a switch stone flips it each time you arrive on it. Boards with a gate or a portal room score more.
|
||||
- Apfelwurm 0.2.8: New pictures for the squirrel, hedgehog, frog, rolling stone, key, switch stone and gate.
|
||||
|
||||
## 0.7.98
|
||||
|
||||
- Shovey 0.6.158: In the Google Play version, buy Dew in Profile through Google Play.
|
||||
- Shovey 0.6.158: Pip explains wooden doors when Shovey walks up to one, rather than when the level starts.
|
||||
|
||||
## 0.7.97
|
||||
|
||||
- Apfelwurm 0.2.6: Glowing portals arrive from level 61: first on a few boards, then more often, with two pairs late in the mountains. Steer into one ring to come out of its partner, keeping your direction. Each ring stands in open ground, so you can always go around it.
|
||||
- Apfelwurm 0.2.6: See your best run on the Profile leaderboard: the furthest level you reached and your highest score, as separate Level and Score columns ranked against your friends.
|
||||
- Apfelwurm 0.2.6: Sign in once for every waozi.xyz site: a profile signed in on Arcade, Dew or here is used by the others in the same browser.
|
||||
- Apfelwurm 0.2.6: Buy Dew inside the Google Play version through Google Play, priced in your own currency. The direct download and F-Droid versions keep buying Dew with Monero.
|
||||
- Apfelwurm 0.2.6: The privacy page explains Google Play purchases and how to delete your account.
|
||||
|
||||
## 0.7.96
|
||||
|
||||
- Shovey 0.6.157: Pip's tips keep what he points at in view: his card moves under the top bar when it would cover it, such as the home in level 1.
|
||||
- Apfelwurm 0.2.4: Play on the whole page at wurm.waozi.xyz, without a title bar above the game.
|
||||
|
||||
## 0.7.95
|
||||
|
||||
- Shovey 0.6.157: Pip's tips keep what he points at in view: his card moves under the top bar when it would cover it, such as the home in level 1.
|
||||
|
||||
## 0.7.94
|
||||
|
||||
- The library's game covers download about four times faster.
|
||||
|
||||
## 0.7.93
|
||||
|
||||
- Shovey 0.6.156: Finishing all 175 levels opens a reward window: press Claim to get your Dew. The first 10 players to finish get 100 Dew, the next 20 get 50, players up to the 100th get 20, and everyone after gets 5.
|
||||
|
||||
## 0.7.92
|
||||
|
||||
- Shovey 0.6.156: Finishing all 175 levels opens a reward window: press Claim to get your Dew. The first 10 players to finish get 100 Dew, the next 20 get 50, players up to the 100th get 20, and everyone after gets 5.
|
||||
|
||||
## 0.7.91
|
||||
|
||||
- Shovey 0.6.155: Set an account alias with capitals, an @ or spaces; a taken alias now says so.
|
||||
- Apfelwurm 0.2.2: Set an account alias with capitals, an @ or spaces; a taken alias now says so.
|
||||
|
||||
## 0.7.90
|
||||
|
||||
- Set an account alias with capitals, an @ or spaces; a taken alias now says so.
|
||||
- Shovey 0.6.155: Set an account alias with capitals, an @ or spaces; a taken alias now says so.
|
||||
|
||||
## 0.7.89
|
||||
|
||||
- Apfelwurm 0.2.1: Use Arcade or Inner Breeze's Profile, Dew and navigation when playing inside them, without duplicate title controls or an extra Back button.
|
||||
- Apfelwurm 0.2.1: Open the shared Profile reliably from the skin shop's sign-in button.
|
||||
|
||||
## 0.7.88
|
||||
|
||||
- Apfelwurm 0.2.0: Play with softer Dusk, Forest and Sage themes, with saved sound and control settings.
|
||||
- Apfelwurm 0.2.0: See a continuous painted meadow instead of a repeating grass grid, and clear Profile and Dew icons on the title.
|
||||
- Apfelwurm 0.2.0: Sign in through the shared Profile to sync completed levels, playtime, settings and your chosen character across devices.
|
||||
- Apfelwurm 0.2.0: Browse the skin shop from the title beside Profile and your Dew balance. Mint, Berry and Rose cost 10, 20 and 30 Dew, with confirmation before buying.
|
||||
- Apfelwurm 0.2.0: Earn Night owl after five hours of active play, Golden apple by reaching level 40, and Explorer by visiting waozi.xyz. Purchased skins belong to your account.
|
||||
- Apfelwurm 0.2.0: Unlock all 200 levels by playing. The mobile selector shows large previews for unlocked levels and only a lock for later ones. Dew is used for optional cosmetics.
|
||||
|
||||
## 0.7.87
|
||||
|
||||
- Open the game library faster with smaller cached cover thumbnails for every game.
|
||||
- Keep covers sharp and logos transparent while downloading much less artwork.
|
||||
|
||||
## 0.7.86
|
||||
|
||||
- Shovey 0.6.154: Keep opened chests open across restarts and account sync; show the blue Dew diamond only while their reward is unclaimed.
|
||||
- Shovey 0.6.154: Show an empty open chest after its Dew is claimed.
|
||||
- Shovey 0.6.154: Use corrected campaign boards after an update, including level 29 when an older campaign was cached offline.
|
||||
|
||||
## 0.7.85
|
||||
|
||||
- Shovey keeps opened and claimed chests synchronized, with a blue diamond only for an unclaimed reward.
|
||||
- Shovey uses corrected boards after an update instead of an older cached campaign.
|
||||
- Apfelwurm shows level previews only after they are unlocked.
|
||||
|
||||
## 0.7.84
|
||||
|
||||
- Complete automatic reward recovery for older Shovey saves.
|
||||
|
||||
## 0.7.83
|
||||
|
||||
- Preserve earned Shovey reward eligibility when upgrading older synced saves.
|
||||
|
||||
## 0.7.82
|
||||
|
||||
- Apfelwurm 0.1.6: Try again after game over starts the furthest unlocked level with three lives and a fresh score.
|
||||
- Apfelwurm 0.1.6: Choose level from the title to browse all five landscapes, preview each board and replay any unlocked level. Future levels remain locked until you reach them.
|
||||
- Apfelwurm 0.1.6: Use Escape to pause or go back in the browser without stopping the game.
|
||||
|
||||
## 0.7.81
|
||||
|
||||
- Update Shovey to the approved campaign and solve puzzles using wooden crates as water bridges.
|
||||
- Shovey Editor recognizes device unlocks, returns to the title, accepts right-click movement and shows a clearer object palette.
|
||||
|
||||
## 0.7.80
|
||||
|
||||
- Keep games covered until their first board is ready and keep complete pictures visible while animation sprites load.
|
||||
- Shovey’s secret chest reopens for unclaimed Dew and shows an empty chest after a confirmed claim.
|
||||
|
||||
## 0.7.79
|
||||
|
||||
- On phones the library shows small covers, two or three in a row.
|
||||
|
||||
## 0.7.78
|
||||
|
||||
- Download Arcade itself in under one megabyte: it lists the games, and their covers and each game arrive separately when you need them.
|
||||
- Covers show only the game art; the download dialog shows the size.
|
||||
- Shovey Editor downloads as a small add-on that reuses Shovey’s game.
|
||||
|
||||
## 0.7.77
|
||||
|
||||
- Apfelwurm 0.1.4: Press Play and go straight into the game: no stage or level select. Play every level in order through all five landscapes, earning lives as your score grows; a game over starts again from level 1.
|
||||
- Apfelwurm 0.1.4: Continue your run from the start of the level you reached; existing stage progress continues from your first uncleared level.
|
||||
|
||||
## 0.7.76
|
||||
|
||||
- Install Shovey Editor as an add-on and reuse Shovey’s art and sounds.
|
||||
- Review every required download and its total size before installing.
|
||||
- Download each game from the server before playing, including Apfelwurm.
|
||||
- Use clean title-screen covers without repeated game names underneath.
|
||||
- Recognize Shovey Editor by its matching Editor title logo.
|
||||
- Shovey includes approved Classic levels 1–175.
|
||||
- All objects stop at the abyss and leave it open.
|
||||
- Existing Shovey saves and completed levels are retained.
|
||||
## 0.7.75
|
||||
|
||||
- See each game’s download size under its cover until it is installed.
|
||||
- Read secondary profile labels clearly in the dark theme.
|
||||
- Browse a dark Arcade library with large rounded title covers; click a cover to play or download its game.
|
||||
- Download games individually, including Apfelwurm, and keep downloaded games available offline.
|
||||
- Return from Shovey levels with the fixed Back control while retaining existing progress.
|
||||
|
||||
## 0.7.74
|
||||
|
||||
- Shovey includes approved Classic levels 1–175.
|
||||
- All objects stop at the abyss and leave it open.
|
||||
- Existing Shovey saves and completed levels are retained.
|
||||
## 0.7.73
|
||||
|
||||
- Shovey includes approved Classic levels 1–175.
|
||||
- All objects stop at the abyss and leave it open.
|
||||
- Existing Shovey saves and completed levels are retained.
|
||||
## 0.7.72
|
||||
|
||||
- Shovey includes approved Classic levels 1–175.
|
||||
- All objects stop at the abyss and leave it open.
|
||||
- Existing Shovey saves and completed levels are retained.
|
||||
## 0.7.71
|
||||
|
||||
- Shovey includes approved Classic levels 1–175.
|
||||
- All objects stop at the abyss and leave it open.
|
||||
- Existing Shovey saves and completed levels are retained.
|
||||
## 0.7.70
|
||||
|
||||
- Shovey includes approved Classic levels 1–175.
|
||||
- All objects stop at the abyss and leave it open.
|
||||
- Existing Shovey saves and completed levels are retained.
|
||||
## 0.7.69
|
||||
|
||||
- Arcade downloads each selected game separately, keeping its initial download smaller.
|
||||
- Shovey keeps movement and unfinished puzzles on each device.
|
||||
- Completed puzzles share unlocks without moving a player already in a level.
|
||||
|
||||
## 0.7.68
|
||||
|
||||
- Shovey includes approved Classic levels 1–175.
|
||||
|
||||
@@ -20,7 +20,7 @@ DATA_DIR ?= $(if $(XDG_DATA_HOME),$(XDG_DATA_HOME),$(HOME)/.local/share)
|
||||
all: collection build/entity.zx build/arcade build/shovey
|
||||
|
||||
games:
|
||||
python3 scripts/check-games.py
|
||||
python3 scripts/check-games.py --ziran '$(ZIRAN)' $(LOCK_FLAGS)
|
||||
python3 scripts/build-games.py --ziran '$(ZIRAN)' $(LOCK_FLAGS)
|
||||
|
||||
$(APPS_BUNDLE): ziran.lock apps-controller.sha256 scripts/build-apps.py Makefile
|
||||
@@ -54,15 +54,19 @@ run: all
|
||||
./build/arcade
|
||||
|
||||
test: all
|
||||
python3 tests/game_updates_test.py
|
||||
$(ZIRAN) fmt --check src/*.zi apps/chess/*.zi tests/chess_engine_behavior.zi tests/chess_app_behavior.zi
|
||||
python3 tests/chess_locale_test.py
|
||||
INBE_SOURCE='$(INBE_SOURCE)' python3 tests/catalog_test.py
|
||||
python3 tests/publisher_test.py
|
||||
python3 tests/apps_controller_test.py
|
||||
python3 tests/startup_art_test.py
|
||||
python3 tests/web_library_art_test.py
|
||||
./build/arcade --list
|
||||
sh tests/chess_engine_zi_test.sh '$(ZIRAN)'
|
||||
sh tests/chess_app_test.sh '$(ZIRAN)'
|
||||
python3 tests/sound_test.py
|
||||
sh tests/collection_loading_test.sh
|
||||
|
||||
chess-engine-test:
|
||||
sh tests/chess_engine_zi_test.sh '$(ZIRAN)'
|
||||
@@ -104,7 +108,17 @@ navigation-ui-test: all
|
||||
timeout 150s xvfb-run -a -n 400 -s '-screen 0 1280x1000x24' python3 tests/standalone_navigation_ui_test.py \
|
||||
--binary '$(CURDIR)/build/arcade' --binary '$(CURDIR)/build/shovey' --inbe-source '$(INBE_SOURCE)'
|
||||
|
||||
install: all
|
||||
.PHONY: install-arcade
|
||||
install-arcade: collection build/entity.zx build/arcade
|
||||
mkdir -p '$(BIN_DIR)' '$(LIB_DIR)' '$(DATA_DIR)/applications'
|
||||
install -m 0755 build/arcade '$(LIB_DIR)/arcade.new'
|
||||
mv -f '$(LIB_DIR)/arcade.new' '$(LIB_DIR)/arcade'
|
||||
install -m 0644 build/entity.zx build/arcade.zx build/arcade.json '$(LIB_DIR)/'
|
||||
install -m 0644 '$(APPS_BUNDLE)' '$(LIB_DIR)/apps.zx'
|
||||
ln -sfn '$(LIB_DIR)/arcade' '$(BIN_DIR)/arcade'
|
||||
install -m 0644 packaging/xyz.waozi.arcade.desktop '$(DATA_DIR)/applications/'
|
||||
|
||||
install: all install-arcade
|
||||
mkdir -p '$(BIN_DIR)' '$(LIB_DIR)/games' '$(DATA_DIR)/applications'
|
||||
mkdir -p '$(LIB_DIR)/startup/shovey'
|
||||
install -m 0644 build/startup/shovey/*.png '$(LIB_DIR)/startup/shovey/'
|
||||
@@ -113,14 +127,33 @@ install: all
|
||||
install -m 0755 build/shovey '$(LIB_DIR)/shovey.new'
|
||||
mv -f '$(LIB_DIR)/shovey.new' '$(LIB_DIR)/shovey'
|
||||
install -m 0644 build/entity.zx build/arcade.zx build/arcade.json build/shovey.zx build/shovey.json '$(LIB_DIR)/'
|
||||
install -m 0644 build/games/*.zx '$(LIB_DIR)/games/'
|
||||
install -m 0644 build/games/*-preview.png '$(LIB_DIR)/games/'
|
||||
install -m 0644 '$(APPS_BUNDLE)' '$(LIB_DIR)/apps.zx'
|
||||
ln -sfn '$(LIB_DIR)/arcade' '$(BIN_DIR)/arcade'
|
||||
ln -sfn '$(LIB_DIR)/shovey' '$(BIN_DIR)/shovey'
|
||||
mkdir -p '$(DATA_DIR)/icons/hicolor/256x256/apps'
|
||||
install -m 0644 build/shovey-icon.png '$(DATA_DIR)/icons/hicolor/256x256/apps/xyz.waozi.shovey.png'
|
||||
install -m 0644 packaging/xyz.waozi.arcade.desktop packaging/xyz.waozi.shovey.desktop '$(DATA_DIR)/applications/'
|
||||
|
||||
# Arcade's own APK opens its whole library offline. Each builds an unsigned
|
||||
# release APK in build/android/; only -gplay carries a Google library.
|
||||
# scripts/android-release.py signs and checks them.
|
||||
.PHONY: android android-fdroid android-gplay
|
||||
android: collection
|
||||
python3 scripts/build-android.py --product arcade --release
|
||||
|
||||
android-fdroid: collection
|
||||
python3 scripts/build-android.py --product arcade --release --edition fdroid
|
||||
|
||||
android-gplay: collection
|
||||
python3 scripts/build-android.py --product arcade --release --edition gplay
|
||||
|
||||
# The collection make android packed opens every game offline (desktop host).
|
||||
.PHONY: android-offline-ui-test
|
||||
android-offline-ui-test: build/arcade build/entity.zx
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS \
|
||||
-u SESSION_MANAGER -u GDK_DISPLAY YUE_DESKTOP_RECOVERY=0 SDL_AUDIODRIVER=dummy \
|
||||
timeout 240s xvfb-run -a -n 400 -s '-screen 0 1280x1000x24' python3 tests/android_offline_ui_test.py --binary '$(CURDIR)/build/arcade' --inbe-source '$(INBE_SOURCE)'
|
||||
|
||||
.PHONY: android-shovey android-shovey-release android-shovey-bundle
|
||||
android-shovey: collection
|
||||
python3 scripts/build-android.py
|
||||
|
||||
@@ -1,15 +1,29 @@
|
||||
# Arcade
|
||||
|
||||
Games and entertainment, alongside Werkzeug for practical tools and Inner
|
||||
Breeze for personal growth. The library opens Shovey Classic and Editor
|
||||
directly from full-screen covers.
|
||||
Swipe, turn the arrows, scroll the wheel, or use the arrow keys to choose;
|
||||
press Play/Open or Enter to launch. Standalone Shovey opens on the same
|
||||
carousel with its own covers. Chess is temporarily disabled in Arcade; its code and
|
||||
Breeze for personal growth. Arcade opens on a dark grid of large rounded
|
||||
title-screen covers from the shared Apps controller. Click a cover to open
|
||||
an installed game or download it first. There are no separate launch buttons.
|
||||
Standalone Shovey opens on its own cover carousel;
|
||||
swipe, use the arrows or scroll the wheel to choose, then press Play/Open.
|
||||
Its desktop startup first draws a small full-colour title preview, then uses
|
||||
the original artwork when the collection is ready.
|
||||
Chess is temporarily disabled in Arcade; its code and
|
||||
existing saved games remain available for a later return.
|
||||
Each edition has a separate save and earned unlocks. Unlocked puzzles show
|
||||
their whole board; locked puzzles keep their lock until earned.
|
||||
|
||||
The published Arcade carries only its catalog, well under one megabyte. Its host supplies the shared Apps controller (Inner Breeze its own, standalone Arcade the `apps.zx` installed beside it), and the covers and previews download once as one separate art bundle. Library covers use thumbnails up to 640 pixels on their longest side, and logos up to 512 pixels, preserving full colours and transparency. Games keep their original artwork. The verified art bundle stays cached across restarts and is replaced when its content changes. The art lives in `assets/arcade/library/` (`python3 scripts/library-art.py` refreshes it when a game's art changes; the build stops until it does). Inner Breeze needs host interface 35 for it. Each game
|
||||
downloads when opened, with its existing identity and saved progress. This
|
||||
catalog requires Inner Breeze host API 34. Downloaded games work offline;
|
||||
standalone Shovey keeps its complete offline collection. Apfelwurm comes from
|
||||
its own package, with the same game identity and private editor records.
|
||||
|
||||
Shovey Editor is an add-on to Shovey. Its install dialog lists Shovey when it
|
||||
is needed and shows the total download size. Once Shovey is installed, only
|
||||
the editor’s additions download. The editor reuses the original game’s art
|
||||
and sounds, and both remain available offline.
|
||||
|
||||
Chess’s retained implementation can choose a side and one of four computer
|
||||
levels. A local game
|
||||
survives returning to the library and restarting the app. Ask for a hint, take
|
||||
@@ -32,8 +46,8 @@ review are not implemented.
|
||||
|
||||
## Shared Apps library
|
||||
|
||||
Arcade embeds the shared `apps.zx` controller and exact game bundles in a
|
||||
verified collection. Each game package lists its apps in its own `apps.json`:
|
||||
Arcade embeds the shared `apps.zx` controller and artwork in a verified
|
||||
catalog. The catalog fixes the digest of every separately downloaded game. Each game package lists its apps in its own `apps.json`:
|
||||
the app's `catalog.json`, and for an app the library opens from a cover, the
|
||||
cover's portrait art, landscape art, logo, caption and action. `games.json`
|
||||
names the game packages, and Arcade's own `apps.json` its own apps. Arcade
|
||||
@@ -69,6 +83,22 @@ bundle, so Inbe supplies its existing profile and account. Inbe retains its
|
||||
existing game sync and friend games. Arcade and Inbe keep separate
|
||||
saved games; this version does not migrate or synchronize games between them.
|
||||
|
||||
## Website
|
||||
|
||||
https://arcade.waozi.xyz runs Arcade in the browser: the latest published
|
||||
`arcade.zx`, the same collection Inner Breeze downloads, with Arcade's own host
|
||||
(`src/web/runtime.zi`) compiled to WebAssembly by Entity's web build. Games
|
||||
download from the node when someone opens them; saves stay in the browser.
|
||||
`.github/workflows/site.yml` rebuilds and publishes it after every push to
|
||||
master and every Arcade release, after `tests/web_site_test.mjs` opens the
|
||||
library in a private browser. `scripts/cloudflare-site.py` creates the Pages
|
||||
project and connects the domain with the repository's `CLOUDFLARE_API_TOKEN`
|
||||
and `CLOUDFLARE_ACCOUNT_ID` secrets.
|
||||
|
||||
Build it locally from this checkout's collection with `make collection`,
|
||||
`python3 scripts/build-entity.py` and `python3 scripts/build-web.py`, then serve
|
||||
`build/web-site`.
|
||||
|
||||
## Build and run
|
||||
|
||||
Dependencies are Git repositories pinned in `ziran.lock`. The toolchain
|
||||
@@ -93,8 +123,28 @@ make
|
||||
Desktop builds need SDL2, Cairo, FreeType, Fontconfig and Pango development
|
||||
packages, a C compiler, Python 3 and Ziran. `make install` installs the command
|
||||
and desktop-menu entry for the current user; it does not publish a release.
|
||||
Harmony registry delivery and Android builds are not implemented in this first
|
||||
desktop version.
|
||||
|
||||
## Android
|
||||
|
||||
Arcade's APK opens the whole library offline: `make android` packs the
|
||||
collection with every game, its art and the Apps controller, and builds an
|
||||
unsigned release APK in `build/android/`. `make android-fdroid` and
|
||||
`make android-gplay` build the other editions; only `-gplay` carries a Google
|
||||
library (Play Billing). Builds need the Android SDK with NDK 28.2.13676358,
|
||||
build-tools 36.0.0, platform 36 and CMake 3.22.1, and Java 21.
|
||||
|
||||
```sh
|
||||
make android
|
||||
python3 scripts/android-release.py sign build/android/arcade-unsigned.apk --version "$(cat VERSION)"
|
||||
make android-offline-ui-test
|
||||
```
|
||||
|
||||
The release key is `backup/android-signing/arcade-release.p12` (ignored) and
|
||||
the GitHub secrets `ARCADE_ANDROID_KEYSTORE` and
|
||||
`ARCADE_ANDROID_KEYSTORE_PASSWORD`; `packaging/android/certificate.pem` is its
|
||||
public certificate. The Android workflow attaches `arcade-VERSION.apk`,
|
||||
`arcade-VERSION-fdroid.apk` and `arcade-VERSION-gplay.apk` to each
|
||||
`node-arcade-VERSION` release; Game updates starts it for every new release.
|
||||
|
||||
Game packages are registered in `games.json`; each declares its apps in its
|
||||
`apps.json`. `scripts/build-games.py` generates the catalog and bundles
|
||||
@@ -152,16 +202,30 @@ The cover collection requires an Inbe host with API 28 and the reviewed
|
||||
carousel controller. Older hosts must keep their compatible Arcade release.
|
||||
Building or installing never publishes.
|
||||
|
||||
`make collection` writes the same catalog to `build/arcade.zx`
|
||||
and `build/node-apps/arcade.zx`. Its exact game payloads
|
||||
are in `build/node-apps/arcade.games/`, named by their SHA-256, and in
|
||||
`build/node-apps/arcade.games.tar` for the existing signed node publisher.
|
||||
`make install-arcade` updates only Arcade's desktop launcher and catalog;
|
||||
it does not install game payloads. Previously downloaded games and saves stay
|
||||
in the person's private data directory.
|
||||
|
||||
## Shovey
|
||||
|
||||
[Shovey](https://github.com/waozixyz/shovey) has its own repository: Classic,
|
||||
Island and Editor, their artwork, puzzles and tests live there. Arcade installs
|
||||
Shovey by default and builds it from that package. Opening Classic
|
||||
[Shovey](https://github.com/waozixyz/shovey) has its own repository: Classic
|
||||
and the Editor, their artwork, puzzles and tests live there. Arcade builds
|
||||
Shovey from that package and offers it as a separate download. Opening Classic
|
||||
or Editor goes straight to its own screen; Levels lets you replay any unlocked
|
||||
puzzle. Shovey also runs as its own desktop app.
|
||||
|
||||
## Shared Entity profile
|
||||
|
||||
Leaderboard is inside the shared Profile, including standalone Arcade and
|
||||
Shovey. Games report their own level totals under their verified identity;
|
||||
Profile shows only games that are installed, with friend rankings for a
|
||||
connected account. Removing a game hides its board while retaining its save
|
||||
and reported score. Account switches keep rankings separate.
|
||||
|
||||
Standalone Shovey's Profile control on its covers opens the shared `entity.zx`
|
||||
supplied by the Entity package. The host keeps account keys and native file
|
||||
access behind Entity's versioned management service. Returning from Profile
|
||||
|
||||
@@ -1 +1 @@
|
||||
20ad36d054088484f069e3e7aa72135762fe25354fb8249ca0a2fcc019834a48
|
||||
fc63c84e19ce2f63fcd587478962c67aee31202353addcf840c9228d69c048c7
|
||||
@@ -1,5 +1,9 @@
|
||||
# Chess changelog
|
||||
|
||||
## [1.2.1] - 2026-10-29
|
||||
|
||||
- Runs in Inner Breeze 2.1.61's smaller app format.
|
||||
|
||||
## [1.2.0] - 2026-10-18
|
||||
|
||||
- Paste one PGN game or a FEN position into the study board.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"kind": "game",
|
||||
"contract_version": 1,
|
||||
"module_api": 2,
|
||||
"host_api": 12,
|
||||
"host_api": 41,
|
||||
"save_schema": 1,
|
||||
"harnesses": ["arcade", "inbe"],
|
||||
"entry": "chess:Main",
|
||||
|
||||
@@ -1,42 +1,56 @@
|
||||
{
|
||||
"host_api": 12,
|
||||
"oldest_host_api": 12,
|
||||
"host_api": 41,
|
||||
"oldest_host_api": 41,
|
||||
"module_api": 2,
|
||||
"node_apps": {
|
||||
"chess": {
|
||||
"id": "inbe.chess",
|
||||
"title": "Chess",
|
||||
"version": "1.2.0",
|
||||
"sequence": 5,
|
||||
"host_api": 12
|
||||
"version": "1.2.1",
|
||||
"sequence": 6,
|
||||
"host_api": 41
|
||||
},
|
||||
"choano": {
|
||||
"id": "xyz.waozi.choano",
|
||||
"title": "Choano",
|
||||
"version": "0.1.2",
|
||||
"sequence": 1,
|
||||
"host_api": 41
|
||||
},
|
||||
"shovey": {
|
||||
"id": "arcade.shovey",
|
||||
"title": "Shovey",
|
||||
"version": "0.6.141",
|
||||
"sequence": 149,
|
||||
"host_api": 12
|
||||
},
|
||||
"shovey-island": {
|
||||
"id": "arcade.shovey-island",
|
||||
"title": "Shovey Island \u2014 Coming Soon",
|
||||
"version": "0.4.6",
|
||||
"sequence": 10,
|
||||
"host_api": 12
|
||||
"version": "0.6.163",
|
||||
"sequence": 170,
|
||||
"host_api": 41
|
||||
},
|
||||
"shovey-editor": {
|
||||
"id": "arcade.shovey-editor",
|
||||
"title": "Shovey Editor",
|
||||
"version": "0.2.134",
|
||||
"sequence": 136,
|
||||
"host_api": 12
|
||||
"version": "0.2.147",
|
||||
"sequence": 149,
|
||||
"host_api": 41
|
||||
},
|
||||
"arcade": {
|
||||
"id": "inbe.arcade",
|
||||
"title": "Arcade",
|
||||
"version": "0.7.68",
|
||||
"sequence": 147,
|
||||
"host_api": 28
|
||||
"version": "0.7.112",
|
||||
"sequence": 191,
|
||||
"host_api": 41
|
||||
},
|
||||
"wurm": {
|
||||
"id": "xyz.waozi.wurm",
|
||||
"title": "Apfelwurm",
|
||||
"version": "0.2.27",
|
||||
"sequence": 22,
|
||||
"host_api": 41
|
||||
},
|
||||
"wurm-editor": {
|
||||
"id": "xyz.waozi.wurm-editor",
|
||||
"title": "Apfelwurm Editor",
|
||||
"version": "0.1.0",
|
||||
"sequence": 1,
|
||||
"host_api": 41
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 95 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 5.4 KiB |
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"choano-landscape": {
|
||||
"source_sha256": "1ca6e31c1062a7cca41bace4cf1bb221291988aea4a1dd61271899c2f5f28307"
|
||||
},
|
||||
"choano-portrait": {
|
||||
"source_sha256": "47b07722c474a67ee4a06b7644a3aff211503674391e363c17eb06a34ce60d6c"
|
||||
},
|
||||
"choano-preview": {
|
||||
"source_sha256": "1ca6e31c1062a7cca41bace4cf1bb221291988aea4a1dd61271899c2f5f28307"
|
||||
},
|
||||
"shovey-editor-landscape": {
|
||||
"source_sha256": "7b1eae4209ede14807806a4cbce1e2bf7a14d342e75c89042958a524cf60d67e"
|
||||
},
|
||||
"shovey-editor-logo": {
|
||||
"source_sha256": "5417341ed432c49d4ce1df45e5e6bf7e07e11a81face45cb93d7cc9fa976f7a5"
|
||||
},
|
||||
"shovey-editor-portrait": {
|
||||
"source_sha256": "bf0bbeb15249f3d73c1b410e9737f7fd207310dcb5f28b7c3ce45401b77c8f9e"
|
||||
},
|
||||
"shovey-editor-preview": {
|
||||
"source_sha256": "bcbf63563187f9dcdb6c7580f638e2fb2770b221240ee5699e54dc3c00be172c"
|
||||
},
|
||||
"shovey-landscape": {
|
||||
"source_sha256": "40c01eb8300e4c5db52b2d75373e17cdaf7f68140c33c0a225613fc174660747"
|
||||
},
|
||||
"shovey-logo": {
|
||||
"source_sha256": "e47781aa3328f68077589f95d813e9c2e6fff10ebd62a9d003773bb2c2f7a092"
|
||||
},
|
||||
"shovey-portrait": {
|
||||
"source_sha256": "ddcbf989eab5971157d8cdc73494ed03660bb4c7a7679543248f45be260777e3"
|
||||
},
|
||||
"shovey-preview": {
|
||||
"source_sha256": "96db251f36835c76cd03cd0104a6e1b5096e4c442d410960457edcd8e2377a38"
|
||||
},
|
||||
"wurm-editor-landscape": {
|
||||
"source_sha256": "670255e43a6fd232951fb3d1ce0d62d098d663230d731e7c447c44a944a907d3"
|
||||
},
|
||||
"wurm-editor-portrait": {
|
||||
"source_sha256": "f3475185324e4f4bfa37561f09422546eab5595ab3887d26e684128b2ac9480b"
|
||||
},
|
||||
"wurm-editor-preview": {
|
||||
"source_sha256": "670255e43a6fd232951fb3d1ce0d62d098d663230d731e7c447c44a944a907d3"
|
||||
},
|
||||
"wurm-landscape": {
|
||||
"source_sha256": "472773b7c106325e12777a81a29209496e22e0853782ca76955b6587824b1b30"
|
||||
},
|
||||
"wurm-portrait": {
|
||||
"source_sha256": "e8962c969f554567d598eb0b54db5836f7f1ed7462619463040c6cc2887a5a47"
|
||||
},
|
||||
"wurm-preview": {
|
||||
"source_sha256": "472773b7c106325e12777a81a29209496e22e0853782ca76955b6587824b1b30"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 110 KiB |
@@ -50,6 +50,9 @@ Unknown languages fall back to the game's English text.
|
||||
|
||||
Arcade and Inbe still provide separate local/account storage. Sharing one
|
||||
game implementation does not silently merge or migrate their saved games.
|
||||
Host API 36 adds read-only records explicitly exported to verified direct
|
||||
dependencies. Shovey exports its local campaign so Editor can display device
|
||||
unlocks alongside account progress without uploading device-only progress.
|
||||
|
||||
## Updates and publication gate
|
||||
|
||||
@@ -87,7 +90,15 @@ Host API numbers alone do not prove compatibility: the intended host must
|
||||
also understand the bundle's VM format. Test each platform and oldest host
|
||||
version a release is intended to support. An unsupported VM format requires
|
||||
a compatible build or a host update; never relabel a package to bypass it.
|
||||
Passing checks prepares a release; the owner still approves publication.
|
||||
Passing checks prepares a release.
|
||||
|
||||
Game releases reach Arcade players automatically. Every fifteen minutes the
|
||||
Game updates workflow compares each game package's latest published GitHub
|
||||
release with Arcade's pin (`scripts/follow-game-releases.py`). For a newer
|
||||
version it pins that release, adds the game's notes as a new Arcade version,
|
||||
builds and checks the collection, commits it and attaches the catalog to the
|
||||
`node-arcade-VERSION` release. Inner Breeze's Node app follower then signs
|
||||
that release and publishes it to Waozi's node.
|
||||
|
||||
Chess 1.1.0 requires host API 12. Public Inbe 2.1.34 supplies API 11 and
|
||||
predates installable Chess apps, so it is outside the declared range. The
|
||||
|
||||
@@ -22,6 +22,18 @@ def ledger = new groovy.json.JsonSlurper().parse(file('../../apps/versions.json'
|
||||
def appRelease = ledger.node_apps[standaloneShovey ? 'shovey' : 'arcade']
|
||||
|
||||
def appCodegen = envOrProp('KRYON_PROJECT_CODEGEN', 'app.codegen') ?: 'c99'
|
||||
// Kryon's three editions: -Papp.edition=direct (the default), fdroid or gplay.
|
||||
// Only the Google Play edition carries a Google library: Kryon's
|
||||
// android-gplay.gradle adds Play Billing (kryon/play_billing), so Entity sells
|
||||
// Dew through Google Play; it needs Android 6 and AndroidX
|
||||
// (-Pandroid.useAndroidX=true). Native code sees GOOGLE_PLAY or FDROID.
|
||||
def appEdition = (project.findProperty('app.edition') ?:
|
||||
(project.findProperty('app.googlePlay') == 'true' ? 'gplay' : 'direct')).toString()
|
||||
if (!(appEdition in ['direct', 'fdroid', 'gplay'])) {
|
||||
throw new GradleException('app.edition must be direct, fdroid or gplay')
|
||||
}
|
||||
def googlePlay = appEdition == 'gplay'
|
||||
def requestedMinSdk = Integer.parseInt((project.findProperty('app.minSdk') ?: '21').toString())
|
||||
def verificationOutput = project.findProperty('app.outputDir')
|
||||
if (verificationOutput != null) { buildDir = file(verificationOutput) }
|
||||
|
||||
@@ -32,11 +44,11 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
applicationId project.findProperty('app.id') ?: (standaloneShovey ? 'xyz.waozi.shovey' : 'xyz.waozi.arcade')
|
||||
minSdk Integer.parseInt((project.findProperty('app.minSdk') ?: '21').toString())
|
||||
minSdk googlePlay ? Math.max(requestedMinSdk, 23) : requestedMinSdk
|
||||
targetSdk 36
|
||||
versionCode Integer.parseInt((project.findProperty('app.versionCode') ?: appRelease.sequence).toString())
|
||||
versionName project.findProperty('app.versionName') ?: appRelease.version
|
||||
manifestPlaceholders = [appLabel: standaloneShovey ? 'Shovey' : 'Arcade', appIcon: standaloneShovey ? '@mipmap/ic_launcher' : '@android:drawable/sym_def_app_icon', zxPlayer: (appCodegen == 'zx').toString(),
|
||||
manifestPlaceholders = [appLabel: standaloneShovey ? 'Shovey' : 'Arcade', appIcon: '@mipmap/ic_launcher', zxPlayer: (appCodegen == 'zx').toString(),
|
||||
nativeLaunchMode: appCodegen == 'zx' ? 'singleTask' : 'standard']
|
||||
ndk {
|
||||
abiFilters += androidAbis
|
||||
@@ -47,7 +59,8 @@ android {
|
||||
'-DZIRAN_DIR=' + ziranDir,
|
||||
'-DRAYLIB_DIR=' + raylibDir,
|
||||
'-DAPP_CODEGEN=' + appCodegen,
|
||||
'-DSHOVEY_STANDALONE=' + (standaloneShovey ? 'ON' : 'OFF')
|
||||
'-DSHOVEY_STANDALONE=' + (standaloneShovey ? 'ON' : 'OFF'),
|
||||
'-DAPP_EDITION=' + appEdition
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,11 +74,10 @@ android {
|
||||
}
|
||||
|
||||
sourceSets.main.assets.srcDir "${rootProject.projectDir}/../build/entity-assets"
|
||||
// Arcade's collection and receipt, staged by make android.
|
||||
// The collection, its receipt and the launcher icon, staged by make android
|
||||
// (scripts/build-android.py).
|
||||
sourceSets.main.assets.srcDir "${rootProject.projectDir}/../build/${standaloneShovey ? 'android-shovey-assets' : 'android-assets'}"
|
||||
if (standaloneShovey) {
|
||||
sourceSets.main.res.srcDir "${rootProject.projectDir}/../build/android-shovey-res"
|
||||
}
|
||||
sourceSets.main.res.srcDir "${rootProject.projectDir}/../build/${standaloneShovey ? 'android-shovey-res' : 'android-res'}"
|
||||
|
||||
if (appCodegen == 'zx') {
|
||||
sourceSets.main.assets.srcDir "${rootProject.projectDir}/../build/android/zx-assets"
|
||||
@@ -80,6 +92,10 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
if (googlePlay) {
|
||||
apply from: new File(kryonDir, 'templates/android-gplay.gradle')
|
||||
}
|
||||
|
||||
// The shared profile is a host asset, never a child of a game collection.
|
||||
tasks.register('prepareEntity', Exec) {
|
||||
workingDir file('../..')
|
||||
|
||||
@@ -26,6 +26,12 @@ set(APP_ZIRAN_DEFINES --define ANDROID_BUILD)
|
||||
if(SHOVEY_STANDALONE)
|
||||
list(APPEND APP_ZIRAN_DEFINES --define SHOVEY_STANDALONE)
|
||||
endif()
|
||||
# The app's edition (build.gradle app.edition): Google Play or F-Droid.
|
||||
if(APP_EDITION STREQUAL "gplay")
|
||||
list(APPEND APP_ZIRAN_DEFINES --define GOOGLE_PLAY)
|
||||
elseif(APP_EDITION STREQUAL "fdroid")
|
||||
list(APPEND APP_ZIRAN_DEFINES --define FDROID)
|
||||
endif()
|
||||
if(NOT DEFINED APP_CODEGEN)
|
||||
set(APP_CODEGEN c99)
|
||||
endif()
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"packages": ["shovey"]
|
||||
"packages": ["shovey", "wurm", "choano"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIFBzCCAu+gAwIBAgIIV4HQ6go6XYwwDQYJKoZIhvcNAQEMBQAwMTELMAkGA1UE
|
||||
BhMCUFkxEjAQBgNVBAoTCXdhb3ppLnh5ejEOMAwGA1UEAxMFV2FvemkwIBcNMjYx
|
||||
MDI5MjIwNzU3WhgPMjA3NjEwMjgyMjA3NTdaMDExCzAJBgNVBAYTAlBZMRIwEAYD
|
||||
VQQKEwl3YW96aS54eXoxDjAMBgNVBAMTBVdhb3ppMIICIjANBgkqhkiG9w0BAQEF
|
||||
AAOCAg8AMIICCgKCAgEAxuar9BhVOeDtMIY1xUFfiEFZZlV+kiTDNWgW/3omykxd
|
||||
tPz4Y28FgqkV2SX7eEqzMzrsjJ6Z8U2QD1TsY1cTrxjih1f8yhNP5poZAgD6DhHb
|
||||
ra1DYHXMRJTCJlASUnoZj5xr4M7ha428xit4Fz0IR88TpN6NZsNNwCy5xQSj/cIX
|
||||
fCTo9n/3itJIGpiKas2J4xancfVSXoLpGBaXf/Vaf/w0UfTxIgImam/U/mx366M+
|
||||
Vv23XPLBa6csT1EjKTOTB6Oyj3fxDJ/HI7T0pm86eA7hvu+LrQ1v2q1I7DwUg5RG
|
||||
HoAeFsNnsHSEluVdnuD+7ESnKTkoNlQe8cAiBXvlpcw6uDdpp/2oMktdrd4xt1tU
|
||||
ozVqiPrvvF/G0Ki1MCS9PXJ6FERBQVjaklPYVa8c2tuXvTcX6VNCpcyFqgNo6AUk
|
||||
nNkhOhPJ2R0OhQGloG5CcdkjHY1W60gudQKK9MMLjf2+or7ewl/nOkHKhPUKjBQO
|
||||
UjTlRG6M+hOzZ/rI+LIJsxCZD4xAP6g2oyH0ROR8SXm3x7l+VZ7r9qW0i8cKxOvC
|
||||
IlX/JQfUkAwcyK0HPQVUPutvtySiMSefZTczvvi+YmiDqr+cxW0T9388SxV+lKQz
|
||||
Rz+6Tby6OyRDM6bJtXaqZTH+lSdmrAI/lbBx5+Yx8+xgHcfgGbpU2h+WOnqwtCEC
|
||||
AwEAAaMhMB8wHQYDVR0OBBYEFPTOgtLO/ZKqfXFOQshN7JHi5yVyMA0GCSqGSIb3
|
||||
DQEBDAUAA4ICAQCxiEH8bPrJlkin92zESDrwXqyfNc7VuoFrANxCD4Mu6/rGU+4V
|
||||
UIVz3BPhDFZV281ztD0eSJef+P5UX/k4Y0pVIzw82iKAjaMiu8wFZghcFsaADQQn
|
||||
YEqrU9158++2H2nsxSL2uSen8qPOea7IMll9SUtg+YqAkXqEToqIv60SDFZUpKnb
|
||||
O3W/NYzVqNKYCk7/HcOYuNf5r76EGVYz6aPHP1CgEpnXNC8NotbH24ZNF3Zgy+UP
|
||||
ypoNx1jffUK+wQbXkE+IadBhw7B1vPIzCZji1zz54sBxhqvTAKCWE10fMEllSu3v
|
||||
HRB0x4feOs4tfuX38UdUrFHDxG7vrrNrCRDwnQ6k6FWUVpJRM9CV9jbUe0bcBQfP
|
||||
SpqJfQMOXPVET799rC4lW4HMGIhfoTkPymYuWZAZx4pF3SYLHor7cQv05a3RuvjP
|
||||
46xkz9ZA9HNU6P2+mgpRuuFSbxyxi5uyT9z5J/vrU45wq2UjwdNn8J/3o4ITcT9o
|
||||
jP20JOHovIrprLi8Wzpb/0o1BagRuqlfVoCJrRNCpoZY98ynAM9swlgL+s5O9LVo
|
||||
mTTtZdDoTyMN+IXxark7oHjUHhWgd/VThTXJu1rQ++vSh/GajYRSOKDjxayGHBp2
|
||||
rjWy9esT5/VdzFlMfOZefeEjSol8tZdjNCCmWRFuOqF+zw7Lc4I5fXqK8g==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sign and verify Arcade's Android APKs: the normal and F-Droid editions,
|
||||
which hold no Google library, and the Google Play edition, the only one with
|
||||
Play Billing. Each carries the whole library for offline play."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ABIS = ['arm64-v8a', 'armeabi-v7a']
|
||||
|
||||
|
||||
def build_tools():
|
||||
sdk = Path(os.environ.get('ANDROID_SDK_ROOT') or os.environ.get('ANDROID_HOME') or Path.home() / 'Android/Sdk')
|
||||
folders = sorted((sdk / 'build-tools').glob('*'), key=lambda p: tuple(int(n) for n in re.findall(r'\d+', p.name)))
|
||||
return next(p for p in reversed(folders) if all((p / name).is_file() for name in ('aapt', 'apksigner', 'zipalign')))
|
||||
|
||||
|
||||
def verify(apk, version, tools, edition='direct'):
|
||||
assert re.fullmatch(r'\d+\.\d+\.\d+', version), 'A numeric release version is required'
|
||||
changelog = (ROOT / 'CHANGELOG.md').read_text()
|
||||
assert re.search(r'^## \[?' + re.escape(version) + r'\]?\s', changelog, re.M), 'Release version is absent from the changelog'
|
||||
badging = subprocess.check_output([str(tools / 'aapt'), 'dump', 'badging', str(apk)], text=True)
|
||||
package = re.search(r"^package: name='([^']+)' versionCode='(\d+)' versionName='([^']+)'", badging, re.M)
|
||||
assert package and package[1] == 'xyz.waozi.arcade' and package[3] == version, 'APK identity or version differs'
|
||||
assert "application-label:'Arcade'" in badging, 'The APK is not labelled Arcade'
|
||||
# Release builds shorten resource names; the manifest names the icon.
|
||||
icon = re.search(r"^application: label='Arcade' icon='(res/[^']+\.png)'", badging, re.M)
|
||||
assert icon, "Arcade's launcher icon is missing"
|
||||
assert 'application-debuggable' not in badging, 'A debug build cannot be published'
|
||||
google_play = edition == 'gplay'
|
||||
assert ("'com.android.vending.BILLING'" in badging) == google_play, \
|
||||
'Only the Google Play edition may ask for Play Billing'
|
||||
certificate = subprocess.check_output(['openssl', 'x509', '-in', str(ROOT / 'packaging/android/certificate.pem'), '-outform', 'DER'])
|
||||
expected = hashlib.sha256(certificate).hexdigest()
|
||||
signature = subprocess.check_output([str(tools / 'apksigner'), 'verify', '--verbose', '--print-certs', str(apk)], text=True)
|
||||
actual = re.findall(r'^(?:Signer #\d+|V[\d.]+ Signer:) certificate SHA-256 digest: ([0-9a-f]+)$', signature, re.M)
|
||||
assert 'Number of signers: 1' in signature and set(actual) == {expected}, 'APK signer differs from the Arcade release certificate'
|
||||
subprocess.run([str(tools / 'zipalign'), '-c', '-P', '16', '4', str(apk)], check=True, capture_output=True)
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
names = archive.namelist()
|
||||
abis = sorted(p.split('/')[1] for p in names if re.fullmatch(r'lib/[^/]+/libmain\.so', p))
|
||||
assert abis == ABIS, 'Both supported ARM architectures must be present'
|
||||
assert icon[1] in names, "Arcade's launcher icon is missing"
|
||||
metadata = json.loads(archive.read('assets/arcade.json'))
|
||||
payload = archive.read('assets/arcade.zx')
|
||||
assert metadata['id'] == 'inbe.arcade' and metadata['version'] == version
|
||||
assert metadata['sha256'] == hashlib.sha256(payload).hexdigest(), 'Embedded collection differs from its receipt'
|
||||
# Offline play: every game in the catalog is packed into the collection.
|
||||
assert metadata.get('games') == 'packed' and 'art' not in metadata and metadata['children'], \
|
||||
'The collection must pack its games and art'
|
||||
for child in metadata['children']:
|
||||
assert child['bundle'].encode() in payload, f"{child['id']} is not packed for offline play"
|
||||
dex = b''.join(archive.read(name) for name in names if re.fullmatch(r'classes\d*\.dex', name))
|
||||
for marker in (b'Lorg/kryonlabs/play/PlayBilling;', b'Lcom/android/billingclient/'):
|
||||
assert (marker in dex) == google_play, 'Only the Google Play edition may include Play Billing'
|
||||
return dict(version=version, version_code=int(package[2]), package=package[1], abis=abis, edition=edition,
|
||||
sha256=hashlib.sha256(apk.read_bytes()).hexdigest(), certificate_sha256=expected,
|
||||
payload_sha256=metadata['sha256'], games=[child['id'] for child in metadata['children']],
|
||||
bytes=apk.stat().st_size)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('sign', 'verify'))
|
||||
parser.add_argument('apk', type=Path)
|
||||
parser.add_argument('--version', required=True)
|
||||
parser.add_argument('--edition', choices=('direct', 'fdroid', 'gplay'), default='direct')
|
||||
parser.add_argument('--output', type=Path, help='Signed APK; build/android/arcade-VERSION[-EDITION].apk by default')
|
||||
parser.add_argument('--keystore', type=Path, default=ROOT / 'backup/android-signing/arcade-release.p12')
|
||||
parser.add_argument('--password-file', type=Path, default=ROOT / 'backup/android-signing/password')
|
||||
parser.add_argument('--alias', default='arcade')
|
||||
args = parser.parse_args()
|
||||
tools = build_tools()
|
||||
apk = args.apk.resolve(strict=True)
|
||||
if args.action == 'verify':
|
||||
verify(apk, args.version, tools, args.edition)
|
||||
print(f'Arcade {args.version} {args.edition}: APK identity, signer, alignment and offline games verified')
|
||||
return
|
||||
suffix = '' if args.edition == 'direct' else '-' + args.edition
|
||||
output = (args.output or ROOT / f'build/android/arcade-{args.version}{suffix}.apk').resolve()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
aligned = output.with_name(output.stem + '.aligned-unsigned.apk')
|
||||
temporary = output.with_name(output.stem + '.new.apk')
|
||||
if subprocess.run([str(tools / 'zipalign'), '-c', '-P', '16', '4', str(apk)], capture_output=True).returncode == 0:
|
||||
shutil.copyfile(apk, aligned)
|
||||
else:
|
||||
subprocess.run([str(tools / 'zipalign'), '-P', '16', '-f', '4', str(apk), str(aligned)], check=True)
|
||||
try:
|
||||
# Keep the aligned entries as they are, so a rebuild from source can
|
||||
# take this signature unchanged.
|
||||
subprocess.run([str(tools / 'apksigner'), 'sign', '--alignment-preserved',
|
||||
'--ks', str(args.keystore.resolve(strict=True)), '--ks-key-alias', args.alias,
|
||||
'--ks-pass', 'file:' + str(args.password_file.resolve(strict=True)),
|
||||
'--out', str(temporary), str(aligned)], check=True)
|
||||
finally:
|
||||
aligned.unlink(missing_ok=True)
|
||||
try:
|
||||
result = verify(temporary, args.version, tools, args.edition)
|
||||
except BaseException:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise
|
||||
temporary.replace(output)
|
||||
temporary.with_name(temporary.name + '.idsig').unlink(missing_ok=True)
|
||||
result['apk'] = str(output)
|
||||
records = ROOT / 'backup/android-release'
|
||||
records.mkdir(parents=True, exist_ok=True)
|
||||
(records / f'verification{suffix}.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
print(f'Arcade {args.version} {args.edition}: signed {output}; identity, signer, alignment and offline games verified')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Package Arcade's existing native host with the standalone Shovey collection."""
|
||||
"""Package Arcade's native Android host: Arcade with its whole library offline,
|
||||
or the older standalone Shovey collection."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
@@ -14,15 +15,51 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
def package(name):
|
||||
return Path(subprocess.check_output([str(ROOT / 'scripts/ziran.sh'), 'pkg', 'path', name], cwd=ROOT, text=True).strip())
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--release', action='store_true', help='Build an unsigned release APK for the release signer')
|
||||
parser.add_argument('--bundle', action='store_true', help='Build an unsigned release Android App Bundle for Google Play')
|
||||
parser.add_argument('--application-id', help='Use an isolated package for device tests')
|
||||
parser.add_argument('--abis', default='arm64-v8a,armeabi-v7a', help='Native ABIs to build')
|
||||
parser.add_argument('--build-dir', type=Path, help='Separate Gradle and CMake output for verification')
|
||||
args = parser.parse_args()
|
||||
subprocess.run(['make', 'build/entity.zx'], cwd=ROOT, check=True)
|
||||
def ziran_bundle(*arguments):
|
||||
# A local checkout overrides packages in ziran.local.toml, as make does.
|
||||
locked = [] if (ROOT / 'ziran.local.toml').exists() else ['--locked']
|
||||
subprocess.run([str(ROOT / 'scripts/ziran.sh'), 'bundle', '--project', *locked, *arguments],
|
||||
cwd=ROOT, check=True)
|
||||
|
||||
def launcher_icon(source, resources):
|
||||
"""Density variants are mechanical packaging of the original logo."""
|
||||
icon = Image.open(source).convert('RGBA')
|
||||
if resources.exists():
|
||||
shutil.rmtree(resources)
|
||||
for density, size in (('mdpi', 48), ('hdpi', 72), ('xhdpi', 96), ('xxhdpi', 144), ('xxxhdpi', 192)):
|
||||
folder = resources / ('mipmap-' + density)
|
||||
folder.mkdir(parents=True)
|
||||
icon.resize((size, size), Image.Resampling.LANCZOS).save(folder / 'ic_launcher.png')
|
||||
|
||||
def stage_arcade():
|
||||
"""Pack the staged collection with its games, art and Apps controller, so
|
||||
the APK opens the whole library offline. Returns Arcade's release."""
|
||||
collection = ROOT / 'build/collection'
|
||||
receipt = json.loads((collection / 'receipt.json').read_text())
|
||||
release = json.loads((ROOT / 'apps/versions.json').read_text())['node_apps']['arcade']
|
||||
if receipt['version'] != release['version'] or receipt['version'] != (ROOT / 'VERSION').read_text().strip():
|
||||
raise ValueError('The Arcade version changed; rebuild the collection first')
|
||||
controller = (collection / 'assets/apps/apps.zx').read_bytes()
|
||||
if hashlib.sha256(controller).hexdigest() != receipt['apps_sha256']:
|
||||
raise ValueError('The staged Apps controller differs from the receipt')
|
||||
assets = ROOT / 'build/android-assets'
|
||||
if assets.exists():
|
||||
shutil.rmtree(assets)
|
||||
assets.mkdir(parents=True)
|
||||
ziran_bundle('--root', str(ROOT / 'src'), '--entry', 'collection:Main',
|
||||
'--asset-dir', 'assets=' + str(collection / 'assets'), '-o', str(assets / 'arcade.zx'),
|
||||
str(ROOT / 'src/collection.zi'))
|
||||
# The library packs its games and art: the host downloads nothing.
|
||||
offline = {key: value for key, value in receipt.items() if key != 'art'} | {'games': 'packed'}
|
||||
offline['sha256'] = hashlib.sha256((assets / 'arcade.zx').read_bytes()).hexdigest()
|
||||
(assets / 'arcade.json').write_text(json.dumps(offline, indent=2) + '\n')
|
||||
# Android before 10 has no font lookup; the Windows build ships the same font.
|
||||
shutil.copyfile(package('kryon') / 'assets/fonts/LiberationSans-Regular.ttf', assets / 'kryon-font.ttf')
|
||||
launcher_icon(ROOT / 'site/icon-512.png', ROOT / 'build/android-res')
|
||||
return release
|
||||
|
||||
def stage_shovey():
|
||||
"""Shovey's standalone collection from Arcade's staging. Returns its release."""
|
||||
metadata = json.loads((ROOT / 'build/shovey.json').read_text())
|
||||
payload = (ROOT / 'build/shovey.zx').read_bytes()
|
||||
if hashlib.sha256(payload).hexdigest() != metadata['sha256']:
|
||||
@@ -34,26 +71,45 @@ def main():
|
||||
assets.mkdir(parents=True, exist_ok=True)
|
||||
for suffix in ('zx', 'json'):
|
||||
shutil.copyfile(ROOT / f'build/shovey.{suffix}', assets / f'arcade.{suffix}')
|
||||
# Android before 10 has no font lookup; the Windows build ships the same font.
|
||||
shutil.copyfile(package('kryon') / 'assets/fonts/LiberationSans-Regular.ttf', assets / 'kryon-font.ttf')
|
||||
# Density variants are mechanical packaging of the original generated logo.
|
||||
icon = Image.open(package('shovey') / 'assets/branding/shovey-icon.png').convert('RGBA')
|
||||
resources = ROOT / 'build/android-shovey-res'
|
||||
for density, size in (('mdpi', 48), ('hdpi', 72), ('xhdpi', 96), ('xxhdpi', 144), ('xxxhdpi', 192)):
|
||||
folder = resources / ('mipmap-' + density)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
icon.resize((size, size), Image.Resampling.LANCZOS).save(folder / 'ic_launcher.png')
|
||||
launcher_icon(package('shovey') / 'assets/branding/shovey-icon.png', ROOT / 'build/android-shovey-res')
|
||||
return release
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--product', choices=('shovey', 'arcade'), default='shovey',
|
||||
help='arcade: Arcade with its whole library; shovey: the standalone Shovey collection')
|
||||
parser.add_argument('--release', action='store_true', help='Build an unsigned release APK for the release signer')
|
||||
parser.add_argument('--edition', choices=('direct', 'fdroid', 'gplay'), default='direct',
|
||||
help='The APK edition; only gplay carries a Google library')
|
||||
parser.add_argument('--bundle', action='store_true',
|
||||
help="Build the Google Play edition's unsigned release Android App Bundle")
|
||||
parser.add_argument('--application-id', help='Use an isolated package for device tests')
|
||||
parser.add_argument('--abis', default='arm64-v8a,armeabi-v7a', help='Native ABIs to build')
|
||||
parser.add_argument('--build-dir', type=Path, help='Separate Gradle and CMake output for verification')
|
||||
args = parser.parse_args()
|
||||
arcade = args.product == 'arcade'
|
||||
if arcade and args.bundle:
|
||||
parser.error('Arcade builds APKs; the App Bundle is the standalone Shovey one')
|
||||
subprocess.run(['make', 'build/entity.zx'], cwd=ROOT, check=True)
|
||||
release = stage_arcade() if arcade else stage_shovey()
|
||||
sdk = Path(os.environ.get('ANDROID_SDK_ROOT') or os.environ.get('ANDROID_HOME') or Path.home() / 'Android/Sdk')
|
||||
env = {key: value for key, value in os.environ.items() if key not in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS')}
|
||||
env.update(ANDROID_HOME=str(sdk), ANDROID_SDK_ROOT=str(sdk),
|
||||
LIBOQS_DIR=str(package('liboqs')), MONOCYPHER_DIR=str(package('monocypher')))
|
||||
command = ['sh', str(ROOT / 'droid/gradlew'), '-p', str(ROOT / 'droid'), '--no-daemon', '--max-workers=2',
|
||||
'-Papp.product=shovey', '-Papp.abis=' + args.abis,
|
||||
'-Papp.product=' + args.product, '-Papp.abis=' + args.abis,
|
||||
'-Pkryon.dir=' + str(package('kryon')), '-Pziran.dir=' + str(package('ziran')),
|
||||
'-Praylib.dir=' + str(package('raylib') / 'src'),
|
||||
'-Papp.versionName=' + metadata['version'], '-Papp.versionCode=' + str(release['sequence']),
|
||||
'-Papp.versionName=' + release['version'], '-Papp.versionCode=' + str(release['sequence']),
|
||||
'-Pandroid.aapt2FromMavenOverride=' + str(sdk / 'build-tools/36.0.0/aapt2'),
|
||||
'bundleRelease' if args.bundle else 'assembleRelease' if args.release else 'assembleDebug']
|
||||
# Kryon's Google Play edition adds Play Billing, so Dew is bought through Play.
|
||||
edition = 'gplay' if args.bundle else args.edition
|
||||
if edition == 'gplay':
|
||||
command[-1:-1] = ['-Papp.edition=gplay', '-Pandroid.useAndroidX=true']
|
||||
elif edition == 'fdroid':
|
||||
command.insert(-1, '-Papp.edition=fdroid')
|
||||
if args.application_id:
|
||||
command.insert(-1, '-Papp.id=' + args.application_id)
|
||||
if args.build_dir:
|
||||
@@ -68,6 +124,13 @@ def main():
|
||||
return
|
||||
apk = app_output / ('outputs/apk/release/app-release-unsigned.apk' if args.release else
|
||||
'outputs/apk/debug/app-debug.apk')
|
||||
if arcade:
|
||||
suffix = '' if edition == 'direct' else '-' + edition
|
||||
output = ROOT / 'build/android' / (f'arcade{suffix}-unsigned.apk' if args.release else f'arcade{suffix}.apk')
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(apk, output)
|
||||
print(f'Arcade APK: {output}')
|
||||
return
|
||||
output = ROOT / ('build/shovey-test-unsigned.apk' if args.application_id else
|
||||
'build/shovey-unsigned.apk' if args.release else 'build/shovey.apk')
|
||||
shutil.copyfile(apk, output)
|
||||
|
||||
@@ -1,23 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the reviewed Apps controller from its locked package, including in development."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import tomllib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def controller_context(root, context):
|
||||
"""Keep the host's exact launcher graph without fetching unrelated games."""
|
||||
manifest = tomllib.loads((root / 'ziran.toml').read_text())
|
||||
lock = json.loads((root / 'ziran.lock').read_text())
|
||||
packages = {package['id']: package for package in lock['packages']}
|
||||
needed = set()
|
||||
|
||||
def include(identifier):
|
||||
if identifier in needed:
|
||||
return
|
||||
needed.add(identifier)
|
||||
for dependency in packages[identifier]['dependencies'].values():
|
||||
include(dependency)
|
||||
|
||||
launcher = lock['root']['dependencies']['apps']
|
||||
include(launcher)
|
||||
lock['packages'] = [package for package in lock['packages'] if package['id'] in needed]
|
||||
lock['root']['dependencies'] = {'apps': launcher}
|
||||
lines = ['[package]', 'name = ' + json.dumps(lock['root']['name'])]
|
||||
for section, values in [('toolchain', manifest['toolchain']),
|
||||
('dependencies.apps', manifest['dependencies']['apps'])]:
|
||||
lines.extend(['', '[' + section + ']'])
|
||||
lines.extend(key + ' = ' + json.dumps(value) for key, value in values.items())
|
||||
(context / 'ziran.toml').write_text('\n'.join(lines) + '\n')
|
||||
(context / 'ziran.lock').write_text(json.dumps(lock, indent=2) + '\n')
|
||||
|
||||
|
||||
def build(root, output):
|
||||
(root / 'build').mkdir(exist_ok=True)
|
||||
# --locked rejects local overrides. Resolve using only the committed
|
||||
# package inputs, so local Kryon/toolchain work cannot change trusted bytes.
|
||||
with tempfile.TemporaryDirectory(prefix='apps-lock-', dir=root / 'build') as directory:
|
||||
context = Path(directory)
|
||||
for name in ('ziran.toml', 'ziran.lock'):
|
||||
shutil.copyfile(root / name, context / name)
|
||||
controller_context(root, context)
|
||||
package = Path(subprocess.check_output(
|
||||
['ziran', 'pkg', 'path', 'apps', '--locked'], cwd=context, text=True).strip())
|
||||
subprocess.run([sys.executable, str(package / 'scripts/build-ui.py'),
|
||||
|
||||
@@ -9,6 +9,7 @@ from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
from game_packages import declared_packages
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -20,14 +21,30 @@ def digest(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def library_art(root, name, key, source):
|
||||
"""Arcade's committed library thumbnail (scripts/library-art.py), as
|
||||
(bytes, suffix): a PNG, or a JPEG for opaque cover art. Never pack a copy
|
||||
of outdated art."""
|
||||
library = Path(root) / "assets/arcade/library"
|
||||
sources = json.loads((library / "sources.json").read_text())
|
||||
copy = f"{name}-{key}"
|
||||
if sources.get(copy, {}).get("source_sha256") != hashlib.sha256(source).hexdigest():
|
||||
raise ValueError(f"{copy} art changed; run scripts/library-art.py")
|
||||
for suffix in (".png", ".jpg"):
|
||||
if (library / (copy + suffix)).is_file():
|
||||
return (library / (copy + suffix)).read_bytes(), suffix
|
||||
raise ValueError(f"{copy} has no library copy; run scripts/library-art.py")
|
||||
|
||||
|
||||
def stage(root, controller, expected_controller_digest, output):
|
||||
"""Validate before replacing a previously staged collection. Returns the
|
||||
catalog and each game package with the IDs of its packed apps."""
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", expected_controller_digest):
|
||||
raise ValueError("An exact trusted Apps controller SHA-256 is required")
|
||||
controller_bytes = controller.read_bytes()
|
||||
if hashlib.sha256(controller_bytes).hexdigest() != expected_controller_digest:
|
||||
raise ValueError("Apps controller differs from the trusted SHA-256")
|
||||
controller_digest = hashlib.sha256(controller_bytes).hexdigest()
|
||||
if controller_digest != expected_controller_digest:
|
||||
raise ValueError(f"Apps controller differs from the trusted SHA-256: {controller_digest} != {expected_controller_digest}")
|
||||
packages = declared_packages(root)
|
||||
arcade = packages[0]
|
||||
if not 1 <= sum(len(package["apps"]) for package in packages) <= MAX_GAMES:
|
||||
@@ -63,13 +80,28 @@ def stage(root, controller, expected_controller_digest, output):
|
||||
bundle_bytes, preview_bytes = bundle.read_bytes(), preview.read_bytes()
|
||||
if not bundle_bytes or not preview_bytes:
|
||||
raise ValueError("Game bundles and previews must be built first")
|
||||
preview_bytes, preview_suffix = library_art(root, name, "preview", preview_bytes)
|
||||
total += len(bundle_bytes) + len(preview_bytes)
|
||||
child = dict(
|
||||
id=identifier, title=game["title"],
|
||||
bundle=f"assets/arcade/games/{name}.zx", protocol="node/2",
|
||||
expected_id=name, version=component["version"],
|
||||
sha256=hashlib.sha256(bundle_bytes).hexdigest(),
|
||||
preview=f"assets/arcade/previews/{name}.png")
|
||||
bytes=len(bundle_bytes),
|
||||
preview=f"assets/arcade/previews/{name}{preview_suffix}",
|
||||
icon=f"assets/arcade/previews/{name}{preview_suffix}")
|
||||
# A thin add-on links its required games' verified code as libraries.
|
||||
if app.get('shared_code'):
|
||||
child['shared_code'] = True
|
||||
if app.get('shared_records'):
|
||||
child['shared_records'] = app['shared_records']
|
||||
if app.get('requires'):
|
||||
shared = json.loads((root / 'build/games' / (name + '-resources.json')).read_text())
|
||||
if shared['dependencies'] != app['requires']:
|
||||
raise ValueError('Game resource dependencies differ from its manifest')
|
||||
child['dependencies'] = shared['dependencies']
|
||||
if shared['resources']:
|
||||
child['resources'] = shared['resources']
|
||||
# The package's declared cover: the library opens the app from it.
|
||||
cover = app["cover"]
|
||||
if cover:
|
||||
@@ -78,10 +110,10 @@ def stage(root, controller, expected_controller_digest, output):
|
||||
if key not in cover:
|
||||
continue
|
||||
relative = Path(cover[key])
|
||||
if relative.is_absolute() or ".." in relative.parts or relative.suffix != ".png":
|
||||
if relative.is_absolute() or ".." in relative.parts or relative.suffix not in {".png", ".jpg"}:
|
||||
raise ValueError("Invalid cover asset path")
|
||||
contents = (app["source"] / relative).read_bytes()
|
||||
destination = Path("arcade/covers") / f"{name}-{key}.png"
|
||||
contents, suffix = library_art(root, name, key, (app["source"] / relative).read_bytes())
|
||||
destination = Path("arcade/covers") / f"{name}-{key}{suffix}"
|
||||
packed_cover[key] = "assets/" + destination.as_posix()
|
||||
copies.append((contents, destination))
|
||||
total += len(contents)
|
||||
@@ -89,11 +121,11 @@ def stage(root, controller, expected_controller_digest, output):
|
||||
children.append(child)
|
||||
package["children"].append(identifier)
|
||||
copies += [(bundle_bytes, Path("arcade/games") / (name + ".zx")),
|
||||
(preview_bytes, Path("arcade/previews") / (name + ".png"))]
|
||||
(preview_bytes, Path("arcade/previews") / (name + preview_suffix))]
|
||||
if total > MAX_PAYLOAD_BYTES:
|
||||
raise ValueError("Arcade collection exceeds the host's payload limit")
|
||||
catalog = dict(schema=1, id=arcade["id"], title=arcade["title"],
|
||||
harness="assets/apps/apps.zx", children=children)
|
||||
harness="assets/apps/apps.zx", presentation={"mode": "covers"}, children=children)
|
||||
# This stable directory contains disposable build output only. Clear it
|
||||
# after all inputs validate so removed registrations cannot linger.
|
||||
if output.exists():
|
||||
@@ -112,6 +144,64 @@ def stage(root, controller, expected_controller_digest, output):
|
||||
return catalog, packages[1:]
|
||||
|
||||
|
||||
def stage_downloads(catalog, source, output, games, art):
|
||||
"""Keep only Arcade's catalog; serve each game and the library art separately.
|
||||
|
||||
The published Arcade is a launcher: the host supplies the shared Apps
|
||||
controller, and the games' covers and previews go to ART for one separate
|
||||
download. The full staging directory is also used by standalone players,
|
||||
which keep their bundled games, art and controller. Validate every game
|
||||
before replacing outputs.
|
||||
"""
|
||||
payloads = {}
|
||||
for child in catalog["children"]:
|
||||
data = (source / child["bundle"]).read_bytes()
|
||||
if hashlib.sha256(data).hexdigest() != child["sha256"]:
|
||||
raise ValueError("Game differs from the collection's declared digest")
|
||||
payloads[child["sha256"]] = data
|
||||
for directory in (output, games, art):
|
||||
if directory.exists():
|
||||
shutil.rmtree(directory)
|
||||
shutil.copytree(source, output)
|
||||
games.mkdir(parents=True)
|
||||
(output / catalog["harness"]).unlink()
|
||||
for child in catalog["children"]:
|
||||
(output / child["bundle"]).unlink()
|
||||
pictures = [child["preview"]] + [path for key, path in child.get("cover", {}).items()
|
||||
if key in ("portrait", "landscape", "logo")]
|
||||
for relative in pictures:
|
||||
if not (output / relative).exists():
|
||||
continue
|
||||
destination = art / relative
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(output / relative, destination)
|
||||
for digest, data in payloads.items():
|
||||
(games / (digest + ".zx")).write_bytes(data)
|
||||
|
||||
|
||||
def add_art(output, games, art_bundle):
|
||||
"""Publish the art bundle beside the games and name it in the catalog."""
|
||||
data = art_bundle.read_bytes()
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
(games / (digest + ".zx")).write_bytes(data)
|
||||
path = output / "assets/apps/catalog.json"
|
||||
catalog = json.loads(path.read_text())
|
||||
catalog["art"] = dict(sha256=digest, bytes=len(data))
|
||||
path.write_text(json.dumps(catalog, indent=2) + "\n")
|
||||
return catalog["art"]
|
||||
|
||||
|
||||
def archive_downloads(games, archive):
|
||||
"""The release asset contains only the immutable game payloads."""
|
||||
with tarfile.open(archive, "w") as output:
|
||||
for path in sorted(games.glob("*.zx")):
|
||||
entry = tarfile.TarInfo(path.name)
|
||||
entry.size = path.stat().st_size
|
||||
entry.mode = 0o644
|
||||
with path.open("rb") as data:
|
||||
output.addfile(entry, data)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--ziran", default=str(ROOT / "scripts/ziran.sh"))
|
||||
@@ -160,15 +250,30 @@ def main():
|
||||
sha256=digest(ROOT / f"build/{name}.zx"), apps_sha256=args.apps_sha256,
|
||||
children=children, source_mode="project")
|
||||
(ROOT / f"build/{name}.json").write_text(json.dumps(metadata, indent=2) + "\n")
|
||||
# Arcade exposes every declared leaf directly; there is no nested chooser.
|
||||
bundle("collection.zi", "collection:Main", output / "assets", ROOT / "build/arcade.zx")
|
||||
# Arcade carries only its catalog. Standalone players keep their offline
|
||||
# games; Arcade downloads the library art once and exactly the game the
|
||||
# person selects.
|
||||
node_apps = ROOT / "build/node-apps"
|
||||
catalog_assets = node_apps / "arcade-catalog"
|
||||
game_downloads = node_apps / "arcade.games"
|
||||
art_assets = node_apps / "arcade-art"
|
||||
stage_downloads(catalog, output, catalog_assets, game_downloads, art_assets)
|
||||
bundle("art.zi", "art:Main", art_assets / "assets", node_apps / "arcade-art.zx")
|
||||
art = add_art(catalog_assets, game_downloads, node_apps / "arcade-art.zx")
|
||||
archive_downloads(game_downloads, node_apps / "arcade.games.tar")
|
||||
bundle("collection.zi", "collection:Main", catalog_assets / "assets", node_apps / "arcade.zx")
|
||||
shutil.copyfile(node_apps / "arcade.zx", ROOT / "build/arcade.zx")
|
||||
# The desktop host supplies its controller from beside the collection.
|
||||
shutil.copyfile(args.apps_bundle, ROOT / "build/apps.zx")
|
||||
receipt = dict(id=catalog["id"], version=(ROOT / "VERSION").read_text().strip(),
|
||||
sha256=digest(ROOT / "build/arcade.zx"),
|
||||
apps_sha256=args.apps_sha256, children=catalog["children"],
|
||||
apps_sha256=args.apps_sha256, children=catalog["children"], art=art,
|
||||
source_mode="project")
|
||||
(output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")
|
||||
(ROOT / "build/arcade.json").write_text(json.dumps(receipt, indent=2) + "\n")
|
||||
print("Arcade collection built with unchanged game bundles and verified Apps controller")
|
||||
node_receipt = receipt | {"sha256": digest(node_apps / "arcade.zx")}
|
||||
(node_apps / "arcade.json").write_text(json.dumps(node_receipt, indent=2) + "\n")
|
||||
print("Arcade catalog built with separate unchanged game downloads; standalone players keep their games")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -11,16 +11,29 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
ZIRAN = str(ROOT / 'scripts/ziran.sh')
|
||||
|
||||
|
||||
def stage_startup_art(source, output):
|
||||
"""Draw small full-colour images before the collection's originals load."""
|
||||
from PIL import Image
|
||||
startup = output / 'startup/shovey'
|
||||
startup.mkdir(parents=True, exist_ok=True)
|
||||
for name, edge in [('title-portrait.png', 640), ('title-landscape.png', 640), ('logo.png', 512)]:
|
||||
with Image.open(source / 'assets/shovey' / name) as original:
|
||||
image = original.convert('RGBA' if 'A' in original.getbands() else 'RGB')
|
||||
image.thumbnail((edge, edge), Image.Resampling.LANCZOS)
|
||||
image.save(startup / name, optimize=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output', type=Path, default=ROOT / 'build/arcade')
|
||||
parser.add_argument('--output', type=Path)
|
||||
parser.add_argument('--standalone-shovey', action='store_true')
|
||||
parser.add_argument('--generated', type=Path, help='Private generated-source output for an isolated build')
|
||||
args = parser.parse_args()
|
||||
output = args.output.resolve()
|
||||
output = (args.output or ROOT / 'build' / ('shovey' if args.standalone_shovey else 'arcade')).resolve()
|
||||
lock = [] if (ROOT / 'ziran.local.toml').exists() else ['--locked']
|
||||
toolchain = Path(subprocess.check_output([ZIRAN, 'pkg', 'path', 'ziran', *lock],
|
||||
cwd=ROOT, text=True).strip())
|
||||
generated = ROOT / ('build/shovey-native' if args.standalone_shovey else 'build/arcade-native') / 'c'
|
||||
generated = args.generated.resolve() if args.generated else ROOT / ('build/shovey-native' if args.standalone_shovey else 'build/arcade-native') / 'c'
|
||||
# Only this build purpose owns generated C. Never replace an installed
|
||||
# binary in place: link separately, then atomically replace the path.
|
||||
if generated.exists():
|
||||
@@ -53,15 +66,12 @@ def main():
|
||||
'-I' + str(package('monocypher') / 'src'), str(package('monocypher') / 'src/monocypher.c'),
|
||||
# Entity's device keys sign with Monocypher's standard Ed25519.
|
||||
str(package('monocypher') / 'src/optional/monocypher-ed25519.c'), str(oqs / 'lib/liboqs.a'),
|
||||
'-Wl,--gc-sections', *libraries, '-lX11', '-l:libcurl.so.4', '-lm', '-lpthread', '-o', str(temporary)], check=True)
|
||||
'-Wl,--gc-sections', *libraries, '-lX11', '-l:libcurl.so.4', '-lz', '-lm', '-lpthread', '-o', str(temporary)], check=True)
|
||||
temporary.replace(output)
|
||||
if args.standalone_shovey:
|
||||
from PIL import Image
|
||||
source = Path(subprocess.check_output([ZIRAN, 'pkg', 'path', 'shovey', *lock], cwd=ROOT, text=True).strip())
|
||||
startup = output.parent / 'startup/shovey'
|
||||
startup.mkdir(parents=True, exist_ok=True)
|
||||
for name in ('title-portrait.png', 'title-landscape.png', 'logo.png'):
|
||||
shutil.copyfile(source / 'assets/shovey' / name, startup / name)
|
||||
stage_startup_art(source, output.parent)
|
||||
Image.open(source / 'assets/branding/shovey-icon.png').resize((256, 256), Image.Resampling.LANCZOS).save(output.parent / 'shovey-icon.png')
|
||||
print(('Shovey' if args.standalone_shovey else 'Arcade') + ' native build passed')
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the apps Arcade and its game packages declare, without copying source."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from game_packages import declared_apps
|
||||
from game_resources import dependency_order, share_resources
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -35,10 +37,21 @@ def build(ziran, lock_flags):
|
||||
[ziran, "pkg", "path", name, *lock_flags], cwd=ROOT, text=True).strip())
|
||||
|
||||
kryon = package("kryon")
|
||||
game2d = package("game2d")
|
||||
toolchain = package("ziran")
|
||||
entity = package("entity")
|
||||
compiler = toolchain / "build/bin/ziran"
|
||||
if not compiler.is_file():
|
||||
compiler = ROOT / "build/toolchain/bin/ziran"
|
||||
def dependency(name, project):
|
||||
return Path(subprocess.check_output(
|
||||
[str(compiler), "pkg", "path", name, *lock_flags], cwd=project, text=True).strip())
|
||||
daochi_client = dependency("daochi_client", entity)
|
||||
crypto = dependency("crypto", daochi_client)
|
||||
entries = []
|
||||
for app in declared_apps(ROOT, ziran, lock_flags):
|
||||
apps = dependency_order(declared_apps(ROOT, ziran, lock_flags))
|
||||
by_id = {app['descriptor']['id']: app for app in apps}
|
||||
for app in apps:
|
||||
source, manifest, descriptor = app["source"], app["manifest"], app["descriptor"]
|
||||
if descriptor["kind"] != "game" or "arcade" not in descriptor["harnesses"]:
|
||||
raise ValueError("Only games registered for Arcade belong in its catalog")
|
||||
@@ -62,7 +75,7 @@ def build(ziran, lock_flags):
|
||||
# Build flags are source metadata, not part of the signed node/2
|
||||
# descriptor schema accepted by existing hosts.
|
||||
(resources / 'catalog.json').write_text(json.dumps(
|
||||
{key: value for key, value in descriptor.items() if key != 'build_defines'}, indent=2) + '\n')
|
||||
{key: value for key, value in descriptor.items() if key not in ('build_defines', 'prepare_assets')}, indent=2) + '\n')
|
||||
defines = descriptor.get('build_defines', [])
|
||||
if 'SHOVEY_RELEASE' in defines:
|
||||
subprocess.run(["python3", str(source / 'scripts/release_assets.py'), str(resources)], check=True)
|
||||
@@ -85,6 +98,31 @@ def build(ziran, lock_flags):
|
||||
# their own locale file and cannot provide newly added game strings.
|
||||
generated = ROOT / 'build/game-generated' / name
|
||||
generated.mkdir(parents=True, exist_ok=True)
|
||||
if descriptor.get('prepare_assets'):
|
||||
prepare = Path(descriptor['prepare_assets'])
|
||||
if prepare.is_absolute() or '..' in prepare.parts or prepare.suffix not in ('.py', '.zi'):
|
||||
raise ValueError('Invalid game asset preparation script')
|
||||
if prepare.suffix == '.zi':
|
||||
# A Ziran preparation program builds with Arcade's compiler and
|
||||
# runs from the game's checkout, where its own files are.
|
||||
tool = ROOT / 'build/game-tools' / name
|
||||
subprocess.run([str(compiler), 'build', '--target=c', '--exe', '--root', str((source / prepare).parent),
|
||||
'--module-path', 'std=' + str(toolchain / 'std'), '--entry', prepare.stem + ':main',
|
||||
'-o', str(tool), str(source / prepare)], cwd=ROOT, check=True)
|
||||
subprocess.run([str(tool / prepare.stem), str(resources), str(generated)], cwd=source, check=True)
|
||||
else:
|
||||
subprocess.run(['python3', str(source / prepare), str(resources), str(generated)], check=True)
|
||||
shared = share_resources(app, apps, resources, ROOT / 'build/game-assets')
|
||||
metadata = ROOT / 'build/games' / (name + '-resources.json')
|
||||
metadata.parent.mkdir(parents=True, exist_ok=True)
|
||||
metadata.write_text(json.dumps(shared, indent=2) + '\n')
|
||||
if shared['dependencies']:
|
||||
# A base-art update must also invalidate cached editor images.
|
||||
originals = {item['descriptor']['id']: item['descriptor']['name'] for item in apps}
|
||||
required = shared | {'sha256': {identifier: hashlib.sha256(
|
||||
(ROOT / 'build/games' / (originals[identifier] + '.zx')).read_bytes()).hexdigest()
|
||||
for identifier in shared['dependencies']}}
|
||||
(resources / 'requirements.json').write_text(json.dumps(required, sort_keys=True) + '\n')
|
||||
code = 'GameLocaleText :: (language: string, key: string) -> string {\n'
|
||||
for language, values in sorted(translations.items(), key=lambda item: item[0] == 'en'):
|
||||
if language != 'en':
|
||||
@@ -98,19 +136,26 @@ def build(ziran, lock_flags):
|
||||
bundle = ROOT / "build/games" / (name + ".zx")
|
||||
bundle.parent.mkdir(parents=True, exist_ok=True)
|
||||
subprocess.run([
|
||||
ziran, "bundle", "--root", str(source),
|
||||
ziran, "bundle", "--root", str((source / descriptor["source"]).parent),
|
||||
# Game packages without a src folder (Shovey) keep sources beside their catalogs.
|
||||
*(["--module-path", str(source / "src")] if (source / "src").is_dir() else []),
|
||||
"--module-path", str(generated),
|
||||
"--module-path", str(kryon / "src/ui"),
|
||||
"--module-path", "kryon=" + str(kryon / "src/ui"),
|
||||
"--module-path", "kryon=" + str(kryon / "src/backend"),
|
||||
"--module-path", "game2d=" + str(game2d / "src"),
|
||||
"--module-path", "std=" + str(toolchain / "std"),
|
||||
"--module-path", str(toolchain / "std"),
|
||||
"--module-path", "apps=" + str(package("apps") / "src"),
|
||||
"--module-path", "mingcute=" + str(package("mingcute") / "src"),
|
||||
"--module-path", "entity=" + str(entity / "src"),
|
||||
"--module-path", "daochi_client=" + str(daochi_client),
|
||||
"--module-path", "crypto=" + str(crypto / "src"),
|
||||
*[flag for name in defines for flag in ('--define', name)],
|
||||
*[flag for entry in app['library_entries'] for flag in ('--retain', entry)],
|
||||
*[flag for dependency_id in app['requires'] if app['shared_code']
|
||||
for flag in ('--library', str(ROOT / 'build/games' /
|
||||
(by_id[dependency_id]['descriptor']['name'] + '.zx')))],
|
||||
"--define", "KRYON_HOSTED_UI", "--asset-dir", "assets=" + str(staged / "assets"),
|
||||
"--entry", descriptor["entry"], "-o", str(bundle),
|
||||
str(source / descriptor["source"])], cwd=ROOT, check=True)
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build Arcade's browser edition into build/web-site.
|
||||
|
||||
The page runs a collection, by default this checkout's build/node-apps/arcade.zx;
|
||||
the website passes the published one Inner Breeze downloads. Arcade's own host
|
||||
is compiled to WebAssembly with the account Profile. The receipt names the
|
||||
collection's digest and the Apps library it trusts. Arcade's own copy of that
|
||||
library goes beside it for collections that do not pack one.
|
||||
|
||||
With --shovey the page is shovey.waozi.xyz: the same host runs a released
|
||||
Shovey download's own shovey.zx, shovey.json and entity.zx, unchanged, on the
|
||||
page files --site names. Their programs, and the game and Apps controller
|
||||
packed in shovey.zx, are compiled into the page, so they run as fast as a
|
||||
native build of them; the page still opens those exact bytes.
|
||||
|
||||
The library's pictures come from the site too (stage_web_library_art), so
|
||||
the covers never wait for the art bundle from api.waozi.xyz.
|
||||
"""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ZIRAN = str(ROOT / 'scripts/ziran.sh')
|
||||
ART_LIMIT = 64 * 1024 * 1024
|
||||
# The committed library copies are at most this large (scripts/library-art.py).
|
||||
PICTURE_LONGEST = 640
|
||||
COVER_QUALITY = 80
|
||||
|
||||
|
||||
def bundle_assets(data):
|
||||
"""The files embedded in a ZX v26 bundle by path; never runs it."""
|
||||
if data[:8] != b'ZX\0\0\x1a\0\0\0' or len(data) > ART_LIMIT:
|
||||
raise ValueError('unsupported bundle')
|
||||
at = 8
|
||||
|
||||
def take(size):
|
||||
nonlocal at
|
||||
if at + size > len(data):
|
||||
raise ValueError('truncated bundle')
|
||||
value = data[at:at + size]
|
||||
at += size
|
||||
return value
|
||||
|
||||
def number():
|
||||
return struct.unpack('<I', take(4))[0]
|
||||
|
||||
def text():
|
||||
return take(number())
|
||||
|
||||
text(); text()
|
||||
for _ in range(number()):
|
||||
text(); text()
|
||||
for _ in range(number()):
|
||||
for _ in range(7):
|
||||
text()
|
||||
take(8); text(); take(4)
|
||||
for _ in range(number()):
|
||||
for _ in range(3):
|
||||
text()
|
||||
take(number())
|
||||
assets = {}
|
||||
for _ in range(number()):
|
||||
path = text().decode()
|
||||
if path in assets:
|
||||
raise ValueError('duplicate bundle file')
|
||||
assets[path] = take(number())
|
||||
if at != len(data):
|
||||
raise ValueError('trailing bundle bytes')
|
||||
return assets
|
||||
|
||||
|
||||
def published_art(folder, digest):
|
||||
"""The art bundle a collection names, from the release's game archive
|
||||
beside it or a local build's arcade.games folder."""
|
||||
built = folder / 'arcade.games' / f'{digest}.zx'
|
||||
if built.is_file():
|
||||
return built.read_bytes()
|
||||
archive = folder / 'arcade.games.tar'
|
||||
if archive.is_file():
|
||||
with tarfile.open(archive) as games:
|
||||
member = next((entry for entry in games if entry.name == f'{digest}.zx'), None)
|
||||
if member is not None and member.isfile() and member.size <= ART_LIMIT:
|
||||
return games.extractfile(member).read()
|
||||
raise ValueError('The collection\'s art bundle is not beside it')
|
||||
|
||||
|
||||
def web_picture(data, exact):
|
||||
"""(bytes, suffix) of the page's copy of one verified library picture: a
|
||||
WebP, lossless when exact (pixel-art previews), unless the original is
|
||||
smaller. Transparency is kept; nothing is larger than PICTURE_LONGEST."""
|
||||
from PIL import Image
|
||||
image = Image.open(io.BytesIO(data))
|
||||
image.load()
|
||||
original = '.' + image.format.lower().replace('jpeg', 'jpg')
|
||||
alpha = 'A' in image.getbands() or 'transparency' in image.info
|
||||
image = image.convert('RGBA' if alpha else 'RGB')
|
||||
scale = min(1.0, PICTURE_LONGEST / max(image.size))
|
||||
if scale < 1.0:
|
||||
size = (max(1, round(image.width * scale)), max(1, round(image.height * scale)))
|
||||
image = image.resize(size, Image.Resampling.LANCZOS)
|
||||
output = io.BytesIO()
|
||||
if exact:
|
||||
image.save(output, 'WEBP', lossless=True, method=6)
|
||||
else:
|
||||
image.save(output, 'WEBP', quality=COVER_QUALITY, method=6)
|
||||
if scale == 1.0 and len(data) <= output.tell():
|
||||
return data, original
|
||||
return output.getvalue(), '.webp'
|
||||
|
||||
|
||||
def stage_web_library_art(bundle, output):
|
||||
"""Serve the collection's separate library art from the site.
|
||||
|
||||
The art bundle must have the exact digest and size the collection's
|
||||
signed catalog names. Its pictures go to output/library as small WebP
|
||||
copies, named by content and listed in library.json under that digest;
|
||||
the exact bundle goes beside them for browsers that cannot draw WebP.
|
||||
Returns the listing, or None when the collection packs its own art.
|
||||
"""
|
||||
assets = bundle_assets(bundle.read_bytes())
|
||||
catalog = json.loads(assets['assets/apps/catalog.json'])
|
||||
art = catalog.get('art')
|
||||
if art is None:
|
||||
return None
|
||||
digest, size = art.get('sha256', ''), art.get('bytes')
|
||||
if not re.fullmatch(r'[0-9a-f]{64}', digest) or not isinstance(size, int):
|
||||
raise ValueError('Invalid art in the collection catalog')
|
||||
data = published_art(bundle.parent, digest)
|
||||
if len(data) != size or hashlib.sha256(data).hexdigest() != digest:
|
||||
raise ValueError('The art bundle differs from the collection catalog')
|
||||
pictures = bundle_assets(data)
|
||||
previews = {child[key] for child in catalog['children'] for key in ('preview', 'icon') if child.get(key)}
|
||||
covers = {path for child in catalog['children'] for key, path in child.get('cover', {}).items()
|
||||
if key in ('portrait', 'landscape', 'logo')}
|
||||
copies = {}
|
||||
for path in sorted(previews | covers):
|
||||
if path not in pictures:
|
||||
raise ValueError(f'The art bundle lacks {path}')
|
||||
copies[path] = web_picture(pictures[path], path in previews)
|
||||
library = output / 'library'
|
||||
if library.exists():
|
||||
shutil.rmtree(library)
|
||||
library.mkdir(parents=True)
|
||||
(library / f'{digest}.zx').write_bytes(data)
|
||||
listed = {}
|
||||
for path, (contents, suffix) in copies.items():
|
||||
name = hashlib.sha256(contents).hexdigest()
|
||||
(library / (name + suffix)).write_bytes(contents)
|
||||
listed[path] = dict(file=f'library/{name}{suffix}', sha256=name, bytes=len(contents))
|
||||
manifest = dict(art=digest, bytes=size, pictures=listed)
|
||||
(output / 'library.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
return manifest
|
||||
|
||||
|
||||
def package(name):
|
||||
flags = [] if (ROOT / 'ziran.local.toml').exists() else ['--locked']
|
||||
return Path(subprocess.check_output([ZIRAN, 'pkg', 'path', name, *flags], cwd=ROOT, text=True).strip())
|
||||
|
||||
|
||||
def compress(path):
|
||||
"""A gzip copy beside path, which the page fetches first: Cloudflare
|
||||
Pages does not compress binary files (apps.zx 1.9 MB -> 0.24 MB)."""
|
||||
with open(path.with_name(path.name + '.gz'), 'wb') as raw:
|
||||
with gzip.GzipFile(filename='', mode='wb', compresslevel=9, fileobj=raw, mtime=0) as packed:
|
||||
packed.write(path.read_bytes())
|
||||
|
||||
|
||||
def version_assets(output, receipt):
|
||||
"""Keep the runtime, its data and the verified collection on one cache key."""
|
||||
page = output / 'index.html'
|
||||
html = page.read_text()
|
||||
if '__ARCADE_ASSET_REVISION__' not in html:
|
||||
return
|
||||
digest = hashlib.sha256()
|
||||
for name in ('runtime.js', 'runtime.wasm', 'runtime.data', 'arcade.json', 'apps.zx', 'library.json'):
|
||||
path = output / name
|
||||
if path.is_file():
|
||||
digest.update(name.encode() + b'\0')
|
||||
digest.update(path.read_bytes())
|
||||
revision = digest.hexdigest()
|
||||
page.write_text(html.replace('__ARCADE_ASSET_REVISION__', revision))
|
||||
source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
(output / 'build.json').write_text(json.dumps({
|
||||
'source_revision': source, 'version': receipt['version'],
|
||||
'assets_sha256': revision,
|
||||
}, indent=2) + '\n')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--bundle', type=Path, default=ROOT / 'build/node-apps/arcade.zx')
|
||||
parser.add_argument('--controller-sha256', default=(ROOT / 'apps-controller.sha256').read_text().strip())
|
||||
parser.add_argument('--version', default=(ROOT / 'VERSION').read_text().strip())
|
||||
parser.add_argument('--profile', type=Path, default=ROOT / 'build/entity.zx')
|
||||
parser.add_argument('--controller', type=Path, default=ROOT / 'build/apps-ui/apps.zx')
|
||||
parser.add_argument('--output', type=Path, default=ROOT / 'build/web-site')
|
||||
parser.add_argument('--shovey', type=Path, help='a released Shovey download folder')
|
||||
parser.add_argument('--site', type=Path, default=ROOT / 'site')
|
||||
args = parser.parse_args()
|
||||
if args.shovey:
|
||||
bundle = (args.shovey / 'shovey.zx').resolve()
|
||||
receipt = json.loads((args.shovey / 'shovey.json').read_text())
|
||||
if receipt.get('id') != 'arcade.shovey-player' or \
|
||||
hashlib.sha256(bundle.read_bytes()).hexdigest() != receipt.get('sha256'):
|
||||
raise SystemExit('The Shovey download does not match its shovey.json')
|
||||
args.profile = args.shovey / 'entity.zx'
|
||||
args.controller_sha256 = receipt['apps_sha256']
|
||||
args.version = receipt['version']
|
||||
else:
|
||||
bundle = args.bundle.resolve()
|
||||
receipt = dict(id='inbe.arcade', version=args.version,
|
||||
sha256=hashlib.sha256(bundle.read_bytes()).hexdigest(),
|
||||
apps_sha256=args.controller_sha256)
|
||||
# The host reads the receipt into a 4 KiB buffer.
|
||||
text = json.dumps(receipt, separators=(',', ':')) if args.shovey else json.dumps(receipt, indent=2) + '\n'
|
||||
if len(text.encode()) >= 4096:
|
||||
raise SystemExit('The receipt exceeds the host buffer')
|
||||
work = ROOT / 'build/web'
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
env = {**os.environ, 'ZIRAN': str(package('ziran') / 'build/bin/ziran')}
|
||||
linked = [item for path in (bundle, args.profile.resolve()) for item in ('--linked', str(path))] \
|
||||
if args.shovey else []
|
||||
subprocess.run([sys.executable, str(package('entity') / 'scripts/build-web.py'),
|
||||
'--bundle', str(bundle), '--profile', str(args.profile.resolve()),
|
||||
'--output', str(work / 'runtime.html'), *linked,
|
||||
'--entry', 'runtime:main', '--source', 'src/web/runtime.zi'], cwd=ROOT, env=env, check=True)
|
||||
output = args.output.resolve()
|
||||
if output.exists():
|
||||
shutil.rmtree(output)
|
||||
shutil.copytree(args.site, output)
|
||||
for name in ('runtime.js', 'runtime.wasm', 'runtime.data'):
|
||||
shutil.copyfile(work / name, output / name)
|
||||
compress(output / 'runtime.data')
|
||||
(output / 'arcade.json').write_text(text)
|
||||
# Only the library the receipt trusts; the host refuses any other.
|
||||
controller = args.controller.read_bytes() if args.controller.is_file() else b''
|
||||
if hashlib.sha256(controller).hexdigest() == args.controller_sha256:
|
||||
(output / 'apps.zx').write_bytes(controller)
|
||||
compress(output / 'apps.zx')
|
||||
else:
|
||||
print('No matching Apps controller beside the collection; it must pack its own')
|
||||
if not args.shovey and stage_web_library_art(bundle, output) is None:
|
||||
print('The collection packs its own library art')
|
||||
version_assets(output, receipt)
|
||||
print(f'{"Shovey" if args.shovey else "Arcade"} {args.version} for the browser in {output}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check game ownership, shared interface versions, translations and update metadata."""
|
||||
import json
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import re
|
||||
from game_packages import declared_apps
|
||||
@@ -8,10 +9,15 @@ from game_packages import declared_apps
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def check():
|
||||
def check(ziran, lock_flags):
|
||||
standard = json.loads((ROOT / 'standards/game-v1.json').read_text())
|
||||
ledger = json.loads((ROOT / 'apps/versions.json').read_text())
|
||||
for app in declared_apps(ROOT):
|
||||
# Arcade's own players refuse games newer than GAME_HOST_API, so it moves
|
||||
# with the standard and the ledger whenever the host interface does.
|
||||
player = re.search(r'^GAME_HOST_API :: (\d+)$', (ROOT / 'src/game_contract.zi').read_text(), re.M)
|
||||
assert player and int(player[1]) == standard['host_api'] == ledger['host_api'], \
|
||||
'src/game_contract.zi GAME_HOST_API, standards/game-v1.json and apps/versions.json must name the same host interface'
|
||||
for app in declared_apps(ROOT, ziran, lock_flags):
|
||||
source, manifest, game = app['source'], app['manifest'], app['descriptor']
|
||||
for field in ['contract_version', 'module_api', 'host_api']:
|
||||
assert game[field] == standard[field], f'{game["name"]}: incompatible {field}'
|
||||
@@ -27,7 +33,9 @@ def check():
|
||||
assert component['sequence'] > 0
|
||||
required = set()
|
||||
for file in manifest.parent.glob('*.zi'):
|
||||
required.update(re.findall(r'"(' + re.escape(game['locale_prefix']) + r'[a-z0-9_]+)"', file.read_text()))
|
||||
# Module names in #import lines share the prefix but are not text keys.
|
||||
code = re.sub(r'^\s*#import\s+"[^"\n]*"', '', file.read_text(), flags=re.M)
|
||||
required.update(re.findall(r'"(' + re.escape(game['locale_prefix']) + r'[a-z0-9_]+)"', code))
|
||||
locales = {}
|
||||
for file in (source / game['locales']).glob('*.txt'):
|
||||
text = file.read_text()
|
||||
@@ -54,5 +62,9 @@ def check():
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
check()
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--ziran', default=str(ROOT / 'scripts/ziran.sh'))
|
||||
parser.add_argument('--locked', action='store_true')
|
||||
arguments = parser.parse_args()
|
||||
check(arguments.ziran, ['--locked'] if arguments.locked else [])
|
||||
print('Game contract, package sources, translated text and independent version ledger passed')
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Keep Arcade's Cloudflare Pages project and arcade.waozi.xyz in place.
|
||||
|
||||
`prepare` creates the `arcade` Pages project when it is missing, before the
|
||||
first deployment. `connect` adds arcade.waozi.xyz to the project and points
|
||||
its DNS at the project. Both are safe to repeat on every deployment. They read
|
||||
CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID and never print the token.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
PROJECT = 'arcade'
|
||||
DOMAIN = 'arcade.waozi.xyz'
|
||||
ZONE = 'waozi.xyz'
|
||||
|
||||
|
||||
def api(method, path, body=None):
|
||||
request = urllib.request.Request('https://api.cloudflare.com/client/v4' + path, method=method,
|
||||
data=None if body is None else json.dumps(body).encode(),
|
||||
headers={'Authorization': 'Bearer ' + os.environ['CLOUDFLARE_API_TOKEN'], 'Content-Type': 'application/json'})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=40) as response:
|
||||
return response.status, json.load(response)
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, json.loads(error.read() or b'{}')
|
||||
|
||||
|
||||
def result(method, path, body=None):
|
||||
status, data = api(method, path, body)
|
||||
if not data.get('success'):
|
||||
raise SystemExit(f'Cloudflare {method} {path} failed ({status}): {data.get("errors")}')
|
||||
return data['result']
|
||||
|
||||
|
||||
def prepare(account):
|
||||
status, data = api('GET', f'/accounts/{account}/pages/projects/{PROJECT}')
|
||||
if data.get('success'):
|
||||
print(f'Pages project {PROJECT} exists.')
|
||||
return
|
||||
if status != 404:
|
||||
raise SystemExit(f'Could not read Pages project {PROJECT} ({status}): {data.get("errors")}')
|
||||
result('POST', f'/accounts/{account}/pages/projects', {'name': PROJECT, 'production_branch': 'master'})
|
||||
print(f'Created Pages project {PROJECT}.')
|
||||
|
||||
|
||||
def connect(account):
|
||||
project = result('GET', f'/accounts/{account}/pages/projects/{PROJECT}')
|
||||
domains = result('GET', f'/accounts/{account}/pages/projects/{PROJECT}/domains')
|
||||
if not any(domain['name'] == DOMAIN for domain in domains):
|
||||
result('POST', f'/accounts/{account}/pages/projects/{PROJECT}/domains', {'name': DOMAIN})
|
||||
print(f'Added {DOMAIN} to Pages project {PROJECT}.')
|
||||
zones = result('GET', f'/zones?name={ZONE}')
|
||||
if len(zones) != 1:
|
||||
raise SystemExit(f'Expected one {ZONE} zone, found {len(zones)}')
|
||||
zone = zones[0]['id']
|
||||
records = result('GET', f'/zones/{zone}/dns_records?name={DOMAIN}')
|
||||
if not records:
|
||||
result('POST', f'/zones/{zone}/dns_records',
|
||||
{'type': 'CNAME', 'name': DOMAIN, 'content': project['subdomain'], 'proxied': True, 'ttl': 1})
|
||||
print(f'Pointed {DOMAIN} at {project["subdomain"]}.')
|
||||
elif not (len(records) == 1 and records[0]['type'] == 'CNAME' and records[0]['content'] == project['subdomain']):
|
||||
# Never overwrite a record someone else made.
|
||||
raise SystemExit(f'{DOMAIN} already has DNS records that do not point at {project["subdomain"]}')
|
||||
print(f'{DOMAIN} serves Pages project {PROJECT}.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) != 2 or sys.argv[1] not in {'prepare', 'connect'}:
|
||||
raise SystemExit('Usage: cloudflare-site.py prepare|connect')
|
||||
account = os.environ['CLOUDFLARE_ACCOUNT_ID']
|
||||
{'prepare': prepare, 'connect': connect}[sys.argv[1]](account)
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Follow the published releases of Arcade's game packages.
|
||||
|
||||
`check` records newer published game releases without changing dependencies.
|
||||
`pin` selects their exact commits in ziran.toml and asks Ziran to update each
|
||||
game and its transitive dependencies. New game imports must reach the lock;
|
||||
unrelated packages and the compiler stay pinned. The updates are recorded in
|
||||
build/game-updates.json.
|
||||
|
||||
`changelog` adds an Arcade release entry naming each updated game with the
|
||||
notes of its newest release, for update_version.sh to synchronize.
|
||||
|
||||
`art` remakes the library's small copies of game art (scripts/library-art.py)
|
||||
only when a game's art changed, so unchanged copies keep their bytes.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
UPDATES = ROOT / 'build/game-updates.json'
|
||||
|
||||
|
||||
def gh(*args):
|
||||
return subprocess.check_output(['gh', *args], text=True).strip()
|
||||
|
||||
|
||||
def repository(url):
|
||||
match = re.fullmatch(r'https://github\.com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+?)(\.git)?', url)
|
||||
if not match:
|
||||
raise SystemExit(f'Not a GitHub package: {url}')
|
||||
return match[1]
|
||||
|
||||
|
||||
def released_updates():
|
||||
lock = json.loads((ROOT / 'ziran.lock').read_text())
|
||||
names = json.loads((ROOT / 'games.json').read_text())['packages']
|
||||
updates = []
|
||||
for name in names:
|
||||
old_id = lock['root']['dependencies'][name]
|
||||
entry = next(item for item in lock['packages'] if item['id'] == old_id)
|
||||
repo = repository(entry['url'])
|
||||
tag = gh('release', 'view', '--repo', repo, '--json', 'tagName', '--jq', '.tagName')
|
||||
commit = gh('api', f'repos/{repo}/commits/{tag}', '--jq', '.sha')
|
||||
if not re.fullmatch(r'[0-9a-f]{40}', commit):
|
||||
raise SystemExit(f'{name}: invalid release commit')
|
||||
if commit == entry['commit']:
|
||||
continue
|
||||
# Release metadata can be recorded before the game is published.
|
||||
# The pinned source must still advance to that release's commit.
|
||||
# Never move back: the release must contain the pinned commit.
|
||||
status = gh('api', f'repos/{repo}/compare/{entry["commit"]}...{commit}', '--jq', '.status')
|
||||
if status != 'ahead':
|
||||
print(f'{name}: release {tag} is {status} of the pinned {entry["commit"][:12]}; kept')
|
||||
continue
|
||||
updates.append({'name': name, 'repository': repo, 'tag': tag, 'commit': commit})
|
||||
print(f'{name}: {repo} {tag} ({commit[:12]})')
|
||||
return updates
|
||||
|
||||
|
||||
def record_updates(updates):
|
||||
UPDATES.parent.mkdir(parents=True, exist_ok=True)
|
||||
UPDATES.write_text(json.dumps(updates, indent=2) + '\n')
|
||||
|
||||
|
||||
def pin(ziran):
|
||||
updates = released_updates()
|
||||
manifest = ROOT / 'ziran.toml'
|
||||
lock_path = ROOT / 'ziran.lock'
|
||||
original_manifest = manifest.read_bytes()
|
||||
original_lock = lock_path.read_bytes()
|
||||
try:
|
||||
for update in updates:
|
||||
name, commit = update['name'], update['commit']
|
||||
# Edit the declaration; only the package manager writes the graph.
|
||||
section = re.compile(r'(^\[dependencies\.' + re.escape(name) +
|
||||
r'\]\s*\n)([^\[]*)', re.M)
|
||||
text = manifest.read_text()
|
||||
match = section.search(text)
|
||||
if match is None:
|
||||
raise ValueError(f'{name}: missing dependency declaration')
|
||||
body, count = re.subn(r'^ref[ \t]*=[ \t]*"[^"\n]*"[ \t]*$',
|
||||
f'ref = "{commit}"', match[2], flags=re.M)
|
||||
if count != 1:
|
||||
raise ValueError(f'{name}: expected one dependency ref')
|
||||
manifest.write_text(text[:match.start(2)] + body + text[match.end(2):])
|
||||
subprocess.run([str(ziran), 'update', name], cwd=ROOT, check=True)
|
||||
lock = json.loads(lock_path.read_text())
|
||||
target = lock['root']['dependencies'][name]
|
||||
entry = next(p for p in lock['packages'] if p['id'] == target)
|
||||
if entry['commit'] != commit:
|
||||
raise ValueError(f'{name}: Ziran did not select the released commit; remove its local override')
|
||||
except BaseException:
|
||||
manifest.write_bytes(original_manifest)
|
||||
lock_path.write_bytes(original_lock)
|
||||
raise
|
||||
record_updates(updates)
|
||||
|
||||
|
||||
def newest_notes(changelog):
|
||||
"""The bullets of a changelog's newest numeric release."""
|
||||
text = changelog.read_text()
|
||||
heading = re.search(r'^## \[?(\d+\.\d+\.\d+)\]?.*$', text, re.M)
|
||||
if heading is None:
|
||||
raise SystemExit(f'{changelog} needs a numeric release entry')
|
||||
following = re.search(r'^## ', text[heading.end():], re.M)
|
||||
section = text[heading.end():heading.end() + following.start()] if following else text[heading.end():]
|
||||
notes = [line[2:].strip() for line in section.splitlines() if line.startswith('- ')]
|
||||
return heading[1], notes
|
||||
|
||||
|
||||
def changelog(ziran):
|
||||
updates = json.loads(UPDATES.read_text())
|
||||
if not updates:
|
||||
return
|
||||
lines = []
|
||||
for update in updates:
|
||||
source = Path(subprocess.check_output([ziran, 'pkg', 'path', update['name']], cwd=ROOT, text=True).strip())
|
||||
declaration = json.loads((source / 'apps.json').read_text())
|
||||
# The package's first app is the game itself; its changelog sits beside its catalog.
|
||||
manifest = source / declaration['apps'][0]['manifest']
|
||||
version, notes = newest_notes(manifest.with_name('CHANGELOG.md'))
|
||||
title = declaration['title']
|
||||
lines += [f'- {title} {version}: {note}' for note in notes] or [f'- {title} {version}.']
|
||||
path = ROOT / 'CHANGELOG.md'
|
||||
text = path.read_text()
|
||||
current = re.search(r'^## (\d+)\.(\d+)\.(\d+)\s*$', text, re.M)
|
||||
if current is None:
|
||||
raise SystemExit('CHANGELOG.md needs a numeric release entry')
|
||||
# Arcade's own changes wait under Unreleased; this release ships them.
|
||||
pending = re.search(r'^## \[Unreleased\]\s*$', text[:current.start()], re.M)
|
||||
if pending is not None:
|
||||
lines = [line for line in text[pending.end():current.start()].splitlines() if line.startswith('- ')] + lines
|
||||
text = text[:pending.start()] + text[current.start():]
|
||||
current = re.search(r'^## (\d+)\.(\d+)\.(\d+)\s*$', text, re.M)
|
||||
version = f'{current[1]}.{current[2]}.{int(current[3]) + 1}'
|
||||
entry = f'## {version}\n\n' + '\n'.join(lines) + '\n\n'
|
||||
path.write_text(text[:current.start()] + entry + text[current.start():])
|
||||
print(f'Arcade {version}')
|
||||
|
||||
|
||||
def art():
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
spec = importlib.util.spec_from_file_location('library_art', ROOT / 'scripts/library-art.py')
|
||||
library = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(library)
|
||||
recorded = json.loads((library.LIBRARY / 'sources.json').read_text())
|
||||
current = {f'{name}-{key}': hashlib.sha256(data).hexdigest() for name, key, data in library.art()}
|
||||
if {copy: item['source_sha256'] for copy, item in recorded.items()} != current:
|
||||
library.main()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('command', choices=['check', 'pin', 'changelog', 'art'])
|
||||
parser.add_argument('--ziran', default=str(ROOT / 'scripts/ziran.sh'))
|
||||
args = parser.parse_args()
|
||||
if args.command == 'check':
|
||||
record_updates(released_updates())
|
||||
elif args.command == 'pin':
|
||||
pin(args.ziran)
|
||||
elif args.command == 'changelog':
|
||||
changelog(args.ziran)
|
||||
else:
|
||||
art()
|
||||
@@ -5,10 +5,11 @@ for an app the library opens from a full-screen cover, that cover's art,
|
||||
caption and action. games.json names the game packages Arcade includes.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
APP_KEYS = {'manifest', 'cover', 'enabled'}
|
||||
APP_KEYS = {'manifest', 'cover', 'enabled', 'requires', 'shared_code', 'library_entries', 'shared_records'}
|
||||
COVER_KEYS = {'portrait', 'landscape', 'logo', 'caption', 'action'}
|
||||
|
||||
|
||||
@@ -41,9 +42,30 @@ def declared_packages(root, ziran=None, lock_flags=()):
|
||||
if not set(app) <= APP_KEYS or not set(app.get('cover', {})) <= COVER_KEYS:
|
||||
raise ValueError(f'{name}: unknown apps.json field')
|
||||
manifest = source / relative_path(app['manifest'])
|
||||
requires = app.get('requires', [])
|
||||
if not isinstance(requires, list) or len(requires) > 8 or \
|
||||
any(not isinstance(item, str) or not item for item in requires) or \
|
||||
len(set(requires)) != len(requires):
|
||||
raise ValueError(f'{name}: invalid app dependencies')
|
||||
shared_code = app.get('shared_code', False)
|
||||
if type(shared_code) is not bool or (shared_code and not requires):
|
||||
raise ValueError(f'{name}: shared code needs declared dependencies')
|
||||
shared_records = app.get('shared_records', [])
|
||||
if not isinstance(shared_records, list) or len(shared_records) > 8 or any(
|
||||
not isinstance(item, str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,63}', item) or
|
||||
item in ('.', '..') for item in shared_records) or len(set(shared_records)) != len(shared_records):
|
||||
raise ValueError(f'{name}: invalid shared records')
|
||||
library_entries = app.get('library_entries', [])
|
||||
if not isinstance(library_entries, list) or len(library_entries) > 64 or \
|
||||
any(not isinstance(item, str) or len(item) > 253 or
|
||||
not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*:[A-Za-z_][A-Za-z0-9_]*', item)
|
||||
for item in library_entries) or len(set(library_entries)) != len(library_entries):
|
||||
raise ValueError(f'{name}: invalid portable library entries')
|
||||
apps.append(dict(package=name, source=source, manifest=manifest,
|
||||
descriptor=json.loads(manifest.read_text()),
|
||||
cover=app.get('cover'), enabled=app.get('enabled', True)))
|
||||
cover=app.get('cover'), requires=requires, shared_code=shared_code,
|
||||
shared_records=shared_records,
|
||||
library_entries=library_entries, enabled=app.get('enabled', True)))
|
||||
packages.append(dict(name=name, source=source, id=declaration['id'],
|
||||
title=declaration['title'], apps=apps))
|
||||
return packages
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Pack additions once; signed collection links bind shared game resources."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
|
||||
def dependency_order(apps):
|
||||
by_id = {app['descriptor']['id']: app for app in apps}
|
||||
visiting, ordered, complete = set(), [], set()
|
||||
|
||||
def visit(app):
|
||||
identifier = app['descriptor']['id']
|
||||
if identifier in visiting:
|
||||
raise ValueError('Cyclic game dependency')
|
||||
if identifier in complete:
|
||||
return
|
||||
visiting.add(identifier)
|
||||
for dependency in app.get('requires', []):
|
||||
if dependency not in by_id or (app['enabled'] and not by_id[dependency]['enabled']):
|
||||
raise ValueError(f'{identifier}: missing dependency {dependency}')
|
||||
visit(by_id[dependency])
|
||||
visiting.remove(identifier)
|
||||
complete.add(identifier)
|
||||
ordered.append(app)
|
||||
|
||||
for app in apps:
|
||||
visit(app)
|
||||
return ordered
|
||||
|
||||
|
||||
def shared_copies(app):
|
||||
path = app['manifest'].with_name('shared_assets.json')
|
||||
return json.loads(path.read_text())['copies'] if path.exists() else []
|
||||
|
||||
|
||||
def share_resources(app, apps, resources, staged):
|
||||
"""Alias only complete, byte-identical resources from a declared dependency.
|
||||
|
||||
Each source has already undergone its game's asset preparation. Comparing
|
||||
the actual staged bytes prevents reusing a differently cropped or edited
|
||||
picture merely because it came from the same original filename.
|
||||
"""
|
||||
requirements = app.get('requires', [])
|
||||
by_id = {item['descriptor']['id']: item for item in apps}
|
||||
links = []
|
||||
for dependency in requirements:
|
||||
original = by_id[dependency]
|
||||
if app['source'] != original['source']:
|
||||
continue
|
||||
descriptor = original['descriptor']
|
||||
prefixes = [{'from': descriptor['assets'], 'to': ''}, *shared_copies(original)]
|
||||
original_root = staged / descriptor['name'] / 'assets' / descriptor['name']
|
||||
for copy in shared_copies(app):
|
||||
for prefix in prefixes:
|
||||
try:
|
||||
relative = Path(copy['from']).relative_to(prefix['from'])
|
||||
except ValueError:
|
||||
continue
|
||||
target = resources / copy['to']
|
||||
source = original_root / prefix['to'] / relative
|
||||
if not target.exists() or not source.exists():
|
||||
continue
|
||||
if target.is_dir() != source.is_dir():
|
||||
continue
|
||||
if target.is_dir():
|
||||
files = [p for p in target.rglob('*') if p.is_file()]
|
||||
if not files or any(not (source / p.relative_to(target)).is_file() or
|
||||
p.read_bytes() != (source / p.relative_to(target)).read_bytes() for p in files):
|
||||
continue
|
||||
suffix = '/'
|
||||
else:
|
||||
if target.read_bytes() != source.read_bytes():
|
||||
continue
|
||||
suffix = ''
|
||||
links.append(dict(dependency=dependency,
|
||||
path=f'assets/{app["descriptor"]["name"]}/{Path(copy["to"]).as_posix()}' + suffix,
|
||||
source=f'assets/{descriptor["name"]}/{(Path(prefix["to"]) / relative).as_posix()}' + suffix))
|
||||
if target.is_dir():
|
||||
shutil.rmtree(target)
|
||||
else:
|
||||
target.unlink()
|
||||
break
|
||||
if len(links) > 16:
|
||||
raise ValueError('Too many shared resource links')
|
||||
return dict(dependencies=requirements, resources=links)
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stage bounded thumbnails for every game's library covers and previews.
|
||||
|
||||
Library covers retain full colour and transparency at thumbnail resolution:
|
||||
opaque cover art is a JPEG, a sixth of its PNG size, while logos keep their
|
||||
transparency and previews their pixel art as PNG. Games keep their own
|
||||
original title artwork. Arcade downloads this small art
|
||||
bundle separately from its launcher and caches it by its content digest.
|
||||
|
||||
The copies and sources.json, which records the SHA-256 of the art each copy
|
||||
was made from, are committed. The collection build uses them as they are,
|
||||
so its bytes never depend on the local image library, and it stops when a
|
||||
game's art changes until this script makes fresh copies.
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
from game_packages import declared_packages
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LIBRARY = ROOT / 'assets/arcade/library'
|
||||
PREVIEW_LONGEST = 480
|
||||
COVER_LONGEST = 640
|
||||
LOGO_LONGEST = 512
|
||||
|
||||
|
||||
COVER_QUALITY = 85
|
||||
SUFFIXES = ('.png', '.jpg')
|
||||
|
||||
|
||||
def copy_path(name):
|
||||
"""The committed copy for name, whichever format it was made in."""
|
||||
for suffix in SUFFIXES:
|
||||
if (LIBRARY / (name + suffix)).is_file():
|
||||
return LIBRARY / (name + suffix)
|
||||
raise FileNotFoundError(f'{name} has no library copy; run scripts/library-art.py')
|
||||
|
||||
|
||||
def small_copy(data, key):
|
||||
"""(bytes, suffix) of the library's copy of one picture."""
|
||||
image = Image.open(io.BytesIO(data))
|
||||
image.load()
|
||||
longest = PREVIEW_LONGEST if key == 'preview' else LOGO_LONGEST if key == 'logo' else COVER_LONGEST
|
||||
scale = min(1.0, longest / max(image.size))
|
||||
alpha = 'A' in image.getbands() or 'transparency' in image.info
|
||||
photo = key in ('portrait', 'landscape') and not alpha
|
||||
if scale == 1.0 and key != 'preview' and not photo:
|
||||
return data, '.png'
|
||||
image = image.convert('RGBA' if alpha else 'RGB')
|
||||
if scale < 1.0:
|
||||
size = (max(1, round(image.width * scale)), max(1, round(image.height * scale)))
|
||||
image = image.resize(size, Image.Resampling.LANCZOS)
|
||||
if key == 'preview':
|
||||
if alpha:
|
||||
image = image.quantize(256, method=Image.Quantize.FASTOCTREE, dither=Image.Dither.FLOYDSTEINBERG)
|
||||
else:
|
||||
image = image.quantize(256, dither=Image.Dither.FLOYDSTEINBERG)
|
||||
output = io.BytesIO()
|
||||
if photo:
|
||||
image.save(output, 'JPEG', quality=COVER_QUALITY, optimize=True, progressive=True)
|
||||
return output.getvalue(), '.jpg'
|
||||
image.save(output, 'PNG', optimize=True)
|
||||
return output.getvalue(), '.png'
|
||||
|
||||
|
||||
def art(root=ROOT):
|
||||
"""(copy name, key, source bytes) for every enabled game's library art."""
|
||||
for package in declared_packages(root)[1:]:
|
||||
for app in package['apps']:
|
||||
if not app['enabled']:
|
||||
continue
|
||||
name = app['descriptor']['name']
|
||||
yield name, 'preview', (app['source'] / app['descriptor']['preview']).read_bytes()
|
||||
for key in ('portrait', 'landscape', 'logo'):
|
||||
if app['cover'] and key in app['cover']:
|
||||
yield name, key, (app['source'] / app['cover'][key]).read_bytes()
|
||||
|
||||
|
||||
def main():
|
||||
LIBRARY.mkdir(parents=True, exist_ok=True)
|
||||
sources = {}
|
||||
written = set()
|
||||
for name, key, data in art():
|
||||
copy = f'{name}-{key}'
|
||||
contents, suffix = small_copy(data, key)
|
||||
(LIBRARY / (copy + suffix)).write_bytes(contents)
|
||||
written.add(copy + suffix)
|
||||
sources[copy] = {'source_sha256': hashlib.sha256(data).hexdigest()}
|
||||
for suffix in SUFFIXES:
|
||||
for stale in LIBRARY.glob('*' + suffix):
|
||||
if stale.name not in written:
|
||||
stale.unlink()
|
||||
(LIBRARY / 'sources.json').write_text(json.dumps(dict(sorted(sources.items())), indent=2) + '\n')
|
||||
total = sum((LIBRARY / name).stat().st_size for name in written)
|
||||
print(f'{len(sources)} library images, {total / 1048576:.1f} MiB')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Wait for the game packages a published Arcade catalog advertises.
|
||||
|
||||
The site still tests the real Inbe API before its browser gate. The publisher
|
||||
can follow a GitHub release by several minutes, so readiness is conditional and
|
||||
has a hard deadline; no package is extracted or executed.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
API_ROOT = "https://api.waozi.xyz"
|
||||
CATALOG_PATH = "assets/apps/catalog.json"
|
||||
BUNDLE_LIMIT = 64 * 1024 * 1024
|
||||
CATALOG_LIMIT = 1024 * 1024
|
||||
READ_CHUNK = 1024 * 1024
|
||||
PREFIX_BYTES = 16
|
||||
REQUEST_TIMEOUT_SECONDS = 15
|
||||
|
||||
|
||||
class Reader:
|
||||
def __init__(self, path):
|
||||
self.size = path.stat().st_size
|
||||
if self.size > BUNDLE_LIMIT:
|
||||
raise ValueError("published Arcade bundle is too large")
|
||||
self.remaining = self.size
|
||||
self.file = path.open("rb")
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, kind, value, traceback):
|
||||
self.file.close()
|
||||
|
||||
def take(self, size):
|
||||
if size < 0 or size > self.remaining:
|
||||
raise ValueError("truncated bundle")
|
||||
data = self.file.read(size)
|
||||
if len(data) != size:
|
||||
raise ValueError("truncated bundle")
|
||||
self.remaining -= size
|
||||
return data
|
||||
|
||||
def skip(self, size):
|
||||
if size < 0 or size > self.remaining:
|
||||
raise ValueError("truncated bundle")
|
||||
self.file.seek(size, 1)
|
||||
self.remaining -= size
|
||||
|
||||
def number(self):
|
||||
return struct.unpack("<I", self.take(4))[0]
|
||||
|
||||
def text(self, limit=BUNDLE_LIMIT):
|
||||
size = self.number()
|
||||
if size > limit or size > self.remaining:
|
||||
raise ValueError("oversized bundle field")
|
||||
return self.take(size)
|
||||
|
||||
def finish(self):
|
||||
if self.file.read(1):
|
||||
raise ValueError("trailing bundle bytes")
|
||||
self.file.close()
|
||||
|
||||
|
||||
def catalog_from_bundle(path):
|
||||
with Reader(path) as reader:
|
||||
if reader.take(8) != b"ZX\0\0\x1a\0\0\0":
|
||||
raise ValueError("unsupported bundle")
|
||||
reader.text()
|
||||
reader.text()
|
||||
for _ in range(reader.number()):
|
||||
reader.text()
|
||||
reader.text()
|
||||
for _ in range(reader.number()):
|
||||
for _ in range(7):
|
||||
reader.text()
|
||||
reader.take(8)
|
||||
reader.text()
|
||||
reader.take(4)
|
||||
for _ in range(reader.number()):
|
||||
for _ in range(3):
|
||||
reader.text()
|
||||
reader.skip(reader.number())
|
||||
assets = reader.number()
|
||||
catalog = None
|
||||
seen = set()
|
||||
for _ in range(assets):
|
||||
name = reader.text().decode()
|
||||
if name in seen:
|
||||
raise ValueError("duplicate bundle file")
|
||||
seen.add(name)
|
||||
size = reader.number()
|
||||
if name == CATALOG_PATH:
|
||||
if catalog is not None or size > CATALOG_LIMIT:
|
||||
raise ValueError("invalid collection catalog")
|
||||
catalog = reader.take(size)
|
||||
else:
|
||||
reader.skip(size)
|
||||
reader.finish()
|
||||
if catalog is None:
|
||||
raise ValueError("the collection lacks a catalog")
|
||||
return json.loads(catalog)
|
||||
|
||||
|
||||
def expected_games(catalog):
|
||||
children = catalog.get("children")
|
||||
if not isinstance(children, list):
|
||||
raise ValueError("invalid collection catalog")
|
||||
games = {}
|
||||
for child in children:
|
||||
digest, size = child.get("sha256", ""), child.get("bytes")
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", digest) or not isinstance(size, int) \
|
||||
or not 0 < size <= BUNDLE_LIMIT:
|
||||
raise ValueError("invalid game in the collection catalog")
|
||||
games[digest] = size
|
||||
return games
|
||||
|
||||
|
||||
def archive_members(archive, games):
|
||||
members = {}
|
||||
with tarfile.open(archive, "r:") as content:
|
||||
for entry in content:
|
||||
digest = entry.name.removesuffix(".zx")
|
||||
if digest not in games:
|
||||
continue
|
||||
if not entry.isfile() or digest in members or entry.size != games[digest]:
|
||||
raise ValueError("the release game archive differs from the catalog")
|
||||
source = content.extractfile(entry)
|
||||
source_digest = hashlib.sha256()
|
||||
prefix = bytearray()
|
||||
read = 0
|
||||
while chunk := source.read(min(READ_CHUNK, games[digest] - read)):
|
||||
source_digest.update(chunk)
|
||||
if len(prefix) < PREFIX_BYTES:
|
||||
prefix.extend(chunk[:PREFIX_BYTES - len(prefix)])
|
||||
read += len(chunk)
|
||||
if read != games[digest] or source_digest.hexdigest() != digest:
|
||||
raise ValueError("the release game archive differs from the catalog")
|
||||
members[digest] = (source_digest.hexdigest(), bytes(prefix))
|
||||
if set(members) != set(games):
|
||||
raise ValueError("the release game archive lacks a catalog game")
|
||||
return members
|
||||
|
||||
|
||||
def package_ready(api_root, digest, size, prefix, timeout_seconds=REQUEST_TIMEOUT_SECONDS):
|
||||
url = f"{api_root.rstrip('/')}/api/v2/packages/inbe.arcade/{digest}.zx"
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={"Range": f"bytes=0-{PREFIX_BYTES - 1}", "User-Agent": "arcade-site-readiness"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout_seconds) as response:
|
||||
status = response.status
|
||||
content_type = response.headers.get_content_type()
|
||||
etag = response.headers.get("ETag")
|
||||
content_range = response.headers.get("Content-Range")
|
||||
content_length = response.headers.get("Content-Length")
|
||||
body = response.read(PREFIX_BYTES)
|
||||
except urllib.error.HTTPError as error:
|
||||
error.close()
|
||||
return False
|
||||
except (TimeoutError, urllib.error.URLError):
|
||||
return False
|
||||
if etag != f'"{digest}"':
|
||||
return False
|
||||
expected_length = size if status == 200 else min(PREFIX_BYTES, size)
|
||||
if content_length is not None:
|
||||
try:
|
||||
length = int(content_length)
|
||||
except ValueError:
|
||||
return False
|
||||
if length != expected_length:
|
||||
return False
|
||||
if status == 206:
|
||||
match = re.fullmatch(r"bytes 0-(\d+)/(\d+)", content_range or "")
|
||||
if not match or int(match[1]) != min(PREFIX_BYTES, size) - 1 or int(match[2]) != size:
|
||||
return False
|
||||
elif status != 200:
|
||||
return False
|
||||
return content_type == "application/octet-stream" and body == prefix
|
||||
|
||||
|
||||
def wait_for_published_games(api_root, archive, games, members, deadline_seconds,
|
||||
poll_seconds=30, clock=time.monotonic, sleep=time.sleep):
|
||||
deadline = clock() + deadline_seconds
|
||||
pending = set(games)
|
||||
while True:
|
||||
for digest in list(pending):
|
||||
remaining = deadline - clock()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError(
|
||||
f"published game packages still unavailable: {', '.join(sorted(pending))}"
|
||||
)
|
||||
ready = package_ready(
|
||||
api_root, digest, games[digest], members[digest][1],
|
||||
timeout_seconds=min(REQUEST_TIMEOUT_SECONDS, remaining),
|
||||
)
|
||||
if not ready:
|
||||
continue
|
||||
pending.remove(digest)
|
||||
if not pending:
|
||||
return
|
||||
now = clock()
|
||||
remaining = deadline - now
|
||||
if remaining <= 0:
|
||||
raise TimeoutError(f"published game packages still unavailable: {', '.join(pending)}")
|
||||
sleep(min(poll_seconds, remaining))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--api-root", default=API_ROOT)
|
||||
parser.add_argument("--deadline-seconds", type=int, default=900)
|
||||
parser.add_argument("--poll-seconds", type=float, default=30)
|
||||
parser.add_argument("bundle", type=Path)
|
||||
parser.add_argument("archive", type=Path)
|
||||
arguments = parser.parse_args()
|
||||
catalog = catalog_from_bundle(arguments.bundle)
|
||||
games = expected_games(catalog)
|
||||
members = archive_members(arguments.archive, games)
|
||||
wait_for_published_games(arguments.api_root, arguments.archive, games, members,
|
||||
arguments.deadline_seconds, arguments.poll_seconds)
|
||||
print(f"all {len(games)} catalog game packages are published and ready")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, TimeoutError, tarfile.TarError) as error:
|
||||
raise SystemExit(str(error))
|
||||
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
X-Content-Type-Options: nosniff
|
||||
Referrer-Policy: strict-origin-when-cross-origin
|
||||
|
||||
/*.webp
|
||||
Cache-Control: public, max-age=604800
|
||||
|
||||
/*.png
|
||||
Cache-Control: public, max-age=604800
|
||||
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#181622"/><g transform="translate(4 4)" fill="none" stroke="#fff" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M15 9v3M13.5 10.5h3M7 5c1 0 3 1 5 1s4-1 5-1c3 0 7 14 3 14-3 0-4.5-4-8-4s-5 4-8 4C0 19 4 5 7 5Zm3 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 394 B |
@@ -0,0 +1,188 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Arcade</title>
|
||||
<meta name="description" content="Arcade: all of Waozi's games in one place. Pick a cover, download the game and play, free in your browser.">
|
||||
<meta name="theme-color" content="#111223">
|
||||
<link rel="canonical" href="https://arcade.waozi.xyz/">
|
||||
<link rel="icon" href="icon.svg" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="apple-touch-icon.png">
|
||||
<link rel="manifest" href="manifest.webmanifest">
|
||||
<!-- The runtime downloads while the page fetches the collection's files. -->
|
||||
<link rel="preload" href="runtime.js?v=__ARCADE_ASSET_REVISION__" as="script">
|
||||
<link rel="preload" href="runtime.wasm?v=__ARCADE_ASSET_REVISION__" as="fetch" type="application/wasm" crossorigin>
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="https://arcade.waozi.xyz/">
|
||||
<meta property="og:title" content="Arcade">
|
||||
<meta property="og:description" content="All of Waozi's games in one place, free in your browser.">
|
||||
<meta property="og:image" content="https://arcade.waozi.xyz/og.jpg">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<style>
|
||||
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; overscroll-behavior: none; background: #111223; color: #f4f2ff; }
|
||||
canvas { display: block; width: 100%; height: 100%; outline: none; touch-action: none; }
|
||||
#loading { position: fixed; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 20px; background: #111223; font: 600 16px/1.4 system-ui, sans-serif; transition: opacity .3s ease; }
|
||||
#loading.done { opacity: 0; pointer-events: none; }
|
||||
#loading svg { width: 64px; height: 64px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
||||
#loading .track { width: min(280px, 70vw); height: 6px; border-radius: 3px; background: #ffffff26; overflow: hidden; }
|
||||
#loading .bar { width: 0; height: 100%; background: #ffd166; transition: width .2s ease; }
|
||||
#loading .failed { display: none; color: #ffb4a8; text-align: center; padding: 0 24px; }
|
||||
#loading.error .failed { display: block; }
|
||||
#loading.error .track { display: none; }
|
||||
#loading.error { opacity: 1; pointer-events: auto; }
|
||||
#loading button { border: 0; border-radius: 12px; padding: 14px 24px; background: #ffd166; color: #111223; font: inherit; cursor: pointer; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="canvas" tabindex="0"></canvas>
|
||||
<div id="loading" role="status" aria-live="polite">
|
||||
<!-- MingCute game_2 gamepad, Apache-2.0 -->
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M15 9v3M13.5 10.5h3M7 5c1 0 3 1 5 1s4-1 5-1c3 0 7 14 3 14-3 0-4.5-4-8-4s-5 4-8 4C0 19 4 5 7 5Zm3 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Z"/></svg>
|
||||
<div class="track"><div class="bar"></div></div>
|
||||
<p class="failed">Arcade stopped while opening an app. Your saved games are kept.</p>
|
||||
<button class="failed" id="retry" type="button">Return to library</button>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
var loading = document.getElementById('loading');
|
||||
var bar = loading.querySelector('.bar');
|
||||
var assetRevision = '__ARCADE_ASSET_REVISION__';
|
||||
function assetUrl(name) {
|
||||
var url = new URL(name, document.baseURI);
|
||||
url.searchParams.set('v', assetRevision);
|
||||
return url.href;
|
||||
}
|
||||
function failed() { loading.classList.remove('done'); loading.classList.add('error'); }
|
||||
document.getElementById('retry').addEventListener('click', function () { location.reload(); });
|
||||
// Keep watching after startup: a later game failure also needs recovery.
|
||||
function watch() {
|
||||
if (window.Module && Module.arcadeFailed) { failed(); return; }
|
||||
if (window.Module && Module.profileReady) loading.classList.add('done');
|
||||
requestAnimationFrame(watch);
|
||||
}
|
||||
window.Module = {
|
||||
canvas: document.getElementById('canvas'),
|
||||
locateFile: assetUrl,
|
||||
setStatus: function (text) {
|
||||
var match = /\((\d+(?:\.\d+)?)\/(\d+)\)/.exec(text || '');
|
||||
if (match) bar.style.width = Math.min(100, 100 * match[1] / match[2]) + '%';
|
||||
},
|
||||
onAbort: failed,
|
||||
onExit: function (code) { if (code !== 0) failed(); }
|
||||
};
|
||||
// Bundles travel gzip-compressed beside their plain copies: Cloudflare
|
||||
// does not compress binary files. Browsers without DecompressionStream,
|
||||
// or a missing .gz, take the plain file; null when neither exists.
|
||||
function plain(name) {
|
||||
return fetch(assetUrl(name)).then(function (response) {
|
||||
return response.ok ? response.arrayBuffer() : null;
|
||||
});
|
||||
}
|
||||
function bundle(name) {
|
||||
if (typeof DecompressionStream !== 'function') return plain(name);
|
||||
return fetch(assetUrl(name + '.gz')).then(function (response) {
|
||||
if (!response.ok) throw new Error(response.status);
|
||||
return response.arrayBuffer();
|
||||
}).then(function (packed) {
|
||||
var head = new Uint8Array(packed, 0, Math.min(2, packed.byteLength));
|
||||
// A server that already decoded it hands over the plain bytes.
|
||||
if (head[0] !== 0x1f || head[1] !== 0x8b) return packed;
|
||||
return new Response(new Blob([packed]).stream()
|
||||
.pipeThrough(new DecompressionStream('gzip'))).arrayBuffer();
|
||||
}).catch(function () { return plain(name); });
|
||||
}
|
||||
function hex(buffer) {
|
||||
return Array.prototype.map.call(new Uint8Array(buffer), function (byte) {
|
||||
return (byte < 16 ? '0' : '') + byte.toString(16);
|
||||
}).join('');
|
||||
}
|
||||
function file(name) {
|
||||
return fetch(assetUrl(name)).then(function (response) {
|
||||
if (!response.ok) throw new Error(response.status);
|
||||
return response.arrayBuffer();
|
||||
});
|
||||
}
|
||||
// The library's pictures come from this site, never api.waozi.xyz:
|
||||
// small copies of the collection's signed art (library.json), each
|
||||
// checked against its digest, or the exact art bundle for a browser
|
||||
// that cannot draw WebP or check them. The host verifies that bundle.
|
||||
function library() {
|
||||
return fetch(assetUrl('library.json')).then(function (response) {
|
||||
return response.ok ? response.json() : null;
|
||||
}).then(function (listing) {
|
||||
if (!listing) return null;
|
||||
var paths = Object.keys(listing.pictures);
|
||||
return Promise.all(paths.map(function (path) {
|
||||
var picture = listing.pictures[path];
|
||||
return file(picture.file).then(function (bytes) {
|
||||
return crypto.subtle.digest('SHA-256', bytes).then(function (digest) {
|
||||
if (hex(digest) !== picture.sha256) throw new Error(path);
|
||||
return bytes;
|
||||
});
|
||||
});
|
||||
})).then(function (copies) {
|
||||
var webp = paths.findIndex(function (path) { return /\.webp$/.test(listing.pictures[path].file); });
|
||||
var drawn = webp < 0 ? Promise.resolve() : createImageBitmap(new Blob([copies[webp]])).then(function (bitmap) { bitmap.close(); });
|
||||
return drawn.then(function () { return { art: listing.art, paths: paths, copies: copies }; });
|
||||
}).catch(function () {
|
||||
return file('library/' + listing.art + '.zx').then(function (bundle) {
|
||||
return { art: listing.art, bundle: bundle };
|
||||
});
|
||||
});
|
||||
}).catch(function () { return null; });
|
||||
}
|
||||
function writeLibrary(pictures) {
|
||||
if (pictures.bundle) {
|
||||
FS.mkdirTree('/packages');
|
||||
FS.writeFile('/packages/' + pictures.art + '.zx', new Uint8Array(pictures.bundle));
|
||||
return;
|
||||
}
|
||||
pictures.paths.forEach(function (path, index) {
|
||||
var name = '/library/' + pictures.art + '/' + path;
|
||||
FS.mkdirTree(name.slice(0, name.lastIndexOf('/')));
|
||||
FS.writeFile(name, new Uint8Array(pictures.copies[index]));
|
||||
});
|
||||
}
|
||||
// The build receipt names the collection's digest and its trusted Apps
|
||||
// library; Arcade's own copy of that library goes in beside it.
|
||||
Promise.all([
|
||||
fetch(assetUrl('arcade.json'), { cache: 'no-cache' }).then(function (response) {
|
||||
if (!response.ok) throw new Error(response.status);
|
||||
return response.text();
|
||||
}),
|
||||
bundle('apps.zx'),
|
||||
bundle('runtime.data'),
|
||||
library()
|
||||
]).then(function (loaded) {
|
||||
Module.arcadeReceipt = loaded[0];
|
||||
Module.preRun = [function () {
|
||||
if (loaded[1]) FS.writeFile('/apps.zx', new Uint8Array(loaded[1]));
|
||||
if (loaded[3]) writeLibrary(loaded[3]);
|
||||
}];
|
||||
// The runtime's file package, already here, is not fetched again.
|
||||
if (loaded[2]) {
|
||||
Module.getPreloadedPackage = function () { return loaded[2]; };
|
||||
}
|
||||
function start() {
|
||||
var script = document.createElement('script');
|
||||
script.src = assetUrl('runtime.js');
|
||||
script.onerror = failed;
|
||||
document.body.appendChild(script);
|
||||
watch();
|
||||
}
|
||||
// One sign-in for every waozi.xyz site: account.waozi.xyz hands over
|
||||
// the shared profile before Arcade starts, or Arcade starts without it.
|
||||
var started = false;
|
||||
function go() { if (!started) { started = true; start(); } }
|
||||
var shared = document.createElement('script');
|
||||
shared.src = 'https://account.waozi.xyz/share.js';
|
||||
shared.onload = function () { WaoziAccount.attach(Module, 2500).then(go, go); };
|
||||
shared.onerror = go;
|
||||
setTimeout(go, 4000);
|
||||
document.head.appendChild(shared);
|
||||
}).catch(failed);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "Arcade",
|
||||
"short_name": "Arcade",
|
||||
"description": "All my games in one place.",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#181622",
|
||||
"theme_color": "#181622",
|
||||
"icons": [
|
||||
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
||||
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 155 KiB |
@@ -19,6 +19,9 @@ ARCADE_BACK_KEY :: 4
|
||||
arcade_state: s32;
|
||||
|
||||
ArcadeStart :: () -> bool {
|
||||
// Later animation pictures load asynchronously too. Keep the last
|
||||
// complete frame visible while a new sprite is being decoded.
|
||||
RaylibCompletePictureFrames(true)
|
||||
// Android before 10 cannot name its system font; the APK carries the
|
||||
// same font as the Windows build, so text never falls back to raylib's
|
||||
// bitmap font.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Arcade's library art: the games' covers, logos and previews, downloaded
|
||||
// beside the games. The Apps host only reads its assets; it never runs.
|
||||
#program_export
|
||||
Main :: () -> s32 { return 0 }
|
||||
@@ -9,12 +9,14 @@ Game :: struct {
|
||||
enabled: bool
|
||||
}
|
||||
|
||||
GameCount :: 4
|
||||
GameCount :: 6
|
||||
|
||||
GameAt :: (index: s32) -> Game {
|
||||
if index == 0 { return Game.{.id = "inbe.chess", .name = "chess", .title = "Chess", .bundle = "chess.zx", .preview = "chess-preview.png", .package = "self", .enabled = false} }
|
||||
if index == 1 { return Game.{.id = "arcade.shovey", .name = "shovey", .title = "Shovey", .bundle = "shovey.zx", .preview = "shovey-preview.png", .package = "shovey", .enabled = true} }
|
||||
if index == 2 { return Game.{.id = "arcade.shovey-island", .name = "shovey-island", .title = "Shovey Island", .bundle = "shovey-island.zx", .preview = "shovey-island-preview.png", .package = "shovey", .enabled = false} }
|
||||
if index == 3 { return Game.{.id = "arcade.shovey-editor", .name = "shovey-editor", .title = "Shovey Editor", .bundle = "shovey-editor.zx", .preview = "shovey-editor-preview.png", .package = "shovey", .enabled = true} }
|
||||
if index == 2 { return Game.{.id = "arcade.shovey-editor", .name = "shovey-editor", .title = "Shovey Editor", .bundle = "shovey-editor.zx", .preview = "shovey-editor-preview.png", .package = "shovey", .enabled = true} }
|
||||
if index == 3 { return Game.{.id = "xyz.waozi.wurm", .name = "wurm", .title = "Apfelwurm", .bundle = "wurm.zx", .preview = "wurm-preview.png", .package = "wurm", .enabled = true} }
|
||||
if index == 4 { return Game.{.id = "xyz.waozi.wurm-editor", .name = "wurm-editor", .title = "Apfelwurm Editor", .bundle = "wurm-editor.zx", .preview = "wurm-editor-preview.png", .package = "wurm", .enabled = true} }
|
||||
if index == 5 { return Game.{.id = "xyz.waozi.choano", .name = "choano", .title = "Choano", .bundle = "choano.zx", .preview = "choano-preview.png", .package = "choano", .enabled = true} }
|
||||
return Game.{}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
// Downloads are separate from saves. The signed collection fixes each
|
||||
// digest; a transfer is made available only after those exact bytes verify.
|
||||
#import "kryon/file_download"
|
||||
#import "kryon/app_files"
|
||||
#import "kryon/hosted_app"
|
||||
#import "apps/host"
|
||||
#import "apps/catalog"
|
||||
#import "apps/tree"
|
||||
#import "apps/protocol"
|
||||
#import "std/text_buffer"
|
||||
#import "std/vec"
|
||||
#import "std/c_string"
|
||||
#import "std/file"
|
||||
#import "platform"
|
||||
|
||||
CollectionPackage :: struct {
|
||||
digest: [65]u8
|
||||
size: s64
|
||||
bytes: string
|
||||
file: string
|
||||
transfer: FileDownload
|
||||
failed: bool
|
||||
next: *CollectionPackage
|
||||
}
|
||||
collection_packages: *CollectionPackage;
|
||||
collection_package_result: string;
|
||||
collection_package_files: *AppFiles;
|
||||
// Packages the platform already holds, read-only and verified like a
|
||||
// download: the website's own copy of the library art. "" for none.
|
||||
collection_package_folder: string;
|
||||
package_c :: #system_library "c";
|
||||
PackageFree :: (memory: *void) #foreign package_c "free";
|
||||
CollectionDownloadsOpen :: (files: *AppFiles) { collection_package_files = files }
|
||||
|
||||
CollectionReadPackage :: (path: string) -> string {
|
||||
file := OpenRead(path)
|
||||
if !file.valid { return "" }
|
||||
size := FileSize(file)
|
||||
unused CloseFile(file)
|
||||
if size < 1 || size > APP_HOST_BYTE_LIMIT { return "" }
|
||||
bytes, found := ReadEntireFile(path)
|
||||
if !found { AppFileFree(bytes); return "" }
|
||||
return bytes
|
||||
}
|
||||
|
||||
CollectionPackageFor :: (entry: *AppEntry) -> *CollectionPackage {
|
||||
package := collection_packages
|
||||
while package != null {
|
||||
if TextUntilNul(package.digest[:]) == TextUntilNul(entry.sha256[:]) { return package }
|
||||
package = package.next
|
||||
}
|
||||
package = New(CollectionPackage)
|
||||
if package == null { return null }
|
||||
package.digest = entry.sha256
|
||||
package.size = entry.bytes
|
||||
name: Vec(u8)
|
||||
BuilderPrint(*name, "downloads/%.zx", TextUntilNul(package.digest[:]))
|
||||
relative := BuilderFinish(name)
|
||||
package.file = AppFilePath(collection_package_files, relative, true)
|
||||
package.bytes = CollectionReadPackage(package.file)
|
||||
AppFileFree(relative)
|
||||
if package.bytes != "" && !CollectionPackageValid(package) {
|
||||
AppFileFree(package.bytes)
|
||||
package.bytes = ""
|
||||
package.failed = true
|
||||
}
|
||||
if package.bytes == "" && collection_package_folder != "" {
|
||||
held: Vec(u8)
|
||||
BuilderPrint(*held, "%/%.zx", collection_package_folder, TextUntilNul(package.digest[:]))
|
||||
path := BuilderFinish(held)
|
||||
package.bytes = CollectionReadPackage(path)
|
||||
AppFileFree(path)
|
||||
if package.bytes != "" && CollectionPackageValid(package) {
|
||||
package.failed = false
|
||||
} else if package.bytes != "" {
|
||||
AppFileFree(package.bytes)
|
||||
package.bytes = ""
|
||||
package.failed = true
|
||||
}
|
||||
}
|
||||
package.next = collection_packages
|
||||
collection_packages = package
|
||||
return package
|
||||
}
|
||||
|
||||
CollectionPackageValid :: (package: *CollectionPackage) -> bool {
|
||||
return package.bytes.count > 0 && package.bytes.count <= APP_HOST_BYTE_LIMIT &&
|
||||
(package.size == 0 || package.bytes.count == package.size) &&
|
||||
AppHostBytesMatch(package.bytes, TextUntilNul(package.digest[:]))
|
||||
}
|
||||
|
||||
CollectionBundle :: (context: *void, parent: *AppNode, entry: *AppEntry) -> HostedAsset {
|
||||
if TextUntilNul(parent.identity.id[:]) != "inbe.arcade" { return HostedAsset.{} }
|
||||
package := CollectionPackageFor(entry)
|
||||
if package == null { return HostedAsset.{} }
|
||||
collection_package_result = package.bytes
|
||||
return HostedAsset.{.data = collection_package_result, .found = collection_package_result != ""}
|
||||
}
|
||||
|
||||
CollectionDownload :: (context: *void, parent: *AppNode, entry: *AppEntry, download: *AppDownload) -> bool {
|
||||
if TextUntilNul(parent.identity.id[:]) != "inbe.arcade" { return false }
|
||||
package := CollectionPackageFor(entry)
|
||||
download.bytes = entry.bytes
|
||||
if package == null { download.failed = true; return true }
|
||||
if package.bytes != "" { return false }
|
||||
download.downloading = package.transfer.status == .Downloading
|
||||
download.failed = package.failed
|
||||
download.progress = -1
|
||||
if package.transfer.total_bytes > 0 {
|
||||
download.progress = cast(s32)(package.transfer.bytes * 100 / package.transfer.total_bytes)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
CollectionFetch :: (context: *void, account: string, parent: *AppNode,
|
||||
entry: *AppEntry, operation: s32, reply: *AppsReply) -> bool {
|
||||
if account != "local" || TextUntilNul(parent.identity.id[:]) != "inbe.arcade" { return false }
|
||||
package := CollectionPackageFor(entry)
|
||||
if package == null { return false }
|
||||
if operation != APPS_INSTALL { return false }
|
||||
// Cached installs and removals use the host's ordinary saved state.
|
||||
if package.bytes != "" { return false }
|
||||
if package.transfer.status != .Downloading {
|
||||
FileDownloadRelease(*package.transfer)
|
||||
package.failed = false
|
||||
base := EnvironmentText("ARCADE_PACKAGE_ORIGIN")
|
||||
if base == "" { base = "https://api.waozi.xyz" }
|
||||
url: Vec(u8)
|
||||
BuilderPrint(*url, "%/api/v2/packages/inbe.arcade/%.zx", base, TextUntilNul(package.digest[:]))
|
||||
address := BuilderFinish(url)
|
||||
defer { AppFileFree(address) }
|
||||
package.transfer.maximum_bytes = cast(u64)(ifx package.size > 0 then package.size else APP_HOST_BYTE_LIMIT)
|
||||
if !FileDownloadStart(*package.transfer, address, package.file) { package.failed = true }
|
||||
}
|
||||
reply.status = ifx package.failed then APPS_REJECTED else APPS_APPLIED
|
||||
return true
|
||||
}
|
||||
|
||||
CollectionDownloadsPump :: () {
|
||||
package := collection_packages
|
||||
while package != null {
|
||||
if package.transfer.status == .Downloading {
|
||||
status := FileDownloadPoll(*package.transfer)
|
||||
if status == .Ready {
|
||||
package.bytes = CollectionReadPackage(package.file)
|
||||
if !CollectionPackageValid(package) {
|
||||
AppFileFree(package.bytes)
|
||||
package.bytes = ""
|
||||
package.failed = true
|
||||
}
|
||||
} else if status == .Error { package.failed = true }
|
||||
}
|
||||
package = package.next
|
||||
}
|
||||
}
|
||||
|
||||
CollectionDownloadsClose :: () {
|
||||
while collection_packages != null {
|
||||
package := collection_packages
|
||||
collection_packages = package.next
|
||||
FileDownloadRelease(*package.transfer)
|
||||
AppFileFree(package.bytes)
|
||||
AppFileFree(package.file)
|
||||
PackageFree(cast(*void)package)
|
||||
}
|
||||
}
|
||||
@@ -21,26 +21,38 @@
|
||||
#import "kryon/button_widget"
|
||||
#import "kryon/button_props"
|
||||
#import "kryon/hosted_values"
|
||||
#import "kryon/hosted_app"
|
||||
#import "kryon/widget_host"
|
||||
#import "kryon/app_files"
|
||||
#import "kryon/app_protocol"
|
||||
#import "kryon/app_context_host"
|
||||
#if !#defined(PLATFORM_DESKTOP) && !#defined(ANDROID_BUILD) && !#defined(PLATFORM_WEB) {
|
||||
CollectionHost :: #import "kryon/app_context";
|
||||
}
|
||||
#import "kryon/key_input"
|
||||
#import "kryon/system_clipboard"
|
||||
#import "apps/host"
|
||||
#import "apps/tree"
|
||||
#import "apps/catalog"
|
||||
#import "apps/protocol"
|
||||
#import "apps/appearance"
|
||||
Rules :: #import "apps/protocol";
|
||||
Node :: #import "apps/node_types";
|
||||
Codec :: #import "apps/node_codec";
|
||||
#import "platform"
|
||||
#import, file "collection_downloads.zi";
|
||||
#import, file "game_contract.zi";
|
||||
#import "sound"
|
||||
#import "entity_host"
|
||||
#import "entity/publications"
|
||||
#import "entity/publications_read"
|
||||
#import "entity/entity_records"
|
||||
#import "entity/entity_dew"
|
||||
#import "entity/leaderboard_native"
|
||||
#import "kryon/widget_palette"
|
||||
#import "kryon/image_raster"
|
||||
#import "kryon/loading_indicator"
|
||||
#import, file "collection_loading.zi";
|
||||
#import "shovey/shovey_theme"
|
||||
ProfileIcon :: #import "mingcute/mingcute_regular_user_4";
|
||||
DewIcon :: #import "mingcute/mingcute_filled_drop";
|
||||
@@ -76,14 +88,31 @@ collection_shared_codec: Codec.WidgetAppSharedCodec;
|
||||
collection_item_codec: Codec.WidgetAppSharedItemCodec;
|
||||
collection_invitation_codec: Codec.WidgetAppInvitationCodec;
|
||||
collection_ready: bool;
|
||||
collection_loading: CollectionLoading;
|
||||
collection_pictures_missing: bool;
|
||||
collection_leave_to_library: bool;
|
||||
// Whether games download new levels when they come out: asked once on the
|
||||
// covers and passed to the games as arcade.updates. -1 unread, 0 off, 1 on,
|
||||
// 2 not answered yet.
|
||||
collection_updates: s32 = -1;
|
||||
|
||||
CollectionTouchFirst :: () -> bool {
|
||||
#if #defined(PLATFORM_DESKTOP) {
|
||||
return false
|
||||
// Whether the device's main input is a keyboard and mouse. A native build
|
||||
// knows its platform; the collection running as a bundle inside Breeze asks
|
||||
// Breeze (Kryon's kryon.input.desktop), and passes the answer to its games.
|
||||
CollectionInputDesktop :: () -> bool {
|
||||
#if #defined(PLATFORM_DESKTOP) && !#defined(ANDROID_BUILD) && !#defined(PLATFORM_WEB) {
|
||||
return true
|
||||
} else {
|
||||
#if #defined(ANDROID_BUILD) || #defined(PLATFORM_WEB) {
|
||||
return false
|
||||
} else {
|
||||
return CollectionHost.AppSupports(COLLECTION_INPUT_DESKTOP)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
COLLECTION_INPUT_DESKTOP :: "kryon.input.desktop"
|
||||
|
||||
CollectionTouchFirst :: () -> bool { return !CollectionInputDesktop() }
|
||||
|
||||
CollectionRecordsFor :: (id: string) -> *CollectionRecords {
|
||||
saved := collection_records
|
||||
@@ -117,10 +146,13 @@ CollectionAllows :: (context: *void, node: *AppNode, name: string) -> bool {
|
||||
return name == "AppRecordHost" || name == "SaveAppRecordHost" ||
|
||||
name == "AppFriendHost" || name == "AppSharedHost" || name == "AppSharedItemHost" ||
|
||||
name == "AppInvitationHost" || name == "RefreshAppSharedHost" || name == "SendAppSharedHost" ||
|
||||
name == "SmoothFramesHost" || name == "AppLocaleHost" || name == "AppSoundHost" ||
|
||||
name == "SmoothFramesHost" || name == "AppLocaleHost" || name == "AppSoundHost" || name == "AppNowHost" ||
|
||||
name == "tile_map.sampling" || name == "arcade.controls" || name == "arcade.sound" || name == "arcade.navigation" ||
|
||||
name == PUBLICATIONS_READ_SERVICE || name == ENTITY_RECORDS_SERVICE || name == ENTITY_DEW_SERVICE ||
|
||||
name == "entity.profile"
|
||||
name == "arcade.updates" ||
|
||||
name == PUBLICATIONS_SERVICE || name == PUBLICATIONS_READ_SERVICE ||
|
||||
name == ENTITY_RECORDS_SERVICE || name == ENTITY_DEW_SERVICE ||
|
||||
name == "entity.profile" || name == "leaderboard" ||
|
||||
(name == COLLECTION_INPUT_DESKTOP && CollectionInputDesktop())
|
||||
}
|
||||
|
||||
CollectionCall :: (context: *void, node: *AppNode, module: *u8, function: *u8,
|
||||
@@ -154,6 +186,12 @@ CollectionCall :: (context: *void, node: *AppNode, module: *u8, function: *u8,
|
||||
result.* = HostScalar("bool", ifx asset.found && SoundPlay(asset.data) then 1 else 0)
|
||||
return 1
|
||||
}
|
||||
// Seconds since 1970: Apfelwurm counts its daily rewards by them.
|
||||
if name == "AppNowHost" && count == 0 {
|
||||
result.* = HostValue.{.kind = cast(s32)HostReal, .type_name = HostTextData("float64"),
|
||||
.real = cast(float64)UnixMilliseconds() / 1000.0}
|
||||
return 1
|
||||
}
|
||||
if name == "SmoothFramesHost" && count == 1 {
|
||||
result.* = HostScalar("bool", 1)
|
||||
return 1
|
||||
@@ -163,7 +201,19 @@ CollectionCall :: (context: *void, node: *AppNode, module: *u8, function: *u8,
|
||||
HostScalarValid(arguments[1], "string", cast(s32)HostString) {
|
||||
service := AppArgumentText(arguments[0])
|
||||
request := AppArgumentText(arguments[1])
|
||||
if service == "leaderboard" {
|
||||
saved := EntityLeaderboardReport("arcade", "Arcade", TextUntilNul(node.identity.id[:]),
|
||||
TextUntilNul(node.entry.title[:]), request)
|
||||
result.* = AppHostText(ifx saved then "{\"status\":\"saved\"}" else "{\"status\":\"rejected\"}")
|
||||
return 1
|
||||
}
|
||||
// Public level collections, such as a game's live campaign.
|
||||
if service == PUBLICATIONS_SERVICE {
|
||||
// Publications sign as this device's native Entity account.
|
||||
EntityPump()
|
||||
result.* = AppHostText(PublicationsAnswer(request))
|
||||
return 1
|
||||
}
|
||||
if service == PUBLICATIONS_READ_SERVICE {
|
||||
result.* = AppHostText(PublicationsReadAnswer(request))
|
||||
return 1
|
||||
@@ -206,6 +256,16 @@ CollectionCall :: (context: *void, node: *AppNode, module: *u8, function: *u8,
|
||||
result.* = AppHostText(value)
|
||||
return 1
|
||||
}
|
||||
if service == "arcade.updates" {
|
||||
if request == "get" {
|
||||
updates := CollectionUpdates()
|
||||
result.* = AppHostText(ifx updates == 1 then "on" else ifx updates == 0 then "off" else "unset")
|
||||
return 1
|
||||
}
|
||||
if (request != "set-on" && request != "set-off") || !CollectionUpdatesSet(request == "set-on") { return 0 }
|
||||
result.* = AppHostText(request[4:])
|
||||
return 1
|
||||
}
|
||||
if service != "arcade.controls" { return 0 }
|
||||
saved := CollectionRecordsFor("arcade.shovey-player")
|
||||
if saved == null { return 0 }
|
||||
@@ -257,15 +317,49 @@ CollectionCall :: (context: *void, node: *AppNode, module: *u8, function: *u8,
|
||||
return 0
|
||||
}
|
||||
|
||||
// The website's small copies of a collection's separate library art, under
|
||||
// its signed catalog's art digest. The page writes only copies whose digests
|
||||
// match its library.json (scripts/build-web.py); "" on other hosts.
|
||||
collection_thumbnails: string;
|
||||
|
||||
CollectionThumbnail :: (node: *AppNode, path: string) -> string {
|
||||
if collection_thumbnails == "" || node == null || !node.collection ||
|
||||
node.catalog.art_sha256[0] == 0 || !AppAssetPathValid(path) { return "" }
|
||||
copy: Vec(u8)
|
||||
BuilderPrint(*copy, "%/%/%", collection_thumbnails, TextUntilNul(node.catalog.art_sha256[:]), path)
|
||||
thumbnail := BuilderFinish(copy)
|
||||
file := OpenRead(thumbnail)
|
||||
if file.valid { unused CloseFile(file); return thumbnail }
|
||||
AppFileFree(thumbnail)
|
||||
return ""
|
||||
}
|
||||
|
||||
// The website names where its page writes the library's pictures: small
|
||||
// copies, or the exact art bundle for a browser that cannot draw them.
|
||||
CollectionWebLibrary :: (thumbnails: string, packages: string) {
|
||||
collection_thumbnails = thumbnails
|
||||
collection_package_folder = packages
|
||||
}
|
||||
|
||||
CollectionAssetAllowed :: (path: string) -> bool {
|
||||
return path == "" || (collection_widget_node != null && AppHostAsset(collection_widget_node, path).found)
|
||||
if path == "" { return true }
|
||||
if collection_widget_node == null { return false }
|
||||
// Checked first: asking for the art itself starts its download.
|
||||
thumbnail := CollectionThumbnail(collection_widget_node, path)
|
||||
if thumbnail != "" { AppFileFree(thumbnail); return true }
|
||||
return AppHostAsset(collection_widget_node, path).found || AppHostAssetPending(collection_widget_node, path)
|
||||
}
|
||||
|
||||
CollectionAssetPath :: (path: string) -> string {
|
||||
if path == "" { return "" }
|
||||
if collection_widget_node == null { return "" }
|
||||
thumbnail := CollectionThumbnail(collection_widget_node, path)
|
||||
if thumbnail != "" {
|
||||
if !VecPush(collection_frame_paths, thumbnail) { AppFileFree(thumbnail); return "" }
|
||||
return thumbnail
|
||||
}
|
||||
asset := AppHostAsset(collection_widget_node, path)
|
||||
if !asset.found { return "" }
|
||||
if !asset.found { collection_pictures_missing = true; return "" }
|
||||
relative := Join(TextUntilNul(collection_widget_node.entry.sha256[:]), path)
|
||||
defer { AppFileFree(relative) }
|
||||
cached := collection_images
|
||||
@@ -298,6 +392,27 @@ CollectionWidgets :: (context: *void, node: *AppNode, module: *u8, function: *u8
|
||||
return WidgetHostCall(context, module, function, arguments, count, result)
|
||||
}
|
||||
|
||||
// Check the same saved install state and verified download plan as Apps.
|
||||
// A cached payload or an old score alone is never installed membership.
|
||||
CollectionLeaderboardInstalled :: (game: string) -> bool {
|
||||
if !collection_ready { return false }
|
||||
for slot: cast(s64)0..collection_host.tree.nodes.count - 1 {
|
||||
parent := collection_host.tree.nodes[slot].node
|
||||
if parent == null || !parent.collection { continue }
|
||||
index := AppCatalogFind(*parent.catalog, game)
|
||||
if index < 0 { continue }
|
||||
entry := AppCatalogAt(*parent.catalog, index)
|
||||
identity := AppIdentity.{.authority = parent.identity.authority, .id = entry.id}
|
||||
state: AppState
|
||||
plan: AppInstallPlan
|
||||
if CollectionState(null, "local", *identity, *state) && state.installed &&
|
||||
AppHostInstallPlan(*collection_host, parent, entry, *plan) && plan.count == 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
CollectionSave :: (context: *void, node: *AppNode) -> bool {
|
||||
saved := collection_records
|
||||
while saved != null {
|
||||
@@ -361,16 +476,39 @@ CollectionEffect :: (context: *void, account: string, locator: *AppLocator,
|
||||
return true
|
||||
}
|
||||
|
||||
// Arcade's own copy of the shared Apps controller. A collection that does not
|
||||
// pack one uses it; the Apps host accepts it only by the trusted digest.
|
||||
collection_controller: string;
|
||||
|
||||
CollectionController :: (context: *void) -> HostedAsset {
|
||||
unused context
|
||||
controller: HostedAsset
|
||||
controller.data = collection_controller
|
||||
controller.found = collection_controller.count > 0
|
||||
return controller
|
||||
}
|
||||
|
||||
// packed: the collection carries every game and its art, as the Android APK
|
||||
// does, so nothing is downloaded.
|
||||
CollectionOpen :: (bundle: string, digest: string, harness_digest: string,
|
||||
data: string, locale: string) -> bool {
|
||||
data: string, locale: string, packed: bool) -> bool {
|
||||
if collection_ready { return false }
|
||||
leaderboard_installed = CollectionLeaderboardInstalled
|
||||
collection_directory = data
|
||||
collection_resource_root = Join(data, "resources")
|
||||
opened := AppFilesOpen(*collection_resources, collection_resource_root)
|
||||
if !opened { Report("Arcade: cannot open the private resources folder"); return false }
|
||||
CollectionDownloadsOpen(*collection_resources)
|
||||
platform := AppPlatform.{.allows = CollectionAllows, .call = CollectionCall,
|
||||
.widgets = CollectionWidgets, .save = CollectionSave, .state = CollectionState,
|
||||
.effect = CollectionEffect}
|
||||
.effect = CollectionEffect, .host_api = GAME_HOST_API,
|
||||
// Covers show only the art; the download dialog names the size.
|
||||
.controller = CollectionController, .presentation = AppPresentation.{.cover_grid = true, .hide_sizes = true}}
|
||||
if !packed {
|
||||
platform.bundle = CollectionBundle
|
||||
platform.download = CollectionDownload
|
||||
platform.fetch = CollectionFetch
|
||||
}
|
||||
collection_ready = AppHostStart(*collection_host, bundle, "arcade.local", "inbe.arcade",
|
||||
"arcade", digest, "local", platform, harness_digest, locale)
|
||||
if !collection_ready { Report("Arcade: the shared Apps host refused the collection") }
|
||||
@@ -378,6 +516,11 @@ CollectionOpen :: (bundle: string, digest: string, harness_digest: string,
|
||||
}
|
||||
|
||||
CollectionOpenFiles :: (directory: string, data: string) -> bool {
|
||||
// The installed controller beside the collection; kept while Arcade runs.
|
||||
controller_path := Join(directory, "apps.zx")
|
||||
controller, controller_found := ReadEntireFile(controller_path)
|
||||
AppFileFree(controller_path)
|
||||
if controller_found { collection_controller = controller } else { AppFileFree(controller) }
|
||||
bundle_path := Join(directory, "arcade.zx")
|
||||
metadata_path := Join(directory, "arcade.json")
|
||||
defer { AppFileFree(bundle_path); AppFileFree(metadata_path) }
|
||||
@@ -395,6 +538,7 @@ CollectionOpenBytes :: (bytes: string, metadata: string, data: string) -> bool {
|
||||
id: [128]u8
|
||||
digest: [65]u8
|
||||
harness: [65]u8
|
||||
games: [16]u8
|
||||
if !AppsReadText(metadata, 0, "id", id[:]) || TextUntilNul(id[:]) != "inbe.arcade" ||
|
||||
!AppsReadText(metadata, 0, "sha256", digest[:]) ||
|
||||
!AppsReadText(metadata, 0, "apps_sha256", harness[:]) {
|
||||
@@ -403,7 +547,8 @@ CollectionOpenBytes :: (bytes: string, metadata: string, data: string) -> bool {
|
||||
}
|
||||
locale := EnvironmentText("LANG")
|
||||
language := ifx locale.count >= 2 then locale[:2] else "en"
|
||||
return CollectionOpen(bytes, TextUntilNul(digest[:]), TextUntilNul(harness[:]), data, language)
|
||||
packed := AppsReadText(metadata, 0, "games", games[:]) && TextUntilNul(games[:]) == "packed"
|
||||
return CollectionOpen(bytes, TextUntilNul(digest[:]), TextUntilNul(harness[:]), data, language, packed)
|
||||
}
|
||||
|
||||
// The standalone player needs only Shovey's own payload and metadata. Its
|
||||
@@ -419,8 +564,16 @@ CollectionOpenShovey :: (directory: string, data: string) -> bool {
|
||||
return found && metadata_found && CollectionOpenShoveyBytes(bytes, metadata, data)
|
||||
}
|
||||
|
||||
// Metadata of the standalone Shovey player, as the downloads and
|
||||
// shovey.waozi.xyz carry it, rather than of Arcade's collection.
|
||||
CollectionShoveyReceipt :: (metadata: string) -> bool {
|
||||
id: [128]u8
|
||||
return AppsReadText(metadata, 0, "id", id[:]) && TextUntilNul(id[:]) == "arcade.shovey-player"
|
||||
}
|
||||
|
||||
CollectionOpenShoveyBytes :: (bytes: string, metadata: string, data: string) -> bool {
|
||||
if collection_ready { return false }
|
||||
leaderboard_installed = CollectionLeaderboardInstalled
|
||||
id: [128]u8
|
||||
digest: [65]u8
|
||||
harness: [65]u8
|
||||
@@ -435,7 +588,7 @@ CollectionOpenShoveyBytes :: (bytes: string, metadata: string, data: string) ->
|
||||
language := ifx locale.count >= 2 then locale[:2] else "en"
|
||||
platform := AppPlatform.{.allows = CollectionAllows, .call = CollectionCall,
|
||||
.widgets = CollectionWidgets, .save = CollectionSave, .state = CollectionState,
|
||||
.effect = CollectionEffect}
|
||||
.effect = CollectionEffect, .host_api = GAME_HOST_API}
|
||||
collection_ready = AppHostStart(*collection_host, bytes, "arcade.local", "arcade.shovey-player",
|
||||
"shovey", TextUntilNul(digest[:]), "local", platform, TextUntilNul(harness[:]), language)
|
||||
return collection_ready
|
||||
@@ -449,6 +602,7 @@ CollectionBack :: () -> bool {
|
||||
}
|
||||
|
||||
CollectionCollect :: () {
|
||||
CollectionDownloadsPump()
|
||||
if entity_ready { EntityPump() }
|
||||
PublicationsReadPump()
|
||||
AppHostCollect(*collection_host)
|
||||
@@ -461,6 +615,8 @@ CollectionClose :: () -> bool {
|
||||
if !EntityClose() { return false }
|
||||
if collection_ready && !AppHostStop(*collection_host) { return false }
|
||||
collection_ready = false
|
||||
collection_loading = .{}
|
||||
CollectionDownloadsClose()
|
||||
CollectionCollect()
|
||||
VecFree(collection_frame_paths)
|
||||
while collection_images != null {
|
||||
@@ -482,12 +638,29 @@ CollectionClose :: () -> bool {
|
||||
AppFilesClose(*collection_resources)
|
||||
AppFileFree(collection_resource_root)
|
||||
collection_resource_root = ""
|
||||
AppFileFree(collection_controller)
|
||||
collection_controller = ""
|
||||
return true
|
||||
}
|
||||
|
||||
CollectionPending :: (request: s64) -> bool {
|
||||
for index: cast(s64)0..collection_host.tree.pending.count - 1 {
|
||||
pending := collection_host.tree.pending[index]
|
||||
if pending.reply.request == request { return !pending.complete }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
CollectionOpenGame :: (id: string) -> bool {
|
||||
root := AppTreeNode(*collection_host.tree, collection_host.tree.active)
|
||||
if root == null || !root.collection { Report("Arcade: no collection is open to start "); Report(id); Report("\n"); return false }
|
||||
entry := AppCatalogAt(*root.catalog, AppCatalogFind(*root.catalog, id))
|
||||
plan: AppInstallPlan
|
||||
if entry != null && AppHostInstallPlan(*collection_host, root, entry, *plan) && plan.count > 0 {
|
||||
unused CopyCString(id, collection_host.platform.presentation.download_id[:])
|
||||
collection_host.platform.presentation.download_request += 1
|
||||
return true
|
||||
}
|
||||
request: AppsRequest
|
||||
request.operation = APPS_OPEN
|
||||
if !CopyCString(id, request.id[:]) { return false }
|
||||
@@ -497,6 +670,12 @@ CollectionOpenGame :: (id: string) -> bool {
|
||||
return false
|
||||
}
|
||||
if !AppTreeDrain(*collection_host.tree) { Report("Arcade: the apps host stopped while starting "); Report(id); Report("\n"); return false }
|
||||
// Games that share code are verified in the background; wait for it.
|
||||
started := MonotonicMilliseconds()
|
||||
while CollectionPending(queued.request) && MonotonicMilliseconds() - started < 60000 {
|
||||
unused SleepMilliseconds(5)
|
||||
if !AppTreeDrain(*collection_host.tree) { Report("Arcade: the apps host stopped while starting "); Report(id); Report("\n"); return false }
|
||||
}
|
||||
for index: cast(s64)0..collection_host.tree.pending.count - 1 {
|
||||
reply := collection_host.tree.pending[index].reply
|
||||
if reply.request == queued.request && reply.status == APPS_REJECTED {
|
||||
@@ -516,18 +695,81 @@ CollectionOpenGame :: (id: string) -> bool {
|
||||
collection_typed: [1024]u8;
|
||||
collection_pasted: [16384]u8;
|
||||
|
||||
// The answer kept with the other game settings. Shovey Classic asked in its
|
||||
// first level before, and its answer counts until the covers ask.
|
||||
CollectionUpdates :: () -> s32 {
|
||||
if collection_updates >= 0 { return collection_updates }
|
||||
collection_updates = 2
|
||||
ids: [2]string = .["arcade.shovey-player", "arcade.shovey"]
|
||||
for id: ids {
|
||||
saved := CollectionRecordsFor(id)
|
||||
if saved == null { continue }
|
||||
AppFileFree(saved.text)
|
||||
saved.text = AppFileRead(*saved.files, "level-updates")
|
||||
if saved.text == "on" || saved.text == "off" {
|
||||
collection_updates = ifx saved.text == "on" then 1 else 0
|
||||
break
|
||||
}
|
||||
}
|
||||
return collection_updates
|
||||
}
|
||||
|
||||
CollectionUpdatesSet :: (on: bool) -> bool {
|
||||
saved := CollectionRecordsFor("arcade.shovey-player")
|
||||
if saved == null || !AppFileWrite(*saved.files, "level-updates", ifx on then "on" else "off") { return false }
|
||||
collection_updates = ifx on then 1 else 0
|
||||
return true
|
||||
}
|
||||
|
||||
// Asked once over the covers, before a game opens; nothing behind it takes
|
||||
// input until it is answered.
|
||||
CollectionUpdatesQuestion :: (session: Session, viewport: Rectangle) {
|
||||
question := "Download new levels when they come out?"
|
||||
Box(session, BoxProps.{.key = cast(u64)49300, .bounds = viewport, .fill = Color.{0, 0, 0, 160}})
|
||||
unused Button(session, ButtonProps.{.key = cast(u64)49301, .id = 49301, .label = question,
|
||||
.bounds = viewport, .invisible = true})
|
||||
width := ifx viewport.width - 24.0 < 480.0 then viewport.width - 24.0 else 480.0
|
||||
height: float32 = 200.0
|
||||
x := viewport.x + (viewport.width - width) / 2.0
|
||||
y := viewport.y + (viewport.height - height) / 2.0
|
||||
Box(session, BoxProps.{.key = cast(u64)49302, .bounds = Rectangle.{x, y, width, height},
|
||||
.fill = Color.{59, 64, 63, 255}, .border = Color.{93, 98, 97, 255}, .radius = 18.0})
|
||||
Text(session, TextProps.{.key = cast(u64)49303, .text = question, .font = 20, .wrap = TextWrap.TextWrapAuto,
|
||||
.bounds = Rectangle.{x + 16.0, y + 16.0, width - 32.0, 60.0}})
|
||||
Text(session, TextProps.{.key = cast(u64)49304, .text = "You can change this anytime in a game's Help.", .font = 14,
|
||||
.wrap = TextWrap.TextWrapAuto, .bounds = Rectangle.{x + 16.0, y + 80.0, width - 32.0, 44.0}})
|
||||
button_width := (width - 48.0 - 12.0) / 2.0
|
||||
if Button(session, ButtonProps.{.key = cast(u64)49305, .id = 49305, .label = "Not now",
|
||||
.bounds = Rectangle.{x + 24.0, y + 136.0, button_width, 44.0},
|
||||
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}) != 0 {
|
||||
unused CollectionUpdatesSet(false)
|
||||
}
|
||||
if Button(session, ButtonProps.{.key = cast(u64)49306, .id = 49306, .label = "Download",
|
||||
.bounds = Rectangle.{x + 36.0 + button_width, y + 136.0, button_width, 44.0},
|
||||
.tone = ButtonTone.ButtonToneAccent}) != 0 {
|
||||
unused CollectionUpdatesSet(true)
|
||||
}
|
||||
}
|
||||
|
||||
CollectionFrame :: (session: Session, viewport: Rectangle, key: s32, modifiers: s32) -> bool {
|
||||
collection_toolbar_visible = true
|
||||
defer { CollectionToolbar(session, viewport) }
|
||||
if entity_visible { return EntityFrame(session, viewport, key, modifiers) }
|
||||
runtime := AppHostActiveRuntime(*collection_host)
|
||||
if runtime == null { Report("Arcade: no app is running\n"); return false }
|
||||
opening := !runtime.node.collection && (!collection_loading.shown ||
|
||||
collection_loading.slot != collection_host.tree.active.slot ||
|
||||
collection_loading.generation != collection_host.tree.active.generation)
|
||||
if opening { key = 0 }
|
||||
nested := runtime.node.parent.generation != 0 && !runtime.node.collection
|
||||
// An app opened from its cover fills the screen with its own navigation.
|
||||
// Other apps get a bar with Back and their title; the library and that
|
||||
// bar keep Profile at the top right.
|
||||
covered := runtime.node.entry.cover.portrait[0] != 0
|
||||
collection_toolbar_visible = !covered
|
||||
// The covers ask about new levels once; the question takes every key.
|
||||
asking := runtime.node.collection && !collection_host.platform.presentation.cover_grid && CollectionUpdates() == 2
|
||||
if asking { key = 0 }
|
||||
top: s32 = ifx !covered && !runtime.node.collection && (entity_ready || nested) then 56 else 0
|
||||
now := cast(float64)MonotonicMilliseconds() / 1000.0
|
||||
runtime.app.session = session
|
||||
@@ -555,6 +797,7 @@ CollectionFrame :: (session: Session, viewport: Rectangle, key: s32, modifiers:
|
||||
.scale = 1.0, .font = 16, .now = now}
|
||||
}
|
||||
WidgetHostBegin(session, CollectionAssetAllowed, CollectionAssetPath)
|
||||
collection_pictures_missing = false
|
||||
drawn := AppHostRun(*collection_host, APP_FRAME)
|
||||
WidgetHostEnd()
|
||||
if !drawn {
|
||||
@@ -566,6 +809,33 @@ CollectionFrame :: (session: Session, viewport: Rectangle, key: s32, modifiers:
|
||||
unused AppHostBack(*collection_host)
|
||||
return true
|
||||
}
|
||||
if opening {
|
||||
pictures_ready := !collection_pictures_missing
|
||||
// Query every path, including those first requested by this frame's
|
||||
// TileMap. Android decodes them asynchronously on its render thread.
|
||||
for path: collection_frame_paths {
|
||||
if AssetWidth(path) < 0 { pictures_ready = false }
|
||||
}
|
||||
if CollectionNeedsCover(*collection_loading, collection_host.tree.active.slot,
|
||||
collection_host.tree.active.generation, pictures_ready) {
|
||||
collection_toolbar_visible = false
|
||||
Box(session, BoxProps.{.key = cast(u64)49400, .bounds = viewport,
|
||||
.fill = ColorFromPacked(ifx entity_shovey then ShoveyPalette().background else AppCoversPalette().background)})
|
||||
unused Button(session, ButtonProps.{.key = cast(u64)49401, .id = 49401,
|
||||
.bounds = viewport, .invisible = true})
|
||||
LoadingIndicator(session, LoadingIndicatorProps.{.key = cast(u64)49402,
|
||||
.bounds = viewport, .now = now, .scale = 1.5})
|
||||
return true
|
||||
}
|
||||
} else if runtime.node.collection {
|
||||
collection_loading = .{}
|
||||
}
|
||||
if asking {
|
||||
unused WidgetPaletteUse(session, ifx entity_shovey then ShoveyPalette() else AppCoversPalette())
|
||||
CollectionUpdatesQuestion(session, viewport)
|
||||
unused WidgetPaletteRestore(session)
|
||||
return true
|
||||
}
|
||||
if nested && !covered {
|
||||
title_bytes: Vec(u8)
|
||||
BuilderPrint(*title_bytes, "%", TextUntilNul(runtime.node.entry.title[:]))
|
||||
@@ -587,8 +857,8 @@ CollectionFrame :: (session: Session, viewport: Rectangle, key: s32, modifiers:
|
||||
|
||||
CollectionToolbar :: (session: Session, viewport: Rectangle) {
|
||||
if !entity_ready || !collection_toolbar_visible { return }
|
||||
if entity_shovey { unused WidgetPaletteUse(session, ShoveyPalette()) }
|
||||
defer { if entity_shovey { unused WidgetPaletteRestore(session) } }
|
||||
unused WidgetPaletteUse(session, ifx entity_shovey then ShoveyPalette() else AppCoversPalette())
|
||||
defer { unused WidgetPaletteRestore(session) }
|
||||
// The account's Dew beside the Profile: a drop and the number, 0 until an
|
||||
// account is connected; it opens the Profile too.
|
||||
dew := EntityDewBalanceText(collection_dew_text[:])
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// A newly opened game stays covered until two complete picture frames have
|
||||
// composed. Images can be requested after the first apparently ready frame.
|
||||
CollectionLoading :: struct {
|
||||
generation: s64
|
||||
slot: s64
|
||||
ready_frame: bool
|
||||
shown: bool
|
||||
}
|
||||
|
||||
CollectionNeedsCover :: (state: *CollectionLoading, slot: s64, generation: s64,
|
||||
pictures_ready: bool) -> bool {
|
||||
if state.slot != slot || state.generation != generation {
|
||||
state.* = CollectionLoading.{.slot = slot, .generation = generation}
|
||||
return true
|
||||
}
|
||||
if state.shown { return false }
|
||||
if !pictures_ready { state.ready_frame = false; return true }
|
||||
if !state.ready_frame { state.ready_frame = true; return true }
|
||||
state.shown = true
|
||||
return false
|
||||
}
|
||||
@@ -12,11 +12,15 @@
|
||||
#import "entity_host"
|
||||
#import "entity/model"
|
||||
#import "kryon/carousel"
|
||||
#import "apps/appearance"
|
||||
#import "kryon/widget_palette"
|
||||
|
||||
sdl :: #system_library "SDL2";
|
||||
SetTitle :: (window: *void, title: *u8) #foreign sdl "SDL_SetWindowTitle";
|
||||
|
||||
DrawStartup :: (session: Session, directory: string) -> bool {
|
||||
// First show small RGB/RGBA previews. The collection replaces them with its
|
||||
// original artwork when ready, using the same layout and coloured logo.
|
||||
DrawStartup :: (session: Session, directory: string, standalone: bool = true) -> bool {
|
||||
if !PollDesktop() || WindowTakeCloseRequestHost() { return false }
|
||||
BeginDesktopFrame()
|
||||
viewport := DesktopViewport()
|
||||
@@ -25,7 +29,15 @@ DrawStartup :: (session: Session, directory: string) -> bool {
|
||||
logo := Join(directory, "startup/shovey/logo.png")
|
||||
defer { EntityFree(art); EntityFree(logo) }
|
||||
if BeginFrame(session, cast(u64)1, viewport) != FrameStatus.FrameOk { return false }
|
||||
unused CarouselArtwork(session, viewport, cast(u64)48000, art, logo, "Shovey")
|
||||
if standalone {
|
||||
unused CarouselArtwork(session, viewport, cast(u64)48000, art, logo, "Shovey")
|
||||
} else {
|
||||
unused WidgetPaletteUse(session, AppCoversPalette())
|
||||
Box(session, BoxProps.{.key = cast(u64)48000, .bounds = viewport, .fill = Color.{17, 18, 35, 255}})
|
||||
Text(session, TextProps.{.key = cast(u64)48001, .text = "Arcade", .font = 32,
|
||||
.bounds = Rectangle.{20.0, 20.0, viewport.width - 40.0, 44.0}})
|
||||
unused WidgetPaletteRestore(session)
|
||||
}
|
||||
if EndFrame(session) != FrameStatus.FrameOk { return false }
|
||||
ok := EndDesktopFrame()
|
||||
TestDriverFrame(session)
|
||||
@@ -127,7 +139,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
|
||||
Report(": no private data directory\n")
|
||||
return 1
|
||||
}
|
||||
if !OpenDesktopSized(480, 820) || !WindowInterceptCloseHost(true) {
|
||||
if !OpenDesktopSized(ifx standalone then 480 else 1000, 820) || !WindowInterceptCloseHost(true) {
|
||||
CloseDesktop()
|
||||
return 1
|
||||
}
|
||||
@@ -138,7 +150,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
|
||||
session := SessionOpen()
|
||||
if !SessionValid(session) { return 1 }
|
||||
defer { SessionClose(session) }
|
||||
if standalone && !DrawStartup(session, directory) { return 0 }
|
||||
if !DrawStartup(session, directory, standalone) { return 0 }
|
||||
// Both open on their library's covers, or straight into a named game.
|
||||
opened := ifx standalone then CollectionOpenShovey(directory, data) else CollectionOpenFiles(directory, data)
|
||||
if opened && standalone && !DrawStartup(session, directory) { unused CollectionClose(); return 0 }
|
||||
|
||||
@@ -14,11 +14,15 @@
|
||||
#import "platform"
|
||||
#import "shovey/shovey_theme"
|
||||
#import "kryon/widget_palette"
|
||||
#import "apps/appearance"
|
||||
#import "kryon/drawing_props"
|
||||
#import "kryon/box_widget"
|
||||
#import "kryon/box_props"
|
||||
#import "kryon/text_widget"
|
||||
#import "kryon/text_props"
|
||||
#import "kryon/modal_props"
|
||||
#import "kryon/modal_frame_widget"
|
||||
#import "kryon/tree"
|
||||
|
||||
entity_bundle: string;
|
||||
entity_ready: bool;
|
||||
@@ -81,19 +85,23 @@ EntityBack :: () -> bool {
|
||||
}
|
||||
|
||||
EntityFrame :: (session: Session, viewport: Rectangle, key: s32, modifiers: s32) -> bool {
|
||||
if entity_shovey { unused WidgetPaletteUse(session, ShoveyPalette()) }
|
||||
defer { if entity_shovey { unused WidgetPaletteRestore(session) } }
|
||||
Box(session, BoxProps.{.key = cast(u64)49000, .bounds = viewport,
|
||||
unused WidgetPaletteUse(session, ifx entity_shovey then ShoveyPalette() else AppCoversPalette())
|
||||
defer { unused WidgetPaletteRestore(session) }
|
||||
Box(session, BoxProps.{.key = cast(u64)49010, .bounds = viewport,
|
||||
.fill = StyleTokenColorOr("canvas", Color.{239, 246, 244, 255})})
|
||||
bounds := Rectangle.{viewport.x, viewport.y + 56.0, viewport.width, viewport.height - 56.0}
|
||||
width := viewport.width - 32.0
|
||||
height := viewport.height - 32.0
|
||||
if width > 560.0 { width = 560.0 }
|
||||
if height > 720.0 { height = 720.0 }
|
||||
modal := ModalFrame(session, ModalFrameProps.{.key = cast(u64)49000, .id = 49000,
|
||||
.title = "Profile", .width = cast(s32)width, .height = cast(s32)height, .scale = 1.0,
|
||||
.has_right_action = true, .right_label = "Back"})
|
||||
if modal.dismissed || modal.right_clicked { unused EntityBack() }
|
||||
if !modal.opened { return true }
|
||||
input := TextFieldInputFor(key, modifiers, TypedTextTake(session, entity_typed[:]))
|
||||
if !EntityHostFrame(session, bounds, key, modifiers, input, entity_shovey) { return false }
|
||||
Text(session, TextProps.{.key = cast(u64)49002, .text = "Profile", .font = 20,
|
||||
.bounds = Rectangle.{viewport.x + 100.0, viewport.y + 12.0, viewport.width - 220.0, 36.0}})
|
||||
if Button(session, ButtonProps.{.key = cast(u64)49001, .id = 49001, .label = "Back",
|
||||
.bounds = Rectangle.{viewport.x + 8.0, viewport.y + 6.0, 76.0, 44.0}}) != 0 {
|
||||
unused EntityBack()
|
||||
}
|
||||
ok := EntityHostFrame(session, modal.layout.content, key, modifiers, input, true)
|
||||
unused End(session)
|
||||
if !ok { return false }
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// The game standard every Arcade game implements (standards/game-v1.json).
|
||||
// GAME_HOST_API is the newest host interface Arcade's players run; a game
|
||||
// that declares a newer one is refused. scripts/check-games.py fails while it
|
||||
// differs from the standard and the ledger.
|
||||
GAME_CONTRACT_VERSION :: 1
|
||||
GAME_HOST_API :: 41
|
||||
@@ -1,6 +1,7 @@
|
||||
// Runs the registered game bundles. The host owns files and input;
|
||||
// each game owns its rules and screens. Chess also runs in Inbe.
|
||||
#import "std/file"
|
||||
#import, file "game_contract.zi";
|
||||
#import "std/bundle_host"
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/date_time_linux"
|
||||
@@ -19,8 +20,6 @@
|
||||
|
||||
using HostValueKind;
|
||||
|
||||
GAME_CONTRACT_VERSION :: 1
|
||||
GAME_HOST_API :: 12
|
||||
|
||||
GameHost :: struct {
|
||||
app: HostedApp
|
||||
|
||||
@@ -48,6 +48,11 @@ DataDirectory :: () -> string {
|
||||
BuilderPrint(*result, "%", private)
|
||||
return BuilderFinish(result)
|
||||
}
|
||||
// The browser keeps saves and downloaded games in the page's persistent
|
||||
// storage, which Kryon mounts at /kryon-apps.
|
||||
#if #defined(PLATFORM_WEB) {
|
||||
return Join("/kryon-apps", "arcade")
|
||||
}
|
||||
exact := EnvironmentText("ARCADE_DATA")
|
||||
if exact != "" { return exact }
|
||||
#if #defined(_WIN32) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Classic, Island and Editor keep independent verified identities.
|
||||
// Classic and the Editor keep independent verified identities.
|
||||
#import "kryon/app_context"
|
||||
#import "kryon/app_protocol"
|
||||
|
||||
|
||||
@@ -10,8 +10,8 @@ SoundMuted :: () -> bool { return sound_muted }
|
||||
|
||||
SoundSetMuted :: (muted: bool) { sound_muted = muted }
|
||||
|
||||
#if #defined(ANDROID_BUILD) {
|
||||
// Android has no SDL audio; games stay silent there and run on.
|
||||
#if #defined(ANDROID_BUILD) || #defined(PLATFORM_WEB) {
|
||||
// Android and the browser have no SDL audio; games stay silent there and run on.
|
||||
SoundPlay :: (bytes: string) -> bool {
|
||||
unused bytes
|
||||
return false
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// Arcade in the browser: the same arcade.zx Inner Breeze downloads, with its
|
||||
// shared Apps library, the account Profile and each game downloaded from the
|
||||
// node when someone opens it. Saves stay in the page's persistent storage.
|
||||
// Given the released Shovey player instead, the shovey.zx and shovey.json of
|
||||
// the downloads, it is shovey.waozi.xyz and opens on Shovey's covers.
|
||||
using Canvas :: #import "kryon/Canvas";
|
||||
#import "kryon/bundle_storage_web"
|
||||
#import "kryon/app_files"
|
||||
#import "kryon/session"
|
||||
#import "kryon/geometry"
|
||||
#import "kryon/tree"
|
||||
#import "kryon/tree_input"
|
||||
#import "kryon/Frame"
|
||||
#import "kryon/ScrollDevice"
|
||||
#import "kryon/key_input"
|
||||
#import "kryon/TestDriver"
|
||||
#import "kryon/page_core"
|
||||
#import "std/file"
|
||||
#import "std/web"
|
||||
#import "std/byte_text_linux"
|
||||
#import "platform"
|
||||
#import "collection_host"
|
||||
#import "entity_host"
|
||||
|
||||
arcade_receipt: [4096]u8;
|
||||
|
||||
// The page passes the collection's build receipt (its digest and trusted
|
||||
// Apps controller) as Module.arcadeReceipt, beside the preloaded /app.zx.
|
||||
ArcadeReceipt :: () -> string {
|
||||
handle := WebAsObject(WebGet(WebGetObject(WebGlobal, WebName("Module")), WebName("arcadeReceipt")))
|
||||
if handle == 0 { return "" }
|
||||
length := WebCopyString(handle, arcade_receipt[:])
|
||||
if length <= 0 || length >= cast(s32)arcade_receipt.count { return "" }
|
||||
return TextFromBytes(arcade_receipt[:length])
|
||||
}
|
||||
|
||||
ArcadeFrame :: (session: Session) -> bool {
|
||||
BeginCanvasFrame()
|
||||
viewport := CanvasViewport()
|
||||
modifiers := CanvasModifiers()
|
||||
KeyboardModifiersSend(session, modifiers)
|
||||
key := CanvasPressedKey()
|
||||
if key == 256 && CollectionBack() { key = 0 }
|
||||
KeyboardSend(session, key)
|
||||
point := CanvasTypedCodepoint()
|
||||
while point != 0 { unused TypedCodepointSend(session, point); point = CanvasTypedCodepoint() }
|
||||
pointer := PollPointer()
|
||||
TreePointerUpdate(session, pointer)
|
||||
TreeSecondaryPointerUpdate(session, PollSecondaryPointer())
|
||||
wheel := CanvasWheelMove()
|
||||
PointerWheelSend(session, pointer.x, pointer.y, wheel)
|
||||
BeginScrollFrame(session, Vector2.{pointer.x, pointer.y}, pointer.pressed,
|
||||
pointer.down, pointer.released, wheel, PageNow() / 1000.0)
|
||||
if BeginFrame(session, cast(u64)1, viewport) != FrameStatus.FrameOk { return false }
|
||||
if !CollectionFrame(session, viewport, key, modifiers) {
|
||||
TreeCancel(session)
|
||||
return false
|
||||
}
|
||||
// Only damaged pixels are cleared and repainted; the rest of the page stays.
|
||||
if EndCanvasUiFrame(session) != FrameStatus.FrameOk { return false }
|
||||
TestDriverFrame(session)
|
||||
CanvasCursor(session)
|
||||
ok := EndCanvasFrame()
|
||||
CollectionCollect()
|
||||
return ok
|
||||
}
|
||||
|
||||
#program_export
|
||||
main :: () -> s32 {
|
||||
if !OpenCanvas() { return 1 }
|
||||
defer CloseCanvas()
|
||||
if !BundleStorageOpen() { return 1 }
|
||||
while !BundleStorageReady() && !BundleStorageFailed() { WebSleep(10) }
|
||||
if !BundleStorageReady() { return 1 }
|
||||
data := DataDirectory()
|
||||
// The page preloads Arcade's published collection; the Profile is embedded.
|
||||
bytes, found := ReadEntireFile("/app.zx")
|
||||
profile, profile_found := ReadEntireFile("/entity.zx")
|
||||
defer { AppFileFree(bytes) }
|
||||
receipt := ArcadeReceipt()
|
||||
// The page writes Arcade's own Apps controller beside the collection.
|
||||
controller, controller_found := ReadEntireFile("/apps.zx")
|
||||
if controller_found { collection_controller = controller } else { AppFileFree(controller) }
|
||||
if !found || !profile_found || receipt == "" { return 1 }
|
||||
// The page writes the library's pictures from this site: small copies
|
||||
// under /library, or else the exact art bundle under /packages.
|
||||
CollectionWebLibrary("/library", "/packages")
|
||||
shovey := CollectionShoveyReceipt(receipt)
|
||||
opened := ifx shovey then CollectionOpenShoveyBytes(bytes, receipt, data) else CollectionOpenBytes(bytes, receipt, data)
|
||||
if !opened { return 1 }
|
||||
if !EntityOpen(profile, data, shovey) { unused CollectionClose(); return 1 }
|
||||
session := SessionOpen()
|
||||
if !SessionValid(session) { unused CollectionClose(); return 1 }
|
||||
defer { SessionClose(session) }
|
||||
saved := PageNow()
|
||||
ok := true
|
||||
while ok && PollCanvas() {
|
||||
scope := WebScope()
|
||||
ok = ArcadeFrame(session)
|
||||
// main returning does not notify Emscripten's onExit unless its
|
||||
// runtime exits too. Tell the page explicitly, so a failed game can
|
||||
// never leave an apparently live library with no input loop.
|
||||
if !ok {
|
||||
WebSet(WebGetObject(WebGlobal, WebName("Module")), WebName("arcadeFailed"), WebBool(true))
|
||||
} else {
|
||||
WebSet(WebGetObject(WebGlobal, WebName("Module")), WebName("profileReady"), WebBool(true))
|
||||
}
|
||||
// Saves reach the browser's storage about once a second.
|
||||
if PageNow() - saved >= 1000.0 {
|
||||
unused BundleStorageSync(false)
|
||||
saved = PageNow()
|
||||
}
|
||||
WebEnd(scope)
|
||||
}
|
||||
unused CollectionClose()
|
||||
unused BundleStorageSync(false)
|
||||
return ifx ok then 0 else 1
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "kryon-node-app",
|
||||
"contract_version": 1,
|
||||
"module_api": 2,
|
||||
"host_api": 12,
|
||||
"host_api": 41,
|
||||
"identity": "Stable signed package ID; moving source must not rename installed games",
|
||||
"frames": {
|
||||
"matching": "Fields match by name",
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Check that the APK's collection opens Arcade's whole library offline.
|
||||
|
||||
The collection make android packs (build/android-assets) is opened by the
|
||||
desktop host from a private folder, as the Android host opens it from the
|
||||
APK's assets: no controller beside it and no reachable download origin, so
|
||||
every game and the art must come from the collection itself."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
LEVEL_UPDATES = 'Download new levels when they come out?'
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--binary', type=Path, required=True)
|
||||
parser.add_argument('--inbe-source', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
assert int(os.environ['DISPLAY'].split(':')[-1].split('.')[0]) >= 400
|
||||
assert os.environ['YUE_DESKTOP_RECOVERY'] == '0'
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
assets = root / 'build/android-assets'
|
||||
receipt = json.loads((assets / 'arcade.json').read_text())
|
||||
assert receipt['id'] == 'inbe.arcade' and receipt['games'] == 'packed' and 'art' not in receipt
|
||||
assert receipt['sha256'] == hashlib.sha256((assets / 'arcade.zx').read_bytes()).hexdigest()
|
||||
sys.path.insert(0, str(args.inbe_source / 'tests'))
|
||||
from ui_driver import UiDriver
|
||||
output = root / 'build/android-offline-ui-test'
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
driver = UiDriver(output / 'driver')
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='arcade-offline-') as temporary:
|
||||
install = Path(temporary) / 'app'
|
||||
install.mkdir()
|
||||
shutil.copy2(args.binary, install / 'arcade')
|
||||
for name in ('arcade.zx', 'arcade.json'):
|
||||
shutil.copyfile(assets / name, install / name)
|
||||
# The shared profile, which the APK also carries.
|
||||
shutil.copyfile(root / 'build/entity.zx', install / 'entity.zx')
|
||||
profile = Path(temporary) / 'profile'
|
||||
log_path = output / 'arcade.log'
|
||||
with log_path.open('w') as log:
|
||||
# Port 9 (discard) refuses connections: any download would fail.
|
||||
child = subprocess.Popen([str(install / 'arcade')], cwd=install,
|
||||
env=os.environ | driver.environment() |
|
||||
{'ARCADE_DATA': str(profile), 'ENTITY_DATA': str(profile / 'entity'),
|
||||
'LANG': 'en_US.UTF-8', 'ARCADE_PACKAGE_ORIGIN': 'http://127.0.0.1:9'},
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
driver.attach(child, log_path)
|
||||
try:
|
||||
for title in ('Shovey', 'Shovey Editor', 'Apfelwurm'):
|
||||
driver.wait(label=title, role='button', timeout=60)
|
||||
covers = [node for node in driver.find(role='image', visible=True)
|
||||
if node['width'] >= 100 and node['height'] >= 140]
|
||||
assert len(covers) >= 2, 'The packed library art must draw without a download'
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
driver.press(label='Shovey', role='button')
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
assert not driver.find(label='Download', role='button'), 'A packed game must not ask to download'
|
||||
assert not driver.find(label='Try again', role='button'), 'A packed game must not download'
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
if [node for node in driver.tree() if str(node.get('label', '')).startswith('Level 1 / ')]:
|
||||
break
|
||||
assert time.monotonic() < deadline, 'Shovey did not start from the packed collection'
|
||||
time.sleep(0.05)
|
||||
assert not list((profile / 'resources').rglob('*.zx')), 'Nothing may be downloaded'
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.terminate()
|
||||
child.wait(timeout=10)
|
||||
print('The Android collection opens every game and its art offline')
|
||||
@@ -1,4 +1,11 @@
|
||||
"""Resume one shared progress fixture on the USB Moto in an isolated APK."""
|
||||
"""Verify completion-only progress on the USB Moto in an isolated APK.
|
||||
|
||||
The default full case covers real swipe motion, device-local board persistence,
|
||||
read-only account progress across movement/restart, earned completion and logout
|
||||
isolation. Startup/account cases are diagnostics, not substitutes for the full
|
||||
case. Supply the exact approved campaign and an offline throwaway account folder;
|
||||
never supply owner keys. Existing verification-profile files are preserved.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
@@ -12,19 +19,45 @@ import time
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--apk', type=Path, required=True)
|
||||
parser.add_argument('--breeze', type=Path, required=True)
|
||||
parser.add_argument('--campaign', type=Path, required=True)
|
||||
parser.add_argument('--test-account', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path)
|
||||
parser.add_argument('--case', choices=('all', 'startup', 'account'), default='all')
|
||||
args = parser.parse_args()
|
||||
sys.path.insert(0, str(args.breeze.resolve() / 'tests'))
|
||||
import android_library_device as transport
|
||||
|
||||
LEVEL_UPDATES = 'Download new levels when they come out?'
|
||||
|
||||
def answer_cover_question(driver):
|
||||
"""Standalone Arcade and Shovey ask once on their covers whether games
|
||||
download new levels; tests keep the levels they ship with. The question
|
||||
shows in the covers' first frame."""
|
||||
driver.wait(label='Play', role='button', timeout=60)
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
transport.OUTPUT = root / 'backup/shared-progress-moto'
|
||||
transport.OUTPUT = args.output or root / 'backup/shared-progress-moto'
|
||||
transport.PACKAGE = 'xyz.waozi.shovey.verification'
|
||||
transport.ACTIVITY = transport.PACKAGE + '/xyz.waozi.arcade.ArcadeActivity'
|
||||
transport.TRANSFER = '/data/local/tmp/shovey-progress-test'
|
||||
transport.OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
class Phone(transport.Device):
|
||||
def owns_foreground(self):
|
||||
# Test-driver file input does not count as Android user activity.
|
||||
# Wake only the USB test device; keep its timeout setting intact.
|
||||
if time.monotonic() - getattr(self, '_last_wake', 0) > 10:
|
||||
self.shell('input', 'keyevent', 'KEYCODE_WAKEUP')
|
||||
self._last_wake = time.monotonic()
|
||||
super().owns_foreground()
|
||||
|
||||
def start(self):
|
||||
self.shell('input', 'keyevent', 'KEYCODE_WAKEUP')
|
||||
self.shell('wm', 'dismiss-keyguard', check=False)
|
||||
result = self.shell('am', 'start', '-W', '-n', transport.ACTIVITY)
|
||||
assert 'Error:' not in result, result
|
||||
self.owns_foreground()
|
||||
@@ -60,7 +93,7 @@ foreground = phone.foreground()
|
||||
assert ' xyz.waozi.shovey/' not in foreground, 'The regular Shovey app is foreground'
|
||||
phone.stop()
|
||||
phone.adb('install', '-r', '-t', apk, timeout=180)
|
||||
phone.state = dict(originating_chat='-1000000002', task='codex-projects-library-bookshelf',
|
||||
phone.state = dict(originating_chat='361338016', task='78530008ff5f508081150dec7522f477464f',
|
||||
foreground_before=foreground, apk_sha256=hashlib.sha256(apk.read_bytes()).hexdigest(),
|
||||
isolated=True, preserved=False)
|
||||
phone.save()
|
||||
@@ -70,34 +103,190 @@ try:
|
||||
phone.state['preserved'] = True
|
||||
phone.save()
|
||||
identifier = 'fd65a3d7ac3d5ceb2d4d96cc5224a740'
|
||||
records = 'files/entity/records/local'
|
||||
game = records + '/game-progress/' + identifier + '.json'
|
||||
phone.private('mkdir', '-p', 'files/kryon-test-driver', records + '/game-progress')
|
||||
phone.private('touch', 'files/.progress-test')
|
||||
stamp = int(time.time())
|
||||
phone.write('state', 'game-progress\nsince 0\n', records + '/state')
|
||||
phone.write('game-progress.index', f'{identifier} {stamp} {stamp * 1000} -- entity.game-progress.v1\n', records + '/game-progress.index')
|
||||
phone.write('campaign.json', json.dumps(dict(game='shovey.classic', unlocked=40,
|
||||
completed='1' * 39, state='', updated_at=stamp)), game)
|
||||
for attempt in ('first', 'restart'):
|
||||
local_campaign = None
|
||||
route = json.loads(args.campaign.read_text())['levels'][0]['solution']
|
||||
timings = []
|
||||
|
||||
def seed(unlocked, completed, account=False):
|
||||
phone.stop()
|
||||
assert phone.exists('files/.progress-test') or not phone.exists('files')
|
||||
if phone.exists('files'):
|
||||
phone.private('rm', '-rf', 'files')
|
||||
phone.private('mkdir', '-p', 'files/kryon-test-driver', 'files/entity')
|
||||
phone.private('touch', 'files/.progress-test')
|
||||
owner = 'local'
|
||||
if account:
|
||||
profile = json.loads((args.test_account / 'entity.json').read_text())
|
||||
owner = profile['owner_id']
|
||||
for name in ('account.key', 'entity.json'):
|
||||
phone.put_private(args.test_account / name, 'files/entity/' + name)
|
||||
records = 'files/entity/records/' + owner
|
||||
phone.private('mkdir', '-p', records + '/game-progress')
|
||||
stamp = int(time.time())
|
||||
phone.write('state', 'game-progress\nsince 0\n', records + '/state')
|
||||
phone.write('game-progress.index', f'{identifier} {stamp} {stamp * 1000} -- entity.game-progress.v1\n', records + '/game-progress.index')
|
||||
game = records + '/game-progress/' + identifier + '.json'
|
||||
phone.write('campaign.json', json.dumps(dict(game='shovey.classic', unlocked=unlocked,
|
||||
completed=completed, updated_at=stamp)), game)
|
||||
return game
|
||||
|
||||
def enter(level):
|
||||
phone.start()
|
||||
driver = transport.AndroidDriver(phone)
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button', timeout=60)
|
||||
deadline = time.monotonic() + 60
|
||||
while not driver.find(contains='Level 40 / ', role='text'):
|
||||
if driver.find(label='Download new levels when they come out?', role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
assert time.monotonic() < deadline, driver.text()
|
||||
driver.wait_idle(frames=5)
|
||||
record = json.loads(phone.private('cat', game))
|
||||
assert record['unlocked'] == 40 and record['completed'] == '1' * 39, record
|
||||
assert record['state'].startswith('M1'), record
|
||||
assert not phone.exists('files/games/arcade.shovey/records/campaign'), 'Duplicate wrapper campaign'
|
||||
assert len(phone.private('ls', records + '/game-progress').splitlines()) == 1
|
||||
phone.capture('level-40-' + attempt)
|
||||
driver.wait(contains=f'Level {level} / ', role='text', timeout=60)
|
||||
if driver.find(label='How do you want to move?', role='text'):
|
||||
driver.press(label='Swipe and tap', role='button')
|
||||
driver.wait(label='Restart', role='button')
|
||||
return driver
|
||||
|
||||
def campaign_path():
|
||||
paths = phone.private('find', 'files/games', '-name', 'local.campaign').splitlines()
|
||||
assert len(paths) == 1, paths
|
||||
return paths[0]
|
||||
|
||||
def player(driver):
|
||||
node = driver.wait(label='Shovey', role='image')
|
||||
return tuple(node[field] for field in ('x', 'y', 'width'))
|
||||
|
||||
def step(driver, direction):
|
||||
before = phone.private('cat', campaign_path())
|
||||
driver.key(('left', 'up', 'right', 'down')[int(direction)])
|
||||
# Input is handled by the real frame and commits its local campaign.
|
||||
deadline = time.monotonic() + 10
|
||||
while phone.private('cat', campaign_path()) == before:
|
||||
assert time.monotonic() < deadline, 'Direction did not update the device-local campaign'
|
||||
time.sleep(.05)
|
||||
|
||||
if args.case in ('all', 'startup'):
|
||||
game = seed(40, '1' * 39)
|
||||
driver = enter(40)
|
||||
provider_before = phone.private('cat', game)
|
||||
local_campaign = campaign_path()
|
||||
first_local = phone.private('cat', local_campaign)
|
||||
phone.capture('level-40-initial')
|
||||
# Android's actual input path, independently of the widget driver.
|
||||
before = player(driver)
|
||||
x, y, cell = before
|
||||
start = time.monotonic()
|
||||
phone.shell('input', 'swipe', round(x + cell / 2), round(y + cell / 2),
|
||||
round(x + cell / 2 - cell * 2), round(y + cell / 2), 150)
|
||||
deadline = time.monotonic() + 10
|
||||
while player(driver) == before:
|
||||
assert time.monotonic() < deadline, 'Real Android swipe did not move the player'
|
||||
timings.append(dict(input='Android swipe left', observed_ms=round((time.monotonic()-start)*1000, 1)))
|
||||
assert phone.private('cat', local_campaign) != first_local
|
||||
assert phone.private('cat', game) == provider_before, 'Movement modified the account progress record'
|
||||
saved = phone.private('cat', local_campaign)
|
||||
position = player(driver)
|
||||
phone.capture('level-40-moved')
|
||||
# The app's own frame metrics retain recent frame times; no global reset.
|
||||
layers = phone.shell('dumpsys', 'SurfaceFlinger', '--list')
|
||||
owned = [line for line in layers.splitlines() if transport.PACKAGE in line]
|
||||
for index, layer in enumerate(owned):
|
||||
(transport.OUTPUT / f'frame-latency-{index}.txt').write_text(phone.shell('dumpsys', 'SurfaceFlinger', '--latency', layer))
|
||||
phone.stop()
|
||||
phone.state['result'] = 'passed'
|
||||
driver = enter(40)
|
||||
assert phone.private('cat', local_campaign) == saved, 'Cold restart changed the saved board'
|
||||
assert player(driver) == position, 'Cold restart changed the player position'
|
||||
after_restart = phone.private('cat', game)
|
||||
(transport.OUTPUT / 'provider-before-restart.json').write_text(provider_before + '\n')
|
||||
(transport.OUTPUT / 'provider-after-restart.json').write_text(after_restart + '\n')
|
||||
assert after_restart == provider_before, 'Cold restart rewrote identical earned account progress'
|
||||
restarted = json.loads(after_restart)
|
||||
assert restarted['unlocked'] == 40 and restarted['completed'].startswith('1' * 39), restarted
|
||||
assert 'state' not in restarted
|
||||
phone.state['level40_restart_record'] = restarted
|
||||
phone.save()
|
||||
phone.capture('level-40-restarted')
|
||||
|
||||
print('Level40 real swipe/local save/cold restart passed', flush=True)
|
||||
if args.case == 'all':
|
||||
game = seed(1, '')
|
||||
driver = enter(1)
|
||||
provider_before = phone.private('cat', game)
|
||||
for direction in route[:-1]:
|
||||
step(driver, direction)
|
||||
assert phone.private('cat', game) == provider_before, 'Active puzzle wrote account progress'
|
||||
step(driver, route[-1])
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
record = json.loads(phone.private('cat', game))
|
||||
if record['unlocked'] == 2 and record['completed'].startswith('1'):
|
||||
break
|
||||
assert time.monotonic() < deadline, record
|
||||
assert 'state' not in record, 'Account record contains player state'
|
||||
phone.state['completion_record'] = record
|
||||
phone.save()
|
||||
phone.stop()
|
||||
driver = enter(2)
|
||||
assert json.loads(phone.private('cat', game))['unlocked'] == 2
|
||||
phone.capture('completion-restarted')
|
||||
print('Completion-only unlock and restart passed', flush=True)
|
||||
|
||||
continued = None
|
||||
if args.case in ('all', 'account'):
|
||||
# Start as an entirely artificial account, with a different local owner.
|
||||
# No owner key, app or profile is read or altered.
|
||||
game = seed(40, '', account=True)
|
||||
driver = enter(40)
|
||||
driver.press(label='Levels', role='button')
|
||||
driver.press(key=33001)
|
||||
driver.wait(contains='Level 1 / ', role='text')
|
||||
step(driver, route[0])
|
||||
before_logout = player(driver)
|
||||
(transport.OUTPUT / 'old-owner-active-campaign.txt').write_text(phone.private('cat', campaign_path()))
|
||||
old_account = phone.private('cat', game)
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Play', role='button')
|
||||
driver.press(label='Profile', role='button')
|
||||
if not driver.find(label='Log out', role='button', visible=True):
|
||||
driver.press(label='Account', role='button')
|
||||
driver.press(label='Log out', role='button')
|
||||
driver.press(key=807)
|
||||
driver.wait(label='Not signed in', role='text', timeout=30)
|
||||
for depth in range(8):
|
||||
if driver.find(label='Play', role='button', visible=True):
|
||||
break
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Play', role='button')
|
||||
driver.press(label='Play', role='button')
|
||||
driver.wait(contains='Level 1 / ', role='text')
|
||||
continued = player(driver) == before_logout
|
||||
assert not phone.exists('files/entity/account.key'), 'Logout did not finish'
|
||||
phone.state['account_switch_kept_active_board'] = continued
|
||||
local_owner_record = 'files/entity/records/local/game-progress/' + identifier + '.json'
|
||||
if phone.exists(local_owner_record):
|
||||
text = phone.private('cat', local_owner_record)
|
||||
(transport.OUTPUT / 'new-owner-before-completion.json').write_text(text + '\n')
|
||||
phone.state['new_owner_before_completion'] = json.loads(text)
|
||||
phone.save()
|
||||
for direction in (route[1:] if continued else route):
|
||||
step(driver, direction)
|
||||
# Owner isolation is independent of whether the host retained the
|
||||
# device-local board or reopened it. Neither path may publish old unlocks.
|
||||
deadline = time.monotonic() + 30
|
||||
while not (driver.find(contains='Level 1 / ', role='text') or
|
||||
driver.find(contains='Level 2 / ', role='text')):
|
||||
assert time.monotonic() < deadline, driver.text()
|
||||
phone.state['account_switch_final_header'] = [node['label'] for node in driver.find(key=20001)]
|
||||
assert phone.private('cat', game) == old_account, 'Signed-out account was modified'
|
||||
new_record = 'files/entity/records/local/game-progress/' + identifier + '.json'
|
||||
if phone.exists(new_record):
|
||||
record = json.loads(phone.private('cat', new_record))
|
||||
(transport.OUTPUT / 'new-owner-completion.json').write_text(json.dumps(record, indent=2) + '\n')
|
||||
phone.state['account_switch_new_record'] = record
|
||||
phone.state['account_switch_kept_active_board'] = continued
|
||||
phone.save()
|
||||
assert record['unlocked'] <= 2 and 'state' not in record, 'Old account progress leaked into new owner: ' + json.dumps(record)
|
||||
phone.state.update(result='passed', case=args.case,
|
||||
movement_saved_locally=args.case in ('all', 'startup'),
|
||||
provider_unchanged_during_moves=args.case in ('all', 'startup'),
|
||||
completion_only=args.case == 'all', cold_restart=args.case in ('all', 'startup'), account_switch=args.case in ('all', 'account'),
|
||||
account_switch_kept_active_board=continued, motion_observations=timings,
|
||||
timing_limitation='ADB-to-widget observation includes transport/poll latency; SurfaceFlinger samples saved separately, no before/after baseline')
|
||||
phone.save()
|
||||
print('Moto standalone Shovey resumes level 40 from one canonical provider record, keeps completion marks and survives a cold restart')
|
||||
print('USB Moto local test passed: ' + args.case)
|
||||
finally:
|
||||
phone.restore()
|
||||
@@ -1,5 +1,6 @@
|
||||
"""A local dependency override must never select the trusted controller's source."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -15,8 +16,17 @@ class ControllerSourceTests(unittest.TestCase):
|
||||
def test_local_overrides_do_not_reach_locked_resolution(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'ziran.toml').write_text('committed manifest')
|
||||
(root / 'ziran.lock').write_text('committed lock')
|
||||
manifest = ('[package]\nname = "Arcade"\n'
|
||||
'[toolchain]\ngit = "https://github.com/ziranlang/ziran.git"\nref = "master"\n'
|
||||
'[dependencies.apps]\ngit = "https://github.com/waozixyz/apps.git"\nref = "master"\n'
|
||||
'[dependencies.wurm]\ngit = "https://github.com/waozixyz/wurm.git"\nref = "master"\n')
|
||||
(root / 'ziran.toml').write_text(manifest)
|
||||
lock = dict(root=dict(name='Arcade', dependencies=dict(apps='launcher', wurm='game')),
|
||||
toolchain=dict(commit='pinned-compiler'), packages=[
|
||||
dict(id='launcher', commit='pinned-launcher', dependencies=dict(kryon='ui')),
|
||||
dict(id='ui', commit='pinned-ui', dependencies={}),
|
||||
dict(id='game', commit='unpublished-game', dependencies={})])
|
||||
(root / 'ziran.lock').write_text(json.dumps(lock))
|
||||
(root / 'ziran.local.toml').write_text('unreviewed local dependency')
|
||||
package = root / 'cached-apps'
|
||||
output = root / 'output'
|
||||
@@ -25,8 +35,11 @@ class ControllerSourceTests(unittest.TestCase):
|
||||
def resolve(command, *, cwd, text):
|
||||
self.assertEqual(command, ['ziran', 'pkg', 'path', 'apps', '--locked'])
|
||||
self.assertTrue(text)
|
||||
self.assertEqual((cwd / 'ziran.toml').read_text(), 'committed manifest')
|
||||
self.assertEqual((cwd / 'ziran.lock').read_text(), 'committed lock')
|
||||
self.assertNotIn('dependencies.wurm', (cwd / 'ziran.toml').read_text())
|
||||
selected = json.loads((cwd / 'ziran.lock').read_text())
|
||||
self.assertEqual(selected['root']['dependencies'], {'apps': 'launcher'})
|
||||
self.assertEqual(selected['packages'], lock['packages'][:2])
|
||||
self.assertEqual(selected['toolchain'], lock['toolchain'])
|
||||
self.assertEqual({p.name for p in cwd.iterdir()}, {'ziran.toml', 'ziran.lock'})
|
||||
contexts.append(cwd)
|
||||
return str(package) + '\n'
|
||||
@@ -38,6 +51,8 @@ class ControllerSourceTests(unittest.TestCase):
|
||||
[builder.sys.executable, str(package / 'scripts/build-ui.py'),
|
||||
'--output', str(output)], cwd=root, check=True)
|
||||
self.assertFalse(contexts[0].exists())
|
||||
self.assertEqual((root / 'ziran.toml').read_text(), manifest)
|
||||
self.assertEqual(json.loads((root / 'ziran.lock').read_text()), lock)
|
||||
self.assertEqual((root / 'ziran.local.toml').read_text(), 'unreviewed local dependency')
|
||||
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@ inbe = Path(os.environ['INBE_SOURCE']) if 'INBE_SOURCE' in os.environ else Path(
|
||||
catalog = json.loads((ROOT / "build/catalog.json").read_text())["games"]
|
||||
chess = next(game for game in catalog if game["name"] == "chess")
|
||||
assert chess["id"] == "inbe.chess"
|
||||
choano = next(game for game in catalog if game["name"] == "choano")
|
||||
assert choano["id"] == "xyz.waozi.choano"
|
||||
assert choano["kind"] == "game"
|
||||
assert choano["entry"] == "portable:Main"
|
||||
assert choano["package"] == "choano"
|
||||
# Inbe releases before its node apps have no node_apps ledger at all.
|
||||
assert "chess" not in json.loads((inbe / "apps/versions.json").read_text()).get("node_apps", {})
|
||||
assert set(chess["harnesses"]) == {"arcade", "inbe"}
|
||||
@@ -20,13 +25,15 @@ assert chess["kind"] == "game"
|
||||
assert (ROOT / "apps/chess/engine.zi").is_file(), "Arcade must own the game"
|
||||
assert not (inbe / "apps/chess").exists(), "Inbe must consume Chess, not own another copy"
|
||||
assert chess["contract_version"] == 1 and chess["module_api"] == 2
|
||||
assert chess["host_api"] == 12 and chess["save_schema"] == 1
|
||||
assert chess["host_api"] == 41 and chess["save_schema"] == 1
|
||||
assert (ROOT / chess["preview"]).is_file()
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if key not in {"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS"}}
|
||||
listed = subprocess.run([str(ROOT / "build/arcade"), "--list"], env=env, capture_output=True, timeout=10)
|
||||
assert listed.returncode == 0 and b"inbe.chess" not in listed.stderr + listed.stdout
|
||||
assert b"arcade.shovey\n" in listed.stderr + listed.stdout
|
||||
listed_output = listed.stderr + listed.stdout
|
||||
assert listed.returncode == 0 and b"inbe.chess" not in listed_output
|
||||
assert b"arcade.shovey\n" in listed_output
|
||||
assert b"xyz.waozi.choano\n" in listed_output
|
||||
unknown = subprocess.run([str(ROOT / "build/arcade"), "--app", "unknown"],
|
||||
env=env, capture_output=True, timeout=10)
|
||||
assert unknown.returncode == 1 and b"unknown game" in unknown.stderr
|
||||
@@ -34,13 +41,19 @@ original = (ROOT / 'build/games/chess.zx').read_bytes()
|
||||
container = (ROOT / 'build/arcade.zx').read_bytes()
|
||||
metadata = json.loads((ROOT / 'build/arcade.json').read_text())
|
||||
assert original not in container, 'Disabled Chess must not remain in the published collection'
|
||||
assert {child['id'] for child in metadata['children']} == {'arcade.shovey', 'arcade.shovey-editor'}
|
||||
assert {child['id'] for child in metadata['children']} == {
|
||||
'arcade.shovey', 'arcade.shovey-editor', 'xyz.waozi.choano',
|
||||
'xyz.waozi.wurm', 'xyz.waozi.wurm-editor'
|
||||
}
|
||||
choano_child = next(child for child in metadata['children'] if child['id'] == 'xyz.waozi.choano')
|
||||
assert choano_child['expected_id'] == 'choano'
|
||||
assert choano_child['bundle'] == 'assets/arcade/games/choano.zx'
|
||||
for child in metadata['children']:
|
||||
name = child['expected_id']
|
||||
exact = (ROOT / f'build/games/{name}.zx').read_bytes()
|
||||
assert container.count(exact) == 1, 'A game must be packed once without a nested chooser'
|
||||
assert exact not in container, 'Arcade must carry no prepackaged game bytes'
|
||||
assert hashlib.sha256(exact).hexdigest() == child['sha256']
|
||||
assert child['cover']['portrait'] and child['cover']['landscape'] and child['cover']['logo']
|
||||
assert child['cover']['portrait'] and child['cover']['landscape']
|
||||
refused = subprocess.run([str(ROOT / 'build/arcade'), '--app', 'chess'], env=env, capture_output=True, timeout=10)
|
||||
assert refused.returncode == 1 and b'unknown game' in refused.stderr
|
||||
print('Game identities, direct collection leaves, full cover resources and disabled Chess passed')
|
||||
@@ -0,0 +1,21 @@
|
||||
#import, file "../src/collection_loading.zi";
|
||||
|
||||
#program_export
|
||||
Check :: () -> s32 {
|
||||
state: CollectionLoading
|
||||
if !CollectionNeedsCover(*state, 1, 1, true) { return 1 }
|
||||
if !CollectionNeedsCover(*state, 1, 1, true) { return 2 }
|
||||
// A later request invalidates the apparently ready frame.
|
||||
if !CollectionNeedsCover(*state, 1, 1, false) { return 3 }
|
||||
if !CollectionNeedsCover(*state, 1, 1, false) { return 4 }
|
||||
if !CollectionNeedsCover(*state, 1, 1, true) { return 5 }
|
||||
if CollectionNeedsCover(*state, 1, 1, true) { return 6 }
|
||||
// Gameplay never returns to its opening cover for an animation sprite.
|
||||
if CollectionNeedsCover(*state, 1, 1, false) { return 7 }
|
||||
// A new game or a reopened slot gets its own loading stage.
|
||||
if !CollectionNeedsCover(*state, 2, 1, true) { return 8 }
|
||||
if !CollectionNeedsCover(*state, 2, 1, true) { return 9 }
|
||||
if CollectionNeedsCover(*state, 2, 1, true) { return 10 }
|
||||
if !CollectionNeedsCover(*state, 2, 2, true) { return 11 }
|
||||
return 42
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$root"
|
||||
mkdir -p build/collection-loading-test
|
||||
./scripts/ziran.sh bundle --project --root "$root" \
|
||||
--entry collection_loading_behavior:Check \
|
||||
-o build/collection-loading-test/test.zx tests/collection_loading_behavior.zi
|
||||
test "$(./scripts/ziran.sh run build/collection-loading-test/test.zx)" = 42
|
||||
echo 'Local collection loading test: late image requests, consecutive ready frames and navigation'
|
||||
@@ -0,0 +1,40 @@
|
||||
#import, file "../src/collection_host.zi";
|
||||
#import "entity/publications"
|
||||
#import "entity/publications_read"
|
||||
#import "std/bundle_host"
|
||||
#import "hosted_values"
|
||||
#import "std/byte_text_linux"
|
||||
|
||||
using HostValueKind;
|
||||
|
||||
CopyText :: (text: string, bytes: []u8) -> bool {
|
||||
if text.count >= bytes.count { return false }
|
||||
for byte, at: text { bytes[at] = byte }
|
||||
bytes[text.count] = 0
|
||||
return true
|
||||
}
|
||||
|
||||
TextValue :: (text: string) -> HostValue {
|
||||
return HostValue.{.kind = cast(s32)HostString, .type_name = HostTextData("string"),
|
||||
.data = HostTextData(text), .length = cast(usize)text.count}
|
||||
}
|
||||
|
||||
BorrowedText :: (value: HostValue) -> string {
|
||||
return TextFromBytes(BytesFromPointer(value.data, cast(u64)value.length))
|
||||
}
|
||||
|
||||
#program_export
|
||||
Check :: () -> s32 {
|
||||
if !CollectionAllows(null, null, PUBLICATIONS_SERVICE) { return 1 }
|
||||
if !CollectionAllows(null, null, PUBLICATIONS_READ_SERVICE) { return 2 }
|
||||
function: [32]u8
|
||||
if !CopyText("AppServiceHost", function[:]) { return 3 }
|
||||
arguments: [2]HostValue
|
||||
arguments[0] = TextValue(PUBLICATIONS_SERVICE)
|
||||
arguments[1] = TextValue("{\"operation\":\"fetch\",\"id\":\"fixture\"}")
|
||||
result: HostValue
|
||||
if CollectionCall(null, null, null, *function[0], *arguments[0], 2, *result) != 1 { return 4 }
|
||||
if result.kind != cast(s32)HostString { return 5 }
|
||||
if BorrowedText(result) != "{\"status\":\"rejected\",\"error\":\"signed-out\"}" { return 6 }
|
||||
return 42
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Check that Arcade routes writable publications through Entity's account gate."""
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WORK = ROOT / "build/collection-publications-host-test"
|
||||
ENVIRONMENT = {
|
||||
key: value for key, value in os.environ.items()
|
||||
if key not in {"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS"}
|
||||
}
|
||||
|
||||
|
||||
def run(program, *arguments):
|
||||
return subprocess.run([program, *arguments], cwd=ROOT, check=True,
|
||||
env=ENVIRONMENT, text=True)
|
||||
|
||||
|
||||
def main():
|
||||
generated = WORK / "c"
|
||||
binary = WORK / "test"
|
||||
for path in (binary, binary.with_suffix(".new")):
|
||||
if path.is_dir():
|
||||
shutil.rmtree(path)
|
||||
elif path.exists():
|
||||
path.unlink()
|
||||
if generated.exists():
|
||||
shutil.rmtree(generated)
|
||||
generated.mkdir(parents=True)
|
||||
ziran = str(ROOT / "scripts/ziran.sh")
|
||||
lock = [] if (ROOT / "ziran.local.toml").exists() else ["--locked"]
|
||||
run(ziran, "build", "--project", *lock, "--target=c", "--no-main",
|
||||
"--define", "PLATFORM_DESKTOP", "--entry",
|
||||
"collection_publications_host_behavior:Check", "-o", str(generated),
|
||||
"tests/collection_publications_host_behavior.zi")
|
||||
main_c = generated / "main.c"
|
||||
main_c.write_text('#include "collection_publications_host_behavior.h"\n'
|
||||
'int main(void) { return Check(); }\n')
|
||||
toolchain = Path(subprocess.check_output(
|
||||
[ziran, "pkg", "path", "ziran", *lock], cwd=ROOT, text=True,
|
||||
env=ENVIRONMENT).strip())
|
||||
runtime = ROOT / "build/ziran/libziran.a"
|
||||
if not runtime.exists():
|
||||
run("make", "-j1", str(runtime))
|
||||
|
||||
def package(name):
|
||||
return Path(subprocess.check_output(
|
||||
[ziran, "pkg", "path", name, *lock], cwd=ROOT, text=True,
|
||||
env=ENVIRONMENT).strip())
|
||||
|
||||
oqs_source = package("liboqs")
|
||||
oqs = WORK / ("oqs-" + oqs_source.name)
|
||||
oqs.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(oqs.with_name(oqs.name + ".lock"), "w") as exclusive:
|
||||
fcntl.flock(exclusive, fcntl.LOCK_EX)
|
||||
run("cmake", "-S", str(oqs_source), "-B", str(oqs),
|
||||
"-DCMAKE_BUILD_TYPE=MinSizeRel", "-DBUILD_SHARED_LIBS=OFF",
|
||||
"-DOQS_BUILD_ONLY_LIB=ON", "-DOQS_USE_OPENSSL=OFF",
|
||||
"-DOQS_DIST_BUILD=OFF", "-DOQS_OPT_TARGET=generic",
|
||||
"-DOQS_MINIMAL_BUILD=SIG_ml_dsa_44")
|
||||
run("cmake", "--build", str(oqs), "--target", "oqs", "--", "-j1")
|
||||
libraries = subprocess.check_output(
|
||||
["pkg-config", "--libs", "sdl2", "cairo", "freetype2", "fontconfig",
|
||||
"pangocairo", "gtk+-3.0"], text=True, env=ENVIRONMENT).split()
|
||||
monocypher = package("monocypher")
|
||||
includes = [item for path in generated.rglob("*") if path.is_dir()
|
||||
for item in ("-iquote", str(path))]
|
||||
temporary = binary.with_suffix(".new")
|
||||
run(os.environ.get("CC", "cc"), "-std=c11", "-O2", "-ffunction-sections",
|
||||
"-fdata-sections", "-I" + str(toolchain / "include"), "-iquote",
|
||||
str(generated), *includes, *map(str, generated.rglob("*.c")),
|
||||
str(ROOT / "build/ziran/libziran.a"), "-I" + str(monocypher / "src"),
|
||||
str(monocypher / "src/monocypher.c"),
|
||||
str(monocypher / "src/optional/monocypher-ed25519.c"),
|
||||
str(oqs / "lib/liboqs.a"), "-Wl,--gc-sections", *libraries,
|
||||
"-lX11", "-l:libcurl.so.4", "-lz", "-lm", "-lpthread", "-o", str(temporary))
|
||||
temporary.replace(binary)
|
||||
result = subprocess.run([binary], cwd=ROOT, env=ENVIRONMENT |
|
||||
{"SDL_AUDIODRIVER": "dummy"})
|
||||
if result.returncode != 42:
|
||||
raise SystemExit(
|
||||
f"collection publications host check returned {result.returncode}")
|
||||
print("Arcade publications host: writable service dispatches through Entity's account gate")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Exercise packaging from the actual registered game builds, preserving bytes."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
@@ -8,12 +9,17 @@ import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
import sys
|
||||
import tarfile
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
spec = importlib.util.spec_from_file_location("build_collection", ROOT / "scripts/build-collection.py")
|
||||
builder = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(builder)
|
||||
art_spec = importlib.util.spec_from_file_location("library_art", ROOT / "scripts/library-art.py")
|
||||
artist = importlib.util.module_from_spec(art_spec)
|
||||
art_spec.loader.exec_module(artist)
|
||||
|
||||
|
||||
class CollectionTests(unittest.TestCase):
|
||||
@@ -37,6 +43,7 @@ class CollectionTests(unittest.TestCase):
|
||||
shutil.copytree(ROOT / "build/games", self.root / "build/games")
|
||||
(self.root / "assets/arcade").mkdir(parents=True)
|
||||
shutil.copyfile(ROOT / "assets/arcade/sidebar.shape", self.root / "assets/arcade/sidebar.shape")
|
||||
shutil.copytree(ROOT / "assets/arcade/library", self.root / "assets/arcade/library")
|
||||
# Only a native VM identity gate can trust a controller. This fixture
|
||||
# tests packing and its exact-content requirement, not that handshake.
|
||||
self.controller = self.root / "controller.zx"
|
||||
@@ -47,31 +54,220 @@ class CollectionTests(unittest.TestCase):
|
||||
def stage(self):
|
||||
return builder.stage(self.root, self.controller, self.controller_digest, self.output)[0]
|
||||
|
||||
def assert_children_match_declarations(self, catalog, packages, payload_root):
|
||||
declarations = builder.declared_packages(self.root)
|
||||
ledger = json.loads((self.root / "apps/versions.json").read_text())["node_apps"]
|
||||
expected_children = []
|
||||
for app in (app for package in declarations for app in package["apps"] if app["enabled"]):
|
||||
descriptor = app["descriptor"]
|
||||
cover = app["cover"] or {}
|
||||
expected_children.append((
|
||||
descriptor["id"], descriptor["title"], descriptor["name"],
|
||||
ledger[descriptor["name"]]["version"], cover.get("caption", ""),
|
||||
cover.get("action"), tuple(app["requires"]), app["shared_code"],
|
||||
))
|
||||
self.assertEqual([(
|
||||
child["id"], child["title"], child["expected_id"], child["version"],
|
||||
child.get("cover", {}).get("caption", ""), child.get("cover", {}).get("action"),
|
||||
tuple(child.get("dependencies", [])), child.get("shared_code", False),
|
||||
) for child in catalog["children"]], expected_children)
|
||||
self.assertEqual([(p["name"], p["id"], p["children"]) for p in packages],
|
||||
[(package["name"], package["id"],
|
||||
[app["descriptor"]["id"] for app in package["apps"] if app["enabled"]])
|
||||
for package in declarations[1:]])
|
||||
library = payload_root / "assets/arcade/library"
|
||||
for child in catalog["children"]:
|
||||
name = child["expected_id"]
|
||||
source = payload_root / f"build/games/{name}.zx"
|
||||
packed = self.output / child["bundle"]
|
||||
self.assertEqual(packed.read_bytes(), source.read_bytes())
|
||||
self.assertEqual(builder.digest(packed), child["sha256"])
|
||||
self.assertEqual(child["bytes"], source.stat().st_size)
|
||||
self.assertEqual(child["protocol"], "node/2")
|
||||
expected_preview = next(library.glob(f"{name}-preview.*"))
|
||||
self.assertEqual(child["preview"], child["icon"])
|
||||
self.assertEqual(child["preview"], f"assets/arcade/previews/{name}{expected_preview.suffix}")
|
||||
self.assertEqual((self.output / child["preview"]).read_bytes(), expected_preview.read_bytes())
|
||||
for key in ("portrait", "landscape", "logo"):
|
||||
if key not in child.get("cover", {}):
|
||||
continue
|
||||
expected_cover = next(library.glob(f"{name}-{key}.*"))
|
||||
self.assertEqual(child["cover"][key],
|
||||
f"assets/arcade/covers/{name}-{key}{expected_cover.suffix}")
|
||||
self.assertEqual((self.output / child["cover"][key]).read_bytes(),
|
||||
expected_cover.read_bytes())
|
||||
|
||||
def add_library_copy(self, name, key, data):
|
||||
library = self.root / "assets/arcade/library"
|
||||
sources = json.loads((library / "sources.json").read_text())
|
||||
contents, suffix = artist.small_copy(data, key)
|
||||
copy = library / f"{name}-{key}{suffix}"
|
||||
copy.write_bytes(contents)
|
||||
sources[f"{name}-{key}"] = {"source_sha256": hashlib.sha256(data).hexdigest()}
|
||||
(library / "sources.json").write_text(json.dumps(sources))
|
||||
|
||||
def stage_four_leaf_wurm_fixture(self):
|
||||
source = self.root / "fixture-packages/wurm"
|
||||
(source / "editor").mkdir(parents=True)
|
||||
(source / "assets").mkdir()
|
||||
|
||||
def image(color, path):
|
||||
picture = Image.new("RGB", (640, 480), color)
|
||||
picture.save(path)
|
||||
return path.read_bytes()
|
||||
|
||||
(source / "catalog.json").write_text(json.dumps({
|
||||
"id": "xyz.waozi.wurm", "name": "wurm", "title": "Apfelwurm",
|
||||
"kind": "game", "contract_version": 1, "module_api": 2, "host_api": 41,
|
||||
"harnesses": ["arcade"], "preview": "assets/wurm-preview.png",
|
||||
}))
|
||||
(source / "editor/catalog.json").write_text(json.dumps({
|
||||
"id": "xyz.waozi.wurm-editor", "name": "wurm-editor", "title": "Apfelwurm Editor",
|
||||
"kind": "game", "contract_version": 1, "module_api": 2, "host_api": 41,
|
||||
"harnesses": ["arcade"], "preview": "assets/wurm-editor-preview.png",
|
||||
}))
|
||||
images = {
|
||||
"wurm-preview": image((255, 0, 0), source / "assets/wurm-preview.png"),
|
||||
"wurm-portrait": image((0, 255, 0), source / "assets/wurm-portrait.png"),
|
||||
"wurm-editor-preview": image((0, 0, 255), source / "assets/wurm-editor-preview.png"),
|
||||
"wurm-editor-portrait": image((255, 255, 0), source / "assets/wurm-editor-portrait.png"),
|
||||
}
|
||||
(source / "apps.json").write_text(json.dumps({
|
||||
"id": "xyz.waozi.wurm-player", "title": "Apfelwurm", "apps": [
|
||||
{"manifest": "catalog.json", "cover": {
|
||||
"portrait": "assets/wurm-portrait.png", "caption": "Classic", "action": "play"}},
|
||||
{"manifest": "editor/catalog.json",
|
||||
"requires": ["xyz.waozi.wurm"], "cover": {
|
||||
"portrait": "assets/wurm-editor-portrait.png", "caption": "Editor", "action": "open"}},
|
||||
],
|
||||
}))
|
||||
games = self.root / "build/games"
|
||||
for name, prefix in (("wurm", b"synthetic wurm payload\n"),
|
||||
("wurm-editor", b"synthetic wurm editor payload\n")):
|
||||
(games / f"{name}.zx").write_bytes(prefix + name.encode())
|
||||
preview_name = f"{name}-preview.png"
|
||||
(games / preview_name).write_bytes(images[f"{name}-preview"])
|
||||
(games / "wurm-editor-resources.json").write_text(json.dumps({
|
||||
"dependencies": ["xyz.waozi.wurm"],
|
||||
"resources": [{"dependency": "xyz.waozi.wurm", "path": "assets/wurm/classic/",
|
||||
"source": "assets/wurm-preview.png"}],
|
||||
}))
|
||||
for name, key in (("wurm", "preview"), ("wurm", "portrait"),
|
||||
("wurm-editor", "preview"), ("wurm-editor", "portrait")):
|
||||
self.add_library_copy(name, key, images[f"{name}-{key}"])
|
||||
ledger_path = self.root / "apps/versions.json"
|
||||
ledger = json.loads(ledger_path.read_text())
|
||||
ledger["node_apps"]["wurm-editor"] = {
|
||||
"id": "xyz.waozi.wurm-editor", "title": "Apfelwurm Editor", "version": "0.1.0",
|
||||
"sequence": 1, "host_api": 41,
|
||||
}
|
||||
ledger_path.write_text(json.dumps(ledger))
|
||||
resolver = self.root / "scripts/ziran.sh"
|
||||
resolver.write_text(
|
||||
f'#!/bin/sh\n'
|
||||
f'if [ "$1" = pkg ] && [ "$2" = path ] && [ "$3" = wurm ]; then\n'
|
||||
f' printf \'%s\\n\' {shlex.quote(str(source))}\n'
|
||||
f' exit 0\n'
|
||||
f'fi\n'
|
||||
f'cd {shlex.quote(str(ROOT))} && exec ./scripts/ziran.sh "$@"\n'
|
||||
)
|
||||
|
||||
def test_unchanged_games_keep_canonical_identity_and_version(self):
|
||||
catalog, packages = builder.stage(self.root, self.controller, self.controller_digest, self.output)
|
||||
self.assertEqual(catalog["id"], "inbe.arcade")
|
||||
# Inbe draws the launcher icon from the collection's own assets.
|
||||
self.assertEqual((self.output / "assets/arcade/sidebar.shape").read_bytes(),
|
||||
(ROOT / "assets/arcade/sidebar.shape").read_bytes())
|
||||
# The ledger also versions Arcade itself, which is not one of its games.
|
||||
ledger = json.loads((ROOT / "apps/versions.json").read_text())["node_apps"]
|
||||
self.assertEqual({c["id"] for c in catalog["children"]},
|
||||
{"arcade.shovey", "arcade.shovey-editor"})
|
||||
# Each leaf keeps the cover its own package declares.
|
||||
self.assertEqual([c["cover"]["caption"] for c in catalog["children"]], ["Classic", "Editor"])
|
||||
self.assertEqual([(p["name"], p["id"], p["children"]) for p in packages],
|
||||
[("shovey", "arcade.shovey-player", ["arcade.shovey", "arcade.shovey-editor"])])
|
||||
for child in catalog["children"]:
|
||||
name = child["expected_id"]
|
||||
packed = self.output / child["bundle"]
|
||||
self.assertEqual(packed.read_bytes(), (ROOT / f"build/games/{name}.zx").read_bytes())
|
||||
self.assertEqual(builder.digest(packed), child["sha256"])
|
||||
self.assertEqual(child["version"], ledger[name]["version"])
|
||||
self.assertEqual(child["protocol"], "node/2")
|
||||
self.assertEqual((self.output / child["preview"]).read_bytes(),
|
||||
(ROOT / f"build/games/{name}-preview.png").read_bytes())
|
||||
# Expected identities and versions come from each package's declarations.
|
||||
self.assert_children_match_declarations(catalog, packages, ROOT)
|
||||
self.assertEqual((self.output / catalog["harness"]).read_bytes(), self.controller.read_bytes())
|
||||
|
||||
pinned_ledger = json.loads((ROOT / "apps/versions.json").read_text())["node_apps"]
|
||||
wurm_version = pinned_ledger["wurm"]["version"]
|
||||
self.stage_four_leaf_wurm_fixture()
|
||||
catalog, packages = builder.stage(self.root, self.controller, self.controller_digest, self.output)
|
||||
self.assert_children_match_declarations(catalog, packages, self.root)
|
||||
self.assertEqual([child["id"] for child in catalog["children"]],
|
||||
["arcade.shovey", "arcade.shovey-editor",
|
||||
"xyz.waozi.wurm", "xyz.waozi.wurm-editor", "xyz.waozi.choano"])
|
||||
wurm_package = next(package for package in packages if package["name"] == "wurm")
|
||||
self.assertEqual(wurm_package["children"], ["xyz.waozi.wurm", "xyz.waozi.wurm-editor"])
|
||||
children = {child["id"]: child for child in catalog["children"]}
|
||||
self.assertEqual(children["xyz.waozi.choano"]["title"], "Choano")
|
||||
self.assertEqual(children["xyz.waozi.choano"]["version"], "0.1.2")
|
||||
self.assertEqual(children["xyz.waozi.choano"]["expected_id"], "choano")
|
||||
self.assertEqual(children["xyz.waozi.wurm"]["version"], wurm_version)
|
||||
self.assertEqual(children["xyz.waozi.wurm-editor"]["version"], "0.1.0")
|
||||
self.assertEqual(children["xyz.waozi.wurm"]["cover"]["caption"], "Classic")
|
||||
self.assertEqual(children["xyz.waozi.wurm-editor"]["cover"]["caption"], "Editor")
|
||||
self.assertEqual(children["xyz.waozi.wurm-editor"]["dependencies"], ["xyz.waozi.wurm"])
|
||||
self.assertFalse(children["xyz.waozi.wurm-editor"].get("shared_code", False))
|
||||
self.assertEqual(children["xyz.waozi.wurm-editor"]["resources"], [{
|
||||
"dependency": "xyz.waozi.wurm", "path": "assets/wurm/classic/",
|
||||
"source": "assets/wurm-preview.png"}])
|
||||
self.assertEqual(children["xyz.waozi.wurm"]["expected_id"], "wurm")
|
||||
self.assertEqual(children["xyz.waozi.wurm-editor"]["expected_id"], "wurm-editor")
|
||||
self.assertNotEqual(children["xyz.waozi.wurm"]["bundle"],
|
||||
children["xyz.waozi.wurm-editor"]["bundle"])
|
||||
|
||||
def test_changed_game_art_needs_fresh_library_copies(self):
|
||||
sources = self.root / "assets/arcade/library/sources.json"
|
||||
value = json.loads(sources.read_text())
|
||||
value["wurm-portrait"]["source_sha256"] = "0" * 64
|
||||
sources.write_text(json.dumps(value))
|
||||
with self.assertRaisesRegex(ValueError, "wurm-portrait art changed"):
|
||||
self.stage()
|
||||
|
||||
def test_every_library_cover_uses_a_bounded_thumbnail(self):
|
||||
catalog, packages = builder.stage(self.root, self.controller, self.controller_digest, self.output)
|
||||
children = {child['id']: child for child in catalog['children']}
|
||||
for package in packages:
|
||||
for app in package['apps']:
|
||||
if not app['enabled'] or not app['cover']:
|
||||
continue
|
||||
child = children[app['descriptor']['id']]
|
||||
for key in ('portrait', 'landscape', 'logo'):
|
||||
if key not in app['cover']:
|
||||
continue
|
||||
original = (app['source'] / app['cover'][key]).read_bytes()
|
||||
with self.subTest(app=child['id'], image=key):
|
||||
with Image.open(io.BytesIO(original)) as source:
|
||||
with Image.open(self.output / child['cover'][key]) as thumbnail:
|
||||
limit = 512 if key == 'logo' else 640
|
||||
self.assertLessEqual(max(thumbnail.size), limit)
|
||||
self.assertLessEqual(thumbnail.width, source.width)
|
||||
self.assertLessEqual(thumbnail.height, source.height)
|
||||
self.assertAlmostEqual(thumbnail.width / thumbnail.height,
|
||||
source.width / source.height, delta=0.01)
|
||||
self.assertIn(thumbnail.mode, ('RGB', 'RGBA'))
|
||||
# Opaque cover art is a JPEG; transparency stays PNG.
|
||||
self.assertEqual(thumbnail.format, 'JPEG' if key != 'logo' and
|
||||
thumbnail.mode == 'RGB' else 'PNG')
|
||||
|
||||
def test_editor_download_reuses_verified_shovey_assets(self):
|
||||
catalog = self.stage()
|
||||
children = {child['id']: child for child in catalog['children']}
|
||||
editor = children['arcade.shovey-editor']
|
||||
original = children['arcade.shovey']
|
||||
self.assertEqual(editor['dependencies'], [original['id']])
|
||||
self.assertTrue(editor['resources'])
|
||||
self.assertLess(editor['bytes'], original['bytes'])
|
||||
for link in editor['resources']:
|
||||
self.assertEqual(link['dependency'], original['id'])
|
||||
self.assertTrue(link['path'].startswith('assets/shovey-editor/'))
|
||||
self.assertTrue(link['source'].startswith('assets/shovey/'))
|
||||
|
||||
def test_changed_dependency_metadata_preserves_previous_stage(self):
|
||||
self.stage()
|
||||
previous = (self.output / 'assets/apps/catalog.json').read_bytes()
|
||||
path = self.root / 'build/games/shovey-editor-resources.json'
|
||||
shared = json.loads(path.read_text())
|
||||
shared['dependencies'] = []
|
||||
path.write_text(json.dumps(shared))
|
||||
with self.assertRaisesRegex(ValueError, 'dependencies differ'):
|
||||
self.stage()
|
||||
self.assertEqual((self.output / 'assets/apps/catalog.json').read_bytes(), previous)
|
||||
|
||||
def test_changed_controller_preserves_previous_stage(self):
|
||||
self.stage()
|
||||
previous = (self.output / "assets/apps/catalog.json").read_bytes()
|
||||
@@ -80,6 +276,79 @@ class CollectionTests(unittest.TestCase):
|
||||
self.stage()
|
||||
self.assertEqual((self.output / "assets/apps/catalog.json").read_bytes(), previous)
|
||||
|
||||
def test_arcade_downloads_preserve_catalog_and_standalone_payloads(self):
|
||||
catalog = self.stage()
|
||||
small = self.root / "small"
|
||||
games = self.root / "arcade.games"
|
||||
builder.stage_downloads(catalog, self.output, small, games, self.root / "art")
|
||||
art = self.root / "art"
|
||||
self.assertEqual((small / "assets/apps/catalog.json").read_bytes(),
|
||||
(self.output / "assets/apps/catalog.json").read_bytes())
|
||||
# The published launcher packs neither the host's controller nor art.
|
||||
self.assertFalse((small / catalog["harness"]).exists())
|
||||
self.assertTrue((self.output / catalog["harness"]).is_file(), "Standalone players keep the controller")
|
||||
for child in catalog["children"]:
|
||||
full = self.output / child["bundle"]
|
||||
self.assertTrue(full.is_file(), "Standalone players retain the game")
|
||||
self.assertFalse((small / child["bundle"]).exists())
|
||||
self.assertEqual((games / (child["sha256"] + ".zx")).read_bytes(), full.read_bytes())
|
||||
pictures = [child["preview"]] + [child["cover"][key] for key in child["cover"].keys() & {"portrait", "landscape", "logo"}]
|
||||
for relative in pictures:
|
||||
self.assertFalse((small / relative).exists())
|
||||
self.assertEqual((art / relative).read_bytes(), (self.output / relative).read_bytes())
|
||||
packed = sum(path.stat().st_size for path in small.rglob("*") if path.is_file())
|
||||
self.assertLess(packed, 1024 * 1024, "Arcade itself stays under one megabyte")
|
||||
|
||||
def test_art_bundle_is_published_and_named_by_the_catalog(self):
|
||||
catalog = self.stage()
|
||||
small = self.root / "small"
|
||||
games = self.root / "arcade.games"
|
||||
builder.stage_downloads(catalog, self.output, small, games, self.root / "art")
|
||||
art_bundle = self.root / "art.zx"
|
||||
art_bundle.write_bytes(b"ZX\0\0art fixture")
|
||||
art = builder.add_art(small, games, art_bundle)
|
||||
self.assertEqual(art, dict(sha256=builder.digest(art_bundle), bytes=art_bundle.stat().st_size))
|
||||
self.assertEqual((games / (art["sha256"] + ".zx")).read_bytes(), art_bundle.read_bytes())
|
||||
self.assertEqual(json.loads((small / "assets/apps/catalog.json").read_text())["art"], art)
|
||||
|
||||
def test_changed_download_preserves_previous_outputs(self):
|
||||
catalog = self.stage()
|
||||
small = self.root / "small"
|
||||
games = self.root / "arcade.games"
|
||||
builder.stage_downloads(catalog, self.output, small, games, self.root / "art")
|
||||
(self.output / catalog["children"][0]["bundle"]).write_bytes(b"changed game")
|
||||
with self.assertRaisesRegex(ValueError, "declared digest"):
|
||||
builder.stage_downloads(catalog, self.output, small, games, self.root / "art")
|
||||
self.assertTrue((small / "assets/apps/catalog.json").exists())
|
||||
self.assertTrue((games / (catalog["children"][0]["sha256"] + ".zx")).exists())
|
||||
|
||||
def test_download_archive_contains_exact_hash_named_games(self):
|
||||
catalog = self.stage()
|
||||
small = self.root / "small"
|
||||
games = self.root / "arcade.games"
|
||||
builder.stage_downloads(catalog, self.output, small, games, self.root / "art")
|
||||
archive = self.root / "arcade.games.tar"
|
||||
builder.archive_downloads(games, archive)
|
||||
with tarfile.open(archive) as content:
|
||||
self.assertEqual(set(content.getnames()), {child["sha256"] + ".zx" for child in catalog["children"]})
|
||||
for member in content:
|
||||
self.assertTrue(member.isfile())
|
||||
self.assertEqual(member.mtime, 0)
|
||||
self.assertEqual(content.extractfile(member).read(), (games / member.name).read_bytes())
|
||||
|
||||
def test_removed_download_does_not_leave_stale_payload(self):
|
||||
catalog = self.stage()
|
||||
small = self.root / "small"
|
||||
games = self.root / "arcade.games"
|
||||
builder.stage_downloads(catalog, self.output, small, games, self.root / "art")
|
||||
catalog["children"] = []
|
||||
# Build a fresh full stage as a real removed registration does.
|
||||
(self.root / "games.json").write_text(json.dumps({"packages": []}))
|
||||
catalog = self.stage()
|
||||
builder.stage_downloads(catalog, self.output, small, games, self.root / "art")
|
||||
self.assertEqual(list(games.iterdir()), [])
|
||||
self.assertFalse((small / "assets/arcade/games/shovey.zx").exists())
|
||||
|
||||
def test_invalid_controller_digest_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, "exact trusted"):
|
||||
builder.stage(self.root, self.controller, "", self.output)
|
||||
@@ -108,7 +377,7 @@ class CollectionTests(unittest.TestCase):
|
||||
(self.root / "games.json").write_text(json.dumps({"packages": []}))
|
||||
self.assertEqual(self.stage()["children"], [])
|
||||
self.assertFalse((self.output / "assets/arcade/games/shovey.zx").exists())
|
||||
self.assertFalse((self.output / "assets/arcade/covers/shovey-portrait.png").exists())
|
||||
self.assertFalse((self.output / "assets/arcade/covers/shovey-portrait.jpg").exists())
|
||||
|
||||
def test_unknown_declaration_field_rejected(self):
|
||||
declaration = json.loads((self.root / "apps.json").read_text())
|
||||
@@ -119,5 +388,56 @@ class CollectionTests(unittest.TestCase):
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
|
||||
class LibraryThumbnailTests(unittest.TestCase):
|
||||
def test_cover_keeps_full_colour_at_thumbnail_resolution(self):
|
||||
source = Image.new('RGB', (900, 1200))
|
||||
source.putdata([(x % 256, y % 256, (x + y) % 256)
|
||||
for y in range(1200) for x in range(900)])
|
||||
data = io.BytesIO()
|
||||
source.save(data, 'PNG')
|
||||
contents, suffix = artist.small_copy(data.getvalue(), 'portrait')
|
||||
self.assertEqual(suffix, '.jpg')
|
||||
with Image.open(io.BytesIO(contents)) as thumbnail:
|
||||
self.assertEqual(thumbnail.format, 'JPEG')
|
||||
self.assertEqual(thumbnail.size, (480, 640))
|
||||
self.assertEqual(thumbnail.mode, 'RGB')
|
||||
self.assertIsNone(thumbnail.getcolors(256))
|
||||
|
||||
def test_logo_retains_transparency(self):
|
||||
source = Image.new('RGBA', (1200, 400), (45, 155, 90, 0))
|
||||
source.paste((200, 35, 100, 255), (100, 50, 1100, 350))
|
||||
data = io.BytesIO()
|
||||
source.save(data, 'PNG')
|
||||
contents, suffix = artist.small_copy(data.getvalue(), 'logo')
|
||||
self.assertEqual(suffix, '.png')
|
||||
with Image.open(io.BytesIO(contents)) as thumbnail:
|
||||
self.assertEqual(thumbnail.size, (512, 171))
|
||||
self.assertEqual(thumbnail.mode, 'RGBA')
|
||||
self.assertEqual(thumbnail.getpixel((0, 0))[3], 0)
|
||||
self.assertEqual(thumbnail.getpixel((256, 85))[3], 255)
|
||||
|
||||
def test_small_covers_are_not_enlarged(self):
|
||||
source = Image.new('RGB', (120, 180), (25, 50, 75))
|
||||
data = io.BytesIO()
|
||||
source.save(data, 'PNG')
|
||||
contents, suffix = artist.small_copy(data.getvalue(), 'portrait')
|
||||
self.assertEqual(suffix, '.jpg')
|
||||
with Image.open(io.BytesIO(contents)) as thumbnail:
|
||||
self.assertEqual(thumbnail.size, (120, 180))
|
||||
|
||||
def test_small_transparent_art_is_not_reencoded(self):
|
||||
source = Image.new('RGBA', (120, 60), (25, 50, 75, 128))
|
||||
data = io.BytesIO()
|
||||
source.save(data, 'PNG')
|
||||
self.assertEqual(artist.small_copy(data.getvalue(), 'logo'), (data.getvalue(), '.png'))
|
||||
|
||||
def test_thin_logos_keep_at_least_one_pixel(self):
|
||||
source = Image.new('RGBA', (4096, 1), (25, 50, 75, 255))
|
||||
data = io.BytesIO()
|
||||
source.save(data, 'PNG')
|
||||
with Image.open(io.BytesIO(artist.small_copy(data.getvalue(), 'logo')[0])) as thumbnail:
|
||||
self.assertEqual(thumbnail.size, (512, 1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Exercise the real shared library and both unchanged games privately."""
|
||||
import argparse
|
||||
import contextlib
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import threading
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -14,6 +17,14 @@ from PIL import Image
|
||||
|
||||
LEVEL_UPDATES = 'Download new levels when they come out?'
|
||||
|
||||
def answer_library_question(driver):
|
||||
"""Keep the test's bundled levels when the library asks about updates."""
|
||||
driver.wait(label='Shovey', role='button', timeout=60)
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
|
||||
|
||||
|
||||
def answer_level_updates(driver, timeout=20):
|
||||
"""An installed Shovey first asks once whether to download new levels;
|
||||
@@ -29,6 +40,41 @@ def answer_level_updates(driver, timeout=20):
|
||||
return
|
||||
time.sleep(0.05)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def package_server(root):
|
||||
metadata = json.loads((root / 'build/arcade.json').read_text())
|
||||
by_digest = {entry['sha256']: entry for entry in metadata['children']}
|
||||
state = {'requests': [], 'corrupt_wurm': False, 'corrupt_shovey': False, 'offline': False}
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
def do_GET(self):
|
||||
digest = self.path.removeprefix('/api/v2/packages/inbe.arcade/').removesuffix('.zx')
|
||||
state['requests'].append(digest)
|
||||
# Every published file: the games and the library art.
|
||||
published = root / 'build/node-apps/arcade.games' / (digest + '.zx')
|
||||
if state['offline'] or not published.is_file():
|
||||
self.send_error(503)
|
||||
return
|
||||
entry = by_digest.get(digest, {})
|
||||
data = published.read_bytes()
|
||||
if (state['corrupt_wurm'] and entry.get('expected_id') == 'wurm') or (state['corrupt_shovey'] and entry.get('expected_id') == 'shovey'):
|
||||
data = data[:-1] + bytes([data[-1] ^ 1])
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Length', str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
server = HTTPServer(('127.0.0.1', 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield 'http://127.0.0.1:' + str(server.server_port), state
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join(timeout=5)
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--binary", type=Path, required=True)
|
||||
@@ -37,6 +83,13 @@ def main():
|
||||
assert int(os.environ["DISPLAY"].split(":")[-1].split(".")[0]) >= 400
|
||||
assert os.environ["YUE_DESKTOP_RECOVERY"] == "0"
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
entries = json.loads((root / 'build/arcade.json').read_text())['children']
|
||||
by_name = {entry['expected_id']: entry for entry in entries}
|
||||
# The library art downloads with Arcade; games only after consent.
|
||||
games = {entry['sha256'] for entry in entries}
|
||||
def size_text(size):
|
||||
return f"{(size * 10 + 500000) // 1000000 / 10:.1f} MB"
|
||||
sizes = {name: size_text(entry['bytes']) for name, entry in by_name.items()}
|
||||
output = root / "build/collection-ui-test"
|
||||
# The Classic heading counts its levels, which Shovey's level file lists.
|
||||
shovey = Path(subprocess.check_output([str(root / "scripts/ziran.sh"), "pkg", "path", "shovey"], text=True).strip())
|
||||
@@ -52,7 +105,8 @@ def main():
|
||||
with log_path.open("w") as log:
|
||||
child = subprocess.Popen([str(args.binary.resolve()), *arguments], cwd=root,
|
||||
env=os.environ | driver.environment() |
|
||||
{"ARCADE_DATA": str(profile), "LANG": "en_US.UTF-8"},
|
||||
{"ARCADE_DATA": str(profile), "ENTITY_DATA": str(profile / "entity"),
|
||||
"LANG": "en_US.UTF-8", "ARCADE_PACKAGE_ORIGIN": origin},
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
driver.attach(child, log_path)
|
||||
try:
|
||||
@@ -77,49 +131,114 @@ def main():
|
||||
assert int(subprocess.check_output(["xdotool", "getwindowpid", window], text=True, timeout=10)) == child.pid
|
||||
subprocess.run(["import", "-window", window, str(output / (name + ".png"))], check=True, timeout=10)
|
||||
|
||||
def cover(child, name):
|
||||
def grid(child, name, phone=False):
|
||||
driver.wait_idle(frames=20)
|
||||
assert not driver.find(label="Arcade", role="text"), "Library must have no heading"
|
||||
driver.wait(label="Arcade", role="text")
|
||||
assert not driver.find(label="Chess"), "Chess is temporarily disabled"
|
||||
images = driver.find(role="image", visible=True)
|
||||
screen = driver.tree()[0]
|
||||
assert max(n["visible_width"] * n["visible_height"] for n in images) >= screen["width"] * screen["height"] * .95
|
||||
assert not driver.find(label="Monkey"), "Monkey does not belong in Arcade"
|
||||
assert not driver.find(label="Next", role="button"), "Arcade must open on its app grid"
|
||||
classic_card = driver.wait(label="Shovey", role="button")
|
||||
editor_card = driver.wait(label="Shovey Editor", role="button")
|
||||
assert classic_card['y'] == editor_card['y'], "Apps must share a grid row"
|
||||
assert classic_card['x'] != editor_card['x']
|
||||
if phone:
|
||||
# Phones show small covers, two or three a row.
|
||||
wurm_card = driver.wait(label='Apfelwurm', role='button')
|
||||
assert wurm_card['y'] == classic_card['y'], 'A phone row holds all three covers'
|
||||
assert 100 <= classic_card['width'] < 200, 'Phone covers must be small cards'
|
||||
else:
|
||||
assert classic_card['width'] >= 200 and classic_card['height'] >= 350
|
||||
assert not driver.find(label='Play', role='button')
|
||||
assert not driver.find(label='Open', role='button')
|
||||
for label in ('Shovey', 'Shovey Editor', 'Apfelwurm'):
|
||||
assert not driver.find(label=label, role='text'), 'Title artwork must not repeat its name underneath'
|
||||
driver.wait(label='Apfelwurm', role='button', visible=False)
|
||||
smallest = (100, 140) if phone else (180, 200)
|
||||
covers = [node for node in driver.find(role='image', visible=True)
|
||||
if node['width'] >= smallest[0] and node['height'] >= smallest[1]]
|
||||
assert len(covers) >= 2, "Apps must use large title-screen artwork"
|
||||
capture(child, name)
|
||||
with Image.open(output / (name + ".png")) as image:
|
||||
assert len(image.convert("RGB").getcolors(1000000) or []) > 1000, "Cover artwork was not painted"
|
||||
assert len(image.convert("RGB").getcolors(1000000) or []) > 100, "App icons were not painted"
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="profile-", dir=output) as temporary:
|
||||
def primary_download(label='Download'):
|
||||
driver.wait(label=label, role='button')
|
||||
actions = driver.find(label=label, role='button', visible=True)
|
||||
action = max(actions, key=lambda node: node['width'])
|
||||
driver.press(key=action['key'], role='button')
|
||||
|
||||
with package_server(root) as (origin, server), tempfile.TemporaryDirectory(prefix="profile-", dir=output) as temporary:
|
||||
profile = Path(temporary)
|
||||
dependency_profile = profile / 'editor-first'
|
||||
with application(dependency_profile, 'editor-dependencies') as child:
|
||||
answer_library_question(driver)
|
||||
driver.press(label='Shovey Editor', role='button')
|
||||
driver.wait(label='Shovey (required) · ' + sizes['shovey'], role='text')
|
||||
driver.wait(label='Shovey Editor · ' + sizes['shovey-editor'], role='text')
|
||||
total = size_text(by_name['shovey']['bytes'] + by_name['shovey-editor']['bytes'])
|
||||
driver.wait(label='Download size: ' + total, role='text')
|
||||
capture(child, 'editor-download-plan')
|
||||
driver.press(label='Cancel', role='button')
|
||||
assert not games & set(server['requests']), 'Dependency consent must precede every download'
|
||||
driver.press(label='Shovey Editor', role='button')
|
||||
server['corrupt_shovey'] = True
|
||||
primary_download()
|
||||
driver.wait(label='Try again', role='button', timeout=60)
|
||||
assert not driver.find(label='New level', role='text'), 'An editor must not open with a corrupt dependency'
|
||||
server['corrupt_shovey'] = False
|
||||
primary_download('Try again')
|
||||
driver.wait(label='New level', role='text', timeout=60)
|
||||
capture(child, 'editor-shared-assets')
|
||||
assert server['requests'].count(by_name['shovey']['sha256']) == 2
|
||||
assert server['requests'].count(by_name['shovey-editor']['sha256']) == 1
|
||||
assert len([digest for digest in server['requests'] if digest in games]) == 3, 'Retry must reuse the already downloaded editor'
|
||||
assert by_name['shovey-editor']['bytes'] < by_name['shovey']['bytes'], 'The editor must carry only its additions'
|
||||
server['requests'].clear()
|
||||
# Disabling an entry must leave a person's older Chess save untouched.
|
||||
chess = profile / "games/inbe.chess/records/computer"
|
||||
chess.parent.mkdir(parents=True)
|
||||
chess.write_bytes(b"existing private Chess save")
|
||||
# Classic keeps its progress in the shared account record.
|
||||
record = profile / "entity/records/local/game-progress/fd65a3d7ac3d5ceb2d4d96cc5224a740.json"
|
||||
# Active play stays on this device; account sync shares completions.
|
||||
record = profile / "games/arcade.shovey/records/local.campaign"
|
||||
|
||||
def progress(data):
|
||||
# Unlocks, completion marks and the board in play.
|
||||
value = json.loads(data)
|
||||
assert value["game"] == "shovey.classic"
|
||||
return value["unlocked"], value["completed"], value["state"][10:42]
|
||||
value = data.decode()
|
||||
assert value[:2] in ("C2", "C3", "C4", "C5")
|
||||
start = value.index("P")
|
||||
state = value[start:]
|
||||
assert state[:2] in ("P1", "P2", "P3")
|
||||
return value[:start], state[:32]
|
||||
|
||||
with application(profile, "carousel") as child:
|
||||
driver.wait(label="Play", role="button")
|
||||
cover(child, "classic-portrait")
|
||||
driver.press(label="Next", role="button")
|
||||
driver.wait(label="Open", role="button")
|
||||
driver.wait(label="Editor", role="text")
|
||||
cover(child, "editor-portrait")
|
||||
driver.press(label="Previous", role="button")
|
||||
driver.key("right")
|
||||
driver.wait(label="Open", role="button")
|
||||
driver.key("left")
|
||||
driver.wait(label="Play", role="button")
|
||||
driver.drag((350, 400), (100, 400))
|
||||
driver.wait(label="Open", role="button")
|
||||
driver.pointer(240, 400, wheel=1)
|
||||
driver.wait(label="Play", role="button")
|
||||
driver.key("enter")
|
||||
with application(profile, "grid") as child:
|
||||
driver.wait(label="Shovey", role="button")
|
||||
answer_library_question(driver)
|
||||
window = subprocess.check_output(['xdotool', 'search', '--onlyvisible', '--pid', str(child.pid)], text=True).splitlines()[0]
|
||||
subprocess.run(['xdotool', 'windowsize', window, '480', '820'], check=True)
|
||||
grid(child, "apps-portrait", phone=True)
|
||||
assert not games & set(server['requests']), "Covers must not predownload games"
|
||||
# Covers show only the art; the download dialog names the size.
|
||||
cover_sizes = dict(sizes, **{'shovey-editor': size_text(by_name['shovey']['bytes'] + by_name['shovey-editor']['bytes'])})
|
||||
for text in cover_sizes.values():
|
||||
assert not driver.find(label=text, role='text'), "Covers must not show download sizes"
|
||||
driver.press(label='Profile', role='button')
|
||||
driver.wait(label='Account', role='text')
|
||||
capture(child, 'arcade-profile')
|
||||
driver.press(label='Leaderboard', role='button')
|
||||
driver.wait(label='Leaderboard', role='text')
|
||||
driver.wait(label='No leaderboard data yet.', role='text')
|
||||
capture(child, 'leaderboard-empty')
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Account', role='text')
|
||||
driver.press(label="Back", role="button")
|
||||
driver.wait(label='Shovey', role='button')
|
||||
assert not [path for path in (profile / 'resources/downloads').glob('*.zx') if path.stem in games]
|
||||
driver.press(label="Shovey", role="button")
|
||||
driver.wait(label='Cancel', role='button')
|
||||
driver.press(label='Cancel', role='button')
|
||||
assert not games & set(server['requests']), 'Cancel must download nothing'
|
||||
driver.press(label="Shovey", role="button")
|
||||
primary_download()
|
||||
driver.wait(label=f"Level 1 / {classic}")
|
||||
answer_level_updates(driver)
|
||||
driver.wait(label="How do you want to move?", role="text")
|
||||
@@ -127,35 +246,98 @@ def main():
|
||||
driver.wait_gone(label="How do you want to move?", role="text")
|
||||
assert not driver.find(label="Play", role="button"), "Arcade must skip the second title screen"
|
||||
assert len(driver.find(label="Back", role="button", visible=True)) == 1
|
||||
driver.press(label="Levels", role="button")
|
||||
driver.wait(label="Continue", role="button")
|
||||
back = driver.wait(label="Back", role="button", visible=True)
|
||||
assert back['width'] >= 100 and back['height'] >= 48
|
||||
scroll = driver.wait(role="scroll")
|
||||
driver.pointer(*UiDriver.center(scroll), wheel=-200)
|
||||
driver.wait_idle(frames=20)
|
||||
assert driver.find(label="Back", role="button", visible=True)[0]['y'] == back['y']
|
||||
driver.press(label="Back", role="button")
|
||||
driver.wait(label="Restart", role="button")
|
||||
driver.press(label="Levels", role="button")
|
||||
driver.wait(label="Continue", role="button")
|
||||
driver.key("escape")
|
||||
driver.wait(label="Restart", role="button")
|
||||
capture(child, "classic-playing")
|
||||
for direction in ("left", "right", "up", "down"):
|
||||
driver.key(direction)
|
||||
driver.wait_idle(frames=5)
|
||||
saved = wait(lambda: record.read_bytes() if record.exists() else None, "Classic did not save")
|
||||
driver.press(label="Back", role="button")
|
||||
driver.wait(label="Play", role="button")
|
||||
driver.press(label="Next", role="button")
|
||||
driver.press(label="Open", role="button")
|
||||
driver.wait(label="Explore", role="button")
|
||||
driver.wait(label="Shovey Editor", role="button")
|
||||
driver.press(label='Profile', role='button')
|
||||
driver.press(label='Leaderboard', role='button')
|
||||
driver.wait(label='Shovey', role='button')
|
||||
assert not driver.find(label='Apfelwurm', role='button'), 'An undownloaded game has a board'
|
||||
assert not driver.find(label='Shovey Editor', role='button'), 'An unranked editor has a board'
|
||||
capture(child, 'leaderboard-installed')
|
||||
state = profile / 'resources/state/arcade.shovey.json'
|
||||
state.parent.mkdir(parents=True, exist_ok=True)
|
||||
state.write_text('{"v":1,"installed":0,"favorite":0}')
|
||||
driver.wait(label='No leaderboard data yet.', role='text')
|
||||
assert not driver.find(label='Shovey', role='button'), 'A retained score kept an uninstalled board visible'
|
||||
state.write_text('{"v":1,"installed":1,"favorite":0}')
|
||||
driver.wait(label='Shovey', role='button')
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Account', role='text')
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Shovey Editor', role='button')
|
||||
assert not driver.find(label=sizes["shovey"], role="text"), "Installed games must omit their download size"
|
||||
driver.press(label="Shovey Editor", role="button")
|
||||
driver.wait(label='Download size: ' + sizes['shovey-editor'], role='text')
|
||||
primary_download()
|
||||
assert server['requests'].count(by_name['shovey']['sha256']) == 1, 'Installed dependencies must not download again'
|
||||
# The editor opens on a blank board.
|
||||
driver.wait(label="New level", role="text")
|
||||
driver.press(label="Levels", role="button")
|
||||
driver.wait(label="Story levels", role="text")
|
||||
back = driver.wait(label="Back", role="button", visible=True)
|
||||
assert back['width'] >= 100 and back['height'] >= 48
|
||||
driver.press(label="Back", role="button")
|
||||
driver.wait(label="New level", role="text")
|
||||
capture(child, "editor-open")
|
||||
driver.key("escape")
|
||||
driver.wait(label="Open", role="button")
|
||||
# Keep the selected editor when returning from its screen.
|
||||
driver.wait(label="Editor", role="text")
|
||||
driver.wait(label="Shovey Editor", role="button")
|
||||
window = subprocess.check_output(["xdotool", "search", "--onlyvisible", "--pid", str(child.pid)], text=True).splitlines()[0]
|
||||
subprocess.run(["xdotool", "windowsize", window, "900", "540"], check=True)
|
||||
cover(child, "editor-landscape")
|
||||
driver.press(label="Previous", role="button")
|
||||
driver.wait(label="Play", role="button")
|
||||
cover(child, "classic-landscape")
|
||||
grid(child, "apps-landscape")
|
||||
server['corrupt_wurm'] = True
|
||||
driver.press(label='Apfelwurm', role='button')
|
||||
primary_download()
|
||||
driver.wait(label='Try again', role='button', timeout=60)
|
||||
assert not driver.find(label='Pause', role='button'), 'Unverified bytes must never run'
|
||||
server['corrupt_wurm'] = False
|
||||
primary_download('Try again')
|
||||
# The hosted player opens its title before its first steering choice.
|
||||
driver.wait(label='Play', role='button', timeout=60)
|
||||
driver.press(label='Play', role='button')
|
||||
driver.wait(label='How do you want to move?', role='text')
|
||||
driver.press(label='Swipe', role='button')
|
||||
driver.wait(label='Pause', role='button')
|
||||
capture(child, 'wurm-playing')
|
||||
driver.press(label='Pause', role='button')
|
||||
driver.wait(label='Resume', role='button')
|
||||
driver.press(label='Back to title', role='button')
|
||||
driver.wait(label='Play', role='button')
|
||||
capture(child, 'wurm-title')
|
||||
driver.key('escape')
|
||||
driver.wait(label='Shovey', role='button')
|
||||
for entry in json.loads((root / 'build/arcade.json').read_text())['children']:
|
||||
path = profile / 'resources/downloads' / (entry['sha256'] + '.zx')
|
||||
assert hashlib.sha256(path.read_bytes()).hexdigest() == entry['sha256']
|
||||
requested = list(server['requests'])
|
||||
server['offline'] = True
|
||||
with application(profile, "restore", "--app", "arcade.shovey"):
|
||||
driver.wait(label=f"Level 1 / {classic}")
|
||||
assert progress(record.read_bytes()) == progress(saved), "Classic progress changed on restart"
|
||||
assert server['requests'] == requested, 'A cached game must reopen offline without downloading'
|
||||
assert chess.read_bytes() == b"existing private Chess save"
|
||||
assert not (profile / "inbe.db").exists()
|
||||
refused = subprocess.run([str(args.binary.resolve()), "--app", "chess"], env=os.environ | {"ARCADE_DATA": str(profile)}, capture_output=True, timeout=10)
|
||||
assert refused.returncode == 1 and b"unknown game" in refused.stderr
|
||||
print("Arcade: full covers, arrows/swipe/wheel/Enter, direct play/editor, Back, rotation and retained saves passed")
|
||||
print("Arcade: rounded covers, download consent/cancel, digest failure/retry, Shovey and Apfelwurm play, Back, rotation, offline reopen and retained saves passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Dependencies reuse only the exact prepared assets they declare."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
from game_resources import dependency_order, share_resources
|
||||
from game_packages import declared_apps
|
||||
|
||||
|
||||
class GameResourcesTest(unittest.TestCase):
|
||||
def test_shared_code_requires_explicit_dependencies_and_valid_library_entries(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'games.json').write_text(json.dumps({'packages': []}))
|
||||
(root / 'catalog.json').write_text(json.dumps({'id': 'editor', 'name': 'editor'}))
|
||||
app = {'manifest': 'catalog.json', 'requires': ['game'], 'shared_code': True,
|
||||
'library_entries': ['engine:Step'], 'shared_records': ['local.campaign']}
|
||||
|
||||
def declare(value):
|
||||
(root / 'apps.json').write_text(json.dumps(
|
||||
{'id': 'fixture', 'title': 'Fixture', 'apps': [value]}))
|
||||
return declared_apps(root)[0]
|
||||
|
||||
parsed = declare(app)
|
||||
self.assertTrue(parsed['shared_code'])
|
||||
self.assertEqual(parsed['library_entries'], ['engine:Step'])
|
||||
self.assertEqual(parsed['shared_records'], ['local.campaign'])
|
||||
for invalid in [app | {'requires': []}, app | {'shared_code': 1},
|
||||
app | {'library_entries': ['engine:../Step']},
|
||||
app | {'library_entries': ['engine:Step', 'engine:Step']},
|
||||
app | {'shared_records': ['../campaign']},
|
||||
app | {'shared_records': ['local.campaign', 'local.campaign']},
|
||||
app | {'shared_records': ['..']}, app | {'shared_records': 'campaign'}]:
|
||||
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
|
||||
declare(invalid)
|
||||
|
||||
def test_dependency_order_rejects_missing_disabled_and_cyclic_games(self):
|
||||
base = dict(enabled=True, descriptor=dict(id='game'), requires=[])
|
||||
editor = dict(enabled=True, descriptor=dict(id='editor'), requires=['game'])
|
||||
self.assertEqual(dependency_order([editor, base]), [base, editor])
|
||||
for candidates in [[editor], [editor, base | dict(enabled=False)],
|
||||
[editor, base | dict(requires=['editor'])]]:
|
||||
with self.assertRaises(ValueError):
|
||||
dependency_order(candidates)
|
||||
|
||||
def test_shared_bytes_are_removed_and_changed_bytes_remain_private(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
manifest = root / 'editor/catalog.json'
|
||||
manifest.parent.mkdir()
|
||||
manifest.with_name('shared_assets.json').write_text(json.dumps(dict(copies=[
|
||||
dict(**{'from': 'assets/game/sprites'}, to='classic/sprites'),
|
||||
dict(**{'from': 'assets/game/sound.ogg'}, to='classic/sound.ogg')])))
|
||||
base = dict(source=root, manifest=root / 'catalog.json',
|
||||
descriptor=dict(id='game', name='game', assets='assets/game'))
|
||||
editor = dict(source=root, manifest=manifest, requires=['game'],
|
||||
descriptor=dict(id='editor', name='editor'))
|
||||
original = root / 'staged/game/assets/game'
|
||||
(original / 'sprites').mkdir(parents=True)
|
||||
(original / 'sprites/player.png').write_bytes(b'original image')
|
||||
(original / 'sound.ogg').write_bytes(b'original audio')
|
||||
resources = root / 'editor-assets'
|
||||
(resources / 'classic/sprites').mkdir(parents=True)
|
||||
(resources / 'classic/sprites/player.png').write_bytes(b'original image')
|
||||
(resources / 'classic/sound.ogg').write_bytes(b'changed editor audio')
|
||||
result = share_resources(editor, [base, editor], resources, root / 'staged')
|
||||
self.assertEqual(result, dict(dependencies=['game'], resources=[dict(
|
||||
dependency='game', path='assets/editor/classic/sprites/', source='assets/game/sprites/')]))
|
||||
self.assertFalse((resources / 'classic/sprites').exists())
|
||||
self.assertEqual((resources / 'classic/sound.ogg').read_bytes(), b'changed editor audio')
|
||||
self.assertEqual((original / 'sprites/player.png').read_bytes(), b'original image')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Released games must bring new dependency edges without moving backwards."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import tomllib
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location('follow_game_releases', ROOT / 'scripts/follow-game-releases.py')
|
||||
follower = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(follower)
|
||||
|
||||
|
||||
class GameUpdates(unittest.TestCase):
|
||||
def follow(self, comparison, same_commit=False, failure=False, wrong_commit=False):
|
||||
with tempfile.TemporaryDirectory(prefix='arcade-release-metadata-') as temporary:
|
||||
root = Path(temporary)
|
||||
(root / 'apps').mkdir()
|
||||
old = '1' * 40
|
||||
new = old if same_commit else '2' * 40
|
||||
lock = {'format': 1, 'toolchain': {'commit': 'compiler'},
|
||||
'root': {'dependencies': {'wurm': 'old', 'other': 'unrelated'}},
|
||||
'packages': [{'id': 'old', 'name': 'Apfelwurm',
|
||||
'url': 'https://github.com/waozixyz/wurm.git',
|
||||
'commit': old, 'ref': 'master', 'dependencies': {}},
|
||||
{'id': 'unrelated', 'commit': 'unchanged', 'dependencies': {}}]}
|
||||
original_lock = json.dumps(lock)
|
||||
(root / 'ziran.lock').write_text(original_lock)
|
||||
original_manifest = ('[package]\nname = "Arcade"\n\n[dependencies.wurm]\n'
|
||||
'git = "https://github.com/waozixyz/wurm.git"\nref = "master"\n\n'
|
||||
'[dependencies.other]\nref = "stable"\n')
|
||||
(root / 'ziran.toml').write_text(original_manifest)
|
||||
(root / 'games.json').write_text(json.dumps({'packages': ['wurm']}))
|
||||
# Release metadata may name a release before its source is pinned.
|
||||
(root / 'apps/versions.json').write_text(json.dumps({'node_apps': {'wurm': {'version': '0.2.0'}}}))
|
||||
|
||||
def gh(*arguments):
|
||||
if arguments[0] == 'release':
|
||||
return 'v0.2.0'
|
||||
return comparison if '/compare/' in arguments[1] else new
|
||||
|
||||
def resolve(command, **kwargs):
|
||||
self.assertEqual(command, ['verified-ziran', 'update', 'wurm'])
|
||||
self.assertEqual(kwargs, {'cwd': root, 'check': True})
|
||||
self.assertIn(f'ref = "{new}"', (root / 'ziran.toml').read_text())
|
||||
declaration = tomllib.loads((root / 'ziran.toml').read_text())
|
||||
self.assertEqual(declaration['dependencies']['wurm']['ref'], new)
|
||||
self.assertEqual(declaration['dependencies']['other']['ref'], 'stable')
|
||||
if failure:
|
||||
(root / 'ziran.lock').write_text('partial resolver output')
|
||||
raise subprocess.CalledProcessError(1, command)
|
||||
# A package-manager result with a newly introduced Entity import.
|
||||
# The follower must retain this graph verbatim, rather than
|
||||
# replacing the game id while preserving its old empty edges.
|
||||
lock['root']['dependencies']['wurm'] = 'released'
|
||||
lock['packages'][0].update(id='released', commit=old if wrong_commit else new,
|
||||
ref=new, dependencies={'entity': 'accounts'})
|
||||
lock['packages'].append({'id': 'accounts', 'commit': 'new-entity', 'dependencies': {}})
|
||||
(root / 'ziran.lock').write_text(json.dumps(lock))
|
||||
|
||||
updates = root / 'updates.json'
|
||||
with patch.object(follower, 'ROOT', root), patch.object(follower, 'UPDATES', updates), \
|
||||
patch.object(follower, 'gh', gh), patch.object(follower.subprocess, 'run', side_effect=resolve) as run:
|
||||
# Discovery must not require a compiler or modify either input.
|
||||
follower.record_updates(follower.released_updates())
|
||||
self.assertEqual((root / 'ziran.lock').read_text(), original_lock)
|
||||
self.assertEqual((root / 'ziran.toml').read_text(), original_manifest)
|
||||
run.assert_not_called()
|
||||
if failure or wrong_commit:
|
||||
with self.assertRaises((subprocess.CalledProcessError, ValueError)):
|
||||
follower.pin('verified-ziran')
|
||||
self.assertEqual((root / 'ziran.lock').read_text(), original_lock)
|
||||
self.assertEqual((root / 'ziran.toml').read_text(), original_manifest)
|
||||
else:
|
||||
follower.pin('verified-ziran')
|
||||
calls = run.call_count
|
||||
return json.loads((root / 'ziran.lock').read_text()), json.loads(updates.read_text()), old, new, calls
|
||||
|
||||
def test_new_release_refreshes_transitive_graph(self):
|
||||
lock, updates, old, new, calls = self.follow('ahead')
|
||||
self.assertEqual(lock['packages'][0]['commit'], new)
|
||||
self.assertEqual(lock['root']['dependencies']['wurm'], lock['packages'][0]['id'])
|
||||
self.assertEqual(lock['packages'][0]['dependencies'], {'entity': 'accounts'})
|
||||
self.assertEqual(lock['packages'][1]['commit'], 'unchanged')
|
||||
self.assertEqual(lock['toolchain']['commit'], 'compiler')
|
||||
self.assertEqual((len(updates), calls), (1, 1))
|
||||
|
||||
def test_same_source_is_unchanged(self):
|
||||
lock, updates, old, new, calls = self.follow('identical', same_commit=True)
|
||||
self.assertEqual(lock['packages'][0]['commit'], old)
|
||||
self.assertEqual((updates, calls), ([], 0))
|
||||
|
||||
def test_older_release_never_moves_the_pin_back(self):
|
||||
lock, updates, old, new, calls = self.follow('behind')
|
||||
self.assertEqual(lock['packages'][0]['commit'], old)
|
||||
self.assertEqual((updates, calls), ([], 0))
|
||||
|
||||
def test_failed_resolution_restores_manifest_and_lock(self):
|
||||
self.follow('ahead', failure=True)
|
||||
|
||||
def test_local_override_cannot_publish_wrong_game(self):
|
||||
self.follow('ahead', wrong_commit=True)
|
||||
|
||||
def test_release_ships_unreleased_notes(self):
|
||||
with tempfile.TemporaryDirectory(prefix='arcade-release-notes-') as temporary:
|
||||
root = Path(temporary)
|
||||
game = root / 'game'
|
||||
game.mkdir()
|
||||
(game / 'apps.json').write_text(json.dumps({'title': 'Apfelwurm', 'apps': [{'manifest': 'catalog.json'}]}))
|
||||
(game / 'CHANGELOG.md').write_text('## [Unreleased]\n\n- Later.\n\n## [0.2.1] - 2026-10-29\n\n- Faster.\n')
|
||||
(root / 'CHANGELOG.md').write_text('# Arcade changelog\n\n## [Unreleased]\n\n- Keyboard first.\n\n'
|
||||
'## 0.7.1\n\n- Older.\n')
|
||||
updates = root / 'updates.json'
|
||||
updates.write_text(json.dumps([{'name': 'wurm'}]))
|
||||
with patch.object(follower, 'ROOT', root), patch.object(follower, 'UPDATES', updates), \
|
||||
patch.object(follower.subprocess, 'check_output', return_value=str(game) + '\n'):
|
||||
follower.changelog('ziran')
|
||||
self.assertEqual((root / 'CHANGELOG.md').read_text(),
|
||||
'# Arcade changelog\n\n## 0.7.2\n\n- Keyboard first.\n'
|
||||
'- Apfelwurm 0.2.1: Faster.\n\n## 0.7.1\n\n- Older.\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -4,6 +4,7 @@ import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
@@ -69,4 +70,34 @@ with tempfile.TemporaryDirectory(prefix='arcade-publisher-') as directory:
|
||||
else:
|
||||
raise AssertionError('Publisher accepted a renamed signed game identity')
|
||||
|
||||
print('Arcade ledger: existing signature, node receiver, idempotence, rollback and stable identity passed')
|
||||
# Arcade's catalog and exact separately downloaded games use the same
|
||||
# signed release and existing node importer.
|
||||
node_bundles = work / 'node-apps'
|
||||
shutil.copytree(ROOT / 'build/node-apps', node_bundles)
|
||||
ledger.write_text(json.dumps(json.loads((ROOT / 'apps/versions.json').read_text())))
|
||||
arcade = publisher.stage_node_app(store, 'arcade', private, 'test-key', pins,
|
||||
ledger_path=ledger, bundle_directory=node_bundles)
|
||||
lookups = publisher.game_lookups(store / 'inbe.arcade', arcade)
|
||||
expected = {path.stem for path in (node_bundles / 'arcade.games').glob('*.zx')}
|
||||
assert {value['artifacts'][0]['sha256'] for value in lookups} == expected
|
||||
for lookup in lookups:
|
||||
key.public_key().verify(bytes.fromhex(lookup['signature']), publisher.signing_message(lookup))
|
||||
entries = {str(path.relative_to(store)): path.read_bytes()
|
||||
for path in (store / 'inbe.arcade').rglob('*')
|
||||
if path.is_file() and path.name not in ('.publish.lock', 'history-v2.json')}
|
||||
publisher.import_node_app(entries, remote, json.loads(pins.read_text()), 'inbe.arcade')
|
||||
for digest in expected:
|
||||
assert (remote / 'inbe.arcade' / (digest + '.zx')).read_bytes() == \
|
||||
(node_bundles / 'arcade.games' / (digest + '.zx')).read_bytes()
|
||||
changed = next((node_bundles / 'arcade.games').glob('*.zx'))
|
||||
changed.write_bytes(b'ZX\0\0changed bytes')
|
||||
try:
|
||||
publisher.stage_node_app(store, 'arcade', private, 'test-key', pins,
|
||||
ledger_path=ledger, bundle_directory=node_bundles)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Publisher accepted game bytes that differ from their digest')
|
||||
assert json.loads((store / 'inbe.arcade/latest-v2.json').read_bytes()) == arcade
|
||||
|
||||
print('Arcade ledger: signatures, separate game downloads, node receiver, immutable bytes, rollback and stable identity passed')
|
||||
@@ -18,6 +18,18 @@ assert os.environ['YUE_DESKTOP_RECOVERY'] == '0'
|
||||
sys.path.insert(0, str(args.breeze / 'tests'))
|
||||
from ui_driver import UiDriver
|
||||
|
||||
LEVEL_UPDATES = 'Download new levels when they come out?'
|
||||
|
||||
def answer_cover_question(driver):
|
||||
"""Standalone Arcade and Shovey ask once on their covers whether games
|
||||
download new levels; tests keep the levels they ship with. The question
|
||||
shows in the covers' first frame."""
|
||||
driver.wait(label='Play', role='button', timeout=60)
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
output = root / 'build/shared-progress-ui-test'
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
@@ -42,6 +54,7 @@ with tempfile.TemporaryDirectory(prefix='shovey-account-progress-') as directory
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
driver.attach(child, output / (attempt + '.log'))
|
||||
try:
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
end = time.monotonic() + 30
|
||||
while True:
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""The real Shovey host opens its account provider from the hidden chest."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
assert int(os.environ['DISPLAY'].split(':')[-1].split('.')[0]) >= 400
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--binary', type=Path, required=True)
|
||||
parser.add_argument('--campaign', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
sys.path.insert(0, str(ROOT.parent / 'breeze/tests'))
|
||||
from ui_driver import UiDriver
|
||||
output = ROOT / 'build/scratch/chest-account-ui'
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=output, prefix='profile-') as temporary:
|
||||
profile = Path(temporary)
|
||||
records = profile / 'games/arcade.shovey/records'
|
||||
records.mkdir(parents=True)
|
||||
records.joinpath('local.campaign').write_text(args.campaign.read_text().splitlines()[0])
|
||||
settings = profile / 'games/arcade.shovey-player/records'
|
||||
settings.mkdir(parents=True)
|
||||
settings.joinpath('controls').write_text('off')
|
||||
settings.joinpath('updates').write_text('off')
|
||||
driver = UiDriver(profile / 'driver')
|
||||
env = os.environ | driver.environment() | dict(ARCADE_DATA=str(profile), XDG_DATA_HOME=str(profile / 'xdg'),
|
||||
YUE_DESKTOP_RECOVERY='0', SDL_AUDIODRIVER='dummy', LANG='en_US.UTF-8')
|
||||
for key in ('WAYLAND_DISPLAY', 'DBUS_SESSION_BUS_ADDRESS', 'SESSION_MANAGER', 'GDK_DISPLAY'):
|
||||
env.pop(key, None)
|
||||
with (output / 'game.log').open('w') as log:
|
||||
child = subprocess.Popen([str(args.binary.resolve()), '--app', 'shovey'], env=env,
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
driver.attach(child, output / 'game.log')
|
||||
try:
|
||||
driver.wait(label='Restart', role='button', timeout=60)
|
||||
window = subprocess.check_output(['xdotool', 'search', '--onlyvisible', '--pid', str(child.pid)], text=True).split()[0]
|
||||
subprocess.run(['xdotool', 'windowsize', window, '1280', '800'], check=True)
|
||||
time.sleep(.5)
|
||||
driver.key('down')
|
||||
driver.wait(contains='29a', role='text')
|
||||
time.sleep(.75)
|
||||
driver.press(label='Levels', role='button')
|
||||
driver.wait(label='Continue', role='button')
|
||||
labels = [node.get('label', '') for node in driver.tree()]
|
||||
assert '29' in labels and '30' in labels
|
||||
assert not any(re.fullmatch(r'[0-9]+[ab]', label) for label in labels), labels
|
||||
driver.press(label='Continue', role='button')
|
||||
for key in ('down', 'right', *(['down'] * 6)):
|
||||
driver.key(key)
|
||||
time.sleep(.18)
|
||||
driver.wait(label='Connect account', role='button')
|
||||
campaign_before = records.joinpath('local.campaign').read_bytes()
|
||||
driver.press(label='Connect account', role='button')
|
||||
driver.wait(label='Create account', role='button')
|
||||
driver.wait(label='Import key', role='button')
|
||||
driver.wait(label='Link from another device', role='button')
|
||||
tree = driver.tree()
|
||||
assert not any('offline preview' in node.get('label', '').lower() for node in tree)
|
||||
subprocess.run(['import', '-window', window, str(output / 'account-modal.png')], check=True)
|
||||
with Image.open(output / 'account-modal.png') as image:
|
||||
pixel = image.convert('RGB').getpixel((372, 52))
|
||||
assert max(pixel) < 130, f'The account modal ignored the dark game palette: {pixel}'
|
||||
driver.key('down')
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Connect account', role='button')
|
||||
driver.wait(contains='29a', role='text')
|
||||
assert records.joinpath('local.campaign').read_bytes() == campaign_before
|
||||
assert not list(profile.rglob('account.key')), 'This test created an account'
|
||||
(output / 'result.json').write_text(json.dumps(dict(actual_host=True, real_beach_entry=True,
|
||||
normal_account_provider=True, signin_actions=['Create account', 'Import key', 'Link from another device'],
|
||||
palette_sample=pixel, game_restored=True, account_created=False, live_claim=False), indent=2) + '\n')
|
||||
print('Actual Shovey: beach29 -> hidden29a -> chest -> normal themed account modal; sign-in choices present; game restored; no account created')
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.terminate()
|
||||
child.wait(timeout=15)
|
||||
@@ -16,6 +16,16 @@ import time
|
||||
|
||||
LEVEL_UPDATES = 'Download new levels when they come out?'
|
||||
|
||||
def answer_cover_question(driver):
|
||||
"""Standalone Arcade and Shovey ask once on their covers whether games
|
||||
download new levels; tests keep the levels they ship with. The question
|
||||
shows in the covers' first frame."""
|
||||
driver.wait(label='Play', role='button', timeout=60)
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
|
||||
|
||||
|
||||
def answer_level_updates(driver, timeout=20):
|
||||
"""An installed Shovey first asks once whether to download new levels;
|
||||
@@ -80,6 +90,7 @@ def main():
|
||||
covers = driver.find(role='image', visible=True)
|
||||
assert any(image['y'] == 0 and image['height'] == height for image in covers), covers
|
||||
# Play opens the level directly, with the game's own header.
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
driver.wait(label='Restart', role='button')
|
||||
answer_level_updates(driver)
|
||||
@@ -112,6 +123,7 @@ def main():
|
||||
driver.wait(label='Restart', role='button')
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Play', role='button')
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
driver.press(label='Levels', role='button')
|
||||
assert driver.wait(label='Back', role='button')['y'] < 16
|
||||
|
||||
@@ -12,6 +12,16 @@ import time
|
||||
|
||||
LEVEL_UPDATES = 'Download new levels when they come out?'
|
||||
|
||||
def answer_cover_question(driver):
|
||||
"""Standalone Arcade and Shovey ask once on their covers whether games
|
||||
download new levels; tests keep the levels they ship with. The question
|
||||
shows in the covers' first frame."""
|
||||
driver.wait(label='Play', role='button', timeout=60)
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
|
||||
|
||||
|
||||
def answer_level_updates(driver, timeout=20):
|
||||
"""An installed Shovey first asks once whether to download new levels;
|
||||
@@ -60,6 +70,7 @@ def main():
|
||||
'LANG': 'en_US.UTF-8'}, stdout=log, stderr=subprocess.STDOUT)
|
||||
driver.attach(child, log_path)
|
||||
try:
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
# The first level asks how to move before its bar takes input.
|
||||
answer_level_updates(driver)
|
||||
|
||||
@@ -15,6 +15,16 @@ import time
|
||||
|
||||
LEVEL_UPDATES = 'Download new levels when they come out?'
|
||||
|
||||
def answer_cover_question(driver):
|
||||
"""Standalone Arcade and Shovey ask once on their covers whether games
|
||||
download new levels; tests keep the levels they ship with. The question
|
||||
shows in the covers' first frame."""
|
||||
driver.wait(label='Play', role='button', timeout=60)
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
|
||||
|
||||
|
||||
def answer_level_updates(driver, timeout=20):
|
||||
"""An installed Shovey first asks once whether to download new levels;
|
||||
@@ -87,11 +97,13 @@ def main():
|
||||
def campaign_progress(data):
|
||||
# Animals keep wandering while the window rotates. Campaign unlocks,
|
||||
# completion marks, player state and board identity must stay intact.
|
||||
record = json.loads(data)
|
||||
state = record['state']
|
||||
assert record['game'] == 'shovey.classic' and state[:2] == 'M1'
|
||||
assert state[10:12] in ('P1', 'P2', 'P3')
|
||||
return (record['unlocked'], record['completed'], state[10:42]), state[2:10]
|
||||
text = data.decode()
|
||||
assert text[:2] in ('C1', 'C2', 'C3', 'C4', 'C5')
|
||||
header, marks = (6, 1000) if text[:2] == 'C5' else (4, 175)
|
||||
state = text[header + marks:]
|
||||
assert state[:2] in ('P1', 'P2', 'P3')
|
||||
assert set(text[header:header + marks]) <= {'0', '1'}
|
||||
return (int(text[2:header], 16), text[header:header + marks], state[:32]), text[-8:]
|
||||
|
||||
def swipe_beside_board_until_saved(record):
|
||||
"""A swipe on the game screen moves Shovey even where the board is not."""
|
||||
@@ -196,9 +208,14 @@ def main():
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='profile-', dir=output) as temporary:
|
||||
profile = Path(temporary)
|
||||
classic = profile / 'entity/records/local/game-progress/fd65a3d7ac3d5ceb2d4d96cc5224a740.json'
|
||||
classic = profile / 'games/arcade.shovey/records/local.campaign'
|
||||
account_progress = profile / 'entity/records/local/game-progress/fd65a3d7ac3d5ceb2d4d96cc5224a740.json'
|
||||
with application(profile, 'play') as child:
|
||||
assert not driver.find(label='Arcade', role='text')
|
||||
# The covers ask once whether games download new levels.
|
||||
driver.wait(label=LEVEL_UPDATES, role='text')
|
||||
answer_cover_question(driver)
|
||||
assert (profile / 'games/arcade.shovey-player/records/level-updates').read_text() == 'off'
|
||||
driver.press(label='Play', role='button')
|
||||
wait_level_one(driver, classic_levels)
|
||||
# The first level asks how to move: swipe and tap, or the pad.
|
||||
@@ -213,6 +230,9 @@ def main():
|
||||
resize_owned_window(child, 480, 820)
|
||||
driver.press(label='Swipe and tap')
|
||||
driver.wait_gone(label='How do you want to move?', role='text')
|
||||
driver.wait(label='Got it', role='button')
|
||||
driver.press(label='Got it', role='button')
|
||||
driver.wait_gone(label='Got it', role='button')
|
||||
assert (profile / 'games/arcade.shovey-player/records/controls').read_text() == 'off'
|
||||
assert not driver.find(label='Continue', role='button'), 'Classic must open straight on a level'
|
||||
assert driver.find(label='Shovey', role='image', visible=True), 'Shovey must be drawn as a picture'
|
||||
@@ -237,6 +257,7 @@ def main():
|
||||
assert not driver.find(label='Continue', role='button', visible=True)
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Play', role='button')
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
wait_level_one(driver, classic_levels)
|
||||
move_until_saved(classic)
|
||||
@@ -282,14 +303,20 @@ def main():
|
||||
assert all(abs(board[field] - swipe_boards[960, 600][field]) <= 1 for field in ('x', 'y', 'width', 'height'))
|
||||
swipe_in_visible_direction()
|
||||
classic_saved = campaign_progress(classic.read_bytes())
|
||||
assert not account_progress.exists(), 'Movement wrote an account progress record'
|
||||
assert len(driver.find(label='Back', role='button', visible=True)) == 1, 'Shovey needs one clear Back action'
|
||||
driver.press(label='Back', role='button')
|
||||
driver.wait(label='Play', role='button')
|
||||
driver.press(label='Next', role='button')
|
||||
driver.press(label='Open', role='button')
|
||||
driver.wait(label='Explore', role='button')
|
||||
driver.press(label='Classic', role='button')
|
||||
# The editor opens on a blank board; Levels loads a story level.
|
||||
driver.wait(label='New level', role='text')
|
||||
driver.press(label='Levels', role='button')
|
||||
driver.wait(label='Story levels', role='text')
|
||||
# Island stays unavailable in the editor until it is offered for sale.
|
||||
assert not driver.find(label='Island', role='button'), 'The editor offers Island'
|
||||
# Only levels Classic has unlocked can be a starting point.
|
||||
assert driver.find(label='Play Classic to unlock this level.', role='button'), 'Locked story levels can be edited'
|
||||
driver.press(label='1', role='button')
|
||||
driver.wait(label='Play', role='button')
|
||||
# Editing follows the device, including portrait screens whose
|
||||
@@ -299,6 +326,7 @@ def main():
|
||||
board = driver.find(key=200000, visible=True)[0]
|
||||
aspect = 5 / 3 if width > height else 3 / 5
|
||||
assert abs(board['width'] / board['height'] - aspect) < .01, ('editor paint orientation', width, height, board)
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
driver.wait(label='Testing', role='text')
|
||||
for width, height in ((390, 844), (844, 390), (480, 820)):
|
||||
@@ -307,23 +335,24 @@ def main():
|
||||
aspect = 5 / 3 if width > height else 3 / 5
|
||||
assert abs(board['width'] / board['height'] - aspect) < .01, ('editor play orientation', width, height, board)
|
||||
swipe_in_visible_direction(board_key=200000)
|
||||
# Island stays unavailable in the editor until it is offered for sale.
|
||||
# Escape returns from testing to the board, then leaves the editor.
|
||||
driver.key('escape')
|
||||
driver.wait(label='Levels', role='button')
|
||||
driver.key('escape')
|
||||
driver.key('escape')
|
||||
driver.wait(label='Classic', role='button')
|
||||
assert not driver.find(label='Island', role='button'), 'The editor offers Island'
|
||||
driver.wait(label='Open', role='button')
|
||||
with application(profile, 'restore'):
|
||||
driver.press(label='Next', role='button')
|
||||
driver.press(label='Open', role='button')
|
||||
driver.wait(label='Explore', role='button')
|
||||
# Escape returns to the editor's cover, which stays selected.
|
||||
driver.wait(label='New level', role='text')
|
||||
# Escape on the board returns to the editor's cover, which stays selected.
|
||||
driver.key('escape')
|
||||
driver.wait(label='Open', role='button')
|
||||
driver.press(label='Previous', role='button')
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
wait_level_one(driver, classic_levels)
|
||||
assert campaign_progress(classic.read_bytes()) == classic_saved
|
||||
assert not account_progress.exists(), 'Restart published an unfinished board'
|
||||
print('Standalone Shovey: portrait/landscape boards, swipe directions, the floating movement pad, rotation saves, covers and independent saves passed')
|
||||
|
||||
|
||||
|
||||
@@ -16,6 +16,16 @@ import time
|
||||
|
||||
LEVEL_UPDATES = 'Download new levels when they come out?'
|
||||
|
||||
def answer_cover_question(driver):
|
||||
"""Standalone Arcade and Shovey ask once on their covers whether games
|
||||
download new levels; tests keep the levels they ship with. The question
|
||||
shows in the covers' first frame."""
|
||||
driver.wait(label='Play', role='button', timeout=60)
|
||||
if driver.find(label=LEVEL_UPDATES, role='text'):
|
||||
driver.press(label='Not now', role='button')
|
||||
driver.wait_gone(label=LEVEL_UPDATES, role='text')
|
||||
|
||||
|
||||
|
||||
def answer_level_updates(driver, timeout=20):
|
||||
"""An installed Shovey first asks once whether to download new levels;
|
||||
@@ -96,31 +106,41 @@ def main():
|
||||
time.sleep(.05)
|
||||
raise AssertionError(f'No move was saved to {record}')
|
||||
|
||||
classic = profile / 'games/arcade.shovey/records/campaign'
|
||||
# Movement and unfinished boards stay in the game's device-only record.
|
||||
classic = profile / 'games/arcade.shovey/records/local.campaign'
|
||||
account_progress = profile / 'entity/records/local/game-progress/fd65a3d7ac3d5ceb2d4d96cc5224a740.json'
|
||||
with application('play'):
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
wait_level_one(driver, classic_levels)
|
||||
# The first level asks how to move; until then it takes every key.
|
||||
answer_level_updates(driver)
|
||||
driver.press(label='Swipe and tap')
|
||||
driver.wait_gone(label='How do you want to move?', role='text')
|
||||
# Entering play saves the untouched campaign.
|
||||
driver.wait(label='Got it', role='button')
|
||||
driver.press(label='Got it', role='button')
|
||||
driver.wait_gone(label='Got it', role='button')
|
||||
# Entering play may save the untouched campaign; a fresh profile may
|
||||
# have no record until the first move.
|
||||
deadline = time.monotonic() + 10
|
||||
while not classic.exists() and time.monotonic() < deadline:
|
||||
time.sleep(.05)
|
||||
fresh = classic.read_bytes()
|
||||
fresh = classic.read_bytes() if classic.exists() else b''
|
||||
driver.press(label='Mute', role='button')
|
||||
driver.wait(label='Unmute', role='button')
|
||||
assert (profile / 'games/arcade.shovey-player/records/sound').read_text() == 'muted'
|
||||
driver.press(label='Unmute', role='button')
|
||||
driver.wait(label='Mute', role='button')
|
||||
assert move_until_saved(classic) != fresh
|
||||
assert not account_progress.exists(), 'Movement wrote an account progress record'
|
||||
driver.key('escape')
|
||||
driver.wait(label='Play', role='button')
|
||||
with application('restart'):
|
||||
answer_cover_question(driver)
|
||||
driver.press(label='Play', role='button')
|
||||
wait_level_one(driver, classic_levels)
|
||||
assert classic.read_bytes() != fresh, 'The move was lost across a restart'
|
||||
assert not account_progress.exists(), 'Restart published an unfinished board'
|
||||
print('Windows Shovey under Wine: title, Classic, sound, saved move, Back and restart passed')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Startup previews keep full colour and alpha while the originals stay intact."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location('build_desktop', ROOT / 'scripts/build-desktop.py')
|
||||
desktop = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(desktop)
|
||||
|
||||
|
||||
class StartupArtTests(unittest.TestCase):
|
||||
def test_previews_keep_colour_alpha_and_aspect_ratio(self):
|
||||
work = ROOT / 'build/scratch'
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='startup-art-', dir=work) as temporary:
|
||||
root = Path(temporary)
|
||||
source = root / 'source/assets/shovey'
|
||||
source.mkdir(parents=True)
|
||||
# A continuous RGB gradient needs more than a 256-colour palette.
|
||||
gradient = Image.new('RGB', (900, 1200))
|
||||
gradient.putdata([(x % 256, y % 256, (x + y) % 256)
|
||||
for y in range(1200) for x in range(900)])
|
||||
gradient.save(source / 'title-portrait.png')
|
||||
gradient.transpose(Image.Transpose.ROTATE_90).save(source / 'title-landscape.png')
|
||||
logo = gradient.resize((1200, 400)).convert('RGBA')
|
||||
alpha = Image.new('L', logo.size, 0)
|
||||
alpha.paste(255, (100, 50, 1100, 350))
|
||||
logo.putalpha(alpha)
|
||||
logo.save(source / 'logo.png')
|
||||
originals = {path.name: path.read_bytes() for path in source.iterdir()}
|
||||
output = root / 'output'
|
||||
desktop.stage_startup_art(root / 'source', output)
|
||||
expected = {'title-portrait.png': (480, 640),
|
||||
'title-landscape.png': (640, 480), 'logo.png': (512, 171)}
|
||||
for name, size in expected.items():
|
||||
with self.subTest(image=name), Image.open(output / 'startup/shovey' / name) as preview:
|
||||
self.assertEqual(preview.size, size)
|
||||
self.assertEqual(preview.mode, 'RGBA' if name == 'logo.png' else 'RGB')
|
||||
self.assertIsNone(preview.getcolors(256), 'Title previews must not use a 256-colour palette')
|
||||
if name == 'logo.png':
|
||||
self.assertEqual(preview.getpixel((0, 0))[3], 0)
|
||||
self.assertEqual(preview.getpixel((256, 85))[3], 255)
|
||||
self.assertEqual((source / name).read_bytes(), originals[name])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Verify coloured startup previews, original covers and title transitions privately."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from PIL import Image
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--binary', type=Path, required=True)
|
||||
parser.add_argument('--driver-source', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
assert int(os.environ['DISPLAY'].split(':')[-1].split('.')[0]) >= 400
|
||||
assert os.environ['YUE_DESKTOP_RECOVERY'] == '0'
|
||||
sys.path.insert(0, str(args.driver_source / 'tests'))
|
||||
from ui_driver import UiDriver
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
output = root / 'build/scratch/title-progressive/ui'
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
binary = args.binary.resolve()
|
||||
driver = UiDriver(output / 'driver')
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='profile-', dir=output) as temporary:
|
||||
profile = Path(temporary)
|
||||
records = profile / 'games/arcade.shovey-player/records'
|
||||
records.mkdir(parents=True)
|
||||
(records / 'level-updates').write_text('off')
|
||||
log_path = output / 'game.log'
|
||||
with log_path.open('w') as log:
|
||||
child = subprocess.Popen([str(binary)], cwd=binary.parent,
|
||||
env=os.environ | driver.environment() |
|
||||
{'ARCADE_DATA': str(profile), 'ENTITY_DATA': str(profile / 'entity'),
|
||||
'LANG': 'en_US.UTF-8', 'SDL_AUDIODRIVER': 'dummy'},
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
driver.attach(child, log_path)
|
||||
try:
|
||||
startup = driver.tree()
|
||||
assert driver.last['frame'] <= 3, 'Preview must precede collection loading'
|
||||
images = [node for node in startup if node['kind'] == 'image' and node['label'] == 'Shovey']
|
||||
assert len(images) == 2, 'Startup must show the artwork and coloured logo together'
|
||||
for node in images:
|
||||
assert 'startup/shovey/' in node['detail']
|
||||
with Image.open(node['detail']) as picture:
|
||||
assert picture.mode in ('RGB', 'RGBA'), 'Startup art must retain full colour'
|
||||
assert max(picture.size) <= 640, 'Startup must use a small preview'
|
||||
(output / 'startup-tree.json').write_text(json.dumps(driver.last, indent=2) + '\n')
|
||||
driver.wait(label='Play', role='button', timeout=60)
|
||||
full = [node for node in driver.tree() if node['kind'] == 'image' and
|
||||
'arcade/covers/shovey-' in node.get('detail', '')]
|
||||
assert len(full) >= 2
|
||||
assert any(max(Image.open(node['detail']).size) >= 1200 for node in full), \
|
||||
'Ready cover must replace the preview with the original artwork'
|
||||
windows = subprocess.check_output(['xdotool', 'search', '--onlyvisible', '--pid', str(child.pid)], text=True).split()
|
||||
assert len(windows) == 1
|
||||
window = windows[0]
|
||||
assert subprocess.check_output(['xdotool', 'getwindowpid', window], text=True).strip() == str(child.pid)
|
||||
subprocess.run(['xdotool', 'windowmove', window, '0', '0'], check=True)
|
||||
subprocess.run(['import', '-window', window, str(output / 'classic-ready.png')], check=True)
|
||||
driver.key('right')
|
||||
subprocess.run(['import', '-window', window, str(output / 'logo-fading.png')], check=True)
|
||||
driver.wait(label='Editor', role='text')
|
||||
driver.wait(label='Open', role='button')
|
||||
driver.wait_idle(frames=5)
|
||||
subprocess.run(['import', '-window', window, str(output / 'editor-ready.png')], check=True)
|
||||
driver.key('left')
|
||||
driver.wait(label='Classic', role='text')
|
||||
driver.wait(label='Play', role='button')
|
||||
assert child.poll() is None
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.terminate()
|
||||
child.wait(timeout=10)
|
||||
print('Local title UI test: full-colour previews precede original covers; Classic/Editor transitions work')
|
||||
@@ -0,0 +1,175 @@
|
||||
import hashlib
|
||||
import http.server
|
||||
import io
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import tarfile
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"wait_published_games", ROOT / "scripts/wait-published-games.py"
|
||||
)
|
||||
readiness = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(readiness)
|
||||
|
||||
|
||||
def bundle(files):
|
||||
def text(value):
|
||||
return struct.pack("<I", len(value)) + value
|
||||
|
||||
data = b"ZX\0\0\x1a\0\0\0" + text(b"arcade") + text(b"Main")
|
||||
data += struct.pack("<IIII", 0, 0, 0, 0) + struct.pack("<I", len(files))
|
||||
for path in sorted(files):
|
||||
data += text(path.encode()) + text(files[path])
|
||||
return data
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self):
|
||||
self.now = 0.0
|
||||
|
||||
def __call__(self):
|
||||
return self.now
|
||||
|
||||
def sleep(self, seconds):
|
||||
self.now += seconds
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
responses = {}
|
||||
|
||||
def do_GET(self):
|
||||
digest = self.path.rsplit("/", 1)[-1].removesuffix(".zx")
|
||||
response = self.responses.get(digest, "ready")
|
||||
if isinstance(response, list):
|
||||
response = response.pop(0)
|
||||
if response == "ready":
|
||||
game = getattr(self.server, "games", {})
|
||||
body = game.get(digest, b"")[:16]
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("ETag", f'"{digest}"')
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if isinstance(response, int):
|
||||
self.send_response(response)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"{}")
|
||||
return
|
||||
body = response.get("body", b"ZX\0\0\x1a\0\0\0port")
|
||||
self.send_response(response.get("status", 200))
|
||||
self.send_header("Content-Type", response.get("type", "application/octet-stream"))
|
||||
if "etag" in response:
|
||||
self.send_header("ETag", response["etag"])
|
||||
if "range" in response:
|
||||
self.send_header("Content-Range", response["range"])
|
||||
self.send_header("Content-Length", str(response.get("length", len(body))))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, format, *arguments):
|
||||
pass
|
||||
|
||||
|
||||
class WaitPublishedGamesTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
work = ROOT / "build/scratch"
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="published-games-", dir=work)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.games = {
|
||||
hashlib.sha256(b"first game").hexdigest(): b"first game",
|
||||
hashlib.sha256(b"second game").hexdigest(): b"second game",
|
||||
hashlib.sha256(b"third game with bytes").hexdigest(): b"third game with bytes",
|
||||
}
|
||||
catalog = {
|
||||
"children": [
|
||||
{"sha256": digest, "bytes": len(data)} for digest, data in self.games.items()
|
||||
]
|
||||
}
|
||||
self.bundle = self.root / "arcade.zx"
|
||||
self.bundle.write_bytes(bundle({"assets/apps/catalog.json": json.dumps(catalog).encode()}))
|
||||
self.archive = self.root / "arcade.games.tar"
|
||||
with tarfile.open(self.archive, "w") as content:
|
||||
for digest, data in self.games.items():
|
||||
member = tarfile.TarInfo(digest + ".zx")
|
||||
member.size = len(data)
|
||||
content.addfile(member, io.BytesIO(data))
|
||||
Handler.responses = {}
|
||||
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self.server.games = {digest: data for digest, data in self.games.items()}
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
self.api_root = f"http://127.0.0.1:{self.server.server_port}"
|
||||
|
||||
def tearDown(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
self.thread.join(timeout=5)
|
||||
self.temporary.cleanup()
|
||||
|
||||
def wait(self, deadline=1.0):
|
||||
games = readiness.expected_games(readiness.catalog_from_bundle(self.bundle))
|
||||
members = readiness.archive_members(self.archive, games)
|
||||
clock = Clock()
|
||||
readiness.wait_for_published_games(self.api_root, self.archive, games, members,
|
||||
deadline, poll_seconds=0.01,
|
||||
clock=clock, sleep=clock.sleep)
|
||||
|
||||
def test_all_packages_ready(self):
|
||||
self.wait()
|
||||
|
||||
def test_a_404_is_retried_until_the_package_is_ready(self):
|
||||
digest = next(iter(self.games))
|
||||
Handler.responses[digest] = [404, "ready"]
|
||||
self.wait(deadline=0.03)
|
||||
|
||||
def test_a_permanent_404_fails_at_the_deadline(self):
|
||||
Handler.responses[next(iter(self.games))] = 404
|
||||
with self.assertRaisesRegex(TimeoutError, "still unavailable"):
|
||||
self.wait(deadline=0.01)
|
||||
|
||||
def test_error_or_mismatched_responses_do_not_count_as_ready(self):
|
||||
digest = next(iter(self.games))
|
||||
for response in (
|
||||
{"etag": '"0" * 64'},
|
||||
{"type": "text/plain"},
|
||||
{"body": b"not the verified prefix"},
|
||||
{"body": b"0123456789abcdef", "etag": None},
|
||||
{"status": 206, "range": "bytes 0-15/1"},
|
||||
500,
|
||||
):
|
||||
Handler.responses[digest] = response
|
||||
with self.subTest(response=response), self.assertRaises(TimeoutError):
|
||||
self.wait()
|
||||
|
||||
def test_an_exact_partial_response_counts_as_ready(self):
|
||||
digest, game = next(item for item in self.games.items() if len(item[1]) > 16)
|
||||
Handler.responses[digest] = {
|
||||
"status": 206,
|
||||
"etag": f'"{digest}"',
|
||||
"range": f"bytes 0-{min(16, len(game)) - 1}/{len(game)}",
|
||||
"body": game[:16],
|
||||
}
|
||||
self.wait()
|
||||
|
||||
def test_a_wrong_full_response_content_length_does_not_count_as_ready(self):
|
||||
digest, game = next(iter(self.games.items()))
|
||||
Handler.responses[digest] = {
|
||||
"etag": f'"{digest}"',
|
||||
"body": game,
|
||||
"length": len(game) + 1,
|
||||
}
|
||||
with self.assertRaisesRegex(TimeoutError, digest):
|
||||
self.wait(deadline=0.02)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,191 @@
|
||||
"""The website serves small verified copies of the collection's library art."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location('build_web', ROOT / 'scripts/build-web.py')
|
||||
web = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(web)
|
||||
|
||||
|
||||
def bundle(files):
|
||||
"""A minimal ZX v26 bundle: empty program sections, then its files."""
|
||||
def text(value):
|
||||
return struct.pack('<I', len(value)) + value
|
||||
data = b'ZX\0\0\x1a\0\0\0' + text(b'art') + text(b'Main') + struct.pack('<IIII', 0, 0, 0, 0)
|
||||
data += struct.pack('<I', len(files))
|
||||
for path in sorted(files):
|
||||
data += text(path.encode()) + text(files[path])
|
||||
return data
|
||||
|
||||
|
||||
def png(image):
|
||||
output = io.BytesIO()
|
||||
image.save(output, 'PNG', optimize=True)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def jpeg(image):
|
||||
output = io.BytesIO()
|
||||
image.save(output, 'JPEG', quality=85)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def gradient(width, height):
|
||||
image = Image.new('RGB', (width, height))
|
||||
image.putdata([(x * 255 // width, y * 255 // height, (x * y) % 256)
|
||||
for y in range(height) for x in range(width)])
|
||||
return image
|
||||
|
||||
|
||||
def decoded(data):
|
||||
image = Image.open(io.BytesIO(data))
|
||||
image.load()
|
||||
return image
|
||||
|
||||
|
||||
class WebLibraryArtTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
work = ROOT / 'build/scratch'
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix='web-art-', dir=work)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.published = self.root / 'published'
|
||||
self.published.mkdir()
|
||||
self.site = self.root / 'site'
|
||||
self.site.mkdir()
|
||||
# A photographic cover, larger than any library copy should be.
|
||||
self.portrait = jpeg(gradient(800, 1200))
|
||||
self.landscape = jpeg(gradient(640, 427))
|
||||
logo = gradient(512, 180).convert('RGBA')
|
||||
logo.putalpha(Image.new('L', logo.size, 0))
|
||||
logo.paste(gradient(300, 100), (100, 40))
|
||||
self.logo = png(logo)
|
||||
# Pixel art with a palette, which must stay exact.
|
||||
pixels = Image.new('P', (48, 32))
|
||||
pixels.putpalette([value for index in range(16) for value in (index * 16, 255 - index * 16, index * 8)])
|
||||
pixels.putdata([(x // 4 + y // 4) % 16 for y in range(32) for x in range(48)])
|
||||
self.preview = png(pixels)
|
||||
self.art = bundle({
|
||||
'assets/arcade/covers/wurm-portrait.jpg': self.portrait,
|
||||
'assets/arcade/covers/wurm-landscape.jpg': self.landscape,
|
||||
'assets/arcade/covers/wurm-logo.png': self.logo,
|
||||
'assets/arcade/previews/wurm.png': self.preview,
|
||||
})
|
||||
|
||||
def tearDown(self):
|
||||
self.temporary.cleanup()
|
||||
|
||||
def collection(self, art=None, archive=True):
|
||||
art = self.art if art is None else art
|
||||
catalog = dict(schema=1, id='inbe.arcade', title='Arcade', harness='assets/apps/apps.zx',
|
||||
art=dict(sha256=hashlib.sha256(self.art).hexdigest(), bytes=len(self.art)),
|
||||
children=[dict(id='xyz.waozi.wurm', title='Apfelwurm',
|
||||
preview='assets/arcade/previews/wurm.png',
|
||||
icon='assets/arcade/previews/wurm.png',
|
||||
cover=dict(portrait='assets/arcade/covers/wurm-portrait.jpg',
|
||||
landscape='assets/arcade/covers/wurm-landscape.jpg',
|
||||
logo='assets/arcade/covers/wurm-logo.png',
|
||||
caption='Play'))])
|
||||
path = self.published / 'arcade.zx'
|
||||
path.write_bytes(bundle({'assets/apps/catalog.json': json.dumps(catalog).encode()}))
|
||||
digest = catalog['art']['sha256']
|
||||
if archive:
|
||||
# The release's game archive, as the website workflow downloads it.
|
||||
with tarfile.open(self.published / 'arcade.games.tar', 'w') as games:
|
||||
for name, data in ((f'{digest}.zx', art), ('0' * 64 + '.zx', b'ZX\0\0game')):
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = len(data)
|
||||
games.addfile(entry, io.BytesIO(data))
|
||||
else:
|
||||
(self.published / 'arcade.games').mkdir()
|
||||
(self.published / 'arcade.games' / f'{digest}.zx').write_bytes(art)
|
||||
return path, digest
|
||||
|
||||
def test_small_webp_copies_keep_alpha_pixels_and_the_exact_art(self):
|
||||
path, digest = self.collection()
|
||||
listing = web.stage_web_library_art(path, self.site)
|
||||
self.assertEqual(listing['art'], digest)
|
||||
self.assertEqual(json.loads((self.site / 'library.json').read_text()), listing)
|
||||
# The exact signed bundle stays beside the copies, for the fallback.
|
||||
self.assertEqual((self.site / 'library' / f'{digest}.zx').read_bytes(), self.art)
|
||||
pictures = listing['pictures']
|
||||
self.assertEqual(set(pictures), {'assets/arcade/covers/wurm-portrait.jpg',
|
||||
'assets/arcade/covers/wurm-landscape.jpg',
|
||||
'assets/arcade/covers/wurm-logo.png',
|
||||
'assets/arcade/previews/wurm.png'})
|
||||
copies = {}
|
||||
for name, picture in pictures.items():
|
||||
data = (self.site / picture['file']).read_bytes()
|
||||
self.assertEqual(hashlib.sha256(data).hexdigest(), picture['sha256'])
|
||||
self.assertEqual(len(data), picture['bytes'])
|
||||
self.assertEqual(picture['file'], f'library/{picture["sha256"]}' + Path(picture['file']).suffix)
|
||||
copies[name] = data
|
||||
portrait = decoded(copies['assets/arcade/covers/wurm-portrait.jpg'])
|
||||
self.assertEqual(portrait.format, 'WEBP')
|
||||
self.assertEqual(portrait.size, (427, 640))
|
||||
landscape = copies['assets/arcade/covers/wurm-landscape.jpg']
|
||||
self.assertEqual(decoded(landscape).format, 'WEBP')
|
||||
self.assertLess(len(landscape), len(self.landscape))
|
||||
logo = decoded(copies['assets/arcade/covers/wurm-logo.png'])
|
||||
self.assertEqual((logo.format, logo.mode, logo.size), ('WEBP', 'RGBA', (512, 180)))
|
||||
self.assertEqual(logo.getpixel((5, 5))[3], 0)
|
||||
self.assertEqual(logo.getpixel((200, 80))[3], 255)
|
||||
preview = copies['assets/arcade/previews/wurm.png']
|
||||
if decoded(preview).format == 'WEBP':
|
||||
self.assertLess(len(preview), len(self.preview))
|
||||
self.assertEqual(decoded(preview).convert('RGB').tobytes(),
|
||||
decoded(self.preview).convert('RGB').tobytes())
|
||||
else:
|
||||
# WebP is no smaller: the verified original goes as it is.
|
||||
self.assertEqual(preview, self.preview)
|
||||
|
||||
def test_a_local_build_folder_also_supplies_the_art(self):
|
||||
path, digest = self.collection(archive=False)
|
||||
self.assertEqual(web.stage_web_library_art(path, self.site)['art'], digest)
|
||||
|
||||
def test_corrupt_or_resized_art_is_refused_before_anything_is_written(self):
|
||||
corrupt = bytearray(self.art)
|
||||
corrupt[-1] ^= 1
|
||||
for art in (bytes(corrupt), self.art + b'\0'):
|
||||
path, _ = self.collection(art)
|
||||
with self.assertRaisesRegex(ValueError, 'differs from the collection catalog'):
|
||||
web.stage_web_library_art(path, self.site)
|
||||
self.assertFalse((self.site / 'library.json').exists())
|
||||
self.assertFalse((self.site / 'library').exists())
|
||||
|
||||
def test_missing_art_or_pictures_are_refused(self):
|
||||
path, _ = self.collection()
|
||||
(self.published / 'arcade.games.tar').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'not beside it'):
|
||||
web.stage_web_library_art(path, self.site)
|
||||
self.art = bundle({'assets/arcade/previews/wurm.png': self.preview})
|
||||
path, _ = self.collection()
|
||||
with self.assertRaisesRegex(ValueError, 'lacks assets/arcade/covers'):
|
||||
web.stage_web_library_art(path, self.site)
|
||||
self.assertFalse((self.site / 'library.json').exists())
|
||||
|
||||
def test_a_collection_that_packs_its_art_needs_no_copies(self):
|
||||
catalog = dict(schema=1, id='inbe.arcade', children=[])
|
||||
path = self.published / 'arcade.zx'
|
||||
path.write_bytes(bundle({'assets/apps/catalog.json': json.dumps(catalog).encode()}))
|
||||
self.assertIsNone(web.stage_web_library_art(path, self.site))
|
||||
self.assertEqual(list(self.site.iterdir()), [])
|
||||
|
||||
def test_truncated_or_trailing_bundles_are_refused(self):
|
||||
for data in (self.art[:-3], self.art + b'x', b'PK' + self.art[2:]):
|
||||
with self.assertRaises(ValueError):
|
||||
web.bundle_assets(data)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,372 @@
|
||||
// Open Arcade's browser edition in a private headless browser and require
|
||||
// install, play, reopen and recover from a failed saved-record read. The
|
||||
// library's art never comes from api.waozi.xyz: those requests are refused,
|
||||
// and the covers must draw from the site's own copies or its exact art.
|
||||
// Usage: node tests/web_site_test.mjs SITE_DIR
|
||||
// ARCADE_TEST_LIBRARY_ONLY=1 checks painted library covers and titles without downloading games.
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createServer } from 'node:http';
|
||||
import { access, mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { extname, join, normalize } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
const site = process.argv[2];
|
||||
const libraryOnly = process.env.ARCADE_TEST_LIBRARY_ONLY === '1';
|
||||
const requiredTitles = ['Apfelwurm', 'Apfelwurm Editor', 'Choano'];
|
||||
const game = process.env.ARCADE_TEST_GAME || 'Apfelwurm';
|
||||
if (!site) throw new Error('Usage: node tests/web_site_test.mjs SITE_DIR');
|
||||
const types = { '.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.json': 'application/json',
|
||||
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp',
|
||||
'.webmanifest': 'application/manifest+json' };
|
||||
const library = JSON.parse(await readFile(join(site, 'library.json'), 'utf8').catch(() => 'null'));
|
||||
// 'site' serves the library as built; 'corrupt' damages every small copy;
|
||||
// 'missing' also withholds the exact art bundle.
|
||||
let libraryMode = 'site';
|
||||
const served = { pictures: 0, art: 0 }, refusedArt = [];
|
||||
const server = createServer(async (request, response) => {
|
||||
const url = new URL(request.url, 'http://x');
|
||||
const path = normalize(decodeURIComponent(url.pathname)).replace(/^\/+/, '') || 'index.html';
|
||||
try {
|
||||
// Model the previous runtime still cached under its unversioned URL.
|
||||
// A new deployment must request its coherent runtime revision instead.
|
||||
if (path === 'runtime.js' && !url.searchParams.has('v')) {
|
||||
response.writeHead(200, { 'Content-Type': 'text/javascript', 'Cache-Control': 'public, max-age=14400' });
|
||||
response.end('console.error("Stale cached Arcade runtime"); Module.onAbort();');
|
||||
return;
|
||||
}
|
||||
let body = await readFile(join(site, path));
|
||||
if (library && path.startsWith('library/')) {
|
||||
if (path.endsWith('.zx')) {
|
||||
served.art++;
|
||||
if (libraryMode === 'missing') throw new Error('withheld');
|
||||
} else {
|
||||
served.pictures++;
|
||||
if (libraryMode !== 'site') body[body.length - 1] ^= 1;
|
||||
}
|
||||
}
|
||||
if (path === 'index.html') {
|
||||
// Enable only the existing widget-tree reader in this disposable page.
|
||||
// Input still travels through the browser's real pointer and key events.
|
||||
body = Buffer.from(body.toString().replace('document.body.appendChild(script);', `
|
||||
Module.preRun = (Module.preRun || []).concat(function () {
|
||||
FS.mkdir('/arcade-test');
|
||||
ENV.KRYON_TEST_DRIVER = '/arcade-test';
|
||||
});
|
||||
document.body.appendChild(script);`));
|
||||
}
|
||||
response.writeHead(200, { 'Content-Type': types[extname(path)] || 'application/octet-stream' });
|
||||
response.end(body);
|
||||
} catch { response.writeHead(404); response.end(); }
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
const profile = await mkdtemp(join(process.env.TMPDIR || tmpdir(), 'arcade-web-'));
|
||||
const env = { ...process.env };
|
||||
for (const key of ['DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS']) delete env[key];
|
||||
env.YUE_DESKTOP_RECOVERY = '0';
|
||||
const browser = spawn(process.env.CHROMIUM || 'chromium', ['--headless=new', '--no-sandbox', '--use-gl=swiftshader',
|
||||
'--enable-unsafe-swiftshader', '--no-first-run', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'],
|
||||
{ env, detached: true, stdio: 'ignore' });
|
||||
let socket, sequence = 0;
|
||||
const pending = new Map(), console_lines = [];
|
||||
const command = (method, params = {}) => new Promise((resolve, reject) => {
|
||||
const id = ++sequence;
|
||||
const timeout = setTimeout(() => { pending.delete(id); reject(new Error(method + ' timed out')); }, 15000);
|
||||
pending.set(id, { resolve, reject, timeout }); socket.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
let failure = '';
|
||||
let expectedDiagnostics = 0;
|
||||
try {
|
||||
const started = Date.now();
|
||||
while (true) {
|
||||
try { await access(join(profile, 'DevToolsActivePort')); break; } catch {}
|
||||
if (Date.now() - started > 15000) throw new Error('the browser did not start');
|
||||
await delay(50);
|
||||
}
|
||||
const port = (await readFile(join(profile, 'DevToolsActivePort'), 'utf8')).split('\n')[0];
|
||||
const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||
socket = new WebSocket(targets.find(target => target.type === 'page').webSocketDebuggerUrl);
|
||||
await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; });
|
||||
socket.onmessage = event => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.method === 'Fetch.requestPaused') {
|
||||
const { requestId, request } = message.params;
|
||||
const refuse = library && request.url.includes(library.art);
|
||||
if (refuse) refusedArt.push(request.url);
|
||||
socket.send(JSON.stringify(refuse
|
||||
? { id: ++sequence, method: 'Fetch.failRequest', params: { requestId, errorReason: 'BlockedByClient' } }
|
||||
: { id: ++sequence, method: 'Fetch.continueRequest', params: { requestId } }));
|
||||
return;
|
||||
}
|
||||
if (message.method === 'Runtime.consoleAPICalled')
|
||||
console_lines.push(message.params.args.map(arg => arg.value ?? arg.description ?? '').join(' '));
|
||||
if (message.method === 'Runtime.exceptionThrown')
|
||||
console_lines.push(message.params.exceptionDetails.exception?.description || message.params.exceptionDetails.text);
|
||||
const request = pending.get(message.id);
|
||||
if (!request) return;
|
||||
pending.delete(message.id);
|
||||
clearTimeout(request.timeout);
|
||||
message.error ? request.reject(new Error(JSON.stringify(message.error))) : request.resolve(message.result);
|
||||
};
|
||||
await command('Runtime.enable'); await command('Page.enable');
|
||||
// Games still download from the API; only its art requests are refused.
|
||||
await command('Fetch.enable', { patterns: [{ urlPattern: '*://api.waozi.xyz/*' }] });
|
||||
await command('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false });
|
||||
await command('Page.navigate', { url: `http://127.0.0.1:${server.address().port}/` });
|
||||
let ready = false;
|
||||
const deadline = Date.now() + 60000;
|
||||
while (!ready && Date.now() < deadline) {
|
||||
// The page may still be loading; it answers once its status element exists.
|
||||
const state = await command('Runtime.evaluate', {
|
||||
expression: 'JSON.stringify({ready: !!(window.Module && Module.profileReady), error: !!document.getElementById("loading")?.classList.contains("error")})',
|
||||
returnByValue: true });
|
||||
if (typeof state.result?.value !== 'string') { await delay(250); continue; }
|
||||
const value = JSON.parse(state.result.value);
|
||||
if (value.error) { failure = 'the page reported that Arcade could not start'; break; }
|
||||
ready = value.ready;
|
||||
if (!ready) await delay(250);
|
||||
}
|
||||
if (!ready && !failure) failure = 'the library never became ready';
|
||||
if (ready) {
|
||||
const resources = await command('Runtime.evaluate', {
|
||||
expression: 'performance.getEntriesByType("resource").map(entry=>entry.name)', returnByValue: true });
|
||||
const runtime = resources.result.value.map(name=>new URL(name)).filter(url=>
|
||||
/\/(runtime\.(js|wasm|data)(\.gz)?|arcade\.json|apps\.zx(\.gz)?)$/.test(url.pathname));
|
||||
const revisions = new Set(runtime.map(url=>url.searchParams.get('v')));
|
||||
if (!runtime.some(url=>url.pathname.endsWith('/runtime.js')) ||
|
||||
!runtime.some(url=>url.pathname.endsWith('/runtime.wasm')) ||
|
||||
revisions.size !== 1 || !/^[a-f0-9]{64}$/.test([...revisions][0]))
|
||||
failure = 'the runtime and collection files did not use one coherent cache revision';
|
||||
}
|
||||
// Let the library draw several frames before judging them.
|
||||
await delay(3000);
|
||||
if (ready && !failure) {
|
||||
const evaluate = async expression => {
|
||||
const value = await command('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
|
||||
if (value.exceptionDetails) throw new Error(value.exceptionDetails.exception?.description || value.exceptionDetails.text);
|
||||
return value.result?.value;
|
||||
};
|
||||
let serial = 0;
|
||||
const tree = async () => {
|
||||
await evaluate(`FS.writeFile('/arcade-test/command', ${JSON.stringify(++serial + '\ttree\n')})`);
|
||||
const end = Date.now() + 10000;
|
||||
while (Date.now() < end) {
|
||||
const failed = console_lines.slice(expectedDiagnostics).find(line => /frame failed|portable execution failed|RuntimeError/.test(line));
|
||||
if (failed) throw new Error(failed);
|
||||
const reply = await evaluate(`FS.analyzePath('/arcade-test/reply').exists ? FS.readFile('/arcade-test/reply', {encoding:'utf8'}) : ''`);
|
||||
if (reply) {
|
||||
await evaluate(`FS.unlink('/arcade-test/reply')`);
|
||||
return JSON.parse(reply).nodes;
|
||||
}
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error('Arcade stopped drawing frames');
|
||||
};
|
||||
const click = async node => {
|
||||
const position = { x: node.visible_x + node.visible_width / 2, y: node.visible_y + node.visible_height / 2 };
|
||||
await command('Input.dispatchMouseEvent', { type: 'mouseMoved', ...position });
|
||||
await command('Input.dispatchMouseEvent', { type: 'mousePressed', ...position, button: 'left', buttons: 1, clickCount: 1 });
|
||||
await delay(80);
|
||||
await command('Input.dispatchMouseEvent', { type: 'mouseReleased', ...position, button: 'left', buttons: 0, clickCount: 1 });
|
||||
await delay(250);
|
||||
};
|
||||
const button = (nodes, label) => nodes.find(node => node.kind === 'button' && node.label === label && node.visible);
|
||||
const waitButton = async label => {
|
||||
let nodes;
|
||||
for (const end = Date.now() + 60000; Date.now() < end;) {
|
||||
nodes = await tree();
|
||||
const found = button(nodes, label);
|
||||
if (found) return found;
|
||||
await delay(150);
|
||||
}
|
||||
throw new Error('Game did not show ' + label + ': ' + nodes.filter(node => node.kind === 'button').map(node => node.label).join(', '));
|
||||
};
|
||||
const pageReady = async () => {
|
||||
for (const end = Date.now() + 60000; Date.now() < end;) {
|
||||
if (await evaluate('!!(window.Module && Module.profileReady)')) return;
|
||||
await delay(150);
|
||||
}
|
||||
throw new Error('The library did not reopen');
|
||||
};
|
||||
// The covers' own pixels: art has far more colours than an empty tile.
|
||||
const coverColours = async () => {
|
||||
const covers = (await tree()).filter(node => node.kind === 'button' && node.visible &&
|
||||
node.visible_width >= 100 && node.visible_height >= 100);
|
||||
return evaluate(`(() => {
|
||||
const canvas = document.getElementById('canvas'), context = canvas.getContext('2d');
|
||||
const scale = canvas.width / canvas.clientWidth;
|
||||
return ${JSON.stringify(covers)}.map(node => {
|
||||
const pixels = context.getImageData(Math.round(node.visible_x * scale), Math.round(node.visible_y * scale),
|
||||
Math.round(node.visible_width * scale), Math.round(node.visible_height * scale)).data;
|
||||
const colours = new Set();
|
||||
for (let at = 0; at < pixels.length; at += 8) colours.add(pixels[at] << 16 | pixels[at + 1] << 8 | pixels[at + 2]);
|
||||
return colours.size;
|
||||
});
|
||||
})()`);
|
||||
};
|
||||
const DRAWN = 1500;
|
||||
const coversDrawn = async () => {
|
||||
let colours = [];
|
||||
for (const end = Date.now() + 15000; Date.now() < end;) {
|
||||
colours = await coverColours();
|
||||
if (colours.length && colours.every(count => count >= DRAWN)) return colours;
|
||||
await delay(250);
|
||||
}
|
||||
throw new Error('The library covers did not draw: ' + JSON.stringify(colours));
|
||||
};
|
||||
const libraryFetched = async () => evaluate(`performance.getEntriesByType('resource').map(entry => entry.name)
|
||||
.filter(name => /\\/library\\//.test(new URL(name).pathname) || name.includes(${JSON.stringify(library?.art || '-')}))`);
|
||||
if (library) {
|
||||
// The first visit draws every cover from the small copies alone.
|
||||
const colours = await coversDrawn();
|
||||
const fetched = await libraryFetched();
|
||||
if (served.art || refusedArt.length || served.pictures !== Object.keys(library.pictures).length ||
|
||||
fetched.some(name => !/\.webp\?v=/.test(name) && !Object.values(library.pictures).some(picture => name.includes(picture.file))))
|
||||
throw new Error('The covers did not come from the small copies alone: ' + JSON.stringify({ served, refusedArt, fetched }));
|
||||
await command('Emulation.setDeviceMetricsOverride', { width: 1280, height: 1400, deviceScaleFactor: 1, mobile: false });
|
||||
await delay(500);
|
||||
// Sample only the Text widget's rectangle below each cover. Neither the
|
||||
// cover image nor its invisible button/alt text can satisfy this check.
|
||||
const titles = (await tree()).filter(node => node.kind === 'text' && node.visible &&
|
||||
node.visible_height >= 20 && requiredTitles.includes(node.label));
|
||||
const paintedTitles = await evaluate(`(() => {
|
||||
const canvas = document.getElementById('canvas'), context = canvas.getContext('2d');
|
||||
const scale = canvas.width / canvas.clientWidth;
|
||||
return Object.fromEntries(${JSON.stringify(titles)}.map(node => {
|
||||
const pixels = context.getImageData(Math.round(node.visible_x * scale), Math.round(node.visible_y * scale),
|
||||
Math.round(node.visible_width * scale), Math.round(node.visible_height * scale)).data;
|
||||
let ink = 0;
|
||||
for (let at = 0; at < pixels.length; at += 4)
|
||||
if (pixels[at] > 120 && pixels[at + 1] > 120 && pixels[at + 2] > 120) ink++;
|
||||
return [node.label, ink];
|
||||
}));
|
||||
})()`);
|
||||
for (const title of requiredTitles) {
|
||||
if (!(paintedTitles[title] >= 100)) throw new Error(`Game title was not painted: ${title}: ${JSON.stringify(paintedTitles)}`);
|
||||
}
|
||||
console.log(`Covers drew from ${served.pictures} small copies (${Object.values(library.pictures).reduce((sum, picture) => sum + picture.bytes, 0)} bytes, art ${library.bytes} bytes); colours ${colours}; title ink pixels ${JSON.stringify(paintedTitles)}`);
|
||||
}
|
||||
if (!libraryOnly) {
|
||||
await command('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false });
|
||||
await delay(500);
|
||||
const cover = button(await tree(), game);
|
||||
if (!cover) throw new Error('Game cover missing');
|
||||
await click(cover);
|
||||
const download = (await tree()).findLast(node => node.kind === 'button' && node.label === 'Download');
|
||||
if (!download) throw new Error('The cover did not offer its download');
|
||||
await click(download);
|
||||
await waitButton(game === 'Apfelwurm' ? 'Play' : 'Back');
|
||||
const play = button(await tree(), 'Play');
|
||||
if (play) await click(play);
|
||||
const swipe = button(await tree(), 'Swipe');
|
||||
if (swipe) await click(swipe);
|
||||
if (game === 'Apfelwurm') await waitButton('Pause');
|
||||
// Flush the actual control record before a cold restart.
|
||||
await evaluate(`new Promise((resolve,reject) => FS.syncfs(false,error => error ? reject(error) : resolve(true)))`);
|
||||
await command('Page.reload');
|
||||
await pageReady();
|
||||
const reloaded = await tree();
|
||||
const installed = button(reloaded, game);
|
||||
if (!installed) throw new Error('Installed cover missing after reload');
|
||||
await click(installed);
|
||||
await waitButton(game === 'Apfelwurm' ? 'Play' : 'Back');
|
||||
console.log(game + ' downloaded, opened its game and reopened from its installed cover');
|
||||
if (game === 'Apfelwurm') {
|
||||
await command('Page.reload');
|
||||
await pageReady();
|
||||
const installed = button(await tree(), game);
|
||||
const saved = await evaluate(`(() => {
|
||||
const root='/kryon-apps/arcade/games';
|
||||
for (const name of FS.readdir(root)) {
|
||||
const path=root+'/'+name+'/records/controls.dat';
|
||||
if (FS.analyzePath(path).exists) return {path,text:FS.readFile(path,{encoding:'utf8'})};
|
||||
}
|
||||
return null;
|
||||
})()`);
|
||||
if (!saved) throw new Error('Playing did not retain the control choice');
|
||||
await evaluate(`(() => {
|
||||
const original=FS.open;
|
||||
FS.open=function(path,...args) {
|
||||
if (String(path).includes('/games/') && String(path).includes('/records/') && !String(path).endsWith('/.lock')) {
|
||||
FS.open=original;
|
||||
throw new FS.ErrnoError(29);
|
||||
}
|
||||
return original.call(this,path,...args);
|
||||
};
|
||||
})()`);
|
||||
await click(installed);
|
||||
// Depending on the game version it first reads records on its title
|
||||
// or on Play. Either path must expose a usable recovery control.
|
||||
if (!await evaluate('!!Module.arcadeFailed')) {
|
||||
try {
|
||||
const play=button(await tree(),'Play');
|
||||
if (play) await click(play);
|
||||
} catch (error) {
|
||||
// The first game frame can fail between sampling the flag and
|
||||
// asking for its tree. Require the runtime's failure signal.
|
||||
let failed=false;
|
||||
for (const end=Date.now()+1000; Date.now()<end;) {
|
||||
failed=await evaluate('!!Module.arcadeFailed');
|
||||
if (failed) break;
|
||||
await delay(50);
|
||||
}
|
||||
if (!failed) throw error;
|
||||
}
|
||||
}
|
||||
let recovered=false;
|
||||
for (const end=Date.now()+15000; Date.now()<end;) {
|
||||
recovered=await evaluate(`!!Module.arcadeFailed && document.getElementById('loading').classList.contains('error') && getComputedStyle(document.getElementById('loading')).opacity==='1'`);
|
||||
if (recovered) break;
|
||||
await delay(100);
|
||||
}
|
||||
if (!recovered) throw new Error('A failed game left the library frozen without recovery');
|
||||
if (!console_lines.some(line=>/portable execution failed in ReadLevel/.test(line)))
|
||||
throw new Error('The fixture did not reproduce the reported saved-record failure');
|
||||
expectedDiagnostics=console_lines.length;
|
||||
const retry=await evaluate(`(() => {const r=document.getElementById('retry').getBoundingClientRect();return {visible_x:r.x,visible_y:r.y,visible_width:r.width,visible_height:r.height};})()`);
|
||||
await click(retry);
|
||||
await pageReady();
|
||||
if (await evaluate(`FS.readFile(${JSON.stringify(saved.path)},{encoding:'utf8'})`) !== saved.text)
|
||||
throw new Error('Recovering from a failed game changed its saved record');
|
||||
await click(button(await tree(),game));
|
||||
await waitButton('Play');
|
||||
console.log('The reported ReadLevel failure showed recovery; returning reopened the installed game and retained its saved record');
|
||||
}
|
||||
if (library) {
|
||||
// Damaged copies are refused; the exact art from the site draws instead.
|
||||
libraryMode = 'corrupt'; served.pictures = served.art = 0;
|
||||
await command('Page.reload');
|
||||
await pageReady();
|
||||
const colours = await coversDrawn();
|
||||
if (served.art !== 1 || refusedArt.length)
|
||||
throw new Error('Damaged copies did not fall back to the site\'s exact art: ' + JSON.stringify({ served, refusedArt }));
|
||||
console.log(`Damaged copies were refused and the site's exact art drew the covers; colours ${colours}`);
|
||||
// Without the site's art the covers stay empty and Arcade asks the API.
|
||||
libraryMode = 'missing';
|
||||
await command('Page.reload');
|
||||
await pageReady();
|
||||
await delay(3000);
|
||||
const empty = await coverColours();
|
||||
if (!refusedArt.length || !empty.length || empty.some(count => count >= DRAWN))
|
||||
throw new Error('The cover check did not tell empty covers apart: ' + JSON.stringify({ empty, refusedArt }));
|
||||
console.log(`Without the site's art the covers stayed empty (colours ${empty}) and the API art request was refused`);
|
||||
libraryMode = 'site';
|
||||
}
|
||||
}
|
||||
}
|
||||
const failed = console_lines.slice(expectedDiagnostics).find(line => /frame failed|portable execution failed/.test(line));
|
||||
if (!failure && failed) failure = failed;
|
||||
} catch (error) {
|
||||
console.error(console_lines.slice(-20).join('\n'));
|
||||
throw error;
|
||||
} finally {
|
||||
socket?.close();
|
||||
try { process.kill(-browser.pid, 'SIGTERM'); } catch {}
|
||||
server.close();
|
||||
await rm(profile, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
if (failure) {
|
||||
console.error(console_lines.slice(-20).join('\n'));
|
||||
throw new Error(failure);
|
||||
}
|
||||
console.log('Arcade opened its library in the browser');
|
||||
@@ -19,71 +19,63 @@
|
||||
"url": "https://github.com/ziranlang/qrcode.git"
|
||||
},
|
||||
{
|
||||
"commit": "27c5c91c66f03ebb8841106defe62ac3476bd575",
|
||||
"dependencies": {"daochi_client": "pf64f159dfdbd5ee5", "kryon": "p681e883c26cf5268", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
|
||||
"id": "p14d320fce2d41ffd",
|
||||
"name": "Entity",
|
||||
"commit": "d74348c2e288ac55740461f7e106cda365b4db4a",
|
||||
"dependencies": {"apps": "p9928fc15e7b93288", "crypto": "pc23fbf455e97614d", "curl": "p1ca0e8d3c19dbe4c", "daochi_client": "p7de54c8ad98fe034", "entity": "pb6d17ac2aeb5844f", "game2d": "pf2f54c7603f6e861", "kryon": "p43481d12b77897ce", "kss": "p1b13dda539ed2a39", "liboqs": "p1aaef6f156781e69", "mingcute": "pe1027b9d16704793", "monocypher": "p809b4d31a48625a3", "oqs": "p7098ac9cd92f7e5f", "plot": "pab5377a2950368a2", "practices": "p9079dde0fcc11248", "qrcode": "p0dfa70137405b096", "rini": "p09fa77e94b0dfc6c", "sqlite": "p1d80baafaa5fa18a"},
|
||||
"id": "p183b01bccc6424e7",
|
||||
"name": "Inbe",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/waozixyz/entity.git"
|
||||
"url": "https://github.com/waozixyz/inbe.git"
|
||||
},
|
||||
{
|
||||
"commit": "a9ad1876e14c2be093a538aca41fd3468fe3cf19",
|
||||
"dependencies": {},
|
||||
"id": "p1aaef6f156781e69",
|
||||
"name": "liboqs",
|
||||
"ref": "main",
|
||||
"source": true,
|
||||
"url": "https://github.com/open-quantum-safe/liboqs.git"
|
||||
},
|
||||
{
|
||||
"commit": "1cb9df183089a77c8a16448a556186f30b261a98",
|
||||
"dependencies": {"kryon": "p681e883c26cf5268"},
|
||||
"dependencies": {"kryon": "p43481d12b77897ce"},
|
||||
"id": "p1b13dda539ed2a39",
|
||||
"name": "Kss",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/kryonlabs/kss.git"
|
||||
},
|
||||
{
|
||||
"commit": "bad2caaa84ef3eae61e40c99bf572d2b060d0ca2",
|
||||
"dependencies": {"kryon": "p681e883c26cf5268"},
|
||||
"id": "p20eb23d3e6db3711",
|
||||
"name": "Game2D",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/kryonlabs/game2d.git"
|
||||
"commit": "da1a7f9b7ed54abaa2ac7c08ecfaaa3b09b842fd",
|
||||
"dependencies": {"apps": "p9928fc15e7b93288", "curl": "p1ca0e8d3c19dbe4c", "entity": "pb6d17ac2aeb5844f", "kryon": "p43481d12b77897ce", "mingcute": "pe1027b9d16704793"},
|
||||
"id": "p1b5832789c5a5053",
|
||||
"name": "Shovey",
|
||||
"ref": "da1a7f9b7ed54abaa2ac7c08ecfaaa3b09b842fd",
|
||||
"url": "https://github.com/waozixyz/shovey.git"
|
||||
},
|
||||
{
|
||||
"commit": "1f3e5e763dbee918ae8f8c44b84bb98f8d0fa2d6",
|
||||
"commit": "19b299005fbe2d895f4ad525cfdae62a2220c3ea",
|
||||
"dependencies": {},
|
||||
"id": "p219661bf4be659ed",
|
||||
"name": "sqlite",
|
||||
"ref": "master",
|
||||
"source": true,
|
||||
"url": "https://github.com/sqlite/sqlite.git"
|
||||
},
|
||||
{
|
||||
"commit": "eb2b201a2da3bfc6fefd7ff2d8e476e3cb9e5bcb",
|
||||
"dependencies": {},
|
||||
"id": "p2f75403ea4cb61e4",
|
||||
"id": "p1ca0e8d3c19dbe4c",
|
||||
"name": "curl",
|
||||
"ref": "master",
|
||||
"source": true,
|
||||
"url": "https://github.com/curl/curl.git"
|
||||
},
|
||||
{
|
||||
"commit": "03c45f9461d9ace179ac6bf0f97fd5176a712f8c",
|
||||
"dependencies": {"crypto": "pf039d7a776333200", "kryon": "p681e883c26cf5268"},
|
||||
"id": "p3c73796b4662b488",
|
||||
"name": "Apps",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/waozixyz/apps.git"
|
||||
},
|
||||
{
|
||||
"commit": "2f6f1f57d7de742ef7ebc01159c2315acf793d5b",
|
||||
"dependencies": {"apps": "p3c73796b4662b488", "crypto": "pf039d7a776333200", "curl": "p2f75403ea4cb61e4", "daochi_client": "pf64f159dfdbd5ee5", "game2d": "p20eb23d3e6db3711", "kryon": "p681e883c26cf5268", "kss": "p1b13dda539ed2a39", "liboqs": "p4b0a50b49959e674", "mingcute": "pe1027b9d16704793", "monocypher": "p809b4d31a48625a3", "oqs": "p7098ac9cd92f7e5f", "plot": "pe8e21a1f2b5ff52c", "qrcode": "p0dfa70137405b096", "rini": "p09fa77e94b0dfc6c", "self": "pa4da0de6c3c44e61", "sqlite": "p219661bf4be659ed"},
|
||||
"id": "p48228a6b7e2920d3",
|
||||
"name": "Inbe",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/waozixyz/inbe.git"
|
||||
},
|
||||
{
|
||||
"commit": "e1f480f382d9443c4412133b55948374c77a5c21",
|
||||
"commit": "5d1ee888094efc63d1fb25a58af93478b103d441",
|
||||
"dependencies": {},
|
||||
"id": "p4b0a50b49959e674",
|
||||
"name": "liboqs",
|
||||
"ref": "main",
|
||||
"id": "p1d80baafaa5fa18a",
|
||||
"name": "sqlite",
|
||||
"ref": "master",
|
||||
"source": true,
|
||||
"url": "https://github.com/open-quantum-safe/liboqs.git"
|
||||
"url": "https://github.com/sqlite/sqlite.git"
|
||||
},
|
||||
{
|
||||
"commit": "e1c1135dbd731560964ce26dc4529014eefcec5c",
|
||||
"dependencies": {"raylib": "p5a77c9c35110e925"},
|
||||
"id": "p43481d12b77897ce",
|
||||
"name": "kryon",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/kryonlabs/kryon.git"
|
||||
},
|
||||
{
|
||||
"commit": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
|
||||
@@ -95,21 +87,29 @@
|
||||
"url": "https://github.com/raysan5/raylib.git"
|
||||
},
|
||||
{
|
||||
"commit": "fed12f5029e025b585b4efc6234a67a4a90a5700",
|
||||
"dependencies": {"raylib": "p5a77c9c35110e925"},
|
||||
"id": "p681e883c26cf5268",
|
||||
"name": "kryon",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/kryonlabs/kryon.git"
|
||||
"commit": "94095a939e5fa5dee1d4d9af3a9af0e9a1cb630a",
|
||||
"dependencies": {"crypto": "pc23fbf455e97614d", "kryon": "p43481d12b77897ce"},
|
||||
"id": "p6a59d2d6364debd6",
|
||||
"name": "Apps",
|
||||
"ref": "94095a939e5fa5dee1d4d9af3a9af0e9a1cb630a",
|
||||
"url": "https://github.com/waozixyz/apps.git"
|
||||
},
|
||||
{
|
||||
"commit": "22d2ddbdc236796953c905a05a2cebf5ab1b4ff3",
|
||||
"dependencies": {"liboqs": "p4b0a50b49959e674"},
|
||||
"dependencies": {"liboqs": "p1aaef6f156781e69"},
|
||||
"id": "p7098ac9cd92f7e5f",
|
||||
"name": "Oqs",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/ziranlang/oqs.git"
|
||||
},
|
||||
{
|
||||
"commit": "8250ece58a03f4d9c07cd8434780d659b54f5d7f",
|
||||
"dependencies": {"crypto": "pc23fbf455e97614d", "oqs": "p7098ac9cd92f7e5f"},
|
||||
"id": "p7de54c8ad98fe034",
|
||||
"name": "DaochiClient",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/ziranlang/daochi-client.git"
|
||||
},
|
||||
{
|
||||
"commit": "f5f0a19a5dc6c14a49adb3cd63ea79a60f6ba77b",
|
||||
"dependencies": {},
|
||||
@@ -120,20 +120,53 @@
|
||||
"url": "https://github.com/LoupVaillant/Monocypher.git"
|
||||
},
|
||||
{
|
||||
"commit": "357a71d1ee2c7c9526c2af18793ea8628c505034",
|
||||
"dependencies": {"daochi_client": "pf64f159dfdbd5ee5", "kryon": "p681e883c26cf5268", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
|
||||
"id": "pa4da0de6c3c44e61",
|
||||
"name": "Self",
|
||||
"commit": "8b81994303400255ddb0ee2da49044dbaef4397f",
|
||||
"dependencies": {},
|
||||
"id": "p9079dde0fcc11248",
|
||||
"name": "practices",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/waozixyz/self.git"
|
||||
"source": true,
|
||||
"url": "https://github.com/waozixyz/practices.git"
|
||||
},
|
||||
{
|
||||
"commit": "4f74d938be40d7f46784352797ba50214e36bd4a",
|
||||
"dependencies": {"apps": "p3c73796b4662b488", "entity": "p14d320fce2d41ffd", "kryon": "p681e883c26cf5268", "mingcute": "pe1027b9d16704793"},
|
||||
"id": "pc134c215e10d2f6a",
|
||||
"name": "Shovey",
|
||||
"commit": "5b67236a8e355e67ce4f8cc0389b9ce3805b874b",
|
||||
"dependencies": {"crypto": "pc23fbf455e97614d", "kryon": "p43481d12b77897ce"},
|
||||
"id": "p9928fc15e7b93288",
|
||||
"name": "Apps",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/waozixyz/shovey.git"
|
||||
"url": "https://github.com/waozixyz/apps.git"
|
||||
},
|
||||
{
|
||||
"commit": "3f888653b6b97010163d824c4cc72476be3214f3",
|
||||
"dependencies": {"kryon": "p43481d12b77897ce"},
|
||||
"id": "pab5377a2950368a2",
|
||||
"name": "plot",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/kryonlabs/plot.git"
|
||||
},
|
||||
{
|
||||
"commit": "99d9ad777325e9dfc15cd8610056948819dc1f07",
|
||||
"dependencies": {"apps": "p9928fc15e7b93288", "crypto": "pc23fbf455e97614d", "entity": "pb6d17ac2aeb5844f", "kryon": "p43481d12b77897ce", "mingcute": "pe1027b9d16704793"},
|
||||
"id": "pb4256918f4b7855d",
|
||||
"name": "Apfelwurm",
|
||||
"ref": "99d9ad777325e9dfc15cd8610056948819dc1f07",
|
||||
"url": "https://github.com/waozixyz/wurm.git"
|
||||
},
|
||||
{
|
||||
"commit": "33e54462886507cfb355f86e6d2d93cef7b2331c",
|
||||
"dependencies": {"daochi_client": "p7de54c8ad98fe034", "kryon": "p43481d12b77897ce", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
|
||||
"id": "pb6d17ac2aeb5844f",
|
||||
"name": "Entity",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/waozixyz/entity.git"
|
||||
},
|
||||
{
|
||||
"commit": "944826f70779a6b6cd53f6b06a75b36f4d8a2558",
|
||||
"dependencies": {},
|
||||
"id": "pc23fbf455e97614d",
|
||||
"name": "crypto",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/ziranlang/crypto.git"
|
||||
},
|
||||
{
|
||||
"commit": "9cc6872f75447c3a24c16764f9829d0f58751cb0",
|
||||
@@ -144,36 +177,36 @@
|
||||
"url": "https://github.com/kryonlabs/mingcute.git"
|
||||
},
|
||||
{
|
||||
"commit": "4b0e25bd2df86b54a8f5af3db48282bd41daab1a",
|
||||
"dependencies": {"kryon": "p681e883c26cf5268"},
|
||||
"id": "pe8e21a1f2b5ff52c",
|
||||
"name": "plot",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/kryonlabs/plot.git"
|
||||
"commit": "b7cfb33ab6f6d5fc0bcf472282d507ada42d0702",
|
||||
"dependencies": {"apps": "p9928fc15e7b93288", "entity": "pb6d17ac2aeb5844f", "game2d": "pf2f54c7603f6e861", "kryon": "p43481d12b77897ce", "mingcute": "pe1027b9d16704793"},
|
||||
"id": "pe128e00fa98e0676",
|
||||
"name": "Choano",
|
||||
"ref": "b7cfb33ab6f6d5fc0bcf472282d507ada42d0702",
|
||||
"url": "https://github.com/waozixyz/choano.git"
|
||||
},
|
||||
{
|
||||
"commit": "08bbad051379813d0fd1c3bb7bb6814f3491da75",
|
||||
"dependencies": {},
|
||||
"id": "pf039d7a776333200",
|
||||
"name": "crypto",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/ziranlang/crypto.git"
|
||||
"commit": "d32e4b606ece83e8869c954f66c334f44f7b4838",
|
||||
"dependencies": {"kryon": "p43481d12b77897ce"},
|
||||
"id": "pe878ed78ee9f8300",
|
||||
"name": "Game2D",
|
||||
"ref": "d32e4b606ece83e8869c954f66c334f44f7b4838",
|
||||
"url": "https://github.com/kryonlabs/game2d.git"
|
||||
},
|
||||
{
|
||||
"commit": "9f824c4eac1ce04df727f8e7a08d2992a8ca45a4",
|
||||
"dependencies": {"oqs": "p7098ac9cd92f7e5f"},
|
||||
"id": "pf64f159dfdbd5ee5",
|
||||
"name": "DaochiClient",
|
||||
"commit": "cee04692f3461dcb098833472f071c434980debb",
|
||||
"dependencies": {"kryon": "p43481d12b77897ce"},
|
||||
"id": "pf2f54c7603f6e861",
|
||||
"name": "Game2D",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/ziranlang/daochi-client.git"
|
||||
"url": "https://github.com/kryonlabs/game2d.git"
|
||||
}
|
||||
],
|
||||
"root": {
|
||||
"dependencies": {"apps": "p3c73796b4662b488", "entity": "p14d320fce2d41ffd", "inbe": "p48228a6b7e2920d3", "kryon": "p681e883c26cf5268", "mingcute": "pe1027b9d16704793", "shovey": "pc134c215e10d2f6a"},
|
||||
"dependencies": {"apps": "p6a59d2d6364debd6", "choano": "pe128e00fa98e0676", "entity": "pb6d17ac2aeb5844f", "game2d": "pe878ed78ee9f8300", "inbe": "p183b01bccc6424e7", "kryon": "p43481d12b77897ce", "mingcute": "pe1027b9d16704793", "shovey": "p1b5832789c5a5053", "wurm": "pb4256918f4b7855d"},
|
||||
"name": "Arcade"
|
||||
},
|
||||
"toolchain": {
|
||||
"commit": "3b54282ca1d0b494130263e28ce5df6fb7ff75e2",
|
||||
"commit": "a97e88b5b0a956c9c9977cce593ea4ecdb7ad72b",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/ziranlang/ziran.git"
|
||||
}
|
||||
|
||||
@@ -34,12 +34,12 @@ ref = "master"
|
||||
[dependencies.apps]
|
||||
git = "https://github.com/waozixyz/apps.git"
|
||||
# Use the shared controller reviewed with the supported collection host.
|
||||
ref = "master"
|
||||
ref = "94095a939e5fa5dee1d4d9af3a9af0e9a1cb630a"
|
||||
|
||||
# Shovey's editions and editor are games Arcade installs by default.
|
||||
# Shovey's editions and editor are available as separate downloads.
|
||||
[dependencies.shovey]
|
||||
git = "https://github.com/waozixyz/shovey.git"
|
||||
ref = "master"
|
||||
ref = "da1a7f9b7ed54abaa2ac7c08ecfaaa3b09b842fd"
|
||||
|
||||
# Compatibility tooling runs Inner Breeze's host checks; releases check its publisher pins.
|
||||
[dependencies.inbe]
|
||||
@@ -53,3 +53,15 @@ ref = "master"
|
||||
[dependencies.mingcute]
|
||||
git = "https://github.com/kryonlabs/mingcute.git"
|
||||
ref = "master"
|
||||
|
||||
[dependencies.wurm]
|
||||
git = "https://github.com/waozixyz/wurm.git"
|
||||
ref = "99d9ad777325e9dfc15cd8610056948819dc1f07"
|
||||
|
||||
[dependencies.game2d]
|
||||
git = "https://github.com/kryonlabs/game2d.git"
|
||||
ref = "d32e4b606ece83e8869c954f66c334f44f7b4838"
|
||||
|
||||
[dependencies.choano]
|
||||
git = "https://github.com/waozixyz/choano.git"
|
||||
ref = "b7cfb33ab6f6d5fc0bcf472282d507ada42d0702"
|
||||