diff --git a/.github/workflows/gamelib-android.yml b/.github/workflows/gamelib-android.yml new file mode 100644 index 00000000..719656ec --- /dev/null +++ b/.github/workflows/gamelib-android.yml @@ -0,0 +1,137 @@ +name: GameLibrary Android app + +# Builds GameLibrary-android.apk (apps/gamelib/android/: a full-screen window around the web app), signs it with the key in the +# repository's secrets, opens it on an emulator and puts it on the gamelib-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "apps/gamelib/android/**" + - ".github/workflows/gamelib-android.yml" + pull_request: + paths: + - "apps/gamelib/android/**" + - ".github/workflows/gamelib-android.yml" + +permissions: + contents: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + + - name: "Build and sign the .apk (no Gradle: aapt2, javac, d8, zipalign, apksigner)" + env: + KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_B64 }} + KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + run: | + tools=$(ls -d "$ANDROID_HOME"/build-tools/34.* 2>/dev/null | sort -V | tail -n 1) + if [ -z "$tools" ]; then tools=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -n 1); fi + platform="$ANDROID_HOME/platforms/android-34" + if [ ! -f "$platform/android.jar" ]; then platform=$(ls -d "$ANDROID_HOME"/platforms/android-* | sort -V | tail -n 1); fi + export ANDROID_BUILD_TOOLS="$tools" ANDROID_JAR="$platform/android.jar" + echo "build-tools: $tools, platform: $platform" + if [ -n "$KEYSTORE_B64" ]; then + echo "$KEYSTORE_B64" | base64 -d > "$RUNNER_TEMP/release.p12" + printf '%s' "$KEYSTORE_PASSWORD" > "$RUNNER_TEMP/release-password.txt" + python3 apps/gamelib/android/build.py --keystore "$RUNNER_TEMP/release.p12" --password-file "$RUNNER_TEMP/release-password.txt" --alias shells + echo "SIGNED=release" >> "$GITHUB_ENV" + else + echo "::warning::No signing key secret here (a pull request from a fork): signed with a throwaway key." + python3 apps/gamelib/android/build.py + echo "SIGNED=throwaway" >> "$GITHUB_ENV" + fi + echo "APKSIGNER=$tools/apksigner" >> "$GITHUB_ENV" + + - name: The certificate is the one app.json names + if: env.SIGNED == 'release' + run: | + expected=$(python3 -c "import json; print(json.load(open('apps/gamelib/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs apps/gamelib/android/dist/GameLibrary-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd apps/gamelib/android/dist && sha256sum GameLibrary-android.apk > GameLibrary-android.apk.sha256 && cat GameLibrary-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: gamelib-android + path: apps/gamelib/android/dist/ + if-no-files-found: error + + emulator: + needs: build + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: gamelib-android + path: apps/gamelib/android/dist + - name: Enable KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + - name: Open the app on an emulator and check it stays up + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 34 + target: google_apis + arch: x86_64 + profile: pixel_6 + disable-animations: true + emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -camera-back none + script: python3 apps/gamelib/android/smoke.py apps/gamelib/android/dist/GameLibrary-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: gamelib-android-emulator-check + path: | + apps/gamelib/android/dist/*.png + apps/gamelib/android/dist/android-logcat.txt + retention-days: 7 + + publish: + needs: [build, emulator] + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: gamelib-android + path: dist + # The gamelib-android release keeps one address for the download. The file there is replaced only when + # apps/gamelib/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the gamelib-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('apps/gamelib/android/app.json'))['versionName'])") + echo "$version" > dist/GameLibrary-android.version.txt + if ! gh release view gamelib-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "Game Library for Android: a full-screen window around the web app (https://juw12.github.io/projects/gamelib/)." "" \ + "Download [GameLibrary-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/gamelib-android/GameLibrary-android.apk), open the file on the phone and allow \"install unknown apps\" for your browser once." \ + "It is not from a store: Android asks before it installs." > notes.md + gh release create gamelib-android dist/GameLibrary-android.apk dist/GameLibrary-android.apk.sha256 dist/GameLibrary-android.version.txt \ + --title "Game Library for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the gamelib-android release with GameLibrary-android.apk $version" + exit 0 + fi + published=$(gh release download gamelib-android --repo "$GITHUB_REPOSITORY" --pattern GameLibrary-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the gamelib-android release already has GameLibrary-android.apk $version" + exit 0 + fi + gh release upload gamelib-android dist/GameLibrary-android.apk dist/GameLibrary-android.apk.sha256 dist/GameLibrary-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "GameLibrary-android.apk on the gamelib-android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/gamelib-desktop.yml b/.github/workflows/gamelib-desktop.yml new file mode 100644 index 00000000..fd226cce --- /dev/null +++ b/.github/workflows/gamelib-desktop.yml @@ -0,0 +1,177 @@ +name: GameLibrary apps + +# Builds the downloadable GameLibrary apps and publishes them to the "gamelib-desktop" release from main: +# Windows GameLibrary-Windows-Setup.exe (per-user installer) + GameLibrary-Windows-Portable.zip +# macOS GameLibrary-macOS-AppleSilicon.dmg + GameLibrary-macOS-Intel.dmg +# The apps are thin native windows around the live site, so every push to the site reaches them through GitHub +# Pages without a rebuild. This workflow only runs when the shell in desktop/ changes. Every build is opened and +# checked on its own system first; only builds that passed are published, and the download links never change. +on: + push: + branches: [main] + paths: + - 'apps/gamelib/desktop/**' + - '.github/workflows/gamelib-desktop.yml' + pull_request: + paths: + - 'apps/gamelib/desktop/**' + - '.github/workflows/gamelib-desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: gamelib-desktop-${{ github.ref }} + cancel-in-progress: true + +jobs: + desktop: + name: Desktop (${{ matrix.name }}) + strategy: + fail-fast: false + matrix: + include: + - name: Windows + os: windows-latest + - name: macOS Apple silicon + os: macos-15 + - name: macOS Intel + os: macos-15-intel + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install PyInstaller, Pillow and pywebview + run: python -m pip install --disable-pip-version-check pyinstaller pillow pywebview + - name: Install Inno Setup + if: runner.os == 'Windows' + shell: pwsh + run: | + $iscc = Join-Path ${env:ProgramFiles(x86)} 'Inno Setup 6\ISCC.exe' + if (-not (Test-Path $iscc) -and -not (Get-Command iscc -ErrorAction SilentlyContinue)) { + choco install innosetup --no-progress -y + } + - name: Make sure the WebView2 runtime is there (the Windows window uses it) + if: runner.os == 'Windows' + shell: pwsh + run: | + $client = '{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' + $keys = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\$client", + "HKCU:\Software\Microsoft\EdgeUpdate\Clients\$client" + $version = $keys | Where-Object { Test-Path $_ } | ForEach-Object { (Get-ItemProperty $_).pv } | + Where-Object { $_ -and $_ -ne '0.0.0.0' } | Select-Object -First 1 + if ($version) { Write-Host "WebView2 runtime $version"; exit 0 } + $setup = Join-Path $env:RUNNER_TEMP 'MicrosoftEdgeWebview2Setup.exe' + Invoke-WebRequest 'https://go.microsoft.com/fwlink/p/?LinkId=2124703' -OutFile $setup + Start-Process -FilePath $setup -ArgumentList '/silent', '/install' -Wait + - name: Stop XProtect scans (they make hdiutil fail with "Resource busy") + if: runner.os == 'macOS' + run: | + sudo pkill -9 XProtect > /dev/null 2>&1 || true + for attempt in $(seq 1 20); do pgrep -x XProtect > /dev/null || break; sleep 3; done + - name: Build and package + run: python apps/gamelib/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's GameLibrary + run: python apps/gamelib/desktop/smoke_test.py --built --local-site + - name: Install with GameLibrary-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'apps/gamelib/desktop/dist/GameLibrary-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'gamelib-setup.log' + $process = Start-Process -FilePath $setup -Wait -PassThru -ArgumentList @( + '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/TASKS=desktopicon', "/LOG=$log") + if ($process.ExitCode -ne 0) { Get-Content $log -Tail 40; throw "Setup failed with exit code $($process.ExitCode)" } + $app = Join-Path $env:LOCALAPPDATA 'Programs\GameLibrary\GameLibrary.exe' + if (-not (Test-Path $app)) { throw "GameLibrary.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'GameLibrary.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'GameLibrary.lnk')) + foreach ($link in $shortcuts) { if (-not (Test-Path $link)) { throw "Missing shortcut: $link" } } + $entry = Get-ChildItem 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall' | + Get-ItemProperty | Where-Object DisplayName -eq 'GameLibrary' + if (-not $entry) { throw 'GameLibrary is missing from Settings > Apps' } + python apps/gamelib/desktop/smoke_test.py --local-site $app + if ($LASTEXITCODE -ne 0) { throw 'The installed app failed its checks' } + Start-Process -FilePath $entry.UninstallString.Trim('"') -Wait -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART' + for ($i = 0; $i -lt 60 -and (Test-Path $app); $i++) { Start-Sleep -Seconds 1 } + if (Test-Path $app) { throw 'Uninstalling left GameLibrary.exe behind' } + foreach ($link in $shortcuts) { if (Test-Path $link) { throw "Uninstalling left a shortcut: $link" } } + Write-Host 'Installed, ran and uninstalled cleanly' + - name: Check the Mac app and disk image + if: runner.os == 'macOS' + run: | + APP=apps/gamelib/desktop/dist/GameLibrary.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.gamelib.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("apps/gamelib/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/GameLibrary")" + codesign --verify --deep --verbose=2 "$APP" + for image in apps/gamelib/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: GameLibrary-${{ runner.os }}-${{ runner.arch }} + path: apps/gamelib/desktop/dist/GameLibrary-* + if-no-files-found: error + retention-days: 14 + + publish: + needs: [desktop] + if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + pattern: GameLibrary-* + path: dist + merge-multiple: true + - name: Publish the apps to the apps release + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: | + cd dist + FILES="" + for name in GameLibrary-Windows-Setup.exe GameLibrary-Windows-Portable.zip \ + GameLibrary-macOS-AppleSilicon.dmg GameLibrary-macOS-Intel.dmg; do + if [ -f "$name" ]; then + FILES="$FILES $name" + else + echo "::warning::$name was not built in this run; the release keeps its previous copy (if any)." + fi + done + if [ -z "$FILES" ]; then + echo "::error::No app passed its checks." + exit 1 + fi + sha256sum $FILES > SHA256SUMS.txt + cat SHA256SUMS.txt + cat > notes.md <<'EOF' + **Game Library**: a searchable collection of browser games by category. The apps open the same Game Library as https://juw12.github.io/projects/gamelib/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [GameLibrary-Windows-Setup.exe](https://github.com/juw12/projects/releases/download/gamelib-desktop/GameLibrary-Windows-Setup.exe) | Open it and press Install (no admin needed). If Windows says it protected your PC, choose **More info → Run anyway** (the app is not code-signed yet). Without installing: [GameLibrary-Windows-Portable.zip](https://github.com/juw12/projects/releases/download/gamelib-desktop/GameLibrary-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [GameLibrary-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/gamelib-desktop/GameLibrary-macOS-AppleSilicon.dmg) | Open it and drag GameLibrary to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [GameLibrary-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/gamelib-desktop/GameLibrary-macOS-Intel.dmg) | Same as above. Not sure which Mac? Apple menu → About This Mac shows **Chip** (Apple) or **Processor** (Intel). | + | **iPhone / iPad** | [Open in Safari](https://juw12.github.io/projects/gamelib/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [GameLibrary-android.apk](https://github.com/juw12/projects/releases/download/gamelib-android/GameLibrary-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load GameLibrary from the web, so new versions arrive the moment they are published, with no reinstall. Checksums for this build: `SHA256SUMS.txt`. + EOF + { + echo + echo "Built from ${GITHUB_SHA::7}." + } >> notes.md + if gh release view gamelib-desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload gamelib-desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit gamelib-desktop --notes-file notes.md --repo "$REPO" + else + gh release create gamelib-desktop $FILES SHA256SUMS.txt --title "Game Library for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/apps/gamelib/README.md b/apps/gamelib/README.md index 7c2560f7..81bd8497 100644 --- a/apps/gamelib/README.md +++ b/apps/gamelib/README.md @@ -14,6 +14,15 @@ access control: the source and direct game URLs remain public. Browser-only saves belong to the browser origin and do not automatically move from the old `juwpegatron.github.io` website to `juw12.github.io`. +## Get it on your device + +- **Windows:** [`GameLibrary-Windows-Setup.exe`](https://github.com/juw12/projects/releases/download/gamelib-desktop/GameLibrary-Windows-Setup.exe) (no admin needed; if Windows says it protected your PC, choose *More info → Run anyway*), or without installing [`GameLibrary-Windows-Portable.zip`](https://github.com/juw12/projects/releases/download/gamelib-desktop/GameLibrary-Windows-Portable.zip). +- **Mac:** [`GameLibrary-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/gamelib-desktop/GameLibrary-macOS-AppleSilicon.dmg) (M1 and newer) or [`GameLibrary-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/gamelib-desktop/GameLibrary-macOS-Intel.dmg). The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`GameLibrary-android.apk`](https://github.com/juw12/projects/releases/download/gamelib-android/GameLibrary-android.apk): open the file on the phone and allow your browser to install apps once. +- **iPhone:** open https://juw12.github.io/projects/gamelib/ in Safari, tap Share, then **Add to Home Screen**. + +The Windows, Mac and Android apps are the web app in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. Each build is opened on GitHub's machines before it is published: on Windows and on a Mac the page loads, the app starts and can store data; on an Android emulator it installs, opens and stays up. They are not code-signed or notarised, and no real phone or PC has run them yet. + ## Sharp canvases on 2x and 3x screens Most games draw into a canvas of a fixed size (for example 900 x 480) that the browser stretches over a diff --git a/apps/gamelib/android/.gitignore b/apps/gamelib/android/.gitignore new file mode 100644 index 00000000..edd9d60a --- /dev/null +++ b/apps/gamelib/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/apps/gamelib/android/AndroidManifest.xml b/apps/gamelib/android/AndroidManifest.xml new file mode 100644 index 00000000..a84845a4 --- /dev/null +++ b/apps/gamelib/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/apps/gamelib/android/README.md b/apps/gamelib/android/README.md new file mode 100644 index 00000000..7456b855 --- /dev/null +++ b/apps/gamelib/android/README.md @@ -0,0 +1,34 @@ +# Game Library for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/projects/gamelib/): the same Game Library a phone +opens in its browser, with its own icon and no address bar. `MainActivity.java` adds what a plain WebView lacks: +Share, saving a file to Downloads, picking a file, and links to other sites opening in the browser. Because it +loads the live web app, every change to the site reaches the installed app on its next start; only a change to +this folder needs a new .apk. + +Get it: [`GameLibrary-android.apk`](https://github.com/juw12/projects/releases/download/gamelib-android/GameLibrary-android.apk). Open the file on the phone and allow "install unknown apps" for your browser once. + +| File | What it is | +| --- | --- | +| `app.json` | name, package id, version (raise `versionCode` and `versionName` when this folder changes), and the SHA-256 of the signing certificate | +| `AndroidManifest.xml`, `res/`, `assets/offline.html` | the app's manifest, icon and colours, the page shown when the first start has no connection | +| `src/.../MainActivity.java` | the whole program (the shell Jeda, Teduh, EarlyStar and Cairn use) | +| `build.py` | builds and signs the .apk without Gradle: aapt2, javac, d8, zipalign, apksigner | +| `smoke.py` | installs the .apk on an emulator, opens it and checks it stays up | + +``` +JAVA_HOME= ANDROID_BUILD_TOOLS= ANDROID_JAR=/android.jar \ + python apps/gamelib/android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/gamelib-android.yml` does this on GitHub: it signs with the key in the repository's secrets, +checks the certificate is the one named in `app.json`, opens the app on an Android 14 emulator, and puts +`GameLibrary-android.apk` on the `gamelib-android` release. The file there is replaced only when `versionName` in `app.json` is a +new one. + +The signing key is not in this repository (its backup is the private `juw12/web-shells-signing`). Without `--keystore` +the build signs with a throwaway key, which is enough to try the app on your own phone. + +Not checked: a real phone, and anything in the page that needs the camera, the microphone or a sign-in window +of another site. The emulator check cannot read the page inside a release build; it checks that the app +installs, opens its own window, stays up and does not crash, and keeps a screenshot. diff --git a/apps/gamelib/android/app.json b/apps/gamelib/android/app.json new file mode 100644 index 00000000..91846201 --- /dev/null +++ b/apps/gamelib/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "GameLibrary", + "id": "io.github.juw12.gamelib", + "url": "https://juw12.github.io/projects/gamelib/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/apps/gamelib/android/assets/offline.html b/apps/gamelib/android/assets/offline.html new file mode 100644 index 00000000..2240b2c3 --- /dev/null +++ b/apps/gamelib/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + Game Library + + + +
+ +

