diff --git a/.gitea/workflows/launcher.yml b/.gitea/workflows/launcher.yml index 188cf15..dc69564 100644 --- a/.gitea/workflows/launcher.yml +++ b/.gitea/workflows/launcher.yml @@ -1,26 +1,66 @@ name: Launcher +# The MoonBit launcher at the repo root: tests (moon test, a browser e2e of the page), then +# on every push to main an APK (android/build.sh) published as a Gitea release, which the +# installed app updates itself from. The previous implementations live in legacy/ and have +# their own manual workflow (legacy.yml). on: push: branches: [main] + pull_request: + workflow_dispatch: jobs: - apk: + test: runs-on: ubuntu-latest - timeout-minutes: 60 - container: eclipse-temurin:17-jdk-noble + # Node comes from the image, not actions/setup-node: its download stalls on this + # runner and holds the cluster's only runner slot (see identicons-web's workflow). + container: + image: node:22-bookworm + timeout-minutes: 20 steps: - - name: Checkout - env: - GITHUB_TOKEN: ${{ github.token }} + - uses: actions/checkout@v4 + + - name: Install MoonBit run: | - apt-get update -qq - apt-get install -y -qq --no-install-recommends git ca-certificates >/dev/null - git init -q - git -c http.extraHeader="Authorization: Basic $(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0)" \ - fetch -q --depth 1 "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" "${GITHUB_SHA}" - git checkout -q --detach FETCH_HEAD - - name: Test, build and release the Qt APK + curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash + echo "$HOME/.moon/bin" >> "$GITHUB_PATH" + + - name: Check and test + run: | + moon update + moon check --target js + moon test --target js + moon test --target wasm-gc + + - name: Build the page and run the browser test + run: | + scripts/build-web.sh --demo + mkdir -p /tmp/e2e && cd /tmp/e2e && npm init -y >/dev/null + # Playwright's own Chromium download (cdn.playwright.dev) times out on this runner, + # so use Debian's chromium and point the tests at it. + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm i --no-audit --no-fund playwright@1.65.1 + apt-get update -qq && apt-get install -y -qq --no-install-recommends chromium >/dev/null + cd "$GITHUB_WORKSPACE" + export CHROMIUM_PATH=/usr/bin/chromium + export PLAYWRIGHT=/tmp/e2e/node_modules/playwright + node tests/e2e.cjs + node tests/android-sim.cjs + + apk: + needs: test + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + # JDK 17 + Android SDK (platforms;android-35, build-tools 35.0.0, NDK) prebuilt by + # charts/android-sdk in nandi/cluster, so no per-run SDK download. Fallback until that image + # is built and pullable: use `node:22-bookworm` here; ci/gitea-apk.sh then installs the JDK + # and downloads the SDK pieces itself. + container: + image: git.site.latha.org/cluster-services/android-sdk:latest + timeout-minutes: 40 + steps: + - uses: actions/checkout@v4 + - name: Build and release the APK env: GITEA_TOKEN: ${{ github.token }} run: bash ci/gitea-apk.sh diff --git a/.gitea/workflows/legacy.yml b/.gitea/workflows/legacy.yml new file mode 100644 index 0000000..ddf6fa3 --- /dev/null +++ b/.gitea/workflows/legacy.yml @@ -0,0 +1,33 @@ +name: Legacy launcher (Qt) + +# The Qt build now lives in legacy/. The launcher is built from the repo root (MoonBit, see +# launcher.yml), so this runs only by hand, and does not publish a release unless asked: its +# releases (build-) would otherwise compete with the MoonBit build's for "latest". +on: + workflow_dispatch: + inputs: + publish: + description: Publish the APK as a release + default: "false" + +jobs: + apk: + runs-on: ubuntu-latest + timeout-minutes: 60 + container: eclipse-temurin:17-jdk-noble + steps: + - name: Checkout + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + apt-get update -qq + apt-get install -y -qq --no-install-recommends git ca-certificates >/dev/null + git init -q + git -c http.extraHeader="Authorization: Basic $(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0)" \ + fetch -q --depth 1 "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" "${GITHUB_SHA}" + git checkout -q --detach FETCH_HEAD + - name: Test, build and release the Qt APK + env: + GITEA_TOKEN: ${{ github.token }} + LEGACY_PUBLISH: ${{ inputs.publish }} + run: bash legacy/ci/gitea-apk.sh diff --git a/.github/workflows/launcher.yml b/.github/workflows/legacy.yml similarity index 90% rename from .github/workflows/launcher.yml rename to .github/workflows/legacy.yml index f40cc9a..028ca66 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/legacy.yml @@ -1,14 +1,17 @@ -name: Launcher +name: Legacy launcher +# The previous implementations (ultra WebView, Qt) now live in legacy/. The launcher is built +# from the repo root (MoonBit, see .gitea/workflows/launcher.yml), so this only runs by hand. on: - push: - branches: [main] - pull_request: workflow_dispatch: permissions: contents: write +defaults: + run: + working-directory: legacy + jobs: web: # Playwright's Chromium has no build for ubuntu-latest (26.04) yet. @@ -24,6 +27,7 @@ jobs: with: cache: false locked: false + manifest-path: legacy/pixi.toml # Playwright's browser download hangs while unpacking under pixi's Node 26, so fetch # Chromium with the runner's own Node; the test itself still runs in the pixi env. - uses: actions/setup-node@v5 @@ -49,14 +53,14 @@ jobs: java-version: 17 - uses: gradle/actions/setup-gradle@v5 - name: Build the APK - working-directory: android + working-directory: legacy/android # The run number only grows, so each build's versionCode is newer than the last # (it restarts if this workflow is renamed; bump past the old numbers then). run: ./gradlew --no-daemon assembleDebug -PversionCode=${{ github.run_number }} - uses: actions/upload-artifact@v5 with: name: ultra-launcher-apk - path: android/app/build/outputs/apk/debug/app-debug.apk + path: legacy/android/app/build/outputs/apk/debug/app-debug.apk # Keep a "launcher-latest" prerelease with the newest APK, so a phone can download it directly. - name: Publish the launcher-latest release if: github.event_name != 'pull_request' diff --git a/.gitignore b/.gitignore index c8a7768..6c3a8b2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,10 @@ -__pycache__/ +_build/ +.mooncakes/ +.context/ node_modules/ -.pixi/ -android/.gradle/ -android/build/ -android/app/build/ -android/local.properties -build/ -build-*/ -android-wasm/target/ -android-wasm/assets/*.wasm +/dist/ +/build/ +/android/build/ +*.apk +__pycache__/ +*.idsig diff --git a/.sweet.config.yml b/.sweet.config.yml new file mode 100644 index 0000000..fe5ece1 --- /dev/null +++ b/.sweet.config.yml @@ -0,0 +1,15 @@ +# Sweet repository configuration +types: + fix: + bump: patch + section: Fixes + feature: + bump: minor + section: Features + chore: + bump: none + refactor: + bump: none + performance: + bump: patch + section: Performance diff --git a/.sweet.yml b/.sweet.yml new file mode 100644 index 0000000..cff4400 --- /dev/null +++ b/.sweet.yml @@ -0,0 +1,8 @@ +# Sweet package configuration +name: launcher +version: 0.1.0 +# The Android versionName comes from moon.mod at build time (android/build.sh), so one file +# carries the version. +version-files: + - path: moon.mod + format: annotated diff --git a/README.md b/README.md index c6d48c9..a3d7a1a 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,97 @@ # ultra launcher -An Android home screen written as an [ultra](https://github.com/nandi-conda/ultra) app (LPython compiled to WebAssembly, Elm-style). The home starts blank (add a clock widget if you want one): long-press it to add apps (the drawer opens in a pick mode) or widgets, and long-press anything on it to drag it somewhere else; let go without moving to get its menu, or, for a widget, handles on its edges that resize it to the grid. Swipe down for the drawer with every app and a search (Enter opens the first match); long-press an app there for its menu (add to home, app info, uninstall; system apps have no uninstall), and swipe up to close it. The panel at the top has a **Windows** button that opens Recents. The layout is saved in localStorage. +An Android home screen, written in [MoonBit](https://www.moonbitlang.com). Home starts blank: long-press it to add apps (the drawer opens in a pick mode) or widgets, and long-press anything on it to drag it somewhere else; let go without moving to get its menu, or, for a widget, handles on its edges that resize it to the grid. Swipe down (or tap the search pill) for the drawer with every app and a search (Enter opens the first match); long-press an app there for its menu (add to home, app info, uninstall; system apps have no uninstall), and swipe up to close it. The **Windows** button in the panel at the top opens Recents. The layout is saved on the device, and the app updates itself from the latest release here. + +| home | drawer | app menu | resize handles | +|---|---|---|---| +| ![home](docs/screenshots/01-home-with-apps.png) | ![drawer](docs/screenshots/03-drawer.png) | ![menu](docs/screenshots/04-drawer-app-menu.png) | ![resize](docs/screenshots/05-resize-handles.png) | + +(Screenshots are of the browser demo at phone size.) ## Install -Get the APK from the [latest release](https://git.site.latha.org/experiments/launcher/releases/latest) on the Gitea forge, which CI rebuilds on every push to `main`. Open it once, press Home, and pick **ultra Home** as the default. Builds are signed with the committed `android/app/debug.keystore`, so each one installs over the last. +Get the APK from the [latest release](https://git.site.latha.org/experiments/launcher/releases/latest), which CI rebuilds on every push to `main`. Open it once, press Home, and pick **ultra Home** as the default. The package is `dev.ultra.launcher` and builds are signed with the committed `android/debug.keystore`, the same key every earlier build (WebView, Qt) used, so this installs over them. The activity keeps the Qt build's class name, so the default-home choice survives. The **Windows** button uses an accessibility service (`RecentsService`, which only performs the Recents action). Enable it once under Settings → Accessibility; on Android 13+ a sideloaded APK may first need App info → ⋮ → Allow restricted settings. -## Layout +On first start the old WebView build's home screen (its `ultra.home.*` localStorage) is imported. The Qt build's layout is not imported (see *Not done* below). -- `web/` is the UI: `app.py` is the ultra app and `app.wasm` its committed build, with `index.html`, `style.css` and the `ultra.js` / `ui.css` runtime the build copies in. `apps.json` and `widgets.json` are demo data for desktop browsers. -- `android/` is a small native shell (Java, no dependencies) that serves `web/` to a transparent WebView over the wallpaper. It answers `apps.json` from `LauncherApps` and `widgets.json` from the installed widget providers, hands icons to the page through the `window.Android` bridge, and draws real `AppWidgetHostView`s over the slots the page reports. -- The ultra framework comes from the `ultra` conda package on [prefix.dev/nandi-testing](https://prefix.dev/channels/nandi-testing), which pixi installs. -- `tests/e2e.cjs` is a Playwright test of the browser demo. +## How it is built -## Build +MoonBit owns the logic and the UI; Java is only what Android itself requires. -```sh -pixi run build # web/app.py -> web/app.wasm -pixi run install-playwright && pixi run test -cd android && ./gradlew assembleDebug # needs JDK 17 and the Android SDK +``` + ┌──────────────── pure MoonBit (no platform deps; moon test on js and wasm-gc) ───────────────┐ + pointer / touch / │ gesture ──► app.input ──► app.update(Model, Msg) ──► Effects (data) │ + key events ───────►│ │ │ + │ └──► app.view(Model) ──► vdom tree (data) │ + └───────────────┬────────────────────────────────────────────────┬───────────────────────────┘ + │ effects │ tree + ┌───────────────▼─────────────────────────────────────────────────▼──────────────┐ + │ web/ (js backend): runs effects against window.Android, patches the DOM, │ + │ listens for events │ + └───────────────┬─────────────────────────────────────────────────────────────────┘ + │ window.Android.* / window.launcher.* + ┌───────────────▼─────────────────────────────────────────────────────────────────┐ + │ android/java (Java): HomeActivity + WebView + AppWidgetHostViews, Updater, │ + │ RecentsService │ + └─────────────────────────────────────────────────────────────────────────────────┘ ``` -`pixi run serve` serves `web/` on http://localhost:8000. In a desktop browser the launcher runs against the demo JSON files, shows a toast instead of launching, and draws widgets as labelled placeholders. Click the bar at the top to open the drawer. +| package | what | tested by | +|---|---|---| +| `grid/` | the home grid: packing (dense, with pinned cells), cell/box math, pin, resize steps, widget columns | `moon test` | +| `gesture/` | pointer state machine: tap, long press (500 ms, 10 px slop), drag, release, swipe | `moon test` | +| `updater/` | release/`version.json` parsing, `build-N` tags, the install/skip decision, 6 h throttle | `moon test` | +| `jsonx/` | small `Json` accessors | `moon test` | +| `vdom/` | a virtual DOM as plain data, generic over the message type; renders to HTML text for snapshots | `moon test` | +| `app/` | `Model`, `Msg`, `update` (returns `Effect`s), `view`, JSON persistence and the import of the old localStorage layout, search, sheets/menus, drag and resize, the update flow | 60 headless tests that drive it through pointer input | +| `web/` | the js-target program: keyed DOM patcher, event wiring, host bridge (`window.Android`, or stand-ins that show a toast in a desktop browser), icon loading | `tests/e2e.cjs`, `tests/android-sim.cjs` (Playwright) | +| `android/` | the Java shell, manifest, resources, signing key, `build.sh` | builds; needs a device to run | -Every push to ultra's main publishes a new `ultra` package. To pick it up, run `pixi update ultra`, rebuild, and commit the rebuilt `web/` files. +Why this shape: the launcher's hard parts are layout math, gestures and state, and all of them are pure functions here, so `moon test` covers them on desktop with no Android and no browser. The view is a data tree rather than direct DOM calls, so its output is snapshot-tested as text, and pointer input is aimed at tree nodes by the tests exactly as the page aims it. Rendering in the existing WebView keeps the design that already works for widgets (real `AppWidgetHostView`s laid over transparent slots in the page). -## Qt rewrite (in progress) +### What stays Java, and why -`qt/` is the launcher rewritten as a Qt Quick (QML) app for Android, replacing ultra and the WebView. `qt/qml` is the UI (`Main.qml`, with the grid packing in `Layout.js`), `qt/src` a thin C++ backend, and `qt/android` the Java side (`HomeActivity`, a `QtActivity` that lists apps, draws icons, launches, and hosts the native widget views over the QML slots). It uses the same package (`dev.ultra.launcher`) and key as the WebView build, so it installs over it, from the releases on the Gitea forge ([experiments/launcher](https://git.site.latha.org/experiments/launcher)), where `.gitea/workflows/launcher.yml` tests, builds and publishes an APK on every push to main (`ci/gitea-apk.sh`); the installed app updates itself from the latest release there. +About 1,100 lines in `android/java/dev/ultra/launcher/`; none of it decides anything, it carries out what the page asks: + +- `HomeActivity`: Android requires an `Activity` for the HOME role; it hosts the WebView, serves `apps.json` / `widgets.json` / icons from `LauncherApps`, `PackageManager` and `AppWidgetManager`, and hosts `AppWidgetHostView`s, which are Java `View`s that can only be created and laid out by Java. Its widget touch interception (long press, drag) must decide synchronously whether to take a gesture from the widget, so it stays there and reports through `window.launcher.widget*`. +- `Updater`: `HttpURLConnection` (the page cannot `fetch` the Gitea API from the WebView's origin) and `PackageInstaller`. +- `RecentsService`: an `AccessibilityService` must be a Java class listed in the manifest; Android instantiates it by name. + +A pure-MoonBit shell (native backend → C, `NativeActivity` + JNI, drawing through the NDK) was considered and rejected: it would still need the same Java classes (`RecentsService`, and something to host `AppWidgetHostView`), the rest would be hundreds of lines of hand-written JNI in C, and nothing of it could be run or tested here (no Android SDK/NDK on the dev machine, no device). The moon toolchain's Android support on mooncakes (e.g. `Nanaloveyuki/ajni`, `wzzc-dev/moui`) is young and was not evaluated further. Rabbita was also considered for the view layer; it would tie the view to its DOM `Html` type and closures, out of reach of plain-data tests, and the gesture/drag handling needs delegated pointer events and its own hit-testing anyway. + +## Build and test + +Needs [MoonBit](https://www.moonbitlang.com/download) (`curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash`), Node 22 for the browser tests, and for the APK a JDK 17+ plus the Android SDK's `build-tools;35.0.0` and `platforms/android-35/android.jar`. ```sh -node qt/tests/layout.test.mjs # grid packing -cmake -S qt -B build && cmake --build build # desktop build, needs Qt 6.8+ -build/ultrahome # try it against the demo apps -QT_QPA_PLATFORM=offscreen build/ultrahome_e2e # end-to-end test of the UI +moon test # the pure core: grid, gestures, updater, the app (js backend) +moon test --target wasm-gc # the same tests on a second backend +scripts/build-web.sh --demo # the page -> dist/web (with the demo apps.json / widgets.json) +npm install && npx playwright install chromium # or CHROMIUM_PATH=/usr/bin/chromium +npm test # builds the page, then tests/e2e.cjs and tests/android-sim.cjs +android/build.sh # the page + Java shell -> build/ultra-launcher.apk, signed ``` + +`android/build.sh` runs `moon build` (via `scripts/build-web.sh`), then `aapt2 compile/link`, `javac`, `d8`, `zip`, `zipalign` and `apksigner`, with no Gradle. It reads `versionName` from `moon.mod` and takes `VERSION_CODE` from the environment (default: minutes since the epoch, which is above every earlier build's). `ANDROID_SDK_ROOT` points at the SDK (default `~/android-sdk`). + +To try the page in a desktop browser: `scripts/build-web.sh --demo && python3 -m http.server -d dist/web 8000`. It runs against `web/apps.json` and `web/widgets.json`, shows a toast instead of launching, and draws widgets as labelled placeholders. Click the search pill, or hold the empty home. + +## CI and releases + +`.gitea/workflows/launcher.yml`: a `test` job (MoonBit installed like in identicons-web, inside `node:22-bookworm`; `moon test` on js and wasm-gc, then the Playwright tests) and, on push to `main`, an `apk` job (container `git.site.latha.org/cluster-services/android-sdk:latest` from `charts/android-sdk` in nandi/cluster: JDK 17 + SDK 35, no per-run download; swap in `node:22-bookworm` as a fallback until it exists, the script then downloads the SDK itself) running `ci/gitea-apk.sh`, which builds the APK and publishes a Gitea release `build-` holding `ultra-launcher.apk` and `version.json` (a draft first, published once both files are up). The installed app compares that `versionCode` with its own and installs the newer APK. No `actions/setup-node`, no docker, every job has a `timeout-minutes`. + +Releases of the app's version are managed with [sweet](https://github.com/chattocorp/sweet-release): `.sweet.config.yml` (feature → minor, fix/performance → patch, chore/refactor → none) and `.sweet.yml` (`moon.mod`'s `version` line is annotated `// sweet-version`). The Android `versionName` is read from `moon.mod` by the build, so that is the one file that carries the version. + +## `legacy/` + +The previous implementations, moved here with `git mv` so their history follows: the ultra (LPython → wasm) WebView build (`web/`, `android/`), the Qt Quick rewrite (`qt/`), and the experiments (`wasi/`, `android-wasm/`), with their tests and CI script. Their paths are fixed so they still build from `legacy/` (see its README), but they are not maintained; their CI workflows run only by hand. The MoonBit launcher is a port of `legacy/web/app.py` (and the gesture code in its `index.html`), `legacy/qt/qml/Layout.js` and the Java shell. + +## Verified, and not + +Verified here: `moon test` (60 tests, js and wasm-gc), the browser flows in `tests/e2e.cjs` (the legacy test's flows, ported), the page against a stub of the Java bridge (`tests/android-sim.cjs`: icons, widget placement, drawer cover, keyboard, Recents, update check and install request), and that `android/build.sh` produces a signed APK with package `dev.ultra.launcher` that `aapt2 dump badging` and `apksigner verify` accept. + +**Not verified: anything on a device.** There is no Android runtime on the dev machine. The Java shell compiles and packages, and its logic was carried over from the legacy shell that ran on devices, but the combination (the MoonBit page in the WebView, real widget views over it, the installer, the accessibility service) has not been run. + +Not done: importing the Qt build's saved layout (a `QSettings` INI file; the old WebView layout is imported), per-widget configuration beyond what the legacy shell did, and shrinking the page's JS (about 560 KB, mostly MoonBit's JSON and number-parsing runtime). diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml new file mode 100644 index 0000000..659221b --- /dev/null +++ b/android/AndroidManifest.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/build.sh b/android/build.sh new file mode 100755 index 0000000..4b80e51 --- /dev/null +++ b/android/build.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Builds the APK without Gradle: the MoonBit page (scripts/build-web.sh) goes in as assets, +# the Java shell (android/java) is compiled with javac and d8, resources go through aapt2, +# and the result is zipaligned and signed with the committed android/debug.keystore (the +# same key every earlier build used, so each one installs over the last). +# +# android/build.sh [out.apk] # default: build/ultra-launcher.apk +# +# Needs JDK 17+, the Android SDK's build-tools and platforms;android-35 (ANDROID_SDK_ROOT, +# default ~/android-sdk) and moon (for the page). VERSION_CODE defaults to minutes since the +# epoch (always rising, and above every earlier build's); versionName comes from moon.mod. +set -euo pipefail +cd "$(dirname "$0")/.." +OUT=${1:-build/ultra-launcher.apk} +SDK=${ANDROID_SDK_ROOT:-${ANDROID_HOME:-$HOME/android-sdk}} +BT=$(ls -d "$SDK"/build-tools/* | sort -V | tail -1) +JAR=$SDK/platforms/android-35/android.jar +VERSION_NAME=$(sed -n 's/^version = "\([^"]*\)".*/\1/p' moon.mod | head -1) +VERSION_CODE=${VERSION_CODE:-$(( $(date +%s) / 60 ))} +W=build/android +mkdir -p "$(dirname "$OUT")" + +echo "== page" +scripts/build-web.sh + +echo "== resources (aapt2)" +rm -rf "$W" && mkdir -p "$W"/{compiled,classes,dex,gen,stage/assets} +"$BT/aapt2" compile --dir android/res -o "$W/compiled" +"$BT/aapt2" link -o "$W/base.apk" -I "$JAR" --manifest android/AndroidManifest.xml \ + --min-sdk-version 26 --target-sdk-version 35 \ + --version-code "$VERSION_CODE" --version-name "$VERSION_NAME" \ + --java "$W/gen" "$W"/compiled/*.flat + +echo "== java (javac, d8)" +javac --release 17 -Xlint:-options -classpath "$JAR" -d "$W/classes" \ + $(find android/java "$W/gen" -name '*.java') +"$BT/d8" --min-api 26 --lib "$JAR" --output "$W/dex" $(find "$W/classes" -name '*.class') + +echo "== package (versionCode $VERSION_CODE, versionName $VERSION_NAME)" +cp "$W/base.apk" "$W/unsigned.apk" +cp -r dist/web/. "$W/stage/assets/" +(cd "$W/dex" && zip -q -j ../unsigned.apk classes.dex) +(cd "$W/stage" && zip -q -r ../unsigned.apk assets) +"$BT/zipalign" -f -p 4 "$W/unsigned.apk" "$W/aligned.apk" +"$BT/apksigner" sign --ks android/debug.keystore --ks-pass pass:android \ + --ks-key-alias androiddebugkey --key-pass pass:android --out "$OUT" "$W/aligned.apk" +"$BT/apksigner" verify --print-certs "$OUT" | head -3 +echo "built $OUT" +printf '{"versionCode": %s, "commit": "%s"}\n' "$VERSION_CODE" "${GITHUB_SHA:-$(git rev-parse HEAD)}" > "$(dirname "$OUT")/version.json" diff --git a/android/app/debug.keystore b/android/debug.keystore similarity index 100% rename from android/app/debug.keystore rename to android/debug.keystore diff --git a/android/java/dev/ultra/launcher/HomeActivity.java b/android/java/dev/ultra/launcher/HomeActivity.java new file mode 100644 index 0000000..dc79026 --- /dev/null +++ b/android/java/dev/ultra/launcher/HomeActivity.java @@ -0,0 +1,959 @@ +package dev.ultra.launcher; + +import android.app.Activity; +import android.appwidget.AppWidgetHost; +import android.appwidget.AppWidgetHostView; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProviderInfo; +import android.content.Context; +import android.content.ActivityNotFoundException; +import android.content.ComponentName; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.LauncherActivityInfo; +import android.content.pm.LauncherApps; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Insets; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Process; +import android.os.UserHandle; +import android.provider.Settings; +import android.util.Base64; +import android.util.Log; +import android.util.SizeF; +import android.view.HapticFeedbackConstants; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.Window; +import android.view.WindowInsets; +import android.view.inputmethod.InputMethodManager; +import android.webkit.JavascriptInterface; +import android.webkit.RenderProcessGoneDetail; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.FrameLayout; +import android.widget.Toast; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.Collator; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * The home screen activity: a thin shell around the page that MoonBit builds (web/, in + * assets). It holds a transparent WebView over the wallpaper and, in a layer above it, the + * real AppWidgetHostViews, and does what only Android code can: + * + * apps.json {"apps": [{"label", "component", "icon", "system"}]}, every launchable activity + * icon?c=COMP the activity's icon as a PNG + * widgets.json {"widgets": [{"label", "app", "provider", "icon", "h"}]}, every widget provider + * wicon?p=PROV the provider's icon as a PNG + * + * and exposes window.Android (launch, appInfo, uninstall, addWidget, removeWidget, + * placeWidgets, coverWidgets, widgetLimits, excludeGestures, loadIcons, haptic, keyboard, + * openSettings, pickWallpaper, openRecents, httpGet, installApk, installedVersion, + * declinedVersion) for the page's host effects. No decisions are made here: the page + * (core/ and app/ in MoonBit) decides, this class carries them out. + * + * Widgets are real AppWidgetHostViews in a layer above the WebView. The page reports where + * its live widget slots are (placeWidgets), and this class moves the views there. Package + * changes, the home button, back, a new widget and a long press on a widget reach + * the page as window.launcher.reload() / home() / back() / widgetAdded(id) / + * widgetMenu(id) / widgetGrab(id) / widgetDrag(x, y) / widgetDrop(moved). + */ +public class HomeActivity extends Activity { + static final String HOST = "appassets.androidplatform.net"; + static final String ORIGIN = "https://" + HOST + "/"; + static final int ICON_DP = 56; + static final int HOST_ID = 0x0171; + static final int REQ_BIND = 1, REQ_CONFIGURE = 2; + + private WebView web; + private CoverLayer widgetLayer; + private long coverRequest; // the latest coverWidgets, so a stale uncover is dropped + private AppWidgetManager widgets; + private AppWidgetHost widgetHost; + private final Map widgetViews = new HashMap<>(); + private final Map widgetSizes = new HashMap<>(); // last size told to each widget + private int pendingWidget = -1; + private int editingWidget = -1; // showing resize handles: a press on it moves it + private boolean ready; + private int insetTop, insetBottom; // CSS px + private LauncherApps launcher; + private final UserHandle user = Process.myUserHandle(); + private final Map icons = new ConcurrentHashMap<>(); + private final Map activities = new ConcurrentHashMap<>(); + private final Handler main = new Handler(Looper.getMainLooper()); + private final ExecutorService iconThread = Executors.newSingleThreadExecutor(); + + private final LauncherApps.Callback packages = new LauncherApps.Callback() { + @Override public void onPackageRemoved(String pkg, UserHandle u) { reload(); } + @Override public void onPackageAdded(String pkg, UserHandle u) { reload(); } + @Override public void onPackageChanged(String pkg, UserHandle u) { reload(); } + @Override public void onPackagesAvailable(String[] pkgs, UserHandle u, boolean replacing) { reload(); } + @Override public void onPackagesUnavailable(String[] pkgs, UserHandle u, boolean replacing) { reload(); } + }; + + @Override + protected void onCreate(Bundle state) { + super.onCreate(state); + launcher = getSystemService(LauncherApps.class); + launcher.registerCallback(packages, main); + widgets = AppWidgetManager.getInstance(this); + widgetHost = new Host(this); + + Window w = getWindow(); + if (Build.VERSION.SDK_INT >= 30) { + w.setDecorFitsSystemWindows(false); + } else { + w.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); + } + createWebView(); + } + + private void createWebView() { + ready = false; + web = new WebView(this); + web.setBackgroundColor(Color.TRANSPARENT); + // Long presses are the page's (on_longpress); no native text selection. + web.setOnLongClickListener(v -> true); + web.setHapticFeedbackEnabled(false); + web.setVerticalScrollBarEnabled(false); + web.setOverScrollMode(View.OVER_SCROLL_NEVER); + WebSettings s = web.getSettings(); + s.setJavaScriptEnabled(true); + s.setDomStorageEnabled(true); // the dock is saved in localStorage + s.setAllowFileAccess(false); + s.setAllowContentAccess(false); + web.addJavascriptInterface(new Bridge(), "Android"); + web.setWebViewClient(new Client()); + web.setOnApplyWindowInsetsListener((v, insets) -> { + int top, bottom; + if (Build.VERSION.SDK_INT >= 30) { + Insets bars = insets.getInsets(WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout()); + Insets ime = insets.getInsets(WindowInsets.Type.ime()); + top = bars.top; + bottom = Math.max(bars.bottom, ime.bottom); + } else { + top = insets.getSystemWindowInsetTop(); + bottom = insets.getSystemWindowInsetBottom(); + } + float d = getResources().getDisplayMetrics().density; + insetTop = Math.round(top / d); + insetBottom = Math.round(bottom / d); + pushInsets(); + return insets; + }); + widgetViews.clear(); + widgetSizes.clear(); + widgetLayer = new CoverLayer(this); + FrameLayout root = new FrameLayout(this); + root.addView(web); + root.addView(widgetLayer); + setContentView(root); + web.loadUrl(ORIGIN + "index.html"); + } + + @Override + protected void onStart() { + super.onStart(); + widgetHost.startListening(); + } + + @Override + protected void onStop() { + super.onStop(); + widgetHost.stopListening(); + } + + @Override + protected void onDestroy() { + launcher.unregisterCallback(packages); + iconThread.shutdownNow(); + web.destroy(); + super.onDestroy(); + } + + // The home button while we are already in front. + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + js("home()"); + } + + // A home screen has nowhere to go back to; let the page clear its search or edit mode. + @Override + @SuppressWarnings("deprecation") + public void onBackPressed() { + js("back()"); + } + + private void js(String call) { + if (ready) web.evaluateJavascript("window.launcher && launcher." + call, null); + } + + private void pushInsets() { + if (!ready) return; + web.evaluateJavascript("(s => { s.setProperty('--inset-top', '" + insetTop + "px');" + + " s.setProperty('--inset-bottom', '" + insetBottom + "px'); })" + + "(document.documentElement.style); window.launcher && launcher.place()", null); + } + + private void reload() { + icons.clear(); + js("reload()"); + } + + /** + * Draw the icons for these keys ("icon?c=COMP" or "wicon?p=PROV", as apps.json and + * widgets.json give them) on the icon thread, and hand them to the page as data: URIs, + * a few at a time, through ultraIcons({key: uri}). A key that can't be drawn gets "". + */ + private void loadIcons(String json) { + List keys = new ArrayList<>(); + try { + JSONArray a = new JSONArray(json); + for (int i = 0; i < a.length(); i++) keys.add(a.getString(i)); + } catch (JSONException e) { + return; + } + iconThread.execute(() -> { + JSONObject batch = new JSONObject(); + for (int i = 0; i < keys.size(); i++) { + String k = keys.get(i); + byte[] png = null; + if (k.startsWith("icon?c=")) png = iconPng(Uri.decode(k.substring(7))); + else if (k.startsWith("wicon?p=")) png = widgetIconPng(Uri.decode(k.substring(8))); + try { + batch.put(k, png == null ? "" + : "data:image/png;base64," + Base64.encodeToString(png, Base64.NO_WRAP)); + } catch (JSONException e) { + continue; + } + if (batch.length() == 8 || i == keys.size() - 1) { + String call = "window.launcher && launcher.icons(" + batch + ")"; + main.post(() -> web.evaluateJavascript(call, null)); + batch = new JSONObject(); + } + } + }); + } + + // ------------------------------------------------------------ apps + + private String appsJson() throws JSONException { + List list = new ArrayList<>(launcher.getActivityList(null, user)); + Map labels = new HashMap<>(); + for (LauncherActivityInfo a : list) labels.put(a, String.valueOf(a.getLabel())); + Collator by = Collator.getInstance(); + list.sort((a, b) -> by.compare(labels.get(a), labels.get(b))); + JSONArray apps = new JSONArray(); + for (LauncherActivityInfo a : list) { + ComponentName cn = a.getComponentName(); + if (cn.getPackageName().equals(getPackageName())) continue; + String c = cn.flattenToShortString(); + activities.put(c, a); + JSONObject o = new JSONObject() + .put("label", labels.get(a)) + .put("component", c) + .put("icon", "icon?c=" + Uri.encode(c)); + // System apps can't be uninstalled, so the drawer offers no Uninstall for them. + if ((a.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) != 0) o.put("system", true); + apps.put(o); + } + return new JSONObject().put("apps", apps).toString(); + } + + // Icons are drawn one at a time: the WebView asks for a screenful at once on several + // threads, and some icon drawables don't survive being loaded and drawn concurrently. + private final Object iconLock = new Object(); + + private byte[] iconPng(String c) { + byte[] png = icons.get(c); + if (png != null) return png; + synchronized (iconLock) { + png = icons.get(c); + if (png != null) return png; + try { + png = drawIcon(c); + } catch (RuntimeException | OutOfMemoryError e) { + Log.w("ultra", "icon for " + c, e); + return null; + } + if (png != null) icons.put(c, png); + else Log.w("ultra", "no icon for " + c); + return png; + } + } + + private byte[] drawIcon(String c) { + ComponentName cn = c == null ? null : ComponentName.unflattenFromString(c); + if (cn == null) return null; + // Prefer the LauncherActivityInfo that apps.json was built from; resolve only if it + // isn't there (e.g. an icon asked for before the list was built). + LauncherActivityInfo info = activities.get(c); + if (info == null) { + info = launcher.resolveActivity( + new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(cn), user); + } + if (info == null) { + Log.w("ultra", "no launchable activity for " + c); + return null; + } + int dpi = getResources().getDisplayMetrics().densityDpi; + Drawable d = info.getIcon(dpi); + if (d == null) d = getPackageManager().getDefaultActivityIcon(); + return toPng(d, Math.round(ICON_DP * dpi / 160f)); + } + + private static byte[] toPng(Drawable d, int size) { + d = d.mutate(); // setBounds on a drawable shared with other callers would move theirs + Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); + d.setBounds(0, 0, size, size); + d.draw(new Canvas(bmp)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bmp.compress(Bitmap.CompressFormat.PNG, 100, out); + bmp.recycle(); + return out.toByteArray(); + } + + // ------------------------------------------------------------ widgets + + private String widgetsJson() throws JSONException { + List list = new ArrayList<>(widgets.getInstalledProvidersForProfile(user)); + Map labels = new HashMap<>(); + for (AppWidgetProviderInfo w : list) labels.put(w, w.loadLabel(getPackageManager())); + Collator by = Collator.getInstance(); + list.sort((a, b) -> by.compare(labels.get(a), labels.get(b))); + float d = getResources().getDisplayMetrics().density; + JSONArray out = new JSONArray(); + for (AppWidgetProviderInfo w : list) { + String p = w.provider.flattenToShortString(); + int h = Math.round(w.minHeight / d); + out.put(new JSONObject() + .put("label", labels.get(w)) + .put("app", appLabel(w.provider.getPackageName())) + .put("provider", p) + .put("icon", "wicon?p=" + Uri.encode(p)) + .put("h", Math.max(80, Math.min(h + 16, 420)))); + } + return new JSONObject().put("widgets", out).toString(); + } + + /** The label of the app a widget comes from, for the picker's search. */ + private String appLabel(String pkg) { + try { + PackageManager pm = getPackageManager(); + return pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString(); + } catch (PackageManager.NameNotFoundException e) { + return ""; + } + } + + private AppWidgetProviderInfo provider(String p) { + ComponentName cn = p == null ? null : ComponentName.unflattenFromString(p); + if (cn == null) return null; + for (AppWidgetProviderInfo w : widgets.getInstalledProvidersForProfile(user)) { + if (w.provider.equals(cn)) return w; + } + return null; + } + + private byte[] widgetIconPng(String p) { + String k = "w:" + p; + byte[] png = icons.get(k); + if (png != null) return png; + synchronized (iconLock) { + AppWidgetProviderInfo w = provider(p); + if (w == null) return null; + int dpi = getResources().getDisplayMetrics().densityDpi; + Drawable d = null; + try { + d = w.loadIcon(this, dpi); + } catch (RuntimeException e) { + Log.w("ultra", "widget icon for " + p, e); + } + if (d == null) { + // Fall back to the app's own icon, then to the system default. + try { + d = getPackageManager().getApplicationIcon(w.provider.getPackageName()); + } catch (android.content.pm.PackageManager.NameNotFoundException | RuntimeException e) { + d = getPackageManager().getDefaultActivityIcon(); + } + } + try { + png = toPng(d, Math.round(ICON_DP * dpi / 160f)); + } catch (RuntimeException | OutOfMemoryError e) { + Log.w("ultra", "drawing widget icon for " + p, e); + return null; + } + icons.put(k, png); + return png; + } + } + + /** Bind a widget for provider p, then configure it if it asks to be; see onActivityResult. */ + private void addWidget(String p) { + AppWidgetProviderInfo w = provider(p); + if (w == null) return; + int id = widgetHost.allocateAppWidgetId(); + pendingWidget = id; + if (widgets.bindAppWidgetIdIfAllowed(id, user, w.provider, null)) { + configureWidget(id); + } else { + Intent i = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, w.provider) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, user); + try { + startActivityForResult(i, REQ_BIND); + } catch (ActivityNotFoundException e) { + dropPending(); + } + } + } + + private void configureWidget(int id) { + AppWidgetProviderInfo w = widgets.getAppWidgetInfo(id); + if (w != null && w.configure != null) { + try { + widgetHost.startAppWidgetConfigureActivityForResult(this, id, 0, REQ_CONFIGURE, null); + return; + } catch (ActivityNotFoundException | SecurityException e) { + // Fall through: add it unconfigured, as most launchers do. + } + } + widgetReady(id); + } + + private void widgetReady(int id) { + pendingWidget = -1; + js("widgetAdded(" + id + ")"); + } + + private void dropPending() { + if (pendingWidget != -1) widgetHost.deleteAppWidgetId(pendingWidget); + pendingWidget = -1; + } + + @Override + protected void onActivityResult(int req, int result, Intent data) { + super.onActivityResult(req, result, data); + if (pendingWidget == -1) return; + if (result != RESULT_OK) { + dropPending(); + } else if (req == REQ_BIND) { + configureWidget(pendingWidget); + } else if (req == REQ_CONFIGURE) { + widgetReady(pendingWidget); + } + } + + private void removeWidget(int id) { + AppWidgetHostView v = widgetViews.remove(id); + if (v != null) widgetLayer.removeView(v); + widgetSizes.remove(id); + widgetHost.deleteAppWidgetId(id); + } + + /** + * A placed widget's natural width and how far it may be resized, in CSS px: {"w", + * "minW", "minH", "maxW", "maxH" (0 = no limit), "h", "v" (whether it resizes + * horizontally / vertically)}. + */ + private String widgetLimits(int id) { + AppWidgetProviderInfo w = widgets.getAppWidgetInfo(id); + JSONObject o = new JSONObject(); + try { + if (w == null) return o.toString(); + float d = getResources().getDisplayMetrics().density; + // A minResize larger than the min size (or unset) means the min size applies. + int minW = w.minResizeWidth > 0 && w.minResizeWidth < w.minWidth ? w.minResizeWidth : w.minWidth; + int minH = w.minResizeHeight > 0 && w.minResizeHeight < w.minHeight ? w.minResizeHeight : w.minHeight; + int maxW = 0, maxH = 0; + if (Build.VERSION.SDK_INT >= 31) { + maxW = w.maxResizeWidth; + maxH = w.maxResizeHeight; + } + o.put("w", Math.round(w.minWidth / d)) + .put("minW", Math.round(minW / d)).put("minH", Math.round(minH / d)) + .put("maxW", Math.round(maxW / d)).put("maxH", Math.round(maxH / d)) + .put("h", (w.resizeMode & AppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0) + .put("v", (w.resizeMode & AppWidgetProviderInfo.RESIZE_VERTICAL) != 0); + } catch (JSONException e) { + Log.w("ultra", "widget limits", e); + } + return o.toString(); + } + + /** Keep the system's edge gestures off these page rects ([[x, y, w, h], ...] in CSS px). */ + private void excludeGestures(String json) { + if (Build.VERSION.SDK_INT < 29) return; + float d = getResources().getDisplayMetrics().density; + List rects = new ArrayList<>(); + try { + JSONArray a = new JSONArray(json); + for (int i = 0; i < a.length(); i++) { + JSONArray r = a.getJSONArray(i); + int x = Math.round(r.getInt(0) * d), y = Math.round(r.getInt(1) * d); + rects.add(new Rect(x, y, x + Math.round(r.getInt(2) * d), y + Math.round(r.getInt(3) * d))); + } + } catch (JSONException e) { + return; + } + web.setSystemGestureExclusionRects(rects); + } + + /** + * Lay widget views over the page's live slots: [[id, x, y, w, h, editing], ...] in CSS + * px, where editing is 1 for the one showing resize handles. + */ + private void placeWidgets(String json) { + float d = getResources().getDisplayMetrics().density; + Map want = new HashMap<>(); + int editing = -1; + try { + JSONArray a = new JSONArray(json); + for (int i = 0; i < a.length(); i++) { + JSONArray r = a.getJSONArray(i); + if (r.optInt(5) == 1) editing = r.getInt(0); + want.put(r.getInt(0), new int[] { + Math.round(r.getInt(1) * d), Math.round(r.getInt(2) * d), + Math.round(r.getInt(3) * d), Math.round(r.getInt(4) * d), + r.getInt(3), r.getInt(4)}); + } + } catch (JSONException e) { + return; + } + editingWidget = editing; + for (Map.Entry e : widgetViews.entrySet()) { + if (!want.containsKey(e.getKey())) e.getValue().setVisibility(View.GONE); + } + for (Map.Entry e : want.entrySet()) { + int id = e.getKey(); + int[] r = e.getValue(); + AppWidgetHostView v = widgetViews.get(id); + if (v == null) { + AppWidgetProviderInfo info = widgets.getAppWidgetInfo(id); + if (info == null) continue; // the provider was uninstalled + v = widgetHost.createView(this, id, info); + widgetViews.put(id, v); + widgetLayer.addView(v); + } + FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(r[2], r[3]); + lp.leftMargin = r[0]; + lp.topMargin = r[1]; + v.setLayoutParams(lp); + v.setVisibility(View.VISIBLE); + // Scrolling moves a widget without resizing it; only tell it about new sizes. + long size = ((long) r[4] << 32) | r[5]; + Long was = widgetSizes.put(id, size); + if (was == null || was != size) { + if (Build.VERSION.SDK_INT >= 31) { + List sizes = new ArrayList<>(); + sizes.add(new SizeF(r[4], r[5])); + v.updateAppWidgetSize(new Bundle(), sizes); + } else { + v.updateAppWidgetSize(new Bundle(), r[4], r[5], r[4], r[5]); + } + } + } + } + + /** + * Widget views that report a long press to the page instead of to the widget. The press + * lifts the widget's slot; the moves and the release that follow go to the page as + * widgetDrag(x, y) in CSS px and widgetDrop(moved), so it can be dragged to a new place. + * A widget showing resize handles is picked up by any press on it (widgetGrab(id)). + */ + static final class Host extends AppWidgetHost { + Host(HomeActivity a) { super(a, HOST_ID); } + + @Override + protected AppWidgetHostView onCreateView(Context context, int id, AppWidgetProviderInfo info) { + return new WidgetView((HomeActivity) context, id); + } + } + + /** + * Holds the widget views. The app drawer slides down over the page, so the widgets + * must be hidden above its edge: cover(top) clips them (and their touches) above top + * px, -1 hides them all, 0 shows them all. + */ + static final class CoverLayer extends FrameLayout { + private int top; + + CoverLayer(Context c) { super(c); } + + void cover(int y) { + if (y == top) return; + top = y; + setVisibility(y < 0 ? View.INVISIBLE : View.VISIBLE); + setClipBounds(y > 0 ? new Rect(0, y, Math.max(getWidth(), 1), Math.max(getHeight(), y + 1)) : null); + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + if (top != 0 && ev.getActionMasked() == MotionEvent.ACTION_DOWN && (top < 0 || ev.getY() < top)) return false; + return super.dispatchTouchEvent(ev); + } + } + + static final class WidgetView extends AppWidgetHostView { + private final HomeActivity home; + private final int id; + private float downX, downY; + private boolean longPressed, moved; + private final int[] webAt = new int[2]; + private final Runnable fire = new Runnable() { + @Override public void run() { + longPressed = true; + moved = false; + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + setAlpha(.85f); + home.js("widgetMenu(" + id + ")"); + } + }; + + WidgetView(HomeActivity home, int id) { + super(home); + this.home = home; + this.id = id; + } + + /** + * No inset: AppWidgetHostView pads older widgets by getDefaultPaddingForWidget + * (about 8dp a side) whenever it binds one, which left a margin inside the slot. + */ + @Override + public void setPadding(int left, int top, int right, int bottom) { + super.setPadding(0, 0, 0, 0); + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent e) { + switch (e.getActionMasked()) { + case MotionEvent.ACTION_DOWN: + longPressed = false; + downX = e.getX(); + downY = e.getY(); + if (home.editingWidget == id) { + // Being resized: the press moves it, without a long press first. + longPressed = true; + moved = false; + setAlpha(.85f); + home.js("widgetGrab(" + id + ")"); + return true; + } + postDelayed(fire, ViewConfiguration.getLongPressTimeout()); + break; + case MotionEvent.ACTION_MOVE: + if (Math.hypot(e.getX() - downX, e.getY() - downY) + > ViewConfiguration.get(getContext()).getScaledTouchSlop()) { + removeCallbacks(fire); + } + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + removeCallbacks(fire); + if (longPressed) { + drop(); // released before any move reached onTouchEvent + return true; + } + break; + } + return longPressed; // once fired, take the gesture away from the widget + } + + private void drop() { + longPressed = false; + setAlpha(1f); + home.js("widgetDrop(" + moved + ")"); + } + + @Override + public boolean onTouchEvent(MotionEvent e) { + if (!longPressed) { + // Where no child took the press, its moves come here instead of through + // onInterceptTouchEvent; keep the gesture so they do. + int a = e.getActionMasked(); + if (a == MotionEvent.ACTION_UP || a == MotionEvent.ACTION_CANCEL + || (a == MotionEvent.ACTION_MOVE && Math.hypot(e.getX() - downX, e.getY() - downY) + > ViewConfiguration.get(getContext()).getScaledTouchSlop())) { + removeCallbacks(fire); + } + return super.onTouchEvent(e) || a == MotionEvent.ACTION_DOWN; + } + switch (e.getActionMasked()) { + case MotionEvent.ACTION_MOVE: + if (!moved && Math.hypot(e.getX() - downX, e.getY() - downY) + > ViewConfiguration.get(getContext()).getScaledTouchSlop()) { + moved = true; + } + if (moved) { + // Raw screen coordinates: this view moves as the page reorders slots. + float d = getResources().getDisplayMetrics().density; + home.web.getLocationOnScreen(webAt); + home.js("widgetDrag(" + Math.round((e.getRawX() - webAt[0]) / d) + "," + + Math.round((e.getRawY() - webAt[1]) / d) + ")"); + } + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + drop(); + break; + } + return true; + } + } + + private void start(String component) { + ComponentName cn = ComponentName.unflattenFromString(component); + try { + launcher.startMainActivity(cn, user, null, null); + } catch (ActivityNotFoundException | SecurityException | NullPointerException e) { + Toast.makeText(this, "Can't open " + component, Toast.LENGTH_SHORT).show(); + } + } + + private void startIntent(Intent i) { + try { + startActivity(i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + } catch (ActivityNotFoundException e) { + Toast.makeText(this, "Not available on this device", Toast.LENGTH_SHORT).show(); + } + } + + /** + * Show Recents through RecentsService. Until the user has turned the service on, take + * them to Accessibility settings, with our service highlighted where Settings supports it. + */ + private void openRecents() { + if (RecentsService.showRecents()) return; + Toast.makeText(this, "Turn on \"" + getString(R.string.recents_service_label) + + "\" to show open windows", Toast.LENGTH_LONG).show(); + String me = new ComponentName(this, RecentsService.class).flattenToString(); + Bundle args = new Bundle(); + args.putString(":settings:fragment_args_key", me); + startIntent(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) + .putExtra(":settings:fragment_args_key", me) + .putExtra(":settings:show_fragment_args", args)); + } + + /** window.Android: called from the page's @jscall imports on a binder thread. */ + final class Bridge { + @JavascriptInterface public void launch(String component) { + main.post(() -> start(component)); + } + + @JavascriptInterface public void appInfo(String component) { + main.post(() -> { + ComponentName cn = ComponentName.unflattenFromString(component); + if (cn != null) launcher.startAppDetailsActivity(cn, user, null, null); + }); + } + + /** The system asks the user to confirm; the app list reloads when the package goes. */ + @JavascriptInterface public void uninstall(String component) { + main.post(() -> { + ComponentName cn = ComponentName.unflattenFromString(component); + if (cn != null) startIntent(new Intent(Intent.ACTION_DELETE, + Uri.fromParts("package", cn.getPackageName(), null))); + }); + } + + @JavascriptInterface public void addWidget(String provider) { + main.post(() -> HomeActivity.this.addWidget(provider)); + } + + @JavascriptInterface public void removeWidget(int id) { + main.post(() -> HomeActivity.this.removeWidget(id)); + } + + @JavascriptInterface public void placeWidgets(String json) { + main.post(() -> HomeActivity.this.placeWidgets(json)); + } + + /** The drawer covers the page down to y (CSS px); -1 is all of it, 0 none. */ + @JavascriptInterface public void coverWidgets(int y) { + main.post(() -> { + long n = ++coverRequest; + if (y != 0) { widgetLayer.cover(y < 0 ? -1 : Math.round(y * getResources().getDisplayMetrics().density)); return; } + // The drawer is gone from the page; show the widgets once the page has + // painted without it, so they don't flash over it for a frame. + web.postVisualStateCallback(n, new WebView.VisualStateCallback() { + @Override public void onComplete(long requestId) { + if (requestId == coverRequest) widgetLayer.cover(0); + } + }); + }); + } + + @JavascriptInterface public String widgetLimits(int id) { + return HomeActivity.this.widgetLimits(id); + } + + @JavascriptInterface public void excludeGestures(String json) { + main.post(() -> HomeActivity.this.excludeGestures(json)); + } + + @JavascriptInterface public void loadIcons(String keys) { + HomeActivity.this.loadIcons(keys); + } + + @JavascriptInterface public void haptic() { + main.post(() -> web.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, + HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING)); + } + + /** The page focused the drawer's search box; show the keyboard for it. */ + @JavascriptInterface public void showKeyboard() { + main.postDelayed(() -> { + web.requestFocus(); + InputMethodManager imm = getSystemService(InputMethodManager.class); + if (imm != null) imm.showSoftInput(web, InputMethodManager.SHOW_IMPLICIT); + }, 50); + } + + @JavascriptInterface public void hideKeyboard() { + main.post(() -> { + InputMethodManager imm = getSystemService(InputMethodManager.class); + if (imm != null) imm.hideSoftInputFromWindow(web.getWindowToken(), 0); + }); + } + + @JavascriptInterface public void openSettings() { + main.post(() -> startIntent(new Intent(Settings.ACTION_SETTINGS))); + } + + @JavascriptInterface public void pickWallpaper() { + main.post(() -> startIntent(Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER), "Wallpaper"))); + } + + @JavascriptInterface public void openRecents() { + main.post(HomeActivity.this::openRecents); + } + + /** GET a URL on a background thread; the page hears back through launcher.httpResult(tag, ok, text). */ + @JavascriptInterface public void httpGet(String url, int tag) { + Updater.get(HomeActivity.this, url, (ok, text) -> main.post(() -> + js("httpResult(" + tag + "," + ok + "," + JSONObject.quote(text) + ")"))); + } + + /** Stream an APK into a PackageInstaller session; Android then asks the user to confirm. */ + @JavascriptInterface public void installApk(String url, int version) { + Updater.install(HomeActivity.this, url, version); + } + + @JavascriptInterface public int installedVersion() { + return Updater.installedVersion(HomeActivity.this); + } + + /** The last build whose install the user cancelled, or -1. */ + @JavascriptInterface public int declinedVersion() { + return Updater.declinedVersion(HomeActivity.this); + } + } + + // ------------------------------------------------------------ serving + + final class Client extends WebViewClient { + @Override + public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest req) { + Uri u = req.getUrl(); + if (!HOST.equals(u.getHost())) return notFound(); + String path = u.getPath() == null ? "/" : u.getPath(); + try { + switch (path) { + case "/apps.json": + return respond("application/json", + new ByteArrayInputStream(appsJson().getBytes(StandardCharsets.UTF_8))); + case "/widgets.json": + return respond("application/json", + new ByteArrayInputStream(widgetsJson().getBytes(StandardCharsets.UTF_8))); + case "/wicon": + byte[] wpng = widgetIconPng(u.getQueryParameter("p")); + return wpng == null ? notFound() : respond("image/png", new ByteArrayInputStream(wpng)); + case "/icon": + byte[] png = iconPng(u.getQueryParameter("c")); + return png == null ? notFound() : respond("image/png", new ByteArrayInputStream(png)); + default: + String name = path.equals("/") ? "index.html" : path.substring(1); + return respond(mime(name), getAssets().open(name)); + } + } catch (IOException | JSONException | RuntimeException e) { + Log.w("ultra", "serving " + path, e); + return notFound(); + } + } + + @Override + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest req) { + return true; // the home screen never navigates away + } + + @Override + public void onPageFinished(WebView view, String url) { + ready = true; + pushInsets(); + } + + @Override + public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) { + // The renderer was killed (e.g. under memory pressure): start over with a new WebView. + for (AppWidgetHostView v : widgetViews.values()) widgetLayer.removeView(v); + web.destroy(); + createWebView(); + return true; + } + } + + private static WebResourceResponse respond(String mime, InputStream body) { + Map headers = new HashMap<>(); + headers.put("Cache-Control", "no-cache"); + return new WebResourceResponse(mime, null, 200, "OK", headers, body); + } + + private static WebResourceResponse notFound() { + return new WebResourceResponse("text/plain", null, 404, "Not Found", new HashMap<>(), + new ByteArrayInputStream(new byte[0])); + } + + private static String mime(String name) { + if (name.endsWith(".html")) return "text/html"; + if (name.endsWith(".js")) return "text/javascript"; + if (name.endsWith(".css")) return "text/css"; + if (name.endsWith(".wasm")) return "application/wasm"; + if (name.endsWith(".json")) return "application/json"; + if (name.endsWith(".png")) return "image/png"; + if (name.endsWith(".svg")) return "image/svg+xml"; + return "application/octet-stream"; + } +} diff --git a/android/app/src/main/java/dev/ultra/launcher/RecentsService.java b/android/java/dev/ultra/launcher/RecentsService.java similarity index 100% rename from android/app/src/main/java/dev/ultra/launcher/RecentsService.java rename to android/java/dev/ultra/launcher/RecentsService.java diff --git a/android/java/dev/ultra/launcher/Updater.java b/android/java/dev/ultra/launcher/Updater.java new file mode 100644 index 0000000..66b252d --- /dev/null +++ b/android/java/dev/ultra/launcher/Updater.java @@ -0,0 +1,158 @@ +package dev.ultra.launcher; + +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageInstaller; +import android.content.pm.PackageManager; +import android.os.Build; +import android.util.Log; +import android.widget.Toast; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +/** + * The network and installer half of self-update. Which release is newer, when to check and + * whether to offer a build the user cancelled are decided by the page (updater/ in MoonBit); + * this only fetches URLs and hands an APK to PackageInstaller. + */ +final class Updater { + static final String EXTRA_VERSION = "dev.ultra.launcher.VERSION"; + + interface Done { void result(boolean ok, String text); } + + private Updater() {} + + private static SharedPreferences prefs(Context c) { + return c.getSharedPreferences("updater", Context.MODE_PRIVATE); + } + + @SuppressWarnings("deprecation") + static int installedVersion(Context c) { + try { + PackageInfo p = c.getPackageManager().getPackageInfo(c.getPackageName(), 0); + return (int) (Build.VERSION.SDK_INT >= 28 ? p.getLongVersionCode() : p.versionCode); + } catch (PackageManager.NameNotFoundException e) { + return 0; + } + } + + static int declinedVersion(Context c) { + return (int) prefs(c).getLong("declined", -1); + } + + /** GET a URL as text on a background thread. */ + static void get(Context c, String url, Done done) { + new Thread(() -> { + try { + HttpURLConnection conn = open(url); + try (InputStream in = conn.getInputStream()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + for (int n; (n = in.read(buf)) > 0; ) out.write(buf, 0, n); + done.result(true, new String(out.toByteArray(), StandardCharsets.UTF_8)); + } finally { + conn.disconnect(); + } + } catch (IOException | RuntimeException e) { + Log.w("ultra", "GET " + url, e); + done.result(false, String.valueOf(e.getMessage())); + } + }, "updater-get").start(); + } + + /** Stream the APK at url into a PackageInstaller session and commit it. */ + static void install(Context ctx, String url, int version) { + Context c = ctx.getApplicationContext(); + new Thread(() -> { + try { + installNow(c, url, version); + } catch (IOException | RuntimeException e) { + Log.w("ultra", "update install", e); + toast(c, "Launcher update failed"); + } + }, "updater-install").start(); + } + + private static void installNow(Context c, String url, int version) throws IOException { + PackageInstaller pi = c.getPackageManager().getPackageInstaller(); + PackageInstaller.SessionParams params = + new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL); + params.setAppPackageName(c.getPackageName()); + if (Build.VERSION.SDK_INT >= 31) { + params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED); + } + int id = pi.createSession(params); + try (PackageInstaller.Session s = pi.openSession(id)) { + HttpURLConnection conn = open(url); + try (InputStream in = conn.getInputStream(); + OutputStream out = s.openWrite("ultra-launcher.apk", 0, conn.getContentLengthLong())) { + byte[] buf = new byte[64 * 1024]; + for (int n; (n = in.read(buf)) > 0; ) out.write(buf, 0, n); + s.fsync(out); + } finally { + conn.disconnect(); + } + Intent done = new Intent(c, InstallReceiver.class).putExtra(EXTRA_VERSION, (long) version); + int flags = PendingIntent.FLAG_UPDATE_CURRENT + | (Build.VERSION.SDK_INT >= 31 ? PendingIntent.FLAG_MUTABLE : 0); + s.commit(PendingIntent.getBroadcast(c, id, done, flags).getIntentSender()); + } catch (IOException | RuntimeException e) { + pi.abandonSession(id); + throw e; + } + } + + private static HttpURLConnection open(String url) throws IOException { + HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); + conn.setConnectTimeout(15000); + conn.setReadTimeout(30000); + conn.setUseCaches(false); + conn.setInstanceFollowRedirects(true); + int code = conn.getResponseCode(); + if (code != HttpURLConnection.HTTP_OK) { + conn.disconnect(); + throw new IOException("HTTP " + code + " for " + url); + } + return conn; + } + + private static void toast(Context c, String msg) { + new android.os.Handler(android.os.Looper.getMainLooper()) + .post(() -> Toast.makeText(c, msg, Toast.LENGTH_LONG).show()); + } + + /** Hears back from the install session: shows Android's confirm screen, or notes the outcome. */ + public static final class InstallReceiver extends BroadcastReceiver { + @Override + @SuppressWarnings("deprecation") + public void onReceive(Context c, Intent intent) { + int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE); + switch (status) { + case PackageInstaller.STATUS_PENDING_USER_ACTION: + Intent confirm = intent.getParcelableExtra(Intent.EXTRA_INTENT); + if (confirm != null) c.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + break; + case PackageInstaller.STATUS_SUCCESS: + break; // the new build replaces this process + case PackageInstaller.STATUS_FAILURE_ABORTED: + prefs(c).edit().putLong("declined", intent.getLongExtra(EXTRA_VERSION, -1)).apply(); + break; + default: + String why = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE); + Log.w("ultra", "update install failed: " + status + " " + why); + Toast.makeText(c, "Launcher update failed" + (why == null ? "" : ": " + why), + Toast.LENGTH_LONG).show(); + } + } + } +} diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/res/drawable/ic_launcher_background.xml similarity index 100% rename from android/app/src/main/res/drawable/ic_launcher_background.xml rename to android/res/drawable/ic_launcher_background.xml diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/res/drawable/ic_launcher_foreground.xml similarity index 100% rename from android/app/src/main/res/drawable/ic_launcher_foreground.xml rename to android/res/drawable/ic_launcher_foreground.xml diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/res/mipmap-anydpi-v26/ic_launcher.xml similarity index 100% rename from android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml rename to android/res/mipmap-anydpi-v26/ic_launcher.xml diff --git a/android/app/src/main/res/values/strings.xml b/android/res/values/strings.xml similarity index 100% rename from android/app/src/main/res/values/strings.xml rename to android/res/values/strings.xml diff --git a/android/app/src/main/res/values/styles.xml b/android/res/values/styles.xml similarity index 100% rename from android/app/src/main/res/values/styles.xml rename to android/res/values/styles.xml diff --git a/android/app/src/main/res/xml/recents_service.xml b/android/res/xml/recents_service.xml similarity index 100% rename from android/app/src/main/res/xml/recents_service.xml rename to android/res/xml/recents_service.xml diff --git a/app/model.mbt b/app/model.mbt new file mode 100644 index 0000000..51abd7e --- /dev/null +++ b/app/model.mbt @@ -0,0 +1,323 @@ +///| +/// The launcher as an Elm-style program, pure: `Model`, `Msg`, `update` (returns the +/// `Effect`s for the platform to run) and `view` (returns a `vdom` tree). It ports +/// legacy/web/app.py, the LPython app, and the gesture handling that lived in its +/// index.html. Nothing here touches a platform: the web/ package runs the effects and +/// renders the tree, and the tests below drive the whole thing headlessly. + +///| +pub(all) struct AppInfo { + label : String + component : String + icon : String + /// A system app: it has no Uninstall. + system : Bool +} + +///| +pub(all) struct WidgetInfo { + label : String + provider : String + icon : String + /// The label of the app the widget comes from (for the picker's search). + app : String + /// Natural height in CSS px. + h : Int32 +} + +///| +/// How a widget may be resized, in CSS px (the shell's `widgetLimits`): its natural +/// width, min/max size (0: no max), and whether it resizes horizontally / vertically. +pub(all) struct Limits { + w : Int32 + min_w : Int32 + min_h : Int32 + max_w : Int32 + max_h : Int32 + h : Bool + v : Bool +} + +///| +pub let default_limits : Limits = { + w: 0, + min_w: 120, + min_h: 80, + max_w: 0, + max_h: 0, + h: true, + v: true, +} + +///| +#derive(Eq, Debug) +pub(all) enum Sheet { + NoSheet + /// The menu of the empty home. + HomeMenu + /// The menu of a home slot. + Item(Int32) + /// The menu of a drawer app (row in the app list). + DrawerApp(Int32) + WidgetPicker +} + +///| +#derive(Eq, Debug) +pub(all) enum Edge { + Right + Bottom + Corner +} + +///| +/// A resize in progress: a handle was pressed on the widget whose box (px, viewport) was +/// at `left`, `top`. +pub(all) struct ResizeDrag { + edge : Edge + slot : Int32 + left : Double + top : Double + mut cols : Int32 + mut rows : Int32 +} + +///| +/// Where the lifted slot was held, and the cell it was last sent to. +pub(all) struct Carry { + dx : Double + dy : Double + mut cell : Int32 +} + +///| +pub(all) struct Model { + mut apps : Array[AppInfo] + mut loading : Bool + mut load_error : String + mut widgets : Array[WidgetInfo] + mut wloading : Bool + /// The home screen, in order. + mut home : Array[@grid.Slot] + mut next_key : Int32 + /// Grid columns, and rows that fill the screen (0 until the page has measured). + mut cols : Int32 + mut nrows : Int32 + /// Where the grid is on the screen (px, viewport) and how wide a column is. + mut grid_left : Double + mut grid_top : Double + mut col_w : Double + mut query : String + mut wquery : String + mut drawer : Bool + /// The drawer is in "add apps" mode: taps toggle home slots. + mut picking : Bool + mut sheet : Sheet + /// The package being uninstalled: its home slot goes when it leaves the app list. + mut gone : String + /// Home slot picked up by a long press, being dragged. + mut lifted : Int32 + /// Widget slot showing resize handles. + mut resizing : Int32 + /// The lifted slot was grabbed while showing handles: drop it back into them. + mut regrab : Bool + mut carry : Carry? + mut resize : ResizeDrag? + /// Native widget views report their drags through `NativeDrag`; where it began. + mut native_from : (Double, Double)? + /// Widget row being added. + mut chosen : Int32 + mut limits : Map[Int32, Limits] + mut notice : String + mut notice_gen : Int32 + // ---- self-update + mut installed : Int32 + mut declined : Int32 + mut checking : Bool + mut manual_check : Bool + mut apk_url : String? + mut release_tag : String + /// The layout JSON last handed to `SaveHome`. + mut saved : String + /// A pointer drag (lift or resize) happened since the pointer went down: the swipe + /// check that follows the touch ignores it. + mut dragged : Bool + /// A widget just added whose limits will set its starting width. + mut fresh : Int32 + mut gesture : @gesture.State +} + +///| +pub fn Model::new() -> Model { + { + apps: [], + loading: true, + load_error: "", + widgets: [], + wloading: false, + home: [], + next_key: 1, + cols: 5, + nrows: 0, + grid_left: 0.0, + grid_top: 0.0, + col_w: 0.0, + query: "", + wquery: "", + drawer: false, + picking: false, + sheet: NoSheet, + gone: "", + lifted: -1, + resizing: -1, + regrab: false, + carry: None, + resize: None, + native_from: None, + chosen: -1, + limits: {}, + notice: "", + notice_gen: 0, + installed: 0, + declined: -1, + checking: false, + manual_check: false, + apk_url: None, + release_tag: "", + saved: "", + dragged: false, + fresh: -1, + gesture: @gesture.State::new(), + } +} + +///| +/// The most slots the home screen holds. +pub let home_cap : Int32 = 200 + +///| +pub let app_cap : Int32 = 512 + +///| +#derive(Eq, Debug) +/// What a view node can send. Raw pointer input goes through `Input` and the gesture +/// recogniser first; everything else is a Msg a handler or the shell sends directly. +pub(all) enum Msg { + // ---- from the platform + /// Boot: the saved layout (this app's JSON, and the old WebView build's + /// `ultra.home.*` localStorage as a JSON object), the clock, and the self-update state. + Restore(saved~ : String?, legacy~ : String?) + Started( + now~ : Int64, + last_check~ : Int64, + declined~ : Int32, + installed~ : Int32, + ) + /// The page measured itself: viewport size, and where the home grid is. + Measured( + vw~ : Int32, + vh~ : Int32, + grid_left~ : Double, + grid_top~ : Double, + grid_w~ : Double, + bottom_pad~ : Double, + ) + AppsLoaded(String?) + WidgetsLoaded(String?) + /// The shell's answer to `QueryLimits`. + LimitsKnown(Int32, String?) + /// A package changed: look at the app list again. + Reload + /// The Home button or intent. + GoHome + Back + WidgetAdded(Int32) + /// A long press on a native widget view lifts its slot. + WidgetMenu(Int32) + /// A press on the native view of the widget showing handles picks it up. + WidgetGrab(Int32) + NativeDrag(Double, Double) + NativeDrop(Bool) + /// The swipe the page saw: dx, dy, ms, whether the home is scrolled to the top, and + /// whether the drawer's list is at its end. + Touch( + dx~ : Double, + dy~ : Double, + ms~ : Int32, + home_top~ : Bool, + list_end~ : Bool, + ) + ReleaseFetched(String?) + VersionFetched(String?) + NoticeDone(Int32) + // ---- from handlers + Query(String) + Clear + WQuery(String) + WClear + OpenDrawer + CloseDrawer + OpenApp(Int32) + OpenFirst + OpenHome(Int32) + AddHome(Int32) + ToggleHome(Int32) + AppMenu(Int32) + AppInfoOf(Int32) + UninstallOf(Int32) + Menu + CloseSheet + PickApps + PickWidget + ChooseWidget(Int32) + ChooseFirstWidget + Remove(Int32) + /// Swap the slot with the one before it. + MoveEarlier(Int32) + InfoOf(Int32) + Settings + Wallpaper + Recents + CheckUpdates + Lift(Int32) + Grab(Int32) + ResizeBegin(Edge) + ResizeDone + /// Does nothing; stands in a chain to stop a tap reaching an element below. + Nop + /// The recogniser saw a drag / the pointer lift (see `input`). + Dragged(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double) + Released(moved~ : Bool, held~ : Bool) +} + +///| +#derive(Eq, Debug) +pub(all) enum Effect { + Launch(String) + AppInfo(String) + Uninstall(String) + AddWidget(String) + RemoveWidget(Int32) + OpenSettings + PickWallpaper + OpenRecents + Haptic + /// Fetch apps.json / widgets.json and answer `AppsLoaded` / `WidgetsLoaded`. + LoadApps + LoadWidgets + /// Ask the shell for a widget's limits and answer `LimitsKnown`. + QueryLimits(Int32) + SaveHome(String) + SaveLastCheck(Int64) + /// Send the message after this many ms. + Delay(Int32, Msg) + /// After this many ms, feed `Hold(token)` to `input` (the long-press timer). + HoldTimer(Int32, Int32) + FetchRelease(String) + FetchVersion(String) + InstallApk(String, Int32) + /// The drawer opened with its search in front: focus it and raise the keyboard. + FocusSearch + HideKeyboard + ScrollTop +} diff --git a/app/moon.pkg b/app/moon.pkg new file mode 100644 index 0000000..826e873 --- /dev/null +++ b/app/moon.pkg @@ -0,0 +1,9 @@ +import { + "experiments/launcher/grid", + "experiments/launcher/gesture", + "experiments/launcher/updater", + "experiments/launcher/vdom", + "experiments/launcher/jsonx", + "moonbitlang/core/cmp", + "moonbitlang/core/string", +} diff --git a/app/persist.mbt b/app/persist.mbt new file mode 100644 index 0000000..bf73923 --- /dev/null +++ b/app/persist.mbt @@ -0,0 +1,169 @@ +///| +/// The saved home layout as JSON: +/// `{"v":1,"slots":[{"kind":"app","str":COMPONENT,"x":-1,"y":-1}, +/// {"kind":"widget","str":LABEL,"wid":ID,"w":COLS,"rows":ROWS,"x":-1,"y":-1}]}`. +pub fn save_json(home : Array[@grid.Slot]) -> String { + let slots : Array[Json] = home.map(fn(s) { + match s.kind { + App => { "kind": "app", "str": s.str, "x": s.x, "y": s.y } + Widget => + { + "kind": "widget", + "str": s.str, + "wid": s.wid, + "w": s.w, + "rows": s.rows, + "x": s.x, + "y": s.y, + } + } + }) + Json::object({ "v": 1, "slots": Json::array(slots) }).stringify() +} + +///| +/// Read a saved layout; `None` if the text is not one. Slots without a name are +/// dropped, and no more than `home_cap` are kept. +pub fn load_json(text : String, next_key : Ref[Int32]) -> Array[@grid.Slot]? { + guard @jsonx.parse(text) is Some(j) else { return None } + guard @jsonx.get(j, "slots") is Some(Array(_)) else { return None } + let out : Array[@grid.Slot] = [] + for s in @jsonx.arr(j, "slots") { + let str = @jsonx.str(s, "str") + if str == "" || out.length() >= home_cap { + continue + } + let slot = if @jsonx.str(s, "kind") == "widget" { + @grid.Slot::widget( + str, + @jsonx.int(s, "wid"), + w=@cmp.maximum(0, @jsonx.int(s, "w")), + rows=@cmp.maximum(1, @jsonx.int(s, "rows", default=1)), + key=take_key(next_key), + ) + } else { + @grid.Slot::app(str, key=take_key(next_key)) + } + slot.x = @jsonx.int(s, "x", default=-1) + slot.y = @jsonx.int(s, "y", default=-1) + out.push(slot) + } + Some(out) +} + +///| +fn take_key(next_key : Ref[Int32]) -> Int32 { + let k = next_key.val + next_key.val = k + 1 + k +} + +///| +/// The WebView build kept its home in localStorage as `ultra.home.n` and, for slot i, +/// `ultra.home.{kind,str,wid,h,w,cx,cy}.i` (all strings; kind 1 is a widget, `h` its +/// height in px, `cx`/`cy` the pinned cell). `text` is those keys as a JSON object. Widget +/// heights in px become whole rows. +pub fn legacy_import(text : String, next_key : Ref[Int32]) -> Array[@grid.Slot] { + guard @jsonx.parse(text) is Some(kv) else { return [] } + fn num(k : String, i : Int32, d : Int32) -> Int32 { + match @jsonx.get(kv, "ultra.home.\{k}.\{i}") { + Some(String(s)) => @string.parse_int(s) catch { _ => d } + Some(Number(n, ..)) => n.to_int() + _ => d + } + } + + let n = num2(kv, "ultra.home.n") + let out : Array[@grid.Slot] = [] + for i in 0.. s + _ => "" + } + if str == "" || out.length() >= home_cap { + continue + } + let slot = if num("kind", i, 0) == 1 { + @grid.Slot::widget( + str, + num("wid", i, 0), + w=@cmp.maximum(0, num("w", i, 0)), + rows=@grid.widget_rows(num("h", i, 120)), + key=take_key(next_key), + ) + } else { + @grid.Slot::app(str, key=take_key(next_key)) + } + slot.x = num("cx", i, -1) + slot.y = num("cy", i, -1) + out.push(slot) + } + out +} + +///| +fn num2(kv : Json, key : String) -> Int32 { + match @jsonx.get(kv, key) { + Some(String(s)) => @string.parse_int(s) catch { _ => 0 } + Some(Number(n, ..)) => n.to_int() + _ => 0 + } +} + +///| +/// The apps.json the shell (or the demo) serves: `{"apps": [{"label", "component", +/// "icon", "system"}]}`, capped at `app_cap`. +pub fn parse_apps(text : String) -> Array[AppInfo]? { + guard @jsonx.parse(text) is Some(j) else { return None } + guard @jsonx.get(j, "apps") is Some(Array(_)) else { return None } + let out : Array[AppInfo] = [] + for a in @jsonx.arr(j, "apps") { + if out.length() >= app_cap { + break + } + out.push({ + label: @jsonx.str(a, "label"), + component: @jsonx.str(a, "component"), + icon: @jsonx.str(a, "icon"), + system: @jsonx.bool(a, "system"), + }) + } + Some(out) +} + +///| +/// widgets.json: `{"widgets": [{"label", "app", "provider", "icon", "h"}]}`. +pub fn parse_widgets(text : String) -> Array[WidgetInfo]? { + guard @jsonx.parse(text) is Some(j) else { return None } + guard @jsonx.get(j, "widgets") is Some(Array(_)) else { return None } + let out : Array[WidgetInfo] = [] + for w in @jsonx.arr(j, "widgets") { + if out.length() >= 256 { + break + } + out.push({ + label: @jsonx.str(w, "label"), + provider: @jsonx.str(w, "provider"), + icon: @jsonx.str(w, "icon"), + app: @jsonx.str(w, "app"), + h: @jsonx.int(w, "h"), + }) + } + Some(out) +} + +///| +/// The shell's `widgetLimits` JSON (`{"w","minW","minH","maxW","maxH","h","v"}`); +/// missing fields take the defaults. +pub fn parse_limits(text : String) -> Limits { + guard @jsonx.parse(text) is Some(j) else { return default_limits } + { + w: @jsonx.int(j, "w"), + min_w: @jsonx.int(j, "minW"), + min_h: @jsonx.int(j, "minH"), + max_w: @jsonx.int(j, "maxW"), + max_h: @jsonx.int(j, "maxH"), + h: @jsonx.bool(j, "h", default=true), + v: @jsonx.bool(j, "v", default=true), + } +} diff --git a/app/pkg.generated.mbti b/app/pkg.generated.mbti new file mode 100644 index 0000000..5c85a8b --- /dev/null +++ b/app/pkg.generated.mbti @@ -0,0 +1,243 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/launcher/app" + +import { + "experiments/launcher/gesture", + "experiments/launcher/grid", + "experiments/launcher/vdom", + "moonbitlang/core/debug", + "moonbitlang/core/ref", +} + +// Values +pub let app_cap : Int32 + +pub let default_limits : Limits + +pub fn handler_table(Array[@vdom.Node[Msg]]) -> Array[@vdom.Handlers[Msg]] + +pub let home_cap : Int32 + +pub fn input(Model, Array[@vdom.Handlers[Msg]], @gesture.Input) -> Array[Effect] + +pub fn key(Model, Array[@vdom.Handlers[Msg]], Array[Int32], Key) -> Array[Effect] + +pub fn legacy_import(String, @ref.Ref[Int32]) -> Array[@grid.Slot] + +pub fn load_json(String, @ref.Ref[Int32]) -> Array[@grid.Slot]? + +pub fn matches_query(String, String) -> Bool + +pub fn parse_apps(String) -> Array[AppInfo]? + +pub fn parse_limits(String) -> Limits + +pub fn parse_widgets(String) -> Array[WidgetInfo]? + +pub fn save_json(Array[@grid.Slot]) -> String + +pub fn typed(Model, Array[@vdom.Handlers[Msg]], Array[Int32], String) -> Array[Effect] + +pub fn update(Model, Msg) -> Array[Effect] + +pub fn view(Model) -> Array[@vdom.Node[Msg]] + +// Errors + +// Types and methods +pub(all) struct AppInfo { + label : String + component : String + icon : String + system : Bool +} + +pub(all) struct Carry { + dx : Double + dy : Double + mut cell : Int32 +} + +#derive(Eq, @debug.Debug) +pub(all) enum Edge { + Right + Bottom + Corner +} + +#derive(Eq, @debug.Debug) +pub(all) enum Effect { + Launch(String) + AppInfo(String) + Uninstall(String) + AddWidget(String) + RemoveWidget(Int32) + OpenSettings + PickWallpaper + OpenRecents + Haptic + LoadApps + LoadWidgets + QueryLimits(Int32) + SaveHome(String) + SaveLastCheck(Int64) + Delay(Int32, Msg) + HoldTimer(Int32, Int32) + FetchRelease(String) + FetchVersion(String) + InstallApk(String, Int32) + FocusSearch + HideKeyboard + ScrollTop +} + +pub(all) enum Key { + Enter + Escape +} + +pub(all) struct Limits { + w : Int32 + min_w : Int32 + min_h : Int32 + max_w : Int32 + max_h : Int32 + h : Bool + v : Bool +} + +pub(all) struct Model { + mut apps : Array[AppInfo] + mut loading : Bool + mut load_error : String + mut widgets : Array[WidgetInfo] + mut wloading : Bool + mut home : Array[@grid.Slot] + mut next_key : Int32 + mut cols : Int32 + mut nrows : Int32 + mut grid_left : Double + mut grid_top : Double + mut col_w : Double + mut query : String + mut wquery : String + mut drawer : Bool + mut picking : Bool + mut sheet : Sheet + mut gone : String + mut lifted : Int32 + mut resizing : Int32 + mut regrab : Bool + mut carry : Carry? + mut resize : ResizeDrag? + mut native_from : (Double, Double)? + mut chosen : Int32 + mut limits : Map[Int32, Limits] + mut notice : String + mut notice_gen : Int32 + mut installed : Int32 + mut declined : Int32 + mut checking : Bool + mut manual_check : Bool + mut apk_url : String? + mut release_tag : String + mut saved : String + mut dragged : Bool + mut fresh : Int32 + mut gesture : @gesture.State +} +pub fn Model::app_row(Self, String) -> Int32 +pub fn Model::first_match(Self) -> Int32 +pub fn Model::first_widget_match(Self) -> Int32 +pub fn Model::hidden(Self, Int32) -> Bool +pub fn Model::home_of(Self, Int32) -> Int32 +pub fn Model::new() -> Self +pub fn Model::packed(Self) -> @grid.Packed +pub fn Model::slot_of_widget(Self, Int32) -> Int32 +pub fn Model::widget_matches(Self, Int32) -> Bool + +#derive(Eq, @debug.Debug) +pub(all) enum Msg { + Restore(saved~ : String?, legacy~ : String?) + Started(now~ : Int64, last_check~ : Int64, declined~ : Int32, installed~ : Int32) + Measured(vw~ : Int32, vh~ : Int32, grid_left~ : Double, grid_top~ : Double, grid_w~ : Double, bottom_pad~ : Double) + AppsLoaded(String?) + WidgetsLoaded(String?) + LimitsKnown(Int32, String?) + Reload + GoHome + Back + WidgetAdded(Int32) + WidgetMenu(Int32) + WidgetGrab(Int32) + NativeDrag(Double, Double) + NativeDrop(Bool) + Touch(dx~ : Double, dy~ : Double, ms~ : Int32, home_top~ : Bool, list_end~ : Bool) + ReleaseFetched(String?) + VersionFetched(String?) + NoticeDone(Int32) + Query(String) + Clear + WQuery(String) + WClear + OpenDrawer + CloseDrawer + OpenApp(Int32) + OpenFirst + OpenHome(Int32) + AddHome(Int32) + ToggleHome(Int32) + AppMenu(Int32) + AppInfoOf(Int32) + UninstallOf(Int32) + Menu + CloseSheet + PickApps + PickWidget + ChooseWidget(Int32) + ChooseFirstWidget + Remove(Int32) + MoveEarlier(Int32) + InfoOf(Int32) + Settings + Wallpaper + Recents + CheckUpdates + Lift(Int32) + Grab(Int32) + ResizeBegin(Edge) + ResizeDone + Nop + Dragged(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double) + Released(moved~ : Bool, held~ : Bool) +} + +pub(all) struct ResizeDrag { + edge : Edge + slot : Int32 + left : Double + top : Double + mut cols : Int32 + mut rows : Int32 +} + +#derive(Eq, @debug.Debug) +pub(all) enum Sheet { + NoSheet + HomeMenu + Item(Int32) + DrawerApp(Int32) + WidgetPicker +} + +pub(all) struct WidgetInfo { + label : String + provider : String + icon : String + app : String + h : Int32 +} + +// Type aliases + +// Traits diff --git a/app/sim_wbtest.mbt b/app/sim_wbtest.mbt new file mode 100644 index 0000000..367a514 --- /dev/null +++ b/app/sim_wbtest.mbt @@ -0,0 +1,904 @@ +///| +/// A headless harness: a model, its rendered tree, and pointer input aimed at elements +/// found by class and text, as the page would aim it. + +///| +let apps_json : String = + #|{"apps":[ + #|{"label":"Calculator","component":"c.calc/.Main","icon":"i1"}, + #|{"label":"Calendar","component":"c.cal/.Main","icon":"i2"}, + #|{"label":"Chrome","component":"c.chrome/.Main","icon":"i3"}, + #|{"label":"Gmail","component":"c.gmail/.Main","icon":"i4"}, + #|{"label":"Phone","component":"c.phone/.Main","icon":"i5","system":true}, + #|{"label":"Weather","component":"c.weather/.Main","icon":"i6"}]} + +///| +let widgets_json : String = + #|{"widgets":[ + #|{"label":"Clock","app":"Clock","provider":"c.clock/.W","icon":"w1","h":140}, + #|{"label":"Weather","app":"Google","provider":"c.google/.W","icon":"w2","h":120}, + #|{"label":"Calendar","app":"Calendar","provider":"c.cal/.W","icon":"w3","h":200}]} + +///| +struct Sim { + m : Model + mut tree : Array[@vdom.Node[Msg]] + mut table : Array[@vdom.Handlers[Msg]] + log : Array[Effect] + mut last_x : Double + mut last_y : Double +} + +///| +fn Sim::new() -> Sim { + let m = Model::new() + let s = { m, tree: [], table: [], log: [], last_x: 0.0, last_y: 0.0, } + s.run(update(m, Restore(saved=None, legacy=None))) + s.send( + Measured( + vw=390, + vh=800, + grid_left=16.0, + grid_top=150.0, + grid_w=358.0, + bottom_pad=24.0, + ), + ) + s.send(AppsLoaded(Some(apps_json))) + s +} + +///| +fn Sim::refresh(self : Sim) -> Unit { + self.tree = view(self.m) + self.table = handler_table(self.tree) +} + +///| +fn Sim::run(self : Sim, fx : Array[Effect]) -> Unit { + for e in fx { + self.log.push(e) + } + self.refresh() +} + +///| +fn Sim::send(self : Sim, msg : Msg) -> Unit { + self.run(update(self.m, msg)) +} + +///| +fn text_of(n : @vdom.Node[Msg]) -> String { + match n { + Text(s) => s + El(e) => e.children.map(text_of).join("") + } +} + +///| +/// The chain (handler numbers, innermost first) of the first element matching `pred`. +fn Sim::chain_where( + self : Sim, + pred : (@vdom.Element[Msg]) -> Bool, + from~ : Int32 = 0, +) -> Array[Int32]? { + let mut counter = 0 + let mut found : Array[Int32]? = None + let stack : Array[Int32] = [] + fn walk(n : @vdom.Node[Msg]) -> Unit { + if found is Some(_) { + return + } + if n is El(e) { + let has = !e.handlers.is_empty() + if has { + stack.push(counter) + counter += 1 + } + if pred(e) { + found = Some(stack.rev()) + return + } + for c in e.children { + walk(c) + } + if has { + ignore(stack.pop()) + } + } + } + + let mut top = 0 + for n in self.tree { + if top < from { + walk_count(n, fn() { counter += 1 }) + } else { + walk(n) + } + top += 1 + } + found +} + +///| +/// Count the handler-bearing elements below a node without matching (to keep numbering). +fn walk_count(n : @vdom.Node[Msg], bump : () -> Unit) -> Unit { + if n is El(e) { + if !e.handlers.is_empty() { + bump() + } + for c in e.children { + walk_count(c, bump) + } + } +} + +///| +fn Sim::chain( + self : Sim, + class : String, + label~ : String = "", + from~ : Int32 = 0, +) -> Array[Int32] { + match + self.chain_where(from~, fn(e) { + e.classes.contains(class) && + (label == "" || text_of(El(e)).contains(label)) + }) { + Some(c) => c + None => abort("no .\{class} \{label} in the tree") + } +} + +///| +fn Sim::feed(self : Sim, inp : @gesture.Input) -> Unit { + self.run(input(self.m, self.table, inp)) +} + +///| +fn Sim::press( + self : Sim, + chain : Array[Int32], + x~ : Double = 0.0, + y~ : Double = 0.0, +) -> Unit { + self.feed(Down(x~, y~, chain~)) + self.last_x = x + self.last_y = y +} + +///| +fn Sim::hold(self : Sim) -> Unit { + let mut token = -1 + for e in self.log { + if e is HoldTimer(_, t) { + token = t + } + } + self.feed(Hold(token)) +} + +///| +fn Sim::move_to(self : Sim, x : Double, y : Double) -> Unit { + self.feed(Move(x~, y~)) + self.last_x = x + self.last_y = y +} + +///| +fn Sim::release(self : Sim) -> Unit { + self.feed(Up(x=self.last_x, y=self.last_y)) +} + +///| +fn Sim::tap( + self : Sim, + class : String, + label~ : String = "", + from~ : Int32 = 0, +) -> Unit { + self.press(self.chain(class, label~, from~)) + self.release() +} + +///| +fn Sim::long_press( + self : Sim, + chain : Array[Int32], + x~ : Double = 0.0, + y~ : Double = 0.0, +) -> Unit { + self.press(chain, x~, y~) + self.hold() + self.release() +} + +///| +fn Sim::home_names(self : Sim) -> Array[String] { + self.m.home.map(fn(s) { + if s.kind == Widget { + "[" + s.str + "]" + } else { + self.m.apps[self.m.app_row(s.str)].label + } + }) +} + +///| +/// The sheet (dialog) as HTML. +fn Sim::sheet_html(self : Sim) -> String { + for n in self.tree { + if n is El(e) && e.classes.contains("sheet") { + return @vdom.to_html(n) + } + } + "" +} + +///| +fn Sim::has_effect(self : Sim, e : Effect) -> Bool { + self.log.contains(e) +} + +///| +/// Centre of the cell (col, row) in viewport px. +fn cell_center(col : Int32, row : Int32) -> (Double, Double) { + ( + 16.0 + col.to_double() * (65.2 + 8.0) + 32.6, + 150.0 + row.to_double() * 72.0 + 32.0, + ) +} + +///| +/// Add apps to the home screen through the long-press menu and the drawer's pick mode. +fn Sim::add_apps(self : Sim, labels : Array[String]) -> Unit { + self.long_press(self.chain("home")) + self.tap("sheet-item", label="Add apps") + for l in labels { + self.tap("tile", label=l, from=1) // the drawer's, not the home screen's under it + } + self.tap("btn", label="Done") +} + +///| +test "boot: blank home with a hint, apps load" { + let s = Sim::new() + assert_true(s.has_effect(LoadApps)) + assert_eq(s.m.apps.length(), 6) + assert_eq(s.m.home.length(), 0) + let html = @vdom.to_html(s.tree[0]) + assert_true(html.contains("Swipe down for all apps")) +} + +///| +test "long press on the blank home opens the menu; Check for updates closes it" { + let s = Sim::new() + s.long_press(s.chain("home")) + assert_eq(s.m.sheet, HomeMenu) + assert_true(s.has_effect(Haptic)) + s.tap("sheet-item", label="Check for updates") + assert_eq(s.m.sheet, NoSheet) + assert_true(s.has_effect(FetchRelease(@updater.release_api))) + assert_eq(s.m.notice, "Checking for updates…") +} + +///| +test "add apps through the drawer's pick mode" { + let s = Sim::new() + s.long_press(s.chain("home")) + s.tap("sheet-item", label="Add apps") + assert_true(s.m.drawer && s.m.picking) + assert_true(!s.has_effect(FocusSearch)) // picking is for scrolling: no keyboard + s.tap("tile", label="Chrome", from=1) + s.tap("tile", label="Gmail", from=1) + s.tap("tile", label="Phone", from=1) + s.tap("tile", label="Gmail", from=1) // toggled off again + s.tap("btn", label="Done") + assert_true(!s.m.drawer) + assert_eq(s.home_names(), ["Chrome", "Phone"]) +} + +///| +test "swipe down opens the drawer, swipe up closes it" { + let s = Sim::new() + s.send(Touch(dx=3.0, dy=120.0, ms=200, home_top=true, list_end=false)) + assert_true(s.m.drawer) + assert_true(s.has_effect(FocusSearch)) + s.send(Touch(dx=3.0, dy=-120.0, ms=200, home_top=false, list_end=false)) + assert_true(s.m.drawer) // the list isn't at its end yet + s.send(Touch(dx=3.0, dy=-120.0, ms=200, home_top=false, list_end=true)) + assert_true(!s.m.drawer) + assert_true(s.has_effect(HideKeyboard)) + s.send(Touch(dx=3.0, dy=40.0, ms=200, home_top=true, list_end=false)) + assert_true(!s.m.drawer) // too short +} + +///| +test "the home search pill opens the drawer" { + let s = Sim::new() + s.tap("search-pill") + assert_true(s.m.drawer && !s.m.picking) + assert_true(s.has_effect(FocusSearch)) +} + +///| +test "search filters the drawer; Enter opens the first match" { + let s = Sim::new() + s.send(OpenDrawer) + let names = fn() { + let out : Array[String] = [] + for n in s.tree { + ignore(n) + } + for a in s.m.apps { + if matches_query(a.label, s.m.query) { + out.push(a.label) + } + } + out + } + assert_eq(names().length(), 6) + let input_chain = s.chain("input") + s.run(typed(s.m, s.table, input_chain, "ca")) + assert_eq( + names(), + ["Calculator", "Calendar", "Camera".to_string()].filter(fn(x) { + x != "Camera" + }), + ) + s.run(typed(s.m, s.table, input_chain, " CAL")) + assert_eq(names(), ["Calculator", "Calendar"]) + s.run(key(s.m, s.table, input_chain, Enter)) + assert_true(s.has_effect(Launch("c.calc/.Main"))) + assert_true(!s.m.drawer) + assert_eq(s.m.query, "") +} + +///| +test "Enter with no search text or no match opens nothing" { + let s = Sim::new() + s.send(OpenDrawer) + let c = s.chain("input") + s.run(key(s.m, s.table, c, Enter)) + assert_true(s.m.drawer) + s.run(typed(s.m, s.table, c, "zzz")) + s.run(key(s.m, s.table, c, Enter)) + assert_true(s.m.drawer) + assert_true(@vdom.to_html(s.tree[1]).contains("No apps match.")) + s.run(key(s.m, s.table, c, Escape)) + assert_eq(s.m.query, "") +} + +///| +test "tapping an app in the drawer launches it" { + let s = Sim::new() + s.send(OpenDrawer) + s.tap("tile", label="Gmail", from=1) + assert_true(s.has_effect(Launch("c.gmail/.Main"))) + assert_true(!s.m.drawer) +} + +///| +test "long press on a drawer app: menu; system apps have no uninstall" { + let s = Sim::new() + s.send(OpenDrawer) + s.long_press(s.chain("tile", label="Gmail", from=1)) + assert_eq(s.m.sheet, DrawerApp(3)) + let html = s.sheet_html() + assert_true(html.contains("Add to home")) + assert_true(html.contains("App info")) + assert_true(html.contains("Uninstall")) + s.tap("sheet-item", label="Add to home") + assert_eq(s.home_names(), ["Gmail"]) + s.long_press(s.chain("tile", label="Phone", from=1)) + assert_true(!s.sheet_html().contains("Uninstall")) + s.tap("sheet-overlay") + assert_eq(s.m.sheet, NoSheet) + s.long_press(s.chain("tile", label="Gmail", from=1)) + assert_true(s.sheet_html().contains("Remove from home")) +} + +///| +test "uninstall asks the shell; the slot goes when the app leaves the list" { + let s = Sim::new() + s.add_apps(["Gmail"]) + s.send(OpenDrawer) + s.long_press(s.chain("tile", label="Gmail", from=1)) + s.tap("sheet-item", label="Uninstall") + assert_true(s.has_effect(Uninstall("c.gmail/.Main"))) + assert_eq(s.home_names(), ["Gmail"]) + s.send( + AppsLoaded( + Some( + "{\"apps\":[{\"label\":\"Chrome\",\"component\":\"c.chrome/.Main\",\"icon\":\"\"}]}", + ), + ), + ) + assert_eq(s.m.home.length(), 0) +} + +///| +test "home slots: tap launches, long press without moving opens the menu" { + let s = Sim::new() + s.add_apps(["Chrome", "Gmail", "Phone"]) + s.tap("tile", label="Gmail") + assert_true(s.has_effect(Launch("c.gmail/.Main"))) + s.long_press(s.chain("tile", label="Gmail")) + assert_eq(s.m.sheet, Item(1)) + s.tap("sheet-item", label="Move earlier") + assert_eq(s.home_names(), ["Gmail", "Chrome", "Phone"]) + s.long_press(s.chain("tile", label="Gmail")) + s.tap("sheet-item", label="Move later") + assert_eq(s.home_names(), ["Chrome", "Gmail", "Phone"]) + s.long_press(s.chain("tile", label="Chrome")) + assert_true(!s.sheet_html().contains("Move earlier")) + s.tap("sheet-item", label="Remove from home") + assert_eq(s.home_names(), ["Gmail", "Phone"]) +} + +///| +test "dragging a home app over another reorders; a drag does not open the menu" { + let s = Sim::new() + s.add_apps(["Chrome", "Gmail", "Phone"]) + let (ax, ay) = cell_center(1, 0) + let (bx, by) = cell_center(0, 0) + s.press(s.chain("tile", label="Gmail"), x=ax, y=ay) + s.hold() + assert_eq(s.m.lifted, 1) + s.move_to(bx + 5.0, by) + s.move_to(bx, by) + s.release() + assert_eq(s.home_names(), ["Gmail", "Chrome", "Phone"]) + assert_eq(s.m.sheet, NoSheet) + assert_eq(s.m.lifted, -1) +} + +///| +test "an app dropped in an empty cell stays there; the rest stay packed" { + let s = Sim::new() + s.add_apps(["Chrome", "Gmail", "Phone"]) + let (px, py) = cell_center(2, 0) + let (tx, ty) = cell_center(3, 2) + s.press(s.chain("tile", label="Phone"), x=px, y=py) + s.hold() + s.move_to(tx - 30.0, ty) + s.move_to(tx, ty) + s.release() + assert_eq(s.home_names(), ["Chrome", "Gmail", "Phone"]) + assert_eq((s.m.home[2].x, s.m.home[2].y), (3, 2)) + let cells = s.m.packed().cells + assert_eq(cells[0], Some({ col: 0, row: 0, w: 1, h: 1, })) + assert_eq(cells[2], Some({ col: 3, row: 2, w: 1, h: 1, })) + // and it survives a save and a load + let back = load_json(save_json(s.m.home), Ref(1)).unwrap() + assert_eq((back[2].x, back[2].y), (3, 2)) +} + +///| +test "dropping a pinned app onto another pinned one moves that one on" { + let s = Sim::new() + s.add_apps(["Chrome", "Gmail"]) + for (label, col, row) in [("Chrome", 3, 1), ("Gmail", 3, 3)] { + let from = cell_center(0, 0) // Gmail flows up into the first cell once Chrome is pinned + let (fx, fy) = from + let (tx, ty) = cell_center(col, row) + s.press(s.chain("tile", label~), x=fx, y=fy) + s.hold() + s.move_to(tx, ty) + s.release() + } + assert_eq((s.m.home[0].x, s.m.home[0].y), (3, 1)) + assert_eq((s.m.home[1].x, s.m.home[1].y), (3, 3)) + // drag Gmail on top of Chrome's cell: Chrome is unpinned + let (gx, gy) = cell_center(3, 3) + let (cx, cy) = cell_center(3, 2) // a free cell next to it + s.press(s.chain("tile", label="Gmail"), x=gx, y=gy) + s.hold() + s.move_to(cx, cy) + s.release() + assert_eq((s.m.home[1].x, s.m.home[1].y), (3, 2)) +} + +///| +test "add a widget: picker search, choose, shell adds it" { + let s = Sim::new() + s.add_apps(["Chrome"]) + s.long_press(s.chain("home")) + s.tap("sheet-item", label="Add widget") + assert_true(s.has_effect(LoadWidgets)) + assert_true(s.sheet_html().contains("Loading widgets")) + s.send(WidgetsLoaded(Some(widgets_json))) + let names = fn() { + let out : Array[String] = [] + for i in 0.. @grid.Slot { + @grid.Slot::app(c) +} + +///| +test "load_json rejects what is not a layout and drops nameless slots" { + assert_true(load_json("nope", Ref(1)) is None) + assert_true(load_json("{}", Ref(1)) is None) + let r = load_json( + "{\"slots\":[{\"kind\":\"app\"},{\"kind\":\"app\",\"str\":\"a\"}]}", + Ref(1), + ).unwrap() + assert_eq(r.length(), 1) +} + +///| +test "self-update: automatic check, newer build, install" { + let s = Sim::new() + s.send(Started(now=100000000L, last_check=0L, declined=-1, installed=10)) + assert_true(s.has_effect(SaveLastCheck(100000000L))) + assert_true(s.has_effect(FetchRelease(@updater.release_api))) + s.send( + ReleaseFetched( + Some( + "{\"tag_name\":\"build-12\",\"assets\":[{\"name\":\"version.json\",\"browser_download_url\":\"u/v\"},{\"name\":\"ultra-launcher.apk\",\"browser_download_url\":\"u/a\"}]}", + ), + ), + ) + assert_true(s.has_effect(FetchVersion("u/v"))) + s.send(VersionFetched(Some("{\"versionCode\":12}"))) + assert_true(s.has_effect(InstallApk("u/a", 12))) + assert_eq(s.m.notice, "Downloading launcher update (build 12)…") + assert_true(!s.m.checking) +} + +///| +test "self-update: up to date is silent unless asked; declined builds are not offered" { + let rel = + #|{"tag_name":"build-10","assets":[{"name":"version.json","browser_download_url":"u/v"},{"name":"ultra-launcher.apk","browser_download_url":"u/a"}]} + let s = Sim::new() + s.send(Started(now=100000000L, last_check=0L, declined=-1, installed=10)) + s.send(ReleaseFetched(Some(rel))) + s.send(VersionFetched(Some("{\"versionCode\":10}"))) + assert_eq(s.m.notice, "") + assert_true(s.log.filter(fn(e) { e is InstallApk(_, _) }).length() == 0) + // manual says so + s.send(CheckUpdates) + s.send(ReleaseFetched(Some(rel))) + s.send(VersionFetched(Some("{\"versionCode\":10}"))) + assert_eq(s.m.notice, "ultra Home is up to date (build 10)") + // a declined build: silent for automatic checks, offered again when asked + let s2 = Sim::new() + s2.send(Started(now=100000000L, last_check=0L, declined=11, installed=10)) + s2.send(ReleaseFetched(Some(rel))) + s2.send(VersionFetched(Some("{\"versionCode\":11}"))) + assert_true(s2.log.filter(fn(e) { e is InstallApk(_, _) }).length() == 0) + s2.send(CheckUpdates) + s2.send(ReleaseFetched(Some(rel))) + s2.send(VersionFetched(Some("{\"versionCode\":11}"))) + assert_true(s2.has_effect(InstallApk("u/a", 11))) +} + +///| +test "self-update: recent check is skipped; failures and the tag fallback" { + let s = Sim::new() + s.send(Started(now=1000L, last_check=900L, declined=-1, installed=10)) + assert_true(!s.has_effect(FetchRelease(@updater.release_api))) + s.send(CheckUpdates) + s.send(CheckUpdates) // already checking + assert_eq(s.m.notice, "Already checking for updates") + s.send(ReleaseFetched(None)) + assert_eq(s.m.notice, "Couldn't check for updates") + assert_true(!s.m.checking) + // version.json unreadable: the release tag says the build number + s.send(CheckUpdates) + s.send( + ReleaseFetched( + Some( + "{\"tag_name\":\"build-20\",\"assets\":[{\"name\":\"version.json\",\"browser_download_url\":\"u/v\"},{\"name\":\"ultra-launcher.apk\",\"browser_download_url\":\"u/a\"}]}", + ), + ), + ) + s.send(VersionFetched(None)) + assert_true(s.has_effect(InstallApk("u/a", 20))) +} + +///| +test "menu items reach the shell" { + let s = Sim::new() + s.long_press(s.chain("home")) + s.tap("sheet-item", label="Wallpaper") + assert_true(s.has_effect(PickWallpaper)) + s.long_press(s.chain("home")) + s.tap("sheet-item", label="Settings") + assert_true(s.has_effect(OpenSettings)) + s.tap("panel-btn") + assert_true(s.has_effect(OpenRecents)) +} + +///| +test "app info for a home slot" { + let s = Sim::new() + s.add_apps(["Chrome"]) + s.long_press(s.chain("tile", label="Chrome")) + s.tap("sheet-item", label="App info") + assert_true(s.has_effect(AppInfo("c.chrome/.Main"))) +} + +///| +test "view snapshot: home with an app" { + let s = Sim::new() + s.add_apps(["Chrome"]) + inspect( + @vdom.to_html(s.tree[0]), + content=( + #|
+ #|
+ #| + #|
+ #| + #|
    + #|
  • + #| + #| Chrome + #|
  • + #|
