Compare commits

...
Author SHA1 Message Date
waozi 57dc367b73 Keep Arcade release on published Apfelwurm source 2026-10-25 19:23:12 -03:00
waozi 09bd3db9a3 Keep standalone Shovey builds at their own default output 2026-10-25 19:17:31 -03:00
waozi c6b9cdd3ce Finish Arcade add-on downloads and isolate launcher build dependencies 2026-10-25 19:08:35 -03:00
waozi 0e2bb2f835 Display game download sizes in Arcade 2026-10-25 16:43:55 -03:00
waozi ef2d78c7ff Build Arcade around downloadable games and a rounded cover library 2026-10-25 16:28:41 -03:00
waozi 215992c6b3 Follow visible account Back actions in the USB progress test 2026-10-25 16:22:47 -03:00
waozi fab417e5b1 Verify standalone device saves without movement account writes 2026-10-25 16:18:00 -03:00
waozi a460ffb25c Pin the approved Shovey 0.6.147 source and release ledger 2026-10-25 15:49:38 -03:00
waozi 9929ecd025 Keep Monkey out of the Arcade app grid 2026-10-25 15:07:17 -03:00
waozi df9e62322e Pin the verified SDL first-frame presentation fix 2026-10-25 15:02:14 -03:00
waozi d1552d1bd4 Open Arcade on the shared app grid with painted startup frames 2026-10-25 14:57:48 -03:00
waozi f82794763c Open the normal account provider in the game themed modal 2026-10-25 14:48:07 -03:00
waozi 14d223de5a Pin the reviewed download controller for the small Arcade catalog 2026-10-25 14:16:52 -03:00
waozi e5be6cda81 Resolve game completion hash dependencies through Entity 2026-10-25 14:11:23 -03:00
waozi 6b2723e651 Verify signed game sidecars before the node release 2026-10-25 11:50:57 -03:00
waozi f83228f6d2 Keep Arcade's node catalog separate from game downloads 2026-10-25 11:49:03 -03:00
waozi 2ef86dc304 Verify completion-only Shovey progress on the USB phone 2026-10-25 04:53:09 -03:00
waozi 893041b7fc Prepare Arcade with device-only Shovey saves for host API 31 2026-10-25 03:38:33 -03:00
waozi 84f32dbeaa Standalone Arcade and Shovey ask once on their covers whether games download new levels, keep the answer with the other game settings (adopting Classic's earlier answer) and offer it to games as arcade.updates; tests answer on the covers 2026-10-25 02:42:22 -03:00
waozi 81f4c26f4c The standalone test opens the editor on its blank board, checks locked story levels and leaves with Back 2026-10-25 02:24:56 -03:00
waozi 1b60ce62db Lock Daochi Client with its SHA-256 from the crypto package 2026-10-25 00:05:55 -03:00
waozi 73d4ba84de The Windows download test reads Classic's progress from the account's shared record, as the Linux test does 2026-10-24 22:58:32 -03:00
34 changed files with 1538 additions and 214 deletions

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
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
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
echo "$EXPECTED_SHA256 build/node-apps/arcade.zx" | sha256sum --check --strict
- 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.'
fi
+49
View File
@@ -1,5 +1,54 @@
# Arcade changelog
## 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.
+10 -3
View File
@@ -104,7 +104,16 @@ 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)/'
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,8 +122,6 @@ 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/'
ln -sfn '$(LIB_DIR)/arcade' '$(BIN_DIR)/arcade'
ln -sfn '$(LIB_DIR)/shovey' '$(BIN_DIR)/shovey'
mkdir -p '$(DATA_DIR)/icons/hicolor/256x256/apps'
+29 -9
View File
@@ -1,15 +1,27 @@
# 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.
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.
Arcade carries only its catalog and covers first. 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 +44,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
@@ -152,11 +164,19 @@ 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
Island and 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.
+1 -1
View File
@@ -1 +1 @@
0.7.68
0.7.76
+1 -1
View File
@@ -1 +1 @@
20ad36d054088484f069e3e7aa72135762fe25354fb8249ca0a2fcc019834a48
5490a8e61f5fa218e813b6e3d78bece6198d2ed935c42fc77b7d5e4aeed9bfe3
+16 -9
View File
@@ -13,30 +13,37 @@
"shovey": {
"id": "arcade.shovey",
"title": "Shovey",
"version": "0.6.141",
"sequence": 149,
"version": "0.6.148",
"sequence": 156,
"host_api": 12
},
"shovey-island": {
"id": "arcade.shovey-island",
"title": "Shovey Island \u2014 Coming Soon",
"version": "0.4.6",
"sequence": 10,
"version": "0.4.7",
"sequence": 11,
"host_api": 12
},
"shovey-editor": {
"id": "arcade.shovey-editor",
"title": "Shovey Editor",
"version": "0.2.134",
"sequence": 136,
"version": "0.2.140",
"sequence": 142,
"host_api": 12
},
"arcade": {
"id": "inbe.arcade",
"title": "Arcade",
"version": "0.7.68",
"sequence": 147,
"host_api": 28
"version": "0.7.76",
"sequence": 155,
"host_api": 33
},
"wurm": {
"id": "xyz.waozi.wurm",
"title": "Apfelwurm",
"version": "0.1.2",
"sequence": 2,
"host_api": 12
}
}
}
+1 -1
View File
@@ -1,3 +1,3 @@
{
"packages": ["shovey"]
"packages": ["shovey", "wurm"]
}
+30 -3
View File
@@ -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'),
+58 -5
View File
@@ -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]
@@ -69,7 +70,16 @@ def stage(root, controller, expected_controller_digest, output):
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}.png",
icon=f"assets/arcade/previews/{name}.png")
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:
@@ -93,7 +103,7 @@ def stage(root, controller, expected_controller_digest, output):
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 +122,40 @@ def stage(root, controller, expected_controller_digest, output):
return catalog, packages[1:]
def stage_downloads(catalog, source, output, games):
"""Keep Arcade's catalog and art together; serve each game separately.
The full staging directory is also used by standalone players, which
keep their bundled games. 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):
if directory.exists():
shutil.rmtree(directory)
shutil.copytree(source, output)
games.mkdir(parents=True)
for child in catalog["children"]:
(output / child["bundle"]).unlink()
for digest, data in payloads.items():
(games / (digest + ".zx")).write_bytes(data)
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 +204,24 @@ 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 the catalog and artwork. Standalone players keep their
# offline games; Arcade downloads exactly the game the person selects.
node_apps = ROOT / "build/node-apps"
catalog_assets = node_apps / "arcade-catalog"
game_downloads = node_apps / "arcade.games"
stage_downloads(catalog, output, catalog_assets, game_downloads)
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")
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"],
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__":
+5 -4
View File
@@ -13,14 +13,15 @@ ZIRAN = str(ROOT / 'scripts/ziran.sh')
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,7 +54,7 @@ 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
+32 -3
View File
@@ -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]
@@ -37,8 +39,17 @@ def build(ziran, lock_flags):
kryon = package("kryon")
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))
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 +73,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 +96,22 @@ 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 != '.py':
raise ValueError('Invalid game asset preparation script')
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,7 +125,7 @@ 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),
@@ -110,6 +137,8 @@ def build(ziran, lock_flags):
"--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)],
"--define", "KRYON_HOSTED_UI", "--asset-dir", "assets=" + str(staged / "assets"),
"--entry", descriptor["entry"], "-o", str(bundle),
+7 -2
View File
@@ -8,7 +8,7 @@ import json
from pathlib import Path
import subprocess
APP_KEYS = {'manifest', 'cover', 'enabled'}
APP_KEYS = {'manifest', 'cover', 'enabled', 'requires'}
COVER_KEYS = {'portrait', 'landscape', 'logo', 'caption', 'action'}
@@ -41,9 +41,14 @@ 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')
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, enabled=app.get('enabled', True)))
packages.append(dict(name=name, source=source, id=declaration['id'],
title=declaration['title'], apps=apps))
return packages
+85
View File
@@ -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)
+2 -1
View File
@@ -9,12 +9,13 @@ Game :: struct {
enabled: bool
}
GameCount :: 4
GameCount :: 5
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 == 4 { return Game.{.id = "xyz.waozi.wurm", .name = "wurm", .title = "Apfelwurm", .bundle = "wurm.zx", .preview = "wurm-preview.png", .package = "wurm", .enabled = true} }
return Game.{}
}
+149
View File
@@ -0,0 +1,149 @@
// 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;
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
}
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)
}
}
+97 -3
View File
@@ -31,10 +31,12 @@
#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 "sound"
#import "entity_host"
#import "entity/publications_read"
@@ -77,6 +79,10 @@ collection_item_codec: Codec.WidgetAppSharedItemCodec;
collection_invitation_codec: Codec.WidgetAppInvitationCodec;
collection_ready: 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) {
@@ -119,6 +125,7 @@ CollectionAllows :: (context: *void, node: *AppNode, name: string) -> bool {
name == "AppInvitationHost" || name == "RefreshAppSharedHost" || name == "SendAppSharedHost" ||
name == "SmoothFramesHost" || name == "AppLocaleHost" || name == "AppSoundHost" ||
name == "tile_map.sampling" || name == "arcade.controls" || name == "arcade.sound" || name == "arcade.navigation" ||
name == "arcade.updates" ||
name == PUBLICATIONS_READ_SERVICE || name == ENTITY_RECORDS_SERVICE || name == ENTITY_DEW_SERVICE ||
name == "entity.profile"
}
@@ -206,6 +213,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 }
@@ -368,9 +385,12 @@ CollectionOpen :: (bundle: string, digest: string, harness_digest: string,
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,
.bundle = CollectionBundle, .download = CollectionDownload, .fetch = CollectionFetch,
.presentation = AppPresentation.{.cover_grid = true}}
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") }
@@ -449,6 +469,7 @@ CollectionBack :: () -> bool {
}
CollectionCollect :: () {
CollectionDownloadsPump()
if entity_ready { EntityPump() }
PublicationsReadPump()
AppHostCollect(*collection_host)
@@ -461,6 +482,7 @@ CollectionClose :: () -> bool {
if !EntityClose() { return false }
if collection_ready && !AppHostStop(*collection_host) { return false }
collection_ready = false
CollectionDownloadsClose()
CollectionCollect()
VecFree(collection_frame_paths)
while collection_images != null {
@@ -488,6 +510,13 @@ CollectionClose :: () -> bool {
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 }
@@ -516,6 +545,62 @@ 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) }
@@ -528,6 +613,9 @@ CollectionFrame :: (session: Session, viewport: Rectangle, key: s32, modifiers:
// 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
@@ -566,6 +654,12 @@ CollectionFrame :: (session: Session, viewport: Rectangle, key: s32, modifiers:
unused AppHostBack(*collection_host)
return true
}
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 +681,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[:])
+14 -4
View File
@@ -12,11 +12,13 @@
#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 {
DrawStartup :: (session: Session, directory: string, standalone: bool = true) -> bool {
if !PollDesktop() || WindowTakeCloseRequestHost() { return false }
BeginDesktopFrame()
viewport := DesktopViewport()
@@ -25,7 +27,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 +137,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 +148,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 }
+19 -11
View File
@@ -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
}
+216 -27
View File
@@ -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()
+19 -4
View File
@@ -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')
+3 -3
View File
@@ -34,13 +34,13 @@ 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.wurm'}
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')
+86 -3
View File
@@ -8,6 +8,7 @@ import shutil
import tempfile
import unittest
import sys
import tarfile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
@@ -56,11 +57,12 @@ class CollectionTests(unittest.TestCase):
# 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"})
{"arcade.shovey", "arcade.shovey-editor", "xyz.waozi.wurm"})
# Each leaf keeps the cover its own package declares.
self.assertEqual([c["cover"]["caption"] for c in catalog["children"]], ["Classic", "Editor"])
self.assertEqual([c["cover"].get("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"])])
[("shovey", "arcade.shovey-player", ["arcade.shovey", "arcade.shovey-editor"]),
("wurm", "xyz.waozi.wurm-player", ["xyz.waozi.wurm"])])
for child in catalog["children"]:
name = child["expected_id"]
packed = self.output / child["bundle"]
@@ -72,6 +74,30 @@ class CollectionTests(unittest.TestCase):
(ROOT / f"build/games/{name}-preview.png").read_bytes())
self.assertEqual((self.output / catalog["harness"]).read_bytes(), self.controller.read_bytes())
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 +106,63 @@ 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.assertEqual((small / "assets/apps/catalog.json").read_bytes(),
(self.output / "assets/apps/catalog.json").read_bytes())
self.assertEqual((small / catalog["harness"]).read_bytes(), self.controller.read_bytes())
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())
self.assertEqual((small / child["preview"]).read_bytes(),
(self.output / child["preview"]).read_bytes())
for key in child["cover"].keys() & {"portrait", "landscape", "logo"}:
relative = child["cover"][key]
self.assertEqual((small / relative).read_bytes(), (self.output / relative).read_bytes())
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.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.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)
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)
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.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)
+186 -42
View File
@@ -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,39 @@ 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)
if state['offline'] or digest not in by_digest:
self.send_error(503)
return
entry = by_digest[digest]
data = (root / 'build/node-apps/arcade.games' / (digest + '.zx')).read_bytes()
if (state['corrupt_wurm'] and entry['expected_id'] == 'wurm') or (state['corrupt_shovey'] and entry['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 +81,11 @@ 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}
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 +101,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 +127,100 @@ 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):
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']
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)
covers = [node for node in driver.find(role='image', visible=True)
if node['width'] >= 180 and node['height'] >= 200]
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 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(server['requests']) == 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")
assert server['requests'] == [], 'Covers must not predownload games'
cover_sizes = dict(sizes, **{'shovey-editor': size_text(by_name['shovey']['bytes'] + by_name['shovey-editor']['bytes'])})
for text in cover_sizes.values():
driver.wait(label=text, role='text', visible=False)
driver.press(label='Profile', role='button')
driver.wait(label='Account', role='text')
capture(child, 'arcade-profile')
driver.press(label="Back", role="button")
driver.wait(label='Shovey', role='button')
assert not list((profile / 'resources/downloads').glob('*.zx'))
driver.press(label="Shovey", role="button")
driver.wait(label='Cancel', role='button')
driver.press(label='Cancel', role='button')
assert 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 +228,78 @@ 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")
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')
driver.wait(label='Play', role='button', timeout=60)
capture(child, 'wurm-title')
driver.press(label='Play', 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')
driver.press(label='Back', role='button')
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__":
+52
View File
@@ -0,0 +1,52 @@
"""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
class GameResourcesTest(unittest.TestCase):
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)
+32 -1
View File
@@ -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')
+13
View File
@@ -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:
+84
View File
@@ -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)
+12
View File
@@ -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
+11
View File
@@ -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)
+40 -14
View File
@@ -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.
@@ -237,6 +254,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 +300,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 +323,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 +332,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')
+20 -3
View File
@@ -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,38 @@ 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.
# 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')
+64 -56
View File
@@ -1,6 +1,14 @@
{
"format": 1,
"packages": [
{
"commit": "ce01eafebd60cf0f729154fa6c735a37cd907d2d",
"dependencies": {"crypto": "pc23fbf455e97614d", "kryon": "p2d318e48a4d2aa44"},
"id": "p00c3077d466cc4cc",
"name": "Apps",
"ref": "master",
"url": "https://github.com/waozixyz/apps.git"
},
{
"commit": "b31299434c785d0f2bd82f36b5bfd2fd36ba1216",
"dependencies": {},
@@ -18,17 +26,9 @@
"ref": "master",
"url": "https://github.com/ziranlang/qrcode.git"
},
{
"commit": "27c5c91c66f03ebb8841106defe62ac3476bd575",
"dependencies": {"daochi_client": "pf64f159dfdbd5ee5", "kryon": "p681e883c26cf5268", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
"id": "p14d320fce2d41ffd",
"name": "Entity",
"ref": "master",
"url": "https://github.com/waozixyz/entity.git"
},
{
"commit": "1cb9df183089a77c8a16448a556186f30b261a98",
"dependencies": {"kryon": "p681e883c26cf5268"},
"dependencies": {"kryon": "p2d318e48a4d2aa44"},
"id": "p1b13dda539ed2a39",
"name": "Kss",
"ref": "master",
@@ -36,7 +36,7 @@
},
{
"commit": "bad2caaa84ef3eae61e40c99bf572d2b060d0ca2",
"dependencies": {"kryon": "p681e883c26cf5268"},
"dependencies": {"kryon": "p2d318e48a4d2aa44"},
"id": "p20eb23d3e6db3711",
"name": "Game2D",
"ref": "master",
@@ -51,6 +51,22 @@
"source": true,
"url": "https://github.com/sqlite/sqlite.git"
},
{
"commit": "be74b13fd9b991e63a96360e8f13d781cece964e",
"dependencies": {"daochi_client": "p9972fcdd2d5ba999", "kryon": "p2d318e48a4d2aa44", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
"id": "p2b0009b9bbaa09de",
"name": "Entity",
"ref": "master",
"url": "https://github.com/waozixyz/entity.git"
},
{
"commit": "92ca1fd68ced43969df57632720060ee9666da16",
"dependencies": {"raylib": "p5a77c9c35110e925"},
"id": "p2d318e48a4d2aa44",
"name": "kryon",
"ref": "master",
"url": "https://github.com/kryonlabs/kryon.git"
},
{
"commit": "eb2b201a2da3bfc6fefd7ff2d8e476e3cb9e5bcb",
"dependencies": {},
@@ -60,17 +76,9 @@
"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"},
"dependencies": {"apps": "p00c3077d466cc4cc", "crypto": "pc23fbf455e97614d", "curl": "p2f75403ea4cb61e4", "daochi_client": "p9972fcdd2d5ba999", "game2d": "p20eb23d3e6db3711", "kryon": "p2d318e48a4d2aa44", "kss": "p1b13dda539ed2a39", "liboqs": "p4b0a50b49959e674", "mingcute": "pe1027b9d16704793", "monocypher": "p809b4d31a48625a3", "oqs": "p7098ac9cd92f7e5f", "plot": "pab5377a2950368a2", "qrcode": "p0dfa70137405b096", "rini": "p09fa77e94b0dfc6c", "self": "pa4da0de6c3c44e61", "sqlite": "p219661bf4be659ed"},
"id": "p48228a6b7e2920d3",
"name": "Inbe",
"ref": "master",
@@ -94,14 +102,6 @@
"source": true,
"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": "22d2ddbdc236796953c905a05a2cebf5ab1b4ff3",
"dependencies": {"liboqs": "p4b0a50b49959e674"},
@@ -119,21 +119,45 @@
"source": true,
"url": "https://github.com/LoupVaillant/Monocypher.git"
},
{
"commit": "25d9f649c43a8de44a5fea602d2835e33e6ca999",
"dependencies": {"crypto": "pc23fbf455e97614d", "oqs": "p7098ac9cd92f7e5f"},
"id": "p9972fcdd2d5ba999",
"name": "DaochiClient",
"ref": "master",
"url": "https://github.com/ziranlang/daochi-client.git"
},
{
"commit": "357a71d1ee2c7c9526c2af18793ea8628c505034",
"dependencies": {"daochi_client": "pf64f159dfdbd5ee5", "kryon": "p681e883c26cf5268", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
"dependencies": {"daochi_client": "p9972fcdd2d5ba999", "kryon": "p2d318e48a4d2aa44", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
"id": "pa4da0de6c3c44e61",
"name": "Self",
"ref": "master",
"url": "https://github.com/waozixyz/self.git"
},
{
"commit": "4f74d938be40d7f46784352797ba50214e36bd4a",
"dependencies": {"apps": "p3c73796b4662b488", "entity": "p14d320fce2d41ffd", "kryon": "p681e883c26cf5268", "mingcute": "pe1027b9d16704793"},
"id": "pc134c215e10d2f6a",
"name": "Shovey",
"commit": "3f888653b6b97010163d824c4cc72476be3214f3",
"dependencies": {"kryon": "p2d318e48a4d2aa44"},
"id": "pab5377a2950368a2",
"name": "plot",
"ref": "master",
"url": "https://github.com/waozixyz/shovey.git"
"url": "https://github.com/kryonlabs/plot.git"
},
{
"commit": "a6aebdbb5af7491b9303e70aed85b32c70a127a2",
"dependencies": {"apps": "p00c3077d466cc4cc", "kryon": "p2d318e48a4d2aa44", "mingcute": "pe1027b9d16704793"},
"id": "pb047b340fde29f6b",
"name": "Apfelwurm",
"ref": "master",
"url": "https://github.com/waozixyz/wurm.git"
},
{
"commit": "944826f70779a6b6cd53f6b06a75b36f4d8a2558",
"dependencies": {},
"id": "pc23fbf455e97614d",
"name": "crypto",
"ref": "master",
"url": "https://github.com/ziranlang/crypto.git"
},
{
"commit": "9cc6872f75447c3a24c16764f9829d0f58751cb0",
@@ -144,36 +168,20 @@
"url": "https://github.com/kryonlabs/mingcute.git"
},
{
"commit": "4b0e25bd2df86b54a8f5af3db48282bd41daab1a",
"dependencies": {"kryon": "p681e883c26cf5268"},
"id": "pe8e21a1f2b5ff52c",
"name": "plot",
"commit": "2c05b39693a6d8a697f5b111f9d438092b4f186a",
"dependencies": {"apps": "p00c3077d466cc4cc", "entity": "p2b0009b9bbaa09de", "kryon": "p2d318e48a4d2aa44", "mingcute": "pe1027b9d16704793"},
"id": "ped09a2b79138be62",
"name": "Shovey",
"ref": "master",
"url": "https://github.com/kryonlabs/plot.git"
},
{
"commit": "08bbad051379813d0fd1c3bb7bb6814f3491da75",
"dependencies": {},
"id": "pf039d7a776333200",
"name": "crypto",
"ref": "master",
"url": "https://github.com/ziranlang/crypto.git"
},
{
"commit": "9f824c4eac1ce04df727f8e7a08d2992a8ca45a4",
"dependencies": {"oqs": "p7098ac9cd92f7e5f"},
"id": "pf64f159dfdbd5ee5",
"name": "DaochiClient",
"ref": "master",
"url": "https://github.com/ziranlang/daochi-client.git"
"url": "https://github.com/waozixyz/shovey.git"
}
],
"root": {
"dependencies": {"apps": "p3c73796b4662b488", "entity": "p14d320fce2d41ffd", "inbe": "p48228a6b7e2920d3", "kryon": "p681e883c26cf5268", "mingcute": "pe1027b9d16704793", "shovey": "pc134c215e10d2f6a"},
"dependencies": {"apps": "p00c3077d466cc4cc", "entity": "p2b0009b9bbaa09de", "inbe": "p48228a6b7e2920d3", "kryon": "p2d318e48a4d2aa44", "mingcute": "pe1027b9d16704793", "shovey": "ped09a2b79138be62", "wurm": "pb047b340fde29f6b"},
"name": "Arcade"
},
"toolchain": {
"commit": "3b54282ca1d0b494130263e28ce5df6fb7ff75e2",
"commit": "21c6a681c9ba684bbe069004fd971748cc5c7dc0",
"ref": "master",
"url": "https://github.com/ziranlang/ziran.git"
}
+5 -1
View File
@@ -36,7 +36,7 @@ git = "https://github.com/waozixyz/apps.git"
# Use the shared controller reviewed with the supported collection host.
ref = "master"
# 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"
@@ -53,3 +53,7 @@ ref = "master"
[dependencies.mingcute]
git = "https://github.com/kryonlabs/mingcute.git"
ref = "master"
[dependencies.wurm]
git = "https://github.com/waozixyz/wurm.git"
ref = "master"