From 6faa34de8c13aaeb460b513cdbf0fcbd918eca31 Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:49:36 +0700 Subject: [PATCH 1/5] Titian for Windows, Mac and Android: the web app in its own window, built and opened on each system before it is published --- .github/workflows/respark-android.yml | 137 +++++ .github/workflows/respark-desktop.yml | 177 +++++++ respark/README.md | 9 + respark/android/.gitignore | 2 + respark/android/AndroidManifest.xml | 23 + respark/android/README.md | 34 ++ respark/android/app.json | 10 + respark/android/assets/offline.html | 25 + respark/android/build.py | 98 ++++ .../res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 2312 bytes respark/android/res/values/styles.xml | 11 + respark/android/smoke.py | 128 +++++ .../io/github/juw12/respark/MainActivity.java | 283 +++++++++++ respark/desktop/.gitignore | 3 + respark/desktop/README.md | 25 + respark/desktop/build.py | 174 +++++++ respark/desktop/icon-512.png | Bin 0 -> 3621 bytes respark/desktop/offline.html | 25 + respark/desktop/respark.iss | 73 +++ respark/desktop/respark.spec | 64 +++ respark/desktop/respark_app.py | 467 ++++++++++++++++++ respark/desktop/shell.json | 3 + respark/desktop/smoke_test.py | 92 ++++ 23 files changed, 1863 insertions(+) create mode 100644 .github/workflows/respark-android.yml create mode 100644 .github/workflows/respark-desktop.yml create mode 100644 respark/android/.gitignore create mode 100644 respark/android/AndroidManifest.xml create mode 100644 respark/android/README.md create mode 100644 respark/android/app.json create mode 100644 respark/android/assets/offline.html create mode 100644 respark/android/build.py create mode 100644 respark/android/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 respark/android/res/values/styles.xml create mode 100644 respark/android/smoke.py create mode 100644 respark/android/src/io/github/juw12/respark/MainActivity.java create mode 100644 respark/desktop/.gitignore create mode 100644 respark/desktop/README.md create mode 100644 respark/desktop/build.py create mode 100644 respark/desktop/icon-512.png create mode 100644 respark/desktop/offline.html create mode 100644 respark/desktop/respark.iss create mode 100644 respark/desktop/respark.spec create mode 100644 respark/desktop/respark_app.py create mode 100644 respark/desktop/shell.json create mode 100644 respark/desktop/smoke_test.py diff --git a/.github/workflows/respark-android.yml b/.github/workflows/respark-android.yml new file mode 100644 index 00000000..f2c4bfd0 --- /dev/null +++ b/.github/workflows/respark-android.yml @@ -0,0 +1,137 @@ +name: Titian Android app + +# Builds Titian-android.apk (respark/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 respark-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "respark/android/**" + - ".github/workflows/respark-android.yml" + pull_request: + paths: + - "respark/android/**" + - ".github/workflows/respark-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 respark/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 respark/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('respark/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs respark/android/dist/Titian-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd respark/android/dist && sha256sum Titian-android.apk > Titian-android.apk.sha256 && cat Titian-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: respark-android + path: respark/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: respark-android + path: respark/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 respark/android/smoke.py respark/android/dist/Titian-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: respark-android-emulator-check + path: | + respark/android/dist/*.png + respark/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: respark-android + path: dist + # The respark-android release keeps one address for the download. The file there is replaced only when + # respark/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the respark-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('respark/android/app.json'))['versionName'])") + echo "$version" > dist/Titian-android.version.txt + if ! gh release view respark-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "Titian for Android: a full-screen window around the web app (https://juw12.github.io/projects/titian/)." "" \ + "Download [Titian-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/respark-android/Titian-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 respark-android dist/Titian-android.apk dist/Titian-android.apk.sha256 dist/Titian-android.version.txt \ + --title "Titian for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the respark-android release with Titian-android.apk $version" + exit 0 + fi + published=$(gh release download respark-android --repo "$GITHUB_REPOSITORY" --pattern Titian-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the respark-android release already has Titian-android.apk $version" + exit 0 + fi + gh release upload respark-android dist/Titian-android.apk dist/Titian-android.apk.sha256 dist/Titian-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "Titian-android.apk on the respark-android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/respark-desktop.yml b/.github/workflows/respark-desktop.yml new file mode 100644 index 00000000..624b7fdf --- /dev/null +++ b/.github/workflows/respark-desktop.yml @@ -0,0 +1,177 @@ +name: Titian apps + +# Builds the downloadable Titian apps and publishes them to the "respark-desktop" release from main: +# Windows Titian-Windows-Setup.exe (per-user installer) + Titian-Windows-Portable.zip +# macOS Titian-macOS-AppleSilicon.dmg + Titian-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: + - 'respark/desktop/**' + - '.github/workflows/respark-desktop.yml' + pull_request: + paths: + - 'respark/desktop/**' + - '.github/workflows/respark-desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: respark-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 respark/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's Titian + run: python respark/desktop/smoke_test.py --built --local-site + - name: Install with Titian-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'respark/desktop/dist/Titian-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'respark-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\Titian\Titian.exe' + if (-not (Test-Path $app)) { throw "Titian.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'Titian.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Titian.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 'Titian' + if (-not $entry) { throw 'Titian is missing from Settings > Apps' } + python respark/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 Titian.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=respark/desktop/dist/Titian.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.respark.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("respark/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/Titian")" + codesign --verify --deep --verbose=2 "$APP" + for image in respark/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: Titian-${{ runner.os }}-${{ runner.arch }} + path: respark/desktop/dist/Titian-* + 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: Titian-* + 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 Titian-Windows-Setup.exe Titian-Windows-Portable.zip \ + Titian-macOS-AppleSilicon.dmg Titian-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' + **Titian**: a broker-run B2B bridge for industrial manufacturers in Southeast Asia. The apps open the same Titian as https://juw12.github.io/projects/titian/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [Titian-Windows-Setup.exe](https://github.com/juw12/projects/releases/download/respark-desktop/Titian-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: [Titian-Windows-Portable.zip](https://github.com/juw12/projects/releases/download/respark-desktop/Titian-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [Titian-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/respark-desktop/Titian-macOS-AppleSilicon.dmg) | Open it and drag Titian to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [Titian-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/respark-desktop/Titian-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/titian/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [Titian-android.apk](https://github.com/juw12/projects/releases/download/respark-android/Titian-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load Titian 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 respark-desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload respark-desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit respark-desktop --notes-file notes.md --repo "$REPO" + else + gh release create respark-desktop $FILES SHA256SUMS.txt --title "Titian for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/respark/README.md b/respark/README.md index f36f4041..d561cfeb 100644 --- a/respark/README.md +++ b/respark/README.md @@ -39,6 +39,15 @@ +## Get it on your device + +- **Windows:** [`Titian-Windows-Setup.exe`](https://github.com/juw12/projects/releases/download/respark-desktop/Titian-Windows-Setup.exe) (no admin needed; if Windows says it protected your PC, choose *More info → Run anyway*), or without installing [`Titian-Windows-Portable.zip`](https://github.com/juw12/projects/releases/download/respark-desktop/Titian-Windows-Portable.zip). +- **Mac:** [`Titian-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/respark-desktop/Titian-macOS-AppleSilicon.dmg) (M1 and newer) or [`Titian-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/respark-desktop/Titian-macOS-Intel.dmg). The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`Titian-android.apk`](https://github.com/juw12/projects/releases/download/respark-android/Titian-android.apk): open the file on the phone and allow your browser to install apps once. +- **iPhone:** open https://juw12.github.io/projects/titian/ 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. + ## About Zero-dependency Python stdlib + SQLite. Re-engages dormant customers for local service businesses. diff --git a/respark/android/.gitignore b/respark/android/.gitignore new file mode 100644 index 00000000..edd9d60a --- /dev/null +++ b/respark/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/respark/android/AndroidManifest.xml b/respark/android/AndroidManifest.xml new file mode 100644 index 00000000..1e5f3c9a --- /dev/null +++ b/respark/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/respark/android/README.md b/respark/android/README.md new file mode 100644 index 00000000..28a091ce --- /dev/null +++ b/respark/android/README.md @@ -0,0 +1,34 @@ +# Titian for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/projects/titian/): the same Titian 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: [`Titian-android.apk`](https://github.com/juw12/projects/releases/download/respark-android/Titian-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 respark/android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/respark-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 +`Titian-android.apk` on the `respark-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/respark/android/app.json b/respark/android/app.json new file mode 100644 index 00000000..6c748c76 --- /dev/null +++ b/respark/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "Titian", + "id": "io.github.juw12.respark", + "url": "https://juw12.github.io/projects/titian/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/respark/android/assets/offline.html b/respark/android/assets/offline.html new file mode 100644 index 00000000..581058c2 --- /dev/null +++ b/respark/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + Titian + + + +
+ +

Titian can't reach the internet

+

