diff --git a/.github/workflows/house-of-articles-android.yml b/.github/workflows/house-of-articles-android.yml new file mode 100644 index 00000000..9fe01c43 --- /dev/null +++ b/.github/workflows/house-of-articles-android.yml @@ -0,0 +1,137 @@ +name: HouseOfArticles Android app + +# Builds HouseOfArticles-android.apk (apps/house-of-articles/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 house-of-articles-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "apps/house-of-articles/android/**" + - ".github/workflows/house-of-articles-android.yml" + pull_request: + paths: + - "apps/house-of-articles/android/**" + - ".github/workflows/house-of-articles-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/house-of-articles/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/house-of-articles/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/house-of-articles/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs apps/house-of-articles/android/dist/HouseOfArticles-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd apps/house-of-articles/android/dist && sha256sum HouseOfArticles-android.apk > HouseOfArticles-android.apk.sha256 && cat HouseOfArticles-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: houseofarticles-android + path: apps/house-of-articles/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: houseofarticles-android + path: apps/house-of-articles/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/house-of-articles/android/smoke.py apps/house-of-articles/android/dist/HouseOfArticles-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: houseofarticles-android-emulator-check + path: | + apps/house-of-articles/android/dist/*.png + apps/house-of-articles/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: houseofarticles-android + path: dist + # The house-of-articles-android release keeps one address for the download. The file there is replaced only when + # apps/house-of-articles/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the house-of-articles-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('apps/house-of-articles/android/app.json'))['versionName'])") + echo "$version" > dist/HouseOfArticles-android.version.txt + if ! gh release view house-of-articles-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "House of Articles for Android: a full-screen window around the web app (https://juw12.github.io/projects/house-of-articles/)." "" \ + "Download [HouseOfArticles-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/house-of-articles-android/HouseOfArticles-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 house-of-articles-android dist/HouseOfArticles-android.apk dist/HouseOfArticles-android.apk.sha256 dist/HouseOfArticles-android.version.txt \ + --title "House of Articles for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the house-of-articles-android release with HouseOfArticles-android.apk $version" + exit 0 + fi + published=$(gh release download house-of-articles-android --repo "$GITHUB_REPOSITORY" --pattern HouseOfArticles-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the house-of-articles-android release already has HouseOfArticles-android.apk $version" + exit 0 + fi + gh release upload house-of-articles-android dist/HouseOfArticles-android.apk dist/HouseOfArticles-android.apk.sha256 dist/HouseOfArticles-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "HouseOfArticles-android.apk on the house-of-articles-android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/house-of-articles-desktop.yml b/.github/workflows/house-of-articles-desktop.yml new file mode 100644 index 00000000..86a4e3a4 --- /dev/null +++ b/.github/workflows/house-of-articles-desktop.yml @@ -0,0 +1,177 @@ +name: HouseOfArticles apps + +# Builds the downloadable HouseOfArticles apps and publishes them to the "house-of-articles-desktop" release from main: +# Windows HouseOfArticles-Windows-Setup.exe (per-user installer) + HouseOfArticles-Windows-Portable.zip +# macOS HouseOfArticles-macOS-AppleSilicon.dmg + HouseOfArticles-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/house-of-articles/desktop/**' + - '.github/workflows/house-of-articles-desktop.yml' + pull_request: + paths: + - 'apps/house-of-articles/desktop/**' + - '.github/workflows/house-of-articles-desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-of-articles-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/house-of-articles/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's HouseOfArticles + run: python apps/house-of-articles/desktop/smoke_test.py --built --local-site + - name: Install with HouseOfArticles-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'apps/house-of-articles/desktop/dist/HouseOfArticles-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'houseofarticles-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\HouseOfArticles\HouseOfArticles.exe' + if (-not (Test-Path $app)) { throw "HouseOfArticles.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'HouseOfArticles.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'HouseOfArticles.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 'HouseOfArticles' + if (-not $entry) { throw 'HouseOfArticles is missing from Settings > Apps' } + python apps/house-of-articles/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 HouseOfArticles.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/house-of-articles/desktop/dist/HouseOfArticles.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.houseofarticles.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("apps/house-of-articles/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/HouseOfArticles")" + codesign --verify --deep --verbose=2 "$APP" + for image in apps/house-of-articles/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: HouseOfArticles-${{ runner.os }}-${{ runner.arch }} + path: apps/house-of-articles/desktop/dist/HouseOfArticles-* + 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: HouseOfArticles-* + 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 HouseOfArticles-Windows-Setup.exe HouseOfArticles-Windows-Portable.zip \ + HouseOfArticles-macOS-AppleSilicon.dmg HouseOfArticles-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' + **House of Articles**: athlete-moment sneaker news plus a live resale market feed. The apps open the same House of Articles as https://juw12.github.io/projects/house-of-articles/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [HouseOfArticles-Windows-Setup.exe](https://github.com/juw12/projects/releases/download/house-of-articles-desktop/HouseOfArticles-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: [HouseOfArticles-Windows-Portable.zip](https://github.com/juw12/projects/releases/download/house-of-articles-desktop/HouseOfArticles-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [HouseOfArticles-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/house-of-articles-desktop/HouseOfArticles-macOS-AppleSilicon.dmg) | Open it and drag HouseOfArticles to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [HouseOfArticles-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/house-of-articles-desktop/HouseOfArticles-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/house-of-articles/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [HouseOfArticles-android.apk](https://github.com/juw12/projects/releases/download/house-of-articles-android/HouseOfArticles-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load HouseOfArticles 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 house-of-articles-desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload house-of-articles-desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit house-of-articles-desktop --notes-file notes.md --repo "$REPO" + else + gh release create house-of-articles-desktop $FILES SHA256SUMS.txt --title "House of Articles for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/.github/workflows/pips-android.yml b/.github/workflows/pips-android.yml new file mode 100644 index 00000000..040b5e72 --- /dev/null +++ b/.github/workflows/pips-android.yml @@ -0,0 +1,137 @@ +name: Pips Android app + +# Builds Pips-android.apk (apps/pips/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 pips-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "apps/pips/android/**" + - ".github/workflows/pips-android.yml" + pull_request: + paths: + - "apps/pips/android/**" + - ".github/workflows/pips-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/pips/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/pips/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/pips/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs apps/pips/android/dist/Pips-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd apps/pips/android/dist && sha256sum Pips-android.apk > Pips-android.apk.sha256 && cat Pips-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: pips-android + path: apps/pips/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: pips-android + path: apps/pips/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/pips/android/smoke.py apps/pips/android/dist/Pips-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: pips-android-emulator-check + path: | + apps/pips/android/dist/*.png + apps/pips/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: pips-android + path: dist + # The pips-android release keeps one address for the download. The file there is replaced only when + # apps/pips/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the pips-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('apps/pips/android/app.json'))['versionName'])") + echo "$version" > dist/Pips-android.version.txt + if ! gh release view pips-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "Pips for Android: a full-screen window around the web app (https://juw12.github.io/projects/pips/web.html)." "" \ + "Download [Pips-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/pips-android/Pips-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 pips-android dist/Pips-android.apk dist/Pips-android.apk.sha256 dist/Pips-android.version.txt \ + --title "Pips for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the pips-android release with Pips-android.apk $version" + exit 0 + fi + published=$(gh release download pips-android --repo "$GITHUB_REPOSITORY" --pattern Pips-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the pips-android release already has Pips-android.apk $version" + exit 0 + fi + gh release upload pips-android dist/Pips-android.apk dist/Pips-android.apk.sha256 dist/Pips-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "Pips-android.apk on the pips-android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/pips-desktop.yml b/.github/workflows/pips-desktop.yml new file mode 100644 index 00000000..17601ef8 --- /dev/null +++ b/.github/workflows/pips-desktop.yml @@ -0,0 +1,177 @@ +name: Pips apps + +# Builds the downloadable Pips apps and publishes them to the "pips-desktop" release from main: +# Windows Pips-Windows-Setup.exe (per-user installer) + Pips-Windows-Portable.zip +# macOS Pips-macOS-AppleSilicon.dmg + Pips-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/pips/desktop/**' + - '.github/workflows/pips-desktop.yml' + pull_request: + paths: + - 'apps/pips/desktop/**' + - '.github/workflows/pips-desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pips-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/pips/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's Pips + run: python apps/pips/desktop/smoke_test.py --built --local-site + - name: Install with Pips-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'apps/pips/desktop/dist/Pips-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'pips-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\Pips\Pips.exe' + if (-not (Test-Path $app)) { throw "Pips.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'Pips.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Pips.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 'Pips' + if (-not $entry) { throw 'Pips is missing from Settings > Apps' } + python apps/pips/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 Pips.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/pips/desktop/dist/Pips.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.pips.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("apps/pips/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/Pips")" + codesign --verify --deep --verbose=2 "$APP" + for image in apps/pips/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: Pips-${{ runner.os }}-${{ runner.arch }} + path: apps/pips/desktop/dist/Pips-* + 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: Pips-* + 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 Pips-Windows-Setup.exe Pips-Windows-Portable.zip \ + Pips-macOS-AppleSilicon.dmg Pips-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' + **Pips**: pomodoro widget with animated animals, skill battles and minigames. The apps open the same Pips as https://juw12.github.io/projects/pips/web.html in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [Pips-Windows-Setup.exe](https://github.com/juw12/projects/releases/download/pips-desktop/Pips-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: [Pips-Windows-Portable.zip](https://github.com/juw12/projects/releases/download/pips-desktop/Pips-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [Pips-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/pips-desktop/Pips-macOS-AppleSilicon.dmg) | Open it and drag Pips to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [Pips-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/pips-desktop/Pips-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/pips/web.html) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [Pips-android.apk](https://github.com/juw12/projects/releases/download/pips-android/Pips-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load Pips 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 pips-desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload pips-desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit pips-desktop --notes-file notes.md --repo "$REPO" + else + gh release create pips-desktop $FILES SHA256SUMS.txt --title "Pips for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/apps/house-of-articles/README.md b/apps/house-of-articles/README.md index 14c77d40..beaed7aa 100644 --- a/apps/house-of-articles/README.md +++ b/apps/house-of-articles/README.md @@ -48,6 +48,15 @@