+ #|
+ ), + ) +} diff --git a/app/update.mbt b/app/update.mbt new file mode 100644 index 0000000..fe6370b --- /dev/null +++ b/app/update.mbt @@ -0,0 +1,815 @@ +///| +fn trimmed(s : String) -> String { + s.trim().to_owned() +} + +///| +/// The lower-cased, trimmed search text matches the label. +pub fn matches_query(label : String, query : String) -> Bool { + let q = trimmed(query).to_lower() + q == "" || label.to_lower().contains(q) +} + +///| +pub fn Model::app_row(self : Model, component : String) -> Int32 { + for i in 0.. Int32 { + let comp = self.apps[row].component + for i in 0.. Int32 { + for i in 0.. Int32 { + for i in 0.. Bool { + matches_query(self.widgets[i].label, self.wquery) || + ( + matches_query(self.widgets[i].app, self.wquery) && + trimmed(self.wquery) != "" + ) +} + +///| +pub fn Model::first_widget_match(self : Model) -> Int32 { + for i in 0.. Bool { + self.home[i].kind == App && self.app_row(self.home[i].str) < 0 +} + +///| +pub fn Model::packed(self : Model) -> @grid.Packed { + @grid.pack(self.home, self.cols, self.nrows, hidden=fn(i) { self.hidden(i) }) +} + +///| +fn Model::say(self : Model, text : String, fx : Array[Effect]) -> Unit { + self.notice = text + self.notice_gen += 1 + fx.push(Delay(1800, NoticeDone(self.notice_gen))) +} + +///| +fn Model::push_slot(self : Model, s : @grid.Slot) -> Unit { + self.home.push(s) +} + +///| +fn Model::new_key(self : Model) -> Int32 { + let k = self.next_key + self.next_key += 1 + k +} + +///| +fn Model::remove_slot(self : Model, at : Int32, fx : Array[Effect]) -> Unit { + if at < 0 || at >= self.home.length() { + return + } + if self.home[at].kind == Widget { + fx.push(RemoveWidget(self.home[at].wid)) + } + ignore(self.home.remove(at)) + if self.lifted == at { + self.lifted = -1 + } else if self.lifted > at { + self.lifted -= 1 + } + if self.resizing == at { + self.resizing = -1 + } else if self.resizing > at { + self.resizing -= 1 + } +} + +///| +fn Model::add_app(self : Model, row : Int32, fx : Array[Effect]) -> Unit { + if self.home_of(row) >= 0 { + self.say("Already on the home screen", fx) + } else if self.home.length() >= home_cap { + self.say("The home screen is full", fx) + } else { + self.push_slot( + @grid.Slot::app(self.apps[row].component, key=self.new_key()), + ) + self.say("Added to home", fx) + } +} + +///| +/// Once an app uninstalled from the drawer is out of the list, take it off home. +fn Model::drop_gone(self : Model, fx : Array[Effect]) -> Unit { + if self.gone == "" { + return + } + if self.app_row(self.gone) >= 0 { + return + } + for i in 0.. Unit { + if self.drawer { + fx.push(HideKeyboard) + } + self.query = "" + self.drawer = false + self.picking = false + self.sheet = NoSheet + self.lifted = -1 + self.resizing = -1 + self.regrab = false + self.carry = None + self.resize = None +} + +///| +fn Model::open_drawer(self : Model, fx : Array[Effect]) -> Unit { + if self.sheet == NoSheet && !self.drawer { + self.drawer = true + fx.push(FocusSearch) + } +} + +///| +fn Model::close_drawer(self : Model, fx : Array[Effect]) -> Unit { + if self.drawer && self.sheet == NoSheet { + self.drawer = false + self.picking = false + self.query = "" + fx.push(HideKeyboard) + } +} + +// ---- dragging ----------------------------------------------------------------- + +///| +/// The box (px, viewport) of slot `i`, from the packing. +fn Model::slot_box( + self : Model, + packed : @grid.Packed, + i : Int32, +) -> (Double, Double, Double, Double)? { + match packed.cells[i] { + Some(c) => { + let (x, y, w, h) = @grid.box(c, self.col_w) + Some((x + self.grid_left, y + self.grid_top, w, h)) + } + None => None + } +} + +///| +fn inside(b : (Double, Double, Double, Double), x : Double, y : Double) -> Bool { + x >= b.0 && x <= b.0 + b.2 && y >= b.1 && y <= b.1 + b.3 +} + +///| +/// The slot (not the lifted one) under a point, or -1. +fn Model::slot_at( + self : Model, + packed : @grid.Packed, + x : Double, + y : Double, +) -> Int32 { + for i in 0.. Unit { + if self.lifted < 0 || self.lifted >= self.home.length() || self.col_w <= 0.0 { + return + } + let packed = self.packed() + let lifted = self.home[self.lifted] + let carry = match self.carry { + Some(c) => c + None => { + let (bx, by) = match self.slot_box(packed, self.lifted) { + Some(b) => (b.0, b.1) + None => (x0, y0) + } + let c = { dx: x0 - bx, dy: y0 - by, cell: -1, } + self.carry = Some(c) + c + } + } + let widget = lifted.kind == Widget + if !widget && self.slot_box(packed, self.lifted) is Some(b) && inside(b, x, y) { + return + } + let half_w = self.col_w / 2.0 + let half_h = @grid.cell_px.to_double() / 2.0 + let (fc, fr) = @grid.cell_at( + x - self.grid_left - half_w, + y - self.grid_top - half_h, + self.col_w, + ) + let mut to = self.slot_at(packed, x, y) + if to < 0 { + let cx = self.grid_left + + fc.to_double() * (self.col_w + @grid.col_gap.to_double()) + + half_w + let cy = self.grid_top + + fr.to_double() * (@grid.cell_px + @grid.row_gap).to_double() + + half_h + to = self.slot_at(packed, cx, cy) + } + if to >= 0 && !widget { + carry.cell = -1 + lifted.x = -1 // back into the flow, at that place in the order + lifted.y = -1 + @grid.move_slot(self.home, self.lifted, to) + self.lifted = to + return + } + let grid_bottom = self.grid_top + + (packed.rows * (@grid.cell_px + @grid.row_gap)).to_double() + if y > grid_bottom { + return // below the grid + } + let (col, row) = @grid.cell_at( + x - self.grid_left - carry.dx, + y - self.grid_top - carry.dy, + self.col_w, + ) + let cell = row * 64 + @cmp.minimum(col, 63) + if cell != carry.cell { + carry.cell = cell + @grid.pin(self.home, self.lifted, col, row, self.cols, self.nrows) + } +} + +///| +/// The pointer is up. Letting go without moving opens the item's menu (a widget gets +/// resize handles instead); letting go of a dragged one just drops it, and whatever it +/// then covers moves on to free cells. +fn Model::drop_lifted(self : Model, moved : Bool) -> Unit { + self.carry = None + if self.lifted < 0 || self.lifted >= self.home.length() { + self.lifted = -1 + self.regrab = false + return + } + let s = self.home[self.lifted] + if s.x >= 0 { + @grid.clear_cells(self.home, self.lifted, self.cols) + } + if !moved || self.regrab { + match s.kind { + Widget => self.resizing = self.lifted + App => self.sheet = Item(self.lifted) + } + } + self.lifted = -1 + self.regrab = false +} + +///| +fn Model::begin_resize(self : Model, edge : Edge, fx : Array[Effect]) -> Unit { + let i = self.resizing + if i < 0 || i >= self.home.length() { + return + } + let s = self.home[i] + let (left, top) = match self.slot_box(self.packed(), i) { + Some(b) => (b.0, b.1) + None => (self.grid_left, self.grid_top) + } + self.resize = Some({ + edge, + slot: i, + left, + top, + cols: s.cols(self.cols), + rows: s.height(), + }) + fx.push(QueryLimits(s.wid)) +} + +///| +/// Dragging a handle snaps the widget to whole columns and rows, within its limits. +fn Model::drag_resize( + self : Model, + r : ResizeDrag, + x : Double, + y : Double, + fx : Array[Effect], +) -> Unit { + if r.slot >= self.home.length() || self.col_w <= 0.0 { + return + } + let s = self.home[r.slot] + let lim = self.limits.get(s.wid).unwrap_or(default_limits) + let n = self.cols + let mut cols = r.cols + let mut rows = r.rows + if r.edge != Bottom && lim.h { + cols = @grid.fit( + x - r.left, + 1, + n, + self.col_w, + @grid.col_gap.to_double(), + lim.min_w, + lim.max_w, + ) + } + if r.edge != Right && lim.v { + rows = @grid.fit( + y - r.top, + 1, + 20, + @grid.cell_px.to_double(), + @grid.row_gap.to_double(), + lim.min_h, + lim.max_h, + ) + } + if cols == r.cols && rows == r.rows { + return + } + r.cols = cols + r.rows = rows + fx.push(Haptic) + s.w = if cols >= n { 0 } else { cols } + s.rows = rows + if s.x >= 0 { + @grid.pin(self.home, r.slot, s.x, s.y, self.cols, self.nrows) + @grid.clear_cells(self.home, r.slot, self.cols) + } +} + +// ---- update ------------------------------------------------------------------- + +///| +/// Apply a message to the model; returns the effects for the platform to run. The +/// saved layout is kept in step automatically (a `SaveHome` whenever it changed). +pub fn update(m : Model, msg : Msg) -> Array[Effect] { + let fx : Array[Effect] = [] + step(m, msg, fx) + let json = save_json(m.home) + if json != m.saved { + m.saved = json + fx.push(SaveHome(json)) + } + fx +} + +///| +fn Model::choose_widget(self : Model, i : Int32, fx : Array[Effect]) -> Unit { + if i >= 0 && i < self.widgets.length() { + if self.home.length() < home_cap { + self.chosen = i + fx.push(AddWidget(self.widgets[i].provider)) + } else { + self.say("The home screen is full", fx) + } + self.sheet = NoSheet + } +} + +///| +fn step(m : Model, msg : Msg, fx : Array[Effect]) -> Unit { + match msg { + Restore(saved~, legacy~) => { + let next = Ref(m.next_key) + let mut slots = None + if saved is Some(text) { + slots = load_json(text, next) + if slots is Some(_) { + m.saved = text + } + } + if slots is None && legacy is Some(text) { + slots = Some(legacy_import(text, next)) + } + if slots is Some(s) { + m.home = s + } + m.next_key = next.val + fx.push(LoadApps) + } + Started(now~, last_check~, declined~, installed~) => { + m.installed = installed + m.declined = declined + if @updater.should_check(now, last_check, manual=false) && !m.checking { + m.checking = true + m.manual_check = false + fx.push(SaveLastCheck(now)) + fx.push(FetchRelease(@updater.release_api)) + } + } + Measured(vw~, vh~, grid_left~, grid_top~, grid_w~, bottom_pad~) => { + m.cols = @grid.columns_for(vw) + m.grid_left = grid_left + m.grid_top = grid_top + m.col_w = @grid.column_width(grid_w, m.cols) + m.nrows = @grid.rows_fit(vh.to_double() - bottom_pad - grid_top) + } + AppsLoaded(text) => { + m.loading = false + match text.bind(parse_apps) { + Some(apps) => { + m.apps = apps + m.load_error = "" + m.drop_gone(fx) + } + None => m.load_error = "no response" + } + if m.sheet is DrawerApp(_) { + m.sheet = NoSheet // rows may have moved + } + } + WidgetsLoaded(text) => { + m.wloading = false + m.widgets = text.bind(parse_widgets).unwrap_or([]) + } + LimitsKnown(wid, text) => { + let lim = match text { + Some(t) => parse_limits(t) + None => default_limits + } + m.limits[wid] = lim + if m.fresh == wid { + m.fresh = -1 + let i = m.slot_of_widget(wid) + if i >= 0 && m.col_w > 0.0 { + m.home[i].w = @grid.widget_cols(lim.w, m.col_w, m.cols) + } + } + } + Reload => fx.push(LoadApps) + GoHome => { + m.close_all(fx) + fx.push(ScrollTop) + } + Back => + if m.lifted >= 0 { + m.lifted = -1 + m.regrab = false + m.carry = None + } else if m.resizing >= 0 { + m.resizing = -1 + } else if m.sheet != NoSheet { + m.sheet = NoSheet + } else if m.drawer { + m.drawer = false + m.picking = false + m.query = "" + fx.push(HideKeyboard) + } + WidgetAdded(id) => + if m.chosen >= 0 && + m.chosen < m.widgets.length() && + m.home.length() < home_cap { + let w = m.widgets[m.chosen] + m.push_slot( + @grid.Slot::widget( + w.label, + id, + rows=@grid.widget_rows(w.h), + key=m.new_key(), + ), + ) + m.chosen = -1 + m.fresh = id + fx.push(QueryLimits(id)) + } + WidgetMenu(wid) => { + let i = m.slot_of_widget(wid) + if i >= 0 && !m.drawer && m.sheet == NoSheet { + m.resizing = -1 + m.regrab = false + m.lifted = i + m.native_from = None + } + } + WidgetGrab(wid) => { + let i = m.slot_of_widget(wid) + if i >= 0 && i == m.resizing && !m.drawer && m.sheet == NoSheet { + m.resizing = -1 + m.regrab = true + m.lifted = i + m.native_from = None + } + } + NativeDrag(x, y) => { + m.dragged = true + let (x0, y0) = match m.native_from { + Some(p) => p + None => { + m.native_from = Some((x, y)) + (x, y) + } + } + m.drag_lifted(x, y, x0, y0) + } + NativeDrop(moved) => { + m.native_from = None + m.drop_lifted(moved) + } + Touch(dx~, dy~, ms~, home_top~, list_end~) => + if !m.dragged && m.lifted < 0 && m.sheet == NoSheet { + match @gesture.classify_swipe(dx, dy, ms) { + Some(Down) => if !m.drawer && home_top { m.open_drawer(fx) } + Some(Up) => if m.drawer && list_end { m.close_drawer(fx) } + None => () + } + } + ReleaseFetched(text) => { + let release = text.bind(@updater.parse_release) + match release { + Some({ version_url: Some(v), apk_url: Some(a), tag, }) => { + m.apk_url = Some(a) + m.release_tag = tag + fx.push(FetchVersion(v)) + } + _ => { + m.checking = false + if m.manual_check { + m.say("Couldn't check for updates", fx) + } + } + } + } + VersionFetched(text) => { + m.checking = false + let latest = match text.bind(@updater.parse_version) { + Some(v) => Some(v) + None => @updater.tag_version(m.release_tag) + } + match (latest, m.apk_url) { + (Some(latest), Some(url)) => + match + @updater.decide( + latest, + m.installed, + m.declined, + manual=m.manual_check, + ) { + UpToDate(n) => + if m.manual_check { + m.say("ultra Home is up to date (build \{n})", fx) + } + Declined(_) => () + Install(n) => { + m.say("Downloading launcher update (build \{n})…", fx) + fx.push(InstallApk(url, n)) + } + } + _ => if m.manual_check { m.say("Couldn't check for updates", fx) } + } + } + NoticeDone(gen) => if gen == m.notice_gen { m.notice = "" } + Query(q) => m.query = q + Clear => m.query = "" + WQuery(q) => m.wquery = q + WClear => m.wquery = "" + OpenDrawer => m.open_drawer(fx) + CloseDrawer => m.close_drawer(fx) + OpenApp(row) => + if row >= 0 && row < m.apps.length() { + fx.push(Launch(m.apps[row].component)) + m.close_all(fx) + } + OpenFirst => { + let i = m.first_match() + if i >= 0 && trimmed(m.query) != "" { + fx.push(Launch(m.apps[i].component)) + m.close_all(fx) + } + } + OpenHome(i) => + if i >= 0 && i < m.home.length() { + m.resizing = -1 + fx.push(Launch(m.home[i].str)) + } + AddHome(row) => { + m.add_app(row, fx) + m.sheet = NoSheet + } + ToggleHome(row) => { + let i = m.home_of(row) + if i >= 0 { + m.remove_slot(i, fx) + } else if m.home.length() < home_cap { + m.push_slot(@grid.Slot::app(m.apps[row].component, key=m.new_key())) + } + } + AppMenu(row) => + if m.drawer && m.sheet == NoSheet { + fx.push(Haptic) + m.sheet = DrawerApp(row) + } + AppInfoOf(row) => { + fx.push(AppInfo(m.apps[row].component)) + m.sheet = NoSheet + } + UninstallOf(row) => { + m.gone = m.apps[row].component + fx.push(Uninstall(m.gone)) + m.sheet = NoSheet + } + Menu => { + m.resizing = -1 + fx.push(Haptic) + m.sheet = HomeMenu + } + CloseSheet => m.sheet = NoSheet + PickApps => { + m.sheet = NoSheet + m.drawer = true + m.picking = true + } + PickWidget => { + m.sheet = WidgetPicker + m.wquery = "" + m.wloading = true + fx.push(LoadWidgets) + } + ChooseWidget(i) => m.choose_widget(i, fx) + ChooseFirstWidget => m.choose_widget(m.first_widget_match(), fx) + Remove(i) => { + m.resizing = -1 + m.remove_slot(i, fx) + m.sheet = NoSheet + } + MoveEarlier(k) => { + if k > 0 && k < m.home.length() { + let a = m.home[k] + m.home[k] = m.home[k - 1] + m.home[k - 1] = a + } + m.sheet = NoSheet + } + InfoOf(i) => { + if i >= 0 && i < m.home.length() { + fx.push(AppInfo(m.home[i].str)) + } + m.sheet = NoSheet + } + Settings => { + fx.push(OpenSettings) + m.sheet = NoSheet + } + Wallpaper => { + fx.push(PickWallpaper) + m.sheet = NoSheet + } + Recents => fx.push(OpenRecents) + CheckUpdates => { + m.sheet = NoSheet + if m.checking { + m.say("Already checking for updates", fx) + } else { + m.checking = true + m.manual_check = true + m.say("Checking for updates…", fx) + fx.push(FetchRelease(@updater.release_api)) + } + } + Lift(i) => + if !m.drawer && m.sheet == NoSheet && i != m.lifted && i < m.home.length() { + fx.push(Haptic) + m.resizing = -1 + m.regrab = false + m.lifted = i + } + Grab(i) => + if i >= 0 && i == m.resizing && !m.drawer && m.sheet == NoSheet { + m.resizing = -1 + m.regrab = true + m.lifted = i + } + ResizeBegin(edge) => m.begin_resize(edge, fx) + ResizeDone => m.resizing = -1 + Nop => () + Dragged(x~, y~, x0~, y0~) => { + m.dragged = true + match m.resize { + Some(r) => m.drag_resize(r, x, y, fx) + None => m.drag_lifted(x, y, x0, y0) + } + } + Released(moved~, held~) => { + ignore(held) + m.resize = None + m.drop_lifted(moved) + } + } +} + +// ---- pointer input -------------------------------------------------------------- + +///| +/// Feed raw pointer input through the gesture recogniser and on to the handlers. +/// `table` holds the handlers of the nodes of the tree last rendered (`vdom` numbers the +/// elements that have any, in document order); an input's `chain` lists those numbers +/// from the innermost element up. Returns the effects to run. +pub fn input( + m : Model, + table : Array[@vdom.Handlers[Msg]], + inp : @gesture.Input, +) -> Array[Effect] { + let fx : Array[Effect] = [] + fn nearest( + chain : Array[Int32], + pick : (@vdom.Handlers[Msg]) -> Msg?, + ) -> Msg? { + for id in chain { + if id >= 0 && id < table.length() { + if pick(table[id]) is Some(msg) { + return Some(msg) + } + } + } + None + } + + if inp is Down(..) { + m.dragged = false + } + for out in m.gesture.step(inp) { + let msg : Msg? = match out { + Schedule(ms, token) => { + fx.push(HoldTimer(ms, token)) + None + } + Began(chain~, ..) => nearest(chain, fn(h) { h.down }) + Tap(chain~) => nearest(chain, fn(h) { h.tap }) + Press(chain~) => nearest(chain, fn(h) { h.press }) + Drag(x~, y~, x0~, y0~) => Some(Dragged(x~, y~, x0~, y0~)) + Release(moved~, held~) => Some(Released(moved~, held~)) + } + if msg is Some(msg) { + fx.append(update(m, msg)) + } + } + fx +} diff --git a/app/view.mbt b/app/view.mbt new file mode 100644 index 0000000..9000861 --- /dev/null +++ b/app/view.mbt @@ -0,0 +1,503 @@ +///| +using @vdom {type Node, type Handlers, el, text, cls_if} + +///| +fn tap(msg : Msg) -> Handlers[Msg] { + { ..Handlers::none(), tap: Some(msg), } +} + +///| +fn icon(key : String) -> Node[Msg] { + el("img", classes=["icon"], attrs=[ + ("alt", ""), + ("draggable", "false"), + ("data-icon", key), + ]) +} + +///| +/// The `grid-column` / `grid-row` of a cell: explicit, so the packing is the model's. +fn cell_style(c : @grid.Cell) -> String { + "grid-column:\{c.col + 1} / span \{c.w};grid-row:\{c.row + 1} / span \{c.h}" +} + +///| +fn handle(edge : String, e : Edge) -> Node[Msg] { + el( + "span", + classes=["resize-handle"], + attrs=[("data-edge", edge), ("aria-hidden", "true")], + handlers={ ..Handlers::none(), down: Some(ResizeBegin(e)), tap: Some(Nop), }, + ) +} + +///| +fn Model::view_slot( + self : Model, + i : Int32, + packed : @grid.Packed, +) -> Node[Msg]? { + let s = self.home[i] + guard packed.cells[i] is Some(cell) else { return None } + let style = cell_style(cell) + match s.kind { + Widget => { + let live = !self.drawer && + self.sheet == NoSheet && + (self.resizing < 0 || i == self.resizing) + let attrs = [("data-slot", i.to_string())] + if live { + attrs.push(("data-wid", s.wid.to_string())) + } + let children = [ + el("span", classes=["widget-label"], children=[text(s.str)]), + ] + if i == self.resizing { + children.push(handle("r", Right)) + children.push(handle("b", Bottom)) + children.push(handle("rb", Corner)) + } + Some( + el( + "li", + key=s.key, + classes=[ + "widget-slot", + cls_if("lifted", i == self.lifted), + cls_if("resizing", i == self.resizing), + ], + attrs~, + style~, + handlers={ + ..Handlers::none(), + press: Some(Lift(i)), + down: if i == self.resizing { + Some(Grab(i)) + } else { + None + }, + tap: if i == self.resizing { + Some(Nop) + } else { + None + }, + }, + children~, + ), + ) + } + App => { + let row = self.app_row(s.str) + let a = self.apps[row] + Some( + el( + "li", + key=s.key, + classes=["tile", cls_if("lifted", i == self.lifted)], + attrs=[("data-slot", i.to_string())], + style~, + handlers={ + ..Handlers::none(), + tap: Some(OpenHome(i)), + press: Some(Lift(i)), + }, + children=[ + icon(a.icon), + el("span", classes=["name"], children=[text(a.label)]), + ], + ), + ) + } + } +} + +///| +fn view_panel() -> Node[Msg] { + el("section", classes=["panel"], attrs=[("aria-label", "Shortcuts")], children=[ + el("button", classes=["panel-btn"], handlers=tap(Recents), children=[ + el("span", classes=["windows-glyph"], attrs=[("aria-hidden", "true")]), + el("span", children=[text("Windows")]), + ]), + ]) +} + +///| +/// The pill under the panel: a tap opens the drawer, where the search takes the keyboard. +fn view_search_pill() -> Node[Msg] { + el( + "button", + classes=["search-pill"], + attrs=[("aria-label", "Search apps")], + handlers=tap(OpenDrawer), + children=[ + el("span", classes=["magnifier"], attrs=[("aria-hidden", "true")]), + el("span", children=[text("Search apps")]), + ], + ) +} + +///| +fn Model::view_home(self : Model) -> Node[Msg] { + let packed = self.packed() + let slots : Array[Node[Msg]] = [] + for i in 0.. 0 { packed.rows } else { 0 } + let children = [ + view_panel(), + view_search_pill(), + el( + "ul", + classes=["slots", cls_if("dragging", self.lifted >= 0)], + style="grid-template-columns:repeat(\{self.cols},minmax(0,1fr));grid-template-rows:repeat(\{rows},\{@grid.cell_px}px)", + children=slots, + ), + ] + if self.home.length() == 0 { + children.push( + el("p", classes=["hint"], children=[ + text("Swipe down for all apps. Long-press to add apps and widgets."), + ]), + ) + } + el( + "div", + classes=["home"], + handlers={ + ..Handlers::none(), + press: Some(Menu), + tap: if self.resizing >= 0 { + Some(ResizeDone) + } else { + None + }, + }, + children~, + ) +} + +///| +fn Model::view_drawer(self : Model) -> Node[Msg] { + let tiles : Array[Node[Msg]] = [] + for i in 0..= 0)], + handlers=if self.picking { + tap(ToggleHome(i)) + } else { + { + ..Handlers::none(), + tap: Some(OpenApp(i)), + press: Some(AppMenu(i)), + } + }, + children=[ + icon(a.icon), + el("span", classes=["name"], children=[text(a.label)]), + ], + ), + ) + } + let children : Array[Node[Msg]] = [ + el("div", classes=["drawer-head"], children=[ + el( + "input", + classes=["input"], + attrs=[ + ("type", "search"), + ("placeholder", "Search apps"), + ("enterkeyhint", "go"), + ("aria-label", "Search apps"), + ("autocomplete", "off"), + ], + props=[("value", self.query)], + handlers={ + ..Handlers::none(), + input: Some(fn(v) { Query(v) }), + enter: Some(OpenFirst), + escape: Some(Clear), + }, + ), + el("button", classes=["btn", "ghost", "sm"], handlers=tap(CloseDrawer), children=[ + text(if self.picking { "Done" } else { "Close" }), + ]), + ]), + ] + if self.picking { + children.push( + el("p", classes=["drawer-note"], children=[ + text("Tap apps to add them to the home screen or take them off."), + ]), + ) + } + if self.load_error != "" { + children.push( + el("div", classes=["alert", "destructive"], attrs=[("role", "alert")], children=[ + text("Could not list apps"), + ]), + ) + } + children.push(el("ul", classes=["apps"], children=tiles)) + if self.loading { + children.push( + el("p", classes=["empty"], children=[text("Loading apps…")]), + ) + } else if tiles.length() == 0 { + children.push(el("p", classes=["empty"], children=[text("No apps match.")])) + } + el("div", classes=["drawer", cls_if("picking", self.picking)], children~) +} + +///| +fn sheet_btn(label : String, msg : Msg) -> Node[Msg] { + el("button", classes=["sheet-item"], handlers=tap(msg), children=[text(label)]) +} + +///| +fn sheet_title(label : String) -> Node[Msg] { + el("h2", classes=["sheet-title"], children=[text(label)]) +} + +///| +fn Model::view_sheet(self : Model) -> Array[Node[Msg]] { + let items : Array[Node[Msg]] = [] + match self.sheet { + NoSheet => () + HomeMenu => { + items.push(sheet_title("Home screen")) + items.push(sheet_btn("Add apps", PickApps)) + items.push(sheet_btn("Add widget", PickWidget)) + items.push(sheet_btn("Wallpaper", Wallpaper)) + items.push(sheet_btn("Settings", Settings)) + items.push(sheet_btn("Check for updates", CheckUpdates)) + } + Item(i) => + if i >= 0 && i < self.home.length() { + let s = self.home[i] + let row = self.app_row(s.str) + items.push( + sheet_title( + if s.kind == Widget { + s.str + } else if row >= 0 { + self.apps[row].label + } else { + s.str + }, + ), + ) + if i > 0 { + items.push(sheet_btn("Move earlier", MoveEarlier(i))) + } + if i < self.home.length() - 1 { + items.push(sheet_btn("Move later", MoveEarlier(i + 1))) + } + if s.kind == App { + items.push(sheet_btn("App info", InfoOf(i))) + items.push(sheet_btn("Remove from home", Remove(i))) + } else { + items.push(sheet_btn("Remove widget", Remove(i))) + } + } + DrawerApp(row) => + if row >= 0 && row < self.apps.length() { + items.push(sheet_title(self.apps[row].label)) + let h = self.home_of(row) + if h >= 0 { + items.push(sheet_btn("Remove from home", Remove(h))) + } else { + items.push(sheet_btn("Add to home", AddHome(row))) + } + items.push(sheet_btn("App info", AppInfoOf(row))) + if !self.apps[row].system { + items.push(sheet_btn("Uninstall", UninstallOf(row))) + } + } + WidgetPicker => { + items.push(sheet_title("Add a widget")) + if self.wloading { + items.push( + el("p", classes=["empty"], children=[text("Loading widgets…")]), + ) + } else if self.widgets.length() == 0 { + items.push( + el("p", classes=["empty"], children=[text("No widgets installed.")]), + ) + } else { + items.push( + el( + "input", + classes=["input", "widget-search"], + attrs=[ + ("type", "search"), + ("placeholder", "Search widgets"), + ("enterkeyhint", "go"), + ("aria-label", "Search widgets"), + ("autocomplete", "off"), + ], + props=[("value", self.wquery)], + handlers={ + ..Handlers::none(), + input: Some(fn(v) { WQuery(v) }), + enter: Some(ChooseFirstWidget), + escape: Some(WClear), + }, + ), + ) + } + let rows : Array[Node[Msg]] = [] + for i in 0.. 0 && rows.length() == 0 { + items.push( + el("p", classes=["empty"], children=[text("No widgets match.")]), + ) + } + } + } + [ + el("div", classes=["sheet-overlay"], handlers=tap(CloseSheet)), + el( + "div", + classes=["sheet"], + attrs=[("role", "dialog"), ("aria-modal", "true")], + handlers={ ..Handlers::none(), escape: Some(CloseSheet), }, + children=items, + ), + ] +} + +///| +fn Model::view_resize_bar(self : Model) -> Node[Msg] { + el("div", classes=["resize-bar"], attrs=[("role", "toolbar")], children=[ + el("span", classes=["resize-hint"], children=[ + text("Drag to move, or drag the handles to resize"), + ]), + el( + "button", + classes=["btn", "ghost", "sm"], + handlers=tap(Remove(self.resizing)), + children=[text("Remove")], + ), + el("button", classes=["btn", "primary", "sm"], handlers=tap(ResizeDone), children=[ + text("Done"), + ]), + ]) +} + +///| +/// The whole screen as a tree. +pub fn view(m : Model) -> Array[Node[Msg]] { + let out : Array[Node[Msg]] = [m.view_home()] + if m.drawer { + out.push(m.view_drawer()) + } + if m.sheet != NoSheet { + out.append(m.view_sheet()) + } else if m.resizing >= 0 && !m.drawer { + out.push(m.view_resize_bar()) + } + if m.notice != "" { + out.push( + el("div", classes=["notice"], attrs=[("role", "status")], children=[ + text(m.notice), + ]), + ) + } + out +} + +///| +/// The handlers of a tree's elements, numbered in document order (pre-order): the +/// platform layer marks each such element with its number and reports pointer input as +/// chains of them (see `input`). +pub fn handler_table(nodes : Array[Node[Msg]]) -> Array[Handlers[Msg]] { + let out : Array[Handlers[Msg]] = [] + fn walk(n : Node[Msg]) -> Unit { + if n is El(e) { + if !e.handlers.is_empty() { + out.push(e.handlers) + } + for c in e.children { + walk(c) + } + } + } + + for n in nodes { + walk(n) + } + out +} + +///| +pub(all) enum Key { + Enter + Escape +} + +///| +/// A key pressed in an input; `chain` as for `input`. +pub fn key( + m : Model, + table : Array[Handlers[Msg]], + chain : Array[Int32], + k : Key, +) -> Array[Effect] { + for id in chain { + if id >= 0 && id < table.length() { + let h = table[id] + let msg = match k { + Enter => h.enter + Escape => h.escape + } + if msg is Some(msg) { + return update(m, msg) + } + } + } + [] +} + +///| +/// An input's text changed. +pub fn typed( + m : Model, + table : Array[Handlers[Msg]], + chain : Array[Int32], + value : String, +) -> Array[Effect] { + for id in chain { + if id >= 0 && id < table.length() { + if table[id].input is Some(f) { + return update(m, f(value)) + } + } + } + [] +} diff --git a/ci/gitea-apk.sh b/ci/gitea-apk.sh index 7a763b8..e9f1e44 100755 --- a/ci/gitea-apk.sh +++ b/ci/gitea-apk.sh @@ -1,60 +1,48 @@ #!/usr/bin/env bash -# Tests the Qt launcher (qt/), builds its APK and publishes it as a Gitea release: -# build-, holding ultra-launcher.apk and version.json, made a draft first -# and published once both files are up, so the latest release never lacks them. -# Runs in .gitea/workflows/launcher.yml's "apk" job (JDK 17 container, as root). +# Builds the launcher APK (MoonBit page + Java shell, android/build.sh) and publishes it as a +# Gitea release: build-, holding ultra-launcher.apk and version.json, made a +# draft first and published once both files are up, so the latest release never lacks them. +# Runs in .gitea/workflows/launcher.yml's "apk" job (node:22-bookworm container, as root, +# no docker). The installed app updates itself from the latest release (updater/ in MoonBit). set -euo pipefail cd "$(dirname "$0")/.." -QT_VERSION=6.8.3 -NDK=26.1.10909125 -# Minutes since the epoch: always above the GitHub builds' run numbers and always rising. -VERSION_CODE=$(( $(date +%s) / 60 )) +# Minutes since the epoch: always above every earlier build's versionCode (the Qt builds used +# the same scale) and always rising. +export VERSION_CODE=$(( $(date +%s) / 60 )) COMMIT="${GITHUB_SHA:-$(git rev-parse HEAD)}" echo "== tools" -apt-get update -qq -# The host Qt tools (moc, qmlimportscanner, qmlcachegen) need glib, GL and friends; -# g++ builds the desktop test and nodejs runs the layout test. -apt-get install -y -qq --no-install-recommends python3-pip python3-venv ninja-build cmake g++ nodejs unzip curl ca-certificates git \ - libglib2.0-0t64 libgl1 libegl1 libopengl0 libgl-dev libglx-dev libopengl-dev libegl-dev libxkbcommon-dev \ - libfontconfig1 libfreetype6 libxkbcommon0 libdbus-1-3 >/dev/null -python3 -m venv /opt/aqt && /opt/aqt/bin/pip install -q aqtinstall +# In the cluster's android-sdk image the JDK, SDK and common tools are already there; on a bare +# image (the documented fallback, e.g. node:22-bookworm) they are installed below. +if ! command -v javac >/dev/null || ! command -v zip >/dev/null || ! command -v curl >/dev/null; then + apt-get update -qq + apt-get install -y -qq --no-install-recommends openjdk-17-jdk-headless unzip zip curl ca-certificates git >/dev/null +fi +command -v moon >/dev/null || [ -x "$HOME/.moon/bin/moon" ] || curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash +export PATH="$HOME/.moon/bin:$PATH" +moon update -echo "== Qt $QT_VERSION (android arm64 + host)" -/opt/aqt/bin/aqt install-qt linux android "$QT_VERSION" android_arm64_v8a -O /opt/Qt --autodesktop >/dev/null -QT_ROOT=/opt/Qt/$QT_VERSION/android_arm64_v8a -QT_HOST=/opt/Qt/$QT_VERSION/gcc_64 - -echo "== tests (desktop Qt)" -node qt/tests/layout.test.mjs -cmake -S qt -B build-desktop -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$QT_HOST" -cmake --build build-desktop -QT_QPA_PLATFORM=offscreen build-desktop/ultrahome_e2e - -echo "== Android SDK + NDK $NDK" -export ANDROID_SDK_ROOT=/opt/android-sdk -mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" -curl -fsSL -o /tmp/cmdline.zip https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -unzip -q /tmp/cmdline.zip -d "$ANDROID_SDK_ROOT/cmdline-tools" && mv "$ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools" "$ANDROID_SDK_ROOT/cmdline-tools/latest" -yes | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null || true -"$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --install "platform-tools" "ndk;$NDK" "platforms;android-35" "build-tools;35.0.0" >/dev/null -export ANDROID_NDK_ROOT=$ANDROID_SDK_ROOT/ndk/$NDK +SDK="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-/opt/android-sdk}}" +if [ -f "$SDK/platforms/android-35/android.jar" ] && ls -d "$SDK"/build-tools/35* >/dev/null 2>&1; then + echo "== Android SDK from the image ($SDK)" +else + echo "== Android SDK fallback (build-tools and the platform jar only)" + SDK=/opt/android-sdk + mkdir -p "$SDK/cmdline-tools" + curl -fsSL -o /tmp/cmdline.zip https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip + unzip -q /tmp/cmdline.zip -d "$SDK/cmdline-tools" + mv "$SDK/cmdline-tools/cmdline-tools" "$SDK/cmdline-tools/latest" + yes | "$SDK/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null || true + "$SDK/cmdline-tools/latest/bin/sdkmanager" --install "build-tools;35.0.0" >/dev/null + # Only android.jar is needed from the platform: unzipping the whole thing (sdkmanager) is slow. + curl -fsSL -o /tmp/platform.zip https://dl.google.com/android/repository/platform-35_r02.zip + mkdir -p "$SDK/platforms" && unzip -q /tmp/platform.zip 'android-35/android.jar' -d "$SDK/platforms" +fi +export ANDROID_SDK_ROOT="$SDK" echo "== build (versionCode $VERSION_CODE)" -# Signed with the committed key, like every earlier build, so it installs over them. -export QT_ANDROID_KEYSTORE_PATH="$PWD/android/app/debug.keystore" -export QT_ANDROID_KEYSTORE_ALIAS=androiddebugkey -export QT_ANDROID_KEYSTORE_STORE_PASS=android -export QT_ANDROID_KEYSTORE_KEY_PASS=android -"$QT_ROOT/bin/qt-cmake" -S qt -B build-android -G Ninja -DCMAKE_BUILD_TYPE=Release \ - -DANDROID_SDK_ROOT="$ANDROID_SDK_ROOT" -DANDROID_NDK_ROOT="$ANDROID_NDK_ROOT" \ - -DQT_HOST_PATH="$QT_HOST" -DQT_ANDROID_SIGN_APK=ON -DVERSION_CODE="$VERSION_CODE" -cmake --build build-android --target apk -apk=$(find build-android -name "*-signed.apk" | head -1) -test -n "$apk" || { find build-android -name "*.apk"; exit 1; } -cp "$apk" ultra-launcher.apk -printf '{"versionCode": %s, "commit": "%s"}\n' "$VERSION_CODE" "$COMMIT" > version.json +android/build.sh ultra-launcher.apk echo "== release build-$VERSION_CODE" server="${GITHUB_SERVER_URL:-https://git.site.latha.org}" @@ -65,9 +53,9 @@ test -n "$token" || { echo "no GITEA_TOKEN/GITHUB_TOKEN in the environment"; exi auth=(-H "Authorization: token $token") tag="build-$VERSION_CODE" id=$(curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X POST "$api/releases" \ - -d "{\"tag_name\": \"$tag\", \"name\": \"ultra Home build $VERSION_CODE\", \"target_commitish\": \"$COMMIT\", \"draft\": true, \"body\": \"Qt launcher built from $COMMIT.\"}" \ + -d "{\"tag_name\": \"$tag\", \"name\": \"ultra Home build $VERSION_CODE\", \"target_commitish\": \"$COMMIT\", \"draft\": true, \"body\": \"MoonBit launcher built from $COMMIT.\"}" \ | python3 -c 'import sys, json; print(json.load(sys.stdin)["id"])') curl -fsS "${auth[@]}" -F "attachment=@ultra-launcher.apk" "$api/releases/$id/assets?name=ultra-launcher.apk" >/dev/null -curl -fsS "${auth[@]}" -F "attachment=@version.json" "$api/releases/$id/assets?name=version.json" >/dev/null +curl -fsS "${auth[@]}" -F "attachment=@$(dirname ultra-launcher.apk)/version.json" "$api/releases/$id/assets?name=version.json" >/dev/null curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X PATCH "$api/releases/$id" -d '{"draft": false}' >/dev/null echo "published $tag to $server/$repo" diff --git a/docs/screenshots/01-home-with-apps.png b/docs/screenshots/01-home-with-apps.png new file mode 100644 index 0000000..8bfeb85 Binary files /dev/null and b/docs/screenshots/01-home-with-apps.png differ diff --git a/docs/screenshots/03-drawer.png b/docs/screenshots/03-drawer.png new file mode 100644 index 0000000..28d47d8 Binary files /dev/null and b/docs/screenshots/03-drawer.png differ diff --git a/docs/screenshots/04-drawer-app-menu.png b/docs/screenshots/04-drawer-app-menu.png new file mode 100644 index 0000000..70510aa Binary files /dev/null and b/docs/screenshots/04-drawer-app-menu.png differ diff --git a/docs/screenshots/05-resize-handles.png b/docs/screenshots/05-resize-handles.png new file mode 100644 index 0000000..d04551b Binary files /dev/null and b/docs/screenshots/05-resize-handles.png differ diff --git a/gesture/gesture.mbt b/gesture/gesture.mbt new file mode 100644 index 0000000..cc67d0a --- /dev/null +++ b/gesture/gesture.mbt @@ -0,0 +1,149 @@ +///| +/// Pointer gestures as a pure state machine. The platform layer reports raw pointer +/// input (down, move, up, cancel, and the long-press timer firing); this decides what +/// it was and answers with `Out`s. It knows nothing about what was touched: a target is +/// a `chain` of node ids from the innermost element up, and the app resolves them. +/// +/// - a stationary hold for `hold_ms` is a *press* (long press); moving more than +/// `slop` px first cancels it +/// - a press that ends without moving is a *release* with `moved = false` +/// (the home screen opens the item's menu) +/// - letting go without a hold or a move is a *tap* +/// - once the pointer has moved past the slop, every move is a *drag* +/// (whether it means anything depends on what the app has lifted) + +///| +/// How long a stationary hold takes to become a long press. +pub let hold_ms : Int32 = 500 + +///| +/// How far (px) the pointer may travel before it stops being a tap or a hold. +pub let slop : Double = 10.0 + +///| +#derive(Eq, Debug) +pub(all) enum Input { + Down(x~ : Double, y~ : Double, chain~ : Array[Int32]) + Move(x~ : Double, y~ : Double) + Up(x~ : Double, y~ : Double) + Cancel + /// The timer started by `Schedule(_, token)` fired. + Hold(Int32) +} + +///| +#derive(Eq, Debug) +pub(all) enum Out { + /// Start a timer of this many ms, then send `Hold(token)`. + Schedule(Int32, Int32) + /// The pointer went down on this chain (the app may act at once, e.g. grab a widget). + Began(chain~ : Array[Int32], x~ : Double, y~ : Double) + Tap(chain~ : Array[Int32]) + Press(chain~ : Array[Int32]) + /// The pointer is at x, y; it went down at x0, y0. + Drag(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double) + /// The pointer is up. `moved`: it travelled past the slop; `held`: a press fired. + Release(moved~ : Bool, held~ : Bool) +} + +///| +pub(all) struct State { + mut down : Bool + mut x0 : Double + mut y0 : Double + mut moved : Bool + mut held : Bool + mut chain : Array[Int32] + mut token : Int32 +} + +///| +pub fn State::new() -> State { + { + down: false, + x0: 0.0, + y0: 0.0, + moved: false, + held: false, + chain: [], + token: 0, + } +} + +///| +/// Feed one input; returns what happened. +pub fn State::step(self : State, input : Input) -> Array[Out] { + match input { + Down(x~, y~, chain~) => { + self.down = true + self.x0 = x + self.y0 = y + self.moved = false + self.held = false + self.chain = chain + self.token += 1 + [Began(chain~, x~, y~), Schedule(hold_ms, self.token)] + } + Move(x~, y~) => + if !self.down { + [] + } else { + if !self.moved { + let dx = x - self.x0 + let dy = y - self.y0 + if (dx * dx + dy * dy).sqrt() >= slop { + self.moved = true + self.token += 1 // a hold timer still running is stale now + } + } + if self.moved { + [Drag(x~, y~, x0=self.x0, y0=self.y0)] + } else { + [] + } + } + Up(..) | Cancel => + if !self.down { + [] + } else { + let chain = self.chain + let moved = self.moved + let held = self.held + self.down = false + self.token += 1 + let tap : Array[Out] = if !moved && !held && input is Up(..) { + [Tap(chain~)] + } else { + [] + } + [..tap, Release(moved~, held~)] + } + Hold(token) => + if self.down && token == self.token && !self.moved && !self.held { + self.held = true + [Press(chain=self.chain)] + } else { + [] + } + } +} + +///| +#derive(Eq, Debug) +pub(all) enum Swipe { + Down + Up +} + +///| +/// A touch that travelled dx, dy px in dt ms is a swipe when it was quick, long enough +/// and more vertical than horizontal. +pub fn classify_swipe(dx : Double, dy : Double, dt : Int32) -> Swipe? { + if dt >= 700 || dy.abs() < 60.0 || dx.abs() > dy.abs() { + None + } else if dy > 0.0 { + Some(Down) + } else { + Some(Up) + } +} diff --git a/gesture/gesture_wbtest.mbt b/gesture/gesture_wbtest.mbt new file mode 100644 index 0000000..d27107c --- /dev/null +++ b/gesture/gesture_wbtest.mbt @@ -0,0 +1,69 @@ +///| +test "a tap: down then up without moving" { + let g = State::new() + assert_eq(g.step(Down(x=10.0, y=10.0, chain=[3, 1])), [ + Began(chain=[3, 1], x=10.0, y=10.0), + Schedule(500, 1), + ]) + assert_eq(g.step(Up(x=11.0, y=10.0)), [ + Tap(chain=[3, 1]), + Release(moved=false, held=false), + ]) +} + +///| +test "a long press: the timer fires, then the release is not a tap" { + let g = State::new() + ignore(g.step(Down(x=0.0, y=0.0, chain=[7]))) + assert_eq(g.step(Hold(1)), [Press(chain=[7])]) + assert_eq(g.step(Up(x=0.0, y=0.0)), [Release(moved=false, held=true)]) +} + +///| +test "moving past the slop cancels the hold and starts a drag" { + let g = State::new() + ignore(g.step(Down(x=0.0, y=0.0, chain=[7]))) + assert_eq(g.step(Move(x=5.0, y=0.0)), []) + assert_eq(g.step(Move(x=20.0, y=0.0)), [Drag(x=20.0, y=0.0, x0=0.0, y0=0.0)]) + assert_eq(g.step(Hold(1)), []) // the stale timer does nothing + assert_eq(g.step(Move(x=30.0, y=2.0)), [Drag(x=30.0, y=2.0, x0=0.0, y0=0.0)]) + assert_eq(g.step(Up(x=30.0, y=2.0)), [Release(moved=true, held=false)]) +} + +///| +test "a press then a drag, then release" { + let g = State::new() + ignore(g.step(Down(x=0.0, y=0.0, chain=[7]))) + ignore(g.step(Hold(1))) + assert_eq(g.step(Move(x=40.0, y=0.0)), [Drag(x=40.0, y=0.0, x0=0.0, y0=0.0)]) + assert_eq(g.step(Up(x=40.0, y=0.0)), [Release(moved=true, held=true)]) +} + +///| +test "cancel releases without a tap; stray input is ignored" { + let g = State::new() + assert_eq(g.step(Up(x=0.0, y=0.0)), []) + assert_eq(g.step(Move(x=0.0, y=0.0)), []) + ignore(g.step(Down(x=0.0, y=0.0, chain=[1]))) + assert_eq(g.step(Cancel), [Release(moved=false, held=false)]) + assert_eq(g.step(Hold(1)), []) +} + +///| +test "a stale timer from an earlier press is ignored" { + let g = State::new() + ignore(g.step(Down(x=0.0, y=0.0, chain=[1]))) + ignore(g.step(Up(x=0.0, y=0.0))) + ignore(g.step(Down(x=0.0, y=0.0, chain=[2]))) + assert_eq(g.step(Hold(1)), []) + assert_eq(g.step(Hold(3)), [Press(chain=[2])]) +} + +///| +test "swipes" { + assert_eq(classify_swipe(5.0, 100.0, 300), Some(Down)) + assert_eq(classify_swipe(5.0, -100.0, 300), Some(Up)) + assert_eq(classify_swipe(5.0, 50.0, 300), None) // too short + assert_eq(classify_swipe(120.0, 100.0, 300), None) // more sideways than down + assert_eq(classify_swipe(5.0, 100.0, 900), None) // too slow +} diff --git a/gesture/moon.pkg b/gesture/moon.pkg new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/gesture/moon.pkg @@ -0,0 +1 @@ + diff --git a/gesture/pkg.generated.mbti b/gesture/pkg.generated.mbti new file mode 100644 index 0000000..3b4fc59 --- /dev/null +++ b/gesture/pkg.generated.mbti @@ -0,0 +1,57 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/launcher/gesture" + +import { + "moonbitlang/core/debug", +} + +// Values +pub fn classify_swipe(Double, Double, Int32) -> Swipe? + +pub let hold_ms : Int32 + +pub let slop : Double + +// Errors + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) enum Input { + Down(x~ : Double, y~ : Double, chain~ : Array[Int32]) + Move(x~ : Double, y~ : Double) + Up(x~ : Double, y~ : Double) + Cancel + Hold(Int32) +} + +#derive(Eq, @debug.Debug) +pub(all) enum Out { + Schedule(Int32, Int32) + Began(chain~ : Array[Int32], x~ : Double, y~ : Double) + Tap(chain~ : Array[Int32]) + Press(chain~ : Array[Int32]) + Drag(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double) + Release(moved~ : Bool, held~ : Bool) +} + +pub(all) struct State { + mut down : Bool + mut x0 : Double + mut y0 : Double + mut moved : Bool + mut held : Bool + mut chain : Array[Int32] + mut token : Int32 +} +pub fn State::new() -> Self +pub fn State::step(Self, Input) -> Array[Out] + +#derive(Eq, @debug.Debug) +pub(all) enum Swipe { + Down + Up +} + +// Type aliases + +// Traits diff --git a/grid/grid.mbt b/grid/grid.mbt new file mode 100644 index 0000000..89c7065 --- /dev/null +++ b/grid/grid.mbt @@ -0,0 +1,354 @@ +///| +/// The home grid as plain functions over a list of slots: packing, the cell under a +/// point, pinning, resize steps. Pure; ported from legacy/qt/qml/Layout.js and the +/// packing logic of legacy/web/app.py. +/// +/// A slot is an app (one cell) or a widget (`w` columns by `rows` rows). `x`/`y` is the +/// cell it was dropped into (column, row from 0), or -1/-1: placed in order into the +/// first free cells that fit it ("dense" packing, so apps fill the cells beside a widget +/// and the grid has no holes). + +///| +/// Row height in px. +pub let cell_px : Int32 = 64 + +///| +/// Gap between rows in px. +pub let row_gap : Int32 = 8 + +///| +/// Gap between columns in px. +pub let col_gap : Int32 = 8 + +///| +#derive(Eq, Debug) +pub(all) enum Kind { + App + Widget +} + +///| +#derive(Eq, Debug) +pub(all) struct Slot { + kind : Kind + /// An app's component name, or a widget's label. + str : String + /// A widget's host id (0 for apps). + wid : Int32 + /// A widget's width in columns (0: the whole row). + mut w : Int32 + /// A widget's height in rows. + mut rows : Int32 + mut x : Int32 + mut y : Int32 + /// A stable identity for the view's keyed diff (not persisted). + key : Int32 +} + +///| +pub fn Slot::app(str : String, key~ : Int32 = 0) -> Slot { + { kind: App, str, wid: 0, w: 0, rows: 1, x: -1, y: -1, key, } +} + +///| +pub fn Slot::widget( + str : String, + wid : Int32, + w~ : Int32 = 0, + rows~ : Int32 = 1, + key~ : Int32 = 0, +) -> Slot { + { kind: Widget, str, wid, w, rows, x: -1, y: -1, key, } +} + +///| +/// Rows of app tiles nearest to a widget height in px, at least one. +pub fn widget_rows(px : Int32) -> Int32 { + let k = (px + row_gap + (cell_px + row_gap) / 2) / (cell_px + row_gap) + if k < 1 { + 1 + } else { + k + } +} + +///| +pub fn Slot::cols(self : Slot, cols : Int32) -> Int32 { + match self.kind { + App => 1 + Widget => if self.w <= 0 || self.w > cols { cols } else { self.w } + } +} + +///| +pub fn Slot::height(self : Slot) -> Int32 { + match self.kind { + App => 1 + Widget => if self.rows < 1 { 1 } else { self.rows } + } +} + +///| +pub fn Slot::pinned(self : Slot, cols : Int32) -> Bool { + self.x >= 0 && self.y >= 0 && self.x + self.cols(cols) <= cols +} + +///| +/// Where a slot goes, in cells. +#derive(Eq, Debug) +pub(all) struct Cell { + col : Int32 + row : Int32 + w : Int32 + h : Int32 +} + +///| +pub(all) struct Packed { + /// One per slot, `None` for a hidden one. + cells : Array[Cell?] + /// Rows used, at least the rows that fill the screen. + rows : Int32 +} + +///| +/// Where each slot goes, and the rows used (at least `nrows`, the rows that fill the +/// screen). Pinned slots keep their cell (they may overlap each other while one is +/// carried); the rest go in order into the first free cells that fit them. `hidden[i]` +/// leaves slot i out (an app that is not installed). +pub fn pack( + slots : Array[Slot], + cols : Int32, + nrows : Int32, + hidden~ : (Int32) -> Bool = fn(_) { false }, +) -> Packed { + let occ : Array[Array[Bool]] = [] + fn taken(c : Int32, r : Int32) -> Bool { + r < occ.length() && occ[r][c] + } + + fn fits(c : Int32, r : Int32, w : Int32, h : Int32) -> Bool { + if c < 0 || c + w > cols { + return false + } + for y in r..<(r + h) { + for x in c..<(c + w) { + if taken(x, y) { + return false + } + } + } + true + } + + fn mark(c : Int32, r : Int32, w : Int32, h : Int32) -> Unit { + for y in r..<(r + h) { + while occ.length() <= y { + occ.push(Array::make(cols, false)) + } + for x in c..<(c + w) { + occ[y][x] = true + } + } + } + + let n = slots.length() + let cells : Array[Cell?] = Array::make(n, None) + let mut rows = if nrows < 0 { 0 } else { nrows } + for i in 0.. (Double, Double, Double, Double) { + let cg = col_gap.to_double() + let rg = row_gap.to_double() + ( + cell.col.to_double() * (col_w + cg), + cell.row.to_double() * (cell_px.to_double() + rg), + cell.w.to_double() * col_w + (cell.w - 1).to_double() * cg, + cell.h.to_double() * cell_px.to_double() + (cell.h - 1).to_double() * rg, + ) +} + +///| +/// The cell nearest to a point (px in the grid, from its top left): (col, row). +pub fn cell_at(x : Double, y : Double, col_w : Double) -> (Int32, Int32) { + let c = (x / (col_w + col_gap.to_double()) + 0.5).floor().to_int() + let r = (y / (cell_px + row_gap).to_double() + 0.5).floor().to_int() + (@cmp.maximum(0, c), @cmp.maximum(0, r)) +} + +///| +/// The cell whose box contains a point, or `None` outside every cell (in the gaps). +pub fn cell_under(x : Double, y : Double, col_w : Double) -> (Int32, Int32)? { + if x < 0.0 || y < 0.0 { + return None + } + let pw = col_w + col_gap.to_double() + let ph = (cell_px + row_gap).to_double() + let c = (x / pw).floor().to_int() + let r = (y / ph).floor().to_int() + if x - c.to_double() * pw > col_w || + y - r.to_double() * ph > cell_px.to_double() { + None + } else { + Some((c, r)) + } +} + +///| +/// Pin slot `i` with its top left at `col`, `row`, kept on the screen's grid (`nrows` of +/// 0: no limit on rows). +pub fn pin( + slots : Array[Slot], + i : Int32, + col : Int32, + row : Int32, + cols : Int32, + nrows : Int32, +) -> Unit { + let s = slots[i] + let mut x = col + let mut y = row + if x + s.cols(cols) > cols { + x = cols - s.cols(cols) + } + if nrows > 0 && y + s.height() > nrows { + y = nrows - s.height() + } + s.x = @cmp.maximum(0, x) + s.y = @cmp.maximum(0, y) +} + +///| +/// Unpin the slots under pinned slot `i`, so they flow into free cells. +pub fn clear_cells(slots : Array[Slot], i : Int32, cols : Int32) -> Unit { + let a = slots[i] + for j in 0.. Unit { + let s = slots.remove(a) + slots.insert(b, s) +} + +///| +/// The size in px of `k` cells of `size` px, `gap` apart. +pub fn span(k : Int32, size : Double, gap : Double) -> Double { + k.to_double() * size + (k - 1).to_double() * gap +} + +///| +/// Resize steps: the number of cells (of `size` px, `gap` apart) nearest to `want` px, +/// kept within `min`..`max` px where it can be (`max` of 0: no limit), and within +/// `lo`..`hi` cells. +pub fn fit( + want : Double, + lo : Int32, + hi : Int32, + size : Double, + gap : Double, + min : Int32, + max : Int32, +) -> Int32 { + let mut k = ((want + gap) / (size + gap) + 0.5).floor().to_int() + while k < hi && span(k, size, gap) < (min - 8).to_double() { + k += 1 + } + while k > lo && max > 0 && span(k, size, gap) > (max + 8).to_double() { + k -= 1 + } + @cmp.maximum(lo, @cmp.minimum(hi, k)) +} + +///| +/// Columns a new widget of natural width `px` starts at (0: the whole row). +pub fn widget_cols(px : Int32, col_w : Double, cols : Int32) -> Int32 { + if px <= 0 { + return 0 + } + let k = @cmp.maximum( + 1, + ((px + col_gap - 8).to_double() / (col_w + col_gap.to_double())) + .ceil() + .to_int(), + ) + if k >= cols { + 0 + } else { + k + } +} + +///| +/// How many grid columns the screen has for a viewport width in CSS px. +pub fn columns_for(width : Int32) -> Int32 { + if width >= 480 { + 6 + } else { + 5 + } +} + +///| +/// The width of one column, given the width of the grid. +pub fn column_width(grid_width : Double, cols : Int32) -> Double { + (grid_width - (cols - 1).to_double() * col_gap.to_double()) / cols.to_double() +} + +///| +/// How many rows of the grid fit in `height` px. +pub fn rows_fit(height : Double) -> Int32 { + let r = ((height + row_gap.to_double()) / (cell_px + row_gap).to_double()) + .floor() + .to_int() + @cmp.maximum(1, r) +} diff --git a/grid/grid_wbtest.mbt b/grid/grid_wbtest.mbt new file mode 100644 index 0000000..37112e4 --- /dev/null +++ b/grid/grid_wbtest.mbt @@ -0,0 +1,157 @@ +///| +fn app(x~ : Int32 = -1, y~ : Int32 = -1) -> Slot { + let s = Slot::app("a") + s.x = x + s.y = y + s +} + +///| +fn widget(w : Int32, rows : Int32, x~ : Int32 = -1, y~ : Int32 = -1) -> Slot { + let s = Slot::widget("W", 1, w~, rows~) + s.x = x + s.y = y + s +} + +///| +fn cells( + home : Array[Slot], + cols~ : Int32 = 5, + nrows~ : Int32 = 0, +) -> Array[(Int32, Int32, Int32, Int32)?] { + pack(home, cols, nrows).cells.map(fn(c) { + match c { + Some(c) => Some((c.col, c.row, c.w, c.h)) + None => None + } + }) +} + +///| +test "apps fill rows left to right" { + assert_eq(cells([app(), app(), app(), app(), app(), app()]), [ + Some((0, 0, 1, 1)), + Some((1, 0, 1, 1)), + Some((2, 0, 1, 1)), + Some((3, 0, 1, 1)), + Some((4, 0, 1, 1)), + Some((0, 1, 1, 1)), + ]) +} + +///| +test "a whole-row widget takes its rows; apps go below" { + assert_eq(cells([widget(0, 2), app()]), [ + Some((0, 0, 5, 2)), + Some((0, 2, 1, 1)), + ]) +} + +///| +test "dense: apps fill the cells beside a narrow widget" { + assert_eq(cells([widget(3, 2), app(), app(), app(), app(), app()]), [ + Some((0, 0, 3, 2)), + Some((3, 0, 1, 1)), + Some((4, 0, 1, 1)), + Some((3, 1, 1, 1)), + Some((4, 1, 1, 1)), + Some((0, 2, 1, 1)), + ]) +} + +///| +test "a widget too wide for the rest of a row starts the next; apps backfill" { + assert_eq(cells([app(), app(), app(), widget(3, 1), app()]), [ + Some((0, 0, 1, 1)), + Some((1, 0, 1, 1)), + Some((2, 0, 1, 1)), + Some((0, 1, 3, 1)), + Some((3, 0, 1, 1)), + ]) +} + +///| +test "pinned slots keep their cell; the rest flow around them" { + assert_eq(cells([app(), app(x=2, y=3), app()]), [ + Some((0, 0, 1, 1)), + Some((2, 3, 1, 1)), + Some((1, 0, 1, 1)), + ]) +} + +///| +test "rows: at least nrows, more if the slots need them" { + assert_eq(pack([app()], 5, 9).rows, 9) + assert_eq(pack([app(x=0, y=12)], 5, 9).rows, 13) +} + +///| +test "a pin that no longer fits the columns flows instead" { + assert_eq(cells([widget(3, 1, x=3, y=0)]), [Some((0, 0, 3, 1))]) +} + +///| +test "hidden slots take no cell" { + let p = pack([app(), app()], 5, 0, hidden=fn(i) { i == 0 }) + assert_eq(p.cells[0], None) + assert_eq(p.cells[1], Some({ col: 0, row: 0, w: 1, h: 1, })) +} + +///| +test "pinning stays on the grid; dropping unpins what it covers" { + let h = [widget(2, 2), app(x=1, y=1), app(x=4, y=4)] + pin(h, 0, 4, 9, 5, 8) + assert_eq((h[0].x, h[0].y), (3, 6)) + pin(h, 0, 0, 0, 5, 8) + clear_cells(h, 0, 5) + assert_eq((h[1].x, h[1].y, h[2].x, h[2].y), (-1, -1, 4, 4)) +} + +///| +test "moving in the order" { + let h = ["a", "b", "c", "d"] + let s = h.map(fn(x) { Slot::app(x) }) + move_slot(s, 0, 2) + assert_eq(s.map(fn(x) { x.str }), ["b", "c", "a", "d"]) + move_slot(s, 3, 0) + assert_eq(s.map(fn(x) { x.str }), ["d", "b", "c", "a"]) +} + +///| +test "widget heights in px to rows" { + assert_eq([40, 64, 100, 136, 208, 420].map(widget_rows), [1, 1, 2, 2, 3, 6]) +} + +///| +test "resize steps snap to cells within the widget's limits" { + assert_eq(fit(150.0, 1, 5, 64.0, 8.0, 0, 0), 2) + assert_eq(fit(10.0, 1, 5, 64.0, 8.0, 200, 0), 3) + assert_eq(fit(400.0, 1, 5, 64.0, 8.0, 0, 150), 2) +} + +///| +test "a new widget's columns from its natural width" { + assert_eq(widget_cols(0, 70.0, 5), 0) + assert_eq(widget_cols(110, 70.0, 5), 2) + assert_eq(widget_cols(400, 70.0, 5), 0) +} + +///| +test "boxes and cells in px" { + let b = box({ col: 1, row: 2, w: 2, h: 1, }, 70.0) + assert_eq(b, (78.0, 144.0, 148.0, 64.0)) + assert_eq(cell_at(80.0, 150.0, 70.0), (1, 2)) + assert_eq(cell_under(80.0, 150.0, 70.0), Some((1, 2))) + assert_eq(cell_under(72.0, 150.0, 70.0), None) // in the column gap + assert_eq(cell_under(-1.0, 5.0, 70.0), None) +} + +///| +test "viewport to grid" { + assert_eq(columns_for(390), 5) + assert_eq(columns_for(600), 6) + assert_eq(column_width(358.0, 5), 65.2) + assert_eq(rows_fit(500.0), 7) + assert_eq(rows_fit(10.0), 1) +} diff --git a/grid/moon.pkg b/grid/moon.pkg new file mode 100644 index 0000000..c4bcced --- /dev/null +++ b/grid/moon.pkg @@ -0,0 +1,3 @@ +import { + "moonbitlang/core/cmp", +} diff --git a/grid/pkg.generated.mbti b/grid/pkg.generated.mbti new file mode 100644 index 0000000..e98b98b --- /dev/null +++ b/grid/pkg.generated.mbti @@ -0,0 +1,84 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/launcher/grid" + +import { + "moonbitlang/core/debug", +} + +// Values +pub fn box(Cell, Double) -> (Double, Double, Double, Double) + +pub fn cell_at(Double, Double, Double) -> (Int32, Int32) + +pub let cell_px : Int32 + +pub fn cell_under(Double, Double, Double) -> (Int32, Int32)? + +pub fn clear_cells(Array[Slot], Int32, Int32) -> Unit + +pub let col_gap : Int32 + +pub fn column_width(Double, Int32) -> Double + +pub fn columns_for(Int32) -> Int32 + +pub fn fit(Double, Int32, Int32, Double, Double, Int32, Int32) -> Int32 + +pub fn move_slot(Array[Slot], Int32, Int32) -> Unit + +pub fn pack(Array[Slot], Int32, Int32, hidden? : (Int32) -> Bool) -> Packed + +pub fn pin(Array[Slot], Int32, Int32, Int32, Int32, Int32) -> Unit + +pub let row_gap : Int32 + +pub fn rows_fit(Double) -> Int32 + +pub fn span(Int32, Double, Double) -> Double + +pub fn widget_cols(Int32, Double, Int32) -> Int32 + +pub fn widget_rows(Int32) -> Int32 + +// Errors + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct Cell { + col : Int32 + row : Int32 + w : Int32 + h : Int32 +} + +#derive(Eq, @debug.Debug) +pub(all) enum Kind { + App + Widget +} + +pub(all) struct Packed { + cells : Array[Cell?] + rows : Int32 +} + +#derive(Eq, @debug.Debug) +pub(all) struct Slot { + kind : Kind + str : String + wid : Int32 + mut w : Int32 + mut rows : Int32 + mut x : Int32 + mut y : Int32 + key : Int32 +} +pub fn Slot::app(String, key? : Int32) -> Self +pub fn Slot::cols(Self, Int32) -> Int32 +pub fn Slot::height(Self) -> Int32 +pub fn Slot::pinned(Self, Int32) -> Bool +pub fn Slot::widget(String, Int32, w? : Int32, rows? : Int32, key? : Int32) -> Self + +// Type aliases + +// Traits diff --git a/jsonx/jsonx.mbt b/jsonx/jsonx.mbt new file mode 100644 index 0000000..777753d --- /dev/null +++ b/jsonx/jsonx.mbt @@ -0,0 +1,52 @@ +///| +/// Small accessors over `Json`, so decoding code reads as lookups with defaults. + +///| +pub fn get(j : Json, key : String) -> Json? { + match j { + Object(o) => o.get(key) + _ => None + } +} + +///| +pub fn str(j : Json, key : String, default~ : String = "") -> String { + match get(j, key) { + Some(String(s)) => s + _ => default + } +} + +///| +pub fn int(j : Json, key : String, default~ : Int32 = 0) -> Int32 { + match get(j, key) { + Some(Number(n, ..)) => n.to_int() + Some(True) => 1 + _ => default + } +} + +///| +pub fn bool(j : Json, key : String, default~ : Bool = false) -> Bool { + match get(j, key) { + Some(True) => true + Some(False) => false + Some(Number(n, ..)) => n != 0.0 + _ => default + } +} + +///| +pub fn arr(j : Json, key : String) -> Array[Json] { + match get(j, key) { + Some(Array(a)) => a + _ => [] + } +} + +///| +pub fn parse(text : String) -> Json? { + Some(@json.parse(text)) catch { + _ => None + } +} diff --git a/jsonx/jsonx_wbtest.mbt b/jsonx/jsonx_wbtest.mbt new file mode 100644 index 0000000..8a5e6d8 --- /dev/null +++ b/jsonx/jsonx_wbtest.mbt @@ -0,0 +1,13 @@ +///| +test "accessors with defaults" { + let j = parse("{\"a\":\"x\",\"n\":3,\"b\":true,\"l\":[1,2],\"o\":{}}").unwrap() + assert_eq(str(j, "a"), "x") + assert_eq(str(j, "zz", default="d"), "d") + assert_eq(int(j, "n"), 3) + assert_eq(int(j, "b"), 1) + assert_eq(int(j, "a", default=-1), -1) + assert_true(bool(j, "b")) + assert_eq(arr(j, "l").length(), 2) + assert_eq(arr(j, "o").length(), 0) + assert_true(parse("{") is None) +} diff --git a/jsonx/moon.pkg b/jsonx/moon.pkg new file mode 100644 index 0000000..f9f1d1a --- /dev/null +++ b/jsonx/moon.pkg @@ -0,0 +1,3 @@ +import { + "moonbitlang/core/json", +} diff --git a/jsonx/pkg.generated.mbti b/jsonx/pkg.generated.mbti new file mode 100644 index 0000000..aae3d83 --- /dev/null +++ b/jsonx/pkg.generated.mbti @@ -0,0 +1,27 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/launcher/jsonx" + +import { + "moonbitlang/core/json", +} + +// Values +pub fn arr(@json.Json, String) -> Array[@json.Json] + +pub fn bool(@json.Json, String, default? : Bool) -> Bool + +pub fn get(@json.Json, String) -> @json.Json? + +pub fn int(@json.Json, String, default? : Int32) -> Int32 + +pub fn parse(String) -> @json.Json? + +pub fn str(@json.Json, String, default? : String) -> String + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/legacy/.gitignore b/legacy/.gitignore new file mode 100644 index 0000000..c8a7768 --- /dev/null +++ b/legacy/.gitignore @@ -0,0 +1,11 @@ +__pycache__/ +node_modules/ +.pixi/ +android/.gradle/ +android/build/ +android/app/build/ +android/local.properties +build/ +build-*/ +android-wasm/target/ +android-wasm/assets/*.wasm diff --git a/legacy/README.md b/legacy/README.md new file mode 100644 index 0000000..e1c6b4f --- /dev/null +++ b/legacy/README.md @@ -0,0 +1,41 @@ +> **This is the previous implementation.** The launcher is now written in MoonBit at the repository root (see the top-level README). This folder keeps the ultra WebView build (`web/`, `android/`), the Qt rewrite (`qt/`) and the experiments (`wasi/`, `android-wasm/`) with paths fixed so they still build from here; nothing in it is maintained beyond that. Its CI runs only by hand (`.gitea/workflows/legacy.yml`, `.github/workflows/legacy.yml`). + +# ultra launcher + +An Android home screen written as an [ultra](https://github.com/nandi-conda/ultra) app (LPython compiled to WebAssembly, Elm-style). The home starts blank (add a clock widget if you want one): long-press it to add apps (the drawer opens in a pick mode) or widgets, and long-press anything on it to drag it somewhere else; let go without moving to get its menu, or, for a widget, handles on its edges that resize it to the grid. Swipe down for the drawer with every app and a search (Enter opens the first match); long-press an app there for its menu (add to home, app info, uninstall; system apps have no uninstall), and swipe up to close it. The panel at the top has a **Windows** button that opens Recents. The layout is saved in localStorage. + +## Install + +Releases now come from the MoonBit build at the repository root; see the top-level README. Open it once, press Home, and pick **ultra Home** as the default. Builds are signed with the committed `android/app/debug.keystore`, so each one installs over the last. + +The **Windows** button uses an accessibility service (`RecentsService`, which only performs the Recents action). Enable it once under Settings → Accessibility; on Android 13+ a sideloaded APK may first need App info → ⋮ → Allow restricted settings. + +## Layout + +- `web/` is the UI: `app.py` is the ultra app and `app.wasm` its committed build, with `index.html`, `style.css` and the `ultra.js` / `ui.css` runtime the build copies in. `apps.json` and `widgets.json` are demo data for desktop browsers. +- `android/` is a small native shell (Java, no dependencies) that serves `web/` to a transparent WebView over the wallpaper. It answers `apps.json` from `LauncherApps` and `widgets.json` from the installed widget providers, hands icons to the page through the `window.Android` bridge, and draws real `AppWidgetHostView`s over the slots the page reports. +- The ultra framework comes from the `ultra` conda package on [prefix.dev/nandi-testing](https://prefix.dev/channels/nandi-testing), which pixi installs. +- `tests/e2e.cjs` is a Playwright test of the browser demo. + +## Build + +```sh +pixi run build # web/app.py -> web/app.wasm +pixi run install-playwright && pixi run test +cd android && ./gradlew assembleDebug # needs JDK 17 and the Android SDK +``` + +`pixi run serve` serves `web/` on http://localhost:8000. In a desktop browser the launcher runs against the demo JSON files, shows a toast instead of launching, and draws widgets as labelled placeholders. Click the bar at the top to open the drawer. + +Every push to ultra's main publishes a new `ultra` package. To pick it up, run `pixi update ultra`, rebuild, and commit the rebuilt `web/` files. + +## Qt rewrite (in progress) + +`qt/` is the launcher rewritten as a Qt Quick (QML) app for Android, replacing ultra and the WebView. `qt/qml` is the UI (`Main.qml`, with the grid packing in `Layout.js`), `qt/src` a thin C++ backend, and `qt/android` the Java side (`HomeActivity`, a `QtActivity` that lists apps, draws icons, launches, and hosts the native widget views over the QML slots). It uses the same package (`dev.ultra.launcher`) and key as the WebView build, so it installs over it, from the releases on the Gitea forge ([experiments/launcher](https://git.site.latha.org/experiments/launcher)), where `.gitea/workflows/launcher.yml` tests, builds and publishes an APK on every push to main (`ci/gitea-apk.sh`); the installed app updates itself from the latest release there. + +```sh +node qt/tests/layout.test.mjs # grid packing +cmake -S qt -B build && cmake --build build # desktop build, needs Qt 6.8+ +build/ultrahome # try it against the demo apps +QT_QPA_PLATFORM=offscreen build/ultrahome_e2e # end-to-end test of the UI +``` diff --git a/android-wasm/Cargo.lock b/legacy/android-wasm/Cargo.lock similarity index 100% rename from android-wasm/Cargo.lock rename to legacy/android-wasm/Cargo.lock diff --git a/android-wasm/Cargo.toml b/legacy/android-wasm/Cargo.toml similarity index 100% rename from android-wasm/Cargo.toml rename to legacy/android-wasm/Cargo.toml diff --git a/android-wasm/build.sh b/legacy/android-wasm/build.sh similarity index 100% rename from android-wasm/build.sh rename to legacy/android-wasm/build.sh diff --git a/android-wasm/java/dev/ultra/launcher/wasm/LauncherActivity.java b/legacy/android-wasm/java/dev/ultra/launcher/wasm/LauncherActivity.java similarity index 100% rename from android-wasm/java/dev/ultra/launcher/wasm/LauncherActivity.java rename to legacy/android-wasm/java/dev/ultra/launcher/wasm/LauncherActivity.java diff --git a/android-wasm/java/dev/ultra/launcher/wasm/RecentsService.java b/legacy/android-wasm/java/dev/ultra/launcher/wasm/RecentsService.java similarity index 100% rename from android-wasm/java/dev/ultra/launcher/wasm/RecentsService.java rename to legacy/android-wasm/java/dev/ultra/launcher/wasm/RecentsService.java diff --git a/android-wasm/res/mipmap-xxxhdpi/ic_launcher.png b/legacy/android-wasm/res/mipmap-xxxhdpi/ic_launcher.png similarity index 100% rename from android-wasm/res/mipmap-xxxhdpi/ic_launcher.png rename to legacy/android-wasm/res/mipmap-xxxhdpi/ic_launcher.png diff --git a/android-wasm/res/values/strings.xml b/legacy/android-wasm/res/values/strings.xml similarity index 100% rename from android-wasm/res/values/strings.xml rename to legacy/android-wasm/res/values/strings.xml diff --git a/android-wasm/res/values/styles.xml b/legacy/android-wasm/res/values/styles.xml similarity index 100% rename from android-wasm/res/values/styles.xml rename to legacy/android-wasm/res/values/styles.xml diff --git a/android-wasm/res/xml/recents_service.xml b/legacy/android-wasm/res/xml/recents_service.xml similarity index 100% rename from android-wasm/res/xml/recents_service.xml rename to legacy/android-wasm/res/xml/recents_service.xml diff --git a/android-wasm/src/lib.rs b/legacy/android-wasm/src/lib.rs similarity index 100% rename from android-wasm/src/lib.rs rename to legacy/android-wasm/src/lib.rs diff --git a/android/app/build.gradle b/legacy/android/app/build.gradle similarity index 100% rename from android/app/build.gradle rename to legacy/android/app/build.gradle diff --git a/legacy/android/app/debug.keystore b/legacy/android/app/debug.keystore new file mode 100644 index 0000000..71f670b Binary files /dev/null and b/legacy/android/app/debug.keystore differ diff --git a/android/app/src/main/AndroidManifest.xml b/legacy/android/app/src/main/AndroidManifest.xml similarity index 100% rename from android/app/src/main/AndroidManifest.xml rename to legacy/android/app/src/main/AndroidManifest.xml diff --git a/android/app/src/main/java/dev/ultra/launcher/MainActivity.java b/legacy/android/app/src/main/java/dev/ultra/launcher/MainActivity.java similarity index 100% rename from android/app/src/main/java/dev/ultra/launcher/MainActivity.java rename to legacy/android/app/src/main/java/dev/ultra/launcher/MainActivity.java diff --git a/qt/android/src/dev/ultra/launcher/RecentsService.java b/legacy/android/app/src/main/java/dev/ultra/launcher/RecentsService.java similarity index 100% rename from qt/android/src/dev/ultra/launcher/RecentsService.java rename to legacy/android/app/src/main/java/dev/ultra/launcher/RecentsService.java diff --git a/android/app/src/main/java/dev/ultra/launcher/Updater.java b/legacy/android/app/src/main/java/dev/ultra/launcher/Updater.java similarity index 100% rename from android/app/src/main/java/dev/ultra/launcher/Updater.java rename to legacy/android/app/src/main/java/dev/ultra/launcher/Updater.java diff --git a/qt/android/res/drawable/ic_launcher_background.xml b/legacy/android/app/src/main/res/drawable/ic_launcher_background.xml similarity index 100% rename from qt/android/res/drawable/ic_launcher_background.xml rename to legacy/android/app/src/main/res/drawable/ic_launcher_background.xml diff --git a/qt/android/res/drawable/ic_launcher_foreground.xml b/legacy/android/app/src/main/res/drawable/ic_launcher_foreground.xml similarity index 100% rename from qt/android/res/drawable/ic_launcher_foreground.xml rename to legacy/android/app/src/main/res/drawable/ic_launcher_foreground.xml diff --git a/qt/android/res/mipmap-anydpi-v26/ic_launcher.xml b/legacy/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml similarity index 100% rename from qt/android/res/mipmap-anydpi-v26/ic_launcher.xml rename to legacy/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml diff --git a/qt/android/res/values/strings.xml b/legacy/android/app/src/main/res/values/strings.xml similarity index 100% rename from qt/android/res/values/strings.xml rename to legacy/android/app/src/main/res/values/strings.xml diff --git a/legacy/android/app/src/main/res/values/styles.xml b/legacy/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..9449e95 --- /dev/null +++ b/legacy/android/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/qt/android/res/xml/recents_service.xml b/legacy/android/app/src/main/res/xml/recents_service.xml similarity index 100% rename from qt/android/res/xml/recents_service.xml rename to legacy/android/app/src/main/res/xml/recents_service.xml diff --git a/android/build.gradle b/legacy/android/build.gradle similarity index 100% rename from android/build.gradle rename to legacy/android/build.gradle diff --git a/android/gradle.properties b/legacy/android/gradle.properties similarity index 100% rename from android/gradle.properties rename to legacy/android/gradle.properties diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/legacy/android/gradle/wrapper/gradle-wrapper.jar similarity index 100% rename from android/gradle/wrapper/gradle-wrapper.jar rename to legacy/android/gradle/wrapper/gradle-wrapper.jar diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/legacy/android/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from android/gradle/wrapper/gradle-wrapper.properties rename to legacy/android/gradle/wrapper/gradle-wrapper.properties diff --git a/android/gradlew b/legacy/android/gradlew similarity index 100% rename from android/gradlew rename to legacy/android/gradlew diff --git a/android/gradlew.bat b/legacy/android/gradlew.bat similarity index 100% rename from android/gradlew.bat rename to legacy/android/gradlew.bat diff --git a/android/settings.gradle b/legacy/android/settings.gradle similarity index 100% rename from android/settings.gradle rename to legacy/android/settings.gradle diff --git a/legacy/ci/gitea-apk.sh b/legacy/ci/gitea-apk.sh new file mode 100755 index 0000000..d55b783 --- /dev/null +++ b/legacy/ci/gitea-apk.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Tests the Qt launcher (qt/), builds its APK and publishes it as a Gitea release: +# build-, holding ultra-launcher.apk and version.json, made a draft first +# and published once both files are up, so the latest release never lacks them. +# Runs in .gitea/workflows/legacy.yml (JDK 17 container, as root), from legacy/; publishes only +# when LEGACY_PUBLISH=true, so it does not compete with the MoonBit build's releases. +set -euo pipefail +cd "$(dirname "$0")/.." + +QT_VERSION=6.8.3 +NDK=26.1.10909125 +# Minutes since the epoch: always above the GitHub builds' run numbers and always rising. +VERSION_CODE=$(( $(date +%s) / 60 )) +COMMIT="${GITHUB_SHA:-$(git rev-parse HEAD)}" + +echo "== tools" +apt-get update -qq +# The host Qt tools (moc, qmlimportscanner, qmlcachegen) need glib, GL and friends; +# g++ builds the desktop test and nodejs runs the layout test. +apt-get install -y -qq --no-install-recommends python3-pip python3-venv ninja-build cmake g++ nodejs unzip curl ca-certificates git \ + libglib2.0-0t64 libgl1 libegl1 libopengl0 libgl-dev libglx-dev libopengl-dev libegl-dev libxkbcommon-dev \ + libfontconfig1 libfreetype6 libxkbcommon0 libdbus-1-3 >/dev/null +python3 -m venv /opt/aqt && /opt/aqt/bin/pip install -q aqtinstall + +echo "== Qt $QT_VERSION (android arm64 + host)" +/opt/aqt/bin/aqt install-qt linux android "$QT_VERSION" android_arm64_v8a -O /opt/Qt --autodesktop >/dev/null +QT_ROOT=/opt/Qt/$QT_VERSION/android_arm64_v8a +QT_HOST=/opt/Qt/$QT_VERSION/gcc_64 + +echo "== tests (desktop Qt)" +node qt/tests/layout.test.mjs +cmake -S qt -B build-desktop -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$QT_HOST" +cmake --build build-desktop +QT_QPA_PLATFORM=offscreen build-desktop/ultrahome_e2e + +echo "== Android SDK + NDK $NDK" +export ANDROID_SDK_ROOT=/opt/android-sdk +mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" +curl -fsSL -o /tmp/cmdline.zip https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip +unzip -q /tmp/cmdline.zip -d "$ANDROID_SDK_ROOT/cmdline-tools" && mv "$ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools" "$ANDROID_SDK_ROOT/cmdline-tools/latest" +yes | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null || true +"$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --install "platform-tools" "ndk;$NDK" "platforms;android-35" "build-tools;35.0.0" >/dev/null +export ANDROID_NDK_ROOT=$ANDROID_SDK_ROOT/ndk/$NDK + +echo "== build (versionCode $VERSION_CODE)" +# Signed with the committed key, like every earlier build, so it installs over them. +export QT_ANDROID_KEYSTORE_PATH="$PWD/android/app/debug.keystore" +export QT_ANDROID_KEYSTORE_ALIAS=androiddebugkey +export QT_ANDROID_KEYSTORE_STORE_PASS=android +export QT_ANDROID_KEYSTORE_KEY_PASS=android +"$QT_ROOT/bin/qt-cmake" -S qt -B build-android -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DANDROID_SDK_ROOT="$ANDROID_SDK_ROOT" -DANDROID_NDK_ROOT="$ANDROID_NDK_ROOT" \ + -DQT_HOST_PATH="$QT_HOST" -DQT_ANDROID_SIGN_APK=ON -DVERSION_CODE="$VERSION_CODE" +cmake --build build-android --target apk +apk=$(find build-android -name "*-signed.apk" | head -1) +test -n "$apk" || { find build-android -name "*.apk"; exit 1; } +cp "$apk" ultra-launcher.apk +printf '{"versionCode": %s, "commit": "%s"}\n' "$VERSION_CODE" "$COMMIT" > version.json + +if [ "${LEGACY_PUBLISH:-false}" != "true" ]; then + echo "built legacy/ultra-launcher.apk; not publishing (LEGACY_PUBLISH != true)" + exit 0 +fi + +echo "== release build-$VERSION_CODE" +server="${GITHUB_SERVER_URL:-https://git.site.latha.org}" +repo="${GITHUB_REPOSITORY:-experiments/launcher}" +api="${server%/}/api/v1/repos/$repo" +token="${GITEA_TOKEN:-${GITHUB_TOKEN:-}}" +test -n "$token" || { echo "no GITEA_TOKEN/GITHUB_TOKEN in the environment"; exit 1; } +auth=(-H "Authorization: token $token") +tag="build-$VERSION_CODE" +id=$(curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X POST "$api/releases" \ + -d "{\"tag_name\": \"$tag\", \"name\": \"ultra Home build $VERSION_CODE\", \"target_commitish\": \"$COMMIT\", \"draft\": true, \"body\": \"Qt launcher built from $COMMIT.\"}" \ + | python3 -c 'import sys, json; print(json.load(sys.stdin)["id"])') +curl -fsS "${auth[@]}" -F "attachment=@ultra-launcher.apk" "$api/releases/$id/assets?name=ultra-launcher.apk" >/dev/null +curl -fsS "${auth[@]}" -F "attachment=@version.json" "$api/releases/$id/assets?name=version.json" >/dev/null +curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X PATCH "$api/releases/$id" -d '{"draft": false}' >/dev/null +echo "published $tag to $server/$repo" diff --git a/pixi.toml b/legacy/pixi.toml similarity index 100% rename from pixi.toml rename to legacy/pixi.toml diff --git a/qt/CMakeLists.txt b/legacy/qt/CMakeLists.txt similarity index 100% rename from qt/CMakeLists.txt rename to legacy/qt/CMakeLists.txt diff --git a/qt/android/AndroidManifest.xml b/legacy/qt/android/AndroidManifest.xml similarity index 100% rename from qt/android/AndroidManifest.xml rename to legacy/qt/android/AndroidManifest.xml diff --git a/legacy/qt/android/res/drawable/ic_launcher_background.xml b/legacy/qt/android/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..ebba2d9 --- /dev/null +++ b/legacy/qt/android/res/drawable/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + + diff --git a/legacy/qt/android/res/drawable/ic_launcher_foreground.xml b/legacy/qt/android/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..d1f97a6 --- /dev/null +++ b/legacy/qt/android/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/legacy/qt/android/res/mipmap-anydpi-v26/ic_launcher.xml b/legacy/qt/android/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6b78462 --- /dev/null +++ b/legacy/qt/android/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/legacy/qt/android/res/values/strings.xml b/legacy/qt/android/res/values/strings.xml new file mode 100644 index 0000000..da3aee5 --- /dev/null +++ b/legacy/qt/android/res/values/strings.xml @@ -0,0 +1,7 @@ + + + ultra Home + ultra Home window list + Lets the home screen\'s Windows button open Recents + Turn this on so the Windows button on the ultra Home screen can show your open windows (Recents). Android only lets accessibility services open Recents. This service reads nothing on screen and does nothing else. + diff --git a/qt/android/res/values/styles.xml b/legacy/qt/android/res/values/styles.xml similarity index 100% rename from qt/android/res/values/styles.xml rename to legacy/qt/android/res/values/styles.xml diff --git a/legacy/qt/android/res/xml/recents_service.xml b/legacy/qt/android/res/xml/recents_service.xml new file mode 100644 index 0000000..f5eb58f --- /dev/null +++ b/legacy/qt/android/res/xml/recents_service.xml @@ -0,0 +1,9 @@ + + + diff --git a/qt/android/src/dev/ultra/launcher/HomeActivity.java b/legacy/qt/android/src/dev/ultra/launcher/HomeActivity.java similarity index 100% rename from qt/android/src/dev/ultra/launcher/HomeActivity.java rename to legacy/qt/android/src/dev/ultra/launcher/HomeActivity.java diff --git a/qt/android/src/dev/ultra/launcher/Native.java b/legacy/qt/android/src/dev/ultra/launcher/Native.java similarity index 100% rename from qt/android/src/dev/ultra/launcher/Native.java rename to legacy/qt/android/src/dev/ultra/launcher/Native.java diff --git a/legacy/qt/android/src/dev/ultra/launcher/RecentsService.java b/legacy/qt/android/src/dev/ultra/launcher/RecentsService.java new file mode 100644 index 0000000..9ef3551 --- /dev/null +++ b/legacy/qt/android/src/dev/ultra/launcher/RecentsService.java @@ -0,0 +1,41 @@ +package dev.ultra.launcher; + +import android.accessibilityservice.AccessibilityService; +import android.content.Intent; +import android.view.accessibility.AccessibilityEvent; + +/** + * An accessibility service that does nothing but open Recents (the system's list of open + * windows) for the home screen's Windows button. Android lets no other app open Recents, + * so the user turns this on once under Settings > Accessibility. It reads no window + * content and asks for no events. + */ +public class RecentsService extends AccessibilityService { + private static volatile RecentsService running; + + /** Open Recents; false when the service isn't turned on. */ + static boolean showRecents() { + RecentsService s = running; + return s != null && s.performGlobalAction(GLOBAL_ACTION_RECENTS); + } + + @Override + protected void onServiceConnected() { + running = this; + } + + @Override + public boolean onUnbind(Intent intent) { + running = null; + return super.onUnbind(intent); + } + + @Override + public void onDestroy() { + running = null; + super.onDestroy(); + } + + @Override public void onAccessibilityEvent(AccessibilityEvent event) { } + @Override public void onInterrupt() { } +} diff --git a/qt/android/src/dev/ultra/launcher/Updater.java b/legacy/qt/android/src/dev/ultra/launcher/Updater.java similarity index 100% rename from qt/android/src/dev/ultra/launcher/Updater.java rename to legacy/qt/android/src/dev/ultra/launcher/Updater.java diff --git a/qt/demo/apps.json b/legacy/qt/demo/apps.json similarity index 100% rename from qt/demo/apps.json rename to legacy/qt/demo/apps.json diff --git a/qt/demo/widgets.json b/legacy/qt/demo/widgets.json similarity index 100% rename from qt/demo/widgets.json rename to legacy/qt/demo/widgets.json diff --git a/qt/qml/AppIcon.qml b/legacy/qt/qml/AppIcon.qml similarity index 100% rename from qt/qml/AppIcon.qml rename to legacy/qt/qml/AppIcon.qml diff --git a/qt/qml/Drawer.qml b/legacy/qt/qml/Drawer.qml similarity index 100% rename from qt/qml/Drawer.qml rename to legacy/qt/qml/Drawer.qml diff --git a/qt/qml/Layout.js b/legacy/qt/qml/Layout.js similarity index 100% rename from qt/qml/Layout.js rename to legacy/qt/qml/Layout.js diff --git a/qt/qml/Main.qml b/legacy/qt/qml/Main.qml similarity index 100% rename from qt/qml/Main.qml rename to legacy/qt/qml/Main.qml diff --git a/qt/qml/PillButton.qml b/legacy/qt/qml/PillButton.qml similarity index 100% rename from qt/qml/PillButton.qml rename to legacy/qt/qml/PillButton.qml diff --git a/qt/qml/SearchField.qml b/legacy/qt/qml/SearchField.qml similarity index 100% rename from qt/qml/SearchField.qml rename to legacy/qt/qml/SearchField.qml diff --git a/qt/qml/Sheet.qml b/legacy/qt/qml/Sheet.qml similarity index 100% rename from qt/qml/Sheet.qml rename to legacy/qt/qml/Sheet.qml diff --git a/qt/qml/SheetButton.qml b/legacy/qt/qml/SheetButton.qml similarity index 100% rename from qt/qml/SheetButton.qml rename to legacy/qt/qml/SheetButton.qml diff --git a/qt/qml/Tile.qml b/legacy/qt/qml/Tile.qml similarity index 100% rename from qt/qml/Tile.qml rename to legacy/qt/qml/Tile.qml diff --git a/qt/src/backend.cpp b/legacy/qt/src/backend.cpp similarity index 100% rename from qt/src/backend.cpp rename to legacy/qt/src/backend.cpp diff --git a/qt/src/backend.h b/legacy/qt/src/backend.h similarity index 100% rename from qt/src/backend.h rename to legacy/qt/src/backend.h diff --git a/qt/src/iconprovider.cpp b/legacy/qt/src/iconprovider.cpp similarity index 100% rename from qt/src/iconprovider.cpp rename to legacy/qt/src/iconprovider.cpp diff --git a/qt/src/iconprovider.h b/legacy/qt/src/iconprovider.h similarity index 100% rename from qt/src/iconprovider.h rename to legacy/qt/src/iconprovider.h diff --git a/qt/src/main.cpp b/legacy/qt/src/main.cpp similarity index 100% rename from qt/src/main.cpp rename to legacy/qt/src/main.cpp diff --git a/qt/tests/e2e.cpp b/legacy/qt/tests/e2e.cpp similarity index 100% rename from qt/tests/e2e.cpp rename to legacy/qt/tests/e2e.cpp diff --git a/qt/tests/layout.test.mjs b/legacy/qt/tests/layout.test.mjs similarity index 100% rename from qt/tests/layout.test.mjs rename to legacy/qt/tests/layout.test.mjs diff --git a/legacy/tests/e2e.cjs b/legacy/tests/e2e.cjs new file mode 100644 index 0000000..ec7345c --- /dev/null +++ b/legacy/tests/e2e.cjs @@ -0,0 +1,189 @@ +// Browser smoke test for the launcher's web UI, against the demo apps.json and widgets.json. +// pixi run test (or: pixi run serve & then node tests/e2e.cjs) +const assert = require("assert"); +const { chromium } = require(process.env.PLAYWRIGHT || "playwright"); +const BASE = process.env.BASE || "http://localhost:8000"; + +(async () => { + const b = await chromium.launch(); + const p = await b.newPage(); + p.on("pageerror", (e) => { console.error("page error:", e.message); process.exitCode = 1; }); + + const settle = () => p.waitForTimeout(250); // renders land on the next frame, which can lag here + await p.emulateMedia({ reducedMotion: "reduce" }); // no sliding drawer under the pointer + await p.goto(BASE + "/"); + await p.evaluate(() => localStorage.clear()); + await p.reload(); + await p.waitForSelector(".hint"); + assert.ok(!(await p.$(".clock")), "home has no built-in clock"); + const longpress = async (sel, fy = 0.5) => { + const r = await p.locator(sel).first().boundingBox(); + await p.mouse.move(r.x + r.width / 2, r.y + r.height * fy); + await p.mouse.down(); await p.waitForTimeout(650); await p.mouse.up(); await settle(); + }; + // the home menu's update check goes to the shell and closes the menu + await longpress(".hint"); + await p.click(".sheet-item >> text=Check for updates"); await settle(); + assert.equal(await p.textContent("#toast"), "Check for updates"); + assert.ok(!(await p.$(".sheet")), "the menu closes"); + const homeApps = () => p.$$eval(".slots .name", (ns) => ns.map((n) => n.textContent)); + // long press on the blank home: add apps through the drawer's pick mode + await longpress(".hint"); + await p.click(".sheet-item >> text=Add apps"); await settle(); + for (const i of [4, 8, 12]) await p.click(`.apps .tile:nth-child(${i})`); + await settle(); + assert.equal(await p.$$eval(".apps .tile.on", (ts) => ts.length), 3); + await p.click(".drawer-head >> text=Done"); await settle(); + assert.deepEqual(await homeApps(), ["Chrome", "Gmail", "Phone"]); + // add a widget: long press on blank home, below the apps + await longpress(".home", 0.95); + await p.click(".sheet-item >> text=Add widget"); + await p.waitForSelector(".widget-list li"); + // search the picker by widget name and by the app it comes from + const widgetNames = () => p.$$eval(".widget-list .widget-name", (ns) => ns.map((n) => n.firstChild.textContent)); + await p.fill(".widget-search", "cal"); await settle(); + assert.deepEqual(await widgetNames(), ["Calendar"]); + await p.fill(".widget-search", "goo"); await settle(); + assert.deepEqual(await widgetNames(), ["Weather"]); + await p.fill(".widget-search", "zzz"); await settle(); + assert.equal(await p.textContent(".sheet .empty"), "No widgets match."); + await p.fill(".widget-search", ""); await settle(); + await p.click(".widget-list li:first-child"); await settle(); + assert.equal(await p.getAttribute(".widget-slot", "data-wid"), "100"); + assert.equal(await p.textContent(".widget-label"), "Clock"); + // hold a home app and drag it: reorder + const drag = async (from, to) => { + const a = await p.locator(from).first().boundingBox(), z = await p.locator(to).first().boundingBox(); + await p.mouse.move(a.x + a.width / 2, a.y + a.height / 2); + await p.mouse.down(); await p.waitForTimeout(650); await settle(); + assert.ok(await p.$(".slots > .lifted"), "a long press lifts the slot"); + await p.mouse.move(z.x + z.width / 2, z.y + z.height / 2, { steps: 5 }); await settle(); + await p.mouse.up(); await settle(); + }; + await drag(".slots .tile:nth-child(2)", ".slots .tile:nth-child(1)"); + assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]); + assert.ok(!(await p.$(".sheet")), "a drag doesn't open the menu"); + assert.ok(!(await p.$(".slots > .lifted"))); + await drag(".slots .tile:nth-child(1)", ".slots .tile:nth-child(3)"); + assert.deepEqual(await homeApps(), ["Chrome", "Phone", "Gmail"]); + // hold without moving: the menu + await longpress(".slots .tile:nth-child(3)"); + await p.click(".sheet-item >> text=Move earlier"); await settle(); + assert.deepEqual(await homeApps(), ["Chrome", "Gmail", "Phone"]); + await longpress(".slots .tile:nth-child(1)"); + await p.click(".sheet-item >> text=Move later"); await settle(); + assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]); + // the grid runs down the screen; an app dropped in an empty cell there stays in it, + // and the rest stay packed + const rows = await p.$eval(".slots", (s) => getComputedStyle(s).gridTemplateRows.split(" ").length); + assert.ok(rows >= 5, `rows fill the screen: ${rows}`); + const tileAt = (n) => p.locator(`.slots .tile:has-text("${n}")`).boundingBox(); + const g0 = await tileAt("Gmail"), c0 = await tileAt("Chrome"), pitch = 64 + 8; + await p.mouse.move(g0.x + g0.width / 2, g0.y + g0.height / 2); + await p.mouse.down(); await p.waitForTimeout(650); await settle(); + await p.mouse.move(g0.x + g0.width / 2 + 10, g0.y + g0.height / 2 + 4 * pitch, { steps: 6 }); await settle(); + await p.mouse.up(); await settle(); + const g1 = await tileAt("Gmail"), c1 = await tileAt("Chrome"); + assert.ok(Math.abs(g1.y - g0.y - 4 * pitch) < 3, `left four rows down: ${g1.y - g0.y}`); + assert.equal(Math.round(c1.x), Math.round(g0.x), "Chrome moves up into the packed first cell"); + await p.reload(); await p.waitForSelector(".slots .tile"); + assert.ok(Math.abs((await tileAt("Gmail")).y - g1.y) < 3, "its cell is saved"); + // dragging it back over an app puts it back in the packed order + const c2 = await tileAt("Chrome"); + await p.mouse.move(g1.x + g1.width / 2, g1.y + g1.height / 2); + await p.mouse.down(); await p.waitForTimeout(650); await settle(); + await p.mouse.move(c2.x + c2.width / 2, c2.y + c2.height / 2, { steps: 6 }); await settle(); + await p.mouse.up(); await settle(); + assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]); + assert.ok(Math.abs((await tileAt("Gmail")).y - c0.y) < 3, "back in the first row"); + await p.mouse.click(5, 300); await settle(); // a tap on empty home ends the drag gesture + // swipe down opens the drawer (and takes the widget off screen), search, long press adds + const swipe = (y0, y1) => p.evaluate(([y0, y1]) => { + const at = (y) => new Touch({ identifier: 1, target: document.body, clientX: 200, clientY: y }); + dispatchEvent(new TouchEvent("touchstart", { touches: [at(y0)], changedTouches: [at(y0)] })); + dispatchEvent(new TouchEvent("touchend", { touches: [], changedTouches: [at(y1)] })); + }, [y0, y1]); + await swipe(200, 500); + await p.waitForSelector(".drawer", { timeout: 2000 }); + assert.equal(await p.$$eval("[data-wid]", (ws) => ws.length), 0); + assert.ok(await p.$eval(".drawer input", (i) => i === document.activeElement), "opening the drawer focuses its search"); + await p.fill(".drawer input", "ma"); await settle(); + assert.deepEqual(await p.$$eval(".apps .name", (ns) => ns.map((n) => n.textContent)), ["Gmail", "Maps"]); + await p.press(".drawer input", "Enter"); await settle(); + assert.equal(await p.textContent("#toast"), "Open com.example.gmail/.MainActivity"); + assert.ok(!(await p.$(".drawer")), "launching closes the drawer"); + await swipe(200, 500); + await p.waitForSelector(".drawer .tile", { timeout: 2000 }); + await longpress(".apps .tile:first-child"); + assert.deepEqual(await p.$$eval(".sheet-item", (bs) => bs.map((b) => b.textContent)), ["Add to home", "App info", "Uninstall"]); + await p.click(".sheet-item:has-text('Uninstall')"); await settle(); + assert.equal(await p.textContent("#toast"), "Uninstall com.example.calculator/.MainActivity"); + assert.ok(!(await p.$(".sheet")) && (await p.$(".drawer")), "uninstalling closes the menu, not the drawer"); + await p.fill(".drawer input", "phone"); await settle(); + await longpress(".apps .tile:first-child"); + assert.ok(!(await p.$(".sheet-item:has-text('Uninstall')")), "system apps can't be uninstalled"); + await p.click(".sheet-overlay", { position: { x: 10, y: 10 } }); await p.fill(".drawer input", ""); await settle(); + await longpress(".apps .tile:first-child"); + await p.click(".sheet-item:has-text('Add to home')"); await settle(); + assert.equal(await p.textContent(".notice"), "Added to home"); + await swipe(600, 200); + await p.waitForSelector(".drawer", { state: "detached", timeout: 2000 }); // swipe up closes it + assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone", "Calculator"]); + // persisted; tap launches; remove + await p.reload(); await p.waitForSelector(".slots .tile"); + assert.equal(await p.$$eval(".slots > li", (ls) => ls.length), 5); + await p.click(".slots .tile:first-child"); await settle(); + assert.equal(await p.textContent("#toast"), "Open com.example.gmail/.MainActivity"); + // hold a widget without moving: resize handles; drag them to snap it to the grid + await longpress(".widget-slot"); + assert.ok(!(await p.$(".sheet")), "a widget gets handles, not the menu"); + assert.ok(await p.$(".widget-slot.resizing .resize-handle[data-edge=rb]")); + const size = () => p.$eval(".widget-slot", (w) => [Math.round(w.getBoundingClientRect().width), Math.round(w.getBoundingClientRect().height)]); + const [w0] = await size(); + const tile = await p.locator(".slots .tile").first().boundingBox(); + const hd = await p.locator(".resize-handle[data-edge=rb]").boundingBox(); + await p.mouse.move(hd.x + hd.width / 2, hd.y + hd.height / 2); + await p.mouse.down(); + const ws = await p.locator(".widget-slot").boundingBox(); + await p.mouse.move(ws.x + tile.width * 2.1, ws.y + 140, { steps: 8 }); await settle(); + await p.mouse.up(); await settle(); + const [w1, h1] = await size(); + assert.ok(w1 < w0 && Math.abs(w1 - (2 * tile.width + 8)) < 3, `two columns wide: ${w1} (tile ${tile.width})`); + assert.equal(h1, 2 * 64 + 8, "snapped to two whole rows of tiles"); + assert.ok(await p.$(".widget-slot.resizing"), "letting go of a handle keeps the handles"); + await p.click(".resize-bar >> text=Done"); await settle(); + assert.ok(!(await p.$(".resize-handle"))); + await p.reload(); await p.waitForSelector(".widget-slot"); + assert.deepEqual(await size(), [w1, h1], "the size is saved"); + // while it shows handles, dragging the widget itself moves it, without another long press + await longpress(".widget-slot"); + const atStart = () => p.$eval(".widget-slot", (w) => { + const r = w.getBoundingClientRect(), s = w.parentElement.getBoundingClientRect(); + return Math.abs(r.left - s.left) < 2 && Math.abs(r.top - s.top) < 2; + }); + assert.ok(!(await atStart())); + const wb = await p.locator(".widget-slot").boundingBox(), first = await p.locator(".slots > li").first().boundingBox(); + await p.mouse.move(wb.x + wb.width / 2, wb.y + wb.height / 2); + await p.mouse.down(); await settle(); + assert.ok(await p.$(".widget-slot.lifted"), "pressing a widget with handles picks it up"); + await p.mouse.move(first.x + first.width / 2, first.y + first.height / 2, { steps: 8 }); await settle(); + await p.mouse.up(); await settle(); + assert.ok(await atStart(), "dragged onto the top row, first cell"); + // the apps flow into the cells beside it: a 2x2 widget in 5 columns leaves room for all four + const beside = await p.$eval(".widget-slot", (w) => { + const r = w.getBoundingClientRect(); + return [...document.querySelectorAll(".slots .tile")].filter((t) => { + const b = t.getBoundingClientRect(); return b.top >= r.top - 1 && b.bottom <= r.bottom + 1; + }).length; + }); + assert.equal(beside, 4, "apps fill the cells beside the widget"); + assert.ok(await p.$(".widget-slot.resizing"), "it keeps its handles after the move"); + assert.ok(!(await p.$(".sheet"))); + await p.click(".resize-bar >> text=Remove"); await settle(); + assert.ok(!(await p.$(".widget-slot"))); + await p.evaluate(() => { window.ultraHome.reload(); }); await settle(); + assert.equal(await p.$$eval(".slots > li", (ls) => ls.length), 4); + console.log("launcher ok"); + + await b.close(); +})().catch((e) => { console.error(e); process.exit(1); }); diff --git a/tests/run.py b/legacy/tests/run.py similarity index 100% rename from tests/run.py rename to legacy/tests/run.py diff --git a/wasi/CMakeLists.txt b/legacy/wasi/CMakeLists.txt similarity index 100% rename from wasi/CMakeLists.txt rename to legacy/wasi/CMakeLists.txt diff --git a/wasi/build.sh b/legacy/wasi/build.sh similarity index 100% rename from wasi/build.sh rename to legacy/wasi/build.sh diff --git a/wasi/fonts.qrc b/legacy/wasi/fonts.qrc similarity index 100% rename from wasi/fonts.qrc rename to legacy/wasi/fonts.qrc diff --git a/wasi/fonts/DejaVuSans-Bold.ttf b/legacy/wasi/fonts/DejaVuSans-Bold.ttf similarity index 100% rename from wasi/fonts/DejaVuSans-Bold.ttf rename to legacy/wasi/fonts/DejaVuSans-Bold.ttf diff --git a/wasi/fonts/DejaVuSans.ttf b/legacy/wasi/fonts/DejaVuSans.ttf similarity index 100% rename from wasi/fonts/DejaVuSans.ttf rename to legacy/wasi/fonts/DejaVuSans.ttf diff --git a/wasi/pixi.lock b/legacy/wasi/pixi.lock similarity index 100% rename from wasi/pixi.lock rename to legacy/wasi/pixi.lock diff --git a/wasi/pixi.toml b/legacy/wasi/pixi.toml similarity index 100% rename from wasi/pixi.toml rename to legacy/wasi/pixi.toml diff --git a/wasi/src/launcher_window.cpp b/legacy/wasi/src/launcher_window.cpp similarity index 100% rename from wasi/src/launcher_window.cpp rename to legacy/wasi/src/launcher_window.cpp diff --git a/wasi/src/launcher_window.h b/legacy/wasi/src/launcher_window.h similarity index 100% rename from wasi/src/launcher_window.h rename to legacy/wasi/src/launcher_window.h diff --git a/wasi/src/layout.cpp b/legacy/wasi/src/layout.cpp similarity index 100% rename from wasi/src/layout.cpp rename to legacy/wasi/src/layout.cpp diff --git a/wasi/src/layout.h b/legacy/wasi/src/layout.h similarity index 100% rename from wasi/src/layout.h rename to legacy/wasi/src/layout.h diff --git a/wasi/src/main.cpp b/legacy/wasi/src/main.cpp similarity index 100% rename from wasi/src/main.cpp rename to legacy/wasi/src/main.cpp diff --git a/wasi/wit/deps/latha-gui/gui.wit b/legacy/wasi/wit/deps/latha-gui/gui.wit similarity index 100% rename from wasi/wit/deps/latha-gui/gui.wit rename to legacy/wasi/wit/deps/latha-gui/gui.wit diff --git a/wasi/wit/launcher.wit b/legacy/wasi/wit/launcher.wit similarity index 100% rename from wasi/wit/launcher.wit rename to legacy/wasi/wit/launcher.wit diff --git a/web/app.py b/legacy/web/app.py similarity index 100% rename from web/app.py rename to legacy/web/app.py diff --git a/web/app.wasm b/legacy/web/app.wasm similarity index 100% rename from web/app.wasm rename to legacy/web/app.wasm diff --git a/legacy/web/apps.json b/legacy/web/apps.json new file mode 100644 index 0000000..3318b39 --- /dev/null +++ b/legacy/web/apps.json @@ -0,0 +1,87 @@ +{ + "apps": [ + { + "label": "Calculator", + "component": "com.example.calculator/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f59e0b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Calendar", + "component": "com.example.calendar/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%233b82f6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Camera", + "component": "com.example.camera/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2364748b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Chrome", + "component": "com.example.chrome/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2322c55e%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Clock", + "component": "com.example.clock/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%230ea5e9%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Contacts", + "component": "com.example.contacts/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%236366f1%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Files", + "component": "com.example.files/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23eab308%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EF%3C/text%3E%3C/svg%3E" + }, + { + "label": "Gmail", + "component": "com.example.gmail/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ef4444%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EG%3C/text%3E%3C/svg%3E" + }, + { + "label": "Maps", + "component": "com.example.maps/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2310b981%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Messages", + "component": "com.example.messages/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%238b5cf6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Music", + "component": "com.example.music/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ec4899%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Phone", + "system": true, + "component": "com.example.phone/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2314b8a6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Photos", + "component": "com.example.photos/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f97316%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Play Store", + "system": true, + "component": "com.example.playstore/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2306b6d4%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Settings", + "system": true, + "component": "com.example.settings/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2371717a%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3ES%3C/text%3E%3C/svg%3E" + }, + { + "label": "Weather", + "component": "com.example.weather/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2338bdf8%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EW%3C/text%3E%3C/svg%3E" + } + ] +} \ No newline at end of file diff --git a/legacy/web/index.html b/legacy/web/index.html new file mode 100644 index 0000000..067159a --- /dev/null +++ b/legacy/web/index.html @@ -0,0 +1,360 @@ + + + + + + ultra · Launcher + + + + +
+
+ + + diff --git a/legacy/web/style.css b/legacy/web/style.css new file mode 100644 index 0000000..9892a0d --- /dev/null +++ b/legacy/web/style.css @@ -0,0 +1,153 @@ +/* Home screen layout; the components come from ui.css. The page is transparent so the + system wallpaper shows through the WebView. MainActivity sets --inset-top and + --inset-bottom to the status and navigation bar (and keyboard) heights. */ +:root { + --top: var(--inset-top, env(safe-area-inset-top, 0px)); + --bottom: var(--inset-bottom, env(safe-area-inset-bottom, 0px)); + --shadow-text: 0 1px 4px rgb(0 0 0 / .6); +} +html, body { background: transparent; } +html.demo { background: linear-gradient(160deg, #1e293b, #4c1d95 55%, #0f172a) fixed; } +body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: transparent; + user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; + overscroll-behavior: none; } +#app { max-width: 560px; margin: 0 auto; } + +/* ---- home */ +.home { min-height: 100vh; box-sizing: border-box; + padding: calc(var(--top) + 1rem) 16px calc(var(--bottom) + 1.5rem); } + +.panel { display: flex; gap: .5rem; margin: 0 auto 1rem; padding: .4rem; max-width: 22rem; + border-radius: 1.25rem; background: rgb(255 255 255 / .12); border: 1px solid rgb(255 255 255 / .16); + backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); } +.panel-btn { flex: 1; display: flex; align-items: center; justify-content: center; gap: .6rem; + min-height: 2.5rem; padding: .4rem 1rem; border: 0; border-radius: .9rem; + background: rgb(255 255 255 / .1); color: #fff; font: inherit; font-weight: 500; + cursor: pointer; text-shadow: 0 1px 4px rgb(0 0 0 / .35); } +.panel-btn:hover, .panel-btn:active { background: rgb(255 255 255 / .22); } +.windows-glyph { position: relative; width: 1.1rem; height: 1.1rem; } +.windows-glyph::before, .windows-glyph::after { content: ""; position: absolute; border: 2px solid currentColor; + border-radius: .25rem; box-sizing: border-box; } +.windows-glyph::before { inset: 0 .3rem .3rem 0; opacity: .6; } +.windows-glyph::after { inset: .3rem 0 0 .3rem; background: rgb(255 255 255 / .15); } +.slots, .apps { list-style: none; margin: 0; padding: 0; display: grid; gap: 1.25rem .5rem; + grid-template-columns: repeat(4, minmax(0, 1fr)); } +/* The home grid is denser than the drawer: an extra column, smaller tiles. Its rows are + all one height, so a widget spans whole rows of app tiles, and apps fill the cells + beside a widget rather than leaving holes (dense packing). Keep the row height and + row gap in sync with widget_rows in app.py. */ +.slots { grid-template-columns: repeat(5, minmax(0, 1fr)); grid-auto-rows: 4rem; row-gap: .5rem; + grid-auto-flow: row dense; } +@media (min-width: 480px) { .apps { grid-template-columns: repeat(5, minmax(0, 1fr)); } + .slots { grid-template-columns: repeat(6, minmax(0, 1fr)); } } +.tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: .4rem; + padding: .35rem .15rem; border-radius: calc(var(--radius) + 4px); cursor: pointer; } +.tile:active { background: rgb(255 255 255 / .12); } +.icon { width: 3.25rem; height: 3.25rem; object-fit: contain; pointer-events: none; + filter: drop-shadow(0 2px 4px rgb(0 0 0 / .3)); } +.icon.missing { border-radius: 999px; background: rgb(255 255 255 / .18); object-position: -999px 0; } +.name { max-width: 100%; font-size: .75rem; line-height: 1.2; text-align: center; + text-shadow: var(--shadow-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.slots .tile { gap: .25rem; padding: .2rem .1rem; } +.slots .icon { width: 2.5rem; height: 2.5rem; } +.slots .name { font-size: .68rem; } + +/* A widget takes whole rows. On a phone the native widget view covers the slot; + the label only shows while the slot is not live (or in a desktop browser). */ +.widget-slot { grid-column: 1 / -1; display: grid; place-items: center; box-sizing: border-box; + border-radius: 1.25rem; background: rgb(255 255 255 / .1); + border: 1px dashed rgb(255 255 255 / .3); } +.widget-label { font-size: .875rem; opacity: .75; text-shadow: var(--shadow-text); + max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +/* The native view can be narrower than the slot, so the label would peek out at its sides. */ +.widget-slot[data-wid] .widget-label { visibility: hidden; } +/* A live widget sits bare on the wallpaper; the frame only comes back while it is picked + up or resized (or while its native view is away, e.g. another widget is being resized). */ +.widget-slot[data-wid]:not(.lifted):not(.resizing) { background: none; border-color: transparent; } + +/* A widget being resized: handles sit just outside its right and bottom edges, where the + native widget view doesn't cover them; the bottom one sits in the gap below the row. */ +.widget-slot { position: relative; } +.widget-slot.resizing { z-index: 2; outline: 2px solid rgb(255 255 255 / .85); + outline-offset: 3px; transition: none; } +.resize-handle { position: absolute; z-index: 2; touch-action: none; cursor: nwse-resize; } +.resize-handle::after { content: ""; position: absolute; border-radius: 999px; background: #fff; + box-shadow: 0 1px 6px rgb(0 0 0 / .45); } +.resize-handle[data-edge="r"] { top: 0; bottom: 0; right: -16px; width: 16px; cursor: ew-resize; } +.resize-handle[data-edge="r"]::after { top: 50%; left: 6px; width: 6px; height: 2.5rem; transform: translateY(-50%); } +.resize-handle[data-edge="b"] { left: 0; right: 0; bottom: -1rem; height: 1rem; cursor: ns-resize; } +.resize-handle[data-edge="b"]::after { left: 50%; top: 5px; width: 2.5rem; height: 6px; transform: translateX(-50%); } +.resize-handle[data-edge="rb"] { right: -16px; bottom: -1rem; width: 2.75rem; height: 1rem; } +.resize-handle[data-edge="rb"]::after { right: 4px; top: 1px; width: 14px; height: 14px; border-radius: 4px; } +.resize-bar { position: fixed; left: 50%; bottom: calc(var(--bottom) + 1rem); z-index: 15; transform: translateX(-50%); + display: flex; align-items: center; gap: .5rem; padding: .4rem .4rem .4rem 1rem; border-radius: 999px; + background: rgb(0 0 0 / .8); color: #fff; font-size: .875rem; white-space: nowrap; + animation: ui-fade .15s; } +.resize-bar .btn.ghost { color: #fff; } +.resize-bar .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; } + +/* A slot picked up by a long press, while it is dragged (index.html moves it). */ +.slots > li { transition: transform .15s ease-out; } +.slots > .lifted { z-index: 1; transform: scale(1.12); background: rgb(255 255 255 / .16); + box-shadow: 0 8px 24px rgb(0 0 0 / .35); } +.slots.dragging > li:not(.lifted) { opacity: .8; } +.slots.dragging .tile:active { background: none; } + +.hint, .empty { text-align: center; opacity: .85; text-shadow: var(--shadow-text); } +.hint { margin-top: 30vh; padding: 0 2rem; font-size: .9rem; line-height: 1.5; } + +/* ---- drawer: slides down over the home screen */ +.drawer { position: fixed; inset: 0; z-index: 10; display: flex; flex-direction: column; + padding: calc(var(--top) + 1rem) 16px 0; background: rgb(10 10 14 / .72); + backdrop-filter: blur(24px); -webkit-backdrop-filter: blur(24px); + animation: drop .22s cubic-bezier(.2, .8, .2, 1); } +@keyframes drop { from { transform: translateY(-100%); } to { transform: none; } } +.drawer-head { display: flex; gap: .5rem; align-items: center; margin-bottom: 1rem; } +.drawer-head .input { flex: 1; height: 2.75rem; border-radius: 999px; padding: 0 1.25rem; font-size: 1rem; + background: rgb(255 255 255 / .1); border-color: rgb(255 255 255 / .15); color: #fff; } +.drawer-head .input::placeholder { color: rgb(255 255 255 / .6); } +.drawer-head .input::-webkit-search-cancel-button { filter: invert(1); } +.drawer-head .btn.ghost { color: #fff; } +.drawer-head .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; } +.drawer-note { margin: 0 0 1rem; font-size: .875rem; opacity: .8; text-align: center; } +.drawer .apps { flex: 1; overflow-y: auto; align-content: start; + padding-bottom: calc(var(--bottom) + 1.5rem); overscroll-behavior: contain; } +.drawer .empty { flex: 1; } +.picking .tile::after { content: ""; position: absolute; top: .1rem; right: .6rem; width: 1.25rem; height: 1.25rem; + border-radius: 999px; border: 2px solid #fff; box-sizing: border-box; + background: rgb(0 0 0 / .35); } +.picking .tile.on::after { content: "✓"; display: grid; place-items: center; font-size: .75rem; font-weight: 700; + background: #fff; color: #111; } + +/* ---- sheets (long-press menus, widget picker) */ +.sheet-overlay { position: fixed; inset: 0; z-index: 20; background: rgb(0 0 0 / .45); animation: ui-fade .15s; } +.sheet { position: fixed; left: 0; right: 0; bottom: 0; z-index: 21; max-width: 560px; margin: 0 auto; + max-height: 70vh; overflow-y: auto; box-sizing: border-box; + padding: .75rem 1rem calc(var(--bottom) + 1rem); border-radius: 1.25rem 1.25rem 0 0; + background: var(--popover); color: var(--popover-foreground); + animation: rise .2s cubic-bezier(.2, .8, .2, 1); } +.sheet::before { content: ""; display: block; width: 2.25rem; height: .3rem; margin: 0 auto .75rem; + border-radius: 999px; background: var(--border); } +@keyframes rise { from { transform: translateY(100%); } to { transform: none; } } +.sheet-title { margin: 0 .5rem .5rem; font-size: 1rem; font-weight: 600; } +.sheet-item { display: block; width: 100%; padding: .85rem .5rem; border: 0; border-radius: var(--radius); + background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; } +.sheet-item:hover, .sheet-item:active { background: var(--accent); } +.sheet .empty { text-shadow: none; color: var(--muted-foreground); } +.widget-list { list-style: none; margin: 0; padding: 0; display: grid; } +.widget-list li { display: flex; align-items: center; gap: .75rem; padding: .5rem; border-radius: var(--radius); + cursor: pointer; } +.widget-list li:hover, .widget-list li:active { background: var(--accent); } +.widget-list .icon { width: 2.5rem; height: 2.5rem; filter: none; } +.widget-name { display: grid; } +.widget-name small { color: var(--muted-foreground); font-size: .8rem; } +.widget-search { width: 100%; margin-bottom: .5rem; } + +.notice, #toast { position: fixed; left: 50%; bottom: calc(var(--bottom) + 2rem); z-index: 30; + transform: translateX(-50%); padding: .5rem 1rem; border-radius: 999px; + background: rgb(0 0 0 / .8); color: #fff; font-size: .875rem; white-space: nowrap; + pointer-events: none; animation: ui-fade .15s; } +#toast { opacity: 0; transition: opacity .2s; animation: none; } +#toast.show { opacity: 1; } + +@media (prefers-reduced-motion: reduce) { .drawer, .sheet { animation: none; } } diff --git a/web/ui.css b/legacy/web/ui.css similarity index 100% rename from web/ui.css rename to legacy/web/ui.css diff --git a/web/ultra.js b/legacy/web/ultra.js similarity index 100% rename from web/ultra.js rename to legacy/web/ultra.js diff --git a/legacy/web/widgets.json b/legacy/web/widgets.json new file mode 100644 index 0000000..c770d4c --- /dev/null +++ b/legacy/web/widgets.json @@ -0,0 +1,32 @@ +{ + "widgets": [ + { + "label": "Clock", + "app": "Clock", + "provider": "com.example.clock/.Widget", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%230ea5e9%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E", + "h": 140 + }, + { + "label": "Weather", + "app": "Google", + "provider": "com.example.weather/.Widget", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%2338bdf8%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E", + "h": 120 + }, + { + "label": "Calendar", + "app": "Calendar", + "provider": "com.example.calendar/.Widget", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%233b82f6%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E", + "h": 200 + }, + { + "label": "Music", + "app": "Music", + "provider": "com.example.music/.Widget", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%23ec4899%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E", + "h": 110 + } + ] +} diff --git a/moon.mod b/moon.mod new file mode 100644 index 0000000..baf746d --- /dev/null +++ b/moon.mod @@ -0,0 +1,15 @@ +name = "experiments/launcher" + +version = "0.1.0" // sweet-version + +readme = "README.md" + +repository = "https://git.site.latha.org/experiments/launcher" + +license = "Apache-2.0" + +keywords = [ "android", "launcher", "home-screen" ] + +description = "Android home screen launcher: pure MoonBit core and UI, rendered in a WebView by a thin Java shell" + +preferred_target = "js" diff --git a/package.json b/package.json new file mode 100644 index 0000000..9a56736 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "launcher-tests", + "private": true, + "description": "Browser tests of the launcher page (Playwright); the launcher itself is MoonBit, see README.md", + "scripts": { + "build:web": "scripts/build-web.sh --demo", + "test": "scripts/build-web.sh --demo && node tests/e2e.cjs && node tests/android-sim.cjs" + }, + "devDependencies": { + "playwright": "1.65.1" + } +} diff --git a/scripts/build-web.sh b/scripts/build-web.sh new file mode 100755 index 0000000..d9078c9 --- /dev/null +++ b/scripts/build-web.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Builds the page: the MoonBit program (web/*.mbt, js backend) plus its static files, +# into dist/web/. With --demo the browser demo's apps.json and widgets.json come too; +# the APK build leaves them out (the shell answers those URLs itself). +set -euo pipefail +cd "$(dirname "$0")/.." +export PATH="$HOME/.moon/bin:$PATH" +moon build --target js --release +out=dist/web +rm -rf "$out" && mkdir -p "$out" +cp _build/js/release/build/web/web.js "$out/launcher.js" +cp web/index.html web/style.css "$out/" +if [ "${1:-}" = "--demo" ]; then cp web/apps.json web/widgets.json "$out/"; fi +echo "built $out ($(wc -c < "$out/launcher.js") bytes of JS)" diff --git a/tests/android-sim.cjs b/tests/android-sim.cjs new file mode 100644 index 0000000..5e5d104 --- /dev/null +++ b/tests/android-sim.cjs @@ -0,0 +1,131 @@ +// Drives the page against a stub of the Java shell's window.Android bridge, to check the seam +// between the MoonBit page and the shell (what the page asks of Android, and how it reacts when +// Android calls window.launcher.*). The Java side itself needs a device; this is the page half. +// scripts/build-web.sh --demo && node tests/android-sim.cjs +const assert = require("assert"); +const fs = require("fs"); +const http = require("http"); +const path = require("path"); +const { chromium } = require(process.env.PLAYWRIGHT || "playwright"); + +const RELEASE = JSON.stringify({ tag_name: "build-9", assets: [ + { name: "version.json", browser_download_url: "https://x/version.json" }, + { name: "ultra-launcher.apk", browser_download_url: "https://x/a.apk" }] }); + +(async () => { + const root = path.join(__dirname, "..", "dist", "web"); + const types = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" }; + const srv = http.createServer((req, res) => { + const u = req.url.split("?")[0] === "/" ? "/index.html" : req.url.split("?")[0]; + fs.readFile(path.join(root, u), (err, data) => { + if (err) { res.writeHead(404); res.end(); return; } + res.writeHead(200, { "content-type": types[path.extname(u)] || "application/octet-stream" }); res.end(data); + }); + }).listen(0); + const BASE = `http://localhost:${srv.address().port}`; + const b = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined }); + const p = await b.newPage({ viewport: { width: 390, height: 780 } }); + p.on("pageerror", (e) => { console.error("page error:", e.message); process.exitCode = 1; }); + await p.addInitScript((release) => { + window.__calls = []; + const rec = (n) => (...a) => { window.__calls.push([n, ...a]); }; + const disc = "data:image/svg+xml," + encodeURIComponent(""); + window.Android = { + launch: rec("launch"), appInfo: rec("appInfo"), uninstall: rec("uninstall"), + addWidget: (prov) => { rec("addWidget")(prov); setTimeout(() => window.launcher.widgetAdded(77), 0); }, + removeWidget: rec("removeWidget"), placeWidgets: rec("placeWidgets"), coverWidgets: rec("coverWidgets"), + excludeGestures: rec("excludeGestures"), + widgetLimits: () => JSON.stringify({ w: 110, minW: 64, minH: 64, maxW: 0, maxH: 0, h: true, v: true }), + loadIcons: (json) => { rec("loadIcons")(json); const o = {}; for (const k of JSON.parse(json)) o[k] = disc; setTimeout(() => window.launcher.icons(o), 0); }, + haptic: rec("haptic"), showKeyboard: rec("showKeyboard"), hideKeyboard: rec("hideKeyboard"), + openSettings: rec("openSettings"), pickWallpaper: rec("pickWallpaper"), openRecents: rec("openRecents"), + httpGet: (url, tag) => { rec("httpGet")(url, tag); + setTimeout(() => window.launcher.httpResult(tag, true, url.endsWith("/latest") ? release : JSON.stringify({ versionCode: 9, commit: "abc" })), 0); }, + installApk: rec("installApk"), installedVersion: () => 5, declinedVersion: () => -1, + }; + }, RELEASE); + const calls = (n) => p.evaluate((n) => window.__calls.filter((c) => c[0] === n), n); + const settle = () => p.waitForTimeout(250); + const longpress = async (sel, fy = 0.5) => { + const r = await p.locator(sel).first().boundingBox(); + await p.mouse.move(r.x + r.width / 2, r.y + r.height * fy); + await p.mouse.down(); await p.waitForTimeout(650); await p.mouse.up(); await settle(); + }; + await p.goto(BASE + "/"); + await p.evaluate(() => localStorage.clear()); + await p.reload(); + await p.waitForSelector(".hint"); + assert.ok(!(await p.evaluate(() => document.documentElement.classList.contains("demo"))), "no demo backdrop on a phone"); + + // on start the page checks for an update: release API, then version.json, then installs build 9 over 5 + await p.waitForFunction(() => window.__calls.some((c) => c[0] === "installApk")); + assert.deepEqual((await calls("httpGet")).map((c) => c[1]), [ + "https://git.site.latha.org/api/v1/repos/experiments/launcher/releases/latest", "https://x/version.json"]); + assert.deepEqual((await calls("installApk"))[0].slice(1), ["https://x/a.apk", 9]); + assert.equal(await p.textContent(".notice"), "Downloading launcher update (build 9)…"); + + // the drawer asks the shell for icons (batched, by key) and fills the images from its answer + await p.evaluate(() => document.body.dispatchEvent(Object.assign(new Event("x"), {}))); + await longpress(".hint"); + await p.click(".sheet-item >> text=Add apps"); await settle(); + assert.ok((await calls("loadIcons")).length > 0, "icons are asked for"); + assert.ok(!(await calls("showKeyboard")).length, "no keyboard in pick mode"); + await p.click(".apps .tile:nth-child(4)"); await p.click(".drawer-head >> text=Done"); await settle(); + assert.ok((await p.getAttribute(".slots .icon", "src")).startsWith("data:image/svg+xml"), "the icon the shell drew"); + await p.click(".slots .tile"); await settle(); + assert.deepEqual((await calls("launch"))[0].slice(1), ["com.example.chrome/.MainActivity"]); + + // Windows asks the shell for Recents; settings and wallpaper too + await p.click(".panel-btn"); await settle(); + assert.equal((await calls("openRecents")).length, 1); + + // add a widget: the shell binds it and the page places it over its slot (wid, x, y, w, h, editing) + await longpress(".home", 0.95); + await p.click(".sheet-item >> text=Add widget"); + await p.waitForSelector(".widget-list li"); + await p.click(".widget-list li:first-child"); await settle(); + assert.equal((await calls("addWidget")).length, 1); + await p.waitForSelector(".widget-slot[data-wid='77']"); + await settle(); + const placed = (await calls("placeWidgets")).pop()[1]; + const [[wid, x, y, w, h, editing]] = JSON.parse(placed); + assert.equal(wid, 77); assert.ok(w > 100 && h >= 64 && x >= 0 && y > 100, placed); assert.equal(editing, 0); + const box = await p.locator(".widget-slot").boundingBox(); + assert.ok(Math.abs(box.x - x) < 2 && Math.abs(box.width - w) < 2, "placed where the slot is"); + assert.ok(w < 358, "starts at its natural width, not the whole row"); // 110px natural = 2 columns + + // opening the drawer: the shell is told to cover the widgets, the keyboard comes up, widgets are unmarked + await p.click(".search-pill"); await settle(); + await p.waitForSelector(".drawer"); + assert.ok((await calls("coverWidgets")).length > 0, "the shell hides widgets under the drawer"); + assert.ok((await calls("showKeyboard")).length > 0, "the search takes the keyboard"); + assert.equal(await p.$$eval("[data-wid]", (ws) => ws.length), 0); + await p.click(".drawer-head >> text=Close"); await settle(); + assert.ok((await calls("hideKeyboard")).length > 0); + assert.equal((await calls("coverWidgets")).pop()[1], 0, "the widgets are shown again"); + + // a long press on the native widget view reaches the page; letting go without moving shows handles, + // and the shell is told to keep its edge swipes off them + await p.evaluate(() => { window.launcher.widgetMenu(77); window.launcher.widgetDrop(false); }); await settle(); + assert.ok(await p.$(".widget-slot.resizing .resize-handle"), "handles"); + assert.ok(JSON.parse((await calls("excludeGestures")).pop()[1]).length === 3, "three handles excluded from system gestures"); + assert.equal(JSON.parse((await calls("placeWidgets")).pop()[1])[0][5], 1, "the shell is told which widget is being edited"); + // dragging it from the native view moves it to a cell (widgetDrag reports page px) + await p.evaluate(() => { window.launcher.widgetGrab(77); window.launcher.widgetDrag(200, 300); window.launcher.widgetDrag(200, 420); window.launcher.widgetDrop(true); }); + await settle(); + const moved = await p.$eval(".widget-slot", (s) => s.style.gridRow); + assert.ok(!moved.startsWith("1 "), `moved off the first row: ${moved}`); + await p.click(".resize-bar >> text=Remove"); await settle(); + assert.equal((await calls("removeWidget"))[0][1], 77); + + // a package change: the shell calls reload(), which fetches the app list again and re-asks for icons + const before = (await calls("loadIcons")).length; + await p.evaluate(() => window.launcher.reload()); await settle(); + assert.ok((await calls("loadIcons")).length > before, "icons are asked for again after a reload"); + // back and home close the drawer + await p.click(".search-pill"); await p.waitForSelector(".drawer"); + await p.evaluate(() => window.launcher.back()); await settle(); + assert.ok(!(await p.$(".drawer"))); + console.log("android bridge ok"); + await b.close(); srv.close(); +})().catch((e) => { console.error(e); process.exit(1); }); diff --git a/tests/e2e.cjs b/tests/e2e.cjs index ec7345c..ee21a23 100644 --- a/tests/e2e.cjs +++ b/tests/e2e.cjs @@ -1,12 +1,33 @@ -// Browser smoke test for the launcher's web UI, against the demo apps.json and widgets.json. -// pixi run test (or: pixi run serve & then node tests/e2e.cjs) +// Browser test of the launcher page built from MoonBit (dist/web, see scripts/build-web.sh), +// against the demo apps.json and widgets.json: the same flows legacy/tests/e2e.cjs drove. +// scripts/build-web.sh --demo && node tests/e2e.cjs +// Serves dist/web itself unless BASE points at a running copy. PLAYWRIGHT names the +// playwright module to load when it is not installed next to the repo; SHOTS=dir saves screenshots. const assert = require("assert"); +const fs = require("fs"); +const http = require("http"); +const path = require("path"); const { chromium } = require(process.env.PLAYWRIGHT || "playwright"); -const BASE = process.env.BASE || "http://localhost:8000"; + +const serve = () => new Promise((resolve) => { + const root = path.join(__dirname, "..", "dist", "web"); + const types = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" }; + const srv = http.createServer((req, res) => { + const f = path.join(root, req.url.split("?")[0] === "/" ? "index.html" : req.url.split("?")[0]); + fs.readFile(f, (err, data) => { + if (err) { res.writeHead(404); res.end(); return; } + res.writeHead(200, { "content-type": types[path.extname(f)] || "application/octet-stream" }); + res.end(data); + }); + }).listen(0, () => resolve([srv, `http://localhost:${srv.address().port}`])); +}); (async () => { - const b = await chromium.launch(); - const p = await b.newPage(); + const [srv, served] = process.env.BASE ? [null, process.env.BASE] : await serve(); + const BASE = served; + const shot = async (p, name) => { if (process.env.SHOTS) await p.screenshot({ path: path.join(process.env.SHOTS, name + ".png") }); }; + const b = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined }); + const p = await b.newPage({ viewport: { width: 390, height: 780 } }); p.on("pageerror", (e) => { console.error("page error:", e.message); process.exitCode = 1; }); const settle = () => p.waitForTimeout(250); // renders land on the next frame, which can lag here @@ -15,6 +36,7 @@ const BASE = process.env.BASE || "http://localhost:8000"; await p.evaluate(() => localStorage.clear()); await p.reload(); await p.waitForSelector(".hint"); + await shot(p, "00-blank-home"); assert.ok(!(await p.$(".clock")), "home has no built-in clock"); const longpress = async (sel, fy = 0.5) => { const r = await p.locator(sel).first().boundingBox(); @@ -35,6 +57,7 @@ const BASE = process.env.BASE || "http://localhost:8000"; assert.equal(await p.$$eval(".apps .tile.on", (ts) => ts.length), 3); await p.click(".drawer-head >> text=Done"); await settle(); assert.deepEqual(await homeApps(), ["Chrome", "Gmail", "Phone"]); + await shot(p, "01-home-with-apps"); // add a widget: long press on blank home, below the apps await longpress(".home", 0.95); await p.click(".sheet-item >> text=Add widget"); @@ -50,6 +73,7 @@ const BASE = process.env.BASE || "http://localhost:8000"; await p.fill(".widget-search", ""); await settle(); await p.click(".widget-list li:first-child"); await settle(); assert.equal(await p.getAttribute(".widget-slot", "data-wid"), "100"); + await shot(p, "02-widget-placeholder"); assert.equal(await p.textContent(".widget-label"), "Clock"); // hold a home app and drag it: reorder const drag = async (from, to) => { @@ -100,11 +124,12 @@ const BASE = process.env.BASE || "http://localhost:8000"; // swipe down opens the drawer (and takes the widget off screen), search, long press adds const swipe = (y0, y1) => p.evaluate(([y0, y1]) => { const at = (y) => new Touch({ identifier: 1, target: document.body, clientX: 200, clientY: y }); - dispatchEvent(new TouchEvent("touchstart", { touches: [at(y0)], changedTouches: [at(y0)] })); - dispatchEvent(new TouchEvent("touchend", { touches: [], changedTouches: [at(y1)] })); + document.body.dispatchEvent(new TouchEvent("touchstart", { bubbles: true, touches: [at(y0)], changedTouches: [at(y0)] })); + document.body.dispatchEvent(new TouchEvent("touchend", { bubbles: true, touches: [], changedTouches: [at(y1)] })); }, [y0, y1]); await swipe(200, 500); await p.waitForSelector(".drawer", { timeout: 2000 }); + await shot(p, "03-drawer"); assert.equal(await p.$$eval("[data-wid]", (ws) => ws.length), 0); assert.ok(await p.$eval(".drawer input", (i) => i === document.activeElement), "opening the drawer focuses its search"); await p.fill(".drawer input", "ma"); await settle(); @@ -116,6 +141,7 @@ const BASE = process.env.BASE || "http://localhost:8000"; await p.waitForSelector(".drawer .tile", { timeout: 2000 }); await longpress(".apps .tile:first-child"); assert.deepEqual(await p.$$eval(".sheet-item", (bs) => bs.map((b) => b.textContent)), ["Add to home", "App info", "Uninstall"]); + await shot(p, "04-drawer-app-menu"); await p.click(".sheet-item:has-text('Uninstall')"); await settle(); assert.equal(await p.textContent("#toast"), "Uninstall com.example.calculator/.MainActivity"); assert.ok(!(await p.$(".sheet")) && (await p.$(".drawer")), "uninstalling closes the menu, not the drawer"); @@ -138,6 +164,7 @@ const BASE = process.env.BASE || "http://localhost:8000"; await longpress(".widget-slot"); assert.ok(!(await p.$(".sheet")), "a widget gets handles, not the menu"); assert.ok(await p.$(".widget-slot.resizing .resize-handle[data-edge=rb]")); + await shot(p, "05-resize-handles"); const size = () => p.$eval(".widget-slot", (w) => [Math.round(w.getBoundingClientRect().width), Math.round(w.getBoundingClientRect().height)]); const [w0] = await size(); const tile = await p.locator(".slots .tile").first().boundingBox(); @@ -181,9 +208,10 @@ const BASE = process.env.BASE || "http://localhost:8000"; assert.ok(!(await p.$(".sheet"))); await p.click(".resize-bar >> text=Remove"); await settle(); assert.ok(!(await p.$(".widget-slot"))); - await p.evaluate(() => { window.ultraHome.reload(); }); await settle(); + await p.evaluate(() => { window.launcher.reload(); }); await settle(); assert.equal(await p.$$eval(".slots > li", (ls) => ls.length), 4); console.log("launcher ok"); await b.close(); + if (srv) srv.close(); })().catch((e) => { console.error(e); process.exit(1); }); diff --git a/updater/moon.pkg b/updater/moon.pkg new file mode 100644 index 0000000..8fbe60a --- /dev/null +++ b/updater/moon.pkg @@ -0,0 +1,3 @@ +import { + "experiments/launcher/jsonx", +} diff --git a/updater/pkg.generated.mbti b/updater/pkg.generated.mbti new file mode 100644 index 0000000..dc24151 --- /dev/null +++ b/updater/pkg.generated.mbti @@ -0,0 +1,45 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/launcher/updater" + +import { + "moonbitlang/core/debug", +} + +// Values +pub let apk_asset : String + +pub let check_every_ms : Int64 + +pub fn decide(Int32, Int32, Int32, manual~ : Bool) -> Decision + +pub fn parse_release(String) -> Release? + +pub fn parse_version(String) -> Int32? + +pub let release_api : String + +pub fn should_check(Int64, Int64, manual~ : Bool) -> Bool + +pub fn tag_version(String) -> Int32? + +pub let version_asset : String + +// Errors + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) enum Decision { + UpToDate(Int32) + Install(Int32) + Declined(Int32) +} + +pub(all) struct Release { + tag : String + version_url : String? + apk_url : String? +} + +// Type aliases + +// Traits diff --git a/updater/updater.mbt b/updater/updater.mbt new file mode 100644 index 0000000..5ed4c30 --- /dev/null +++ b/updater/updater.mbt @@ -0,0 +1,110 @@ +///| +/// Self-update logic, pure. The shell does the network and the install; this decides +/// what the releases it fetched mean. +/// +/// CI publishes a Gitea release `build-` holding `ultra-launcher.apk` and +/// `version.json` (`{"versionCode": N, "commit": SHA}`), with N also the APK's +/// versionCode. The latest-release API names the download URLs of both assets. + +///| +pub let release_api : String = "https://git.site.latha.org/api/v1/repos/experiments/launcher/releases/latest" + +///| +pub let apk_asset : String = "ultra-launcher.apk" + +///| +pub let version_asset : String = "version.json" + +///| +/// How often the home screen checks by itself (6 hours). +pub let check_every_ms : Int64 = 6L * 60L * 60L * 1000L + +///| +pub(all) struct Release { + tag : String + version_url : String? + apk_url : String? +} + +///| +/// The latest-release JSON from the Gitea API. +pub fn parse_release(text : String) -> Release? { + let json = @jsonx.parse(text) + guard json is Some(json) else { return None } + let mut version_url = None + let mut apk_url = None + for a in @jsonx.arr(json, "assets") { + let name = @jsonx.str(a, "name") + let url = @jsonx.str(a, "browser_download_url") + if url != "" { + if name == version_asset { + version_url = Some(url) + } else if name == apk_asset { + apk_url = Some(url) + } + } + } + Some({ tag: @jsonx.str(json, "tag_name"), version_url, apk_url, }) +} + +///| +/// The versionCode in a `version.json`. +pub fn parse_version(text : String) -> Int32? { + guard @jsonx.parse(text) is Some(json) else { return None } + match @jsonx.get(json, "versionCode") { + Some(Number(n, ..)) => Some(n.to_int()) + _ => None + } +} + +///| +/// The versionCode a release tag `build-` stands for. +pub fn tag_version(tag : String) -> Int32? { + guard tag.has_prefix("build-") else { return None } + let rest = tag.clamped_view(start=6) + if rest.length() == 0 { + return None + } + let mut n = 0 + for c in rest { + if c < '0' || c > '9' { + return None + } + n = n * 10 + (c.to_int() - '0'.to_int()) + } + Some(n) +} + +///| +#derive(Eq, Debug) +pub(all) enum Decision { + UpToDate(Int32) + /// A newer build exists and should be installed. + Install(Int32) + /// The user already cancelled this build's install; not offered again unless they ask. + Declined(Int32) +} + +///| +/// `latest` is the newest published versionCode, `installed` the running one, `declined` +/// the last build whose install the user cancelled (-1: none). +pub fn decide( + latest : Int32, + installed : Int32, + declined : Int32, + manual~ : Bool, +) -> Decision { + if latest <= installed { + UpToDate(installed) + } else if !manual && latest == declined { + Declined(latest) + } else { + Install(latest) + } +} + +///| +/// An automatic check runs at most every `check_every_ms`; a manual one always runs. +pub fn should_check(now : Int64, last : Int64, manual~ : Bool) -> Bool { + manual || now - last >= check_every_ms +} diff --git a/updater/updater_wbtest.mbt b/updater/updater_wbtest.mbt new file mode 100644 index 0000000..d6e5489 --- /dev/null +++ b/updater/updater_wbtest.mbt @@ -0,0 +1,59 @@ +///| +let sample : String = + #|{"tag_name":"build-29000123","assets":[ + #|{"name":"version.json","browser_download_url":"https://x/v.json"}, + #|{"name":"ultra-launcher.apk","browser_download_url":"https://x/a.apk"}]} + +///| +test "release assets by name" { + let r = parse_release(sample).unwrap() + assert_eq(r.tag, "build-29000123") + assert_eq(r.version_url, Some("https://x/v.json")) + assert_eq(r.apk_url, Some("https://x/a.apk")) +} + +///| +test "bad or partial release json" { + assert_eq(parse_release("nope").map(fn(r) { r.tag }), None) + let r = parse_release("{\"tag_name\":\"t\"}").unwrap() + assert_eq(r.apk_url, None) +} + +///| +test "version.json" { + assert_eq( + parse_version("{\"versionCode\": 29000123, \"commit\": \"abc\"}"), + Some(29000123), + ) + assert_eq(parse_version("{}"), None) + assert_eq(parse_version("x"), None) +} + +///| +test "tags compare as build numbers" { + assert_eq(tag_version("build-29000123"), Some(29000123)) + assert_eq(tag_version("build-"), None) + assert_eq(tag_version("v1.2.3"), None) + assert_eq(tag_version("build-12x"), None) + assert_true( + tag_version("build-10").unwrap() < tag_version("build-9000").unwrap(), + ) +} + +///| +test "deciding" { + assert_eq(decide(5, 5, -1, manual=false), UpToDate(5)) + assert_eq(decide(4, 5, -1, manual=true), UpToDate(5)) + assert_eq(decide(6, 5, -1, manual=false), Install(6)) + assert_eq(decide(6, 5, 6, manual=false), Declined(6)) + assert_eq(decide(6, 5, 6, manual=true), Install(6)) + assert_eq(decide(7, 5, 6, manual=false), Install(7)) +} + +///| +test "throttling the automatic check" { + let h = 60L * 60L * 1000L + assert_true(should_check(7L * h, 0L, manual=false)) + assert_true(!should_check(5L * h, 0L, manual=false)) + assert_true(should_check(1L, 0L, manual=true)) +} diff --git a/vdom/moon.pkg b/vdom/moon.pkg new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/vdom/moon.pkg @@ -0,0 +1 @@ + diff --git a/vdom/pkg.generated.mbti b/vdom/pkg.generated.mbti new file mode 100644 index 0000000..1a58190 --- /dev/null +++ b/vdom/pkg.generated.mbti @@ -0,0 +1,45 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/launcher/vdom" + +// Values +pub fn cls_if(String, Bool) -> String + +pub fn[M] el(String, key? : Int32, classes? : Array[String], attrs? : Array[(String, String)], props? : Array[(String, String)], style? : String, handlers? : Handlers[M], children? : Array[Node[M]]) -> Node[M] + +pub fn[M] text(String) -> Node[M] + +pub fn[M] to_html(Node[M], indent? : Int32) -> String + +// Errors + +// Types and methods +pub(all) struct Element[M] { + tag : String + key : Int32 + classes : Array[String] + attrs : Array[(String, String)] + props : Array[(String, String)] + style : String + handlers : Handlers[M] + children : Array[Node[M]] +} + +pub(all) struct Handlers[M] { + down : M? + tap : M? + press : M? + enter : M? + escape : M? + input : ((String) -> M)? +} +pub fn[M] Handlers::is_empty(Self[M]) -> Bool +pub fn[M] Handlers::none() -> Self[M] + +pub(all) enum Node[M] { + Text(String) + El(Element[M]) +} + +// Type aliases + +// Traits diff --git a/vdom/vdom.mbt b/vdom/vdom.mbt new file mode 100644 index 0000000..d3d1d7b --- /dev/null +++ b/vdom/vdom.mbt @@ -0,0 +1,179 @@ +///| +/// A tiny virtual DOM, pure data, generic over the message type `M` the handlers send. +/// The app's `view` builds a tree; a platform layer (web/) turns it into real DOM and +/// patches it by key. Because the tree is plain data, views are unit-tested by +/// rendering them to HTML text (`to_html`). + +///| +/// What the user can do to an element. Pointer gestures are recognised by the gesture +/// package; the platform layer reports them against the chain of elements that have +/// handlers. +pub(all) struct Handlers[M] { + /// Pointer went down (acted on at once, e.g. grabbing a widget). + down : M? + /// A tap (down and up without a hold or a move). + tap : M? + /// A long press. + press : M? + /// Enter pressed in an input. + enter : M? + /// Escape pressed in an input. + escape : M? + /// An input's text changed. + input : ((String) -> M)? +} + +///| +pub fn[M] Handlers::none() -> Handlers[M] { + { + down: None, + tap: None, + press: None, + enter: None, + escape: None, + input: None, + } +} + +///| +pub fn[M] Handlers::is_empty(self : Handlers[M]) -> Bool { + self.down is None && + self.tap is None && + self.press is None && + self.enter is None && + self.escape is None && + self.input is None +} + +///| +pub(all) enum Node[M] { + Text(String) + El(Element[M]) +} + +///| +pub(all) struct Element[M] { + tag : String + /// Identity among siblings for the keyed diff (0: none). + key : Int32 + classes : Array[String] + attrs : Array[(String, String)] + /// DOM properties (not attributes), e.g. an input's `value`. + props : Array[(String, String)] + style : String + handlers : Handlers[M] + children : Array[Node[M]] +} + +///| +/// An element builder: `el("div", classes=["a"], children=[...])`. +pub fn[M] el( + tag : String, + key~ : Int32 = 0, + classes~ : Array[String] = [], + attrs~ : Array[(String, String)] = [], + props~ : Array[(String, String)] = [], + style~ : String = "", + handlers~ : Handlers[M] = Handlers::none(), + children~ : Array[Node[M]] = [], +) -> Node[M] { + El({ tag, key, classes, attrs, props, style, handlers, children, }) +} + +///| +pub fn[M] text(s : String) -> Node[M] { + Text(s) +} + +///| +/// `cls("a", on=false)` is the empty class, so callers can build lists with `filter`. +pub fn cls_if(name : String, on : Bool) -> String { + if on { + name + } else { + "" + } +} + +///| +fn escape_html(s : String) -> String { + let b = StringBuilder() + for c in s { + match c { + '&' => b.write_string("&") + '<' => b.write_string("<") + '>' => b.write_string(">") + '"' => b.write_string(""") + _ => b.write_char(c) + } + } + b.to_string() +} + +///| +fn[M] handler_names(h : Handlers[M]) -> String { + let names : Array[String] = [] + if h.down is Some(_) { + names.push("down") + } + if h.tap is Some(_) { + names.push("tap") + } + if h.press is Some(_) { + names.push("press") + } + if h.enter is Some(_) { + names.push("enter") + } + if h.escape is Some(_) { + names.push("escape") + } + if h.input is Some(_) { + names.push("input") + } + names.join(" ") +} + +///| +/// Render a node as HTML text, one element per line (children indented), for tests. +/// Handlers show as an `on="tap press"` attribute. +pub fn[M] to_html(node : Node[M], indent~ : Int32 = 0) -> String { + let pad = " ".repeat(indent) + match node { + Text(s) => pad + escape_html(s) + El(e) => { + let b = StringBuilder() + b.write_string("\{pad}<\{e.tag}") + let classes = e.classes.filter(fn(c) { c != "" }) + if classes.length() > 0 { + b.write_string(" class=\"\{classes.join(" ")}\"") + } + for kv in e.attrs { + b.write_string(" \{kv.0}=\"\{escape_html(kv.1)}\"") + } + for kv in e.props { + b.write_string(" .\{kv.0}=\"\{escape_html(kv.1)}\"") + } + if e.style != "" { + b.write_string(" style=\"\{e.style}\"") + } + let on = handler_names(e.handlers) + if on != "" { + b.write_string(" on=\"\{on}\"") + } + b.write_string(">") + if e.children.length() == 1 && e.children[0] is Text(s) { + b.write_string("\{escape_html(s)}") + } else if e.children.length() == 0 { + b.write_string("") + } else { + for c in e.children { + b.write_string("\n") + b.write_string(to_html(c, indent=indent + 1)) + } + b.write_string("\n\{pad}") + } + b.to_string() + } + } +} diff --git a/vdom/vdom_wbtest.mbt b/vdom/vdom_wbtest.mbt new file mode 100644 index 0000000..16bd095 --- /dev/null +++ b/vdom/vdom_wbtest.mbt @@ -0,0 +1,18 @@ +///| +test "to_html" { + let n : Node[Int32] = el( + "div", + classes=["a", cls_if("b", false), cls_if("c", true)], + handlers={ ..Handlers::none(), tap: Some(1), }, + children=[el("span", children=[text("x < y")]), text("tail")], + ) + inspect( + to_html(n), + content=( + #|
+ #| x < y + #| tail + #|
+ ), + ) +} diff --git a/web/ffi.mbt b/web/ffi.mbt new file mode 100644 index 0000000..3846fdf --- /dev/null +++ b/web/ffi.mbt @@ -0,0 +1,376 @@ +///| +/// The few places MoonBit touches the browser: one-line JavaScript bodies for DOM +/// calls and the host bridge. Everything that decides anything is in the pure packages. + +///| +#external +type Dom + +///| +#external +type Ev + +// ---- DOM ---------------------------------------------------------------------- + +///| +extern "js" fn dom_create(tag : String) -> Dom = + #|(t) => document.createElement(t) + +///| +extern "js" fn dom_text(s : String) -> Dom = + #|(s) => document.createTextNode(s) + +///| +extern "js" fn dom_set_text(d : Dom, s : String) -> Unit = + #|(d, s) => { d.data = s } + +///| +extern "js" fn dom_attr(d : Dom, k : String, v : String) -> Unit = + #|(d, k, v) => d.setAttribute(k, v) + +///| +extern "js" fn dom_rm_attr(d : Dom, k : String) -> Unit = + #|(d, k) => d.removeAttribute(k) + +///| +extern "js" fn dom_prop(d : Dom, k : String, v : String) -> Unit = + #|(d, k, v) => { if (d[k] !== v) d[k] = v } + +///| +extern "js" fn dom_class(d : Dom, v : String) -> Unit = + #|(d, v) => { d.className = v } + +///| +/// Put `d` into `parent` right before `before` (or last when `before` is not a node), +/// unless it is already there. +extern "js" fn dom_place( + parent : Dom, + d : Dom, + before : Dom, + has_before : Bool, +) -> Unit = + #|(p, d, b, has) => { const next = has ? b : null; if (d.parentNode !== p || d.nextSibling !== next) p.insertBefore(d, next); } + +///| +extern "js" fn dom_remove(d : Dom) -> Unit = + #|(d) => d.remove() + +///| +extern "js" fn dom_root() -> Dom = + #|() => document.getElementById("app") + +// ---- events --------------------------------------------------------------------- + +///| +extern "js" fn listen( + target : String, + ty : String, + passive : Bool, + f : (Ev) -> Unit, +) -> Unit = + #|(target, ty, passive, f) => (target === "window" ? window : document).addEventListener(ty, f, { passive, capture: true }) + +///| +extern "js" fn ev_x(e : Ev) -> Double = + #|(e) => e.clientX ?? 0 + +///| +extern "js" fn ev_y(e : Ev) -> Double = + #|(e) => e.clientY ?? 0 + +///| +extern "js" fn ev_key(e : Ev) -> String = + #|(e) => e.key ?? "" + +///| +extern "js" fn ev_composing(e : Ev) -> Bool = + #|(e) => !!e.isComposing + +///| +extern "js" fn ev_primary(e : Ev) -> Bool = + #|(e) => e.isPrimary !== false && (e.button ?? 0) === 0 + +///| +extern "js" fn ev_value(e : Ev) -> String = + #|(e) => e.target && e.target.value != null ? String(e.target.value) : "" + +///| +extern "js" fn ev_prevent(e : Ev) -> Unit = + #|(e) => { if (e.cancelable) e.preventDefault() } + +///| +extern "js" fn ev_touch_x(e : Ev) -> Double = + #|(e) => (e.changedTouches && e.changedTouches[0] ? e.changedTouches[0].clientX : 0) + +///| +extern "js" fn ev_touch_y(e : Ev) -> Double = + #|(e) => (e.changedTouches && e.changedTouches[0] ? e.changedTouches[0].clientY : 0) + +///| +extern "js" fn ev_touches(e : Ev) -> Int32 = + #|(e) => (e.touches ? e.touches.length : 0) + +///| +/// The handler numbers (`data-n`) from the event's target up, as "3,1,0". +extern "js" fn ev_chain(e : Ev) -> String = + #|(e) => { const out = []; for (let n = e.target; n && n.getAttribute; n = n.parentNode) { const v = n.getAttribute("data-n"); if (v !== null) out.push(v); } return out.join(","); } + +///| +extern "js" fn set_timeout(ms : Int32, f : () -> Unit) -> Unit = + #|(ms, f) => { setTimeout(f, ms) } + +///| +extern "js" fn request_frame(f : () -> Unit) -> Unit = + #|(f) => { requestAnimationFrame(() => f()) } + +///| +extern "js" fn now_ms() -> Double = + #|() => Date.now() + +// ---- storage and network ---------------------------------------------------------- + +///| +extern "js" fn storage_get(k : String) -> String = + #|(k) => { try { return localStorage.getItem(k) ?? "" } catch { return "" } } + +///| +extern "js" fn storage_has(k : String) -> Bool = + #|(k) => { try { return localStorage.getItem(k) !== null } catch { return false } } + +///| +extern "js" fn storage_set(k : String, v : String) -> Unit = + #|(k, v) => { try { localStorage.setItem(k, v) } catch {} } + +///| +/// The old WebView build's `ultra.home.*` keys as a JSON object. +extern "js" fn storage_legacy() -> String = + #|() => { const o = {}; try { for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k.startsWith("ultra.home.")) o[k] = localStorage.getItem(k); } } catch {} return JSON.stringify(o); } + +///| +extern "js" fn fetch_text(url : String, f : (Bool, String) -> Unit) -> Unit = + #|(url, f) => { fetch(url, { cache: "no-store" }).then((r) => r.ok ? r.text().then((t) => f(true, t)) : f(false, "HTTP " + r.status)).catch((e) => f(false, String(e))) } + +// ---- page measurements (after each render) ------------------------------------------ + +///| +/// Measure the viewport and the home grid (into `window.__m`); false without a grid. +extern "js" fn measure() -> Bool = + #|() => { const s = document.querySelector(".slots"), h = document.querySelector(".home"); if (!s || !h) return false; const r = s.getBoundingClientRect(); window.__m = [innerWidth, innerHeight, r.left, r.top, r.width, parseFloat(getComputedStyle(h).paddingBottom) || 0]; return true; } + +///| +/// Measurement i: viewport width, height, grid left, top, width, the home's bottom padding. +extern "js" fn measured(i : Int32) -> Double = + #|(i) => window.__m[i] + +///| +/// The live widget slots, as the shell wants them: [[id, x, y, w, h, editing]...]. +extern "js" fn widget_slots() -> String = + #|() => JSON.stringify([...document.querySelectorAll(".widget-slot[data-wid]")].map((s) => { const r = s.getBoundingClientRect(); return [+s.dataset.wid, Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height), s.classList.contains("resizing") ? 1 : 0]; })) + +///| +extern "js" fn resize_handles() -> String = + #|() => JSON.stringify([...document.querySelectorAll(".resize-handle")].map((h) => { const r = h.getBoundingClientRect(); return [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)]; })) + +///| +/// The drawer covers the page down to this y (px); -1 once it covers the screen, 0 when +/// there is no drawer. `last` is the previous bottom edge, so the answer can run ahead of it. +extern "js" fn drawer_cover(last : Double) -> Double = + #|(last) => { const d = document.querySelector(".drawer"); if (!d) return 0; const b = d.getBoundingClientRect().bottom; if (b >= innerHeight - 1) return -1; return Math.min(innerHeight - 1, Math.max(0, Math.ceil(b + 2 * Math.max(0, b - last)))); } + +///| +extern "js" fn drawer_bottom() -> Double = + #|() => { const d = document.querySelector(".drawer"); return d ? d.getBoundingClientRect().bottom : 0 } + +///| +/// A drawer or sheet over the home screen's widgets (the shell has them step aside). +extern "js" fn has_drawer() -> Bool = + #|() => !!document.querySelector(".drawer") && !document.querySelector(".sheet-overlay") + +///| +extern "js" fn focus_search() -> Unit = + #|() => { const i = document.querySelector(".drawer:not(.picking) .drawer-head input"); if (i) i.focus({ preventScroll: true }) } + +///| +extern "js" fn blur_active() -> Unit = + #|() => { document.activeElement && document.activeElement.blur && document.activeElement.blur() } + +///| +extern "js" fn scroll_top() -> Unit = + #|() => window.scrollTo({ top: 0, behavior: "smooth" }) + +///| +extern "js" fn home_at_top() -> Bool = + #|() => window.scrollY <= 0 + +///| +/// The drawer's list is at its end (or does not scroll); false without a drawer. +extern "js" fn list_at_end() -> Bool = + #|() => { const l = document.querySelector(".drawer .apps"); return !!l && l.scrollTop + l.clientHeight >= l.scrollHeight - 2 } + +///| +/// The sheet is covering the page (a swipe must not act under it). +extern "js" fn toast(s : String) -> Unit = + #|(s) => { const t = document.getElementById("toast"); if (!t) return; t.textContent = s; t.classList.add("show"); clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove("show"), 1600); } + +// ---- icons --------------------------------------------------------------------------- + +///| +/// Snapshot the page's icon images; returns how many. +extern "js" fn icons_scan() -> Int32 = + #|() => { window.__imgs = [...document.querySelectorAll("img.icon[data-icon]")]; return window.__imgs.length; } + +///| +extern "js" fn icon_key(i : Int32) -> String = + #|(i) => window.__imgs[i].dataset.icon + +///| +/// Whether image i already shows the icon for its key. +extern "js" fn icon_done(i : Int32) -> Bool = + #|(i) => window.__imgs[i].__icon === window.__imgs[i].dataset.icon + +///| +extern "js" fn icon_set(i : Int32, src : String) -> Unit = + #|(i, src) => { const img = window.__imgs[i]; img.__icon = img.dataset.icon; if (src) { img.src = src; img.classList.remove("missing"); } else img.classList.add("missing"); } + +///| +/// Forget what images show, so they are filled again. +extern "js" fn icons_reset() -> Unit = + #|() => { for (const img of document.querySelectorAll("img.icon")) img.__icon = undefined; } + +// ---- the host (Android's window.Android, or stand-ins in a desktop browser) ------------- + +///| +extern "js" fn is_android() -> Bool = + #|() => !!window.Android + +///| +extern "js" fn h_launch(c : String) -> Unit = + #|(c) => window.Android.launch(c) + +///| +extern "js" fn h_app_info(c : String) -> Unit = + #|(c) => window.Android.appInfo(c) + +///| +extern "js" fn h_uninstall(c : String) -> Unit = + #|(c) => window.Android.uninstall(c) + +///| +extern "js" fn h_add_widget(p : String) -> Unit = + #|(p) => window.Android.addWidget(p) + +///| +extern "js" fn h_remove_widget(id : Int32) -> Unit = + #|(id) => window.Android.removeWidget(id) + +///| +extern "js" fn h_place_widgets(json : String) -> Unit = + #|(j) => window.Android.placeWidgets(j) + +///| +extern "js" fn h_cover_widgets(y : Int32) -> Unit = + #|(y) => window.Android.coverWidgets(y) + +///| +extern "js" fn h_exclude_gestures(json : String) -> Unit = + #|(j) => window.Android.excludeGestures && window.Android.excludeGestures(j) + +///| +extern "js" fn h_widget_limits(id : Int32) -> String = + #|(id) => window.Android.widgetLimits(id) + +///| +extern "js" fn h_load_icons(json : String) -> Unit = + #|(j) => window.Android.loadIcons(j) + +///| +extern "js" fn h_has_load_icons() -> Bool = + #|() => !!(window.Android && window.Android.loadIcons) + +///| +extern "js" fn h_haptic() -> Unit = + #|() => { if (window.Android) window.Android.haptic(); else navigator.vibrate && navigator.vibrate(10) } + +///| +extern "js" fn h_show_keyboard() -> Unit = + #|() => window.Android && window.Android.showKeyboard() + +///| +extern "js" fn h_hide_keyboard() -> Unit = + #|() => window.Android && window.Android.hideKeyboard() + +///| +extern "js" fn h_open_settings() -> Unit = + #|() => window.Android.openSettings() + +///| +extern "js" fn h_pick_wallpaper() -> Unit = + #|() => window.Android.pickWallpaper() + +///| +extern "js" fn h_open_recents() -> Unit = + #|() => window.Android.openRecents() + +///| +extern "js" fn h_http_get(url : String, tag : Int32) -> Unit = + #|(url, tag) => window.Android.httpGet(url, tag) + +///| +extern "js" fn h_install_apk(url : String, version : Int32) -> Unit = + #|(url, v) => window.Android.installApk(url, v) + +///| +extern "js" fn h_declined_version() -> Int32 = + #|() => window.Android.declinedVersion() + +///| +extern "js" fn h_installed_version() -> Int32 = + #|() => window.Android.installedVersion() + +// ---- what the shell calls on the page ----------------------------------------------- + +///| +extern "js" fn expose_init() -> Unit = + #|() => { window.launcher = window.launcher || {}; } + +///| +extern "js" fn expose0(name : String, f : () -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +extern "js" fn expose1(name : String, f : (Int32) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +extern "js" fn expose_b(name : String, f : (Bool) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +extern "js" fn expose_dd(name : String, f : (Double, Double) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +/// `f(tag, ok, text)`: a finished `httpGet`. +extern "js" fn expose_result( + name : String, + f : (Int32, Bool, String) -> Unit, +) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +/// `f(json)`: a batch of icons `{key: dataUri}`. +extern "js" fn expose_json(name : String, f : (String) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = (batch) => f(JSON.stringify(batch)) } + +///| +/// Run `f` for each `key\nsrc` pair of a JSON object (flattened, so no arrays cross). +extern "js" fn json_entries( + json : String, + f : (String, String) -> Unit, +) -> Unit = + #|(j, f) => { const o = JSON.parse(j); for (const k in o) f(k, o[k] ?? "") } + +///| +/// Mark the page as running outside the shell (a desktop browser): the stylesheet gives it a backdrop. +extern "js" fn mark_demo() -> Unit = + #|() => document.documentElement.classList.add("demo") diff --git a/web/index.html b/web/index.html index 067159a..2960795 100644 --- a/web/index.html +++ b/web/index.html @@ -4,357 +4,15 @@ ultra · Launcher - +
- + diff --git a/web/main.mbt b/web/main.mbt new file mode 100644 index 0000000..f4e6689 --- /dev/null +++ b/web/main.mbt @@ -0,0 +1,495 @@ +///| +/// The page runtime: renders `@app.view` into the DOM, turns pointer, touch and key +/// events into `@app` input, runs the effects it returns against the host (Android's +/// `window.Android`, or stand-ins that show toasts in a desktop browser), and exposes +/// `window.launcher.*` for the Android shell to call. + +///| +let model : @app.Model = @app.Model::new() + +///| +let state : Ref[PageState] = Ref(PageState::new()) + +///| +priv struct PageState { + mut tree : Array[@vdom.Node[@app.Msg]] + mut table : Array[@vdom.Handlers[@app.Msg]] + mut rendered : Array[RNode] + mut render_pending : Bool + mut focus_pending : Bool + mut placed : String + mut excluded : String + mut cover_y : Int32 + mut cover_last : Double + mut cover_loop : Bool + mut measured : String + mut touch : (Double, Double, Double)? + mut demo_widget : Int32 + mut http_tag : Int32 + http : Map[Int32, (Bool, String) -> Unit] + icon_src : Map[String, String] + icon_asked : Map[String, Bool] + icon_tries : Map[String, Int32] +} + +///| +fn PageState::new() -> PageState { + { + tree: [], + table: [], + rendered: [], + render_pending: false, + focus_pending: false, + placed: "", + excluded: "[]", + cover_y: 0, + cover_last: 0.0, + cover_loop: false, + measured: "", + touch: None, + demo_widget: 100, + http_tag: 0, + http: {}, + icon_src: {}, + icon_asked: {}, + icon_tries: {}, + } +} + +///| +fn dispatch(msg : @app.Msg) -> Unit { + run(@app.update(model, msg)) +} + +///| +fn feed(inp : @gesture.Input) -> Unit { + run(@app.input(model, state.val.table, inp)) +} + +///| +fn run(fx : Array[@app.Effect]) -> Unit { + for e in fx { + exec(e) + } + schedule_render() +} + +///| +fn schedule_render() -> Unit { + if state.val.render_pending { + return + } + state.val.render_pending = true + request_frame(render) +} + +///| +fn http_get(url : String, f : (Bool, String) -> Unit) -> Unit { + if is_android() { + let tag = state.val.http_tag + 1 + state.val.http_tag = tag + state.val.http[tag] = f + h_http_get(url, tag) + } else { + fetch_text(url, f) + } +} + +///| +fn exec(e : @app.Effect) -> Unit { + let android = is_android() + match e { + Launch(c) => if android { h_launch(c) } else { toast("Open " + c) } + AppInfo(c) => + if android { + h_app_info(c) + } else { + toast("App info for " + c) + } + Uninstall(c) => + if android { + h_uninstall(c) + } else { + toast("Uninstall " + c) + } + AddWidget(p) => + if android { + h_add_widget(p) + } else { + let id = state.val.demo_widget + state.val.demo_widget = id + 1 + set_timeout(0, fn() { dispatch(WidgetAdded(id)) }) + } + RemoveWidget(id) => if android { h_remove_widget(id) } + OpenSettings => + if android { + h_open_settings() + } else { + toast("Open system settings") + } + PickWallpaper => + if android { + h_pick_wallpaper() + } else { + toast("Pick a wallpaper") + } + OpenRecents => + if android { + h_open_recents() + } else { + toast("Show open windows") + } + Haptic => h_haptic() + LoadApps => + fetch_text("apps.json", fn(ok, text) { + dispatch(AppsLoaded(if ok { Some(text) } else { None })) + }) + LoadWidgets => + fetch_text("widgets.json", fn(ok, text) { + dispatch(WidgetsLoaded(if ok { Some(text) } else { None })) + }) + QueryLimits(id) => { + let json = if android { + h_widget_limits(id) + } else { + "{\"minW\":120,\"minH\":80,\"maxW\":0,\"maxH\":0,\"h\":true,\"v\":true}" + } + dispatch(LimitsKnown(id, Some(json))) + } + SaveHome(json) => storage_set("launcher.home", json) + SaveLastCheck(t) => storage_set("launcher.update.lastCheck", t.to_string()) + Delay(ms, msg) => set_timeout(ms, fn() { dispatch(msg) }) + HoldTimer(ms, token) => set_timeout(ms, fn() { feed(Hold(token)) }) + FetchRelease(url) => + if android { + http_get(url, fn(ok, text) { + dispatch(ReleaseFetched(if ok { Some(text) } else { None })) + }) + } else { + toast("Check for updates") + set_timeout(0, fn() { dispatch(ReleaseFetched(None)) }) + } + FetchVersion(url) => + http_get(url, fn(ok, text) { + dispatch(VersionFetched(if ok { Some(text) } else { None })) + }) + InstallApk(url, n) => + if android { + h_install_apk(url, n) + } else { + toast("Install update \{n}") + } + FocusSearch => state.val.focus_pending = true + HideKeyboard => { + blur_active() + h_hide_keyboard() + } + ScrollTop => scroll_top() + } +} + +// ---- rendering --------------------------------------------------------------------- + +///| +fn render() -> Unit { + let st = state.val + st.render_pending = false + st.tree = @app.view(model) + st.table = @app.handler_table(st.tree) + st.rendered = patch_root(dom_root(), st.rendered, st.tree) + after_render() +} + +///| +fn after_render() -> Unit { + let st = state.val + fill_icons() + if measure() { + let key = "\{measured(0)},\{measured(1)},\{measured(2)},\{measured(3)},\{measured(4)},\{measured(5)}" + if key != st.measured { + st.measured = key + dispatch( + Measured( + vw=measured(0).to_int(), + vh=measured(1).to_int(), + grid_left=measured(2), + grid_top=measured(3), + grid_w=measured(4), + bottom_pad=measured(5), + ), + ) + } + } + if is_android() { + place() + cover() + } + if st.focus_pending { + st.focus_pending = false + focus_search() + h_show_keyboard() + } +} + +///| +/// Tell the shell where the live widget slots are, and keep its edge swipes off the +/// resize handles. +fn place() -> Unit { + let st = state.val + let json = widget_slots() + // The drawer unmarks the slots, but the home under it doesn't move, so the widgets + // stay where they were and `cover` hides them as the drawer slides over them. + if json != st.placed && !has_drawer() { + st.placed = json + h_place_widgets(json) + } + let handles = resize_handles() + if handles != st.excluded { + st.excluded = handles + h_exclude_gestures(handles) + } +} + +///| +/// Native widgets sit above the page, so the drawer can't cover them by itself. While +/// it slides down the shell hides them above its bottom edge each frame, a little ahead +/// of it (by its speed), since the shell trails a frame. +fn cover() -> Unit { + let st = state.val + let y = drawer_cover(st.cover_last).to_int() + st.cover_last = drawer_bottom() + if y != st.cover_y { + st.cover_y = y + h_cover_widgets(y) + } + if y != 0 && y != -1 && !st.cover_loop { + st.cover_loop = true + request_frame(fn() { + state.val.cover_loop = false + cover() + }) + } +} + +// ---- icons ------------------------------------------------------------------------- + +///| +/// Each `` gets its src from here. On a phone the shell +/// draws icons on its own thread and hands them back as data: URIs in batches, so the +/// WebView never loads icons through request interception; in a desktop browser the key +/// already is a URL. +fn fill_icons() -> Unit { + let st = state.val + let n = icons_scan() + let want : Array[Json] = [] + let loader = h_has_load_icons() + for i in 0.. 0 { + h_load_icons(Json::array(want).stringify()) + } +} + +///| +/// A batch from the shell: `{key: dataUri}`. A key it couldn't draw ("") is asked for +/// again, up to 3 times, with backoff; until then, and after, it shows as a blank disc. +fn got_icons(json : String) -> Unit { + let st = state.val + let mut retry = 0 + json_entries(json, fn(k, src) { + st.icon_src[k] = src + st.icon_asked.remove(k) + let tries = st.icon_tries.get(k).unwrap_or(0) + if src == "" && tries < 3 { + st.icon_tries[k] = tries + 1 + retry = tries + 1 + } + }) + fill_icons() + if retry > 0 { + set_timeout(800 * retry, fn() { + let keys : Array[String] = [] + for kv in st.icon_src { + if kv.1 == "" { + keys.push(kv.0) + } + } + for k in keys { + st.icon_src.remove(k) + } + icons_reset() + fill_icons() + }) + } +} + +// ---- input ------------------------------------------------------------------------- + +///| +fn parse_chain(s : String) -> Array[Int32] { + if s == "" { + return [] + } + let out : Array[Int32] = [] + for part in s.split(",") { + out.push(@string.parse_int(part) catch { _ => -1 }) + } + out +} + +///| +fn is_dragging() -> Bool { + model.lifted >= 0 || model.resize is Some(_) +} + +///| +fn wire_events() -> Unit { + listen("document", "pointerdown", true, fn(e) { + if ev_primary(e) { + feed(Down(x=ev_x(e), y=ev_y(e), chain=parse_chain(ev_chain(e)))) + } + }) + listen("document", "pointermove", true, fn(e) { + feed(Move(x=ev_x(e), y=ev_y(e))) + }) + listen("document", "pointerup", true, fn(e) { feed(Up(x=ev_x(e), y=ev_y(e))) }) + listen("document", "pointercancel", true, fn(_) { feed(Cancel) }) + // keep the page from scrolling under a lifted slot or a handle being dragged + listen("document", "touchmove", false, fn(e) { + if is_dragging() { + ev_prevent(e) + } + }) + listen("document", "contextmenu", false, fn(e) { ev_prevent(e) }) + listen("document", "input", true, fn(e) { + run( + @app.typed(model, state.val.table, parse_chain(ev_chain(e)), ev_value(e)), + ) + }) + listen("document", "keydown", true, fn(e) { + if ev_composing(e) { + return + } + let k = ev_key(e) + if k == "Enter" { + run(@app.key(model, state.val.table, parse_chain(ev_chain(e)), Enter)) + } else if k == "Escape" { + run(@app.key(model, state.val.table, parse_chain(ev_chain(e)), Escape)) + } + }) + // Swipes: down on the home opens the drawer, up closes it once its list is at the end. + listen("document", "touchstart", true, fn(e) { + state.val.touch = if ev_touches(e) == 1 { + Some((ev_touch_x(e), ev_touch_y(e), now_ms())) + } else { + None + } + }) + listen("document", "touchend", true, fn(e) { + match state.val.touch { + Some((x0, y0, t0)) => { + state.val.touch = None + dispatch( + Touch( + dx=ev_touch_x(e) - x0, + dy=ev_touch_y(e) - y0, + ms=(now_ms() - t0).to_int(), + home_top=home_at_top(), + list_end=list_at_end(), + ), + ) + } + None => () + } + }) + listen("window", "resize", true, fn(_) { schedule_render() }) + listen("window", "scroll", true, fn(_) { + if is_android() { + request_frame(place) + } + }) +} + +///| +/// What the Android shell calls: `window.launcher.*`. +fn expose_api() -> Unit { + expose_init() + expose0("reload", fn() { + state.val.icon_src.clear() + state.val.icon_asked.clear() + state.val.icon_tries.clear() + icons_reset() + dispatch(Reload) + }) + expose0("home", fn() { dispatch(GoHome) }) + expose0("back", fn() { dispatch(Back) }) + expose1("widgetAdded", fn(id) { dispatch(WidgetAdded(id)) }) + expose1("widgetMenu", fn(id) { dispatch(WidgetMenu(id)) }) + expose1("widgetGrab", fn(id) { dispatch(WidgetGrab(id)) }) + expose_dd("widgetDrag", fn(x, y) { dispatch(NativeDrag(x, y)) }) + expose_b("widgetDrop", fn(moved) { dispatch(NativeDrop(moved)) }) + expose0("place", fn() { + state.val.placed = "" + place() + }) + expose_json("icons", got_icons) + expose_result("httpResult", fn(tag, ok, text) { + if state.val.http.get(tag) is Some(f) { + state.val.http.remove(tag) + f(ok, text) + } + }) +} + +///| +fn num(key : String) -> Int64 { + let s = storage_get(key) + if s == "" { + 0L + } else { + @string.parse_int64(s) catch { + _ => 0L + } + } +} + +///| +fn main { + if !is_android() { + mark_demo() + } + expose_api() + wire_events() + let saved = if storage_has("launcher.home") { + Some(storage_get("launcher.home")) + } else { + None + } + let legacy = if saved is None { Some(storage_legacy()) } else { None } + dispatch(Restore(saved~, legacy~)) + if is_android() { + // the shell keeps the build whose install the user cancelled (-1: none) + let declined = h_declined_version() + dispatch( + Started( + now=now_ms().to_int64(), + last_check=num("launcher.update.lastCheck"), + declined~, + installed=h_installed_version(), + ), + ) + } + render() +} diff --git a/web/moon.pkg b/web/moon.pkg new file mode 100644 index 0000000..0bb340b --- /dev/null +++ b/web/moon.pkg @@ -0,0 +1,10 @@ +import { + "experiments/launcher/app", + "experiments/launcher/vdom", + "experiments/launcher/gesture", + "moonbitlang/core/string", +} + +pkgtype(kind: "executable") + +supported_targets = "js" diff --git a/web/patch.mbt b/web/patch.mbt new file mode 100644 index 0000000..a3efd04 --- /dev/null +++ b/web/patch.mbt @@ -0,0 +1,189 @@ +///| +/// Turns `vdom` trees into DOM and patches the DOM to match the next tree: keyed +/// children are reused (and moved) so a reordered tile keeps its element, and the CSS +/// transitions on it. Elements with handlers get `data-n`, their number in document +/// order, which pointer events report back (see `@app.handler_table`). + +///| +priv struct RNode { + dom : Dom + is_text : Bool + tag : String + key : Int32 + mut text : String + mut n : Int32 + mut classes : String + mut attrs : Map[String, String] + mut style : String + mut children : Array[RNode] +} + +///| +fn new_rnode(n : @vdom.Node[@app.Msg]) -> RNode { + match n { + Text(s) => + { + dom: dom_text(s), + is_text: true, + tag: "", + key: 0, + text: s, + n: -1, + classes: "", + attrs: {}, + style: "", + children: [], + } + El(e) => + { + dom: dom_create(e.tag), + is_text: false, + tag: e.tag, + key: e.key, + text: "", + n: -1, + classes: "", + attrs: {}, + style: "", + children: [], + } + } +} + +///| +fn update_rnode( + r : RNode, + n : @vdom.Node[@app.Msg], + counter : Ref[Int32], +) -> Unit { + match n { + Text(s) => + if s != r.text { + r.text = s + dom_set_text(r.dom, s) + } + El(e) => { + // numbered first: children come after their parent in document order + let id = if e.handlers.is_empty() { + -1 + } else { + let id = counter.val + counter.val = id + 1 + id + } + if id != r.n { + r.n = id + if id < 0 { + dom_rm_attr(r.dom, "data-n") + } else { + dom_attr(r.dom, "data-n", id.to_string()) + } + } + let classes = e.classes.filter(fn(c) { c != "" }).join(" ") + if classes != r.classes { + r.classes = classes + dom_class(r.dom, classes) + } + let attrs : Map[String, String] = Map([]) + for kv in e.attrs { + attrs[kv.0] = kv.1 + } + for kv in attrs { + if r.attrs.get(kv.0) != Some(kv.1) { + dom_attr(r.dom, kv.0, kv.1) + } + } + for kv in r.attrs { + if !attrs.contains(kv.0) { + dom_rm_attr(r.dom, kv.0) + } + } + r.attrs = attrs + for kv in e.props { + dom_prop(r.dom, kv.0, kv.1) + } + if e.style != r.style { + r.style = e.style + if e.style == "" { + dom_rm_attr(r.dom, "style") + } else { + dom_attr(r.dom, "style", e.style) + } + } + r.children = patch_children(r.dom, r.children, e.children, counter) + } + } +} + +///| +fn compatible(r : RNode, n : @vdom.Node[@app.Msg]) -> Bool { + match n { + Text(_) => r.is_text + El(e) => !r.is_text && r.tag == e.tag && r.key == e.key + } +} + +///| +fn patch_children( + parent : Dom, + old : Array[RNode], + new : Array[@vdom.Node[@app.Msg]], + counter : Ref[Int32], +) -> Array[RNode] { + let used : Array[Bool] = Array::make(old.length(), false) + let by_key : Map[Int32, Int32] = Map([]) + for i in 0.. + if by_key.get(e.key) is Some(i) && !used[i] && compatible(old[i], n) { + found = i + } + _ => + for i in 0..= 0 { + used[found] = true + old[found] + } else { + new_rnode(n) + } + update_rnode(r, n, counter) + out.push(r) + } + for i in 0..= 0; j = j - 1 { + if j == out.length() - 1 { + dom_place(parent, out[j].dom, out[j].dom, false) + } else { + dom_place(parent, out[j].dom, out[j + 1].dom, true) + } + } + out +} + +///| +/// Patch the children of `root` to `tree`; returns the new state to pass next time. +fn patch_root( + root : Dom, + old : Array[RNode], + tree : Array[@vdom.Node[@app.Msg]], +) -> Array[RNode] { + patch_children(root, old, tree, Ref(0)) +} diff --git a/web/pkg.generated.mbti b/web/pkg.generated.mbti new file mode 100644 index 0000000..103a470 --- /dev/null +++ b/web/pkg.generated.mbti @@ -0,0 +1,15 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/launcher/web" + +// Values + +// Errors + +// Types and methods +type Dom + +type Ev + +// Type aliases + +// Traits diff --git a/web/style.css b/web/style.css index 9892a0d..4a6c4e4 100644 --- a/web/style.css +++ b/web/style.css @@ -1,3 +1,99 @@ +/* ultra launcher: shadcn-neutral tokens and the few components the views use (from legacy/web/ui.css), then the home screen layout. */ + +:root { + color-scheme: light dark; + --radius: .625rem; + --background: light-dark(oklch(1 0 0), oklch(.145 0 0)); + --foreground: light-dark(oklch(.145 0 0), oklch(.985 0 0)); + --card: light-dark(oklch(1 0 0), oklch(.205 0 0)); + --card-foreground: var(--foreground); + --popover: var(--card); + --popover-foreground: var(--foreground); + --primary: light-dark(oklch(.205 0 0), oklch(.922 0 0)); + --primary-foreground: light-dark(oklch(.985 0 0), oklch(.205 0 0)); + --secondary: light-dark(oklch(.97 0 0), oklch(.269 0 0)); + --secondary-foreground: light-dark(oklch(.205 0 0), oklch(.985 0 0)); + --muted: var(--secondary); + --muted-foreground: light-dark(oklch(.556 0 0), oklch(.708 0 0)); + --accent: var(--secondary); + --accent-foreground: var(--secondary-foreground); + --destructive: light-dark(oklch(.577 .245 27.325), oklch(.704 .191 22.216)); + --border: light-dark(oklch(.922 0 0), oklch(1 0 0 / 10%)); + --input: light-dark(oklch(.922 0 0), oklch(1 0 0 / 15%)); + --input-bg: light-dark(transparent, oklch(1 0 0 / 4.5%)); + --ring: light-dark(oklch(.708 0 0), oklch(.556 0 0)); + --shadow-xs: 0 1px 2px 0 rgb(0 0 0 / .05); + --shadow-sm: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1); + --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1); + --font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} +.light { color-scheme: light; } +.dark { color-scheme: dark; } + +/* ---------------------------------------------------------------- base */ +*, ::before, ::after { box-sizing: border-box; } +body { + margin: 0; background: var(--background); color: var(--foreground); + font: 14px/1.5 var(--font-sans); -webkit-font-smoothing: antialiased; +} +.light, .dark { background: var(--background); color: var(--foreground); } +button, input { font: inherit; color: inherit; margin: 0; } +button { border: 0; background: none; padding: 0; } +:focus-visible { outline: none; } +.muted { color: var(--muted-foreground); } +.mono { font-family: var(--font-mono); } +.stack { display: grid; gap: 1rem; } +.row { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; } +.grow { flex: 1; } + +/* ---------------------------------------------------------------- button */ +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: .5rem; + height: 2.25rem; padding: .5rem 1rem; border-radius: calc(var(--radius) - 2px); + border: 1px solid transparent; cursor: pointer; user-select: none; + background: var(--primary); color: var(--primary-foreground); box-shadow: var(--shadow-xs); + transition: background-color .15s, color .15s, box-shadow .15s, opacity .15s; +} +.btn:hover { background: color-mix(in oklab, var(--primary) 90%, transparent); } +.btn:disabled { opacity: .5; pointer-events: none; } +.btn:focus-visible, .input:focus-visible, .checkbox:focus-visible, .switch:focus-visible, +.tab:focus-visible, .toggle:focus-visible { + border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent); +} +.btn.secondary { background: var(--secondary); color: var(--secondary-foreground); } +.btn.secondary:hover { background: color-mix(in oklab, var(--secondary) 80%, transparent); } +.btn.outline { + background: light-dark(var(--background), var(--input-bg)); color: var(--foreground); + border-color: light-dark(var(--border), var(--input)); +} +.btn.outline:hover, .btn.ghost:hover { background: var(--accent); color: var(--accent-foreground); } +.btn.ghost { background: transparent; color: var(--foreground); box-shadow: none; } +.btn.destructive { background: light-dark(var(--destructive), color-mix(in oklab, var(--destructive) 60%, transparent)); color: #fff; } +.btn.destructive:hover { background: color-mix(in oklab, var(--destructive) 90%, transparent); } +.btn.link { background: none; color: var(--primary); box-shadow: none; text-underline-offset: 4px; } +.btn.link:hover { text-decoration: underline; } +.btn.sm { height: 2rem; padding: 0 .75rem; gap: .375rem; } +.btn.lg { height: 2.5rem; padding: 0 1.5rem; } +.btn.icon { width: 2.25rem; padding: 0; } +.btn.icon.sm { width: 2rem; } +.input { + display: flex; width: 100%; min-width: 0; height: 2.25rem; padding: .25rem .75rem; + border: 1px solid var(--input); border-radius: calc(var(--radius) - 2px); + background: var(--input-bg); box-shadow: var(--shadow-xs); font-size: .875rem; + transition: box-shadow .15s, border-color .15s; +} +.input::placeholder { color: var(--muted-foreground); } +@keyframes ui-fade { from { opacity: 0; } } +.alert { + display: grid; gap: .125rem; width: 100%; padding: .75rem 1rem; font-size: .875rem; + border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); color: var(--card-foreground); +} +.alert-title { font-weight: 500; } +.alert-description { color: var(--muted-foreground); } +.alert.destructive { color: var(--destructive); } +.alert.destructive .alert-description { color: color-mix(in oklab, var(--destructive) 90%, transparent); } + /* Home screen layout; the components come from ui.css. The page is transparent so the system wallpaper shows through the WebView. MainActivity sets --inset-top and --inset-bottom to the status and navigation bar (and keyboard) heights. */ @@ -32,14 +128,10 @@ body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: t .windows-glyph::after { inset: .3rem 0 0 .3rem; background: rgb(255 255 255 / .15); } .slots, .apps { list-style: none; margin: 0; padding: 0; display: grid; gap: 1.25rem .5rem; grid-template-columns: repeat(4, minmax(0, 1fr)); } -/* The home grid is denser than the drawer: an extra column, smaller tiles. Its rows are - all one height, so a widget spans whole rows of app tiles, and apps fill the cells - beside a widget rather than leaving holes (dense packing). Keep the row height and - row gap in sync with widget_rows in app.py. */ -.slots { grid-template-columns: repeat(5, minmax(0, 1fr)); grid-auto-rows: 4rem; row-gap: .5rem; - grid-auto-flow: row dense; } -@media (min-width: 480px) { .apps { grid-template-columns: repeat(5, minmax(0, 1fr)); } - .slots { grid-template-columns: repeat(6, minmax(0, 1fr)); } } +/* The home grid is placed explicitly by the model (app/view.mbt sets its columns, rows and + every slot's cell inline); the gaps and the 64px row height must match grid/grid.mbt. */ +.slots { gap: 8px; } +@media (min-width: 480px) { .apps { grid-template-columns: repeat(5, minmax(0, 1fr)); } } .tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: .4rem; padding: .35rem .15rem; border-radius: calc(var(--radius) + 4px); cursor: pointer; } .tile:active { background: rgb(255 255 255 / .12); } @@ -54,7 +146,7 @@ body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: t /* A widget takes whole rows. On a phone the native widget view covers the slot; the label only shows while the slot is not live (or in a desktop browser). */ -.widget-slot { grid-column: 1 / -1; display: grid; place-items: center; box-sizing: border-box; +.widget-slot { display: grid; place-items: center; box-sizing: border-box; border-radius: 1.25rem; background: rgb(255 255 255 / .1); border: 1px dashed rgb(255 255 255 / .3); } .widget-label { font-size: .875rem; opacity: .75; text-shadow: var(--shadow-text); @@ -83,6 +175,9 @@ body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: t display: flex; align-items: center; gap: .5rem; padding: .4rem .4rem .4rem 1rem; border-radius: 999px; background: rgb(0 0 0 / .8); color: #fff; font-size: .875rem; white-space: nowrap; animation: ui-fade .15s; } +.resize-bar { max-width: calc(100vw - 1rem); } +.resize-hint { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.resize-bar .btn { flex: none; } .resize-bar .btn.ghost { color: #fff; } .resize-bar .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; } @@ -96,6 +191,19 @@ body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: t .hint, .empty { text-align: center; opacity: .85; text-shadow: var(--shadow-text); } .hint { margin-top: 30vh; padding: 0 2rem; font-size: .9rem; line-height: 1.5; } +/* The search pill under the panel: a tap opens the drawer. */ +.search-pill { display: flex; align-items: center; gap: .75rem; width: 100%; max-width: 22rem; height: 2.75rem; + margin: -.25rem auto 1rem; padding: 0 1.1rem; border-radius: 999px; cursor: pointer; + background: rgb(255 255 255 / .1); border: 1px solid rgb(255 255 255 / .15); + color: rgb(255 255 255 / .6); font-size: 1rem; text-align: left; } +.search-pill:active { background: rgb(255 255 255 / .18); } +.magnifier { position: relative; flex: none; width: 1rem; height: 1rem; } +.magnifier::before { content: ""; position: absolute; inset: 0 .3rem .3rem 0; border: 2px solid rgb(255 255 255 / .75); + border-radius: 999px; } +.magnifier::after { content: ""; position: absolute; right: 0; bottom: .05rem; width: .45rem; height: 2px; + background: rgb(255 255 255 / .75); border-radius: 1px; transform: rotate(45deg); } +button { cursor: pointer; } + /* ---- drawer: slides down over the home screen */ .drawer { position: fixed; inset: 0; z-index: 10; display: flex; flex-direction: column; padding: calc(var(--top) + 1rem) 16px 0; background: rgb(10 10 14 / .72);