Titian 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/respark/android/build.py b/respark/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/respark/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/respark/android/res/mipmap-xxxhdpi/ic_launcher.png b/respark/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..6c31c6f879417c9ec6d34d8061cc3d8852158dc9 GIT binary patch literal 2312 zcmeHJ=|3Cj8qH>;RXep-VwotKT1G8l2#tNL6W!&@w}9v058S;y88hD zfTE8#CPc>ldw_yu=S<&Lkc@z&5HEKCYeZitYcL5BK0o>U1I%SL6aXwp1VHvAGU&f4}xOfd5nP3H_ZMhh-y(J{Y&qOTg7yzjL8j?ZKsyS}&Zh+x`#@ z6*rCGTZXUXg4JyCMP((r>M5<19h^XZJ`*NI8z(l;^4X_XEj68o0={o zJ$(HV{i4UxPd#ST*%@X%ugNndDY+Ipj&1BnMX+Mc-5#RXp!~WO=15bf|o`E|; zsp@FBvz5_hwC5(&SVc)&6%9AeyrK$~r$XU0RTnPw3fL2(G6aRiK)66-5H$WunH6a6 zvMLZ_!}Zc86Z#7QAe}j5D%#;R20*5YRXySQ|Lx;wR=(jF2lIo)a#B6bxcf|_R9gum z_mWE4;Bl#Cp&SYJ;}b6jWYG1$&OE);-OY-bY{V)gX*H{1-GYRl3L6hs!Su8_Q{%js zW4nQN^*)GE`s39b`l(oWdLN~6o{>?H$7d#N50`vOx=>E~g@LdTZ#BLoyo=)BR(IXu zEC)T~NpoxV1&kOG)_13lYz#$ieR-|iW!LvX#BsXwxqM9Cg}?QtpU_&Yl%Hg8`RmFb zbol|M_#Fx6y4|L{0sW-uCyGj0?uiZ%RoRn9YL$Oy%~M5o)CV~GNHai z;=CcaTE&*$4^d(<-{+&xY^P%QMPVCcSVLVpwJYSHb=!l?+TYN`w?JGNu zOLNn}E?z6EHHj8(-IXf3i4G2>|IYH^^>}cu&oC;+JH{0RqwMQ>7E9WL5H&)6Y@dpz zdBNL~Day1WQiEvC6Iq}Tv`3$H4(avT5QLs3EySJLCogyI=FJe3dx)K(!vXqy*7RnT zAKi6Ii9TA58+=f+i@hMnNpT8=Iw5E)4yp)c+qD&g?)R0j_O(=p@4A=7TI3VQ?uO{QX4K8(yN^ji z?qbDX-J1;^pEgUg)^@-0?C)Tv2DY7~krR;jCta!ou(Mt4^(W)iVaQYA(OtH+%t}6W zvDA%K^DQpCoq4a}(Gp$qG0GD4GU6yHMa-@NBbQ2R&bp#db|$b@I<}Xnlo|miAFfYa zQgD=>{h{vbf*Ug}166S-ePOb!E=SP8X0Ug=EW6gSADUxNgyH8;a}Jqnt+Gk$mO6~T zJ6nP!yM+!?3rGbVl4VmK54Mq@uTlBKJ2=wPr7F6dV5;_FZdK(!yT7DVf5|! z+w%yw)qCcm%@1#|zb^D=@m)YtyWnTra9YCKKKgO^ECSDgLD&bTyNFN$AA^+Sp)1K- zVM^r8YUX0L%8(6VcG!@XtllxL42t|lgmZ*^Jl|Nki?(=^|bcM$2bSE#W z40TbWMDpY#U`dPq|CcC(O2B1;d>>h|i*hlpo&yQvGK0Ibn zU;rA3rC2?h$k;i_yE7`+^G{Oet!CtbirZe9-(MqnBlP0gx8!#wBEL{`P@NfPFJ7*) zGQ5gjm}*iJ<_${f&h7SU6bJ^Ex8Aj0qlB8tXXG3Jm6S!Wnr$ZM0ws_5>5D5X#%sN= zJF+BB;HSOofQt)EZb!A&^U@WBG||~$LowC9-f^Psed%H`?+5;8%Hy(Z_HxVXk+_f4 zW2->>Ir}`ud5a6&&NKK((P0Ev@Mj0kAnWaoV~WdKuaB0SHYXWptybZb>%WMGgfP$c zr~ja7wVGu^Z3klKgEc%j?qLQm{9eFv82e&5nW^#TnA)1xVs2I!@Ya1#N{&Sr8L77h zO@5t-a4|*;@P2ibvDQbYn(u?j46@BS(wd_1Sx3l(5zKz`Zo|tG3VH5|1`rZr644f;Q!s&}6|@1i5<<2pQ#iddr+1x!7U=C^5#k zN#- + + #fbfaf6 + + diff --git a/respark/android/smoke.py b/respark/android/smoke.py new file mode 100644 index 00000000..4616083c --- /dev/null +++ b/respark/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the Titian APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/Titian-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("\nTitian 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/respark/android/src/io/github/juw12/respark/MainActivity.java b/respark/android/src/io/github/juw12/respark/MainActivity.java new file mode 100644 index 00000000..bb309ce2 --- /dev/null +++ b/respark/android/src/io/github/juw12/respark/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.respark; + +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; + +/** + * Titian 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/titian/"; + private static final String SCOPE = "juw12.github.io/projects/titian"; + 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() + " TitianAndroid/" + 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("TitianShell", "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("TitianShell", "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/respark/desktop/.gitignore b/respark/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/respark/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/respark/desktop/README.md b/respark/desktop/README.md new file mode 100644 index 00000000..11ac32a5 --- /dev/null +++ b/respark/desktop/README.md @@ -0,0 +1,25 @@ +# Titian for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/titian/): 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 Titian 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 | +| --- | --- | +| `respark_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 | +| `respark.spec`, `respark.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 Titian | +| `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/respark-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 +[respark-desktop release](https://github.com/juw12/projects/releases/tag/respark-desktop). The download links never change. diff --git a/respark/desktop/build.py b/respark/desktop/build.py new file mode 100644 index 00000000..a55518aa --- /dev/null +++ b/respark/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the Titian 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 Titian-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + Titian-Windows-Portable.zip unzip and run Titian.exe + macOS Titian-macOS-AppleSilicon.dmg or Titian-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', 'Titian - A broker-run B2B bridge for industrial manufacturers in Southeast Asia'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'Titian'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'Titian.exe'), + StringStruct('ProductName', 'Titian'), + 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, "respark.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, RESPARK_VERSION=version, RESPARK_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["RESPARK_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "respark.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, "Titian") + portable = os.path.join(DIST, "Titian-Windows-Portable.zip") + zip_folder(folder, portable, "Titian") + 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 Titian-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped Titian-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, "respark.iss")], + check=True, + ) + return [os.path.join(DIST, "Titian-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "Titian.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "Titian-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, "Titian.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "Titian", "-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 Titian 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("Titian desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by respark.spec) + except ImportError: + raise SystemExit("The Titian window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("Titian", "Titian.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building Titian %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/respark/desktop/icon-512.png b/respark/desktop/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..35b24089f667aaa3d304edaf7f0064f5856575ce GIT binary patch literal 3621 zcmeHK|3B0F9{)@nUrJm~spLz^akNk**;*UAzD1lOWmw-%MA`~rqfI$=(#g^x+_G`p zQZ$l@tXUl)iTVCzmhWM+FBh|!eLJ7-{TJ>}_x98K{eC@P@8|3Fe!bt1_v`h#9el*c z&|r%J004%5zK4zifEGB_0`$HPge_h)P%iL0RE8ec@>D)jpWT$ZyA5=;3AjL>LXmIo~tn>zrd&-R%kQ z$UGOYUC-~=3;90;>pjo3eX(n;z>zREwKjd?%U#DuOGvgn{UA13sw6H6hE<({)XocI z^wdyuAQk3s1Qf4>0D86nP@)Z3=K?^c2|x=u%A88!eWv5}InkrkA`6OLzl)0t!X2?^kLy9_eS7z(UBNwN zVaIXewl%l1#q)^Qtm74VmcFUis(WcCtJO>_L-=`qUuD#_K%PTHfQ3cT61-uCEe!9g zJ=gqmg?c`}v&c#*nuuge(-LGAK}Q1aGDOuJw|F&{z0Q+fS2spiM>*)l4Wf(m$<`c=kAs1^vA#66FDd&nQQA8zu9|r3*xrd~CE~wN4jR495j5EtXnPQ+fLd`r(8dZ;YMsO%YfA2%GY z(;*7H^I%K{HM-h?If2)^YYqIZlF%NQ%w4SRfj+(2-(DsEK%+V^uX`Jl2HeULI>lUR znNTQvd@FdfIktYvXOJ6$*GaMiXxJ%3D+wl2%@T1|{LE-y^ilH+)r?U-1-1Mfvn(|X zV^&BE_=kaTZY{Jb`K(pV(y>8C^z&wY)E&ZXtr&{PD96hhsM4OF;!H^!>n6&RA5c)C z4pCjq*kKOniwz{^a@^>fMv3-L0l(cXmx8j;M?ulx&72;b1o7Q6a_v4y%+Ghs5<#1_ z4kzpB5^cUO5I$_X)Ziaf%xRc$_z{r-Ga(Jkd}c+An|?UMTA;;DpF*`S)MEhFogTRSpEoxT}Sa^P{5hdV!}C&rElh zv6L&7x=)^z`D05;w5|J;uOlChUY-@YrKb!}LP23cPIbbF?7&y8&UMtqvwAy#ZWs(! zMQra7r;jMG5ekava9A$I>&7EEa%C|NP93R>m#HmGe?MDE*aaC!Ms_o2d@A2uT3(Dh z?#OH)bU$=L(=Sfg-kI$zbgN5<^6@Ea4{@*Me46fiKP`FxVW?~TUv0f!cH| zlLAPMH3$y9k3pMmqF&7U4_vfagpJdR_WsU4h;;HR*$a2A-TM1`r&v*|0}_Yr%g~M z-Wb@4jgfp(jj5ZwDJw!V%hct$QE!UgvNb@zUWQS()F4L86ONDZY=}$mXU!8f_T>Rx z+Z$J8)D+=e@t`8Ndtm~JpLX+ZxyesA-b(_(7CRrYVuTTe3~eRr6%}k%a7$UkghiAp zo8)Z*gtxx!x=mn7-+?)R)_Q}SZKQekfPsNYA`q5avy6f8kK;Ivok-JsM~#0wU$$N) z3LC>HOK*)&f_poL-pkoo)m(n#LR(3FCOPfIxmuSh2ov z<-KglMZ#n=O;^zvHk%ZDAGmi$ejn- + + + + + Titian + + + +
+ +

Titian can't reach the internet

+

Titian 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/respark/desktop/respark.iss b/respark/desktop/respark.iss new file mode 100644 index 00000000..6e729e98 --- /dev/null +++ b/respark/desktop/respark.iss @@ -0,0 +1,73 @@ +; Titian for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= respark.iss +; Installs to %LOCALAPPDATA%\Programs\Titian, adds Titian 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%\Titian, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\Titian" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\respark.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=Titian +AppVersion={#AppVersion} +AppVerName=Titian {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/titian/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\Titian +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=Titian-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\Titian.exe +UninstallDisplayName=Titian +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}\Titian"; Filename: "{app}\Titian.exe"; Comment: "A broker-run B2B bridge for industrial manufacturers in Southeast Asia" +Name: "{userdesktop}\Titian"; Filename: "{app}\Titian.exe"; Comment: "A broker-run B2B bridge for industrial manufacturers in Southeast Asia"; Tasks: desktopicon + +[Run] +Filename: "{app}\Titian.exe"; Description: "{cm:LaunchProgram,Titian}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\Titian.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopTitian" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open Titian window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\Titian.exe')) then + Exec(ExpandConstant('{app}\Titian.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/respark/desktop/respark.spec b/respark/desktop/respark.spec new file mode 100644 index 00000000..3feff625 --- /dev/null +++ b/respark/desktop/respark.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for Titian on Windows and macOS. Build with python desktop/build.py +# Windows dist/Titian/Titian.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/Titian.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("RESPARK_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("RESPARK_VERSION_FILE") or None +ICON = os.environ.get("RESPARK_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, "respark_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="Titian", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="Titian", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="Titian.app", + icon=ICON, + bundle_identifier="io.github.juw12.respark.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "Titian", + "CFBundleDisplayName": "Titian", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/respark/desktop/respark_app.py b/respark/desktop/respark_app.py new file mode 100644 index 00000000..cb0c6b07 --- /dev/null +++ b/respark/desktop/respark_app.py @@ -0,0 +1,467 @@ +"""Titian for Windows and macOS: the Titian 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/titian/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time Titian 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 +Titian opens in the default browser instead. + +Opening Titian while its window is open brings that window to the front; `Titian --stop` closes it. + +Automated checks: RESPARK_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; RESPARK_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 = "Titian" +APP_URL = os.environ.get("RESPARK_DESKTOP_URL") or "https://juw12.github.io/projects/titian/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#fbfaf6" +DARK_BACKGROUND = "#fbfaf6" +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('respark.desktop.check', '1');" + " return localStorage.getItem('respark.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("[respark] " + 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"), "Titian") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "Titian") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "respark") + + +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 Titian site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "TitianDesktop/" + 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="respark-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 Titian 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 Titian 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 Titian 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="respark-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("Titian %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("RESPARK_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/respark/desktop/shell.json b/respark/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/respark/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/respark/desktop/smoke_test.py b/respark/desktop/smoke_test.py new file mode 100644 index 00000000..a0bb046e --- /dev/null +++ b/respark/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built Titian desktop app and check its window really shows Titian. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/Titian.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with RESPARK_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is Titian, 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, "respark", "guide")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/titian/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "Titian", "Titian.exe") + return os.path.join(DESKTOP, "dist", "Titian.app", "Contents", "MacOS", "Titian") + + +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 Titian 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="respark-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, RESPARK_WINDOW_TEST=report, RESPARK_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 "Titian" 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("Titian 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: Titian %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main() From 2c8a4bdfbc775902613b8250993ca38dc52ed4df Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:49:59 +0700 Subject: [PATCH 2/5] KiniBuka for Windows, Mac and Android: the web app in its own window, built and opened on each system before it is published --- .github/workflows/kinibuka-android.yml | 137 +++++ .github/workflows/kinibuka-desktop.yml | 177 +++++++ apps/kinibuka/README.md | 9 + apps/kinibuka/android/.gitignore | 2 + apps/kinibuka/android/AndroidManifest.xml | 23 + apps/kinibuka/android/README.md | 34 ++ apps/kinibuka/android/app.json | 10 + apps/kinibuka/android/assets/offline.html | 25 + apps/kinibuka/android/build.py | 98 ++++ .../res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 4411 bytes apps/kinibuka/android/res/values/styles.xml | 11 + apps/kinibuka/android/smoke.py | 128 +++++ .../github/juw12/kinibuka/MainActivity.java | 283 +++++++++++ apps/kinibuka/desktop/.gitignore | 3 + apps/kinibuka/desktop/README.md | 25 + apps/kinibuka/desktop/build.py | 174 +++++++ apps/kinibuka/desktop/icon-512.png | Bin 0 -> 8547 bytes apps/kinibuka/desktop/kinibuka.iss | 73 +++ apps/kinibuka/desktop/kinibuka.spec | 64 +++ apps/kinibuka/desktop/kinibuka_app.py | 467 ++++++++++++++++++ apps/kinibuka/desktop/offline.html | 25 + apps/kinibuka/desktop/shell.json | 3 + apps/kinibuka/desktop/smoke_test.py | 92 ++++ 23 files changed, 1863 insertions(+) create mode 100644 .github/workflows/kinibuka-android.yml create mode 100644 .github/workflows/kinibuka-desktop.yml create mode 100644 apps/kinibuka/android/.gitignore create mode 100644 apps/kinibuka/android/AndroidManifest.xml create mode 100644 apps/kinibuka/android/README.md create mode 100644 apps/kinibuka/android/app.json create mode 100644 apps/kinibuka/android/assets/offline.html create mode 100644 apps/kinibuka/android/build.py create mode 100644 apps/kinibuka/android/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 apps/kinibuka/android/res/values/styles.xml create mode 100644 apps/kinibuka/android/smoke.py create mode 100644 apps/kinibuka/android/src/io/github/juw12/kinibuka/MainActivity.java create mode 100644 apps/kinibuka/desktop/.gitignore create mode 100644 apps/kinibuka/desktop/README.md create mode 100644 apps/kinibuka/desktop/build.py create mode 100644 apps/kinibuka/desktop/icon-512.png create mode 100644 apps/kinibuka/desktop/kinibuka.iss create mode 100644 apps/kinibuka/desktop/kinibuka.spec create mode 100644 apps/kinibuka/desktop/kinibuka_app.py create mode 100644 apps/kinibuka/desktop/offline.html create mode 100644 apps/kinibuka/desktop/shell.json create mode 100644 apps/kinibuka/desktop/smoke_test.py diff --git a/.github/workflows/kinibuka-android.yml b/.github/workflows/kinibuka-android.yml new file mode 100644 index 00000000..370c0306 --- /dev/null +++ b/.github/workflows/kinibuka-android.yml @@ -0,0 +1,137 @@ +name: KiniBuka Android app + +# Builds KiniBuka-android.apk (apps/kinibuka/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 kinibuka-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "apps/kinibuka/android/**" + - ".github/workflows/kinibuka-android.yml" + pull_request: + paths: + - "apps/kinibuka/android/**" + - ".github/workflows/kinibuka-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/kinibuka/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/kinibuka/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/kinibuka/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs apps/kinibuka/android/dist/KiniBuka-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd apps/kinibuka/android/dist && sha256sum KiniBuka-android.apk > KiniBuka-android.apk.sha256 && cat KiniBuka-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: kinibuka-android + path: apps/kinibuka/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: kinibuka-android + path: apps/kinibuka/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/kinibuka/android/smoke.py apps/kinibuka/android/dist/KiniBuka-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: kinibuka-android-emulator-check + path: | + apps/kinibuka/android/dist/*.png + apps/kinibuka/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: kinibuka-android + path: dist + # The kinibuka-android release keeps one address for the download. The file there is replaced only when + # apps/kinibuka/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the kinibuka-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('apps/kinibuka/android/app.json'))['versionName'])") + echo "$version" > dist/KiniBuka-android.version.txt + if ! gh release view kinibuka-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "KiniBuka for Android: a full-screen window around the web app (https://juw12.github.io/projects/kinibuka/)." "" \ + "Download [KiniBuka-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/kinibuka-android/KiniBuka-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 kinibuka-android dist/KiniBuka-android.apk dist/KiniBuka-android.apk.sha256 dist/KiniBuka-android.version.txt \ + --title "KiniBuka for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the kinibuka-android release with KiniBuka-android.apk $version" + exit 0 + fi + published=$(gh release download kinibuka-android --repo "$GITHUB_REPOSITORY" --pattern KiniBuka-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the kinibuka-android release already has KiniBuka-android.apk $version" + exit 0 + fi + gh release upload kinibuka-android dist/KiniBuka-android.apk dist/KiniBuka-android.apk.sha256 dist/KiniBuka-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "KiniBuka-android.apk on the kinibuka-android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/kinibuka-desktop.yml b/.github/workflows/kinibuka-desktop.yml new file mode 100644 index 00000000..35c11664 --- /dev/null +++ b/.github/workflows/kinibuka-desktop.yml @@ -0,0 +1,177 @@ +name: KiniBuka apps + +# Builds the downloadable KiniBuka apps and publishes them to the "kinibuka-desktop" release from main: +# Windows KiniBuka-Windows-Setup.exe (per-user installer) + KiniBuka-Windows-Portable.zip +# macOS KiniBuka-macOS-AppleSilicon.dmg + KiniBuka-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/kinibuka/desktop/**' + - '.github/workflows/kinibuka-desktop.yml' + pull_request: + paths: + - 'apps/kinibuka/desktop/**' + - '.github/workflows/kinibuka-desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: kinibuka-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/kinibuka/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's KiniBuka + run: python apps/kinibuka/desktop/smoke_test.py --built --local-site + - name: Install with KiniBuka-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'apps/kinibuka/desktop/dist/KiniBuka-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'kinibuka-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\KiniBuka\KiniBuka.exe' + if (-not (Test-Path $app)) { throw "KiniBuka.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'KiniBuka.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'KiniBuka.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 'KiniBuka' + if (-not $entry) { throw 'KiniBuka is missing from Settings > Apps' } + python apps/kinibuka/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 KiniBuka.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/kinibuka/desktop/dist/KiniBuka.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.kinibuka.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("apps/kinibuka/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/KiniBuka")" + codesign --verify --deep --verbose=2 "$APP" + for image in apps/kinibuka/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: KiniBuka-${{ runner.os }}-${{ runner.arch }} + path: apps/kinibuka/desktop/dist/KiniBuka-* + 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: KiniBuka-* + 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 KiniBuka-Windows-Setup.exe KiniBuka-Windows-Portable.zip \ + KiniBuka-macOS-AppleSilicon.dmg KiniBuka-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' + **KiniBuka**: find small stalls that are open right now. The apps open the same KiniBuka as https://juw12.github.io/projects/kinibuka/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [KiniBuka-Windows-Setup.exe](https://github.com/juw12/projects/releases/download/kinibuka-desktop/KiniBuka-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: [KiniBuka-Windows-Portable.zip](https://github.com/juw12/projects/releases/download/kinibuka-desktop/KiniBuka-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [KiniBuka-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/kinibuka-desktop/KiniBuka-macOS-AppleSilicon.dmg) | Open it and drag KiniBuka to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [KiniBuka-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/kinibuka-desktop/KiniBuka-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/kinibuka/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [KiniBuka-android.apk](https://github.com/juw12/projects/releases/download/kinibuka-android/KiniBuka-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load KiniBuka 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 kinibuka-desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload kinibuka-desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit kinibuka-desktop --notes-file notes.md --repo "$REPO" + else + gh release create kinibuka-desktop $FILES SHA256SUMS.txt --title "KiniBuka for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/apps/kinibuka/README.md b/apps/kinibuka/README.md index 591270ca..4d547e03 100644 --- a/apps/kinibuka/README.md +++ b/apps/kinibuka/README.md @@ -46,6 +46,15 @@

