From cb2c360c8de7351fb71d12cffc153d608bd7c66d Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:40:06 +0700 Subject: [PATCH] Morrow for Windows, Mac and Android: the web app in its own window, built and opened on each system before it is published --- .github/workflows/android.yml | 137 ++++++ .github/workflows/desktop.yml | 177 +++++++ README.md | 9 + android/.gitignore | 2 + android/AndroidManifest.xml | 23 + android/README.md | 34 ++ android/app.json | 10 + android/assets/offline.html | 25 + android/build.py | 98 ++++ android/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 11257 bytes android/res/values/styles.xml | 11 + android/smoke.py | 121 +++++ .../io/github/juw12/morrow/MainActivity.java | 283 ++++++++++++ desktop/.gitignore | 3 + desktop/README.md | 25 + desktop/build.py | 174 +++++++ desktop/icon-512.png | Bin 0 -> 32002 bytes desktop/morrow.iss | 73 +++ desktop/morrow.spec | 64 +++ desktop/morrow_app.py | 434 ++++++++++++++++++ desktop/offline.html | 25 + desktop/shell.json | 3 + desktop/smoke_test.py | 92 ++++ 23 files changed, 1823 insertions(+) create mode 100644 .github/workflows/android.yml create mode 100644 .github/workflows/desktop.yml create mode 100644 android/.gitignore create mode 100644 android/AndroidManifest.xml create mode 100644 android/README.md create mode 100644 android/app.json create mode 100644 android/assets/offline.html create mode 100644 android/build.py create mode 100644 android/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 android/res/values/styles.xml create mode 100644 android/smoke.py create mode 100644 android/src/io/github/juw12/morrow/MainActivity.java create mode 100644 desktop/.gitignore create mode 100644 desktop/README.md create mode 100644 desktop/build.py create mode 100644 desktop/icon-512.png create mode 100644 desktop/morrow.iss create mode 100644 desktop/morrow.spec create mode 100644 desktop/morrow_app.py create mode 100644 desktop/offline.html create mode 100644 desktop/shell.json create mode 100644 desktop/smoke_test.py diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 0000000..71ad259 --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,137 @@ +name: Morrow Android app + +# Builds Morrow-android.apk (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 android release. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "android/**" + - ".github/workflows/android.yml" + pull_request: + paths: + - "android/**" + - ".github/workflows/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 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 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('android/app.json'))['certSha256'])") + found=$("$APKSIGNER" verify --print-certs android/dist/Morrow-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p') + echo "expected $expected" + echo "found $found" + [ "$expected" = "$found" ] + (cd android/dist && sha256sum Morrow-android.apk > Morrow-android.apk.sha256 && cat Morrow-android.apk.sha256) + + - uses: actions/upload-artifact@v4 + with: + name: morrow-android + path: 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: morrow-android + path: 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 android/smoke.py android/dist/Morrow-android.apk + - uses: actions/upload-artifact@v4 + if: always() + with: + name: morrow-android-emulator-check + path: | + android/dist/*.png + 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: morrow-android + path: dist + # The android release keeps one address for the download. The file there is replaced only when + # android/app.json names a new versionName, never by a rebuild of the same version. + - name: Put the .apk on the android release + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(python3 -c "import json; print(json.load(open('android/app.json'))['versionName'])") + echo "$version" > dist/Morrow-android.version.txt + if ! gh release view android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + printf '%s\n' "Morrow for Android: a full-screen window around the web app (https://juw12.github.io/morrow/)." "" \ + "Download [Morrow-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/android/Morrow-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 android dist/Morrow-android.apk dist/Morrow-android.apk.sha256 dist/Morrow-android.version.txt \ + --title "Morrow for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY" + echo "Made the android release with Morrow-android.apk $version" + exit 0 + fi + published=$(gh release download android --repo "$GITHUB_REPOSITORY" --pattern Morrow-android.version.txt --output - 2>/dev/null || true) + if [ "$published" = "$version" ]; then + echo "the android release already has Morrow-android.apk $version" + exit 0 + fi + gh release upload android dist/Morrow-android.apk dist/Morrow-android.apk.sha256 dist/Morrow-android.version.txt --clobber --repo "$GITHUB_REPOSITORY" + echo "Morrow-android.apk on the android release is now $version (was: ${published:-none})" diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml new file mode 100644 index 0000000..2b12f3c --- /dev/null +++ b/.github/workflows/desktop.yml @@ -0,0 +1,177 @@ +name: Morrow apps + +# Builds the downloadable Morrow apps and publishes them to the "desktop" release from main: +# Windows Morrow-Windows-Setup.exe (per-user installer) + Morrow-Windows-Portable.zip +# macOS Morrow-macOS-AppleSilicon.dmg + Morrow-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: + - 'desktop/**' + - '.github/workflows/desktop.yml' + pull_request: + paths: + - 'desktop/**' + - '.github/workflows/desktop.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: 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 desktop/build.py --require-installer + - name: Open the built app and check its window shows this commit's Morrow + run: python desktop/smoke_test.py --built --local-site + - name: Install with Morrow-Windows-Setup.exe, run it, uninstall it + if: runner.os == 'Windows' + shell: pwsh + run: | + $setup = Resolve-Path 'desktop/dist/Morrow-Windows-Setup.exe' + $log = Join-Path $env:RUNNER_TEMP 'morrow-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\Morrow\Morrow.exe' + if (-not (Test-Path $app)) { throw "Morrow.exe was not installed to $app" } + $shortcuts = @( + (Join-Path ([Environment]::GetFolderPath('Programs')) 'Morrow.lnk'), + (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Morrow.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 'Morrow' + if (-not $entry) { throw 'Morrow is missing from Settings > Apps' } + python 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 Morrow.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=desktop/dist/Morrow.app + test "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist")" = "io.github.juw12.morrow.desktop" + test "$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist")" = "$(python3 -c 'import json; print(json.load(open("desktop/shell.json"))["version"])')" + echo "Architecture: $(lipo -archs "$APP/Contents/MacOS/Morrow")" + codesign --verify --deep --verbose=2 "$APP" + for image in desktop/dist/*.dmg; do hdiutil verify "$image"; done + - uses: actions/upload-artifact@v4 + with: + name: Morrow-${{ runner.os }}-${{ runner.arch }} + path: desktop/dist/Morrow-* + 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: Morrow-* + 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 Morrow-Windows-Setup.exe Morrow-Windows-Portable.zip \ + Morrow-macOS-AppleSilicon.dmg Morrow-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' + **Morrow**: your morning news, curated: merged stories. The apps open the same Morrow as https://juw12.github.io/morrow/ in their own window. + + | Your device | Download | How to install | + | --- | --- | --- | + | **Windows 10/11** | [Morrow-Windows-Setup.exe](https://github.com/juw12/morrow/releases/download/desktop/Morrow-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: [Morrow-Windows-Portable.zip](https://github.com/juw12/morrow/releases/download/desktop/Morrow-Windows-Portable.zip). | + | **Mac with Apple chip (M1 and newer)** | [Morrow-macOS-AppleSilicon.dmg](https://github.com/juw12/morrow/releases/download/desktop/Morrow-macOS-AppleSilicon.dmg) | Open it and drag Morrow to Applications. The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. | + | **Mac with Intel chip** | [Morrow-macOS-Intel.dmg](https://github.com/juw12/morrow/releases/download/desktop/Morrow-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/morrow/) | Share → **Add to Home Screen** (free, full screen, updates itself). | + | **Android** | [Morrow-android.apk](https://github.com/juw12/morrow/releases/download/android/Morrow-android.apk) | Open the file on the phone and allow your browser to install apps once. | + + The apps load Morrow 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 desktop --repo "$REPO" > /dev/null 2>&1; then + gh release upload desktop $FILES SHA256SUMS.txt --clobber --repo "$REPO" + gh release edit desktop --notes-file notes.md --repo "$REPO" + else + gh release create desktop $FILES SHA256SUMS.txt --title "Morrow for Windows and Mac" \ + --notes-file notes.md --latest=false --repo "$REPO" + fi diff --git a/README.md b/README.md index 67483fa..9ad77ae 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,15 @@ A morning newspaper for markets, AI and chips, robotics, space and tech. Hundreds of headlines become one edition: coverage from several outlets is merged, there's an AI brief at the top and a "why it matters" line on every story. A stock desk sits alongside with valuation scores for big US tech and Indonesian blue chips. +## Get it on your device + +- **Windows:** [`Morrow-Windows-Setup.exe`](https://github.com/juw12/morrow/releases/download/desktop/Morrow-Windows-Setup.exe) (no admin needed; if Windows says it protected your PC, choose *More info → Run anyway*), or without installing [`Morrow-Windows-Portable.zip`](https://github.com/juw12/morrow/releases/download/desktop/Morrow-Windows-Portable.zip). +- **Mac:** [`Morrow-macOS-AppleSilicon.dmg`](https://github.com/juw12/morrow/releases/download/desktop/Morrow-macOS-AppleSilicon.dmg) (M1 and newer) or [`Morrow-macOS-Intel.dmg`](https://github.com/juw12/morrow/releases/download/desktop/Morrow-macOS-Intel.dmg). The first time, macOS blocks it because it is not notarized: **System Settings → Privacy & Security → Open Anyway**. +- **Android:** [`Morrow-android.apk`](https://github.com/juw12/morrow/releases/download/android/Morrow-android.apk): open the file on the phone and allow your browser to install apps once. +- **iPhone:** open https://juw12.github.io/morrow/ 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. + ## What you get - **Curated news**: refreshed through the day, with stories you already saw in earlier editions skipped. diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..edd9d60 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml new file mode 100644 index 0000000..654f76d --- /dev/null +++ b/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/android/README.md b/android/README.md new file mode 100644 index 0000000..7b7bca7 --- /dev/null +++ b/android/README.md @@ -0,0 +1,34 @@ +# Morrow for Android + +One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/morrow/): the same Morrow 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: [`Morrow-android.apk`](https://github.com/juw12/morrow/releases/download/android/Morrow-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 android/build.py --keystore release.p12 --password-file release-password.txt --alias shells +``` + +`.github/workflows/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 +`Morrow-android.apk` on the `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/android/app.json b/android/app.json new file mode 100644 index 0000000..7f90def --- /dev/null +++ b/android/app.json @@ -0,0 +1,10 @@ +{ + "name": "Morrow", + "id": "io.github.juw12.morrow", + "url": "https://juw12.github.io/morrow/", + "versionName": "1.0.0", + "versionCode": 1, + "minSdk": 24, + "targetSdk": 34, + "certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36" +} diff --git a/android/assets/offline.html b/android/assets/offline.html new file mode 100644 index 0000000..64c8494 --- /dev/null +++ b/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + Morrow + + + +
+ +