+## Get it on your device + +- **Windows:** [`HouseOfArticles-Windows-Setup.exe`](https://github.com/juw12/projects/releases/download/house-of-articles-desktop/HouseOfArticles-Windows-Setup.exe) (no admin needed; if Windows says it protected your PC, choose *More info → Run anyway*), or without installing [`HouseOfArticles-Windows-Portable.zip`](https://github.com/juw12/projects/releases/download/house-of-articles-desktop/HouseOfArticles-Windows-Portable.zip). +- **Mac:** [`HouseOfArticles-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/house-of-articles-desktop/HouseOfArticles-macOS-AppleSilicon.dmg) (M1 and newer) or [`HouseOfArticles-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/house-of-articles-desktop/HouseOfArticles-macOS-Intel.dmg). The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`HouseOfArticles-android.apk`](https://github.com/juw12/projects/releases/download/house-of-articles-android/HouseOfArticles-android.apk): open the file on the phone and allow your browser to install apps once. +- **iPhone:** open https://juw12.github.io/projects/house-of-articles/ 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 > "See what athletes wear, and what it's worth — right now." diff --git a/apps/house-of-articles/android/.gitignore b/apps/house-of-articles/android/.gitignore new file mode 100644 index 00000000..edd9d60a --- /dev/null +++ b/apps/house-of-articles/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/apps/house-of-articles/android/AndroidManifest.xml b/apps/house-of-articles/android/AndroidManifest.xml new file mode 100644 index 00000000..558cf4ec --- /dev/null +++ b/apps/house-of-articles/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/apps/house-of-articles/android/README.md b/apps/house-of-articles/android/README.md new file mode 100644 index 00000000..2ea64e96 --- /dev/null +++ b/apps/house-of-articles/android/README.md @@ -0,0 +1,34 @@ +# House of Articles for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/projects/house-of-articles/): the same House of Articles 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: [`HouseOfArticles-android.apk`](https://github.com/juw12/projects/releases/download/house-of-articles-android/HouseOfArticles-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/house-of-articles/android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/house-of-articles-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 +`HouseOfArticles-android.apk` on the `house-of-articles-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/house-of-articles/android/app.json b/apps/house-of-articles/android/app.json new file mode 100644 index 00000000..cec2b6a5 --- /dev/null +++ b/apps/house-of-articles/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "HouseOfArticles", + "id": "io.github.juw12.houseofarticles", + "url": "https://juw12.github.io/projects/house-of-articles/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/apps/house-of-articles/android/assets/offline.html b/apps/house-of-articles/android/assets/offline.html new file mode 100644 index 00000000..30204c31 --- /dev/null +++ b/apps/house-of-articles/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + House of Articles + + + +
+ +