+## Get it on your device + +- **Windows:** [`KiniBuka-Windows-Setup.exe`](https://github.com/juw12/projects/releases/download/kinibuka-desktop/KiniBuka-Windows-Setup.exe) (no admin needed; if Windows says it protected your PC, choose *More info → Run anyway*), or without installing [`KiniBuka-Windows-Portable.zip`](https://github.com/juw12/projects/releases/download/kinibuka-desktop/KiniBuka-Windows-Portable.zip). +- **Mac:** [`KiniBuka-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/kinibuka-desktop/KiniBuka-macOS-AppleSilicon.dmg) (M1 and newer) or [`KiniBuka-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/kinibuka-desktop/KiniBuka-macOS-Intel.dmg). The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`KiniBuka-android.apk`](https://github.com/juw12/projects/releases/download/kinibuka-android/KiniBuka-android.apk): open the file on the phone and allow your browser to install apps once. +- **iPhone:** open https://juw12.github.io/projects/kinibuka/ 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. + ## About **Kini buka** means "open now". KiniBuka helps people find small Indonesian food and retail stalls (UMKM) that are open right now, follow the ones they like, and order ahead. diff --git a/apps/kinibuka/android/.gitignore b/apps/kinibuka/android/.gitignore new file mode 100644 index 00000000..edd9d60a --- /dev/null +++ b/apps/kinibuka/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/apps/kinibuka/android/AndroidManifest.xml b/apps/kinibuka/android/AndroidManifest.xml new file mode 100644 index 00000000..0fab009f --- /dev/null +++ b/apps/kinibuka/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/apps/kinibuka/android/README.md b/apps/kinibuka/android/README.md new file mode 100644 index 00000000..2d05ffa9 --- /dev/null +++ b/apps/kinibuka/android/README.md @@ -0,0 +1,34 @@ +# KiniBuka for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/projects/kinibuka/): the same KiniBuka 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: [`KiniBuka-android.apk`](https://github.com/juw12/projects/releases/download/kinibuka-android/KiniBuka-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/kinibuka/android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/kinibuka-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 +`KiniBuka-android.apk` on the `kinibuka-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/kinibuka/android/app.json b/apps/kinibuka/android/app.json new file mode 100644 index 00000000..b4c17d95 --- /dev/null +++ b/apps/kinibuka/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "KiniBuka", + "id": "io.github.juw12.kinibuka", + "url": "https://juw12.github.io/projects/kinibuka/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/apps/kinibuka/android/assets/offline.html b/apps/kinibuka/android/assets/offline.html new file mode 100644 index 00000000..d9d94c3c --- /dev/null +++ b/apps/kinibuka/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + KiniBuka + + + +
+ +

KiniBuka can't reach the internet

+

