From 3b45beee1347f6921c1c8e9e49b12c71b6f61188 Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:16:26 +0700 Subject: [PATCH 1/5] Sortie for Windows, Mac and Android: the web app in its own window, built and opened on each system before it is published --- .github/workflows/sortie-android.yml | 137 +++++ .github/workflows/sortie-desktop.yml | 177 +++++++ apps/sortie/README.md | 9 + apps/sortie/android/.gitignore | 2 + apps/sortie/android/AndroidManifest.xml | 23 + apps/sortie/android/README.md | 34 ++ apps/sortie/android/app.json | 10 + apps/sortie/android/assets/offline.html | 25 + apps/sortie/android/build.py | 98 ++++ .../res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 14683 bytes apps/sortie/android/res/values/styles.xml | 9 + apps/sortie/android/smoke.py | 128 +++++ .../io/github/juw12/sortie/MainActivity.java | 283 +++++++++++ apps/sortie/desktop/.gitignore | 3 + apps/sortie/desktop/README.md | 25 + apps/sortie/desktop/build.py | 174 +++++++ apps/sortie/desktop/icon-512.png | Bin 0 -> 59242 bytes apps/sortie/desktop/offline.html | 25 + apps/sortie/desktop/shell.json | 3 + apps/sortie/desktop/smoke_test.py | 92 ++++ apps/sortie/desktop/sortie.iss | 73 +++ apps/sortie/desktop/sortie.spec | 64 +++ apps/sortie/desktop/sortie_app.py | 467 ++++++++++++++++++ 23 files changed, 1861 insertions(+) create mode 100644 .github/workflows/sortie-android.yml create mode 100644 .github/workflows/sortie-desktop.yml create mode 100644 apps/sortie/android/.gitignore create mode 100644 apps/sortie/android/AndroidManifest.xml create mode 100644 apps/sortie/android/README.md create mode 100644 apps/sortie/android/app.json create mode 100644 apps/sortie/android/assets/offline.html create mode 100644 apps/sortie/android/build.py create mode 100644 apps/sortie/android/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 apps/sortie/android/res/values/styles.xml create mode 100644 apps/sortie/android/smoke.py create mode 100644 apps/sortie/android/src/io/github/juw12/sortie/MainActivity.java create mode 100644 apps/sortie/desktop/.gitignore create mode 100644 apps/sortie/desktop/README.md create mode 100644 apps/sortie/desktop/build.py create mode 100644 apps/sortie/desktop/icon-512.png create mode 100644 apps/sortie/desktop/offline.html create mode 100644 apps/sortie/desktop/shell.json create mode 100644 apps/sortie/desktop/smoke_test.py create mode 100644 apps/sortie/desktop/sortie.iss create mode 100644 apps/sortie/desktop/sortie.spec create mode 100644 apps/sortie/desktop/sortie_app.py diff --git a/.github/workflows/sortie-android.yml b/.github/workflows/sortie-android.yml new file mode 100644 index 00000000..2c2e88bc --- /dev/null +++ b/.github/workflows/sortie-android.yml @@ -0,0 +1,137 @@ +name: Sortie Android app + +# Builds Sortie-android.apk (apps/sortie/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 sortie-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "apps/sortie/android/**" + - ".github/workflows/sortie-android.yml" + pull_request: + paths: + - "apps/sortie/android/**" + - ".github/workflows/sortie-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/sortie/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/sortie/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/sortie/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs apps/sortie/android/dist/Sortie-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd apps/sortie/android/dist && sha256sum Sortie-android.apk > Sortie-android.apk.sha256 && cat Sortie-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: sortie-android + path: apps/sortie/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: sortie-android + path: apps/sortie/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/sortie/android/smoke.py apps/sortie/android/dist/Sortie-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: sortie-android-emulator-check + path: | + apps/sortie/android/dist/*.png + apps/sortie/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: sortie-android + path: dist + # The sortie-android release keeps one address for the download. The file there is replaced only when + # apps/sortie/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the sortie-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('apps/sortie/android/app.json'))['versionName'])") + echo "$version" > dist/Sortie-android.version.txt + if ! gh release view sortie-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "Sortie for Android: a full-screen window around the web app (https://juw12.github.io/projects/sortie/)." "" \ + "Download [Sortie-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/sortie-android/Sortie-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 sortie-android dist/Sortie-android.apk dist/Sortie-android.apk.sha256 dist/Sortie-android.version.txt \ + --title "Sortie for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the sortie-android release with Sortie-android.apk $version" + exit 0 + fi + published=$(gh release download sortie-android --repo "$GITHUB_REPOSITORY" --pattern Sortie-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the sortie-android release already has Sortie-android.apk $version" + exit 0 + fi + gh release upload sortie-android dist/Sortie-android.apk dist/Sortie-android.apk.sha256 dist/Sortie-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "Sortie-android.apk on the sortie-android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/sortie-desktop.yml b/.github/workflows/sortie-desktop.yml new file mode 100644 index 00000000..14d401d5 --- /dev/null +++ b/.github/workflows/sortie-desktop.yml @@ -0,0 +1,177 @@ +name: Sortie apps + +# Builds the downloadable Sortie apps and publishes them to the "sortie-desktop" release from main: +# Windows Sortie-Windows-Setup.exe (per-user installer) + Sortie-Windows-Portable.zip +# macOS Sortie-macOS-AppleSilicon.dmg + Sortie-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/sortie/desktop/**' + - '.github/workflows/sortie-desktop.yml' + pull_request: + paths: + - 'apps/sortie/desktop/**' + - '.github/workflows/sortie-desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: sortie-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/sortie/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's Sortie + run: python apps/sortie/desktop/smoke_test.py --built --local-site + - name: Install with Sortie-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'apps/sortie/desktop/dist/Sortie-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'sortie-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\Sortie\Sortie.exe' + if (-not (Test-Path $app)) { throw "Sortie.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'Sortie.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Sortie.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 'Sortie' + if (-not $entry) { throw 'Sortie is missing from Settings > Apps' } + python apps/sortie/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 Sortie.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/sortie/desktop/dist/Sortie.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.sortie.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("apps/sortie/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/Sortie")" + codesign --verify --deep --verbose=2 "$APP" + for image in apps/sortie/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: Sortie-${{ runner.os }}-${{ runner.arch }} + path: apps/sortie/desktop/dist/Sortie-* + 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: Sortie-* + 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 Sortie-Windows-Setup.exe Sortie-Windows-Portable.zip \ + Sortie-macOS-AppleSilicon.dmg Sortie-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' + **Sortie**: a file organizer that is fun to use. The apps open the same Sortie as https://juw12.github.io/projects/sortie/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [Sortie-Windows-Setup.exe](https://github.com/juw12/projects/releases/download/sortie-desktop/Sortie-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: [Sortie-Windows-Portable.zip](https://github.com/juw12/projects/releases/download/sortie-desktop/Sortie-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [Sortie-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/sortie-desktop/Sortie-macOS-AppleSilicon.dmg) | Open it and drag Sortie to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [Sortie-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/sortie-desktop/Sortie-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/sortie/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [Sortie-android.apk](https://github.com/juw12/projects/releases/download/sortie-android/Sortie-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load Sortie 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 sortie-desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload sortie-desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit sortie-desktop --notes-file notes.md --repo "$REPO" + else + gh release create sortie-desktop $FILES SHA256SUMS.txt --title "Sortie for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/apps/sortie/README.md b/apps/sortie/README.md index ac4bbad1..60d48425 100644 --- a/apps/sortie/README.md +++ b/apps/sortie/README.md @@ -48,6 +48,15 @@