House of Articles can't reach the internet

+

House of Articles 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/house-of-articles/android/build.py b/apps/house-of-articles/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/apps/house-of-articles/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/house-of-articles/android/res/mipmap-xxxhdpi/ic_launcher.png b/apps/house-of-articles/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..05685094 Binary files /dev/null and b/apps/house-of-articles/android/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/apps/house-of-articles/android/res/values/styles.xml b/apps/house-of-articles/android/res/values/styles.xml new file mode 100644 index 00000000..d87c2f6f --- /dev/null +++ b/apps/house-of-articles/android/res/values/styles.xml @@ -0,0 +1,11 @@ + + + #F5F1E8 + + diff --git a/apps/house-of-articles/android/smoke.py b/apps/house-of-articles/android/smoke.py new file mode 100644 index 00000000..bb5a126d --- /dev/null +++ b/apps/house-of-articles/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the HouseOfArticles APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/HouseOfArticles-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("\nHouseOfArticles 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/house-of-articles/android/src/io/github/juw12/houseofarticles/MainActivity.java b/apps/house-of-articles/android/src/io/github/juw12/houseofarticles/MainActivity.java new file mode 100644 index 00000000..0d82666a --- /dev/null +++ b/apps/house-of-articles/android/src/io/github/juw12/houseofarticles/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.houseofarticles; + +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; + +/** + * HouseOfArticles 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/house-of-articles/"; + private static final String SCOPE = "juw12.github.io/projects/house-of-articles"; + 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() + " HouseOfArticlesAndroid/" + 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("HouseOfArticlesShell", "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("HouseOfArticlesShell", "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/house-of-articles/desktop/.gitignore b/apps/house-of-articles/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/apps/house-of-articles/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/apps/house-of-articles/desktop/README.md b/apps/house-of-articles/desktop/README.md new file mode 100644 index 00000000..f2dae561 --- /dev/null +++ b/apps/house-of-articles/desktop/README.md @@ -0,0 +1,25 @@ +# HouseOfArticles for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/house-of-articles/): 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 HouseOfArticles 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 | +| --- | --- | +| `houseofarticles_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 | +| `houseofarticles.spec`, `houseofarticles.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 HouseOfArticles | +| `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/house-of-articles-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 +[house-of-articles-desktop release](https://github.com/juw12/projects/releases/tag/house-of-articles-desktop). The download links never change. diff --git a/apps/house-of-articles/desktop/build.py b/apps/house-of-articles/desktop/build.py new file mode 100644 index 00000000..f400dc5a --- /dev/null +++ b/apps/house-of-articles/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the HouseOfArticles 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 HouseOfArticles-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + HouseOfArticles-Windows-Portable.zip unzip and run HouseOfArticles.exe + macOS HouseOfArticles-macOS-AppleSilicon.dmg or HouseOfArticles-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', 'HouseOfArticles - Athlete-moment sneaker news plus a live resale market feed'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'HouseOfArticles'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'HouseOfArticles.exe'), + StringStruct('ProductName', 'HouseOfArticles'), + 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, "houseofarticles.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, HOUSEOFARTICLES_VERSION=version, HOUSEOFARTICLES_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["HOUSEOFARTICLES_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "houseofarticles.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, "HouseOfArticles") + portable = os.path.join(DIST, "HouseOfArticles-Windows-Portable.zip") + zip_folder(folder, portable, "HouseOfArticles") + 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 HouseOfArticles-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped HouseOfArticles-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, "houseofarticles.iss")], + check=True, + ) + return [os.path.join(DIST, "HouseOfArticles-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "HouseOfArticles.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "HouseOfArticles-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, "HouseOfArticles.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "HouseOfArticles", "-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 HouseOfArticles 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("HouseOfArticles desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by houseofarticles.spec) + except ImportError: + raise SystemExit("The HouseOfArticles window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("HouseOfArticles", "HouseOfArticles.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building HouseOfArticles %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/house-of-articles/desktop/houseofarticles.iss b/apps/house-of-articles/desktop/houseofarticles.iss new file mode 100644 index 00000000..8af7b114 --- /dev/null +++ b/apps/house-of-articles/desktop/houseofarticles.iss @@ -0,0 +1,73 @@ +; HouseOfArticles for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= houseofarticles.iss +; Installs to %LOCALAPPDATA%\Programs\HouseOfArticles, adds HouseOfArticles 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%\HouseOfArticles, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\HouseOfArticles" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\houseofarticles.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=HouseOfArticles +AppVersion={#AppVersion} +AppVerName=HouseOfArticles {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/house-of-articles/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\HouseOfArticles +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=HouseOfArticles-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\HouseOfArticles.exe +UninstallDisplayName=HouseOfArticles +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}\HouseOfArticles"; Filename: "{app}\HouseOfArticles.exe"; Comment: "Athlete-moment sneaker news plus a live resale market feed" +Name: "{userdesktop}\HouseOfArticles"; Filename: "{app}\HouseOfArticles.exe"; Comment: "Athlete-moment sneaker news plus a live resale market feed"; Tasks: desktopicon + +[Run] +Filename: "{app}\HouseOfArticles.exe"; Description: "{cm:LaunchProgram,HouseOfArticles}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\HouseOfArticles.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopHouseOfArticles" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open HouseOfArticles window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\HouseOfArticles.exe')) then + Exec(ExpandConstant('{app}\HouseOfArticles.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/apps/house-of-articles/desktop/houseofarticles.spec b/apps/house-of-articles/desktop/houseofarticles.spec new file mode 100644 index 00000000..74122c06 --- /dev/null +++ b/apps/house-of-articles/desktop/houseofarticles.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for HouseOfArticles on Windows and macOS. Build with python desktop/build.py +# Windows dist/HouseOfArticles/HouseOfArticles.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/HouseOfArticles.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("HOUSEOFARTICLES_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("HOUSEOFARTICLES_VERSION_FILE") or None +ICON = os.environ.get("HOUSEOFARTICLES_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, "houseofarticles_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="HouseOfArticles", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="HouseOfArticles", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="HouseOfArticles.app", + icon=ICON, + bundle_identifier="io.github.juw12.houseofarticles.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "HouseOfArticles", + "CFBundleDisplayName": "HouseOfArticles", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/apps/house-of-articles/desktop/houseofarticles_app.py b/apps/house-of-articles/desktop/houseofarticles_app.py new file mode 100644 index 00000000..dc047860 --- /dev/null +++ b/apps/house-of-articles/desktop/houseofarticles_app.py @@ -0,0 +1,467 @@ +"""HouseOfArticles for Windows and macOS: the HouseOfArticles 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/house-of-articles/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time HouseOfArticles 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 +HouseOfArticles opens in the default browser instead. + +Opening HouseOfArticles while its window is open brings that window to the front; `HouseOfArticles --stop` closes it. + +Automated checks: HOUSEOFARTICLES_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; HOUSEOFARTICLES_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 = "House of Articles" +APP_URL = os.environ.get("HOUSEOFARTICLES_DESKTOP_URL") or "https://juw12.github.io/projects/house-of-articles/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#F5F1E8" +DARK_BACKGROUND = "#F5F1E8" +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('houseofarticles.desktop.check', '1');" + " return localStorage.getItem('houseofarticles.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("[houseofarticles] " + 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"), "HouseOfArticles") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "HouseOfArticles") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "houseofarticles") + + +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 HouseOfArticles site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "HouseOfArticlesDesktop/" + 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="houseofarticles-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 HouseOfArticles 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 HouseOfArticles 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 HouseOfArticles 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="houseofarticles-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("HouseOfArticles %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("HOUSEOFARTICLES_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/house-of-articles/desktop/icon-512.png b/apps/house-of-articles/desktop/icon-512.png new file mode 100644 index 00000000..42b65a47 Binary files /dev/null and b/apps/house-of-articles/desktop/icon-512.png differ diff --git a/apps/house-of-articles/desktop/offline.html b/apps/house-of-articles/desktop/offline.html new file mode 100644 index 00000000..02a86ae1 --- /dev/null +++ b/apps/house-of-articles/desktop/offline.html @@ -0,0 +1,25 @@ + + + + + + HouseOfArticles + + + +
+ +