KiniBuka 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/kinibuka/android/build.py b/apps/kinibuka/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/apps/kinibuka/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/kinibuka/android/res/mipmap-xxxhdpi/ic_launcher.png b/apps/kinibuka/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..1a299abe1455364a7f5a8efb9b64c3ffff0c54df GIT binary patch literal 4411 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 a!5v@YF + + #fbfaf6 + + diff --git a/apps/kinibuka/android/smoke.py b/apps/kinibuka/android/smoke.py new file mode 100644 index 00000000..ee611e6b --- /dev/null +++ b/apps/kinibuka/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the KiniBuka APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/KiniBuka-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("\nKiniBuka 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/kinibuka/android/src/io/github/juw12/kinibuka/MainActivity.java b/apps/kinibuka/android/src/io/github/juw12/kinibuka/MainActivity.java new file mode 100644 index 00000000..ad4eccbe --- /dev/null +++ b/apps/kinibuka/android/src/io/github/juw12/kinibuka/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.kinibuka; + +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; + +/** + * KiniBuka 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/kinibuka/"; + private static final String SCOPE = "juw12.github.io/projects/kinibuka"; + 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() + " KiniBukaAndroid/" + 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("KiniBukaShell", "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("KiniBukaShell", "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/kinibuka/desktop/.gitignore b/apps/kinibuka/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/apps/kinibuka/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/apps/kinibuka/desktop/README.md b/apps/kinibuka/desktop/README.md new file mode 100644 index 00000000..8c05ba0b --- /dev/null +++ b/apps/kinibuka/desktop/README.md @@ -0,0 +1,25 @@ +# KiniBuka for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/kinibuka/): 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 KiniBuka 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 | +| --- | --- | +| `kinibuka_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 | +| `kinibuka.spec`, `kinibuka.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 KiniBuka | +| `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/kinibuka-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 +[kinibuka-desktop release](https://github.com/juw12/projects/releases/tag/kinibuka-desktop). The download links never change. diff --git a/apps/kinibuka/desktop/build.py b/apps/kinibuka/desktop/build.py new file mode 100644 index 00000000..16579945 --- /dev/null +++ b/apps/kinibuka/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the KiniBuka 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 KiniBuka-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + KiniBuka-Windows-Portable.zip unzip and run KiniBuka.exe + macOS KiniBuka-macOS-AppleSilicon.dmg or KiniBuka-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', 'KiniBuka - Find small stalls that are open right now'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'KiniBuka'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'KiniBuka.exe'), + StringStruct('ProductName', 'KiniBuka'), + 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, "kinibuka.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, KINIBUKA_VERSION=version, KINIBUKA_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["KINIBUKA_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "kinibuka.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, "KiniBuka") + portable = os.path.join(DIST, "KiniBuka-Windows-Portable.zip") + zip_folder(folder, portable, "KiniBuka") + 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 KiniBuka-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped KiniBuka-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, "kinibuka.iss")], + check=True, + ) + return [os.path.join(DIST, "KiniBuka-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "KiniBuka.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "KiniBuka-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, "KiniBuka.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "KiniBuka", "-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 KiniBuka 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("KiniBuka desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by kinibuka.spec) + except ImportError: + raise SystemExit("The KiniBuka window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("KiniBuka", "KiniBuka.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building KiniBuka %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/kinibuka/desktop/icon-512.png b/apps/kinibuka/desktop/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..3db1016268baa4d5210fbf3f76cd2d97c53e673e GIT binary patch literal 8547 zcmeHN~oh1GilI z@0S1S<^SLeU%AJ~>mCS|UMWz#e}CZnOTne)w5B`fl#c~f`u%wA&1q`u>DnKV)$_C| zT{)y8GFcs`xP~dKWq4MAUugbMvUs8#O+p>sI)^L&;Bv5ge#|%=t9t zJ0y{!*3&QewsYo2nM>#2+Bue4{E1icQt@G-1so_DQSKa*9i3Xy-ByBae9hZiGjT{D z6l}@RPyGE@tcg08q{0!W6l%n2_KbjvW2(t@64$iyNyZlMNbFM7))Cs=T^s7H-~`U5>so)Uscs~OKwvwXK25CIH+}iy z`k8}2ej^{H*L%?57xszE$j#0$w~EC-bLfb{{CIt)50zqBA;Na{>e0@VeGkWc`-vO! z%hkLoj#H@?YTTWZ5}^D;rD$91rx^!qJF1Py!al{hyU||IKD~rv*k)orC9_c+C-T$f zYi}w=P^EIUTv)V{BpJ8%Bd^8?R=b?kq{G_Z94yzTxt@-__mK;KtOxDdO=O?=s!;^k zubh*1*$H|2noo%E#B`7z!I0HC*m z8Q*hP37osXkcj2YwB-&Tbn}`^>!2m~yxn^I9c`r#F0Ik+H$u+tufGtj^xCWZ2NVil zIO%DTn>-v@a}DI=-Vc_L!N=QUWO-^_zXU$Lp-rILx0V#5Q2>oEx~_>uTx2^^zE2SK zIll7>f28M4zFlk$z3Y||xv_GP5`{v%Td7OG>pWel`+%$EQ{##=b4fEyBboCYsat9* zTXaAWi59q-a#M|Jf69|yFY|ZuDI>Z~HB3Y@qj0#`RASC^MS~?y1hl+<&z?l>frZyz z!j*Ghhq`nt!tBmiL^uz&#c86%bt&Jd28Y=(XQQYo&LASvA0}nQQq9L<+<~H`QCPii zWz9PJZ_DW|5pr+D$?triFwJG)0H47lzh?FKf!~pgwD+UH>-SV=B**x;yO3yZo`T1Y z3$aNp42cYky=jRbawj4m=h|6j(lD9GYZ8!1Q8MnkULkue;J5+CO+qP8x$yc$w}*eb zccvIzc);sMF^vb5Z$wfR4O~#krp=WvFZ1ns$^CnFU_2`L>+e>v3xrk=Z8GV2L4r`f~LOAn8h@5; zLw$@-T|Zo@y;PfAHTea{Pdb7jdL*5Otzna(NW8l;fAiFiP^)Q)1_9YsM@AHV zTm+0_&kaW2TU6J~?1T1k4WQt^^2@YB4{ksMxdD##(S;hvh^ZS@n!ic>3=Y>l2w?9kxrA$np>@gQ!P*?1v92j~ux3it_pIt?gc4H`L! zqh3qT+pWXHh|p^s zImHgjx*SF?38+M?@xygttcNy_Sy&=Hy^Tb9Tw$c23IXF~`KlC~jbiv5056)nyXsrF`lKTYatE>p%V-yl!a+q}Hac+WugsNfjR{9ncxf==A_+shoqPD!k8eSxn z`X(9dH_w`OjOC!{K0{T>pUbr`N)fTk@8bL<7rxr79KB35%f#I@Lr{Pn6aKNDz-q~# zFA@Zog=J^(dM7rb3mR?+oj`yZ!zV$J@AJmlnXO`0-w(G8n-i*iUDRqICEKUnW?BkO zucgNBym0z32Sf8A>y~W!s-=XFrtJN)$Q*wFCQgkA$XQ_hBR)UK7Esfi8`HZgKpiVN89SmdO@Dgv}GOiEEA?oXa+e%CpbzO23Q z<+nXEms}o-;n7J1II4vaCRKD%Ng}kkY6>&Y$U&RB+M zPWz}?N#DuQFNPBW@`f3Z_%s4&JCvdNmS#>~Kl8|3u*2KaYTede=ae3##VP@A;|G>q zzx3?wx_ET-8^5(T%R!kI3onoP)omcbZD-2Lz{Ay~G#3r6Q;s%cDd9NJ+LA9y1nzut zGEg2bG#5d1RWzt|F=q_YTPE&A_ z8eF1PXEVK*gU75M49Y`BFlhSmreGn_sk*`ZRVi`!Z7kHn>R?3!Tt!j<@qv83k14*j zzuEq1|IDs=ur+0DpET@bMBt8i4eB~zHfBExFAyqKVaqH0>IHS5Fyd`M;AZd#btQ`y z7s9<JvYk`W{cOO#kK&FzA zDRXa{NyqZ>l!C`C9!){itZF_*%P!w=H@O)R=&{=wx92(%Ps3!vmS?sa(^Oim^U&iV zHc8ibDmRus~W8P^G4B3BXm;C>g*K z7h1y>7O-wYLK(fgU2meBFSy!$4K1}F@6ZVsT=yItJfXx5^2JF>bi)3AH75A_I7TWC zpJ;^fzz1DJ0)e(ECz_+Bt#?%7dOt_@diH30br%xJb|fgkr`ZR78DaOi5>rA;9rqRm zg?%zm)RQAfkdyUKrnJeUnbY#r5SkFPD8fmhR~3NSy@5laE6z_?&Bc?NOBV~y@Bdwa zGOvw6n#>V$?;D5TGq1<}FBtD~t-y$0tA_EHhSHSbbY*-l9*^>$*nEYd+Aa^ueR-HWI-UUgtQ+%|QqaOs8~O3wlnTxLW8 zGE`Q&VOmU*^m{ixSpCPc8v=xpqzQ>9H3K-Ed$YNZF)x&sT5ONYs=NL*$(8;=fXNog zytPj9S05v~%^(WAZWs#`emS(zv*BE|-|!L%Xjq~XufBw+1v6rml6P!zT%QhsxsHVo zTz%-0Iv6j-^kXsLN=O;bUEgtGy&@A}Xb@;eSo4#d=x(ScmXY~Pq^#@!TcZSXj=yi- zRTYn0w>#p4AJRUJ?C3n1|p5){B(XF>Ya#HKc znWJe9SQ2ZNbUn9ezTjst4;{pj0>nxgckqbV+4N<`6uy6@r5xC#Oj=>20Mb(N(dw}h z?RGDUqIm@5o=o<=hqv>gK%nL5#3mOQ1(k{mX05xPJqQt(aPN^lMzZzy1$-kZ5!xP* zZTiUExFDzwZ%yC@U8%4_9hn$zAJ67u$92ReTJMNcMuY+dzYfCY;sM^|}UB}FF@ zu<#)0YNGQ_;mL$XOzpg(yof$L#GM-`j5$$C6=lwysmY{$#tRe@LR7+Qp|S-;Rbg6C zu$1^_ZD49RwoG{z?p2WNtFurJXbdbEy-I}uWaoIVS=DJZ=-Ykv1K`z1If2yvt(8ZP zr(Xkr=yz}F`W0z;isJ%_u$)h^FmqNqew35u5D6G8`Nw*tN4x!8gWM=US8}r=`Lv;- z2VP~6905cf%8iG5osI2Sv+3U|^AO*;0b2b%fA?Vq&5RiO6oe=}9ixIxi&b3~y-QlfZSATsTv60_Zv!(6mH<{( z)!6;5Oe(BwktUl>T~eU(IVBj}(+pq`+a$tzO7*i=*=mla6_M&jIHp}MgF2Y@?B?jD zrm=dY02x44I8;45DjT}98$iUH>dF^<&!{qp$$FUde8p}7LIDXr70;U{CCU4^Efh@K zA2k<#Oh21wnoi?3W={p1lBGnl*N|2FF8SQw@FXp_tWA010H!=n!&WXsmE}JU?S7uj z-`6TX%DGZQ__TcHfzgmV(LTvwYcMD=%fLKqFXs0c=X@rV=_WAa$}CNIB>BQ_mfmDt z-|MSG?+MQqvxHS#R9|@tj-Q(hfmVx$fV!S*uWR~suUo$SFp750ElD>6dOK9MU&GkH zxu(9mc$aH@ciY_L&&-yGo@`;`()wksI}&eK@cZ?!_<{N8(fAb0e)RaEiR~;){E+Y< z>iI}((iK1R(1pQs+37fbGiM5bbu(MX%@TYkbJvX)Oh*rHjZ3VayxLV~q2&KhEVwBF zv&X23k%EnZ6M492VVT24i{0nt@-$*D|0gQY36NDk#AH2LH?`Ht%u-IG6YjZrJ`A(( z<>enCA43Sm-&dk&J$;QZnB8UqZD(GE!vus^Wm@rkYK34y*=f5oocUsu~S0V@>6xA>Al#OhTa% zTib%ubB#_~YT6!Iq)h;*Bdg+EZ3#NHjPg|;}*yTl@7%8=?x`sjNe{az<_bvyc>Vm#og%Fwr--I=*~c?b15 zhM%MZ?k{}8u6J-kPby{vr_rG`{#p0FV?SnopbV1wa$03-PPuNuEDk2^@k+PdhSV- zoXi6#4BU0tfs-jW>luCfBc$c(F_gM}o}WeMu3pdxDs9^aS`Zew=;xW@T!x~%?OD^* z=4omo*fTY*`A%PR=A1?!@>I;Bw-~^@i`U^mh`n!iMNZ3LbiLM!zPIgJ4N8S)_g!lF z8=y{>ctF?RB@KEnkAab57O}uu%FGgW;>J6{78^llk+|?*U9!gn0)ayKfjKIAY`-RR z_-Qa}-2v&kheT0c-fOV$$UjL2Xt#w2x7LN{P}c8i>i))AwPe#yNI&9dImskFU*7$; z($8@SqWPo!Aal9!Zi{|mZ-Hyjwy)VHw*LM%m_tjFM%Ca!G-SXCz#SmWji9k%j7n^x%}!Gw9xQ?n|5$N_?P>WkjNLlO#&_yC?exJ}^s~iIRaq z=Owdr?Vq2+)QSvYJ^dGUp#63nGPcFL))JF3?_mcEO$|rL4pDCHLoQaWjt$YmaAt4XbiBRVRnQ5IW@U`T<_3nd%D){9_cYhPD$ak2MGLZ`h-hX6JtSuaZp zNTOb18k+p3*X)tNj7Yi^t#rn}@qCI5ycs0PwZ-bqG;$tdF(nT`bJ@fel!CmY$$uJJ+YEF)alVGSF9# ztv|-vZi=n(J$*9jOe)-W8#a@$h--^0Y&$S_RStZn*6Ju(F8fG`4D6V~iDb~He~f!M z-OvDzS)js(89=gnPD0`6KRzYPxttWytw3Pzg6Y}y%YjkMt|67_%M(a9bB#{da$^Yj zloa6W6d_>CH-Zq*m(m|@XhyPM^9|HFciXgo=1X8PLZ^hzO_BqS z8{rJkmHssv)(vBO5S;O)bh`IRxnk>5XYfbZjJvkZZRPs3k&%QQ4qF|~*JB#f;&woS z2Xk*XPDs>7SOf>)h<$I8ySU-^3a~Ojj+h)(nXR(n2c$0uVwMiQT{T_-9-xq1LU%NF z5;CZ9xznYAacu7Vz<`ca3dhSWSq$_5ns}sVKc2Ov6gSS&j%DH zJ+iC>3!rZ-Rs>Nw8KPGh0e3RA-qGyYQ-jiyGS>=QtE(ZW3fRpm>>o&3+i;9dg>f#Q zergYALrDYFnVb|~VWExpKL$lFH#S~fh4$&=A>$4X2cM@Q&K~03`DcnN3cOVf;&J>B z^xzmxjvjIK&3U-LBHq}y-urRM9YC@EQqY0*1G`QW3k3HoGsSJcL#=*|uW#RmOZ^*X z(fS+FD`N2aL9OqlYC_;a7vVwU1}9`9G|#BmaKv9LAx9|THPV(@v+w`_N_xl9cV zAEwe^^Yyg0kLPp2d7f=Le=WkpO7-4*9-;V4Lwn&{EoN{sNsAKempyh63XqywCb=}b zcl=x5A2pQdiAQn@>r$#L4X6^3Ya)Jwl`fi z2Y7qm{@Jy+hsyZ2Ls7{TSKi9TK^g=@T2@~Kh+N>TH-c##C$>fYVG`-?VwD4>(SW19 z7QE8Iys=Lp@XGs;*JIqO|u9*)_4k>ARZ zhN9SEB3-HM%OA`4<7_RRQBj|}c^YQb^q+SmjAV@6C-db2h4EuPnycWVID7XEv`!>D z|M1=iM*^ju!|}XoIH?W$J8R8pmireW@N7vQ8_nK*aCW4WnPZyV%Mj9fRWBz0q$=pw z#d7X>)M8Q%!!onnww`ju;s--dT)f}X>3BRZ7oL*!_Da~ozRUVrOP-aG)5%?GQu#KQ zBOJ-r=KEX>!;E0C7|2nppsU8$s(A_*MZoTqCC+i$ocP+fLK&UJ2pq#OH?;E!s*~ZU zgQ5nDk|gATV=ktoaC^p7uK#gm%~L4;uE@1Ian(BtlgefM z(U&x|2n(xF1pdQUZMVJ&Hj_K&;Hf%n|1=Y=OW^p-AdyK=->6`3J^huu5E&es&VI`} zoX5G7J80RNKius}sxeI6XD*S=Nvd$dx4FKO`7$tL>_e<7>@eDtvoW3WGR`2KS9aAnl+%cyY82Tt-u5Zpk3`8(7fP)Z`Uqg$5 z+s3#RjG5}z&X%UXk-*$h^!iKJa)hsZ7e#z5DqROON535rh}FzYICJn|=`mIAkN z)lwO(*{Vku!B+u6r|Z3Y>6N3HR{do7QbzS@d3=97tWe8H=u42uV83Xk`CdNu#bFPe z>F8~`!-pfODkoy1dufq=oG1mDXyst}FkE!+$^IYsDDv=I0nfFRXg7+@U8@%Btov6~ z!dar(rF`Ayet(P$D`*apVi!{OYHg(C(3*+8*eIUM`u;SFuCR>c<;GbzDRw#y9a~#- zwL6bJVY5HoFn3}*UaorU_CudnxNj-2cLXVA)X4unBLDa0{Qu(@1 /DOutputDir= /DIconFile= kinibuka.iss +; Installs to %LOCALAPPDATA%\Programs\KiniBuka, adds KiniBuka 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%\KiniBuka, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\KiniBuka" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\kinibuka.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=KiniBuka +AppVersion={#AppVersion} +AppVerName=KiniBuka {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/kinibuka/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\KiniBuka +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=KiniBuka-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\KiniBuka.exe +UninstallDisplayName=KiniBuka +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}\KiniBuka"; Filename: "{app}\KiniBuka.exe"; Comment: "Find small stalls that are open right now" +Name: "{userdesktop}\KiniBuka"; Filename: "{app}\KiniBuka.exe"; Comment: "Find small stalls that are open right now"; Tasks: desktopicon + +[Run] +Filename: "{app}\KiniBuka.exe"; Description: "{cm:LaunchProgram,KiniBuka}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\KiniBuka.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopKiniBuka" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open KiniBuka window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\KiniBuka.exe')) then + Exec(ExpandConstant('{app}\KiniBuka.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/apps/kinibuka/desktop/kinibuka.spec b/apps/kinibuka/desktop/kinibuka.spec new file mode 100644 index 00000000..4d268f1f --- /dev/null +++ b/apps/kinibuka/desktop/kinibuka.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for KiniBuka on Windows and macOS. Build with python desktop/build.py +# Windows dist/KiniBuka/KiniBuka.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/KiniBuka.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("KINIBUKA_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("KINIBUKA_VERSION_FILE") or None +ICON = os.environ.get("KINIBUKA_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, "kinibuka_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="KiniBuka", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="KiniBuka", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="KiniBuka.app", + icon=ICON, + bundle_identifier="io.github.juw12.kinibuka.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "KiniBuka", + "CFBundleDisplayName": "KiniBuka", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/apps/kinibuka/desktop/kinibuka_app.py b/apps/kinibuka/desktop/kinibuka_app.py new file mode 100644 index 00000000..25e8cf99 --- /dev/null +++ b/apps/kinibuka/desktop/kinibuka_app.py @@ -0,0 +1,467 @@ +"""KiniBuka for Windows and macOS: the KiniBuka 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/kinibuka/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time KiniBuka 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 +KiniBuka opens in the default browser instead. + +Opening KiniBuka while its window is open brings that window to the front; `KiniBuka --stop` closes it. + +Automated checks: KINIBUKA_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; KINIBUKA_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 = "KiniBuka" +APP_URL = os.environ.get("KINIBUKA_DESKTOP_URL") or "https://juw12.github.io/projects/kinibuka/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#fbfaf6" +DARK_BACKGROUND = "#fbfaf6" +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('kinibuka.desktop.check', '1');" + " return localStorage.getItem('kinibuka.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("[kinibuka] " + 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"), "KiniBuka") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "KiniBuka") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "kinibuka") + + +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 KiniBuka site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "KiniBukaDesktop/" + 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="kinibuka-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 KiniBuka 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 KiniBuka 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 KiniBuka 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="kinibuka-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("KiniBuka %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("KINIBUKA_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/kinibuka/desktop/offline.html b/apps/kinibuka/desktop/offline.html new file mode 100644 index 00000000..e09eed12 --- /dev/null +++ b/apps/kinibuka/desktop/offline.html @@ -0,0 +1,25 @@ + + + + + + KiniBuka + + + +
+ +