Morrow can't reach the internet

+

Morrow 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/android/build.py b/android/build.py new file mode 100644 index 0000000..ae5e3b1 --- /dev/null +++ b/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/android/res/mipmap-xxxhdpi/ic_launcher.png b/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..8a50a0b3fd3c3663d152e89876bf13aa9d878722 GIT binary patch literal 11257 zcmYLPWmKF!u-?Tf?hcDqaVE};9 zP)bx-*#&r}4X>xHGB0=`D@9A5h>i&gApGVR;s@0tsmWMrC5DZ3tfA_B=3^jSQ)Qt^ zWYJUqx#=wgVOk{(N(zCx0Q?P6N)qI_?0zA1P?*BTZnHm@K15|-6_o0FF@KR|f6;u9 z<<1Q6h1v0)1dCu~0`HmETq!vr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}Y5?>Z zX)Qr6EXm!`Cn(Vrs&mkq8c)=7RTdVm+_;T*##Ew5!uCfnuJK7bp7Yux1LYi(stG}E zHyE7~VKgBRmh{dH9++@p+%3VrFHQo#L5|dRRB65OqXCudzpz1CTY#Gp$!0qx5^8Gi zfhn=!a|l6-&#a%ko_8E-jagmtUI4{QyVmZ5TrtUN`^w7TN1{Z7u!ccEK*MHUR@@gt z(^8xsz#sFyLj&>?R9r#F#;Q;X`zF{g`umaP&gfO zj0-nb@n0qwOS*AXDf~uNb{CTPnhmcoFuVTTCY?8SCmGnznTxi&N?gaeL~)j^x#h5N e=1u + + #f7f6f2 + + diff --git a/android/smoke.py b/android/smoke.py new file mode 100644 index 0000000..6cf5a0a --- /dev/null +++ b/android/smoke.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Install the Morrow APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/Morrow-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): + result = subprocess.run(["adb", *args], capture_output=True, text=True, timeout=180) + 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("\nMorrow 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/android/src/io/github/juw12/morrow/MainActivity.java b/android/src/io/github/juw12/morrow/MainActivity.java new file mode 100644 index 0000000..93c5b26 --- /dev/null +++ b/android/src/io/github/juw12/morrow/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.morrow; + +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; + +/** + * Morrow 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/morrow/"; + private static final String SCOPE = "juw12.github.io/morrow"; + 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() + " MorrowAndroid/" + 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("MorrowShell", "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("MorrowShell", "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/desktop/.gitignore b/desktop/.gitignore new file mode 100644 index 0000000..398ca16 --- /dev/null +++ b/desktop/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +__pycache__/ diff --git a/desktop/README.md b/desktop/README.md new file mode 100644 index 0000000..6d92904 --- /dev/null +++ b/desktop/README.md @@ -0,0 +1,25 @@ +# Morrow for Windows and Mac + +A small native window around the live site (https://juw12.github.io/morrow/): 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 Morrow 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 | +| --- | --- | +| `morrow_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 | +| `morrow.spec`, `morrow.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 Morrow | +| `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/apps.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 +[apps release](https://github.com/juw12/morrow/releases/tag/apps). The download links never change. diff --git a/desktop/build.py b/desktop/build.py new file mode 100644 index 0000000..bbbb3a4 --- /dev/null +++ b/desktop/build.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Build the Morrow 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 Morrow-Windows-Setup.exe per-user installer, no admin rights (needs Inno Setup 6) + Morrow-Windows-Portable.zip unzip and run Morrow.exe + macOS Morrow-macOS-AppleSilicon.dmg or Morrow-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', 'Morrow - Your morning news, curated: merged stories'), + StringStruct('FileVersion', '{version}'), + StringStruct('InternalName', 'Morrow'), + StringStruct('LegalCopyright', 'Open source - github.com/juw12/morrow'), + StringStruct('OriginalFilename', 'Morrow.exe'), + StringStruct('ProductName', 'Morrow'), + 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, "morrow.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, MORROW_VERSION=version, MORROW_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["MORROW_VERSION_FILE"] = version_file + subprocess.run( + [ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", + "--distpath", DIST, + "--workpath", os.path.join(BUILD, "pyinstaller"), + os.path.join(DESKTOP, "morrow.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, "Morrow") + portable = os.path.join(DIST, "Morrow-Windows-Portable.zip") + zip_folder(folder, portable, "Morrow") + 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 Morrow-Windows-Setup.exe") + print("Inno Setup 6 not found: skipped Morrow-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, "morrow.iss")], + check=True, + ) + return [os.path.join(DIST, "Morrow-Windows-Setup.exe")] + made + + +def package_macos(): + app = os.path.join(DIST, "Morrow.app") + chip = "AppleSilicon" if platform.machine() == "arm64" else "Intel" + image = os.path.join(DIST, "Morrow-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, "Morrow.app")], check=True) # keeps links and signature + os.symlink("/Applications", os.path.join(stage, "Applications")) + command = ["hdiutil", "create", "-volname", "Morrow", "-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 Morrow 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("Morrow desktop builds are made on Windows and macOS") + try: + import webview # noqa: F401 (bundled by morrow.spec) + except ImportError: + raise SystemExit("The Morrow window needs pywebview: python -m pip install pywebview") + + version = read_version() + os.makedirs(BUILD, exist_ok=True) + for leftover in ("Morrow", "Morrow.app"): + shutil.rmtree(os.path.join(DIST, leftover), ignore_errors=True) + print("Building Morrow %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/desktop/icon-512.png b/desktop/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..60de03b2cb8f692c74be2854a85dc590c54a3f49 GIT binary patch literal 32002 zcmYhibzGF)6F0n+v~(&ZNFyR8ogyhIDJ)8hfONAo(g@NiDbn36(g-Wv-5}k$yU(@W zzxREfzx3mtYtHn1XU-U|@#Zxl9xWaS1R_*Yl-B}*(1E|AgK!=If1GSgtlaE9q?*6FNxhB7qDHA(Skvyw@-%;ul9`bj zeF_g}O=IPwZ5eG1#M9*#*u`PD!2gua!|y!oDK*^0KRD)|oVw_3<+p5ZTo23eJ{p2c zY!?Sg8;;0-p!~|6Df;$!x^F0Ty>WRdHMuWpm%_FRdrOJ0(m<s`zly-fWqMNVPXbJ);KK0qg zV>twu&S)K9Er{vAJ6lxIDA6j@(r9Bfe3jo2tmv1+QWhiT<@jE|RP^I&XPKDfVS+rR zLt!B-H9_EkDRDlC8g$n|@I)kub4VoPO-()7JrS$g?~?M^mva<1DVE=-Kk->#^^}qE+E=X$IxQQ3Kr6;`N7~nZN!LZs(^(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;?&5s?R<}3mgT)f+llaJ@ ziu1J5Y;DjnH`wN0Q%DS$O_@h#K^_zVeA(jHQA}lW;{1?UI#aCu@w}Ff zGplI`KW<3q{U9B&mm#NEd@$Q?~b4X1AOp4Pv9}m!eG~4MCo} zJ3rlP9pVJCg^lrPOThJ#aFCXLXRzm`f2W~(7S3|sTTyNx?mUk>jBj55K1BYe1e;!=NhkRDn zKvY(-K5&ay_q;?le#Ur+oBaCA>2rM^1IqspbGNjbCvdRyl@c{ zyBAMbHdrL}hn2sW+sT^&3pRvC4zkyXuJXzgs{;Q1XG?iZMRu<@(J3h6=3+GaS#N6K z%_I;uVI)lX^GAY^y`j%?8Bj2CclF|19ho(+>ZBWgNrED29e16;*RDqPs7ILV099!} zjm&Prp-LLtjaN$hK;NY-GPK~3yD%UT*G|C89*&Q{v}13l{nHpf zT~%(Bo1!AS#%*P5{t))v9rBIt17W4TDaZqq#I1?0{_Dv6?7ewA_39hN9j#B>E*HzbHijZs~HuodZ_O>rvP?29*AX9=|}VI>?zHr3Q4{}OEZ@Y29MtMu!3@uF_%!F zv}}v5lJMoshPmXrub?BT0=u<()+6$HxHwrRl@QHpFkDaJq@zH|_wV_!+r)^T${3;{ zk0;tDoGLHPUgIj>N9PH&rExu>TJOR1wXhcVyixYWG(Ia1C}i3eVmj^gu=zO54erVM zkwsv5O^nsscn!A9#HYOXf2ro&?g^)~)SArp0AaCw+)6ZAaEQ_YhU|Uc+s}QWA@TZ? zKsEmpok#Rj%63n`Y;$}XNdDfLkjxsyJHrVX6DFArG%MgOude /DOutputDir= /DIconFile= morrow.iss +; Installs to %LOCALAPPDATA%\Programs\Morrow, adds Morrow 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%\Morrow, which +; uninstalling leaves in place so a reinstall finds it again. + +#ifndef AppVersion + #define AppVersion "1.0.0" +#endif +#ifndef SourceDir + #define SourceDir "dist\Morrow" +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef IconFile + #define IconFile "build\morrow.ico" +#endif + +[Setup] +AppId={{E81247BA-698B-569E-A6DE-E1E1C366EEFB} +AppName=Morrow +AppVersion={#AppVersion} +AppVerName=Morrow {#AppVersion} +AppPublisher=Juwen Lie +AppPublisherURL=https://juw12.github.io/morrow/ +AppSupportURL=https://github.com/juw12/morrow +DefaultDirName={autopf}\Morrow +DisableDirPage=yes +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputDir={#OutputDir} +OutputBaseFilename=Morrow-Windows-Setup +SetupIconFile={#IconFile} +UninstallDisplayIcon={app}\Morrow.exe +UninstallDisplayName=Morrow +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}\Morrow"; Filename: "{app}\Morrow.exe"; Comment: "Your morning news, curated: merged stories" +Name: "{userdesktop}\Morrow"; Filename: "{app}\Morrow.exe"; Comment: "Your morning news, curated: merged stories"; Tasks: desktopicon + +[Run] +Filename: "{app}\Morrow.exe"; Description: "{cm:LaunchProgram,Morrow}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: "{app}\Morrow.exe"; Parameters: "--stop"; Flags: runhidden waituntilterminated; RunOnceId: "StopMorrow" + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Result := ''; + { Updating: close an open Morrow window first so its files can be replaced. } + if FileExists(ExpandConstant('{app}\Morrow.exe')) then + Exec(ExpandConstant('{app}\Morrow.exe'), '--stop', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/desktop/morrow.spec b/desktop/morrow.spec new file mode 100644 index 0000000..505a91f --- /dev/null +++ b/desktop/morrow.spec @@ -0,0 +1,64 @@ +# -*- mode: python ; coding: utf-8 -*- +# PyInstaller recipe for Morrow on Windows and macOS. Build with python desktop/build.py +# Windows dist/Morrow/Morrow.exe (+ _internal/) - no console; its window uses Edge WebView2 (pywebview) +# macOS dist/Morrow.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("MORROW_VERSION", "1.0.0") +VERSION_FILE = os.environ.get("MORROW_VERSION_FILE") or None +ICON = os.environ.get("MORROW_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, "morrow_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="Morrow", + console=False, + icon=ICON, + version=VERSION_FILE if IS_WIN else None, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="Morrow", upx=False) # noqa: F821 + +if sys.platform == "darwin": + app = BUNDLE( # noqa: F821 + coll, + name="Morrow.app", + icon=ICON, + bundle_identifier="io.github.juw12.morrow.desktop", + version=VERSION, + info_plist={ + "CFBundleName": "Morrow", + "CFBundleDisplayName": "Morrow", + "CFBundleShortVersionString": VERSION, + "CFBundleVersion": VERSION, + "NSHighResolutionCapable": True, + "NSRequiresAquaSystemAppearance": False, + "LSApplicationCategoryType": "public.app-category.lifestyle", + "NSHumanReadableCopyright": "Open source - github.com/juw12/morrow", + }, + ) diff --git a/desktop/morrow_app.py b/desktop/morrow_app.py new file mode 100644 index 0000000..e1f07bf --- /dev/null +++ b/desktop/morrow_app.py @@ -0,0 +1,434 @@ +"""Morrow for Windows and macOS: the Morrow 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/morrow/ and keeps its browser data (what you saved in it) in a per-user +folder, so everything is still there the next time Morrow 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 +Morrow opens in the default browser instead. + +Opening Morrow while its window is open brings that window to the front; `Morrow --stop` closes it. + +Automated checks: MORROW_WINDOW_TEST= makes the window write a report once the page has +loaded and then close itself; MORROW_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 = "Morrow" +APP_URL = os.environ.get("MORROW_DESKTOP_URL") or "https://juw12.github.io/morrow/" +DEFAULT_SIZE = (1280, 860) +MIN_SIZE = (420, 560) +LIGHT_BACKGROUND = "#f7f6f2" +DARK_BACKGROUND = "#f7f6f2" +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('morrow.desktop.check', '1');" + " return localStorage.getItem('morrow.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("[morrow] " + 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"), "Morrow") + if sys.platform == "darwin": + return os.path.join(home, "Library", "Application Support", "Morrow") + return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"), "morrow") + + +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 Morrow site answers (the window then loads it; otherwise the offline page).""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "MorrowDesktop/" + 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="morrow-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 Morrow 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 Morrow 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(window.evaluate_js(PAGE_SCRIPT) or "{}") + except Exception as error: + page = {"error": str(error)} + # Wait until a fully loaded Morrow 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="morrow-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 main(argv=None): + args = list(sys.argv[1:] if argv is None else argv) + folder = data_dir() + if "--version" in args: + print("Morrow %s" % VERSION) + return 0 + if "--stop" in args: + send_to_window(folder, "quit") + return 0 + report_path = os.environ.get("MORROW_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/desktop/offline.html b/desktop/offline.html new file mode 100644 index 0000000..c4bbc01 --- /dev/null +++ b/desktop/offline.html @@ -0,0 +1,25 @@ + + + + + + Morrow + + + +