HouseOfArticles can't reach the internet

+

HouseOfArticles 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/house-of-articles/desktop/shell.json b/apps/house-of-articles/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/apps/house-of-articles/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/apps/house-of-articles/desktop/smoke_test.py b/apps/house-of-articles/desktop/smoke_test.py new file mode 100644 index 00000000..c9772cf3 --- /dev/null +++ b/apps/house-of-articles/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built HouseOfArticles desktop app and check its window really shows HouseOfArticles. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/HouseOfArticles.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with HOUSEOFARTICLES_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is HouseOfArticles, 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", "house-of-articles", "web")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/house-of-articles/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "HouseOfArticles", "HouseOfArticles.exe") + return os.path.join(DESKTOP, "dist", "HouseOfArticles.app", "Contents", "MacOS", "HouseOfArticles") + + +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 HouseOfArticles 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="houseofarticles-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, HOUSEOFARTICLES_WINDOW_TEST=report, HOUSEOFARTICLES_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 "House of Articles" 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("HouseOfArticles 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: HouseOfArticles %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main() diff --git a/apps/house-of-articles/web/icons/apple-touch-icon.png b/apps/house-of-articles/web/icons/apple-touch-icon.png new file mode 100644 index 00000000..3168d3ea Binary files /dev/null and b/apps/house-of-articles/web/icons/apple-touch-icon.png differ diff --git a/apps/house-of-articles/web/icons/icon-192.png b/apps/house-of-articles/web/icons/icon-192.png new file mode 100644 index 00000000..e7a8d874 Binary files /dev/null and b/apps/house-of-articles/web/icons/icon-192.png differ diff --git a/apps/house-of-articles/web/icons/icon-512.png b/apps/house-of-articles/web/icons/icon-512.png new file mode 100644 index 00000000..42b65a47 Binary files /dev/null and b/apps/house-of-articles/web/icons/icon-512.png differ diff --git a/apps/house-of-articles/web/index.html b/apps/house-of-articles/web/index.html index 0491c0c2..62e1fe72 100644 --- a/apps/house-of-articles/web/index.html +++ b/apps/house-of-articles/web/index.html @@ -4,6 +4,12 @@ House of Articles — Mobile Prototype + + + + + + + + +
+ +

Pips can't reach the internet

+

Pips 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/pips/android/build.py b/apps/pips/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/apps/pips/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/pips/android/res/mipmap-xxxhdpi/ic_launcher.png b/apps/pips/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..c9e36ff9 Binary files /dev/null and b/apps/pips/android/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/apps/pips/android/res/values/styles.xml b/apps/pips/android/res/values/styles.xml new file mode 100644 index 00000000..0538918e --- /dev/null +++ b/apps/pips/android/res/values/styles.xml @@ -0,0 +1,11 @@ + + + #faf8f3 + + diff --git a/apps/pips/android/smoke.py b/apps/pips/android/smoke.py new file mode 100644 index 00000000..6d419712 --- /dev/null +++ b/apps/pips/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the Pips APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/Pips-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("\nPips 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/pips/android/src/io/github/juw12/pips/MainActivity.java b/apps/pips/android/src/io/github/juw12/pips/MainActivity.java new file mode 100644 index 00000000..d736bc5c --- /dev/null +++ b/apps/pips/android/src/io/github/juw12/pips/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.pips; + +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; + +/** + * Pips 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/pips/web.html"; + private static final String SCOPE = "juw12.github.io/projects/pips"; + 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() + " PipsAndroid/" + 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("PipsShell", "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("PipsShell", "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/pips/desktop/.gitignore b/apps/pips/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/apps/pips/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/apps/pips/desktop/README.md b/apps/pips/desktop/README.md new file mode 100644 index 00000000..c5885948 --- /dev/null +++ b/apps/pips/desktop/README.md @@ -0,0 +1,25 @@ +# Pips for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/pips/web.html): 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 Pips 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 | +| --- | --- | +| `pips_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 | +| `pips.spec`, `pips.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 Pips | +| `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/pips-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 +[pips-desktop release](https://github.com/juw12/projects/releases/tag/pips-desktop). The download links never change. diff --git a/apps/pips/desktop/build.py b/apps/pips/desktop/build.py new file mode 100644 index 00000000..63d69a7e --- /dev/null +++ b/apps/pips/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the Pips 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 Pips-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + Pips-Windows-Portable.zip unzip and run Pips.exe + macOS Pips-macOS-AppleSilicon.dmg or Pips-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', 'Pips - Pomodoro widget with animated animals, skill battles and minigames'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'Pips'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'Pips.exe'), + StringStruct('ProductName', 'Pips'), + 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, "pips.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, PIPS_VERSION=version, PIPS_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["PIPS_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "pips.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, "Pips") + portable = os.path.join(DIST, "Pips-Windows-Portable.zip") + zip_folder(folder, portable, "Pips") + 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 Pips-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped Pips-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, "pips.iss")], + check=True, + ) + return [os.path.join(DIST, "Pips-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "Pips.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "Pips-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, "Pips.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "Pips", "-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 Pips 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("Pips desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by pips.spec) + except ImportError: + raise SystemExit("The Pips window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("Pips", "Pips.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building Pips %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/pips/desktop/icon-512.png b/apps/pips/desktop/icon-512.png new file mode 100644 index 00000000..55123759 Binary files /dev/null and b/apps/pips/desktop/icon-512.png differ diff --git a/apps/pips/desktop/offline.html b/apps/pips/desktop/offline.html new file mode 100644 index 00000000..8200ea49 --- /dev/null +++ b/apps/pips/desktop/offline.html @@ -0,0 +1,25 @@ + + + + + + Pips + + + +
+ +

Pips can't reach the internet

+

Pips 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/pips/desktop/pips.iss b/apps/pips/desktop/pips.iss new file mode 100644 index 00000000..c6e2ccd5 --- /dev/null +++ b/apps/pips/desktop/pips.iss @@ -0,0 +1,73 @@ +; Pips for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= pips.iss +; Installs to %LOCALAPPDATA%\Programs\Pips, adds Pips 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%\Pips, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\Pips" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\pips.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=Pips +AppVersion={#AppVersion} +AppVerName=Pips {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/pips/web.html +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\Pips +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=Pips-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\Pips.exe +UninstallDisplayName=Pips +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}\Pips"; Filename: "{app}\Pips.exe"; Comment: "Pomodoro widget with animated animals, skill battles and minigames" +Name: "{userdesktop}\Pips"; Filename: "{app}\Pips.exe"; Comment: "Pomodoro widget with animated animals, skill battles and minigames"; Tasks: desktopicon + +[Run] +Filename: "{app}\Pips.exe"; Description: "{cm:LaunchProgram,Pips}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\Pips.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopPips" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open Pips window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\Pips.exe')) then + Exec(ExpandConstant('{app}\Pips.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/apps/pips/desktop/pips.spec b/apps/pips/desktop/pips.spec new file mode 100644 index 00000000..1ef70803 --- /dev/null +++ b/apps/pips/desktop/pips.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for Pips on Windows and macOS. Build with python desktop/build.py +# Windows dist/Pips/Pips.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/Pips.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("PIPS_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("PIPS_VERSION_FILE") or None +ICON = os.environ.get("PIPS_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, "pips_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="Pips", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="Pips", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="Pips.app", + icon=ICON, + bundle_identifier="io.github.juw12.pips.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "Pips", + "CFBundleDisplayName": "Pips", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/apps/pips/desktop/pips_app.py b/apps/pips/desktop/pips_app.py new file mode 100644 index 00000000..17fb7b23 --- /dev/null +++ b/apps/pips/desktop/pips_app.py @@ -0,0 +1,467 @@ +"""Pips for Windows and macOS: the Pips 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/pips/web.html and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time Pips 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 +Pips opens in the default browser instead. + +Opening Pips while its window is open brings that window to the front; `Pips --stop` closes it. + +Automated checks: PIPS_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; PIPS_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 = "Pips" +APP_URL = os.environ.get("PIPS_DESKTOP_URL") or "https://juw12.github.io/projects/pips/web.html" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#faf8f3" +DARK_BACKGROUND = "#faf8f3" +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('pips.desktop.check', '1');" + " return localStorage.getItem('pips.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("[pips] " + 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"), "Pips") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "Pips") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "pips") + + +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 Pips site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "PipsDesktop/" + 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="pips-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 Pips 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 Pips 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 Pips 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="pips-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("Pips %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("PIPS_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/pips/desktop/shell.json b/apps/pips/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/apps/pips/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/apps/pips/desktop/smoke_test.py b/apps/pips/desktop/smoke_test.py new file mode 100644 index 00000000..6df1d500 --- /dev/null +++ b/apps/pips/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built Pips desktop app and check its window really shows Pips. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/Pips.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with PIPS_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is Pips, 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", "pips", "web")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/pips/web.html" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "Pips", "Pips.exe") + return os.path.join(DESKTOP, "dist", "Pips.app", "Contents", "MacOS", "Pips") + + +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/web.html" % server.server_address[1] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("app", nargs="?", help="the Pips 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="pips-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, PIPS_WINDOW_TEST=report, PIPS_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 "Pips" 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("Pips 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: Pips %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main()