+## Get it on your device + +- **Windows:** [`Sortie-Windows-Setup.exe`](https://github.com/juw12/projects/releases/download/sortie-desktop/Sortie-Windows-Setup.exe) (no admin needed; if Windows says it protected your PC, choose *More info → Run anyway*), or without installing [`Sortie-Windows-Portable.zip`](https://github.com/juw12/projects/releases/download/sortie-desktop/Sortie-Windows-Portable.zip). +- **Mac:** [`Sortie-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/sortie-desktop/Sortie-macOS-AppleSilicon.dmg) (M1 and newer) or [`Sortie-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/sortie-desktop/Sortie-macOS-Intel.dmg). The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`Sortie-android.apk`](https://github.com/juw12/projects/releases/download/sortie-android/Sortie-android.apk): open the file on the phone and allow your browser to install apps once. +- **iPhone:** open https://juw12.github.io/projects/sortie/ in Safari, tap Share, then **Add to Home Screen**. + +The Windows, Mac and Android apps are the web app in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. Each build is opened on GitHub's machines before it is published: on Windows and on a Mac the page loads, the app starts and can store data; on an Android emulator it installs, opens and stays up. They are not code-signed or notarised, and no real phone or PC has run them yet. + ## About A file organizer with animated sorting, a recoverable delete ("Vacuum bag") and a built-in assistant. diff --git a/apps/sortie/android/.gitignore b/apps/sortie/android/.gitignore new file mode 100644 index 00000000..edd9d60a --- /dev/null +++ b/apps/sortie/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/apps/sortie/android/AndroidManifest.xml b/apps/sortie/android/AndroidManifest.xml new file mode 100644 index 00000000..89ed1a90 --- /dev/null +++ b/apps/sortie/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/apps/sortie/android/README.md b/apps/sortie/android/README.md new file mode 100644 index 00000000..48f5749b --- /dev/null +++ b/apps/sortie/android/README.md @@ -0,0 +1,34 @@ +# Sortie for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/projects/sortie/): the same Sortie 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: [`Sortie-android.apk`](https://github.com/juw12/projects/releases/download/sortie-android/Sortie-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/sortie/android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/sortie-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 +`Sortie-android.apk` on the `sortie-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/sortie/android/app.json b/apps/sortie/android/app.json new file mode 100644 index 00000000..be6a6974 --- /dev/null +++ b/apps/sortie/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "Sortie", + "id": "io.github.juw12.sortie", + "url": "https://juw12.github.io/projects/sortie/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/apps/sortie/android/assets/offline.html b/apps/sortie/android/assets/offline.html new file mode 100644 index 00000000..7cec843a --- /dev/null +++ b/apps/sortie/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + Sortie + + + +
+ +

Sortie can't reach the internet

+

Sortie 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/sortie/android/build.py b/apps/sortie/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/apps/sortie/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/sortie/android/res/mipmap-xxxhdpi/ic_launcher.png b/apps/sortie/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..b072c630686d597bb474cb89557b4158da4443ff GIT binary patch literal 14683 zcmch8Q*CCd%<}O#%UNj!20L zsd@rm`FSOfYIs=?EPKom&BU-4yO1&!n~0yL37!H$4;#kUEUJxJ+|N?bQ^Xz81@?u8)-u8L4lnLqHr&;b;fhCZ7oWuJ$}Vq_e`I6cz1S6 z!zXiXX)*LY>s>#8-W^rfTxM;vjpZz<*r9{`5-V_M3{TYy146EVQoSvp1EU6M0XHzy zMXuNv)PYh3vxe=RY$sM632H^EfLg-vO?470hz7MIQbewxd!asv7DR_!7cL-H)VWa` zMGvAz_#GxFR?xaz9YX`62C#$;iWamR(7@IJtKyu;06`C053XmfgK`Z8oL*gBTwGjT z@d-B@Xgx*?N+_;t*Y;W1+k2ar={qEdpvP8GpkPW8C~$STU;R7F)al!6N2eLJu&~IE z^&Tl)2SMhoTK4ui&YJ1S+qT*9o^e~zbNSbyW8ix`!tk|I|8W!H;YfWh^1P|^OF^t) zD80A7&B59Hj)dTIX6JKjXU+4x@_=U4+}wPiqVlYA!~S*P<;AmSfw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b)5PgC5lvAQO(pME%Mod2(eIaR0srOv$n$wD{Z Zz{DDPsoz_fk^eO|N{Pvf)(IO1{~zs|`;Y(t literal 0 HcmV?d00001 diff --git a/apps/sortie/android/res/values/styles.xml b/apps/sortie/android/res/values/styles.xml new file mode 100644 index 00000000..03052e90 --- /dev/null +++ b/apps/sortie/android/res/values/styles.xml @@ -0,0 +1,9 @@ + + + #0e1014 + + diff --git a/apps/sortie/android/smoke.py b/apps/sortie/android/smoke.py new file mode 100644 index 00000000..b8d26fd0 --- /dev/null +++ b/apps/sortie/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the Sortie APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/Sortie-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("\nSortie 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/sortie/android/src/io/github/juw12/sortie/MainActivity.java b/apps/sortie/android/src/io/github/juw12/sortie/MainActivity.java new file mode 100644 index 00000000..70833d84 --- /dev/null +++ b/apps/sortie/android/src/io/github/juw12/sortie/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.sortie; + +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; + +/** + * Sortie 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/sortie/"; + private static final String SCOPE = "juw12.github.io/projects/sortie"; + 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() + " SortieAndroid/" + 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("SortieShell", "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("SortieShell", "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/sortie/desktop/.gitignore b/apps/sortie/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/apps/sortie/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/apps/sortie/desktop/README.md b/apps/sortie/desktop/README.md new file mode 100644 index 00000000..34e081ca --- /dev/null +++ b/apps/sortie/desktop/README.md @@ -0,0 +1,25 @@ +# Sortie for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/sortie/): 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 Sortie 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 | +| --- | --- | +| `sortie_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 | +| `sortie.spec`, `sortie.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 Sortie | +| `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/sortie-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 +[sortie-desktop release](https://github.com/juw12/projects/releases/tag/sortie-desktop). The download links never change. diff --git a/apps/sortie/desktop/build.py b/apps/sortie/desktop/build.py new file mode 100644 index 00000000..47935c89 --- /dev/null +++ b/apps/sortie/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the Sortie 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 Sortie-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + Sortie-Windows-Portable.zip unzip and run Sortie.exe + macOS Sortie-macOS-AppleSilicon.dmg or Sortie-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', 'Sortie - A file organizer that is fun to use'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'Sortie'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'Sortie.exe'), + StringStruct('ProductName', 'Sortie'), + 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, "sortie.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, SORTIE_VERSION=version, SORTIE_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["SORTIE_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "sortie.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, "Sortie") + portable = os.path.join(DIST, "Sortie-Windows-Portable.zip") + zip_folder(folder, portable, "Sortie") + 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 Sortie-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped Sortie-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, "sortie.iss")], + check=True, + ) + return [os.path.join(DIST, "Sortie-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "Sortie.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "Sortie-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, "Sortie.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "Sortie", "-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 Sortie 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("Sortie desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by sortie.spec) + except ImportError: + raise SystemExit("The Sortie window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("Sortie", "Sortie.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building Sortie %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/sortie/desktop/icon-512.png b/apps/sortie/desktop/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..f4b867ae6a5acd4f8e76d51446d530057334cfcb GIT binary patch literal 59242 zcmeEug;yJ4-(_%jcPLs)@ghZwyE_zjDDD<0?oiydK#N0hNht1C+}+(Z8{YSPyZb-v z@|>I*NX|@V<|p^L_dZ0bC`n_WlA;0t01R0f2{ix!7P<=yKz`f!l8RSCH!!Yh(qe$B zG4ccGFA^3yvX+X90A}buG5{vr1_1x|5$KB)`T_vp@?ijQ&@If{-|}Jq=UrGpKHUG= zfBPWXeM2Y!APSI`_@dzjbKJ3)#3JjmKKE17?&kVx=Q?fHa zHxcKQl9Dpx6o-$xs#czayA2=y{!hKb238`aeUI4jV(%533OVZ6IpEP6E)a zd;3kLQ6%059QIle(|-m`iYPY#PVb_2{=dhW1oU|R_Xx(K^w=2SKrKHOk7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Pcky3q0L8@Sy11u zq^F_1BgygD2tY%B#KM)7u&FPZ1fZ2-=1Ssu$VE@fES_(h1Xx$w;-*@YHBJINw@eZL z&q)F;y?BLA-hb9uXz43Wh3J#1PS$zF0cYPKrc`UzT;c$!NpWVX6Y&ZF&8Yv6D^zQD z9s_7(3mA>XsZP$Q?KF(M%>DmO{{LS7zcnzDDFDCqu8hV}cMkydu`;`D+I++F@&5pj CqnybA literal 0 HcmV?d00001 diff --git a/apps/sortie/desktop/offline.html b/apps/sortie/desktop/offline.html new file mode 100644 index 00000000..6cf54085 --- /dev/null +++ b/apps/sortie/desktop/offline.html @@ -0,0 +1,25 @@ + + + + + + Sortie + + + +