KiniBuka can't reach the internet

+

KiniBuka 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/kinibuka/desktop/shell.json b/apps/kinibuka/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/apps/kinibuka/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/apps/kinibuka/desktop/smoke_test.py b/apps/kinibuka/desktop/smoke_test.py new file mode 100644 index 00000000..2f10e92f --- /dev/null +++ b/apps/kinibuka/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built KiniBuka desktop app and check its window really shows KiniBuka. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/KiniBuka.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with KINIBUKA_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is KiniBuka, 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", "kinibuka", "guide")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/kinibuka/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "KiniBuka", "KiniBuka.exe") + return os.path.join(DESKTOP, "dist", "KiniBuka.app", "Contents", "MacOS", "KiniBuka") + + +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 KiniBuka 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="kinibuka-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, KINIBUKA_WINDOW_TEST=report, KINIBUKA_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 "KiniBuka" 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("KiniBuka 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: KiniBuka %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main() From 5e4598834931f89fa02a5a050d0014eb9830bfc3 Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:50:26 +0700 Subject: [PATCH 3/5] Push Lab for Windows, Mac and Android: the web app in its own window, built and opened on each system before it is published --- .github/workflows/pushlab-android.yml | 137 +++++ .github/workflows/pushlab-desktop.yml | 177 +++++++ apps/pushlab/README.md | 9 + apps/pushlab/android/.gitignore | 2 + apps/pushlab/android/AndroidManifest.xml | 23 + apps/pushlab/android/README.md | 34 ++ apps/pushlab/android/app.json | 10 + apps/pushlab/android/assets/offline.html | 25 + apps/pushlab/android/build.py | 98 ++++ .../res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 3400 bytes apps/pushlab/android/res/values/styles.xml | 11 + apps/pushlab/android/smoke.py | 128 +++++ .../io/github/juw12/pushlab/MainActivity.java | 283 +++++++++++ apps/pushlab/desktop/.gitignore | 3 + apps/pushlab/desktop/README.md | 25 + apps/pushlab/desktop/build.py | 174 +++++++ apps/pushlab/desktop/icon-512.png | Bin 0 -> 5647 bytes apps/pushlab/desktop/offline.html | 25 + apps/pushlab/desktop/pushlab.iss | 73 +++ apps/pushlab/desktop/pushlab.spec | 64 +++ apps/pushlab/desktop/pushlab_app.py | 467 ++++++++++++++++++ apps/pushlab/desktop/shell.json | 3 + apps/pushlab/desktop/smoke_test.py | 92 ++++ 23 files changed, 1863 insertions(+) create mode 100644 .github/workflows/pushlab-android.yml create mode 100644 .github/workflows/pushlab-desktop.yml create mode 100644 apps/pushlab/android/.gitignore create mode 100644 apps/pushlab/android/AndroidManifest.xml create mode 100644 apps/pushlab/android/README.md create mode 100644 apps/pushlab/android/app.json create mode 100644 apps/pushlab/android/assets/offline.html create mode 100644 apps/pushlab/android/build.py create mode 100644 apps/pushlab/android/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 apps/pushlab/android/res/values/styles.xml create mode 100644 apps/pushlab/android/smoke.py create mode 100644 apps/pushlab/android/src/io/github/juw12/pushlab/MainActivity.java create mode 100644 apps/pushlab/desktop/.gitignore create mode 100644 apps/pushlab/desktop/README.md create mode 100644 apps/pushlab/desktop/build.py create mode 100644 apps/pushlab/desktop/icon-512.png create mode 100644 apps/pushlab/desktop/offline.html create mode 100644 apps/pushlab/desktop/pushlab.iss create mode 100644 apps/pushlab/desktop/pushlab.spec create mode 100644 apps/pushlab/desktop/pushlab_app.py create mode 100644 apps/pushlab/desktop/shell.json create mode 100644 apps/pushlab/desktop/smoke_test.py diff --git a/.github/workflows/pushlab-android.yml b/.github/workflows/pushlab-android.yml new file mode 100644 index 00000000..8a167d2d --- /dev/null +++ b/.github/workflows/pushlab-android.yml @@ -0,0 +1,137 @@ +name: PushLab Android app + +# Builds PushLab-android.apk (apps/pushlab/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 pushlab-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "apps/pushlab/android/**" + - ".github/workflows/pushlab-android.yml" + pull_request: + paths: + - "apps/pushlab/android/**" + - ".github/workflows/pushlab-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/pushlab/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/pushlab/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/pushlab/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs apps/pushlab/android/dist/PushLab-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd apps/pushlab/android/dist && sha256sum PushLab-android.apk > PushLab-android.apk.sha256 && cat PushLab-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: pushlab-android + path: apps/pushlab/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: pushlab-android + path: apps/pushlab/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/pushlab/android/smoke.py apps/pushlab/android/dist/PushLab-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: pushlab-android-emulator-check + path: | + apps/pushlab/android/dist/*.png + apps/pushlab/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: pushlab-android + path: dist + # The pushlab-android release keeps one address for the download. The file there is replaced only when + # apps/pushlab/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the pushlab-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('apps/pushlab/android/app.json'))['versionName'])") + echo "$version" > dist/PushLab-android.version.txt + if ! gh release view pushlab-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "Push Lab for Android: a full-screen window around the web app (https://juw12.github.io/projects/pushlab/)." "" \ + "Download [PushLab-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/pushlab-android/PushLab-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 pushlab-android dist/PushLab-android.apk dist/PushLab-android.apk.sha256 dist/PushLab-android.version.txt \ + --title "Push Lab for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the pushlab-android release with PushLab-android.apk $version" + exit 0 + fi + published=$(gh release download pushlab-android --repo "$GITHUB_REPOSITORY" --pattern PushLab-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the pushlab-android release already has PushLab-android.apk $version" + exit 0 + fi + gh release upload pushlab-android dist/PushLab-android.apk dist/PushLab-android.apk.sha256 dist/PushLab-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "PushLab-android.apk on the pushlab-android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/pushlab-desktop.yml b/.github/workflows/pushlab-desktop.yml new file mode 100644 index 00000000..2f7d1d12 --- /dev/null +++ b/.github/workflows/pushlab-desktop.yml @@ -0,0 +1,177 @@ +name: PushLab apps + +# Builds the downloadable PushLab apps and publishes them to the "pushlab-desktop" release from main: +# Windows PushLab-Windows-Setup.exe (per-user installer) + PushLab-Windows-Portable.zip +# macOS PushLab-macOS-AppleSilicon.dmg + PushLab-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/pushlab/desktop/**' + - '.github/workflows/pushlab-desktop.yml' + pull_request: + paths: + - 'apps/pushlab/desktop/**' + - '.github/workflows/pushlab-desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pushlab-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/pushlab/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's PushLab + run: python apps/pushlab/desktop/smoke_test.py --built --local-site + - name: Install with PushLab-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'apps/pushlab/desktop/dist/PushLab-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'pushlab-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\PushLab\PushLab.exe' + if (-not (Test-Path $app)) { throw "PushLab.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'PushLab.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'PushLab.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 'PushLab' + if (-not $entry) { throw 'PushLab is missing from Settings > Apps' } + python apps/pushlab/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 PushLab.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/pushlab/desktop/dist/PushLab.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.pushlab.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("apps/pushlab/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/PushLab")" + codesign --verify --deep --verbose=2 "$APP" + for image in apps/pushlab/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: PushLab-${{ runner.os }}-${{ runner.arch }} + path: apps/pushlab/desktop/dist/PushLab-* + 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: PushLab-* + 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 PushLab-Windows-Setup.exe PushLab-Windows-Portable.zip \ + PushLab-macOS-AppleSilicon.dmg PushLab-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' + **Push Lab**: send push from your own server, and prove it works on a real phone. The apps open the same Push Lab as https://juw12.github.io/projects/pushlab/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [PushLab-Windows-Setup.exe](https://github.com/juw12/projects/releases/download/pushlab-desktop/PushLab-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: [PushLab-Windows-Portable.zip](https://github.com/juw12/projects/releases/download/pushlab-desktop/PushLab-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [PushLab-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/pushlab-desktop/PushLab-macOS-AppleSilicon.dmg) | Open it and drag PushLab to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [PushLab-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/pushlab-desktop/PushLab-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/pushlab/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [PushLab-android.apk](https://github.com/juw12/projects/releases/download/pushlab-android/PushLab-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load PushLab 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 pushlab-desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload pushlab-desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit pushlab-desktop --notes-file notes.md --repo "$REPO" + else + gh release create pushlab-desktop $FILES SHA256SUMS.txt --title "Push Lab for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/apps/pushlab/README.md b/apps/pushlab/README.md index 4cad2f43..8a01cb55 100644 --- a/apps/pushlab/README.md +++ b/apps/pushlab/README.md @@ -47,6 +47,15 @@

+## Get it on your device + +- **Windows:** [`PushLab-Windows-Setup.exe`](https://github.com/juw12/projects/releases/download/pushlab-desktop/PushLab-Windows-Setup.exe) (no admin needed; if Windows says it protected your PC, choose *More info → Run anyway*), or without installing [`PushLab-Windows-Portable.zip`](https://github.com/juw12/projects/releases/download/pushlab-desktop/PushLab-Windows-Portable.zip). +- **Mac:** [`PushLab-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/pushlab-desktop/PushLab-macOS-AppleSilicon.dmg) (M1 and newer) or [`PushLab-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/pushlab-desktop/PushLab-macOS-Intel.dmg). The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`PushLab-android.apk`](https://github.com/juw12/projects/releases/download/pushlab-android/PushLab-android.apk): open the file on the phone and allow your browser to install apps once. +- **iPhone:** open https://juw12.github.io/projects/pushlab/ 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. + ## About **Send push notifications from your own server, and prove they work on a real phone.** One self-hosted, diff --git a/apps/pushlab/android/.gitignore b/apps/pushlab/android/.gitignore new file mode 100644 index 00000000..edd9d60a --- /dev/null +++ b/apps/pushlab/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/apps/pushlab/android/AndroidManifest.xml b/apps/pushlab/android/AndroidManifest.xml new file mode 100644 index 00000000..ce4f772b --- /dev/null +++ b/apps/pushlab/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/apps/pushlab/android/README.md b/apps/pushlab/android/README.md new file mode 100644 index 00000000..53bd9264 --- /dev/null +++ b/apps/pushlab/android/README.md @@ -0,0 +1,34 @@ +# Push Lab for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/projects/pushlab/): the same Push Lab 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: [`PushLab-android.apk`](https://github.com/juw12/projects/releases/download/pushlab-android/PushLab-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/pushlab/android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/pushlab-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 +`PushLab-android.apk` on the `pushlab-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/pushlab/android/app.json b/apps/pushlab/android/app.json new file mode 100644 index 00000000..1a5010b4 --- /dev/null +++ b/apps/pushlab/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "PushLab", + "id": "io.github.juw12.pushlab", + "url": "https://juw12.github.io/projects/pushlab/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/apps/pushlab/android/assets/offline.html b/apps/pushlab/android/assets/offline.html new file mode 100644 index 00000000..e66246aa --- /dev/null +++ b/apps/pushlab/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + Push Lab + + + +
+ +

Push Lab can't reach the internet

+

Push Lab 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/pushlab/android/build.py b/apps/pushlab/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/apps/pushlab/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/pushlab/android/res/mipmap-xxxhdpi/ic_launcher.png b/apps/pushlab/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..076137295f571366ff19a3e5a503daf756548f87 GIT binary patch literal 3400 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 literal 0 HcmV?d00001 diff --git a/apps/pushlab/android/res/values/styles.xml b/apps/pushlab/android/res/values/styles.xml new file mode 100644 index 00000000..9514b4a1 --- /dev/null +++ b/apps/pushlab/android/res/values/styles.xml @@ -0,0 +1,11 @@ + + + #fbfaf6 + + diff --git a/apps/pushlab/android/smoke.py b/apps/pushlab/android/smoke.py new file mode 100644 index 00000000..f590dd4f --- /dev/null +++ b/apps/pushlab/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the PushLab APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/PushLab-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("\nPushLab 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/pushlab/android/src/io/github/juw12/pushlab/MainActivity.java b/apps/pushlab/android/src/io/github/juw12/pushlab/MainActivity.java new file mode 100644 index 00000000..cb7498f5 --- /dev/null +++ b/apps/pushlab/android/src/io/github/juw12/pushlab/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.pushlab; + +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; + +/** + * PushLab 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/pushlab/"; + private static final String SCOPE = "juw12.github.io/projects/pushlab"; + 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() + " PushLabAndroid/" + 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("PushLabShell", "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("PushLabShell", "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/pushlab/desktop/.gitignore b/apps/pushlab/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/apps/pushlab/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/apps/pushlab/desktop/README.md b/apps/pushlab/desktop/README.md new file mode 100644 index 00000000..d5183d73 --- /dev/null +++ b/apps/pushlab/desktop/README.md @@ -0,0 +1,25 @@ +# PushLab for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/pushlab/): 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 PushLab 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 | +| --- | --- | +| `pushlab_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 | +| `pushlab.spec`, `pushlab.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 PushLab | +| `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/pushlab-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 +[pushlab-desktop release](https://github.com/juw12/projects/releases/tag/pushlab-desktop). The download links never change. diff --git a/apps/pushlab/desktop/build.py b/apps/pushlab/desktop/build.py new file mode 100644 index 00000000..d3d0eb69 --- /dev/null +++ b/apps/pushlab/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the PushLab 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 PushLab-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + PushLab-Windows-Portable.zip unzip and run PushLab.exe + macOS PushLab-macOS-AppleSilicon.dmg or PushLab-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', 'PushLab - Send push from your own server, and prove it works on a real phone'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'PushLab'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'PushLab.exe'), + StringStruct('ProductName', 'PushLab'), + 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, "pushlab.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, PUSHLAB_VERSION=version, PUSHLAB_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["PUSHLAB_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "pushlab.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, "PushLab") + portable = os.path.join(DIST, "PushLab-Windows-Portable.zip") + zip_folder(folder, portable, "PushLab") + 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 PushLab-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped PushLab-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, "pushlab.iss")], + check=True, + ) + return [os.path.join(DIST, "PushLab-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "PushLab.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "PushLab-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, "PushLab.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "PushLab", "-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 PushLab 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("PushLab desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by pushlab.spec) + except ImportError: + raise SystemExit("The PushLab window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("PushLab", "PushLab.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building PushLab %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/pushlab/desktop/icon-512.png b/apps/pushlab/desktop/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..31cdc4fc7162e0c9d6eb3d2f722ed8a2e503b988 GIT binary patch literal 5647 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 + + + + + PushLab + + + +
+ +

PushLab can't reach the internet

+

PushLab 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/pushlab/desktop/pushlab.iss b/apps/pushlab/desktop/pushlab.iss new file mode 100644 index 00000000..4176491d --- /dev/null +++ b/apps/pushlab/desktop/pushlab.iss @@ -0,0 +1,73 @@ +; PushLab for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= pushlab.iss +; Installs to %LOCALAPPDATA%\Programs\PushLab, adds PushLab 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%\PushLab, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\PushLab" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\pushlab.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=PushLab +AppVersion={#AppVersion} +AppVerName=PushLab {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/pushlab/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\PushLab +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=PushLab-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\PushLab.exe +UninstallDisplayName=PushLab +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}\PushLab"; Filename: "{app}\PushLab.exe"; Comment: "Send push from your own server, and prove it works on a real phone" +Name: "{userdesktop}\PushLab"; Filename: "{app}\PushLab.exe"; Comment: "Send push from your own server, and prove it works on a real phone"; Tasks: desktopicon + +[Run] +Filename: "{app}\PushLab.exe"; Description: "{cm:LaunchProgram,PushLab}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\PushLab.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopPushLab" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open PushLab window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\PushLab.exe')) then + Exec(ExpandConstant('{app}\PushLab.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/apps/pushlab/desktop/pushlab.spec b/apps/pushlab/desktop/pushlab.spec new file mode 100644 index 00000000..11a557a1 --- /dev/null +++ b/apps/pushlab/desktop/pushlab.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for PushLab on Windows and macOS. Build with python desktop/build.py +# Windows dist/PushLab/PushLab.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/PushLab.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("PUSHLAB_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("PUSHLAB_VERSION_FILE") or None +ICON = os.environ.get("PUSHLAB_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, "pushlab_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="PushLab", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="PushLab", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="PushLab.app", + icon=ICON, + bundle_identifier="io.github.juw12.pushlab.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "PushLab", + "CFBundleDisplayName": "PushLab", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/apps/pushlab/desktop/pushlab_app.py b/apps/pushlab/desktop/pushlab_app.py new file mode 100644 index 00000000..d9472794 --- /dev/null +++ b/apps/pushlab/desktop/pushlab_app.py @@ -0,0 +1,467 @@ +"""PushLab for Windows and macOS: the PushLab 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/pushlab/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time PushLab 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 +PushLab opens in the default browser instead. + +Opening PushLab while its window is open brings that window to the front; `PushLab --stop` closes it. + +Automated checks: PUSHLAB_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; PUSHLAB_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 = "Push Lab" +APP_URL = os.environ.get("PUSHLAB_DESKTOP_URL") or "https://juw12.github.io/projects/pushlab/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#fbfaf6" +DARK_BACKGROUND = "#fbfaf6" +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('pushlab.desktop.check', '1');" + " return localStorage.getItem('pushlab.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("[pushlab] " + 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"), "PushLab") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "PushLab") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "pushlab") + + +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 PushLab site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "PushLabDesktop/" + 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="pushlab-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 PushLab 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 PushLab 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 PushLab 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="pushlab-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("PushLab %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("PUSHLAB_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/pushlab/desktop/shell.json b/apps/pushlab/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/apps/pushlab/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/apps/pushlab/desktop/smoke_test.py b/apps/pushlab/desktop/smoke_test.py new file mode 100644 index 00000000..86f5d34e --- /dev/null +++ b/apps/pushlab/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built PushLab desktop app and check its window really shows PushLab. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/PushLab.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with PUSHLAB_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is PushLab, 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", "pushlab", "guide")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/pushlab/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "PushLab", "PushLab.exe") + return os.path.join(DESKTOP, "dist", "PushLab.app", "Contents", "MacOS", "PushLab") + + +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 PushLab 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="pushlab-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, PUSHLAB_WINDOW_TEST=report, PUSHLAB_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 "Push Lab" 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("PushLab 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: PushLab %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main() From f1d8b78178d10d3742fe37118694128f9969a061 Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:50:55 +0700 Subject: [PATCH 4/5] E-coder for Windows, Mac and Android: the web app in its own window, built and opened on each system before it is published --- .github/workflows/E-coder-android.yml | 137 +++++ .github/workflows/E-coder-desktop.yml | 177 +++++++ agents-lab/E-coder/README.md | 9 + agents-lab/E-coder/android/.gitignore | 2 + .../E-coder/android/AndroidManifest.xml | 23 + agents-lab/E-coder/android/README.md | 34 ++ agents-lab/E-coder/android/app.json | 10 + .../E-coder/android/assets/offline.html | 25 + agents-lab/E-coder/android/build.py | 98 ++++ .../res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 2566 bytes .../E-coder/android/res/values/styles.xml | 11 + agents-lab/E-coder/android/smoke.py | 128 +++++ .../io/github/juw12/ecoder/MainActivity.java | 283 +++++++++++ agents-lab/E-coder/desktop/.gitignore | 3 + agents-lab/E-coder/desktop/README.md | 25 + agents-lab/E-coder/desktop/build.py | 174 +++++++ agents-lab/E-coder/desktop/ecoder.iss | 73 +++ agents-lab/E-coder/desktop/ecoder.spec | 64 +++ agents-lab/E-coder/desktop/ecoder_app.py | 467 ++++++++++++++++++ agents-lab/E-coder/desktop/icon-512.png | Bin 0 -> 4074 bytes agents-lab/E-coder/desktop/offline.html | 25 + agents-lab/E-coder/desktop/shell.json | 3 + agents-lab/E-coder/desktop/smoke_test.py | 92 ++++ 23 files changed, 1863 insertions(+) create mode 100644 .github/workflows/E-coder-android.yml create mode 100644 .github/workflows/E-coder-desktop.yml create mode 100644 agents-lab/E-coder/android/.gitignore create mode 100644 agents-lab/E-coder/android/AndroidManifest.xml create mode 100644 agents-lab/E-coder/android/README.md create mode 100644 agents-lab/E-coder/android/app.json create mode 100644 agents-lab/E-coder/android/assets/offline.html create mode 100644 agents-lab/E-coder/android/build.py create mode 100644 agents-lab/E-coder/android/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 agents-lab/E-coder/android/res/values/styles.xml create mode 100644 agents-lab/E-coder/android/smoke.py create mode 100644 agents-lab/E-coder/android/src/io/github/juw12/ecoder/MainActivity.java create mode 100644 agents-lab/E-coder/desktop/.gitignore create mode 100644 agents-lab/E-coder/desktop/README.md create mode 100644 agents-lab/E-coder/desktop/build.py create mode 100644 agents-lab/E-coder/desktop/ecoder.iss create mode 100644 agents-lab/E-coder/desktop/ecoder.spec create mode 100644 agents-lab/E-coder/desktop/ecoder_app.py create mode 100644 agents-lab/E-coder/desktop/icon-512.png create mode 100644 agents-lab/E-coder/desktop/offline.html create mode 100644 agents-lab/E-coder/desktop/shell.json create mode 100644 agents-lab/E-coder/desktop/smoke_test.py diff --git a/.github/workflows/E-coder-android.yml b/.github/workflows/E-coder-android.yml new file mode 100644 index 00000000..2caa8380 --- /dev/null +++ b/.github/workflows/E-coder-android.yml @@ -0,0 +1,137 @@ +name: ECoder Android app + +# Builds ECoder-android.apk (agents-lab/E-coder/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 E-coder-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "agents-lab/E-coder/android/**" + - ".github/workflows/E-coder-android.yml" + pull_request: + paths: + - "agents-lab/E-coder/android/**" + - ".github/workflows/E-coder-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 agents-lab/E-coder/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 agents-lab/E-coder/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('agents-lab/E-coder/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs agents-lab/E-coder/android/dist/ECoder-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd agents-lab/E-coder/android/dist && sha256sum ECoder-android.apk > ECoder-android.apk.sha256 && cat ECoder-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: ecoder-android + path: agents-lab/E-coder/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: ecoder-android + path: agents-lab/E-coder/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 agents-lab/E-coder/android/smoke.py agents-lab/E-coder/android/dist/ECoder-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: ecoder-android-emulator-check + path: | + agents-lab/E-coder/android/dist/*.png + agents-lab/E-coder/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: ecoder-android + path: dist + # The E-coder-android release keeps one address for the download. The file there is replaced only when + # agents-lab/E-coder/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the E-coder-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('agents-lab/E-coder/android/app.json'))['versionName'])") + echo "$version" > dist/ECoder-android.version.txt + if ! gh release view E-coder-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "E-coder for Android: a full-screen window around the web app (https://juw12.github.io/projects/e-coder/)." "" \ + "Download [ECoder-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/E-coder-android/ECoder-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 E-coder-android dist/ECoder-android.apk dist/ECoder-android.apk.sha256 dist/ECoder-android.version.txt \ + --title "E-coder for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the E-coder-android release with ECoder-android.apk $version" + exit 0 + fi + published=$(gh release download E-coder-android --repo "$GITHUB_REPOSITORY" --pattern ECoder-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the E-coder-android release already has ECoder-android.apk $version" + exit 0 + fi + gh release upload E-coder-android dist/ECoder-android.apk dist/ECoder-android.apk.sha256 dist/ECoder-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "ECoder-android.apk on the E-coder-android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/E-coder-desktop.yml b/.github/workflows/E-coder-desktop.yml new file mode 100644 index 00000000..e219b204 --- /dev/null +++ b/.github/workflows/E-coder-desktop.yml @@ -0,0 +1,177 @@ +name: ECoder apps + +# Builds the downloadable ECoder apps and publishes them to the "E-coder-desktop" release from main: +# Windows ECoder-Windows-Setup.exe (per-user installer) + ECoder-Windows-Portable.zip +# macOS ECoder-macOS-AppleSilicon.dmg + ECoder-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: + - 'agents-lab/E-coder/desktop/**' + - '.github/workflows/E-coder-desktop.yml' + pull_request: + paths: + - 'agents-lab/E-coder/desktop/**' + - '.github/workflows/E-coder-desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: E-coder-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 agents-lab/E-coder/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's ECoder + run: python agents-lab/E-coder/desktop/smoke_test.py --built --local-site + - name: Install with ECoder-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'agents-lab/E-coder/desktop/dist/ECoder-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'ecoder-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\ECoder\ECoder.exe' + if (-not (Test-Path $app)) { throw "ECoder.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'ECoder.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'ECoder.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 'ECoder' + if (-not $entry) { throw 'ECoder is missing from Settings > Apps' } + python agents-lab/E-coder/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 ECoder.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=agents-lab/E-coder/desktop/dist/ECoder.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.ecoder.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("agents-lab/E-coder/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/ECoder")" + codesign --verify --deep --verbose=2 "$APP" + for image in agents-lab/E-coder/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: ECoder-${{ runner.os }}-${{ runner.arch }} + path: agents-lab/E-coder/desktop/dist/ECoder-* + 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: ECoder-* + 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 ECoder-Windows-Setup.exe ECoder-Windows-Portable.zip \ + ECoder-macOS-AppleSilicon.dmg ECoder-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' + **E-coder**: a stdlib-only coding agent that runs on your own machine. The apps open the same E-coder as https://juw12.github.io/projects/e-coder/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [ECoder-Windows-Setup.exe](https://github.com/juw12/projects/releases/download/E-coder-desktop/ECoder-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: [ECoder-Windows-Portable.zip](https://github.com/juw12/projects/releases/download/E-coder-desktop/ECoder-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [ECoder-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/E-coder-desktop/ECoder-macOS-AppleSilicon.dmg) | Open it and drag ECoder to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [ECoder-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/E-coder-desktop/ECoder-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/e-coder/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [ECoder-android.apk](https://github.com/juw12/projects/releases/download/E-coder-android/ECoder-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load ECoder 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 E-coder-desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload E-coder-desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit E-coder-desktop --notes-file notes.md --repo "$REPO" + else + gh release create E-coder-desktop $FILES SHA256SUMS.txt --title "E-coder for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/agents-lab/E-coder/README.md b/agents-lab/E-coder/README.md index b89e85d4..476acec7 100644 --- a/agents-lab/E-coder/README.md +++ b/agents-lab/E-coder/README.md @@ -39,6 +39,15 @@ +## Get it on your device + +- **Windows:** [`ECoder-Windows-Setup.exe`](https://github.com/juw12/projects/releases/download/E-coder-desktop/ECoder-Windows-Setup.exe) (no admin needed; if Windows says it protected your PC, choose *More info → Run anyway*), or without installing [`ECoder-Windows-Portable.zip`](https://github.com/juw12/projects/releases/download/E-coder-desktop/ECoder-Windows-Portable.zip). +- **Mac:** [`ECoder-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/E-coder-desktop/ECoder-macOS-AppleSilicon.dmg) (M1 and newer) or [`ECoder-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/E-coder-desktop/ECoder-macOS-Intel.dmg). The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`ECoder-android.apk`](https://github.com/juw12/projects/releases/download/E-coder-android/ECoder-android.apk): open the file on the phone and allow your browser to install apps once. +- **iPhone:** open https://juw12.github.io/projects/e-coder/ 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. + ## About A small coding agent that can read a repo, plan, edit files, and run tests. diff --git a/agents-lab/E-coder/android/.gitignore b/agents-lab/E-coder/android/.gitignore new file mode 100644 index 00000000..edd9d60a --- /dev/null +++ b/agents-lab/E-coder/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/agents-lab/E-coder/android/AndroidManifest.xml b/agents-lab/E-coder/android/AndroidManifest.xml new file mode 100644 index 00000000..d38c45c7 --- /dev/null +++ b/agents-lab/E-coder/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/agents-lab/E-coder/android/README.md b/agents-lab/E-coder/android/README.md new file mode 100644 index 00000000..eda145bc --- /dev/null +++ b/agents-lab/E-coder/android/README.md @@ -0,0 +1,34 @@ +# E-coder for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/projects/e-coder/): the same E-coder 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: [`ECoder-android.apk`](https://github.com/juw12/projects/releases/download/E-coder-android/ECoder-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 agents-lab/E-coder/android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/E-coder-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 +`ECoder-android.apk` on the `E-coder-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/agents-lab/E-coder/android/app.json b/agents-lab/E-coder/android/app.json new file mode 100644 index 00000000..a2583015 --- /dev/null +++ b/agents-lab/E-coder/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "ECoder", + "id": "io.github.juw12.ecoder", + "url": "https://juw12.github.io/projects/e-coder/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/agents-lab/E-coder/android/assets/offline.html b/agents-lab/E-coder/android/assets/offline.html new file mode 100644 index 00000000..129784b7 --- /dev/null +++ b/agents-lab/E-coder/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + E-coder + + + +
+ +

E-coder can't reach the internet

+

E-coder 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/agents-lab/E-coder/android/build.py b/agents-lab/E-coder/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/agents-lab/E-coder/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/agents-lab/E-coder/android/res/mipmap-xxxhdpi/ic_launcher.png b/agents-lab/E-coder/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..dc39fa74fc76d550d562ee7ad0e9245dbb587b70 GIT binary patch literal 2566 zcmeHJS6tIs8vTcWGy{l2Mv8;b5=RZTnVi0{Ph(Uj`}$Bq;0+>b9+ki@7;)j$QKrpcr?6^QVOkF*X1IoC5;D zYzF<*ayb6o?Z^TDr~YX)*VXO=0N%SMsNen!1g&PR`<%o{^i1BE^yVT_zxHN;tBya5 z2AzOdVqQ4Tf#UZ%!iCT53JS>xL(pdw1-rQQtYd|O0pU}!acJ;wqE^vJQ5cd#{A1KR zO(xj3{z6@V_n|*uNj)dwuneC)$heLn6Zdy!n4#@!YeD#C%hu|;fz3HC?kZfzQ*UYN z9I_7ta0=K80I>8B#bZdv@Ff6nCdD`doX7rJ;`ip^2$cE-blBs#MV9HP4uP_?DQ3{= z!=exsz5fw=PaL_4(i2UNGMsO`?YEMKxF%9@PDw>+16p8nazmy}RyL(h*ZZk%rTuD~ z7|}QqZ53WYKij|u>&p-JAT@Qz#S?{Mlt0dUrS_HD_Yffj};9L2HsIISZ>Imb2fl-3KUH8hd%XdT@l5) ztVBd!={D-7IoKi6IgtZV$jtSF_+4cW>?MT~s8FhBZ>SSkSoh7#P*Yeel32Ex}gvlHCi8+>>F$x)Sc#@!Sr@Vm`!zBDgFH z5AlZ(1(aHgi_gHsbUwdJs1U7E_pf0w#}PKbhlWx2FPV2j zojy{7u(5l*Fw$kS}cB4X=E=T!z40YLq9go!8nfp~^G z-AM%ly|;Me%e8^==DHev)$#a~TeKM{L#q_9ir|XjvIFYHVZZ6sN zYu$M0$Flqf!7kPPS^R)@Dn#<1R8MLNt@2_*c1s~g&WG*cZwgl|E9-2f?*#yhw&yPK z`+X$fRagN(yrE@0-;o0kF)JIyF!;ojxE%B~U%2l)H5IXKyY1uZ^OB!MZxA@T1y9rl zggRTiOwR|{Pi^(52dY=pytUgStWe4m{rTy^vnMDlO5dQaq>pkbz=gDgN zuvdG$yLw!TW4E^9*D}3ctw(LS$Z#?iav^+PL%ZQs(HwF6I;f#0b+q4o^=20hCstg+bFN#o2|gBTT*cTcgl(P~;< zOM*ZcsbW$}Ts_W|CrN7o8p1(prGDEX5BrCyh42wi4b7t~fhx!T{PEL8ij!L~LPKYfK|Q&4 zEIb0e(Zxt@HEi9ZhZSd7ysKbnc(&w`kA?T*J)Si)=~{vdpPB2FI>a@C-NB8JFSuzy zX!G)HNA3R3TK<dl^oIK5aeAC^pd>`=J~ZjbnFPZ*b{z$Z_mER#2B5Tgfq6I*sh zk~|cH_w1ArpA<`*`E-{T`S8^AOkPUYX8MA{ofie(I+#y95X7O#r8hbJ(O_9{d29K8 z=J&7zn!+dptE7Lc89zR*eNxM943T^N#Pt+qKG8JuUzH(g(Gk+^$#!pl*VYlz_g|r@ zP7{;;hn_*#-X}y7Wpdm7?^yEUcJNll4(|0lvO7(V&~;YW=9qDJ)tU1O0_E zcRP^o2F}Wr!wxJzu2#dk + + #fbfaf6 + + diff --git a/agents-lab/E-coder/android/smoke.py b/agents-lab/E-coder/android/smoke.py new file mode 100644 index 00000000..7fe1e26d --- /dev/null +++ b/agents-lab/E-coder/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the ECoder APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/ECoder-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("\nECoder 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/agents-lab/E-coder/android/src/io/github/juw12/ecoder/MainActivity.java b/agents-lab/E-coder/android/src/io/github/juw12/ecoder/MainActivity.java new file mode 100644 index 00000000..8ae4b4cd --- /dev/null +++ b/agents-lab/E-coder/android/src/io/github/juw12/ecoder/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.ecoder; + +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; + +/** + * ECoder 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/e-coder/"; + private static final String SCOPE = "juw12.github.io/projects/e-coder"; + 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() + " ECoderAndroid/" + 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("ECoderShell", "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("ECoderShell", "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/agents-lab/E-coder/desktop/.gitignore b/agents-lab/E-coder/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/agents-lab/E-coder/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/agents-lab/E-coder/desktop/README.md b/agents-lab/E-coder/desktop/README.md new file mode 100644 index 00000000..705339cf --- /dev/null +++ b/agents-lab/E-coder/desktop/README.md @@ -0,0 +1,25 @@ +# ECoder for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/e-coder/): 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 ECoder 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 | +| --- | --- | +| `ecoder_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 | +| `ecoder.spec`, `ecoder.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 ECoder | +| `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/E-coder-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 +[E-coder-desktop release](https://github.com/juw12/projects/releases/tag/E-coder-desktop). The download links never change. diff --git a/agents-lab/E-coder/desktop/build.py b/agents-lab/E-coder/desktop/build.py new file mode 100644 index 00000000..7d96b3ba --- /dev/null +++ b/agents-lab/E-coder/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the ECoder 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 ECoder-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + ECoder-Windows-Portable.zip unzip and run ECoder.exe + macOS ECoder-macOS-AppleSilicon.dmg or ECoder-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', 'ECoder - A stdlib-only coding agent that runs on your own machine'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'ECoder'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'ECoder.exe'), + StringStruct('ProductName', 'ECoder'), + 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, "ecoder.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, ECODER_VERSION=version, ECODER_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["ECODER_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "ecoder.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, "ECoder") + portable = os.path.join(DIST, "ECoder-Windows-Portable.zip") + zip_folder(folder, portable, "ECoder") + 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 ECoder-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped ECoder-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, "ecoder.iss")], + check=True, + ) + return [os.path.join(DIST, "ECoder-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "ECoder.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "ECoder-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, "ECoder.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "ECoder", "-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 ECoder 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("ECoder desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by ecoder.spec) + except ImportError: + raise SystemExit("The ECoder window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("ECoder", "ECoder.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building ECoder %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/agents-lab/E-coder/desktop/ecoder.iss b/agents-lab/E-coder/desktop/ecoder.iss new file mode 100644 index 00000000..823a8ddf --- /dev/null +++ b/agents-lab/E-coder/desktop/ecoder.iss @@ -0,0 +1,73 @@ +; ECoder for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= ecoder.iss +; Installs to %LOCALAPPDATA%\Programs\ECoder, adds ECoder 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%\ECoder, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\ECoder" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\ecoder.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=ECoder +AppVersion={#AppVersion} +AppVerName=ECoder {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/e-coder/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\ECoder +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=ECoder-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\ECoder.exe +UninstallDisplayName=ECoder +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}\ECoder"; Filename: "{app}\ECoder.exe"; Comment: "A stdlib-only coding agent that runs on your own machine" +Name: "{userdesktop}\ECoder"; Filename: "{app}\ECoder.exe"; Comment: "A stdlib-only coding agent that runs on your own machine"; Tasks: desktopicon + +[Run] +Filename: "{app}\ECoder.exe"; Description: "{cm:LaunchProgram,ECoder}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\ECoder.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopECoder" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open ECoder window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\ECoder.exe')) then + Exec(ExpandConstant('{app}\ECoder.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/agents-lab/E-coder/desktop/ecoder.spec b/agents-lab/E-coder/desktop/ecoder.spec new file mode 100644 index 00000000..8c0a0890 --- /dev/null +++ b/agents-lab/E-coder/desktop/ecoder.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for ECoder on Windows and macOS. Build with python desktop/build.py +# Windows dist/ECoder/ECoder.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/ECoder.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("ECODER_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("ECODER_VERSION_FILE") or None +ICON = os.environ.get("ECODER_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, "ecoder_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="ECoder", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="ECoder", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="ECoder.app", + icon=ICON, + bundle_identifier="io.github.juw12.ecoder.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "ECoder", + "CFBundleDisplayName": "ECoder", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/agents-lab/E-coder/desktop/ecoder_app.py b/agents-lab/E-coder/desktop/ecoder_app.py new file mode 100644 index 00000000..ab383517 --- /dev/null +++ b/agents-lab/E-coder/desktop/ecoder_app.py @@ -0,0 +1,467 @@ +"""ECoder for Windows and macOS: the ECoder 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/e-coder/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time ECoder 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 +ECoder opens in the default browser instead. + +Opening ECoder while its window is open brings that window to the front; `ECoder --stop` closes it. + +Automated checks: ECODER_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; ECODER_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 = "E-coder" +APP_URL = os.environ.get("ECODER_DESKTOP_URL") or "https://juw12.github.io/projects/e-coder/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#fbfaf6" +DARK_BACKGROUND = "#fbfaf6" +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('ecoder.desktop.check', '1');" + " return localStorage.getItem('ecoder.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("[ecoder] " + 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"), "ECoder") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "ECoder") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "ecoder") + + +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 ECoder site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "ECoderDesktop/" + 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="ecoder-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 ECoder 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 ECoder 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 ECoder 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="ecoder-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("ECoder %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("ECODER_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/agents-lab/E-coder/desktop/icon-512.png b/agents-lab/E-coder/desktop/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..786323a206be1c122699a3c153781812950fde31 GIT binary patch literal 4074 zcmeHK_g|A&7rz872(kp!DiHlpg-R8WDI=hOAVaWVDKY|83Wxy_FpMSvt)sGRK_V-F zHtZ#YO#o#{Wf?{wjDRc&BcMrG8Sg{&*Y_W2`_uD0=iGDdbM8Io`#tA3$4gd{;)lfn z0FoE2Exrc;2ED?7*zP0huz3jp(l0MsoO2G(Sed}Z9b{oT*LT+E8jT#!u89WBMS_iCB5 zy0ax$$lO9c*=XxHS`kfeaI>o%&;D^oWpd%|20NS^!F{F9Y%$s5PesK$m8K5^GeRy! z7^s;8aDFc^QxgJW#{tL@0Y{So_;o*sc7y>LoBx#mTJ8TmWKx97|Hb0S=#TDTE z2YP#?jRh?xMJdI<`1sVt45oB^OSM-g#|U>lo7aLHV)W=#dE+%>vj5O? zs~}g-cm>5=%>is4&(L0Kb;$}FLI_B+W~>jfnJ%Zuv`^=!MWT^!;(i+lGTxBLvqQ9# z8662tN-n=FB}tb>{mGJfye>mPbBwIAuzf`I&MMMZ3S| zQo_x4Yw+IT8;9~%mGn5}eSHG=MFshzU>Qj)h_r;z9XA(-rm6v{M1L4qncCLDbnB+{>r; zFRkO@8YVH9kApZr_yD2_)fju7W>VhpsU4o;`3ll!Mv=Bei^KRIxL6z?CFU`NL?jQWBia-h)Df#z$KXgiOF`U8maa+bKb47lK& z)?r|k#&Bd;G@Pc>8cJ9)yHXv!`U@$L@S|X}P3}mRn#r$cPTt2Nv&*4;F5Mhfg?nyT zFCLRu0Z;NnFbh{~%OWDi-a-lS2QW*ylI}9Wz2}xvXtj*9AQq?V%7YP1cEN02MbA`WV4qT0uWsy>Ev9jm&-o*z<2 zx{eOemjbzWMSzrXPkaw_&9n|u7%8m#nZXNhhQBE)o}JY{9Vy64_B{d0*5$Mo4v&n5)OYleu>N;isSV6+g}VMUl%_fB{!! zS15V^c6!t_g58C$4pbxGg_g_Aa^`CA1T*L_t=E?W`X)D)(Y9sT55#~)zLcbA6^oHG zokKCtKL!J`f#GWp^7KqR{*E}CKe0ZNiFD-;QPlI#KBWjpqp1-5ZoM|wuRjCjadu$X zMktQc)JGSL^Pnnu0UfoY1FnyXA^K*ZdF?aoA?TdS5b=c$*K3Rep_8})=Yfr>bkzv-tD z?OtO}TnTyXfN6F3dgAJbMdr6AkIyuI1#(W1(A)_oX1>{UeTqA?fS)}7H4MBvp=7*R zZQ8`H-=hAImS!8|P1+0k*L?FZHz9U&Ni$Z>umsUH-KJQ+y+mMWtQxH4(X==9QT5cX zd+@zm;fo4!%0gak*)gKYqe|Ymj?RyQwRjFUum2I--`}r^dhPs05?T^0d-(8V zn0LiL#iR2wV03t9H`Q44o;T@NyZ}-NqmUbM$1vHxk~AZ_b2#H)&Qc~ z#8PIc{N#sGhFF*b7@=Z{m?83>wE9=FyWYy+#Zjb&yfKg0CgjCMid;B#FW5P(sLZW- zN)N?fA43P>yx&R?UDisWy=FLbu~FL?P4`kJB1+J|=D4WPxC9aZNOjcM`_2PK_QgSw zV$aTjk>+%`D+ybac;A|}R&Pc42s8Ui$V;$Yh;f+=@d@+mk9odtpOm`*DPddYl`IB= zmO3>|gV|)Pp;tsX~5p5N=oySj@++BvoSSyuyqi#CPIx+;0pI6 zeUg_N^GXO`7$jX9@xh6{6$)MANujAs-hvaIf3J)?t(~3~TpY<}t2V9U1=!T?JpYW_ z6C}zJ15M|&G!4Yu`(^^V&f#&HD#X&IZXD^2ZEm79tVJV_ST}b!sjqnobFi^5ai4Ju zicaSBb_&=>?LLChwbcTrOaAbI)dbPUlQENXOSsTJZCmAV ze$0e$gKb~VH$qd?EB=Mtd2cH?)bMmF2QSaACrQK6o6|E=Og}jNsz0iLMAE6z(Tyx9 zh-UPA38n}W!k8ddXi!9DKx?&RKy`7%&z~5oNKA#H^Qo7Q(o~>{h&! + + + + + ECoder + + + +
+ +

ECoder can't reach the internet

+

ECoder 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/agents-lab/E-coder/desktop/shell.json b/agents-lab/E-coder/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/agents-lab/E-coder/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/agents-lab/E-coder/desktop/smoke_test.py b/agents-lab/E-coder/desktop/smoke_test.py new file mode 100644 index 00000000..4b8cea1e --- /dev/null +++ b/agents-lab/E-coder/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built ECoder desktop app and check its window really shows ECoder. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/ECoder.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with ECODER_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is ECoder, 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, "agents-lab", "E-coder", "guide")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/e-coder/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "ECoder", "ECoder.exe") + return os.path.join(DESKTOP, "dist", "ECoder.app", "Contents", "MacOS", "ECoder") + + +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 ECoder 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="ecoder-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, ECODER_WINDOW_TEST=report, ECODER_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 "E-coder" 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("ECoder 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: ECoder %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main() From f4878802d8ec58b256e99f6fdbdaccae5907539e Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:51:14 +0700 Subject: [PATCH 5/5] READMEs: the apps open each project's guide, and the program itself runs on a computer --- agents-lab/E-coder/README.md | 2 +- apps/kinibuka/README.md | 2 +- apps/pushlab/README.md | 2 +- respark/README.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/agents-lab/E-coder/README.md b/agents-lab/E-coder/README.md index 476acec7..dd3295da 100644 --- a/agents-lab/E-coder/README.md +++ b/agents-lab/E-coder/README.md @@ -46,7 +46,7 @@ - **Android:** [`ECoder-android.apk`](https://github.com/juw12/projects/releases/download/E-coder-android/ECoder-android.apk): open the file on the phone and allow your browser to install apps once. - **iPhone:** open https://juw12.github.io/projects/e-coder/ 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. +The Windows, Mac and Android apps open the E-coder guide (https://juw12.github.io/projects/e-coder/: this README laid out for a phone, readable without a connection) in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. E-coder itself runs on a computer and is installed the way this README says; the apps do not contain 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. ## About diff --git a/apps/kinibuka/README.md b/apps/kinibuka/README.md index 4d547e03..15f440e5 100644 --- a/apps/kinibuka/README.md +++ b/apps/kinibuka/README.md @@ -53,7 +53,7 @@ - **Android:** [`KiniBuka-android.apk`](https://github.com/juw12/projects/releases/download/kinibuka-android/KiniBuka-android.apk): open the file on the phone and allow your browser to install apps once. - **iPhone:** open https://juw12.github.io/projects/kinibuka/ 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. +The Windows, Mac and Android apps open the KiniBuka guide (https://juw12.github.io/projects/kinibuka/: this README laid out for a phone, readable without a connection) in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. KiniBuka itself runs on a computer and is installed the way this README says; the apps do not contain 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. ## About diff --git a/apps/pushlab/README.md b/apps/pushlab/README.md index 8a01cb55..fc19139e 100644 --- a/apps/pushlab/README.md +++ b/apps/pushlab/README.md @@ -54,7 +54,7 @@ - **Android:** [`PushLab-android.apk`](https://github.com/juw12/projects/releases/download/pushlab-android/PushLab-android.apk): open the file on the phone and allow your browser to install apps once. - **iPhone:** open https://juw12.github.io/projects/pushlab/ 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. +The Windows, Mac and Android apps open the Push Lab guide (https://juw12.github.io/projects/pushlab/: this README laid out for a phone, readable without a connection) in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. Push Lab itself runs on a computer and is installed the way this README says; the apps do not contain 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. ## About diff --git a/respark/README.md b/respark/README.md index d561cfeb..e3879671 100644 --- a/respark/README.md +++ b/respark/README.md @@ -46,7 +46,7 @@ - **Android:** [`Titian-android.apk`](https://github.com/juw12/projects/releases/download/respark-android/Titian-android.apk): open the file on the phone and allow your browser to install apps once. - **iPhone:** open https://juw12.github.io/projects/titian/ 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. +The Windows, Mac and Android apps open the Titian guide (https://juw12.github.io/projects/titian/: this README laid out for a phone, readable without a connection) in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. Titian itself runs on a computer and is installed the way this README says; the apps do not contain 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. ## About