Game Library can't reach the internet

+

Game Library needs a connection the first time it opens. After that it also opens offline. Check your connection and try again.

+ Try again +
+ + diff --git a/apps/gamelib/android/build.py b/apps/gamelib/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/apps/gamelib/android/build.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Build the Android app in this folder without Gradle: aapt2, javac, d8, zipalign, apksigner. + + python android/build.py --keystore PATH.p12 --password-file PATH.txt [--alias NAME] + +Needs three things, named by environment variables: + JAVA_HOME a JDK 17 (https://adoptium.net) + ANDROID_BUILD_TOOLS the folder of Android build-tools 34 (aapt2, d8, zipalign, apksigner) + ANDROID_JAR android.jar of platform 34 +Without --keystore the app is signed with a throwaway key: fine to try on your own phone, useless as +an update of the published app. The result is android/dist/-android.apk. +""" +import argparse +import json +import os +import shutil +import subprocess +import sys +import zipfile + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def run(*command): + print("+", " ".join(os.path.basename(part) if index == 0 else part for index, part in enumerate(command)), flush=True) + subprocess.run(command, check=True) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--keystore") + parser.add_argument("--password-file") + parser.add_argument("--alias", default="release") + args = parser.parse_args() + for name in ("JAVA_HOME", "ANDROID_BUILD_TOOLS", "ANDROID_JAR"): + if not os.environ.get(name): + raise SystemExit("Set %s (see the top of this file)" % name) + java_bin = os.path.join(os.environ["JAVA_HOME"], "bin") + tools = os.environ["ANDROID_BUILD_TOOLS"] + android_jar = os.environ["ANDROID_JAR"] + os.environ["PATH"] = java_bin + os.pathsep + os.environ["PATH"] + with open(os.path.join(HERE, "app.json"), encoding="utf-8") as handle: + app = json.load(handle) + + work = os.path.join(HERE, "build") + dist = os.path.join(HERE, "dist") + shutil.rmtree(work, ignore_errors=True) + for folder in ("gen", "classes", "dex"): + os.makedirs(os.path.join(work, folder)) + os.makedirs(dist, exist_ok=True) + + resources = os.path.join(work, "resources.zip") + run(os.path.join(tools, "aapt2"), "compile", "--dir", os.path.join(HERE, "res"), "-o", resources) + unsigned = os.path.join(work, "unsigned.apk") + run(os.path.join(tools, "aapt2"), "link", "-o", unsigned, "-I", android_jar, + "--manifest", os.path.join(HERE, "AndroidManifest.xml"), "--java", os.path.join(work, "gen"), + "-A", os.path.join(HERE, "assets"), + "--min-sdk-version", str(app["minSdk"]), "--target-sdk-version", str(app["targetSdk"]), + "--version-code", str(app["versionCode"]), "--version-name", app["versionName"], resources) + + sources = [] + for root in (os.path.join(HERE, "src"), os.path.join(work, "gen")): + for folder, _, files in os.walk(root): + sources += [os.path.join(folder, name) for name in files if name.endswith(".java")] + run(os.path.join(java_bin, "javac"), "-source", "8", "-target", "8", "-Xlint:-options", "-bootclasspath", android_jar, + "-d", os.path.join(work, "classes"), *sources) + classes = [] + for folder, _, files in os.walk(os.path.join(work, "classes")): + classes += [os.path.join(folder, name) for name in files if name.endswith(".class")] + run(os.path.join(tools, "d8"), "--release", "--lib", android_jar, "--min-api", str(app["minSdk"]), + "--output", os.path.join(work, "dex"), *classes) + with zipfile.ZipFile(unsigned, "a", zipfile.ZIP_DEFLATED) as archive: + archive.write(os.path.join(work, "dex", "classes.dex"), "classes.dex") + + aligned = os.path.join(work, "aligned.apk") + run(os.path.join(tools, "zipalign"), "-f", "-p", "4", unsigned, aligned) + keystore, password_file, alias = args.keystore, args.password_file, args.alias + if not keystore: + keystore = os.path.join(work, "throwaway.p12") + password_file = os.path.join(work, "throwaway.txt") + alias = "throwaway" + with open(password_file, "w", encoding="utf-8") as handle: + handle.write("throwaway-key") + run(os.path.join(java_bin, "keytool"), "-genkeypair", "-keystore", keystore, "-storetype", "PKCS12", + "-storepass:file", password_file, "-alias", alias, "-keyalg", "RSA", "-keysize", "2048", + "-validity", "30", "-dname", "CN=throwaway") + print("No --keystore: signed with a throwaway key.") + result = os.path.join(dist, "%s-android.apk" % app["name"]) + run(os.path.join(tools, "apksigner"), "sign", "--ks", keystore, "--ks-type", "PKCS12", "--ks-key-alias", alias, + "--ks-pass", "file:" + password_file, "--out", result, aligned) + run(os.path.join(tools, "apksigner"), "verify", "--verbose", "--print-certs", result) + if os.path.exists(result + ".idsig"): + os.remove(result + ".idsig") + print("Built %s (%d bytes)" % (result, os.path.getsize(result))) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/apps/gamelib/android/res/mipmap-xxxhdpi/ic_launcher.png b/apps/gamelib/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..34a47585 Binary files /dev/null and b/apps/gamelib/android/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/apps/gamelib/android/res/values/styles.xml b/apps/gamelib/android/res/values/styles.xml new file mode 100644 index 00000000..ac168c7a --- /dev/null +++ b/apps/gamelib/android/res/values/styles.xml @@ -0,0 +1,9 @@ + + + #0f0f11 + + diff --git a/apps/gamelib/android/smoke.py b/apps/gamelib/android/smoke.py new file mode 100644 index 00000000..3b44f4e9 --- /dev/null +++ b/apps/gamelib/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the GameLibrary APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/GameLibrary-android.apk + +The app is a release build, so the page inside cannot be read from outside. This checks what can be: +the package installs, the window is the app's, the process is still there after 25 s, the shell's own log +says the live page finished loading, and nothing crashed. +A screenshot (android-emulator.png) is saved next to the APK to look at. Needs adb on PATH. +""" + +import json +import os +import subprocess +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def adb(*args, check=True): + try: + result = subprocess.run(["adb", *args], capture_output=True, text=True, timeout=180) + except subprocess.TimeoutExpired: + # A busy emulator can take minutes over the whole log. Where the answer is only read (check=False) + # an empty one is enough: the checks above decide, not the dump. + if check: + raise + return "" + if check and result.returncode != 0: + raise SystemExit("adb %s failed: %s" % (" ".join(args), result.stderr.strip())) + return result.stdout + + +def main(): + apk = os.path.abspath(sys.argv[1]) + out = os.path.dirname(apk) + with open(os.path.join(HERE, "app.json"), encoding="utf-8") as handle: + app = json.load(handle) + package, site, shell_tag = app["id"], app["url"], app["name"] + "Shell" + failures = [] + + def check(condition, label): + print((" ok " if condition else " FAIL ") + label, flush=True) + if not condition: + failures.append(label) + + adb("wait-for-device") + # A freshly started emulator answers adb before it can look up a name: wait until it can, so a slow + # emulator is not mistaken for an app that cannot reach its site. + host = site.split("/")[2] + for _ in range(30): + # An emulator answers no ping from outside; "PING name (address)" is enough: the name was looked up. + if adb("shell", "ping", "-c", "1", "-W", "2", host, check=False).startswith("PING "): + break + time.sleep(3) + adb("install", "-r", apk) + adb("logcat", "-c", check=False) + adb("shell", "am", "start", "-W", "-n", package + "/.MainActivity") + + first = "" + for _ in range(30): + first = adb("shell", "pidof", package, check=False).strip() + if first: + break + time.sleep(1) + check(bool(first), "the app started (pid %s)" % (first or "-")) + time.sleep(25) + later = adb("shell", "pidof", package, check=False).strip() + check(bool(later) and later == first, "the same process is still there after 25 s (pid %s)" % (later or "-")) + focus = adb("shell", "dumpsys", "window", check=False) + focused = [line.strip() for line in focus.splitlines() if "mCurrentFocus" in line or "mFocusedApp" in line] + check(any(package in line for line in focused), "its window is in front (%s)" % (focused[0] if focused else "no focus line")) + # The shell says in the log which page finished loading, and when one did not load. + said = [line for line in adb("logcat", "-d", "-v", "brief", "-s", shell_tag, check=False).splitlines() if shell_tag in line] + finished = [line.split("page finished: ", 1)[1].strip() for line in said if "page finished: " in line] + refused = [line.split("did not load: ", 1)[1].strip() for line in said if "did not load: " in line] + check(any(page.startswith(site) for page in finished), "the live page finished loading (%s)" % (finished[-1] if finished else "nothing finished")) + check(not refused, "no page failed to load (%s)" % (refused[-1] if refused else "none")) + with open(os.path.join(out, "android-emulator.png"), "wb") as handle: + handle.write(subprocess.run(["adb", "exec-out", "screencap", "-p"], capture_output=True, timeout=60).stdout) + crashes = [line for line in adb("logcat", "-d", "-b", "crash", check=False).splitlines() if package in line] + check(not crashes, "no crash in logcat") + + log = adb("logcat", "-d", "-v", "brief", check=False) + with open(os.path.join(out, "android-logcat.txt"), "w", encoding="utf-8") as handle: + handle.write(log) + if failures: + # What the phone said about the app, so a failed run can be understood from its log. + words = (package, "AndroidRuntime", "FATAL", "Killing", "has died", "WebViewFactory", "chromium", "ActivityTaskManager: Displayed") + told = [line for line in log.splitlines() if any(word in line for word in words)] + print("\nfrom logcat (%d lines about the app, the last 50):" % len(told)) + for line in told[-50:]: + print(" " + line[:220]) + print("\n%d check(s) failed" % len(failures)) + sys.exit(1) + print("\nGameLibrary for Android installs, opens and stays up") + + +def killed_with_play_services(folder): + """True when Android ended the app because Google Play services restarted under it. + + A freshly started emulator updates Play services in its first minutes. The WebView holds Play + services' font provider, so Android ends every app that does when Play services goes down. That + says nothing about the app, and the next start stays up. + """ + try: + with open(os.path.join(folder, "android-logcat.txt"), encoding="utf-8") as handle: + log = handle.read() + except OSError: + return False + with open(os.path.join(HERE, "app.json"), encoding="utf-8") as handle: + package = json.load(handle)["id"] + return any("Killing" in line and package in line and "com.google.android.gms" in line for line in log.splitlines()) + + +if __name__ == "__main__": + for attempt in (1, 2, 3): + try: + main() + break + except SystemExit as stopped: + folder = os.path.dirname(os.path.abspath(sys.argv[1])) + if not stopped.code or attempt == 3 or not killed_with_play_services(folder): + raise + print("\nAndroid ended the app because Google Play services restarted on this new emulator. " + "Trying again (%d of 3).\n" % (attempt + 1), flush=True) + time.sleep(20) diff --git a/apps/gamelib/android/src/io/github/juw12/gamelib/MainActivity.java b/apps/gamelib/android/src/io/github/juw12/gamelib/MainActivity.java new file mode 100644 index 00000000..493bd64f --- /dev/null +++ b/apps/gamelib/android/src/io/github/juw12/gamelib/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.gamelib; + +import android.Manifest; +import android.app.Activity; +import android.content.ContentValues; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.provider.MediaStore; +import android.util.Base64; +import android.webkit.GeolocationPermissions; +import android.webkit.JavascriptInterface; +import android.webkit.ValueCallback; +import android.webkit.WebChromeClient; +import android.webkit.WebResourceError; +import android.webkit.WebResourceRequest; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.Toast; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; + +/** + * GameLibrary for Android: one full-screen window around the live web app. The page keeps its own data + * (the WebView's storage), works offline after the first visit (its service worker), and gets what + * a plain WebView lacks from this class: sharing, saving files, picking files, location, and links + * to other sites opening in the browser. + */ +public class MainActivity extends Activity { + private static final String START_URL = "https://juw12.github.io/projects/gamelib/"; + private static final String SCOPE = "juw12.github.io/projects/gamelib"; + private static final String SHELL_VERSION = "1.0.0"; + private static final int REQUEST_LOCATION = 7; + private static final int REQUEST_FILE = 8; + + // Runs in the page: Android's WebView has no navigator.share and cannot save blob: downloads. + private static final String PAGE_SCRIPT = "(function(){" + + "if(window.__androidShell){return;}window.__androidShell=true;" + + "if(!navigator.share){" + + "navigator.share=function(d){d=d||{};" + + "if(d.files&&d.files.length){return Promise.reject(new DOMException('Files cannot be shared here','NotSupportedError'));}" + + "AndroidShell.share(String(d.title||''),String(d.text||''),String(d.url||''));return Promise.resolve();};" + + "navigator.canShare=function(d){return !(d&&d.files&&d.files.length);};}" + + "function save(a){var href=String(a.href||'');" + + "if(!a.hasAttribute('download')||(href.indexOf('blob:')!==0&&href.indexOf('data:')!==0)){return false;}" + + "var name=a.getAttribute('download')||'download';" + + "fetch(href).then(function(r){return r.blob();}).then(function(b){var reader=new FileReader();" + + "reader.onload=function(){var s=String(reader.result);" + + "AndroidShell.saveFile(name,b.type||'application/octet-stream',s.slice(s.indexOf(',')+1));};" + + "reader.readAsDataURL(b);}).catch(function(){});return true;}" + + "var click=HTMLAnchorElement.prototype.click;" + + "HTMLAnchorElement.prototype.click=function(){if(!save(this)){click.call(this);}};" + + "document.addEventListener('click',function(e){" + + "var a=e.target&&e.target.closest?e.target.closest('a[download]'):null;" + + "if(a&&e.isTrusted&&save(a)){e.preventDefault();}},true);" + + "})();"; + + private WebView web; + private ValueCallback fileCallback; + private GeolocationPermissions.Callback locationCallback; + private String locationOrigin; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + web = new WebView(this); + web.setBackgroundColor(getResources().getColor(R.color.background)); + setContentView(web); + + WebSettings settings = web.getSettings(); + settings.setJavaScriptEnabled(true); + settings.setDomStorageEnabled(true); + settings.setDatabaseEnabled(true); + settings.setGeolocationEnabled(true); + settings.setMediaPlaybackRequiresUserGesture(false); + settings.setSupportMultipleWindows(false); + settings.setUserAgentString(settings.getUserAgentString() + " GameLibraryAndroid/" + SHELL_VERSION); + web.addJavascriptInterface(new Bridge(), "AndroidShell"); + + web.setWebViewClient(new WebViewClient() { + @Override + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { + Uri uri = request.getUrl(); + String scheme = uri.getScheme() == null ? "" : uri.getScheme(); + if (scheme.equals("file") || scheme.equals("about") || scheme.equals("blob") || scheme.equals("data")) { + return false; + } + String place = (uri.getHost() == null ? "" : uri.getHost()) + (uri.getPath() == null ? "" : uri.getPath()); + if (scheme.equals("https") && (place.equals(SCOPE) || place.startsWith(SCOPE + "/"))) { + return false; + } + openOutside(uri); + return true; + } + + @Override + public void onPageFinished(WebView view, String url) { + android.util.Log.i("GameLibraryShell", "page finished: " + url); + view.evaluateJavascript(PAGE_SCRIPT, null); + } + + @Override + public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { + if (request.isForMainFrame()) { + // Said in the phone's log, so "no connection" can be told from a page that would not load. + android.util.Log.w("GameLibraryShell", "the page did not load: " + error.getErrorCode() + " " + error.getDescription() + " " + request.getUrl()); + view.loadUrl("file:///android_asset/offline.html"); + } + } + }); + + web.setWebChromeClient(new WebChromeClient() { + @Override + public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { + boolean allowed = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED + || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; + if (allowed) { + callback.invoke(origin, true, false); + return; + } + locationOrigin = origin; + locationCallback = callback; + requestPermissions(new String[] { + Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, + }, REQUEST_LOCATION); + } + + @Override + public boolean onShowFileChooser(WebView view, ValueCallback callback, FileChooserParams params) { + if (fileCallback != null) { + fileCallback.onReceiveValue(null); + } + fileCallback = callback; + try { + startActivityForResult(params.createIntent(), REQUEST_FILE); + } catch (Exception error) { + fileCallback = null; + callback.onReceiveValue(null); + } + return true; + } + }); + + if (savedInstanceState == null || web.restoreState(savedInstanceState) == null) { + web.loadUrl(START_URL); + } + } + + private void openOutside(Uri uri) { + try { + startActivity(new Intent(Intent.ACTION_VIEW, uri)); + } catch (Exception error) { + Toast.makeText(this, "No app can open this link", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) { + super.onRequestPermissionsResult(requestCode, permissions, results); + if (requestCode != REQUEST_LOCATION || locationCallback == null) { + return; + } + boolean granted = false; + for (int result : results) { + granted = granted || result == PackageManager.PERMISSION_GRANTED; + } + locationCallback.invoke(locationOrigin, granted, false); + locationCallback = null; + locationOrigin = null; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == REQUEST_FILE && fileCallback != null) { + fileCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data)); + fileCallback = null; + } + } + + @Override + public void onBackPressed() { + if (web.canGoBack()) { + web.goBack(); + } else { + super.onBackPressed(); + } + } + + @Override + protected void onSaveInstanceState(Bundle state) { + super.onSaveInstanceState(state); + web.saveState(state); + } + + @Override + protected void onPause() { + web.onPause(); + super.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + web.onResume(); + } + + @Override + protected void onDestroy() { + web.destroy(); + super.onDestroy(); + } + + /** Called from the page (PAGE_SCRIPT). Methods arrive on a background thread. */ + public class Bridge { + @JavascriptInterface + public String version() { + return SHELL_VERSION; + } + + @JavascriptInterface + public void share(final String title, final String text, final String url) { + runOnUiThread(new Runnable() { + @Override + public void run() { + String body = text.isEmpty() ? url : (url.isEmpty() ? text : text + "\n" + url); + Intent send = new Intent(Intent.ACTION_SEND); + send.setType("text/plain"); + send.putExtra(Intent.EXTRA_TEXT, body); + if (!title.isEmpty()) { + send.putExtra(Intent.EXTRA_SUBJECT, title); + } + try { + startActivity(Intent.createChooser(send, title.isEmpty() ? null : title)); + } catch (Exception error) { + Toast.makeText(MainActivity.this, "Nothing to share with", Toast.LENGTH_SHORT).show(); + } + } + }); + } + + @JavascriptInterface + public void saveFile(String name, String mime, String base64) { + String safeName = name.replaceAll("[\\\\/:*?\"<>|]", "_"); + String message; + try { + byte[] bytes = Base64.decode(base64, Base64.DEFAULT); + if (Build.VERSION.SDK_INT >= 29) { + ContentValues values = new ContentValues(); + values.put(MediaStore.MediaColumns.DISPLAY_NAME, safeName); + values.put(MediaStore.MediaColumns.MIME_TYPE, mime); + values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS); + Uri target = getContentResolver().insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values); + OutputStream stream = getContentResolver().openOutputStream(target); + stream.write(bytes); + stream.close(); + message = "Saved to Downloads: " + safeName; + } else { + File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), safeName); + FileOutputStream stream = new FileOutputStream(file); + stream.write(bytes); + stream.close(); + message = "Saved: " + file.getAbsolutePath(); + } + } catch (Exception error) { + message = "Could not save " + safeName; + } + final String shown = message; + runOnUiThread(new Runnable() { + @Override + public void run() { + Toast.makeText(MainActivity.this, shown, Toast.LENGTH_LONG).show(); + } + }); + } + } +} diff --git a/apps/gamelib/desktop/.gitignore b/apps/gamelib/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/apps/gamelib/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/apps/gamelib/desktop/README.md b/apps/gamelib/desktop/README.md new file mode 100644 index 00000000..dd8a6a7a --- /dev/null +++ b/apps/gamelib/desktop/README.md @@ -0,0 +1,25 @@ +# GameLibrary for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/gamelib/): Microsoft Edge WebView2 on Windows, the system +WebKit on macOS, both through [pywebview](https://pywebview.flowrl.com/). The window keeps its own browser data +(what you saved in it), so it is all still there the next time GameLibrary opens. Because it loads the live +site, every push to `main` reaches the installed app on its next start; only a change to this folder needs a new build. + +| File | What it is | +| --- | --- | +| `gamelib_app.py` | the program: one window, remembers its size, a second start brings the open window forward | +| `shell.json` | the shell's version (bump it when this folder changes) | +| `build.py` | builds the app for the system it runs on | +| `gamelib.spec`, `gamelib.iss` | PyInstaller recipe, Windows installer (Inno Setup 6, per user, no admin rights) | +| `smoke_test.py` | opens the built app and checks its window shows GameLibrary | +| `offline.html` | shown when the site cannot be reached on the very first start | + +``` +python -m pip install pyinstaller pillow pywebview +python desktop/build.py +python desktop/smoke_test.py --built --local-site +``` + +`.github/workflows/gamelib-desktop.yml` does the same on Windows, an Apple-chip Mac and an Intel Mac, installs and uninstalls +the Windows setup, and publishes the files that passed to the +[gamelib-desktop release](https://github.com/juw12/projects/releases/tag/gamelib-desktop). The download links never change. diff --git a/apps/gamelib/desktop/build.py b/apps/gamelib/desktop/build.py new file mode 100644 index 00000000..688768f9 --- /dev/null +++ b/apps/gamelib/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the GameLibrary desktop app for the system this runs on (Windows or macOS). + + python -m pip install pyinstaller pillow pywebview + python desktop/build.py [--require-installer] + +Output in desktop/dist/ (the names the "apps" GitHub release uses): + Windows GameLibrary-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + GameLibrary-Windows-Portable.zip unzip and run GameLibrary.exe + macOS GameLibrary-macOS-AppleSilicon.dmg or GameLibrary-macOS-Intel.dmg (the chip of this Mac) +""" + +import argparse +import json +import os +import platform +import shutil +import subprocess +import sys +import time +import zipfile + +DESKTOP = os.path.dirname(os.path.abspath(__file__)) +APP = os.path.dirname(DESKTOP) +BUILD = os.path.join(DESKTOP, "build") +DIST = os.path.join(DESKTOP, "dist") +ICON_SOURCE = os.path.join(APP, *"desktop/icon-512.png".split("/")) + +WINDOWS_VERSION_INFO = """VSVersionInfo( + ffi=FixedFileInfo(filevers={numbers}, prodvers={numbers}, mask=0x3f, flags=0x0, OS=0x40004, + fileType=0x1, subtype=0x0, date=(0, 0)), + kids=[ + StringFileInfo([StringTable('040904B0', [ + StringStruct('CompanyName', 'Juwen Lie'), + StringStruct('FileDescription', 'GameLibrary - A searchable collection of browser games by category'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'GameLibrary'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'GameLibrary.exe'), + StringStruct('ProductName', 'GameLibrary'), + StringStruct('ProductVersion', '{version}')])]), + VarFileInfo([VarStruct('Translation', [1033, 1200])]) + ] +) +""" + + +def read_version(): + """The desktop shell's version: desktop/shell.json (the built app carries the same file).""" + with open(os.path.join(DESKTOP, "shell.json"), encoding="utf-8") as handle: + return json.load(handle)["version"] + + +def make_icon(): + """The app icon from the app's 512 px PNG: .ico on Windows, the PNG itself on macOS.""" + if sys.platform != "win32": + return ICON_SOURCE + from PIL import Image + + target = os.path.join(BUILD, "gamelib.ico") + with Image.open(ICON_SOURCE) as image: + image.convert("RGBA").save(target, sizes=[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]) + return target + + +def run_pyinstaller(version, icon): + env = dict(os.environ, GAMELIB_VERSION=version, GAMELIB_ICON=icon) + if sys.platform == "win32": + numbers = tuple(int(part) for part in (version.split(".") + ["0", "0", "0"])[:4]) + version_file = os.path.join(BUILD, "version_info.txt") + with open(version_file, "w", encoding="utf-8") as handle: + handle.write(WINDOWS_VERSION_INFO.format(numbers=numbers, version=version)) + env["GAMELIB_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "gamelib.spec"), + ], + check=True, + env=env, + ) + + +def zip_folder(folder, archive, root_name): + with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as bundle: + for current, _dirs, files in os.walk(folder): + for name in files: + full = os.path.join(current, name) + bundle.write(full, os.path.join(root_name, os.path.relpath(full, folder))) + + +def find_iscc(): + candidates = [ + shutil.which("iscc"), + os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Inno Setup 6", "ISCC.exe"), + os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Inno Setup 6", "ISCC.exe"), + os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs", "Inno Setup 6", "ISCC.exe"), + ] + return next((path for path in candidates if path and os.path.isfile(path)), None) + + +def package_windows(version, icon, require_installer): + folder = os.path.join(DIST, "GameLibrary") + portable = os.path.join(DIST, "GameLibrary-Windows-Portable.zip") + zip_folder(folder, portable, "GameLibrary") + made = [portable] + iscc = find_iscc() + if not iscc: + if require_installer: + raise SystemExit("Inno Setup 6 (ISCC.exe) was not found - install it to build GameLibrary-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped GameLibrary-Windows-Setup.exe (the portable zip was built)") + return made + subprocess.run( + [iscc, "/Qp", "/DAppVersion=" + version, "/DSourceDir=" + folder, "/DOutputDir=" + DIST, + "/DIconFile=" + icon, os.path.join(DESKTOP, "gamelib.iss")], + check=True, + ) + return [os.path.join(DIST, "GameLibrary-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "GameLibrary.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "GameLibrary-macOS-%s.dmg" % chip) + stage = os.path.join(BUILD, "dmg") + shutil.rmtree(stage, ignore_errors=True) + os.makedirs(stage) + subprocess.run(["ditto", app, os.path.join(stage, "GameLibrary.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "GameLibrary", "-srcfolder", stage, "-ov", "-format", "UDZO", image] + # hdiutil sometimes fails with "Resource busy" while macOS scans the new volume (common on CI runners). + for attempt in range(1, 6): + if os.path.exists(image): + os.remove(image) + result = subprocess.run(command, capture_output=True, text=True) + if result.returncode == 0: + return [image] + message = (result.stderr or result.stdout).strip() or "exit code %d" % result.returncode + if attempt == 5: + raise SystemExit("hdiutil create failed: %s" % message) + print("hdiutil create failed (%s); trying again in %d s" % (message, 10 * attempt)) + time.sleep(10 * attempt) + return [image] + + +def main(): + parser = argparse.ArgumentParser(description="Build the GameLibrary desktop app for this system") + parser.add_argument("--require-installer", action="store_true", + help="Windows: fail if Inno Setup is missing instead of building only the portable zip") + args = parser.parse_args() + if sys.platform not in ("win32", "darwin"): + raise SystemExit("GameLibrary desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by gamelib.spec) + except ImportError: + raise SystemExit("The GameLibrary window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("GameLibrary", "GameLibrary.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building GameLibrary %s for %s %s" % (version, platform.system(), platform.machine())) + icon = make_icon() + run_pyinstaller(version, icon) + made = package_windows(version, icon, args.require_installer) if sys.platform == "win32" else package_macos() + print("\nBuilt:") + for path in made: + print(" %s (%.1f MB)" % (path, os.path.getsize(path) / 1e6)) + + +if __name__ == "__main__": + main() diff --git a/apps/gamelib/desktop/gamelib.iss b/apps/gamelib/desktop/gamelib.iss new file mode 100644 index 00000000..2b2da930 --- /dev/null +++ b/apps/gamelib/desktop/gamelib.iss @@ -0,0 +1,73 @@ +; GameLibrary for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= gamelib.iss +; Installs to %LOCALAPPDATA%\Programs\GameLibrary, adds GameLibrary to the Start menu (and optionally the desktop) and lists it +; in Settings > Apps. The window keeps its data (what you saved in it) in %LOCALAPPDATA%\GameLibrary, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\GameLibrary" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\gamelib.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=GameLibrary +AppVersion={#AppVersion} +AppVerName=GameLibrary {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/gamelib/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\GameLibrary +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=GameLibrary-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\GameLibrary.exe +UninstallDisplayName=GameLibrary +Compression=lzma2 +SolidCompression=yes +WizardStyle=modern +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +CloseApplications=no +SetupLogging=yes + +[Languages] +Name: "english"; MessagesFile: "compiler:Default.isl" + +[Tasks] +Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}" + +[Files] +Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs + +[Icons] +Name: "{userprograms}\GameLibrary"; Filename: "{app}\GameLibrary.exe"; Comment: "A searchable collection of browser games by category" +Name: "{userdesktop}\GameLibrary"; Filename: "{app}\GameLibrary.exe"; Comment: "A searchable collection of browser games by category"; Tasks: desktopicon + +[Run] +Filename: "{app}\GameLibrary.exe"; Description: "{cm:LaunchProgram,GameLibrary}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\GameLibrary.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopGameLibrary" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open GameLibrary window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\GameLibrary.exe')) then + Exec(ExpandConstant('{app}\GameLibrary.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/apps/gamelib/desktop/gamelib.spec b/apps/gamelib/desktop/gamelib.spec new file mode 100644 index 00000000..27b1e6cf --- /dev/null +++ b/apps/gamelib/desktop/gamelib.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for GameLibrary on Windows and macOS. Build with python desktop/build.py +# Windows dist/GameLibrary/GameLibrary.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/GameLibrary.app - a normal Dock app; its window uses WKWebView (pywebview) +import os +import sys + +DESKTOP = os.path.dirname(os.path.abspath(SPEC)) # noqa: F821 (provided by PyInstaller) +VERSION = os.environ.get("GAMELIB_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("GAMELIB_VERSION_FILE") or None +ICON = os.environ.get("GAMELIB_ICON") or None +IS_WIN = sys.platform == "win32" + +EXCLUDES = ["tkinter", "unittest", "test", "idlelib", "lib2to3"] +# pywebview: bundle only the backend this system uses (the others would drag in Qt, GTK or CEF). +OTHER_BACKENDS = ["webview.platforms.qt", "webview.platforms.gtk", "webview.platforms.cef", + "webview.platforms.android", "PyQt5", "PyQt6", "PySide2", "PySide6", "qtpy", "gi"] +if IS_WIN: + HIDDEN = ["webview", "webview.platforms.winforms", "webview.platforms.edgechromium", "clr"] + EXCLUDES += OTHER_BACKENDS + ["webview.platforms.cocoa"] +else: + HIDDEN = ["webview", "webview.platforms.cocoa"] + EXCLUDES += OTHER_BACKENDS + ["webview.platforms.winforms", "webview.platforms.edgechromium", + "webview.platforms.mshtml", "webview.platforms.win32"] + +a = Analysis( # noqa: F821 + [os.path.join(DESKTOP, "gamelib_app.py")], + pathex=[DESKTOP], + datas=[(os.path.join(DESKTOP, "offline.html"), "."), (os.path.join(DESKTOP, "shell.json"), ".")], + hiddenimports=HIDDEN, + excludes=EXCLUDES, +) +pyz = PYZ(a.pure) # noqa: F821 +exe = EXE( # noqa: F821 + pyz, + a.scripts, + [], + exclude_binaries=True, + name="GameLibrary", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="GameLibrary", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="GameLibrary.app", + icon=ICON, + bundle_identifier="io.github.juw12.gamelib.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "GameLibrary", + "CFBundleDisplayName": "GameLibrary", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/apps/gamelib/desktop/gamelib_app.py b/apps/gamelib/desktop/gamelib_app.py new file mode 100644 index 00000000..ab24e126 --- /dev/null +++ b/apps/gamelib/desktop/gamelib_app.py @@ -0,0 +1,467 @@ +"""GameLibrary for Windows and macOS: the GameLibrary web app in its own window. + + Windows Microsoft Edge WebView2 (part of Windows 10 and 11), through pywebview + macOS the system WebKit (WKWebView), through pywebview + +The window opens https://juw12.github.io/projects/gamelib/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time GameLibrary opens. Because the window loads the live site, every +push to main reaches the desktop app on its next launch; the app shell itself only changes when +desktop/shell.json gets a new version. Links to other sites open in the default browser. Without WebView2 +GameLibrary opens in the default browser instead. + +Opening GameLibrary while its window is open brings that window to the front; `GameLibrary --stop` closes it. + +Automated checks: GAMELIB_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; GAMELIB_DESKTOP_URL overrides the address. +""" + +import hmac +import json +import os +import secrets +import socket +import subprocess +import sys +import threading +import time +import urllib.request +import webbrowser + +TITLE = "Game Library" +APP_URL = os.environ.get("GAMELIB_DESKTOP_URL") or "https://juw12.github.io/projects/gamelib/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#0f0f11" +DARK_BACKGROUND = "#0f0f11" +CONTROL_FILE = "window.json" +SIZE_FILE = "window-size.json" +TEST_TIMEOUT = 60 +PAGE_SCRIPT = ( + "JSON.stringify({title: document.title, url: location.href, userAgent: navigator.userAgent," + " app: !!(document.body && document.body.children.length && document.scripts.length && document.body.innerText.trim().length + document.querySelectorAll('canvas').length > 0)," + " storage: (function () { try { localStorage.setItem('gamelib.desktop.check', '1');" + " return localStorage.getItem('gamelib.desktop.check') === '1'; } catch (e) { return false; } })()," + " ready: document.readyState, width: window.innerWidth, height: window.innerHeight})" +) + + +def log(message): + if sys.stdout is not None: + print("[gamelib] " + message, flush=True) + + +def here(): + """Folder with this program's own files (the PyInstaller bundle, or this checkout).""" + return getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__))) + + +def read_version(): + """The shell's version: desktop/shell.json, bundled next to the program.""" + try: + with open(os.path.join(here(), "shell.json"), encoding="utf-8") as handle: + return str(json.load(handle)["version"]) + except (OSError, ValueError, KeyError): + return "0.0.0" + + +VERSION = read_version() + + +def data_dir(): + """Per-user folder for the window's browser data and its own small settings.""" + home = os.path.expanduser("~") + if sys.platform == "win32": + return os.path.join(os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local"), "GameLibrary") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "GameLibrary") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "gamelib") + + +def system_prefers_dark(): + try: + if sys.platform == "win32": + import winreg + + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize") as key: + return winreg.QueryValueEx(key, "AppsUseLightTheme")[0] == 0 + if sys.platform == "darwin": + result = subprocess.run(["defaults", "read", "-g", "AppleInterfaceStyle"], + capture_output=True, text=True, timeout=5) + return "dark" in result.stdout.lower() + except (OSError, ValueError, subprocess.SubprocessError): + pass + return False + + +def saved_size(folder): + try: + with open(os.path.join(folder, SIZE_FILE), encoding="utf-8") as handle: + data = json.load(handle) + width, height = int(data["width"]), int(data["height"]) + except (OSError, ValueError, KeyError, TypeError): + return DEFAULT_SIZE + if MIN_SIZE[0] <= width <= 8000 and MIN_SIZE[1] <= height <= 8000: + return width, height + return DEFAULT_SIZE + + +def save_size(folder, width, height): + try: + width, height = int(width), int(height) + if width < MIN_SIZE[0] or height < MIN_SIZE[1]: + return + os.makedirs(folder, exist_ok=True) + with open(os.path.join(folder, SIZE_FILE), "w", encoding="utf-8") as handle: + json.dump({"width": width, "height": height}, handle) + except (OSError, ValueError, TypeError): + pass + + +def screen_work_area(): + """(width, height) of the primary screen's work area in window units, or None.""" + try: + if sys.platform == "win32": + import ctypes + from ctypes import wintypes + + rect = wintypes.RECT() + if ctypes.windll.user32.SystemParametersInfoW(0x0030, 0, ctypes.byref(rect), 0): # SPI_GETWORKAREA + return rect.right - rect.left, rect.bottom - rect.top + if sys.platform == "darwin": + from AppKit import NSScreen # comes with pywebview + + frame = NSScreen.mainScreen().visibleFrame() + return int(frame.size.width), int(frame.size.height) + except Exception: # sizing is cosmetic + return None + return None + + +def fit_size(size, work_area): + width, height = size + if work_area: + width = min(width, work_area[0] - 40) + height = min(height, work_area[1] - 40) + return max(width, MIN_SIZE[0]), max(height, MIN_SIZE[1]) + + +def online(url, timeout=6): + """True when the GameLibrary site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "GameLibraryDesktop/" + VERSION}) + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.status < 500 + except Exception: + return False + + +def offline_page(): + path = os.path.join(here(), "offline.html") + return "file:///" + path.replace("\\", "/").lstrip("/") if os.path.isfile(path) else None + + +# ------------------------------------------------------- one window at a time +class WindowControl: + """Loopback endpoint of the open window: 'show' brings it to the front, 'quit' closes it.""" + + def __init__(self, folder, on_show, on_quit): + self.path = os.path.join(folder, CONTROL_FILE) + self.token = secrets.token_hex(16) + self.on_show = on_show + self.on_quit = on_quit + self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.server.bind(("127.0.0.1", 0)) + self.server.listen(4) + os.makedirs(folder, exist_ok=True) + with open(self.path, "w", encoding="utf-8") as handle: + json.dump({"pid": os.getpid(), "port": self.server.getsockname()[1], "token": self.token}, handle) + threading.Thread(target=self._serve, name="gamelib-window-control", daemon=True).start() + + def _serve(self): + while True: + try: + connection, _address = self.server.accept() + except OSError: + return + with connection: + try: + connection.settimeout(2) + line = connection.makefile("r", encoding="utf-8").readline().strip() + except (OSError, UnicodeDecodeError): + continue + token, _space, command = line.partition(" ") + action = {"show": self.on_show, "quit": self.on_quit}.get(command) + if not action or not hmac.compare_digest(token, self.token): + continue + try: + connection.sendall(b"ok\n") + except OSError: + pass + try: + action() + except Exception as error: + log("control %s failed: %s" % (command, error)) + + def close(self): + try: + self.server.close() + except OSError: + pass + try: + with open(self.path, encoding="utf-8") as handle: + mine = json.load(handle).get("token") == self.token + if mine: + os.remove(self.path) + except (OSError, ValueError): + pass + + +def send_to_window(folder, command, timeout=2.0): + """Ask an open GameLibrary window to 'show' itself or 'quit'. True if one answered.""" + try: + with open(os.path.join(folder, CONTROL_FILE), encoding="utf-8") as handle: + info = json.load(handle) + port, token, pid = int(info["port"]), str(info["token"]), int(info.get("pid") or 0) + except (OSError, ValueError, KeyError, TypeError): + return False + if command == "show" and sys.platform == "win32" and pid: + try: + import ctypes + + ctypes.windll.user32.AllowSetForegroundWindow(pid) + except (OSError, AttributeError): + pass + try: + with socket.create_connection(("127.0.0.1", port), timeout=timeout) as connection: + connection.settimeout(timeout) + connection.sendall(("%s %s\n" % (token, command)).encode("utf-8")) + reply = connection.makefile("r", encoding="utf-8").readline().strip() + except (OSError, UnicodeDecodeError): + return False + if reply == "ok" and command == "quit" and pid: + deadline = time.time() + 15 + while time.time() < deadline and process_alive(pid): + time.sleep(0.2) + return reply == "ok" + + +def process_alive(pid): + if sys.platform == "win32": + import ctypes + + kernel32 = ctypes.windll.kernel32 + handle = kernel32.OpenProcess(0x00100000, False, pid) # SYNCHRONIZE + if not handle: + return False + try: + return kernel32.WaitForSingleObject(handle, 0) != 0 + finally: + kernel32.CloseHandle(handle) + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + +# ------------------------------------------------------------ the window +def webview2_runtime(): + """Version of the installed Microsoft Edge WebView2 runtime, or None (Windows only).""" + if sys.platform != "win32": + return None + import platform + import winreg + + clients = [ + "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}", # WebView2 Runtime + "{2CD8A007-E189-409D-A2C8-9AF4EF3C72AA}", # Beta + "{0D50BFEC-CD6A-4F9A-964C-C7416E3ACB10}", # Dev + "{65C35B14-6C1D-4122-AC46-7148CC9D6497}", # Canary + ] + for client in clients: + for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE): + native = hive == winreg.HKEY_CURRENT_USER or platform.machine() == "x86" + path = r"SOFTWARE\%sMicrosoft\EdgeUpdate\Clients\%s" % ("" if native else "WOW6432Node\\", client) + try: + with winreg.OpenKey(hive, path) as key: + version = str(winreg.QueryValueEx(key, "pv")[0]) + except OSError: + continue + if version and version != "0.0.0.0": + return version + return None + + +def bring_to_front(window): + if sys.platform == "win32": + try: + import ctypes + + user32 = ctypes.windll.user32 + hwnd = int(window.native.Handle.ToInt64()) + if user32.IsIconic(hwnd): + user32.ShowWindow(hwnd, 9) # SW_RESTORE + user32.SetForegroundWindow(hwnd) + return + except Exception: + pass + else: + window.restore() + window.show() + + +def write_report(path, **fields): + fields.setdefault("pid", os.getpid()) + fields.setdefault("version", VERSION) + temporary = path + ".tmp" + with open(temporary, "w", encoding="utf-8") as handle: + json.dump(fields, handle, indent=2) + os.replace(temporary, path) + + +def run_window(url, folder, report_path): + """Show GameLibrary in a native window until it is closed. Returns False when this system can't.""" + if sys.platform == "win32": + runtime = webview2_runtime() + if not runtime: + log("Microsoft Edge WebView2 runtime not found") + return False + gui = "edgechromium" + elif sys.platform == "darwin": + runtime = None + gui = "cocoa" + else: + return False + try: + import webview + except ImportError as error: + log("pywebview is not available: %s" % error) + return False + + # Let the page save files and send other sites to the default browser. + webview.settings["ALLOW_DOWNLOADS"] = True + webview.settings["OPEN_EXTERNAL_LINKS_IN_BROWSER"] = True + + start_url = url if (report_path or online(url)) else (offline_page() or url) + width, height = fit_size(saved_size(folder), screen_work_area()) + window = webview.create_window( + TITLE, + start_url, + width=width, + height=height, + min_size=MIN_SIZE, + background_color=DARK_BACKGROUND if system_prefers_dark() else LIGHT_BACKGROUND, + text_select=True, + zoomable=True, + focus=not report_path, + ) + control = WindowControl(folder, on_show=lambda: bring_to_front(window), on_quit=window.destroy) + state = {"tested": False} + + def remember_size(): + try: + save_size(folder, window.width, window.height) + except Exception: + pass + + def self_test(): + deadline = time.time() + TEST_TIMEOUT + page = {} + settled = 0 + while time.time() < deadline: + try: + page = json.loads(read_page(window, PAGE_SCRIPT) or "{}") + except Exception as error: + page = {"error": str(error)} + # Wait until a fully loaded GameLibrary page stays put for a moment. + settled = settled + 1 if page.get("app") and page.get("ready") == "complete" else 0 + if settled >= 3: + break + time.sleep(0.5) + renderer = gui + if sys.platform == "win32": + renderer = getattr(sys.modules.get("webview.platforms.winforms"), "renderer", gui) + write_report(report_path, method="window", toolkit=renderer, runtime=runtime, **page) + window.destroy() + + def on_loaded(): + if report_path and not state["tested"]: + state["tested"] = True + threading.Thread(target=self_test, name="gamelib-window-test", daemon=True).start() + + window.events.closing += remember_size + window.events.loaded += on_loaded + storage = None + if sys.platform == "win32": + # Automated checks use a throwaway profile so they never touch a person's own data. + base = os.path.dirname(os.path.abspath(report_path)) if report_path else folder + storage = os.path.join(base, "WebView2") + try: + webview.start(gui=gui, private_mode=False, storage_path=storage) + except Exception as error: + log("the window failed: %s" % error) + return False + finally: + control.close() + return True + + +def read_page(window, script): + """The page's answer to `script`. + + A page that forbids eval (Content-Security-Policy: script-src 'self') refuses pywebview's own + evaluate_js on a Mac, which wraps the script in eval. There the question is put to WebKit itself, + which the page's policy does not bind. + """ + try: + return window.evaluate_js(script) + except Exception: + if sys.platform != "darwin": + raise + from PyObjCTools import AppHelper + from webview.platforms.cocoa import BrowserView + + answer, done = {}, threading.Event() + + def ask(): + def finished(result, error): + answer["value"] = result + answer["error"] = None if error is None else str(error) + done.set() + + BrowserView.instances[window.uid].webview.evaluateJavaScript_completionHandler_(script, finished) + + AppHelper.callAfter(ask) + if not done.wait(20): + raise RuntimeError("the page did not answer") + if answer["error"]: + raise RuntimeError(answer["error"]) + return answer["value"] + + +def main(argv=None): + args = list(sys.argv[1:] if argv is None else argv) + folder = data_dir() + if "--version" in args: + print("GameLibrary %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("GAMELIB_WINDOW_TEST") or None + if not report_path and send_to_window(folder, "show"): + return 0 # already open: brought to the front + if run_window(APP_URL, folder, report_path): + return 0 + if report_path: + write_report(report_path, method="none", error="no native window on this system") + return 1 + webbrowser.open(APP_URL) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/apps/gamelib/desktop/icon-512.png b/apps/gamelib/desktop/icon-512.png new file mode 100644 index 00000000..3a58c7f8 Binary files /dev/null and b/apps/gamelib/desktop/icon-512.png differ diff --git a/apps/gamelib/desktop/offline.html b/apps/gamelib/desktop/offline.html new file mode 100644 index 00000000..f61c04ce --- /dev/null +++ b/apps/gamelib/desktop/offline.html @@ -0,0 +1,25 @@ + + + + + + GameLibrary + + + +
+ +

GameLibrary can't reach the internet

+

GameLibrary needs a connection the first time it opens. After that it also opens offline. Check your connection and try again.

+ Try again +
+ + diff --git a/apps/gamelib/desktop/shell.json b/apps/gamelib/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/apps/gamelib/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/apps/gamelib/desktop/smoke_test.py b/apps/gamelib/desktop/smoke_test.py new file mode 100644 index 00000000..67251979 --- /dev/null +++ b/apps/gamelib/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built GameLibrary desktop app and check its window really shows GameLibrary. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/GameLibrary.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with GAMELIB_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is GameLibrary, the app started (the page with its scripts and something on it) and the page can store data. +""" + +import argparse +import functools +import http.server +import json +import os +import subprocess +import sys +import tempfile +import threading +import time + +DESKTOP = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.normpath(os.path.join(DESKTOP, os.pardir, os.pardir, os.pardir, "apps", "gamelib", "web")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/gamelib/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "GameLibrary", "GameLibrary.exe") + return os.path.join(DESKTOP, "dist", "GameLibrary.app", "Contents", "MacOS", "GameLibrary") + + +def serve_site(): + """Serve this checkout (the site is the repository itself) on a free loopback port.""" + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=REPO) + handler.log_message = lambda *args: None + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return "http://127.0.0.1:%d/" % server.server_address[1] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("app", nargs="?", help="the GameLibrary program to open") + parser.add_argument("--built", action="store_true", help="open the app in desktop/dist/") + parser.add_argument("--local-site", action="store_true", help="serve this checkout instead of the live site") + args = parser.parse_args() + app = built_app() if args.built or not args.app else args.app + if not os.path.isfile(app): + raise SystemExit("Not found: %s" % app) + + url = serve_site() if args.local_site else LIVE_URL + folder = tempfile.mkdtemp(prefix="gamelib-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, GAMELIB_WINDOW_TEST=report, GAMELIB_DESKTOP_URL=url) + print("Opening %s on %s" % (app, url), flush=True) + started = time.time() + process = subprocess.Popen([app], env=env) + try: + process.wait(timeout=180) + except subprocess.TimeoutExpired: + process.kill() + raise SystemExit("The app did not close itself within 180 s") + if not os.path.isfile(report): + raise SystemExit("The app exited (code %s) without a report" % process.returncode) + with open(report, encoding="utf-8") as handle: + result = json.load(handle) + print(json.dumps(result, indent=2)) + + with open(os.path.join(DESKTOP, "shell.json"), encoding="utf-8") as handle: + version = json.load(handle)["version"] + problems = [] + if result.get("method") != "window": + problems.append("no native window (%s)" % (result.get("error") or result.get("method"))) + if "Game Library" not in str(result.get("title") or ""): + problems.append("page title is %r" % result.get("title")) + if not str(result.get("url") or "").startswith(url): + problems.append("the window is on %r" % result.get("url")) + if not result.get("app"): + problems.append("GameLibrary did not start in the page (missing: the page with its scripts and something on it)") + if not result.get("storage"): + problems.append("the page cannot store data") + if result.get("version") != version: + problems.append("the app says version %r, desktop/shell.json says %r" % (result.get("version"), version)) + if problems: + raise SystemExit("FAILED: " + "; ".join(problems)) + print("OK: GameLibrary %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main() diff --git a/apps/gamelib/web/icons/apple-touch-icon.png b/apps/gamelib/web/icons/apple-touch-icon.png new file mode 100644 index 00000000..6ef1ceaa Binary files /dev/null and b/apps/gamelib/web/icons/apple-touch-icon.png differ diff --git a/apps/gamelib/web/icons/icon-192.png b/apps/gamelib/web/icons/icon-192.png new file mode 100644 index 00000000..ab2e2e2e Binary files /dev/null and b/apps/gamelib/web/icons/icon-192.png differ diff --git a/apps/gamelib/web/icons/icon-512.png b/apps/gamelib/web/icons/icon-512.png new file mode 100644 index 00000000..3a58c7f8 Binary files /dev/null and b/apps/gamelib/web/icons/icon-512.png differ diff --git a/apps/gamelib/web/index.html b/apps/gamelib/web/index.html index 18c584aa..c51200ac 100644 --- a/apps/gamelib/web/index.html +++ b/apps/gamelib/web/index.html @@ -5,6 +5,12 @@ Game Library + + + + + +