4 Commits
Author SHA1 Message Date
nandi 472a48f4bd Add an icon size setting (#3)
Launcher / test (push) Successful in 1m59s
Launcher / apk (push) Successful in 38s
2026-11-24 22:43:04 +00:00
nandi 3070db4fb4 Fix wallpaper transparency, Recents setup guide, drawer animation, and widget resizing (#2)
Launcher / test (push) Successful in 1m21s
Launcher / apk (push) Successful in 17s
2026-11-23 05:36:23 +00:00
nandi 2fa7bd745b Rewrite the launcher in MoonBit (old code moves to legacy/) (#1)
Launcher / test (push) Successful in 1m20s
Launcher / apk (push) Successful in 37s
2026-11-23 01:57:10 +00:00
nandi 7d2bf5996f Add home search pill that opens the app drawer
Launcher / apk (push) Failing after 2m47s
2026-11-18 22:18:50 +00:00
159 changed files with 10101 additions and 488 deletions

No files matched your search

+53 -13
View File
@@ -1,26 +1,66 @@
name: Launcher 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: on:
push: push:
branches: [main] branches: [main]
pull_request:
workflow_dispatch:
jobs: jobs:
apk: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 60 # Node comes from the image, not actions/setup-node: its download stalls on this
container: eclipse-temurin:17-jdk-noble # runner and holds the cluster's only runner slot (see identicons-web's workflow).
container:
image: node:22-bookworm
timeout-minutes: 20
steps: steps:
- name: Checkout - uses: actions/checkout@v4
env:
GITHUB_TOKEN: ${{ github.token }} - name: Install MoonBit
run: | run: |
apt-get update -qq curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
apt-get install -y -qq --no-install-recommends git ca-certificates >/dev/null echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
git init -q
git -c http.extraHeader="Authorization: Basic $(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0)" \ - name: Check and test
fetch -q --depth 1 "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" "${GITHUB_SHA}" run: |
git checkout -q --detach FETCH_HEAD moon update
- name: Test, build and release the Qt APK 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: env:
GITEA_TOKEN: ${{ github.token }} GITEA_TOKEN: ${{ github.token }}
run: bash ci/gitea-apk.sh 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: on:
push:
branches: [main]
pull_request:
workflow_dispatch: workflow_dispatch:
permissions: permissions:
contents: write contents: write
defaults:
run:
working-directory: legacy
jobs: jobs:
web: web:
# Playwright's Chromium has no build for ubuntu-latest (26.04) yet. # Playwright's Chromium has no build for ubuntu-latest (26.04) yet.
@@ -24,6 +27,7 @@ jobs:
with: with:
cache: false cache: false
locked: false locked: false
manifest-path: legacy/pixi.toml
# Playwright's browser download hangs while unpacking under pixi's Node 26, so fetch # 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. # Chromium with the runner's own Node; the test itself still runs in the pixi env.
- uses: actions/setup-node@v5 - uses: actions/setup-node@v5
@@ -49,14 +53,14 @@ jobs:
java-version: 17 java-version: 17
- uses: gradle/actions/setup-gradle@v5 - uses: gradle/actions/setup-gradle@v5
- name: Build the APK - 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 # 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). # (it restarts if this workflow is renamed; bump past the old numbers then).
run: ./gradlew --no-daemon assembleDebug -PversionCode=${{ github.run_number }} run: ./gradlew --no-daemon assembleDebug -PversionCode=${{ github.run_number }}
- uses: actions/upload-artifact@v5 - uses: actions/upload-artifact@v5
with: with:
name: ultra-launcher-apk 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. # Keep a "launcher-latest" prerelease with the newest APK, so a phone can download it directly.
- name: Publish the launcher-latest release - name: Publish the launcher-latest release
if: github.event_name != 'pull_request' if: github.event_name != 'pull_request'
+9 -10
View File
@@ -1,11 +1,10 @@
__pycache__/ _build/
.mooncakes/
.context/
node_modules/ node_modules/
.pixi/ /dist/
android/.gradle/ /build/
android/build/ /android/build/
android/app/build/ *.apk
android/local.properties __pycache__/
build/ *.idsig
build-*/
android-wasm/target/
android-wasm/assets/*.wasm
+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
+5
View File
@@ -0,0 +1,5 @@
---
type: fix
---
Show the Android system wallpaper behind the transparent WebView, add an in-app setup guide for Android 13+ "Restricted setting" on the Windows button, smooth out app drawer animations with keyed overlays, GPU-composited transitions, delayed IME focus, and pre-warmed app icons, and fix widget resizing across all four edges with edge touch passthrough, scroll-synced coordinates, and axis-conditional handles.
+5
View File
@@ -0,0 +1,5 @@
---
type: feature
---
Add an icon size setting (long-press the home screen, then Icon size): a 70-160% slider with Small / Medium / Large presets and a live preview that resizes the home grid and the app drawer together. Icon, label and row height scale, the column count reflows so nothing overlaps or clips, the choice is saved, and a corrupt saved value is logged and shown instead of silently replaced. 100% is the original size.
+84 -20
View File
@@ -1,39 +1,103 @@
# ultra launcher # 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. **Icon size** in the same menu sets how big icons are (70%–160% in steps of 5, with Small / Medium / Large presets and a live preview; Medium, 100%, is the original size). It applies to the home screen and the app drawer together, scales icon, label and row height, and changes the column count so nothing overlaps or clips. 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) |
Icon size, before (100%) and at 130% / 70%, the drawer at 130%, and the error shown for a corrupt saved value:
| before | 130% | 70% | drawer 130% | corrupt value |
|---|---|---|---|---|
| ![before](docs/screenshots/06-icon-size-before.png) | ![large](docs/screenshots/07-icon-size-large.png) | ![small](docs/screenshots/08-icon-size-small.png) | ![drawer](docs/screenshots/09-icon-size-drawer-large.png) | ![corrupt](docs/screenshots/10-icon-size-corrupt.png) |
(Screenshots are of the browser demo at phone size.)
## Install ## 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. 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. ## How it is built
- `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 MoonBit owns the logic and the UI; Java is only what Android itself requires.
```sh ```
pixi run build # web/app.py -> web/app.wasm ┌──────────────── pure MoonBit (no platform deps; moon test on js and wasm-gc) ───────────────┐
pixi run install-playwright && pixi run test pointer / touch / │ gesture ──► app.input ──► app.update(Model, Msg) ──► Effects (data) │
cd android && ./gradlew assembleDebug # needs JDK 17 and the Android SDK 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, and the icon size setting (range, parsing, row height, column counts) | `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 ```sh
node qt/tests/layout.test.mjs # grid packing moon test # the pure core: grid, gestures, updater, the app (js backend)
cmake -S qt -B build && cmake --build build # desktop build, needs Qt 6.8+ moon test --target wasm-gc # the same tests on a second backend
build/ultrahome # try it against the demo apps scripts/build-web.sh --demo # the page -> dist/web (with the demo apps.json / widgets.json)
QT_QPA_PLATFORM=offscreen build/ultrahome_e2e # end-to-end test of the UI 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.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,46 @@
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;
/** Whether the accessibility service is currently connected. */
static boolean isRunning() {
return running != null;
}
/** 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() { }
}
@@ -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();
}
}
}
}
+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. If Android blocks this as a restricted setting, open ultra Home\'s App info and turn on Allow restricted settings once. This service reads nothing on screen and does nothing else.</string>
</resources>
File renamed without changes.
+377
View File
@@ -0,0 +1,377 @@
///|
/// 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
RecentsSetup
/// The icon size slider and presets.
IconSize
}
///|
#derive(Eq, Debug)
pub(all) enum Edge {
Left
Right
Top
Bottom
Corner
}
///|
/// A resize in progress: a handle was pressed on the widget whose viewport box and
/// grid edges were captured on down.
pub(all) struct ResizeDrag {
edge : Edge
slot : Int32
left : Double
top : Double
right : Double
bottom : Double
anchor_col : Int32
anchor_row : Int32
right_col : Int32
bottom_row : Int32
mut col : Int32
mut row : Int32
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
/// Icon size in percent of the original (see grid/scale.mbt), applied to the home
/// grid and the drawer.
mut icon_pct : Int32
/// Why the saved icon size could not be used (empty: it could); shown in the icon
/// size sheet. The bad stored value is left alone until a size is chosen.
mut icon_error : String
/// The last measurement, kept so a size change can lay out again without one.
mut vw : Int32
mut grid_w : Double
/// Px of screen below the top of the grid that rows can fill.
mut avail_h : Double
/// Columns of the drawer's app list.
mut drawer_cols : Int32
mut query : String
mut wquery : String
mut drawer : Bool
/// The drawer is animating out before detaching.
mut drawer_closing : Bool
mut drawer_gen : Int32
/// 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,
icon_pct: @grid.scale_default,
icon_error: "",
vw: 0,
grid_w: 0.0,
avail_h: 0.0,
drawer_cols: 4,
query: "",
wquery: "",
drawer: false,
drawer_closing: false,
drawer_gen: 0,
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?, icon_size~ : 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,
scroll_y~ : 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
DrawerClosed(Int32)
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
/// Open the icon size sheet.
IconSizeMenu
/// The slider's value (text, as the input reports it).
SetIconSize(String)
/// A preset button, in percent.
IconPreset(Int32)
Wallpaper
Recents
RecentsUnavailable
OpenAccessibilitySettings
OpenSelfAppInfo
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
OpenAccessibilitySettings
OpenSelfAppInfo
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)
/// Store the icon size (percent).
SaveIconSize(Int32)
/// Write a line to the platform's error log.
LogError(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),
}
}
+277
View File
@@ -0,0 +1,277 @@
// 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 {
Left
Right
Top
Bottom
Corner
}
#derive(Eq, @debug.Debug)
pub(all) enum Effect {
Launch(String)
AppInfo(String)
Uninstall(String)
AddWidget(String)
RemoveWidget(Int32)
OpenSettings
PickWallpaper
OpenRecents
OpenAccessibilitySettings
OpenSelfAppInfo
Haptic
LoadApps
LoadWidgets
QueryLimits(Int32)
SaveHome(String)
SaveIconSize(Int32)
LogError(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 icon_pct : Int32
mut icon_error : String
mut vw : Int32
mut grid_w : Double
mut avail_h : Double
mut drawer_cols : Int32
mut query : String
mut wquery : String
mut drawer : Bool
mut drawer_closing : Bool
mut drawer_gen : Int32
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::cell_h(Self) -> Int32
pub fn Model::drawer_open(Self) -> Bool
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::icon_keys(Self) -> Array[String]
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?, icon_size~ : 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, scroll_y~ : 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
DrawerClosed(Int32)
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
IconSizeMenu
SetIconSize(String)
IconPreset(Int32)
Wallpaper
Recents
RecentsUnavailable
OpenAccessibilitySettings
OpenSelfAppInfo
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
right : Double
bottom : Double
anchor_col : Int32
anchor_row : Int32
right_col : Int32
bottom_row : Int32
mut col : Int32
mut row : Int32
mut cols : Int32
mut rows : Int32
}
#derive(Eq, @debug.Debug)
pub(all) enum Sheet {
NoSheet
HomeMenu
Item(Int32)
DrawerApp(Int32)
WidgetPicker
RecentsSetup
IconSize
}
pub(all) struct WidgetInfo {
label : String
provider : String
icon : String
app : String
h : Int32
}
// Type aliases
// Traits
+1340
View File
File diff suppressed because it is too large. Load diff
+997
View File
@@ -0,0 +1,997 @@
///|
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
}
///|
/// Height of a home row at the current icon size.
pub fn Model::cell_h(self : Model) -> Int32 {
@grid.cell_height(self.icon_pct)
}
///|
/// Columns, rows and column width from the last measurement and the icon size. Run when
/// either changes.
fn Model::relayout(self : Model) -> Unit {
if self.vw <= 0 {
return // not measured yet
}
self.cols = @grid.home_columns(self.vw, self.grid_w, self.icon_pct)
self.col_w = @grid.column_width(self.grid_w, self.cols)
self.nrows = @grid.rows_fit(self.avail_h, ch=self.cell_h())
self.drawer_cols = @grid.drawer_columns(self.vw, self.icon_pct)
}
///|
/// Apply a new icon size (already valid): lay out again and save it.
fn Model::set_icon_pct(self : Model, pct : Int32, fx : Array[Effect]) -> Unit {
self.icon_error = ""
if pct == self.icon_pct {
fx.push(SaveIconSize(pct)) // also replaces a corrupt stored value
return
}
self.icon_pct = pct
self.relayout()
fx.push(SaveIconSize(pct))
}
///|
/// The icon size is unusable: say so on screen and in the log; nothing is changed.
fn Model::icon_size_error(
self : Model,
reason : String,
fx : Array[Effect],
) -> Unit {
self.icon_error = reason
fx.push(LogError("launcher: \{reason}"))
self.say("Icon size problem: \{reason}", fx)
}
///|
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 = ""
}
///|
/// Whether the drawer is open and not currently animating out.
pub fn Model::drawer_open(self : Model) -> Bool {
self.drawer && !self.drawer_closing
}
///|
/// App icon keys in priority order: home-screen apps first, then the rest of the app list.
pub fn Model::icon_keys(self : Model) -> Array[String] {
let out : Array[String] = []
let seen : Map[String, Bool] = Map([])
for s in self.home {
if s.kind == App {
let row = self.app_row(s.str)
if row >= 0 {
let k = self.apps[row].icon
if k != "" && !seen.contains(k) {
seen[k] = true
out.push(k)
}
}
}
}
for a in self.apps {
let k = a.icon
if k != "" && !seen.contains(k) {
seen[k] = true
out.push(k)
}
}
out
}
///|
fn Model::close_all(self : Model, fx : Array[Effect]) -> Unit {
if self.drawer && !self.drawer_closing {
fx.push(HideKeyboard)
}
self.query = ""
self.drawer = false
self.drawer_closing = false
self.drawer_gen += 1
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_open() {
self.drawer = true
self.drawer_closing = false
self.drawer_gen += 1
self.picking = false
self.query = ""
fx.push(FocusSearch)
}
}
///|
fn Model::close_drawer(self : Model, fx : Array[Effect]) -> Unit {
if self.drawer_open() && self.sheet == NoSheet {
self.drawer_closing = true
self.drawer_gen += 1
fx.push(HideKeyboard)
fx.push(Delay(140, DrawerClosed(self.drawer_gen)))
}
}
// ---- 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, ch=self.cell_h())
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 = self.cell_h().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,
ch=self.cell_h(),
)
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() * (self.cell_h() + @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 * (self.cell_h() + @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,
ch=self.cell_h(),
)
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, fx : Array[Effect]) -> 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
fx.push(QueryLimits(s.wid))
}
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]
guard self.packed().cells[i] is Some(cell) else { return }
s.x = cell.col
s.y = cell.row
let (bx, by, bw, bh) = @grid.box(cell, self.col_w, ch=self.cell_h())
let left = self.grid_left + bx
let top = self.grid_top + by
self.resize = Some({
edge,
slot: i,
left,
top,
right: left + bw,
bottom: top + bh,
anchor_col: cell.col,
anchor_row: cell.row,
right_col: cell.col + cell.w,
bottom_row: cell.row + cell.h,
col: cell.col,
row: cell.row,
cols: cell.w,
rows: cell.h,
})
fx.push(QueryLimits(s.wid))
}
///|
/// Dragging a handle snaps the widget to whole columns and rows, within its limits
/// and without shifting its anchored edge.
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 col = r.col
let mut row = r.row
let mut cols = r.cols
let mut rows = r.rows
let cg = @grid.col_gap.to_double()
let rg = @grid.row_gap.to_double()
if lim.h {
match r.edge {
Right | Corner => {
let hi = @cmp.maximum(1, n - r.anchor_col)
cols = @grid.fit(
x - r.left,
1,
hi,
self.col_w,
cg,
lim.min_w,
lim.max_w,
)
col = r.anchor_col
}
Left => {
let hi = @cmp.maximum(1, @cmp.minimum(n, r.right_col))
cols = @grid.fit(
r.right - x,
1,
hi,
self.col_w,
cg,
lim.min_w,
lim.max_w,
)
col = r.right_col - cols
}
Top | Bottom => ()
}
}
if lim.v {
match r.edge {
Bottom | Corner => {
rows = @grid.fit(
y - r.top,
1,
20,
self.cell_h().to_double(),
rg,
lim.min_h,
lim.max_h,
)
row = r.anchor_row
}
Top => {
let hi = @cmp.maximum(1, @cmp.minimum(20, r.bottom_row))
rows = @grid.fit(
r.bottom - y,
1,
hi,
self.cell_h().to_double(),
rg,
lim.min_h,
lim.max_h,
)
row = r.bottom_row - rows
}
Left | Right => ()
}
}
if col == r.col && row == r.row && cols == r.cols && rows == r.rows {
return
}
r.col = col
r.row = row
r.cols = cols
r.rows = rows
fx.push(Haptic)
s.x = col
s.y = row
s.w = if cols >= n { 0 } else { cols }
s.rows = rows
@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~, icon_size~) => {
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
if icon_size is Some(text) {
match @grid.parse_scale(text) {
Ok(pct) => {
m.icon_pct = pct
m.relayout()
}
Err(reason) => m.icon_size_error("saved \{reason}", fx)
}
}
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~, scroll_y~) => {
m.vw = vw
m.grid_left = grid_left
m.grid_top = grid_top
m.grid_w = grid_w
m.avail_h = vh.to_double() - bottom_pad - (grid_top + scroll_y)
m.relayout()
}
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_open() {
m.close_drawer(fx)
}
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, ch=m.cell_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_open() && 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_open() && 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, fx)
}
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_open() && home_top { m.open_drawer(fx) }
Some(Up) => if m.drawer_open() && 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)
DrawerClosed(gen) =>
if gen == m.drawer_gen && m.drawer_closing {
m.drawer = false
m.drawer_closing = false
m.picking = false
m.query = ""
}
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_open() && 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.drawer_closing = false
m.drawer_gen += 1
m.picking = true
m.query = ""
}
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
}
IconSizeMenu => m.sheet = IconSize
SetIconSize(text) =>
match @grid.parse_scale(text) {
Ok(pct) => m.set_icon_pct(pct, fx)
Err(reason) => m.icon_size_error(reason, fx)
}
IconPreset(pct) =>
if @grid.scale_valid(pct) {
m.set_icon_pct(pct, fx)
} else {
m.icon_size_error("preset \{pct} is not a valid icon size", fx)
}
Wallpaper => {
fx.push(PickWallpaper)
m.sheet = NoSheet
}
Recents => fx.push(OpenRecents)
RecentsUnavailable => {
m.resizing = -1
m.sheet = RecentsSetup
}
OpenAccessibilitySettings => fx.push(OpenAccessibilitySettings)
OpenSelfAppInfo => fx.push(OpenSelfAppInfo)
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_open() &&
m.sheet == NoSheet &&
m.resize is None &&
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_open() && 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, fx)
}
}
}
// ---- 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
}
+703
View File
@@ -0,0 +1,703 @@
///|
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, active : Bool) -> Node[Msg] {
el(
"span",
classes=["resize-handle", cls_if("active", active)],
attrs=[("data-edge", edge), ("aria-hidden", "true")],
handlers={
..Handlers::none(),
down: Some(ResizeBegin(e)),
tap: Some(Nop),
press: 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_open() &&
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 {
let lim = self.limits.get(s.wid).unwrap_or(default_limits)
let active = match self.resize {
Some(r) if r.slot == i => Some(r.edge)
_ => None
}
if lim.h {
children.push(handle("l", Left, active == Some(Left)))
children.push(handle("r", Right, active == Some(Right)))
}
if lim.v {
children.push(handle("t", Top, active == Some(Top)))
children.push(handle("b", Bottom, active == Some(Bottom)))
}
if lim.h && lim.v {
children.push(handle("rb", Corner, active == Some(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="--s:\{@grid.css_factor(self.icon_pct)};grid-template-columns:repeat(\{self.cols},minmax(0,1fr));grid-template-rows:repeat(\{rows},\{self.cell_h()}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",
key=1,
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"],
style="--s:\{@grid.css_factor(self.icon_pct)};grid-template-columns:repeat(\{self.drawer_cols},minmax(0,1fr))",
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",
key=2,
classes=[
"drawer",
cls_if("picking", self.picking),
cls_if("closing", self.drawer_closing),
],
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 preset_btn(label : String, pct : Int32, current : Int32) -> Node[Msg] {
el(
"button",
classes=[
"btn",
if pct == current {
"primary"
} else {
"outline"
},
"sm",
cls_if("on", pct == current),
],
attrs=[("data-preset", pct.to_string())],
handlers=tap(IconPreset(pct)),
children=[text(label)],
)
}
///|
/// The icon size sheet: a preview of a few real icons at the chosen size, the slider, the
/// presets. The home grid behind the sheet changes with the slider as well.
fn Model::view_icon_size(self : Model, items : Array[Node[Msg]]) -> Unit {
let pct = self.icon_pct
items.push(sheet_title("Icon size"))
if self.icon_error != "" {
items.push(
el(
"div",
classes=["alert", "destructive", "icon-error"],
attrs=[("role", "alert")],
children=[
el("div", classes=["alert-title"], children=[
text("Icon size problem"),
]),
el("div", classes=["alert-description"], children=[
text(self.icon_error),
]),
],
),
)
}
let sample : Array[Node[Msg]] = []
for i in 0..<self.apps.length() {
if sample.length() >= 4 {
break
}
let a = self.apps[i]
sample.push(
el("li", key=i + 1, classes=["tile"], children=[
icon(a.icon),
el("span", classes=["name"], children=[text(a.label)]),
]),
)
}
items.push(
el(
"ul",
classes=["icon-preview"],
attrs=[("aria-label", "Preview")],
style="--s:\{@grid.css_factor(pct)}",
children=sample,
),
)
items.push(
el("div", classes=["icon-size-row"], children=[
el(
"input",
classes=["icon-size-slider"],
attrs=[
("type", "range"),
("min", @grid.scale_min.to_string()),
("max", @grid.scale_max.to_string()),
("step", @grid.scale_step.to_string()),
("aria-label", "Icon size"),
],
props=[("value", pct.to_string())],
handlers={ ..Handlers::none(), input: Some(fn(v) { SetIconSize(v) }), },
),
el("span", classes=["resize-size", "icon-size-value"], children=[
text("\{pct}%"),
]),
]),
)
items.push(
el("div", classes=["icon-presets"], children=[
preset_btn("Small", @grid.scale_small, pct),
preset_btn("Medium", @grid.scale_medium, pct),
preset_btn("Large", @grid.scale_large, pct),
]),
)
items.push(
el("div", classes=["sheet-actions"], children=[
el("button", classes=["btn", "ghost"], handlers=tap(CloseSheet), children=[
text("Done"),
]),
]),
)
}
///|
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("Icon size", IconSizeMenu))
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.")]),
)
}
}
IconSize => self.view_icon_size(items)
RecentsSetup => {
items.push(sheet_title("Enable window list"))
items.push(
el("p", classes=["sheet-copy"], children=[
text(
"Android only lets accessibility services open Recents, and blocks them on sideloaded apps until you allow restricted settings once (it stays allowed across updates). This service reads nothing on screen.",
),
]),
)
items.push(
el("ol", classes=["sheet-steps"], children=[
el("li", children=[
text("Tap "),
el("strong", children=[text("Open Accessibility settings")]),
text(" and tap "),
el("strong", children=[text("ultra Home window list")]),
text("."),
]),
el("li", children=[
text("If Android says "),
el("strong", children=[text("Restricted setting")]),
text(", return here, tap "),
el("strong", children=[text("Open App info")]),
text(", then tap "),
el("strong", children=[text("⋮")]),
text(" (or scroll to the bottom on Android 15+) → "),
el("strong", children=[text("Allow restricted settings")]),
text("."),
]),
el("li", children=[
text("Return to "),
el("strong", children=[text("Accessibility settings")]),
text(" and turn on "),
el("strong", children=[text("ultra Home window list")]),
text("."),
]),
]),
)
items.push(
el("div", classes=["sheet-actions"], children=[
el(
"button",
classes=["btn"],
handlers=tap(OpenAccessibilitySettings),
children=[text("Open Accessibility settings")],
),
el(
"button",
classes=["btn", "secondary"],
handlers=tap(OpenSelfAppInfo),
children=[text("Open App info")],
),
el("button", classes=["btn", "ghost"], handlers=tap(CloseSheet), children=[
text("Close"),
]),
]),
)
}
}
[
el("div", key=3, classes=["sheet-overlay"], handlers=tap(CloseSheet)),
el(
"div",
key=4,
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] {
let s = self.home[self.resizing]
let size = "\{s.cols(self.cols)} × \{s.height()}"
el("div", key=5, classes=["resize-bar"], attrs=[("role", "toolbar")], children=[
el("span", classes=["resize-size"], children=[text(size)]),
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_open() {
out.push(m.view_resize_bar())
}
if m.notice != "" {
out.push(
el("div", key=6, 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 #!/usr/bin/env bash
# Tests the Qt launcher (qt/), builds its APK and publishes it as a Gitea release: # Builds the launcher APK (MoonBit page + Java shell, android/build.sh) and publishes it as a
# build-<versionCode>, holding ultra-launcher.apk and version.json, made a draft first # Gitea release: build-<versionCode>, holding ultra-launcher.apk and version.json, made a
# and published once both files are up, so the latest release never lacks them. # 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). # 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 set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
QT_VERSION=6.8.3 # Minutes since the epoch: always above every earlier build's versionCode (the Qt builds used
NDK=26.1.10909125 # the same scale) and always rising.
# Minutes since the epoch: always above the GitHub builds' run numbers and always rising. export VERSION_CODE=$(( $(date +%s) / 60 ))
VERSION_CODE=$(( $(date +%s) / 60 ))
COMMIT="${GITHUB_SHA:-$(git rev-parse HEAD)}" COMMIT="${GITHUB_SHA:-$(git rev-parse HEAD)}"
echo "== tools" echo "== tools"
apt-get update -qq # In the cluster's android-sdk image the JDK, SDK and common tools are already there; on a bare
# The host Qt tools (moc, qmlimportscanner, qmlcachegen) need glib, GL and friends; # image (the documented fallback, e.g. node:22-bookworm) they are installed below.
# g++ builds the desktop test and nodejs runs the layout test. if ! command -v javac >/dev/null || ! command -v zip >/dev/null || ! command -v curl >/dev/null; then
apt-get install -y -qq --no-install-recommends python3-pip python3-venv ninja-build cmake g++ nodejs unzip curl ca-certificates git \ apt-get update -qq
libglib2.0-0t64 libgl1 libegl1 libopengl0 libgl-dev libglx-dev libopengl-dev libegl-dev libxkbcommon-dev \ apt-get install -y -qq --no-install-recommends openjdk-17-jdk-headless unzip zip curl ca-certificates git >/dev/null
libfontconfig1 libfreetype6 libxkbcommon0 libdbus-1-3 >/dev/null fi
python3 -m venv /opt/aqt && /opt/aqt/bin/pip install -q aqtinstall 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)" SDK="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-/opt/android-sdk}}"
/opt/aqt/bin/aqt install-qt linux android "$QT_VERSION" android_arm64_v8a -O /opt/Qt --autodesktop >/dev/null if [ -f "$SDK/platforms/android-35/android.jar" ] && ls -d "$SDK"/build-tools/35* >/dev/null 2>&1; then
QT_ROOT=/opt/Qt/$QT_VERSION/android_arm64_v8a echo "== Android SDK from the image ($SDK)"
QT_HOST=/opt/Qt/$QT_VERSION/gcc_64 else
echo "== Android SDK fallback (build-tools and the platform jar only)"
echo "== tests (desktop Qt)" SDK=/opt/android-sdk
node qt/tests/layout.test.mjs mkdir -p "$SDK/cmdline-tools"
cmake -S qt -B build-desktop -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$QT_HOST" curl -fsSL -o /tmp/cmdline.zip https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
cmake --build build-desktop unzip -q /tmp/cmdline.zip -d "$SDK/cmdline-tools"
QT_QPA_PLATFORM=offscreen build-desktop/ultrahome_e2e mv "$SDK/cmdline-tools/cmdline-tools" "$SDK/cmdline-tools/latest"
yes | "$SDK/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null || true
echo "== Android SDK + NDK $NDK" "$SDK/cmdline-tools/latest/bin/sdkmanager" --install "build-tools;35.0.0" >/dev/null
export ANDROID_SDK_ROOT=/opt/android-sdk # Only android.jar is needed from the platform: unzipping the whole thing (sdkmanager) is slow.
mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" curl -fsSL -o /tmp/platform.zip https://dl.google.com/android/repository/platform-35_r02.zip
curl -fsSL -o /tmp/cmdline.zip https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip mkdir -p "$SDK/platforms" && unzip -q /tmp/platform.zip 'android-35/android.jar' -d "$SDK/platforms"
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" fi
yes | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null || true export ANDROID_SDK_ROOT="$SDK"
"$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)" echo "== build (versionCode $VERSION_CODE)"
# Signed with the committed key, like every earlier build, so it installs over them. android/build.sh ultra-launcher.apk
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
echo "== release build-$VERSION_CODE" echo "== release build-$VERSION_CODE"
server="${GITHUB_SERVER_URL:-https://git.site.latha.org}" 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") auth=(-H "Authorization: token $token")
tag="build-$VERSION_CODE" tag="build-$VERSION_CODE"
id=$(curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X POST "$api/releases" \ 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"])') | 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=@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 curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X PATCH "$api/releases/$id" -d '{"draft": false}' >/dev/null
echo "published $tag to $server/$repo" 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

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 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
+367
View File
@@ -0,0 +1,367 @@
///|
/// 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, ch~ : Int32 = cell_px) -> Int32 {
let k = (px + row_gap + (ch + row_gap) / 2) / (ch + 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 and the row height `ch`: (x, y, w, h).
pub fn box(
cell : Cell,
col_w : Double,
ch~ : Int32 = cell_px,
) -> (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() * (ch.to_double() + rg),
cell.w.to_double() * col_w + (cell.w - 1).to_double() * cg,
cell.h.to_double() * ch.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,
ch~ : Int32 = cell_px,
) -> (Int32, Int32) {
let c = (x / (col_w + col_gap.to_double()) + 0.5).floor().to_int()
let r = (y / (ch + 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,
ch~ : Int32 = cell_px,
) -> (Int32, Int32)? {
if x < 0.0 || y < 0.0 {
return None
}
let pw = col_w + col_gap.to_double()
let ph = (ch + 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 > ch.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 height `ch` fit in `height` px.
pub fn rows_fit(height : Double, ch~ : Int32 = cell_px) -> Int32 {
let r = ((height + row_gap.to_double()) / (ch + row_gap).to_double())
.floor()
.to_int()
@cmp.maximum(1, r)
}
+172
View File
@@ -0,0 +1,172 @@
///|
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(fn(p) { widget_rows(p) }), [
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)
}
///|
test "fit clamps anchored spans within lo..hi and negative targets" {
// Widget pinned at col 2 of 5 can only grow to hi = 3 columns on the right
assert_eq(fit(500.0, 1, 3, 65.2, 8.0, 64, 0), 3)
// Negative drag past the left/top edge clamps cleanly to 1
assert_eq(fit(-120.0, 1, 4, 65.2, 8.0, 0, 0), 1)
// Expanding a widget unpins slots now overlapped by it
let h = [widget(2, 2, x=1, y=1), app(x=3, y=1), app(x=0, y=0)]
h[0].w = 3
clear_cells(h, 0, 5)
assert_eq((h[1].x, h[1].y, h[2].x, h[2].y), (-1, -1, 0, 0))
}
+4
View File
@@ -0,0 +1,4 @@
import {
"moonbitlang/core/cmp",
"moonbitlang/core/string",
}
+120
View File
@@ -0,0 +1,120 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/launcher/grid"
import {
"moonbitlang/core/debug",
}
// Values
pub fn box(Cell, Double, ch? : Int32) -> (Double, Double, Double, Double)
pub fn cell_at(Double, Double, Double, ch? : Int32) -> (Int32, Int32)
pub fn cell_height(Int32) -> Int32
pub let cell_px : Int32
pub fn cell_under(Double, Double, Double, ch? : Int32) -> (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 css_factor(Int32) -> String
pub fn drawer_columns(Int32, Int32) -> Int32
pub let drawer_icon_px : Int32
pub fn fit(Double, Int32, Int32, Double, Double, Int32, Int32) -> Int32
pub fn home_columns(Int32, Double, Int32) -> Int32
pub let home_icon_px : Int32
pub let min_cols : Int32
pub fn move_slot(Array[Slot], Int32, Int32) -> Unit
pub fn pack(Array[Slot], Int32, Int32, hidden? : (Int32) -> Bool) -> Packed
pub fn parse_scale(String) -> Result[Int32, String]
pub fn pin(Array[Slot], Int32, Int32, Int32, Int32, Int32) -> Unit
pub let row_gap : Int32
pub fn rows_fit(Double, ch? : Int32) -> Int32
pub let scale_default : Int32
pub let scale_large : Int32
pub let scale_max : Int32
pub let scale_medium : Int32
pub let scale_min : Int32
pub let scale_small : Int32
pub let scale_step : Int32
pub fn scale_valid(Int32) -> Bool
pub fn scaled_columns(Int32, Int32, Double, Int32, Int32) -> Int32
pub fn scaled_px(Int32, Int32) -> Int32
pub fn span(Int32, Double, Double) -> Double
pub fn widget_cols(Int32, Double, Int32) -> Int32
pub fn widget_rows(Int32, ch? : 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
+142
View File
@@ -0,0 +1,142 @@
///|
/// The icon size setting as plain functions: the allowed range, parsing a stored or
/// slider value, and how icon size, row height and column count follow from it.
/// The size is a whole percent of today's size (`scale_default` = 100: no change).
///|
pub let scale_min : Int32 = 70
///|
pub let scale_max : Int32 = 160
///|
pub let scale_default : Int32 = 100
///|
/// Slider step in percent.
pub let scale_step : Int32 = 5
///|
/// The presets: Small, Medium (today's size), Large.
pub let scale_small : Int32 = 80
///|
pub let scale_medium : Int32 = 100
///|
pub let scale_large : Int32 = 130
///|
/// The home icon at 100%, in px (`.slots .icon`).
pub let home_icon_px : Int32 = 40
///|
/// The drawer icon at 100%, in px (`.icon`).
pub let drawer_icon_px : Int32 = 52
///|
/// Fewest columns either grid is reduced to, however large the icons.
pub let min_cols : Int32 = 3
///|
/// A size is a valid setting: in range and on the step.
pub fn scale_valid(pct : Int32) -> Bool {
pct >= scale_min && pct <= scale_max && pct % scale_step == 0
}
///|
/// Parse a stored or slider value (decimal whole percent, nothing else). The error says
/// what was wrong and what is allowed; callers show and log it.
pub fn parse_scale(text : String) -> Result[Int32, String] {
let t = text.trim().to_owned()
let n = @string.parse_int(t) catch {
_ => return Err("icon size \"\{text}\" is not a whole number")
}
if scale_valid(n) {
Ok(n)
} else {
Err(
"icon size \{n} is outside \{scale_min}..\{scale_max} in steps of \{scale_step}",
)
}
}
///|
/// `base` px at `pct` percent, rounded to a whole px, at least 1.
pub fn scaled_px(base : Int32, pct : Int32) -> Int32 {
@cmp.maximum(1, (base * pct + 50) / 100)
}
///|
/// Height of a home row at `pct`.
pub fn cell_height(pct : Int32) -> Int32 {
scaled_px(cell_px, pct)
}
///|
/// The percent as a CSS number (`1`, `1.25`, `0.8`), for the `--s` custom property.
pub fn css_factor(pct : Int32) -> String {
let whole = pct / 100
let frac = pct % 100
if frac == 0 {
whole.to_string()
} else if frac < 10 {
"\{whole}.0\{frac}"
} else if frac % 10 == 0 {
"\{whole}.\{frac / 10}"
} else {
"\{whole}.\{frac}"
}
}
///|
/// Columns of a grid `avail` px wide whose icons are `icon` px: `base` columns at 100%,
/// `base * 100 / pct` (rounded) at `pct`, no fewer than `min_cols` and then never so
/// many that a column (`gap` px apart) is narrower than its icon.
pub fn scaled_columns(
base : Int32,
pct : Int32,
avail : Double,
gap : Int32,
icon : Int32,
) -> Int32 {
let mut c = @cmp.maximum(min_cols, (base * 100 + pct / 2) / pct)
while c > 1 && column_width_in(avail, c, gap) < icon.to_double() {
c -= 1
}
c
}
///|
fn column_width_in(avail : Double, cols : Int32, gap : Int32) -> Double {
(avail - (cols - 1).to_double() * gap.to_double()) / cols.to_double()
}
///|
/// Home grid columns for a viewport width, the width of the grid and the size.
pub fn home_columns(vw : Int32, grid_w : Double, pct : Int32) -> Int32 {
scaled_columns(
columns_for(vw),
pct,
grid_w,
col_gap,
scaled_px(home_icon_px, pct),
)
}
///|
/// Drawer columns (4 below 480px, else 5, at 100%); its list is the viewport less 16px
/// padding each side, with 8px between columns.
pub fn drawer_columns(vw : Int32, pct : Int32) -> Int32 {
scaled_columns(
if vw >= 480 {
5
} else {
4
},
pct,
(vw - 32).to_double(),
8,
scaled_px(drawer_icon_px, pct),
)
}
+136
View File
@@ -0,0 +1,136 @@
///|
test "the default size is today's size" {
assert_eq(scale_default, 100)
assert_eq(scale_medium, scale_default)
assert_eq(cell_height(scale_default), cell_px)
assert_eq(scaled_px(home_icon_px, scale_default), 40)
assert_eq(scaled_px(drawer_icon_px, scale_default), 52)
// the column counts the app had before the setting existed
assert_eq(home_columns(390, 358.0, 100), columns_for(390))
assert_eq(home_columns(600, 528.0, 100), columns_for(600))
assert_eq(drawer_columns(390, 100), 4)
assert_eq(drawer_columns(600, 100), 5)
}
///|
test "presets and range are valid settings" {
for p in [scale_small, scale_medium, scale_large, scale_min, scale_max] {
assert_true(scale_valid(p))
}
assert_true(scale_min < scale_default && scale_default < scale_max)
}
///|
test "parse_scale accepts steps in range" {
assert_eq(parse_scale("100"), Ok(100))
assert_eq(parse_scale(" 85 "), Ok(85))
assert_eq(parse_scale("70"), Ok(70))
assert_eq(parse_scale("160"), Ok(160))
}
///|
test "parse_scale rejects corrupt values with a reason" {
assert_eq(parse_scale("abc"), Err("icon size \"abc\" is not a whole number"))
assert_eq(parse_scale(""), Err("icon size \"\" is not a whole number"))
assert_eq(parse_scale("1.5"), Err("icon size \"1.5\" is not a whole number"))
assert_eq(
parse_scale("65"),
Err("icon size 65 is outside 70..160 in steps of 5"),
)
assert_eq(
parse_scale("500"),
Err("icon size 500 is outside 70..160 in steps of 5"),
)
assert_eq(
parse_scale("-10"),
Err("icon size -10 is outside 70..160 in steps of 5"),
)
// in range but off the step
assert_eq(
parse_scale("102"),
Err("icon size 102 is outside 70..160 in steps of 5"),
)
}
///|
test "sizes scale together" {
assert_eq(scaled_px(home_icon_px, 150), 60)
assert_eq(scaled_px(home_icon_px, 70), 28)
assert_eq(cell_height(150), 96)
assert_eq(cell_height(70), 45)
assert_eq(cell_height(scale_min) < cell_px, true)
assert_eq(scaled_px(1, 70), 1) // never below a pixel
}
///|
test "css_factor" {
assert_eq(css_factor(100), "1")
assert_eq(css_factor(130), "1.3")
assert_eq(css_factor(80), "0.8")
assert_eq(css_factor(105), "1.05")
assert_eq(css_factor(160), "1.6")
assert_eq(css_factor(70), "0.7")
}
///|
test "larger icons mean fewer columns, smaller mean more" {
assert_eq(home_columns(390, 358.0, 70), 7)
assert_eq(home_columns(390, 358.0, 130), 4)
assert_eq(home_columns(390, 358.0, 160), 3)
assert_eq(drawer_columns(390, 70), 6)
assert_eq(drawer_columns(390, 160), 3)
}
///|
test "columns never go below min_cols while icons fit" {
for pct in 70..<=160 {
if pct % scale_step == 0 {
assert_true(home_columns(390, 358.0, pct) >= min_cols)
assert_true(drawer_columns(390, pct) >= min_cols)
}
}
}
///|
test "icons never overlap or clip: a column is at least as wide as its icon" {
// every size, on phones of several widths (grid is the viewport less 32px, max 528)
for vw in [320, 360, 390, 412, 480, 600, 800] {
let grid_w = ((if vw > 560 { 560 } else { vw }) - 32).to_double()
for pct in 70..<=160 {
if pct % scale_step != 0 {
continue
}
let c = home_columns(vw, grid_w, pct)
assert_true(
column_width(grid_w, c) >= scaled_px(home_icon_px, pct).to_double(),
)
let d = drawer_columns(vw, pct)
let dw = (vw - 32).to_double()
assert_true(
(dw - (d - 1).to_double() * 8.0) / d.to_double() >=
scaled_px(drawer_icon_px, pct).to_double(),
)
}
}
}
///|
test "a very narrow grid sheds columns to keep the icons whole" {
// 160px of grid at 160%: icons are 64px, so only two columns fit with the 8px gap
assert_eq(scaled_columns(5, 160, 160.0, 8, 64), 2)
assert_eq(scaled_columns(5, 100, 400.0, 8, 40), 5)
}
///|
test "row height parameter threads through the cell maths" {
let c : Cell = { col: 1, row: 2, w: 2, h: 2, }
let (x, y, w, h) = box(c, 60.0, ch=96)
assert_eq((x, y, w, h), (68.0, 208.0, 128.0, 200.0))
assert_eq(box(c, 60.0), box(c, 60.0, ch=cell_px))
assert_eq(rows_fit(500.0, ch=96), 4)
assert_eq(rows_fit(500.0), 7)
assert_eq(widget_rows(200, ch=96), 2)
assert_eq(cell_at(80.0, 220.0, 70.0, ch=96), (1, 2))
assert_eq(cell_under(80.0, 220.0, 70.0, ch=96), Some((1, 2)))
assert_eq(cell_under(80.0, 100.0, 70.0, ch=96), None) // in the row gap
}
+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>
File renamed without changes.
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" />
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more