+ +

Morrow can't reach the internet

+

Morrow 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/desktop/shell.json b/desktop/shell.json new file mode 100644 index 0000000..1587a66 --- /dev/null +++ b/desktop/shell.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} diff --git a/desktop/smoke_test.py b/desktop/smoke_test.py new file mode 100644 index 0000000..f861619 --- /dev/null +++ b/desktop/smoke_test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Open the built Morrow desktop app and check its window really shows Morrow. + + python desktop/smoke_test.py --built the app in desktop/dist/ (after build.py) + python desktop/smoke_test.py PATH/TO/Morrow.exe an installed copy + add --local-site to serve this checkout instead of the live site + +The app runs with MORROW_WINDOW_TEST set, so it writes a report once the page has loaded and closes +itself. Passes when the page is Morrow, 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.dirname(DESKTOP) +LIVE_URL = "https://juw12.github.io/morrow/" + + +def built_app(): + if sys.platform == "win32": + return os.path.join(DESKTOP, "dist", "Morrow", "Morrow.exe") + return os.path.join(DESKTOP, "dist", "Morrow.app", "Contents", "MacOS", "Morrow") + + +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 Morrow 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="morrow-smoke-") + report = os.path.join(folder, "report.json") + env = dict(os.environ, MORROW_WINDOW_TEST=report, MORROW_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 "Morrow" 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("Morrow 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: Morrow %s opened in its own window (%s) in %.0f s" % (version, result.get("toolkit"), time.time() - started)) + + +if __name__ == "__main__": + main()