+ +

Sortie can't reach the internet

+

Sortie 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/sortie/desktop/shell.json b/apps/sortie/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/apps/sortie/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/apps/sortie/desktop/smoke_test.py b/apps/sortie/desktop/smoke_test.py new file mode 100644 index 00000000..0b4924e8 --- /dev/null +++ b/apps/sortie/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built Sortie desktop app and check its window really shows Sortie. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/Sortie.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with SORTIE_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is Sortie, 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", "sortie", "web")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/sortie/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "Sortie", "Sortie.exe") + return os.path.join(DESKTOP, "dist", "Sortie.app", "Contents", "MacOS", "Sortie") + + +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 Sortie 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="sortie-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, SORTIE_WINDOW_TEST=report, SORTIE_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 "Sortie" 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("Sortie 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: Sortie %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/sortie/desktop/sortie.iss b/apps/sortie/desktop/sortie.iss new file mode 100644 index 00000000..00f0da7f --- /dev/null +++ b/apps/sortie/desktop/sortie.iss @@ -0,0 +1,73 @@ +; Sortie for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= sortie.iss +; Installs to %LOCALAPPDATA%\Programs\Sortie, adds Sortie 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%\Sortie, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\Sortie" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\sortie.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=Sortie +AppVersion={#AppVersion} +AppVerName=Sortie {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/sortie/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\Sortie +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=Sortie-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\Sortie.exe +UninstallDisplayName=Sortie +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}\Sortie"; Filename: "{app}\Sortie.exe"; Comment: "A file organizer that is fun to use" +Name: "{userdesktop}\Sortie"; Filename: "{app}\Sortie.exe"; Comment: "A file organizer that is fun to use"; Tasks: desktopicon + +[Run] +Filename: "{app}\Sortie.exe"; Description: "{cm:LaunchProgram,Sortie}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\Sortie.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopSortie" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open Sortie window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\Sortie.exe')) then + Exec(ExpandConstant('{app}\Sortie.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/apps/sortie/desktop/sortie.spec b/apps/sortie/desktop/sortie.spec new file mode 100644 index 00000000..1e781742 --- /dev/null +++ b/apps/sortie/desktop/sortie.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for Sortie on Windows and macOS. Build with python desktop/build.py +# Windows dist/Sortie/Sortie.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/Sortie.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("SORTIE_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("SORTIE_VERSION_FILE") or None +ICON = os.environ.get("SORTIE_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, "sortie_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="Sortie", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="Sortie", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="Sortie.app", + icon=ICON, + bundle_identifier="io.github.juw12.sortie.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "Sortie", + "CFBundleDisplayName": "Sortie", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/apps/sortie/desktop/sortie_app.py b/apps/sortie/desktop/sortie_app.py new file mode 100644 index 00000000..03eed20d --- /dev/null +++ b/apps/sortie/desktop/sortie_app.py @@ -0,0 +1,467 @@ +"""Sortie for Windows and macOS: the Sortie 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/sortie/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time Sortie 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 +Sortie opens in the default browser instead. + +Opening Sortie while its window is open brings that window to the front; `Sortie --stop` closes it. + +Automated checks: SORTIE_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; SORTIE_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 = "Sortie" +APP_URL = os.environ.get("SORTIE_DESKTOP_URL") or "https://juw12.github.io/projects/sortie/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#0e1014" +DARK_BACKGROUND = "#0e1014" +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('sortie.desktop.check', '1');" + " return localStorage.getItem('sortie.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("[sortie] " + 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"), "Sortie") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "Sortie") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "sortie") + + +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 Sortie site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "SortieDesktop/" + 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="sortie-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 Sortie 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 Sortie 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 Sortie 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="sortie-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("Sortie %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("SORTIE_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()) From 1be0876cbe99aa96b5ba475648772c8ec7fd101a Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:16:40 +0700 Subject: [PATCH 2/5] Lingua for Mac: the web app in its own window, built and opened on each system before it is published --- .github/workflows/lingua-mac.yml | 172 +++++++++++ apps/lingua/README.md | 6 + apps/lingua/desktop/.gitignore | 3 + apps/lingua/desktop/README.md | 25 ++ apps/lingua/desktop/build.py | 174 +++++++++++ apps/lingua/desktop/icon-512.png | Bin 0 -> 24830 bytes apps/lingua/desktop/lingua.iss | 73 +++++ apps/lingua/desktop/lingua.spec | 64 ++++ apps/lingua/desktop/lingua_app.py | 467 ++++++++++++++++++++++++++++++ apps/lingua/desktop/offline.html | 25 ++ apps/lingua/desktop/shell.json | 3 + apps/lingua/desktop/smoke_test.py | 92 ++++++ 12 files changed, 1104 insertions(+) create mode 100644 .github/workflows/lingua-mac.yml create mode 100644 apps/lingua/desktop/.gitignore create mode 100644 apps/lingua/desktop/README.md create mode 100644 apps/lingua/desktop/build.py create mode 100644 apps/lingua/desktop/icon-512.png create mode 100644 apps/lingua/desktop/lingua.iss create mode 100644 apps/lingua/desktop/lingua.spec create mode 100644 apps/lingua/desktop/lingua_app.py create mode 100644 apps/lingua/desktop/offline.html create mode 100644 apps/lingua/desktop/shell.json create mode 100644 apps/lingua/desktop/smoke_test.py diff --git a/.github/workflows/lingua-mac.yml b/.github/workflows/lingua-mac.yml new file mode 100644 index 00000000..80e0ef75 --- /dev/null +++ b/.github/workflows/lingua-mac.yml @@ -0,0 +1,172 @@ +name: Lingua apps + +# Builds the downloadable Lingua apps and publishes them to the "lingua-mac" release from main: +# macOS Lingua-macOS-AppleSilicon.dmg + Lingua-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/lingua/desktop/**' + - '.github/workflows/lingua-mac.yml' + pull_request: + paths: + - 'apps/lingua/desktop/**' + - '.github/workflows/lingua-mac.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: lingua-mac-${{ github.ref }} + cancel-in-progress: true + +jobs: + desktop: + name: Desktop (${{ matrix.name }}) + strategy: + fail-fast: false + matrix: + include: + - 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/lingua/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's Lingua + run: python apps/lingua/desktop/smoke_test.py --built --local-site + - name: Install with Lingua-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'apps/lingua/desktop/dist/Lingua-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'lingua-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\Lingua\Lingua.exe' + if (-not (Test-Path $app)) { throw "Lingua.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'Lingua.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Lingua.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 'Lingua' + if (-not $entry) { throw 'Lingua is missing from Settings > Apps' } + python apps/lingua/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 Lingua.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/lingua/desktop/dist/Lingua.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.lingua.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("apps/lingua/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/Lingua")" + codesign --verify --deep --verbose=2 "$APP" + for image in apps/lingua/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: Lingua-${{ runner.os }}-${{ runner.arch }} + path: apps/lingua/desktop/dist/Lingua-* + 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: Lingua-* + 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 Lingua-macOS-AppleSilicon.dmg Lingua-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' + **Lingua**: translate live Teams captions. The apps open the same Lingua as https://juw12.github.io/projects/lingua/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Mac with Apple chip (M1 and newer)** | [Lingua-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/lingua-mac/Lingua-macOS-AppleSilicon.dmg) | Open it and drag Lingua to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [Lingua-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/lingua-mac/Lingua-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/lingua/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [Lingua-android.apk](https://github.com/juw12/projects/releases/download/lingua-android/Lingua-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load Lingua 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 lingua-mac --repo "$REPO" > /dev/null 2>&1; then + gh release upload lingua-mac $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit lingua-mac --notes-file notes.md --repo "$REPO" + else + gh release create lingua-mac $FILES SHA256SUMS.txt --title "Lingua for Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/apps/lingua/README.md b/apps/lingua/README.md index c144f955..20d3fff7 100644 --- a/apps/lingua/README.md +++ b/apps/lingua/README.md @@ -7,6 +7,12 @@ language. > Teams talks. You read along, translated. +## On a Mac + +- **Mac:** [`Lingua-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/lingua-mac/Lingua-macOS-AppleSilicon.dmg) (M1 and newer) or [`Lingua-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/lingua-mac/Lingua-macOS-Intel.dmg). Open it and drag Lingua to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. + +It is the web edition (https://juw12.github.io/projects/lingua/) in its own window ([`desktop/`](desktop/README.md)) and changes with it. Live caption capture needs a browser that can share the screen (Chrome, Edge or Firefox on the Mac); in this window use Mobile translate and Read picture. Each build is opened on an Apple-silicon Mac and an Intel Mac on GitHub before it is published: the page loads, the app starts and can store data. No Mac of ours has run it yet. + ## Status **v0.1** (new). The whole app is one two-stage pipeline: screen-read the diff --git a/apps/lingua/desktop/.gitignore b/apps/lingua/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/apps/lingua/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/apps/lingua/desktop/README.md b/apps/lingua/desktop/README.md new file mode 100644 index 00000000..287fbad8 --- /dev/null +++ b/apps/lingua/desktop/README.md @@ -0,0 +1,25 @@ +# Lingua for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/lingua/): 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 Lingua 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 | +| --- | --- | +| `lingua_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 | +| `lingua.spec`, `lingua.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 Lingua | +| `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/lingua-mac.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 +[lingua-mac release](https://github.com/juw12/projects/releases/tag/lingua-mac). The download links never change. diff --git a/apps/lingua/desktop/build.py b/apps/lingua/desktop/build.py new file mode 100644 index 00000000..ca21288e --- /dev/null +++ b/apps/lingua/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the Lingua 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 Lingua-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + Lingua-Windows-Portable.zip unzip and run Lingua.exe + macOS Lingua-macOS-AppleSilicon.dmg or Lingua-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', 'Lingua - Translate live Teams captions'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'Lingua'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'Lingua.exe'), + StringStruct('ProductName', 'Lingua'), + 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, "lingua.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, LINGUA_VERSION=version, LINGUA_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["LINGUA_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "lingua.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, "Lingua") + portable = os.path.join(DIST, "Lingua-Windows-Portable.zip") + zip_folder(folder, portable, "Lingua") + 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 Lingua-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped Lingua-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, "lingua.iss")], + check=True, + ) + return [os.path.join(DIST, "Lingua-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "Lingua.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "Lingua-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, "Lingua.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "Lingua", "-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 Lingua 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("Lingua desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by lingua.spec) + except ImportError: + raise SystemExit("The Lingua window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("Lingua", "Lingua.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building Lingua %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/lingua/desktop/icon-512.png b/apps/lingua/desktop/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..111158bfa724c9ded0bbeecc254995f2c883819f GIT binary patch literal 24830 zcmX_nbwHC}8|Y|I8focL0RfScmJ|?FkS+n~?g4`l(%l_`qS7K=Lt46fqZ>vK7;#^I z-@SK#jBW2Z&w0+%MZ`OGC87s(4?rLg(Hmv?4;NX0<7ZTor zK4%iu1zsOM=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2Nqt1W$>7(Z!mrjEePU&e7g;V+^sp-Z z+lke!ACHQ^TaxtZ6Nti(AZw3uXL;<<=CJl+RB)Qo(%ysLq)z~IQRcks!J@Qt7my_- z49{@OmjIJN^PXo72CB*tJ;HmrSsxu5eqv3Ore`s&uwJ*y@|RIi_~m{lG?e-^*xR*q zf=!{m%I0D`7S7>3u6jlga+~pWj6)-79*zkvuBdnq9wjbMUKUco@0od|-N3)usi^pU z^y-rfN0LV<@Ddsr91z&+JiB#904$h00s}i=hB^!Ht zP~n}RJ3Z~8sROdwtJU7fA|QYq3~O6QMSh`r(7v!OP6}9B?Q1-8$FOj6a=w&9h4NCc zo4Rel8nco$i+N&_0t(RY*;j1x?zD|UxF0=yD20m@P$jOuzN0D$TpOVcmY1;04L|;)M1AM% z5*pdJ@yU^y_vX`s-xu%Qi)Q;QE!YK#Ds#j&W}PM0TTf?yK^Y?CJx^pZ(VTep9&8Ze zxK(!QOFv6;`?=Tox(RN1#2Qnpjres1o0YqFzOhjBU8gXF!Ka8jcZ{*DCx5)Hs2Boq z33kSnj{ELYbv}GAIzlQQz=D|Q{yY_u#2NSYW+?iuj%SwJ?PoUF+s_RT8(4Y(zUl{L z9_6PtZ`{nlz{Dh)o|-~}kB^U!j(!sz9UT`P{gBMT$H&2u{_fpmrS<~2i7#%XP;1}a h#3Yqnua`_6=!9iVw3S!^|JML=?~a~Ek-Bx*{{zjaE7t%3 literal 0 HcmV?d00001 diff --git a/apps/lingua/desktop/lingua.iss b/apps/lingua/desktop/lingua.iss new file mode 100644 index 00000000..1b514d9d --- /dev/null +++ b/apps/lingua/desktop/lingua.iss @@ -0,0 +1,73 @@ +; Lingua for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= lingua.iss +; Installs to %LOCALAPPDATA%\Programs\Lingua, adds Lingua 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%\Lingua, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\Lingua" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\lingua.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=Lingua +AppVersion={#AppVersion} +AppVerName=Lingua {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/lingua/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\Lingua +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=Lingua-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\Lingua.exe +UninstallDisplayName=Lingua +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}\Lingua"; Filename: "{app}\Lingua.exe"; Comment: "Translate live Teams captions" +Name: "{userdesktop}\Lingua"; Filename: "{app}\Lingua.exe"; Comment: "Translate live Teams captions"; Tasks: desktopicon + +[Run] +Filename: "{app}\Lingua.exe"; Description: "{cm:LaunchProgram,Lingua}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\Lingua.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopLingua" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open Lingua window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\Lingua.exe')) then + Exec(ExpandConstant('{app}\Lingua.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/apps/lingua/desktop/lingua.spec b/apps/lingua/desktop/lingua.spec new file mode 100644 index 00000000..85b0e477 --- /dev/null +++ b/apps/lingua/desktop/lingua.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for Lingua on Windows and macOS. Build with python desktop/build.py +# Windows dist/Lingua/Lingua.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/Lingua.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("LINGUA_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("LINGUA_VERSION_FILE") or None +ICON = os.environ.get("LINGUA_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, "lingua_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="Lingua", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="Lingua", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="Lingua.app", + icon=ICON, + bundle_identifier="io.github.juw12.lingua.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "Lingua", + "CFBundleDisplayName": "Lingua", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/apps/lingua/desktop/lingua_app.py b/apps/lingua/desktop/lingua_app.py new file mode 100644 index 00000000..e08d8d85 --- /dev/null +++ b/apps/lingua/desktop/lingua_app.py @@ -0,0 +1,467 @@ +"""Lingua for Windows and macOS: the Lingua 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/lingua/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time Lingua 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 +Lingua opens in the default browser instead. + +Opening Lingua while its window is open brings that window to the front; `Lingua --stop` closes it. + +Automated checks: LINGUA_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; LINGUA_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 = "Lingua" +APP_URL = os.environ.get("LINGUA_DESKTOP_URL") or "https://juw12.github.io/projects/lingua/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#0b0e14" +DARK_BACKGROUND = "#0b0e14" +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('lingua.desktop.check', '1');" + " return localStorage.getItem('lingua.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("[lingua] " + 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"), "Lingua") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "Lingua") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "lingua") + + +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 Lingua site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "LinguaDesktop/" + 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="lingua-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 Lingua 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 Lingua 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 Lingua 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="lingua-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("Lingua %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("LINGUA_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/lingua/desktop/offline.html b/apps/lingua/desktop/offline.html new file mode 100644 index 00000000..dccab756 --- /dev/null +++ b/apps/lingua/desktop/offline.html @@ -0,0 +1,25 @@ + + + + + + Lingua + + + +
+ +

Lingua can't reach the internet

+

Lingua 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/lingua/desktop/shell.json b/apps/lingua/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/apps/lingua/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/apps/lingua/desktop/smoke_test.py b/apps/lingua/desktop/smoke_test.py new file mode 100644 index 00000000..7e969507 --- /dev/null +++ b/apps/lingua/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built Lingua desktop app and check its window really shows Lingua. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/Lingua.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with LINGUA_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is Lingua, 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", "lingua", "web")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/lingua/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "Lingua", "Lingua.exe") + return os.path.join(DESKTOP, "dist", "Lingua.app", "Contents", "MacOS", "Lingua") + + +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 Lingua 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="lingua-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, LINGUA_WINDOW_TEST=report, LINGUA_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 "Lingua" 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("Lingua 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: Lingua %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main() From c1628eb5e1a0fc0c483a98d9bb52c20764f2ebc5 Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:17:00 +0700 Subject: [PATCH 3/5] Lingua for Android: the web app in its own window, built and opened on each system before it is published --- .github/workflows/lingua-android.yml | 137 +++++++++ apps/lingua/android/.gitignore | 2 + apps/lingua/android/AndroidManifest.xml | 23 ++ apps/lingua/android/README.md | 34 +++ apps/lingua/android/app.json | 10 + apps/lingua/android/assets/offline.html | 25 ++ apps/lingua/android/build.py | 98 ++++++ .../res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 13359 bytes apps/lingua/android/res/values/styles.xml | 9 + apps/lingua/android/smoke.py | 128 ++++++++ .../io/github/juw12/lingua/MainActivity.java | 283 ++++++++++++++++++ 11 files changed, 749 insertions(+) create mode 100644 .github/workflows/lingua-android.yml create mode 100644 apps/lingua/android/.gitignore create mode 100644 apps/lingua/android/AndroidManifest.xml create mode 100644 apps/lingua/android/README.md create mode 100644 apps/lingua/android/app.json create mode 100644 apps/lingua/android/assets/offline.html create mode 100644 apps/lingua/android/build.py create mode 100644 apps/lingua/android/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 apps/lingua/android/res/values/styles.xml create mode 100644 apps/lingua/android/smoke.py create mode 100644 apps/lingua/android/src/io/github/juw12/lingua/MainActivity.java diff --git a/.github/workflows/lingua-android.yml b/.github/workflows/lingua-android.yml new file mode 100644 index 00000000..ea0804a8 --- /dev/null +++ b/.github/workflows/lingua-android.yml @@ -0,0 +1,137 @@ +name: Lingua Android app + +# Builds Lingua-android.apk (apps/lingua/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 lingua-android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "apps/lingua/android/**" + - ".github/workflows/lingua-android.yml" + pull_request: + paths: + - "apps/lingua/android/**" + - ".github/workflows/lingua-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/lingua/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/lingua/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/lingua/android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs apps/lingua/android/dist/Lingua-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd apps/lingua/android/dist && sha256sum Lingua-android.apk > Lingua-android.apk.sha256 && cat Lingua-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: lingua-android + path: apps/lingua/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: lingua-android + path: apps/lingua/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/lingua/android/smoke.py apps/lingua/android/dist/Lingua-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: lingua-android-emulator-check + path: | + apps/lingua/android/dist/*.png + apps/lingua/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: lingua-android + path: dist + # The lingua-android release keeps one address for the download. The file there is replaced only when + # apps/lingua/android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the lingua-android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('apps/lingua/android/app.json'))['versionName'])") + echo "$version" > dist/Lingua-android.version.txt + if ! gh release view lingua-android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "Lingua for Android: a full-screen window around the web app (https://juw12.github.io/projects/lingua/)." "" \ + "Download [Lingua-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/lingua-android/Lingua-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 lingua-android dist/Lingua-android.apk dist/Lingua-android.apk.sha256 dist/Lingua-android.version.txt \ + --title "Lingua for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the lingua-android release with Lingua-android.apk $version" + exit 0 + fi + published=$(gh release download lingua-android --repo "$GITHUB_REPOSITORY" --pattern Lingua-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the lingua-android release already has Lingua-android.apk $version" + exit 0 + fi + gh release upload lingua-android dist/Lingua-android.apk dist/Lingua-android.apk.sha256 dist/Lingua-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "Lingua-android.apk on the lingua-android release is now $version (was: ${published:-none})" diff --git a/apps/lingua/android/.gitignore b/apps/lingua/android/.gitignore new file mode 100644 index 00000000..edd9d60a --- /dev/null +++ b/apps/lingua/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/apps/lingua/android/AndroidManifest.xml b/apps/lingua/android/AndroidManifest.xml new file mode 100644 index 00000000..0bd5efb3 --- /dev/null +++ b/apps/lingua/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/apps/lingua/android/README.md b/apps/lingua/android/README.md new file mode 100644 index 00000000..df17d99e --- /dev/null +++ b/apps/lingua/android/README.md @@ -0,0 +1,34 @@ +# Lingua for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/projects/lingua/): the same Lingua 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: [`Lingua-android.apk`](https://github.com/juw12/projects/releases/download/lingua-android/Lingua-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/lingua/android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/lingua-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 +`Lingua-android.apk` on the `lingua-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/lingua/android/app.json b/apps/lingua/android/app.json new file mode 100644 index 00000000..264770b1 --- /dev/null +++ b/apps/lingua/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "Lingua", + "id": "io.github.juw12.lingua", + "url": "https://juw12.github.io/projects/lingua/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/apps/lingua/android/assets/offline.html b/apps/lingua/android/assets/offline.html new file mode 100644 index 00000000..6ea3d45b --- /dev/null +++ b/apps/lingua/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + Lingua + + + +
+ +

Lingua can't reach the internet

+

Lingua 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/lingua/android/build.py b/apps/lingua/android/build.py new file mode 100644 index 00000000..ae5e3b1f --- /dev/null +++ b/apps/lingua/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/lingua/android/res/mipmap-xxxhdpi/ic_launcher.png b/apps/lingua/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..56e1901b0d24e17452495af4ab72206487bc67fb GIT binary patch literal 13359 zcmV+~G|Px#L}ge>W=%~1DgXcg2mk?xX#fNO00031000^Q000001E2u_0{{R30RRC20H6W@ z1ONa40RR91z@P&F1ONa40RR91zyJUM08KkN$^ZZ}nMp)JRCodHeF=OO)!BFMnmr*Q z3kd-Nf}pseA_DFpYOCT7qF<|TTVJc6Z>!Z`zbZG`ib`vX0#!sd z68*pJ&cFbLPy9BNB;ZS-tuF z{`&fc#>S={J9n;F`O(f@yY}zf-_Y1}`0!ze!(p|w48Ir;AfUy?#nn}VDl037*VdkS z=7bT$YpbdT4IW(W^?GAatvGO4m_SIBWy@9|V?J5Ex~^_-M@NURyW8cY4SB;iD|F8A zNZ|p*lyBj1I1~!!=H?U>6bv0wbNcD0PMUb;7=!aM>Ls0`}XaB={bf|v*@3tQ2GJnDTG)* zNMsfy+tDbI3r?4rBhfzuv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h?BZa53bGrYMC3ORFhyZQPEM76=|i!vkY6*F5{ddq<5LDeq%r2?V~OQ26yX-g@}A zzu&lNOSaeRa`V;rtTB=oYZfz;KxRFclnyI2aF6}Cxb4}>-P6k3`cVl71afH?KjeJBipAOYI|q}wjWKNt*QwhwDF zZn*xs|9jgl14~Oyh&7o&TvFYhy)V5y_vKgS?ylQ|2GHyEIPujS+R`@?;*u@e%cvO@ zC4+4hPE@J|P^?mTrX6{M6TWuX(3vx?xnbrEJXva5N}m#lOKmxDaLETt-<Sz_SAb|wC zy1G3pKl=EC50`)Z@oGFPjfrdw&2UTK;XpFcIA369fOLC+}P8q + + #0b0e14 + + diff --git a/apps/lingua/android/smoke.py b/apps/lingua/android/smoke.py new file mode 100644 index 00000000..da17e0c0 --- /dev/null +++ b/apps/lingua/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the Lingua APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/Lingua-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("\nLingua 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/lingua/android/src/io/github/juw12/lingua/MainActivity.java b/apps/lingua/android/src/io/github/juw12/lingua/MainActivity.java new file mode 100644 index 00000000..0cc1c7e2 --- /dev/null +++ b/apps/lingua/android/src/io/github/juw12/lingua/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.lingua; + +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; + +/** + * Lingua 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/lingua/"; + private static final String SCOPE = "juw12.github.io/projects/lingua"; + 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() + " LinguaAndroid/" + 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("LinguaShell", "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("LinguaShell", "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(); + } + }); + } + } +} From f264444719f3786098153f109637d947e845e7cb Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:17:43 +0700 Subject: [PATCH 4/5] READMEs: what the Lingua and Sortie windows do and do not do --- apps/lingua/README.md | 10 ++++++++-- apps/sortie/README.md | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/lingua/README.md b/apps/lingua/README.md index 20d3fff7..04465785 100644 --- a/apps/lingua/README.md +++ b/apps/lingua/README.md @@ -7,11 +7,17 @@ language. > Teams talks. You read along, translated. -## On a Mac +## On a Mac and on Android - **Mac:** [`Lingua-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/lingua-mac/Lingua-macOS-AppleSilicon.dmg) (M1 and newer) or [`Lingua-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/lingua-mac/Lingua-macOS-Intel.dmg). Open it and drag Lingua to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`Lingua-android.apk`](https://github.com/juw12/projects/releases/download/lingua-android/Lingua-android.apk): open the file on the phone and allow your browser to install apps once. -It is the web edition (https://juw12.github.io/projects/lingua/) in its own window ([`desktop/`](desktop/README.md)) and changes with it. Live caption capture needs a browser that can share the screen (Chrome, Edge or Firefox on the Mac); in this window use Mobile translate and Read picture. Each build is opened on an Apple-silicon Mac and an Intel Mac on GitHub before it is published: the page loads, the app starts and can store data. No Mac of ours has run it yet. +Both are the web edition (https://juw12.github.io/projects/lingua/) in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. What they do and do not do: + +- Mobile translate and Read picture work in them. Live caption capture needs a browser that can share the screen (Chrome, Edge or Firefox on the Mac), and the floating caption window over Teams is the Windows app only. +- They call the translation gateway you set, straight from the page. A gateway on plain `http` or one only reachable from the office network (the company one) cannot be called this way: use **Share to phone** from the laptop for that, as described under [Versions](#versions-laptop-web-iphone-android). + +Each build is opened on GitHub's machines before it is published: on an Apple-silicon Mac and an Intel Mac the page loads, the app starts and can store data; on an Android emulator it installs, opens and stays up. No translation was made in them, and no Mac or phone of ours has run them yet. ## Status diff --git a/apps/sortie/README.md b/apps/sortie/README.md index 60d48425..6e095920 100644 --- a/apps/sortie/README.md +++ b/apps/sortie/README.md @@ -55,7 +55,7 @@ - **Android:** [`Sortie-android.apk`](https://github.com/juw12/projects/releases/download/sortie-android/Sortie-android.apk): open the file on the phone and allow your browser to install apps once. - **iPhone:** open https://juw12.github.io/projects/sortie/ in Safari, tap Share, then **Add to Home Screen**. -The Windows, Mac and Android apps are the web app in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. Each build is opened on GitHub's machines before it is published: on Windows and on a Mac the page loads, the app starts and can store data; on an Android emulator it installs, opens and stays up. They are not code-signed or notarised, and no real phone or PC has run them yet. +The Windows, Mac and Android apps are the web app in its own window ([`desktop/`](desktop/README.md), [`android/`](android/README.md)) and change with it. As in a browser, demo data loads by default and nothing touches your disk until you open a folder. Moving and renaming real files needs the folder access that only Chrome's and Edge's engine has: the Windows app uses Edge's engine (moving real files in it has not been tried yet); the Mac and Android apps are the demo and the read-only preview, like a phone browser. 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 From 45626dc12f187f4ec4c8563f0be31408cc324092 Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:24:24 +0700 Subject: [PATCH 5/5] Airiz Motor for Mac: the web app in its own window, built and opened on each system before it is published --- .github/workflows/airiz-motor-mac.yml | 172 +++++++ apps/airiz-motor/README.md | 6 + apps/airiz-motor/shell/desktop/.gitignore | 3 + apps/airiz-motor/shell/desktop/README.md | 25 + apps/airiz-motor/shell/desktop/airizmotor.iss | 73 +++ .../airiz-motor/shell/desktop/airizmotor.spec | 64 +++ .../shell/desktop/airizmotor_app.py | 467 ++++++++++++++++++ apps/airiz-motor/shell/desktop/build.py | 174 +++++++ apps/airiz-motor/shell/desktop/icon-512.png | Bin 0 -> 18911 bytes apps/airiz-motor/shell/desktop/offline.html | 25 + apps/airiz-motor/shell/desktop/shell.json | 3 + apps/airiz-motor/shell/desktop/smoke_test.py | 92 ++++ 12 files changed, 1104 insertions(+) create mode 100644 .github/workflows/airiz-motor-mac.yml create mode 100644 apps/airiz-motor/shell/desktop/.gitignore create mode 100644 apps/airiz-motor/shell/desktop/README.md create mode 100644 apps/airiz-motor/shell/desktop/airizmotor.iss create mode 100644 apps/airiz-motor/shell/desktop/airizmotor.spec create mode 100644 apps/airiz-motor/shell/desktop/airizmotor_app.py create mode 100644 apps/airiz-motor/shell/desktop/build.py create mode 100644 apps/airiz-motor/shell/desktop/icon-512.png create mode 100644 apps/airiz-motor/shell/desktop/offline.html create mode 100644 apps/airiz-motor/shell/desktop/shell.json create mode 100644 apps/airiz-motor/shell/desktop/smoke_test.py diff --git a/.github/workflows/airiz-motor-mac.yml b/.github/workflows/airiz-motor-mac.yml new file mode 100644 index 00000000..297cca41 --- /dev/null +++ b/.github/workflows/airiz-motor-mac.yml @@ -0,0 +1,172 @@ +name: AirizMotor apps + +# Builds the downloadable AirizMotor apps and publishes them to the "airiz-motor-mac" release from main: +# macOS AirizMotor-macOS-AppleSilicon.dmg + AirizMotor-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/airiz-motor/shell/desktop/**' + - '.github/workflows/airiz-motor-mac.yml' + pull_request: + paths: + - 'apps/airiz-motor/shell/desktop/**' + - '.github/workflows/airiz-motor-mac.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: airiz-motor-mac-${{ github.ref }} + cancel-in-progress: true + +jobs: + desktop: + name: Desktop (${{ matrix.name }}) + strategy: + fail-fast: false + matrix: + include: + - 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/airiz-motor/shell/desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's AirizMotor + run: python apps/airiz-motor/shell/desktop/smoke_test.py --built --local-site + - name: Install with AirizMotor-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'apps/airiz-motor/shell/desktop/dist/AirizMotor-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'airizmotor-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\AirizMotor\AirizMotor.exe' + if (-not (Test-Path $app)) { throw "AirizMotor.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'AirizMotor.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'AirizMotor.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 'AirizMotor' + if (-not $entry) { throw 'AirizMotor is missing from Settings > Apps' } + python apps/airiz-motor/shell/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 AirizMotor.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/airiz-motor/shell/desktop/dist/AirizMotor.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.airizmotor.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("apps/airiz-motor/shell/desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/AirizMotor")" + codesign --verify --deep --verbose=2 "$APP" + for image in apps/airiz-motor/shell/desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: AirizMotor-${{ runner.os }}-${{ runner.arch }} + path: apps/airiz-motor/shell/desktop/dist/AirizMotor-* + 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: AirizMotor-* + 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 AirizMotor-macOS-AppleSilicon.dmg AirizMotor-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' + **Airiz Motor**: console for the AIRIZ rig: remote control by code, camera and device checks. The apps open the same Airiz Motor as https://juw12.github.io/projects/airiz-motor/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Mac with Apple chip (M1 and newer)** | [AirizMotor-macOS-AppleSilicon.dmg](https://github.com/juw12/projects/releases/download/airiz-motor-mac/AirizMotor-macOS-AppleSilicon.dmg) | Open it and drag AirizMotor to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [AirizMotor-macOS-Intel.dmg](https://github.com/juw12/projects/releases/download/airiz-motor-mac/AirizMotor-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/airiz-motor/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [AirizMotor-android.apk](https://github.com/juw12/projects/releases/download/airiz-motor-android/AirizMotor-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load AirizMotor 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 airiz-motor-mac --repo "$REPO" > /dev/null 2>&1; then + gh release upload airiz-motor-mac $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit airiz-motor-mac --notes-file notes.md --repo "$REPO" + else + gh release create airiz-motor-mac $FILES SHA256SUMS.txt --title "Airiz Motor for Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/apps/airiz-motor/README.md b/apps/airiz-motor/README.md index b0929b8e..a8a82087 100644 --- a/apps/airiz-motor/README.md +++ b/apps/airiz-motor/README.md @@ -53,6 +53,12 @@

+## On a Mac + +- **Mac:** [`AirizMotor-macOS-AppleSilicon.dmg`](https://github.com/juw12/projects/releases/download/airiz-motor-mac/AirizMotor-macOS-AppleSilicon.dmg) (M1 and newer) or [`AirizMotor-macOS-Intel.dmg`](https://github.com/juw12/projects/releases/download/airiz-motor-mac/AirizMotor-macOS-Intel.dmg). Open it and drag AirizMotor to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. + +It is the web edition (https://juw12.github.io/projects/airiz-motor/) in its own window ([`desktop/`](shell/desktop/README.md)) and changes with it. It cannot reach the AIRIZ over USB itself (the Mac's WebKit has no Web Serial or WebUSB): use it with Remote by code or the demo device, or open the page in Chrome on the Mac for a direct connection. Each build is opened on an Apple-silicon Mac and an Intel Mac on GitHub before it is published: the page loads, the app starts and can store data. No Mac of ours has run it yet. + ## About Owner: **Juwen Lie** · Team: **Ziris PTB** (co-admins and testers) diff --git a/apps/airiz-motor/shell/desktop/.gitignore b/apps/airiz-motor/shell/desktop/.gitignore new file mode 100644 index 00000000..398ca165 --- /dev/null +++ b/apps/airiz-motor/shell/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/apps/airiz-motor/shell/desktop/README.md b/apps/airiz-motor/shell/desktop/README.md new file mode 100644 index 00000000..d386639b --- /dev/null +++ b/apps/airiz-motor/shell/desktop/README.md @@ -0,0 +1,25 @@ +# AirizMotor for Windows and Mac + +A small native window around the live site (https://juw12.github.io/projects/airiz-motor/): 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 AirizMotor 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 | +| --- | --- | +| `airizmotor_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 | +| `airizmotor.spec`, `airizmotor.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 AirizMotor | +| `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/airiz-motor-mac.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 +[airiz-motor-mac release](https://github.com/juw12/projects/releases/tag/airiz-motor-mac). The download links never change. diff --git a/apps/airiz-motor/shell/desktop/airizmotor.iss b/apps/airiz-motor/shell/desktop/airizmotor.iss new file mode 100644 index 00000000..5a6a70b2 --- /dev/null +++ b/apps/airiz-motor/shell/desktop/airizmotor.iss @@ -0,0 +1,73 @@ +; AirizMotor for Windows - per-user installer (no admin rights). build.py compiles it with: +; iscc /DAppVersion=1.0.0 /DSourceDir= /DOutputDir= /DIconFile= airizmotor.iss +; Installs to %LOCALAPPDATA%\Programs\AirizMotor, adds AirizMotor 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%\AirizMotor, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\AirizMotor" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\airizmotor.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=AirizMotor +AppVersion={#AppVersion} +AppVerName=AirizMotor {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/projects/airiz-motor/ +AppSupportURL=https://github.com/juw12/projects +DefaultDirName={autopf}\AirizMotor +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=AirizMotor-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\AirizMotor.exe +UninstallDisplayName=AirizMotor +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}\AirizMotor"; Filename: "{app}\AirizMotor.exe"; Comment: "Console for the AIRIZ rig: remote control by code, camera and device checks" +Name: "{userdesktop}\AirizMotor"; Filename: "{app}\AirizMotor.exe"; Comment: "Console for the AIRIZ rig: remote control by code, camera and device checks"; Tasks: desktopicon + +[Run] +Filename: "{app}\AirizMotor.exe"; Description: "{cm:LaunchProgram,AirizMotor}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\AirizMotor.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopAirizMotor" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open AirizMotor window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\AirizMotor.exe')) then + Exec(ExpandConstant('{app}\AirizMotor.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/apps/airiz-motor/shell/desktop/airizmotor.spec b/apps/airiz-motor/shell/desktop/airizmotor.spec new file mode 100644 index 00000000..6f6062f5 --- /dev/null +++ b/apps/airiz-motor/shell/desktop/airizmotor.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for AirizMotor on Windows and macOS. Build with python desktop/build.py +# Windows dist/AirizMotor/AirizMotor.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/AirizMotor.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("AIRIZMOTOR_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("AIRIZMOTOR_VERSION_FILE") or None +ICON = os.environ.get("AIRIZMOTOR_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, "airizmotor_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="AirizMotor", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="AirizMotor", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="AirizMotor.app", + icon=ICON, + bundle_identifier="io.github.juw12.airizmotor.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "AirizMotor", + "CFBundleDisplayName": "AirizMotor", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/projects", + }, + ) diff --git a/apps/airiz-motor/shell/desktop/airizmotor_app.py b/apps/airiz-motor/shell/desktop/airizmotor_app.py new file mode 100644 index 00000000..f3f951ac --- /dev/null +++ b/apps/airiz-motor/shell/desktop/airizmotor_app.py @@ -0,0 +1,467 @@ +"""AirizMotor for Windows and macOS: the AirizMotor 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/airiz-motor/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time AirizMotor 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 +AirizMotor opens in the default browser instead. + +Opening AirizMotor while its window is open brings that window to the front; `AirizMotor --stop` closes it. + +Automated checks: AIRIZMOTOR_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; AIRIZMOTOR_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 = "Airiz Motor" +APP_URL = os.environ.get("AIRIZMOTOR_DESKTOP_URL") or "https://juw12.github.io/projects/airiz-motor/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#0d1117" +DARK_BACKGROUND = "#0d1117" +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('airizmotor.desktop.check', '1');" + " return localStorage.getItem('airizmotor.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("[airizmotor] " + 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"), "AirizMotor") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "AirizMotor") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "airizmotor") + + +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 AirizMotor site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "AirizMotorDesktop/" + 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="airizmotor-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 AirizMotor 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 AirizMotor 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 AirizMotor 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="airizmotor-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("AirizMotor %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("AIRIZMOTOR_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/airiz-motor/shell/desktop/build.py b/apps/airiz-motor/shell/desktop/build.py new file mode 100644 index 00000000..82a29b20 --- /dev/null +++ b/apps/airiz-motor/shell/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the AirizMotor 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 AirizMotor-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + AirizMotor-Windows-Portable.zip unzip and run AirizMotor.exe + macOS AirizMotor-macOS-AppleSilicon.dmg or AirizMotor-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', 'AirizMotor - Console for the AIRIZ rig: remote control by code, camera and device checks'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'AirizMotor'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/projects'), + StringStruct('OriginalFilename', 'AirizMotor.exe'), + StringStruct('ProductName', 'AirizMotor'), + 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, "airizmotor.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, AIRIZMOTOR_VERSION=version, AIRIZMOTOR_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["AIRIZMOTOR_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "airizmotor.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, "AirizMotor") + portable = os.path.join(DIST, "AirizMotor-Windows-Portable.zip") + zip_folder(folder, portable, "AirizMotor") + 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 AirizMotor-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped AirizMotor-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, "airizmotor.iss")], + check=True, + ) + return [os.path.join(DIST, "AirizMotor-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "AirizMotor.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "AirizMotor-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, "AirizMotor.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "AirizMotor", "-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 AirizMotor 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("AirizMotor desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by airizmotor.spec) + except ImportError: + raise SystemExit("The AirizMotor window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("AirizMotor", "AirizMotor.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building AirizMotor %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/airiz-motor/shell/desktop/icon-512.png b/apps/airiz-motor/shell/desktop/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..9215c16d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FJz-Rk`(YnoH7aiG20*9c4Fxxnhf(+yH2 zWAo$t_kO$>cp{f-rv-lc;qxI{kT=^kqx6f%XkyvO!MTE|(6NH4tu5o!7kDKWbaobx z4)DWG5<@f}o<@^G*GD9`YYv<2%P*$@^xNXV+|aNtObGx0d|}8xw;;2lzjgk8IRYT2 z1ONcu@A$KA>G%FL0l|AI|@11`@ zi~#(cbJCCtE!%oo#x$py0s!1t=D*QpTzBP$48#VpQK>nB}C~hXx0sw#@9_|m`1VBs+004q_xSs^z zw9v^z+l9EypJmLIMsm>n0U#)s^p(iAKPtBDr;0|+SRHJi-vsl`cTT*lo>9r4B;9O` ziQ?A*0D|J+o*WsyY1@ux^T&L$J6PjjXbO@h4vKS{kUv<`U6M&8AOH}MkNihmmR` z*nPU6%qisaT(!AW9u3jbs!)B;1iGf-`TP!=7knb4yI*% zBmiC#{{D!j4wq|;Ei=YQjfe;URO-|I4kOpZ5{Kixf{|0V5)l#ruLyg8M6(c=tFJBf zH8Q;=#S;|(aI2%X?8U}tQL*h>R5*I(20}st;By6pVH1b7bQtxOF@25HOHwrg0{|81 z@JG$uNFg5yfM0QbIJmA=6xvS4)!vrcNv4&N>Ju3N_{CDaG-GR%R{fa zhXf!{eRyR=SYcsfhh>`CvQv$%W=1B}HcBy41OWmNpq+f4k+#~ly~$W+vn_jbiEVEx zj4j&2`g{@qQCv8@k!)A0Wm~DT?RZJiMkdNOcC@iglr1~T$VA(+qhu6qY!fA;SRx0Y zl6&(E+t@j>m2G5lY-8sb+hqUvr|cX_*)ry+ahWY8A@-(%k<-!$obUL5t78>S3F|_0 P00000NkvXXu0mjfhT + + + + + AirizMotor + + + + + + diff --git a/apps/airiz-motor/shell/desktop/shell.json b/apps/airiz-motor/shell/desktop/shell.json new file mode 100644 index 00000000..1587a669 --- /dev/null +++ b/apps/airiz-motor/shell/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/apps/airiz-motor/shell/desktop/smoke_test.py b/apps/airiz-motor/shell/desktop/smoke_test.py new file mode 100644 index 00000000..7c4b3f5d --- /dev/null +++ b/apps/airiz-motor/shell/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built AirizMotor desktop app and check its window really shows AirizMotor. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/AirizMotor.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with AIRIZMOTOR_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is AirizMotor, 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, os.pardir, "apps", "airiz-motor", "web")) # the folder GitHub Pages serves +LIVE_URL = "https://juw12.github.io/projects/airiz-motor/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "AirizMotor", "AirizMotor.exe") + return os.path.join(DESKTOP, "dist", "AirizMotor.app", "Contents", "MacOS", "AirizMotor") + + +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 AirizMotor 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="airizmotor-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, AIRIZMOTOR_WINDOW_TEST=report, AIRIZMOTOR_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 "AIRIZ" 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("AirizMotor 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: AirizMotor %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main()
+ +

AirizMotor can't reach the internet

+

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

+
Try again +