Author SHA1 Message Date
SpriteandClaude Sonnet 5.5 49ea6c54ae CI: run the browser tests on Debian's chromium
Launcher / test (pull_request) Successful in 1m11s
Launcher / apk (pull_request) Skipped
Playwright's Chromium download from cdn.playwright.dev timed out on the runner
(the only failing step; moon tests passed). Install chromium with apt, skip the
Playwright download, and let the tests take CHROMIUM_PATH. The workflow now also
runs tests/android-sim.cjs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 01:49:54 +00:00
SpriteandClaude Sonnet 5.5 a8ce535f37 CI: build the APK in the cluster's android-sdk image
Launcher / test (pull_request) Failing after 5m41s
Launcher / apk (pull_request) Skipped
apk job uses git.site.latha.org/cluster-services/android-sdk:latest; gitea-apk.sh
uses the image's JDK/SDK when present and falls back to installing them
(documented, for use with node:22-bookworm until the image is built).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 01:15:50 +00:00
SpriteandClaude Sonnet 5.5 67b6b58c94 Shell: drop the resetIcons call the page does itself
Launcher / test (pull_request) Failing after 5m46s
Launcher / apk (pull_request) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 01:13:19 +00:00
SpriteandClaude Sonnet 5.5 5258ac22ad Add the README, screenshots, legacy CI moved to manual, cleanups
Root README for the new layout; legacy/README.md points back. Legacy Gitea and
GitHub workflows run only by hand from legacy/ and the Gitea one does not
publish unless asked. Fix compiler warnings.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 01:12:48 +00:00
SpriteandClaude Sonnet 5.5 17f81c60c8 moon fmt
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 01:08:53 +00:00
SpriteandClaude Sonnet 5.5 dccbfd7d86 Add the Android shell, APK build, bridge test, sweet config and CI
android/: HomeActivity (derived from the legacy MainActivity, same package
dev.ultra.launcher and class name as the Qt build so the default-home choice
carries over), Updater reduced to httpGet + PackageInstaller, RecentsService,
manifest and resources, the committed debug keystore. android/build.sh builds
the APK with aapt2, javac, d8, zipalign and apksigner (no Gradle).
tests/android-sim.cjs drives the page against a stub of window.Android.
.sweet.config.yml / .sweet.yml with moon.mod as the annotated version file.
CI: test job (moon test on js and wasm-gc, browser tests) and an apk job that
publishes a Gitea release.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 01:08:35 +00:00
SpriteandClaude Sonnet 5.5 637129aa4e Add the web runtime (DOM patcher, events, host bridge) and a browser e2e
web/ is the js-target MoonBit program: it renders app.view into the DOM with a
keyed patcher, turns pointer/touch/key events into app input, runs effects
against window.Android or demo stand-ins, and exposes window.launcher.* for the
Android shell. tests/e2e.cjs ports the legacy Playwright flows and passes
against the build; scripts/build-web.sh assembles dist/web.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 01:02:08 +00:00
SpriteandClaude Sonnet 5.5 28e0284d9b Add the pure MoonBit core: grid, gestures, updater, vdom, app
grid: packing, pinning, resize steps (port of Layout.js and app.py's grid logic).
gesture: pointer state machine (tap, long press, drag, release, swipe).
updater: release/version parsing and the update decision.
vdom: pure virtual DOM with an HTML-text renderer for tests.
app: Elm-style Model/Msg/update/view with effects as data, persistence (JSON
layout, import of the old WebView build's localStorage), drawer/search, menus,
drag and resize. 60 headless tests drive it through pointer input.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 00:55:16 +00:00
SpriteandClaude Sonnet 5.5 66e8e90da1 Move the existing launcher into legacy/
git mv of everything (web/ android/ qt/ wasi/ android-wasm/ tests/ ci/ pixi.toml
README) so history follows; legacy/ keeps its own .gitignore and a new root
.gitignore starts for the MoonBit project.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 00:55:15 +00:00
150 changed files with 8319 additions and 462 deletions

No files matched your search

+53 -13
View File
@@ -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
+33
View File
@@ -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-<minutes>) 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
@@ -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'
+9 -10
View File
@@ -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
+15
View File
@@ -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
+8
View File
@@ -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
+78 -20
View File
@@ -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-<versionCode>` 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).
+63
View File
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- versionCode and versionName are given to aapt2 by android/build.sh. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dev.ultra.launcher">
<!-- The updater downloads new builds of the launcher and installs them over itself. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- Uninstall from the app drawer's long-press menu (ACTION_DELETE needs it on Android 9+). -->
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<!-- Android 11+ package visibility: list every launchable activity. -->
<queries>
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent>
</queries>
<application
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:theme="@style/Home"
android:allowBackup="false"
android:supportsRtl="true">
<!-- Same class name as the Qt build's, so a default-home choice survives the update. -->
<activity
android:name=".HomeActivity"
android:exported="true"
android:launchMode="singleTask"
android:stateNotNeeded="true"
android:clearTaskOnLaunch="true"
android:excludeFromRecents="true"
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".Updater$InstallReceiver"
android:exported="false" />
<!-- Opens Recents for the Windows button; the user turns it on in Accessibility. -->
<service
android:name=".RecentsService"
android:label="@string/recents_service_label"
android:exported="true"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/recents_service" />
</service>
</application>
</manifest>
+49
View File
@@ -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"
File renamed without changes.
@@ -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<Integer, AppWidgetHostView> widgetViews = new HashMap<>();
private final Map<Integer, Long> 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<String, byte[]> icons = new ConcurrentHashMap<>();
private final Map<String, LauncherActivityInfo> 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<String> 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<LauncherActivityInfo> list = new ArrayList<>(launcher.getActivityList(null, user));
Map<LauncherActivityInfo, String> 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<AppWidgetProviderInfo> list = new ArrayList<>(widgets.getInstalledProvidersForProfile(user));
Map<AppWidgetProviderInfo, String> 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<Rect> 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<Integer, int[]> 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<Integer, AppWidgetHostView> e : widgetViews.entrySet()) {
if (!want.containsKey(e.getKey())) e.getValue().setVisibility(View.GONE);
}
for (Map.Entry<Integer, int[]> 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<SizeF> 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<String, String> 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";
}
}
@@ -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();
}
}
}
}
File renamed without changes.
File renamed without changes.
+323
View File
@@ -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
}
+9
View File
@@ -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",
}
+169
View File
@@ -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..<n {
let str = match @jsonx.get(kv, "ultra.home.str.\{i}") {
Some(String(s)) => 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),
}
}
+243
View File
@@ -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
+904
View File
@@ -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..<s.m.widgets.length() {
if s.m.widget_matches(i) {
out.push(s.m.widgets[i].label)
}
}
out
}
let c = s.chain("widget-search")
s.run(typed(s.m, s.table, c, "cal"))
assert_eq(names(), ["Calendar"])
s.run(typed(s.m, s.table, c, "goo"))
assert_eq(names(), ["Weather"]) // by the app it comes from
s.run(typed(s.m, s.table, c, "zzz"))
assert_true(s.sheet_html().contains("No widgets match."))
s.run(typed(s.m, s.table, c, ""))
s.press(
s
.chain_where(fn(e) { e.tag == "li" && text_of(El(e)).contains("Clock") })
.unwrap(),
)
s.release()
assert_true(s.has_effect(AddWidget("c.clock/.W")))
s.send(WidgetAdded(100))
assert_eq(s.home_names(), ["Chrome", "[Clock]"])
assert_eq(s.m.home[1].wid, 100)
assert_eq(s.m.home[1].rows, 2) // 140px: two rows
assert_true(s.has_effect(QueryLimits(100)))
// its natural width sets the starting columns: 110px wide = 2 columns
s.send(
LimitsKnown(
100,
Some("{\"w\":110,\"minW\":110,\"minH\":80,\"h\":true,\"v\":true}"),
),
)
assert_eq(s.m.home[1].w, 2)
let html = @vdom.to_html(s.tree[0])
assert_true(html.contains("data-wid=\"100\""))
assert_true(html.contains("widget-slot"))
}
///|
test "widget picker Enter chooses the first match" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
let c = s.chain("widget-search")
s.run(typed(s.m, s.table, c, "cal"))
s.run(key(s.m, s.table, c, Enter))
assert_true(s.has_effect(AddWidget("c.cal/.W")))
assert_eq(s.m.sheet, NoSheet)
}
///|
test "a widget: hold opens resize handles; drag the handles; Done" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(100))
s.send(
LimitsKnown(
100,
Some("{\"w\":0,\"minW\":64,\"minH\":64,\"h\":true,\"v\":true}"),
),
)
assert_eq(s.m.home[0].w, 0)
let (wx, wy) = cell_center(2, 0)
s.long_press(s.chain("widget-slot"), x=wx, y=wy)
assert_eq(s.m.resizing, 0) // no item menu for a widget: handles
assert_eq(s.m.sheet, NoSheet)
let html = @vdom.to_html(s.tree[0])
assert_true(html.contains("resize-handle"))
assert_true(
@vdom.to_html(s.tree[1]).contains(
"Drag to move, or drag the handles to resize",
),
)
// drag the bottom handle down to the fourth row
let hc = s
.chain_where(fn(e) { e.attrs.contains(("data-edge", "b")) })
.unwrap()
s.press(hc, x=100.0, y=150.0 + 2.0 * 72.0 + 70.0)
assert_true(s.has_effect(QueryLimits(100)))
s.move_to(100.0, 150.0 + 3.0 * 72.0 + 40.0)
s.release()
assert_eq(s.m.home[0].rows, 4)
assert_eq(s.m.resizing, 0) // handles stay
// the right handle to three columns (the widget starts the full row)
let rc = s
.chain_where(fn(e) { e.attrs.contains(("data-edge", "r")) })
.unwrap()
s.press(rc, x=370.0, y=170.0)
let (c3x, _) = cell_center(2, 0)
s.move_to(c3x + 36.0, 170.0)
s.release()
assert_eq(s.m.home[0].w, 3)
// pressing the widget's body picks it up at once; letting go keeps the handles
let wc = s.chain("widget-slot")
s.press(wc, x=wx, y=wy)
assert_eq(s.m.lifted, 0)
s.release()
assert_eq(s.m.resizing, 0)
assert_eq(s.m.lifted, -1)
// Done (a tap on the bar's button) ends it
s.tap("btn", label="Done")
assert_eq(s.m.resizing, -1)
assert_eq(s.m.home[0].w, 3)
}
///|
test "resizing stays within the widget's limits" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(100))
s.send(
LimitsKnown(
100,
Some(
"{\"w\":0,\"minW\":200,\"maxW\":220,\"minH\":64,\"h\":true,\"v\":false}",
),
),
)
let (wx, wy) = cell_center(2, 0)
s.long_press(s.chain("widget-slot"), x=wx, y=wy)
let rc = s
.chain_where(fn(e) { e.attrs.contains(("data-edge", "rb")) })
.unwrap()
s.press(rc, x=370.0, y=250.0)
s.move_to(60.0, 600.0) // far left and down
s.release()
assert_eq(s.m.home[0].w, 3) // 3 columns = 204px, the nearest to 200 within the limit
assert_eq(s.m.home[0].rows, 2) // vertical resizing is off
}
///|
test "a native widget view lifts, drags and drops its slot" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(2))
s.send(WidgetAdded(7))
s.send(
LimitsKnown(
7,
Some("{\"w\":130,\"minW\":64,\"minH\":64,\"h\":true,\"v\":true}"),
),
)
assert_eq(s.m.home[0].w, 2)
s.send(WidgetMenu(7))
assert_eq(s.m.lifted, 0)
let (x, y) = cell_center(1, 0)
s.send(NativeDrag(x, y))
let (tx, ty) = cell_center(2, 3)
s.send(NativeDrag(tx, ty))
s.send(NativeDrop(true))
assert_eq(s.m.lifted, -1)
assert_eq(s.m.sheet, NoSheet)
assert_eq((s.m.home[0].x, s.m.home[0].y), (1, 3)) // it moved by the finger's travel
// lifting and letting go without moving shows the handles
s.send(WidgetMenu(7))
s.send(NativeDrop(false))
assert_eq(s.m.resizing, 0)
// a press on the native view while handles show picks it up
s.send(WidgetGrab(7))
assert_eq(s.m.lifted, 0)
s.send(NativeDrop(false))
assert_eq(s.m.resizing, 0)
}
///|
test "widgets and apps drawn under a sheet or the drawer are not live" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(5))
assert_true(@vdom.to_html(s.tree[0]).contains("data-wid=\"5\""))
s.send(OpenDrawer)
assert_true(!@vdom.to_html(s.tree[0]).contains("data-wid"))
}
///|
test "back and home close things from the top down" {
let s = Sim::new()
s.send(OpenDrawer)
s.long_press(s.chain("tile", label="Gmail", from=1))
assert_eq(s.m.sheet, DrawerApp(3))
s.send(Back)
assert_eq(s.m.sheet, NoSheet)
assert_true(s.m.drawer)
s.send(Back)
assert_true(!s.m.drawer)
s.send(OpenDrawer)
s.send(GoHome)
assert_true(!s.m.drawer)
assert_true(s.has_effect(ScrollTop))
}
///|
test "the layout is saved on every change and restored" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail"])
let mut saved = ""
for e in s.log {
if e is SaveHome(j) {
saved = j
}
}
assert_eq(saved, save_json(s.m.home))
let s2 = Sim::new()
s2.run(update(s2.m, Restore(saved=Some(saved), legacy=None)))
assert_eq(s2.home_names(), ["Chrome", "Gmail"])
// restoring what is already saved doesn't save it again
let n = s2.log.filter(fn(e) { e is SaveHome(_) }).length() - 1 // Sim::new saved the empty one
assert_eq(n, 0)
}
///|
test "the old WebView build's home screen is brought over once" {
let legacy =
#|{"ultra.home.n":"3",
#|"ultra.home.kind.0":"0","ultra.home.str.0":"c.chrome/.Main","ultra.home.cx.0":"-1","ultra.home.cy.0":"-1",
#|"ultra.home.kind.1":"1","ultra.home.str.1":"Clock","ultra.home.wid.1":"12","ultra.home.h.1":"136",
#|"ultra.home.w.1":"3","ultra.home.cx.1":"1","ultra.home.cy.1":"2",
#|"ultra.home.kind.2":"0"}
let next = Ref(1)
let slots = legacy_import(legacy, next)
assert_eq(slots.length(), 2)
assert_eq((slots[0].kind, slots[0].str), (App, "c.chrome/.Main"))
assert_eq(
(slots[1].wid, slots[1].w, slots[1].rows, slots[1].x, slots[1].y),
(12, 3, 2, 1, 2),
)
assert_eq(legacy_import("{}", Ref(1)).length(), 0)
assert_eq(legacy_import("garbage", Ref(1)).length(), 0)
let s = Sim::new()
s.run(update(s.m, Restore(saved=None, legacy=Some(legacy))))
assert_eq(s.m.home.length(), 2)
assert_true(s.log.contains(SaveHome(save_json(s.m.home)))) // saved in the new format
// a saved layout wins over the old one
let s2 = Sim::new()
s2.run(
update(
s2.m,
Restore(
saved=Some(save_json([slot_app("c.gmail/.Main")])),
legacy=Some(legacy),
),
),
)
assert_eq(s2.m.home.length(), 1)
}
///|
fn slot_app(c : String) -> @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=(
#|<div class="home" on="press">
#| <section class="panel" aria-label="Shortcuts">
#| <button class="panel-btn" on="tap">
#| <span class="windows-glyph" aria-hidden="true"></span>
#| <span>Windows</span>
#| </button>
#| </section>
#| <button class="search-pill" aria-label="Search apps" on="tap">
#| <span class="magnifier" aria-hidden="true"></span>
#| <span>Search apps</span>
#| </button>
#| <ul class="slots" style="grid-template-columns:repeat(5,minmax(0,1fr));grid-template-rows:repeat(8,64px)">
#| <li class="tile" data-slot="0" style="grid-column:1 / span 1;grid-row:1 / span 1" on="tap press">
#| <img class="icon" alt="" draggable="false" data-icon="i3"></img>
#| <span class="name">Chrome</span>
#| </li>
#| </ul>
#|</div>
),
)
}
+815
View File
@@ -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..<self.apps.length() {
if self.apps[i].component == component {
return i
}
}
-1
}
///|
/// The home slot holding the app at `row` in the app list, or -1.
pub fn Model::home_of(self : Model, row : Int32) -> Int32 {
let comp = self.apps[row].component
for i in 0..<self.home.length() {
if self.home[i].kind == App && self.home[i].str == comp {
return i
}
}
-1
}
///|
pub fn Model::slot_of_widget(self : Model, wid : Int32) -> Int32 {
for i in 0..<self.home.length() {
if self.home[i].kind == Widget && self.home[i].wid == wid {
return i
}
}
-1
}
///|
/// The first app (row in the list) whose label matches the search.
pub fn Model::first_match(self : Model) -> Int32 {
for i in 0..<self.apps.length() {
if matches_query(self.apps[i].label, self.query) {
return i
}
}
-1
}
///|
pub fn Model::widget_matches(self : Model, i : Int32) -> 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..<self.widgets.length() {
if self.widget_matches(i) {
return i
}
}
-1
}
///|
/// Home slots that are not drawn: apps that are not installed.
pub fn Model::hidden(self : Model, i : Int32) -> 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..<self.home.length() {
if self.home[i].kind == App && self.home[i].str == self.gone {
self.remove_slot(i, fx)
break
}
}
self.gone = ""
}
///|
fn Model::close_all(self : Model, fx : Array[Effect]) -> 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..<self.home.length() {
if i == self.lifted {
continue
}
if self.slot_box(packed, i) is Some(b) && inside(b, x, y) {
return i
}
}
-1
}
///|
/// The pointer is at x, y with a slot lifted (it went down at x0, y0). An app over
/// another slot takes its place in the order; over an empty cell it is left in that cell.
/// A widget goes to the cell under it wherever that is (apps flow around it).
fn Model::drag_lifted(
self : Model,
x : Double,
y : Double,
x0 : Double,
y0 : Double,
) -> 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
}
+503
View File
@@ -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..<self.home.length() {
if self.view_slot(i, packed) is Some(n) {
slots.push(n)
}
}
let rows = if self.home.length() > 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..<self.apps.length() {
let a = self.apps[i]
if !matches_query(a.label, self.query) {
continue
}
tiles.push(
el(
"li",
key=i + 1,
classes=["tile", cls_if("on", self.picking && self.home_of(i) >= 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..<self.widgets.length() {
if !self.widget_matches(i) {
continue
}
let w = self.widgets[i]
let name : Array[Node[Msg]] = [text(w.label)]
if w.app != "" && w.app != w.label {
name.push(el("small", children=[text(w.app)]))
}
rows.push(
el("li", key=i + 1, handlers=tap(ChooseWidget(i)), children=[
icon(w.icon),
el("span", classes=["widget-name"], children=name),
]),
)
}
items.push(el("ul", classes=["widget-list"], children=rows))
if !self.wloading && self.widgets.length() > 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))
}
}
}
[]
}
+37 -49
View File
@@ -1,60 +1,48 @@
#!/usr/bin/env bash
# Tests the Qt launcher (qt/), builds its APK and publishes it as a Gitea release:
# build-<versionCode>, 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-<versionCode>, 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"
Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

+149
View File
@@ -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)
}
}
+69
View File
@@ -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
}
+1
View File
@@ -0,0 +1 @@
+57
View File
@@ -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
+354
View File
@@ -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..<n {
let s = slots[i]
if hidden(i) || !s.pinned(cols) {
continue
}
let w = s.cols(cols)
let h = s.height()
cells[i] = Some({ col: s.x, row: s.y, w, h, })
mark(s.x, s.y, w, h)
rows = @cmp.maximum(rows, s.y + h)
}
for i in 0..<n {
let s = slots[i]
if hidden(i) || cells[i] is Some(_) {
continue
}
let w = s.cols(cols)
let h = s.height()
let mut r = 0
while cells[i] is None {
let mut c = 0
while c + w <= cols {
if fits(c, r, w, h) {
cells[i] = Some({ col: c, row: r, w, h, })
mark(c, r, w, h)
rows = @cmp.maximum(rows, r + h)
break
}
c += 1
}
r += 1
}
}
{ cells, rows, }
}
///|
/// A cell's box in px, given the column width: (x, y, w, h).
pub fn box(cell : Cell, col_w : Double) -> (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..<slots.length() {
let b = slots[j]
if j == i || b.x < 0 {
continue
}
if b.x < a.x + a.cols(cols) &&
a.x < b.x + b.cols(cols) &&
b.y < a.y + a.height() &&
a.y < b.y + b.height() {
b.x = -1
b.y = -1
}
}
}
///|
/// Take slot `a` out and put it back at `b`, shifting the slots between.
pub fn move_slot(slots : Array[Slot], a : Int32, b : Int32) -> 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)
}
+157
View File
@@ -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)
}
+3
View File
@@ -0,0 +1,3 @@
import {
"moonbitlang/core/cmp",
}
+84
View File
@@ -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
+52
View File
@@ -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
}
}
+13
View File
@@ -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)
}
+3
View File
@@ -0,0 +1,3 @@
import {
"moonbitlang/core/json",
}
+27
View File
@@ -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
+11
View File
@@ -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
+41
View File
@@ -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
```
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 4.7 KiB

File renamed without changes.
File renamed without changes.
File renamed without changes.
Binary file not shown.
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- The wallpaper shows through the transparent window and WebView. -->
<style name="Home" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
<item name="android:windowShowWallpaper">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
</style>
</resources>
File renamed without changes.
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env bash
# Tests the Qt launcher (qt/), builds its APK and publishes it as a Gitea release:
# build-<versionCode>, 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"
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:angle="315" android:startColor="#4C1D95" android:endColor="#1E293B" />
</shape>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A 3x3 grid of app dots inside the adaptive icon's 72dp safe zone. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp" android:height="108dp"
android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#FFFFFF"
android:pathData="M36,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M36,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M36,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0" />
</vector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ultra Home</string>
<string name="recents_service_label">ultra Home window list</string>
<string name="recents_service_summary">Lets the home screen\'s Windows button open Recents</string>
<string name="recents_service_description">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.</string>
</resources>
File renamed without changes.
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Only performGlobalAction(RECENTS): no events, no window content. -->
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/recents_service_description"
android:summary="@string/recents_service_summary"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagDefault"
android:canRetrieveWindowContent="false"
android:notificationTimeout="0" />
@@ -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() { }
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more