Rewrite the launcher in MoonBit (old code moves to legacy/) #1
No files matched your search
@@ -1,26 +1,57 @@
|
||||
name: Launcher
|
||||
|
||||
# The MoonBit launcher at the repo root: tests (moon test, a browser e2e of the page), then
|
||||
# on every push to main an APK (android/build.sh) published as a Gitea release, which the
|
||||
# installed app updates itself from. The previous implementations live in legacy/ and have
|
||||
# their own manual workflow (legacy.yml).
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
apk:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
container: eclipse-temurin:17-jdk-noble
|
||||
# Node comes from the image, not actions/setup-node: its download stalls on this
|
||||
# runner and holds the cluster's only runner slot (see identicons-web's workflow).
|
||||
container:
|
||||
image: node:22-bookworm
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Checkout
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install MoonBit
|
||||
run: |
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends git ca-certificates >/dev/null
|
||||
git init -q
|
||||
git -c http.extraHeader="Authorization: Basic $(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0)" \
|
||||
fetch -q --depth 1 "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" "${GITHUB_SHA}"
|
||||
git checkout -q --detach FETCH_HEAD
|
||||
- name: Test, build and release the Qt APK
|
||||
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
|
||||
echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Check and test
|
||||
run: |
|
||||
moon update
|
||||
moon check --target js
|
||||
moon test --target js
|
||||
moon test --target wasm-gc
|
||||
|
||||
- name: Build the page and run the browser test
|
||||
run: |
|
||||
scripts/build-web.sh --demo
|
||||
mkdir -p /tmp/e2e && cd /tmp/e2e && npm init -y >/dev/null
|
||||
npm i --no-audit --no-fund playwright@1.65.1
|
||||
npx playwright install --with-deps chromium
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
PLAYWRIGHT=/tmp/e2e/node_modules/playwright node tests/e2e.cjs
|
||||
|
||||
apk:
|
||||
needs: test
|
||||
if: github.event_name != 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: node:22-bookworm
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build and release the APK
|
||||
env:
|
||||
GITEA_TOKEN: ${{ github.token }}
|
||||
run: bash ci/gitea-apk.sh
|
||||
@@ -7,3 +7,4 @@ node_modules/
|
||||
/android/build/
|
||||
*.apk
|
||||
__pycache__/
|
||||
*.idsig
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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>
|
||||
Executable
+49
@@ -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"
|
||||
Binary file not shown.
@@ -0,0 +1,960 @@
|
||||
package dev.ultra.launcher;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.appwidget.AppWidgetHost;
|
||||
import android.appwidget.AppWidgetHostView;
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.appwidget.AppWidgetProviderInfo;
|
||||
import android.content.Context;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.LauncherActivityInfo;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Insets;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
import android.provider.Settings;
|
||||
import android.util.Base64;
|
||||
import android.util.Log;
|
||||
import android.util.SizeF;
|
||||
import android.view.HapticFeedbackConstants;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
import android.view.Window;
|
||||
import android.view.WindowInsets;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.webkit.JavascriptInterface;
|
||||
import android.webkit.RenderProcessGoneDetail;
|
||||
import android.webkit.WebResourceRequest;
|
||||
import android.webkit.WebResourceResponse;
|
||||
import android.webkit.WebSettings;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.Collator;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* The home screen activity: a thin shell around the page that MoonBit builds (web/, in
|
||||
* assets). It holds a transparent WebView over the wallpaper and, in a layer above it, the
|
||||
* real AppWidgetHostViews, and does what only Android code can:
|
||||
*
|
||||
* apps.json {"apps": [{"label", "component", "icon", "system"}]}, every launchable activity
|
||||
* icon?c=COMP the activity's icon as a PNG
|
||||
* widgets.json {"widgets": [{"label", "app", "provider", "icon", "h"}]}, every widget provider
|
||||
* wicon?p=PROV the provider's icon as a PNG
|
||||
*
|
||||
* and exposes window.Android (launch, appInfo, uninstall, addWidget, removeWidget,
|
||||
* placeWidgets, coverWidgets, widgetLimits, excludeGestures, loadIcons, haptic, keyboard,
|
||||
* openSettings, pickWallpaper, openRecents, httpGet, installApk, installedVersion,
|
||||
* declinedVersion) for the page's host effects. No decisions are made here: the page
|
||||
* (core/ and app/ in MoonBit) decides, this class carries them out.
|
||||
*
|
||||
* Widgets are real AppWidgetHostViews in a layer above the WebView. The page reports where
|
||||
* its live widget slots are (placeWidgets), and this class moves the views there. Package
|
||||
* changes, the home button, back, a new widget and a long press on a widget reach
|
||||
* the page as window.launcher.reload() / home() / back() / widgetAdded(id) /
|
||||
* widgetMenu(id) / widgetGrab(id) / widgetDrag(x, y) / widgetDrop(moved).
|
||||
*/
|
||||
public class HomeActivity extends Activity {
|
||||
static final String HOST = "appassets.androidplatform.net";
|
||||
static final String ORIGIN = "https://" + HOST + "/";
|
||||
static final int ICON_DP = 56;
|
||||
static final int HOST_ID = 0x0171;
|
||||
static final int REQ_BIND = 1, REQ_CONFIGURE = 2;
|
||||
|
||||
private WebView web;
|
||||
private CoverLayer widgetLayer;
|
||||
private long coverRequest; // the latest coverWidgets, so a stale uncover is dropped
|
||||
private AppWidgetManager widgets;
|
||||
private AppWidgetHost widgetHost;
|
||||
private final Map<Integer, AppWidgetHostView> widgetViews = new HashMap<>();
|
||||
private final Map<Integer, Long> widgetSizes = new HashMap<>(); // last size told to each widget
|
||||
private int pendingWidget = -1;
|
||||
private int editingWidget = -1; // showing resize handles: a press on it moves it
|
||||
private boolean ready;
|
||||
private int insetTop, insetBottom; // CSS px
|
||||
private LauncherApps launcher;
|
||||
private final UserHandle user = Process.myUserHandle();
|
||||
private final Map<String, byte[]> icons = new ConcurrentHashMap<>();
|
||||
private final Map<String, LauncherActivityInfo> activities = new ConcurrentHashMap<>();
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private final ExecutorService iconThread = Executors.newSingleThreadExecutor();
|
||||
|
||||
private final LauncherApps.Callback packages = new LauncherApps.Callback() {
|
||||
@Override public void onPackageRemoved(String pkg, UserHandle u) { reload(); }
|
||||
@Override public void onPackageAdded(String pkg, UserHandle u) { reload(); }
|
||||
@Override public void onPackageChanged(String pkg, UserHandle u) { reload(); }
|
||||
@Override public void onPackagesAvailable(String[] pkgs, UserHandle u, boolean replacing) { reload(); }
|
||||
@Override public void onPackagesUnavailable(String[] pkgs, UserHandle u, boolean replacing) { reload(); }
|
||||
};
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
launcher = getSystemService(LauncherApps.class);
|
||||
launcher.registerCallback(packages, main);
|
||||
widgets = AppWidgetManager.getInstance(this);
|
||||
widgetHost = new Host(this);
|
||||
|
||||
Window w = getWindow();
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
w.setDecorFitsSystemWindows(false);
|
||||
} else {
|
||||
w.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
|
||||
}
|
||||
createWebView();
|
||||
}
|
||||
|
||||
private void createWebView() {
|
||||
ready = false;
|
||||
web = new WebView(this);
|
||||
web.setBackgroundColor(Color.TRANSPARENT);
|
||||
// Long presses are the page's (on_longpress); no native text selection.
|
||||
web.setOnLongClickListener(v -> true);
|
||||
web.setHapticFeedbackEnabled(false);
|
||||
web.setVerticalScrollBarEnabled(false);
|
||||
web.setOverScrollMode(View.OVER_SCROLL_NEVER);
|
||||
WebSettings s = web.getSettings();
|
||||
s.setJavaScriptEnabled(true);
|
||||
s.setDomStorageEnabled(true); // the dock is saved in localStorage
|
||||
s.setAllowFileAccess(false);
|
||||
s.setAllowContentAccess(false);
|
||||
web.addJavascriptInterface(new Bridge(), "Android");
|
||||
web.setWebViewClient(new Client());
|
||||
web.setOnApplyWindowInsetsListener((v, insets) -> {
|
||||
int top, bottom;
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
Insets bars = insets.getInsets(WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout());
|
||||
Insets ime = insets.getInsets(WindowInsets.Type.ime());
|
||||
top = bars.top;
|
||||
bottom = Math.max(bars.bottom, ime.bottom);
|
||||
} else {
|
||||
top = insets.getSystemWindowInsetTop();
|
||||
bottom = insets.getSystemWindowInsetBottom();
|
||||
}
|
||||
float d = getResources().getDisplayMetrics().density;
|
||||
insetTop = Math.round(top / d);
|
||||
insetBottom = Math.round(bottom / d);
|
||||
pushInsets();
|
||||
return insets;
|
||||
});
|
||||
widgetViews.clear();
|
||||
widgetSizes.clear();
|
||||
widgetLayer = new CoverLayer(this);
|
||||
FrameLayout root = new FrameLayout(this);
|
||||
root.addView(web);
|
||||
root.addView(widgetLayer);
|
||||
setContentView(root);
|
||||
web.loadUrl(ORIGIN + "index.html");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
widgetHost.startListening();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
widgetHost.stopListening();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
launcher.unregisterCallback(packages);
|
||||
iconThread.shutdownNow();
|
||||
web.destroy();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
// The home button while we are already in front.
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
js("home()");
|
||||
}
|
||||
|
||||
// A home screen has nowhere to go back to; let the page clear its search or edit mode.
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public void onBackPressed() {
|
||||
js("back()");
|
||||
}
|
||||
|
||||
private void js(String call) {
|
||||
if (ready) web.evaluateJavascript("window.launcher && launcher." + call, null);
|
||||
}
|
||||
|
||||
private void pushInsets() {
|
||||
if (!ready) return;
|
||||
web.evaluateJavascript("(s => { s.setProperty('--inset-top', '" + insetTop + "px');"
|
||||
+ " s.setProperty('--inset-bottom', '" + insetBottom + "px'); })"
|
||||
+ "(document.documentElement.style); window.launcher && launcher.place()", null);
|
||||
}
|
||||
|
||||
private void reload() {
|
||||
icons.clear();
|
||||
js("resetIcons()");
|
||||
js("reload()");
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the icons for these keys ("icon?c=COMP" or "wicon?p=PROV", as apps.json and
|
||||
* widgets.json give them) on the icon thread, and hand them to the page as data: URIs,
|
||||
* a few at a time, through ultraIcons({key: uri}). A key that can't be drawn gets "".
|
||||
*/
|
||||
private void loadIcons(String json) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
try {
|
||||
JSONArray a = new JSONArray(json);
|
||||
for (int i = 0; i < a.length(); i++) keys.add(a.getString(i));
|
||||
} catch (JSONException e) {
|
||||
return;
|
||||
}
|
||||
iconThread.execute(() -> {
|
||||
JSONObject batch = new JSONObject();
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
String k = keys.get(i);
|
||||
byte[] png = null;
|
||||
if (k.startsWith("icon?c=")) png = iconPng(Uri.decode(k.substring(7)));
|
||||
else if (k.startsWith("wicon?p=")) png = widgetIconPng(Uri.decode(k.substring(8)));
|
||||
try {
|
||||
batch.put(k, png == null ? ""
|
||||
: "data:image/png;base64," + Base64.encodeToString(png, Base64.NO_WRAP));
|
||||
} catch (JSONException e) {
|
||||
continue;
|
||||
}
|
||||
if (batch.length() == 8 || i == keys.size() - 1) {
|
||||
String call = "window.launcher && launcher.icons(" + batch + ")";
|
||||
main.post(() -> web.evaluateJavascript(call, null));
|
||||
batch = new JSONObject();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ apps
|
||||
|
||||
private String appsJson() throws JSONException {
|
||||
List<LauncherActivityInfo> list = new ArrayList<>(launcher.getActivityList(null, user));
|
||||
Map<LauncherActivityInfo, String> labels = new HashMap<>();
|
||||
for (LauncherActivityInfo a : list) labels.put(a, String.valueOf(a.getLabel()));
|
||||
Collator by = Collator.getInstance();
|
||||
list.sort((a, b) -> by.compare(labels.get(a), labels.get(b)));
|
||||
JSONArray apps = new JSONArray();
|
||||
for (LauncherActivityInfo a : list) {
|
||||
ComponentName cn = a.getComponentName();
|
||||
if (cn.getPackageName().equals(getPackageName())) continue;
|
||||
String c = cn.flattenToShortString();
|
||||
activities.put(c, a);
|
||||
JSONObject o = new JSONObject()
|
||||
.put("label", labels.get(a))
|
||||
.put("component", c)
|
||||
.put("icon", "icon?c=" + Uri.encode(c));
|
||||
// System apps can't be uninstalled, so the drawer offers no Uninstall for them.
|
||||
if ((a.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) != 0) o.put("system", true);
|
||||
apps.put(o);
|
||||
}
|
||||
return new JSONObject().put("apps", apps).toString();
|
||||
}
|
||||
|
||||
// Icons are drawn one at a time: the WebView asks for a screenful at once on several
|
||||
// threads, and some icon drawables don't survive being loaded and drawn concurrently.
|
||||
private final Object iconLock = new Object();
|
||||
|
||||
private byte[] iconPng(String c) {
|
||||
byte[] png = icons.get(c);
|
||||
if (png != null) return png;
|
||||
synchronized (iconLock) {
|
||||
png = icons.get(c);
|
||||
if (png != null) return png;
|
||||
try {
|
||||
png = drawIcon(c);
|
||||
} catch (RuntimeException | OutOfMemoryError e) {
|
||||
Log.w("ultra", "icon for " + c, e);
|
||||
return null;
|
||||
}
|
||||
if (png != null) icons.put(c, png);
|
||||
else Log.w("ultra", "no icon for " + c);
|
||||
return png;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] drawIcon(String c) {
|
||||
ComponentName cn = c == null ? null : ComponentName.unflattenFromString(c);
|
||||
if (cn == null) return null;
|
||||
// Prefer the LauncherActivityInfo that apps.json was built from; resolve only if it
|
||||
// isn't there (e.g. an icon asked for before the list was built).
|
||||
LauncherActivityInfo info = activities.get(c);
|
||||
if (info == null) {
|
||||
info = launcher.resolveActivity(
|
||||
new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(cn), user);
|
||||
}
|
||||
if (info == null) {
|
||||
Log.w("ultra", "no launchable activity for " + c);
|
||||
return null;
|
||||
}
|
||||
int dpi = getResources().getDisplayMetrics().densityDpi;
|
||||
Drawable d = info.getIcon(dpi);
|
||||
if (d == null) d = getPackageManager().getDefaultActivityIcon();
|
||||
return toPng(d, Math.round(ICON_DP * dpi / 160f));
|
||||
}
|
||||
|
||||
private static byte[] toPng(Drawable d, int size) {
|
||||
d = d.mutate(); // setBounds on a drawable shared with other callers would move theirs
|
||||
Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
|
||||
d.setBounds(0, 0, size, size);
|
||||
d.draw(new Canvas(bmp));
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
|
||||
bmp.recycle();
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ widgets
|
||||
|
||||
private String widgetsJson() throws JSONException {
|
||||
List<AppWidgetProviderInfo> list = new ArrayList<>(widgets.getInstalledProvidersForProfile(user));
|
||||
Map<AppWidgetProviderInfo, String> labels = new HashMap<>();
|
||||
for (AppWidgetProviderInfo w : list) labels.put(w, w.loadLabel(getPackageManager()));
|
||||
Collator by = Collator.getInstance();
|
||||
list.sort((a, b) -> by.compare(labels.get(a), labels.get(b)));
|
||||
float d = getResources().getDisplayMetrics().density;
|
||||
JSONArray out = new JSONArray();
|
||||
for (AppWidgetProviderInfo w : list) {
|
||||
String p = w.provider.flattenToShortString();
|
||||
int h = Math.round(w.minHeight / d);
|
||||
out.put(new JSONObject()
|
||||
.put("label", labels.get(w))
|
||||
.put("app", appLabel(w.provider.getPackageName()))
|
||||
.put("provider", p)
|
||||
.put("icon", "wicon?p=" + Uri.encode(p))
|
||||
.put("h", Math.max(80, Math.min(h + 16, 420))));
|
||||
}
|
||||
return new JSONObject().put("widgets", out).toString();
|
||||
}
|
||||
|
||||
/** The label of the app a widget comes from, for the picker's search. */
|
||||
private String appLabel(String pkg) {
|
||||
try {
|
||||
PackageManager pm = getPackageManager();
|
||||
return pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString();
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private AppWidgetProviderInfo provider(String p) {
|
||||
ComponentName cn = p == null ? null : ComponentName.unflattenFromString(p);
|
||||
if (cn == null) return null;
|
||||
for (AppWidgetProviderInfo w : widgets.getInstalledProvidersForProfile(user)) {
|
||||
if (w.provider.equals(cn)) return w;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private byte[] widgetIconPng(String p) {
|
||||
String k = "w:" + p;
|
||||
byte[] png = icons.get(k);
|
||||
if (png != null) return png;
|
||||
synchronized (iconLock) {
|
||||
AppWidgetProviderInfo w = provider(p);
|
||||
if (w == null) return null;
|
||||
int dpi = getResources().getDisplayMetrics().densityDpi;
|
||||
Drawable d = null;
|
||||
try {
|
||||
d = w.loadIcon(this, dpi);
|
||||
} catch (RuntimeException e) {
|
||||
Log.w("ultra", "widget icon for " + p, e);
|
||||
}
|
||||
if (d == null) {
|
||||
// Fall back to the app's own icon, then to the system default.
|
||||
try {
|
||||
d = getPackageManager().getApplicationIcon(w.provider.getPackageName());
|
||||
} catch (android.content.pm.PackageManager.NameNotFoundException | RuntimeException e) {
|
||||
d = getPackageManager().getDefaultActivityIcon();
|
||||
}
|
||||
}
|
||||
try {
|
||||
png = toPng(d, Math.round(ICON_DP * dpi / 160f));
|
||||
} catch (RuntimeException | OutOfMemoryError e) {
|
||||
Log.w("ultra", "drawing widget icon for " + p, e);
|
||||
return null;
|
||||
}
|
||||
icons.put(k, png);
|
||||
return png;
|
||||
}
|
||||
}
|
||||
|
||||
/** Bind a widget for provider p, then configure it if it asks to be; see onActivityResult. */
|
||||
private void addWidget(String p) {
|
||||
AppWidgetProviderInfo w = provider(p);
|
||||
if (w == null) return;
|
||||
int id = widgetHost.allocateAppWidgetId();
|
||||
pendingWidget = id;
|
||||
if (widgets.bindAppWidgetIdIfAllowed(id, user, w.provider, null)) {
|
||||
configureWidget(id);
|
||||
} else {
|
||||
Intent i = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, w.provider)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, user);
|
||||
try {
|
||||
startActivityForResult(i, REQ_BIND);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
dropPending();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void configureWidget(int id) {
|
||||
AppWidgetProviderInfo w = widgets.getAppWidgetInfo(id);
|
||||
if (w != null && w.configure != null) {
|
||||
try {
|
||||
widgetHost.startAppWidgetConfigureActivityForResult(this, id, 0, REQ_CONFIGURE, null);
|
||||
return;
|
||||
} catch (ActivityNotFoundException | SecurityException e) {
|
||||
// Fall through: add it unconfigured, as most launchers do.
|
||||
}
|
||||
}
|
||||
widgetReady(id);
|
||||
}
|
||||
|
||||
private void widgetReady(int id) {
|
||||
pendingWidget = -1;
|
||||
js("widgetAdded(" + id + ")");
|
||||
}
|
||||
|
||||
private void dropPending() {
|
||||
if (pendingWidget != -1) widgetHost.deleteAppWidgetId(pendingWidget);
|
||||
pendingWidget = -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActivityResult(int req, int result, Intent data) {
|
||||
super.onActivityResult(req, result, data);
|
||||
if (pendingWidget == -1) return;
|
||||
if (result != RESULT_OK) {
|
||||
dropPending();
|
||||
} else if (req == REQ_BIND) {
|
||||
configureWidget(pendingWidget);
|
||||
} else if (req == REQ_CONFIGURE) {
|
||||
widgetReady(pendingWidget);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeWidget(int id) {
|
||||
AppWidgetHostView v = widgetViews.remove(id);
|
||||
if (v != null) widgetLayer.removeView(v);
|
||||
widgetSizes.remove(id);
|
||||
widgetHost.deleteAppWidgetId(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* A placed widget's natural width and how far it may be resized, in CSS px: {"w",
|
||||
* "minW", "minH", "maxW", "maxH" (0 = no limit), "h", "v" (whether it resizes
|
||||
* horizontally / vertically)}.
|
||||
*/
|
||||
private String widgetLimits(int id) {
|
||||
AppWidgetProviderInfo w = widgets.getAppWidgetInfo(id);
|
||||
JSONObject o = new JSONObject();
|
||||
try {
|
||||
if (w == null) return o.toString();
|
||||
float d = getResources().getDisplayMetrics().density;
|
||||
// A minResize larger than the min size (or unset) means the min size applies.
|
||||
int minW = w.minResizeWidth > 0 && w.minResizeWidth < w.minWidth ? w.minResizeWidth : w.minWidth;
|
||||
int minH = w.minResizeHeight > 0 && w.minResizeHeight < w.minHeight ? w.minResizeHeight : w.minHeight;
|
||||
int maxW = 0, maxH = 0;
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
maxW = w.maxResizeWidth;
|
||||
maxH = w.maxResizeHeight;
|
||||
}
|
||||
o.put("w", Math.round(w.minWidth / d))
|
||||
.put("minW", Math.round(minW / d)).put("minH", Math.round(minH / d))
|
||||
.put("maxW", Math.round(maxW / d)).put("maxH", Math.round(maxH / d))
|
||||
.put("h", (w.resizeMode & AppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0)
|
||||
.put("v", (w.resizeMode & AppWidgetProviderInfo.RESIZE_VERTICAL) != 0);
|
||||
} catch (JSONException e) {
|
||||
Log.w("ultra", "widget limits", e);
|
||||
}
|
||||
return o.toString();
|
||||
}
|
||||
|
||||
/** Keep the system's edge gestures off these page rects ([[x, y, w, h], ...] in CSS px). */
|
||||
private void excludeGestures(String json) {
|
||||
if (Build.VERSION.SDK_INT < 29) return;
|
||||
float d = getResources().getDisplayMetrics().density;
|
||||
List<Rect> rects = new ArrayList<>();
|
||||
try {
|
||||
JSONArray a = new JSONArray(json);
|
||||
for (int i = 0; i < a.length(); i++) {
|
||||
JSONArray r = a.getJSONArray(i);
|
||||
int x = Math.round(r.getInt(0) * d), y = Math.round(r.getInt(1) * d);
|
||||
rects.add(new Rect(x, y, x + Math.round(r.getInt(2) * d), y + Math.round(r.getInt(3) * d)));
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
return;
|
||||
}
|
||||
web.setSystemGestureExclusionRects(rects);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lay widget views over the page's live slots: [[id, x, y, w, h, editing], ...] in CSS
|
||||
* px, where editing is 1 for the one showing resize handles.
|
||||
*/
|
||||
private void placeWidgets(String json) {
|
||||
float d = getResources().getDisplayMetrics().density;
|
||||
Map<Integer, int[]> want = new HashMap<>();
|
||||
int editing = -1;
|
||||
try {
|
||||
JSONArray a = new JSONArray(json);
|
||||
for (int i = 0; i < a.length(); i++) {
|
||||
JSONArray r = a.getJSONArray(i);
|
||||
if (r.optInt(5) == 1) editing = r.getInt(0);
|
||||
want.put(r.getInt(0), new int[] {
|
||||
Math.round(r.getInt(1) * d), Math.round(r.getInt(2) * d),
|
||||
Math.round(r.getInt(3) * d), Math.round(r.getInt(4) * d),
|
||||
r.getInt(3), r.getInt(4)});
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
return;
|
||||
}
|
||||
editingWidget = editing;
|
||||
for (Map.Entry<Integer, AppWidgetHostView> e : widgetViews.entrySet()) {
|
||||
if (!want.containsKey(e.getKey())) e.getValue().setVisibility(View.GONE);
|
||||
}
|
||||
for (Map.Entry<Integer, int[]> e : want.entrySet()) {
|
||||
int id = e.getKey();
|
||||
int[] r = e.getValue();
|
||||
AppWidgetHostView v = widgetViews.get(id);
|
||||
if (v == null) {
|
||||
AppWidgetProviderInfo info = widgets.getAppWidgetInfo(id);
|
||||
if (info == null) continue; // the provider was uninstalled
|
||||
v = widgetHost.createView(this, id, info);
|
||||
widgetViews.put(id, v);
|
||||
widgetLayer.addView(v);
|
||||
}
|
||||
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(r[2], r[3]);
|
||||
lp.leftMargin = r[0];
|
||||
lp.topMargin = r[1];
|
||||
v.setLayoutParams(lp);
|
||||
v.setVisibility(View.VISIBLE);
|
||||
// Scrolling moves a widget without resizing it; only tell it about new sizes.
|
||||
long size = ((long) r[4] << 32) | r[5];
|
||||
Long was = widgetSizes.put(id, size);
|
||||
if (was == null || was != size) {
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
List<SizeF> sizes = new ArrayList<>();
|
||||
sizes.add(new SizeF(r[4], r[5]));
|
||||
v.updateAppWidgetSize(new Bundle(), sizes);
|
||||
} else {
|
||||
v.updateAppWidgetSize(new Bundle(), r[4], r[5], r[4], r[5]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Widget views that report a long press to the page instead of to the widget. The press
|
||||
* lifts the widget's slot; the moves and the release that follow go to the page as
|
||||
* widgetDrag(x, y) in CSS px and widgetDrop(moved), so it can be dragged to a new place.
|
||||
* A widget showing resize handles is picked up by any press on it (widgetGrab(id)).
|
||||
*/
|
||||
static final class Host extends AppWidgetHost {
|
||||
Host(HomeActivity a) { super(a, HOST_ID); }
|
||||
|
||||
@Override
|
||||
protected AppWidgetHostView onCreateView(Context context, int id, AppWidgetProviderInfo info) {
|
||||
return new WidgetView((HomeActivity) context, id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds the widget views. The app drawer slides down over the page, so the widgets
|
||||
* must be hidden above its edge: cover(top) clips them (and their touches) above top
|
||||
* px, -1 hides them all, 0 shows them all.
|
||||
*/
|
||||
static final class CoverLayer extends FrameLayout {
|
||||
private int top;
|
||||
|
||||
CoverLayer(Context c) { super(c); }
|
||||
|
||||
void cover(int y) {
|
||||
if (y == top) return;
|
||||
top = y;
|
||||
setVisibility(y < 0 ? View.INVISIBLE : View.VISIBLE);
|
||||
setClipBounds(y > 0 ? new Rect(0, y, Math.max(getWidth(), 1), Math.max(getHeight(), y + 1)) : null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean dispatchTouchEvent(MotionEvent ev) {
|
||||
if (top != 0 && ev.getActionMasked() == MotionEvent.ACTION_DOWN && (top < 0 || ev.getY() < top)) return false;
|
||||
return super.dispatchTouchEvent(ev);
|
||||
}
|
||||
}
|
||||
|
||||
static final class WidgetView extends AppWidgetHostView {
|
||||
private final HomeActivity home;
|
||||
private final int id;
|
||||
private float downX, downY;
|
||||
private boolean longPressed, moved;
|
||||
private final int[] webAt = new int[2];
|
||||
private final Runnable fire = new Runnable() {
|
||||
@Override public void run() {
|
||||
longPressed = true;
|
||||
moved = false;
|
||||
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
|
||||
setAlpha(.85f);
|
||||
home.js("widgetMenu(" + id + ")");
|
||||
}
|
||||
};
|
||||
|
||||
WidgetView(HomeActivity home, int id) {
|
||||
super(home);
|
||||
this.home = home;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* No inset: AppWidgetHostView pads older widgets by getDefaultPaddingForWidget
|
||||
* (about 8dp a side) whenever it binds one, which left a margin inside the slot.
|
||||
*/
|
||||
@Override
|
||||
public void setPadding(int left, int top, int right, int bottom) {
|
||||
super.setPadding(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onInterceptTouchEvent(MotionEvent e) {
|
||||
switch (e.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
longPressed = false;
|
||||
downX = e.getX();
|
||||
downY = e.getY();
|
||||
if (home.editingWidget == id) {
|
||||
// Being resized: the press moves it, without a long press first.
|
||||
longPressed = true;
|
||||
moved = false;
|
||||
setAlpha(.85f);
|
||||
home.js("widgetGrab(" + id + ")");
|
||||
return true;
|
||||
}
|
||||
postDelayed(fire, ViewConfiguration.getLongPressTimeout());
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
if (Math.hypot(e.getX() - downX, e.getY() - downY)
|
||||
> ViewConfiguration.get(getContext()).getScaledTouchSlop()) {
|
||||
removeCallbacks(fire);
|
||||
}
|
||||
break;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
removeCallbacks(fire);
|
||||
if (longPressed) {
|
||||
drop(); // released before any move reached onTouchEvent
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return longPressed; // once fired, take the gesture away from the widget
|
||||
}
|
||||
|
||||
private void drop() {
|
||||
longPressed = false;
|
||||
setAlpha(1f);
|
||||
home.js("widgetDrop(" + moved + ")");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent e) {
|
||||
if (!longPressed) {
|
||||
// Where no child took the press, its moves come here instead of through
|
||||
// onInterceptTouchEvent; keep the gesture so they do.
|
||||
int a = e.getActionMasked();
|
||||
if (a == MotionEvent.ACTION_UP || a == MotionEvent.ACTION_CANCEL
|
||||
|| (a == MotionEvent.ACTION_MOVE && Math.hypot(e.getX() - downX, e.getY() - downY)
|
||||
> ViewConfiguration.get(getContext()).getScaledTouchSlop())) {
|
||||
removeCallbacks(fire);
|
||||
}
|
||||
return super.onTouchEvent(e) || a == MotionEvent.ACTION_DOWN;
|
||||
}
|
||||
switch (e.getActionMasked()) {
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
if (!moved && Math.hypot(e.getX() - downX, e.getY() - downY)
|
||||
> ViewConfiguration.get(getContext()).getScaledTouchSlop()) {
|
||||
moved = true;
|
||||
}
|
||||
if (moved) {
|
||||
// Raw screen coordinates: this view moves as the page reorders slots.
|
||||
float d = getResources().getDisplayMetrics().density;
|
||||
home.web.getLocationOnScreen(webAt);
|
||||
home.js("widgetDrag(" + Math.round((e.getRawX() - webAt[0]) / d) + ","
|
||||
+ Math.round((e.getRawY() - webAt[1]) / d) + ")");
|
||||
}
|
||||
break;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
drop();
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void start(String component) {
|
||||
ComponentName cn = ComponentName.unflattenFromString(component);
|
||||
try {
|
||||
launcher.startMainActivity(cn, user, null, null);
|
||||
} catch (ActivityNotFoundException | SecurityException | NullPointerException e) {
|
||||
Toast.makeText(this, "Can't open " + component, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void startIntent(Intent i) {
|
||||
try {
|
||||
startActivity(i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
|
||||
} catch (ActivityNotFoundException e) {
|
||||
Toast.makeText(this, "Not available on this device", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show Recents through RecentsService. Until the user has turned the service on, take
|
||||
* them to Accessibility settings, with our service highlighted where Settings supports it.
|
||||
*/
|
||||
private void openRecents() {
|
||||
if (RecentsService.showRecents()) return;
|
||||
Toast.makeText(this, "Turn on \"" + getString(R.string.recents_service_label)
|
||||
+ "\" to show open windows", Toast.LENGTH_LONG).show();
|
||||
String me = new ComponentName(this, RecentsService.class).flattenToString();
|
||||
Bundle args = new Bundle();
|
||||
args.putString(":settings:fragment_args_key", me);
|
||||
startIntent(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
.putExtra(":settings:fragment_args_key", me)
|
||||
.putExtra(":settings:show_fragment_args", args));
|
||||
}
|
||||
|
||||
/** window.Android: called from the page's @jscall imports on a binder thread. */
|
||||
final class Bridge {
|
||||
@JavascriptInterface public void launch(String component) {
|
||||
main.post(() -> start(component));
|
||||
}
|
||||
|
||||
@JavascriptInterface public void appInfo(String component) {
|
||||
main.post(() -> {
|
||||
ComponentName cn = ComponentName.unflattenFromString(component);
|
||||
if (cn != null) launcher.startAppDetailsActivity(cn, user, null, null);
|
||||
});
|
||||
}
|
||||
|
||||
/** The system asks the user to confirm; the app list reloads when the package goes. */
|
||||
@JavascriptInterface public void uninstall(String component) {
|
||||
main.post(() -> {
|
||||
ComponentName cn = ComponentName.unflattenFromString(component);
|
||||
if (cn != null) startIntent(new Intent(Intent.ACTION_DELETE,
|
||||
Uri.fromParts("package", cn.getPackageName(), null)));
|
||||
});
|
||||
}
|
||||
|
||||
@JavascriptInterface public void addWidget(String provider) {
|
||||
main.post(() -> HomeActivity.this.addWidget(provider));
|
||||
}
|
||||
|
||||
@JavascriptInterface public void removeWidget(int id) {
|
||||
main.post(() -> HomeActivity.this.removeWidget(id));
|
||||
}
|
||||
|
||||
@JavascriptInterface public void placeWidgets(String json) {
|
||||
main.post(() -> HomeActivity.this.placeWidgets(json));
|
||||
}
|
||||
|
||||
/** The drawer covers the page down to y (CSS px); -1 is all of it, 0 none. */
|
||||
@JavascriptInterface public void coverWidgets(int y) {
|
||||
main.post(() -> {
|
||||
long n = ++coverRequest;
|
||||
if (y != 0) { widgetLayer.cover(y < 0 ? -1 : Math.round(y * getResources().getDisplayMetrics().density)); return; }
|
||||
// The drawer is gone from the page; show the widgets once the page has
|
||||
// painted without it, so they don't flash over it for a frame.
|
||||
web.postVisualStateCallback(n, new WebView.VisualStateCallback() {
|
||||
@Override public void onComplete(long requestId) {
|
||||
if (requestId == coverRequest) widgetLayer.cover(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@JavascriptInterface public String widgetLimits(int id) {
|
||||
return HomeActivity.this.widgetLimits(id);
|
||||
}
|
||||
|
||||
@JavascriptInterface public void excludeGestures(String json) {
|
||||
main.post(() -> HomeActivity.this.excludeGestures(json));
|
||||
}
|
||||
|
||||
@JavascriptInterface public void loadIcons(String keys) {
|
||||
HomeActivity.this.loadIcons(keys);
|
||||
}
|
||||
|
||||
@JavascriptInterface public void haptic() {
|
||||
main.post(() -> web.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
|
||||
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING));
|
||||
}
|
||||
|
||||
/** The page focused the drawer's search box; show the keyboard for it. */
|
||||
@JavascriptInterface public void showKeyboard() {
|
||||
main.postDelayed(() -> {
|
||||
web.requestFocus();
|
||||
InputMethodManager imm = getSystemService(InputMethodManager.class);
|
||||
if (imm != null) imm.showSoftInput(web, InputMethodManager.SHOW_IMPLICIT);
|
||||
}, 50);
|
||||
}
|
||||
|
||||
@JavascriptInterface public void hideKeyboard() {
|
||||
main.post(() -> {
|
||||
InputMethodManager imm = getSystemService(InputMethodManager.class);
|
||||
if (imm != null) imm.hideSoftInputFromWindow(web.getWindowToken(), 0);
|
||||
});
|
||||
}
|
||||
|
||||
@JavascriptInterface public void openSettings() {
|
||||
main.post(() -> startIntent(new Intent(Settings.ACTION_SETTINGS)));
|
||||
}
|
||||
|
||||
@JavascriptInterface public void pickWallpaper() {
|
||||
main.post(() -> startIntent(Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER), "Wallpaper")));
|
||||
}
|
||||
|
||||
@JavascriptInterface public void openRecents() {
|
||||
main.post(HomeActivity.this::openRecents);
|
||||
}
|
||||
|
||||
/** GET a URL on a background thread; the page hears back through launcher.httpResult(tag, ok, text). */
|
||||
@JavascriptInterface public void httpGet(String url, int tag) {
|
||||
Updater.get(HomeActivity.this, url, (ok, text) -> main.post(() ->
|
||||
js("httpResult(" + tag + "," + ok + "," + JSONObject.quote(text) + ")")));
|
||||
}
|
||||
|
||||
/** Stream an APK into a PackageInstaller session; Android then asks the user to confirm. */
|
||||
@JavascriptInterface public void installApk(String url, int version) {
|
||||
Updater.install(HomeActivity.this, url, version);
|
||||
}
|
||||
|
||||
@JavascriptInterface public int installedVersion() {
|
||||
return Updater.installedVersion(HomeActivity.this);
|
||||
}
|
||||
|
||||
/** The last build whose install the user cancelled, or -1. */
|
||||
@JavascriptInterface public int declinedVersion() {
|
||||
return Updater.declinedVersion(HomeActivity.this);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ serving
|
||||
|
||||
final class Client extends WebViewClient {
|
||||
@Override
|
||||
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest req) {
|
||||
Uri u = req.getUrl();
|
||||
if (!HOST.equals(u.getHost())) return notFound();
|
||||
String path = u.getPath() == null ? "/" : u.getPath();
|
||||
try {
|
||||
switch (path) {
|
||||
case "/apps.json":
|
||||
return respond("application/json",
|
||||
new ByteArrayInputStream(appsJson().getBytes(StandardCharsets.UTF_8)));
|
||||
case "/widgets.json":
|
||||
return respond("application/json",
|
||||
new ByteArrayInputStream(widgetsJson().getBytes(StandardCharsets.UTF_8)));
|
||||
case "/wicon":
|
||||
byte[] wpng = widgetIconPng(u.getQueryParameter("p"));
|
||||
return wpng == null ? notFound() : respond("image/png", new ByteArrayInputStream(wpng));
|
||||
case "/icon":
|
||||
byte[] png = iconPng(u.getQueryParameter("c"));
|
||||
return png == null ? notFound() : respond("image/png", new ByteArrayInputStream(png));
|
||||
default:
|
||||
String name = path.equals("/") ? "index.html" : path.substring(1);
|
||||
return respond(mime(name), getAssets().open(name));
|
||||
}
|
||||
} catch (IOException | JSONException | RuntimeException e) {
|
||||
Log.w("ultra", "serving " + path, e);
|
||||
return notFound();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest req) {
|
||||
return true; // the home screen never navigates away
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPageFinished(WebView view, String url) {
|
||||
ready = true;
|
||||
pushInsets();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
|
||||
// The renderer was killed (e.g. under memory pressure): start over with a new WebView.
|
||||
for (AppWidgetHostView v : widgetViews.values()) widgetLayer.removeView(v);
|
||||
web.destroy();
|
||||
createWebView();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static WebResourceResponse respond(String mime, InputStream body) {
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Cache-Control", "no-cache");
|
||||
return new WebResourceResponse(mime, null, 200, "OK", headers, body);
|
||||
}
|
||||
|
||||
private static WebResourceResponse notFound() {
|
||||
return new WebResourceResponse("text/plain", null, 404, "Not Found", new HashMap<>(),
|
||||
new ByteArrayInputStream(new byte[0]));
|
||||
}
|
||||
|
||||
private static String mime(String name) {
|
||||
if (name.endsWith(".html")) return "text/html";
|
||||
if (name.endsWith(".js")) return "text/javascript";
|
||||
if (name.endsWith(".css")) return "text/css";
|
||||
if (name.endsWith(".wasm")) return "application/wasm";
|
||||
if (name.endsWith(".json")) return "application/json";
|
||||
if (name.endsWith(".png")) return "image/png";
|
||||
if (name.endsWith(".svg")) return "image/svg+xml";
|
||||
return "application/octet-stream";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package dev.ultra.launcher;
|
||||
|
||||
import android.accessibilityservice.AccessibilityService;
|
||||
import android.content.Intent;
|
||||
import android.view.accessibility.AccessibilityEvent;
|
||||
|
||||
/**
|
||||
* An accessibility service that does nothing but open Recents (the system's list of open
|
||||
* windows) for the home screen's Windows button. Android lets no other app open Recents,
|
||||
* so the user turns this on once under Settings > Accessibility. It reads no window
|
||||
* content and asks for no events.
|
||||
*/
|
||||
public class RecentsService extends AccessibilityService {
|
||||
private static volatile RecentsService running;
|
||||
|
||||
/** Open Recents; false when the service isn't turned on. */
|
||||
static boolean showRecents() {
|
||||
RecentsService s = running;
|
||||
return s != null && s.performGlobalAction(GLOBAL_ACTION_RECENTS);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onServiceConnected() {
|
||||
running = this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onUnbind(Intent intent) {
|
||||
running = null;
|
||||
return super.onUnbind(intent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
running = null;
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override public void onAccessibilityEvent(AccessibilityEvent event) { }
|
||||
@Override public void onInterrupt() { }
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">ultra Home</string>
|
||||
<string name="recents_service_label">ultra Home window list</string>
|
||||
<string name="recents_service_summary">Lets the home screen\'s Windows button open Recents</string>
|
||||
<string name="recents_service_description">Turn this on so the Windows button on the ultra Home screen can show your open windows (Recents). Android only lets accessibility services open Recents. This service reads nothing on screen and does nothing else.</string>
|
||||
</resources>
|
||||
@@ -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>
|
||||
@@ -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" />
|
||||
@@ -231,7 +231,6 @@ pub(all) enum Msg {
|
||||
Touch(dx~ : Double, dy~ : Double, ms~ : Int, home_top~ : Bool, list_end~ : Bool)
|
||||
ReleaseFetched(String?)
|
||||
VersionFetched(String?)
|
||||
UpdateDeclined(Int)
|
||||
NoticeDone(Int)
|
||||
// ---- from handlers
|
||||
Query(String)
|
||||
@@ -292,7 +291,6 @@ pub(all) enum Effect {
|
||||
QueryLimits(Int)
|
||||
SaveHome(String)
|
||||
SaveLastCheck(Int64)
|
||||
SaveDeclined(Int)
|
||||
/// Send the message after this many ms.
|
||||
Delay(Int, Msg)
|
||||
/// After this many ms, feed `Hold(token)` to `input` (the long-press timer).
|
||||
|
||||
@@ -81,7 +81,6 @@ pub(all) enum Effect {
|
||||
QueryLimits(Int32)
|
||||
SaveHome(String)
|
||||
SaveLastCheck(Int64)
|
||||
SaveDeclined(Int32)
|
||||
Delay(Int32, Msg)
|
||||
HoldTimer(Int32, Int32)
|
||||
FetchRelease(String)
|
||||
@@ -176,7 +175,6 @@ pub(all) enum Msg {
|
||||
Touch(dx~ : Double, dy~ : Double, ms~ : Int32, home_top~ : Bool, list_end~ : Bool)
|
||||
ReleaseFetched(String?)
|
||||
VersionFetched(String?)
|
||||
UpdateDeclined(Int32)
|
||||
NoticeDone(Int32)
|
||||
Query(String)
|
||||
Clear
|
||||
|
||||
@@ -746,8 +746,6 @@ test "self-update: up to date is silent unless asked; declined builds are not of
|
||||
s2.send(ReleaseFetched(Some(rel)))
|
||||
s2.send(VersionFetched(Some("{\"versionCode\":11}")))
|
||||
assert_true(s2.has_effect(InstallApk("u/a", 11)))
|
||||
s2.send(UpdateDeclined(11))
|
||||
assert_true(s2.has_effect(SaveDeclined(11)))
|
||||
}
|
||||
|
||||
///|
|
||||
|
||||
@@ -605,10 +605,6 @@ fn step(m : Model, msg : Msg, fx : Array[Effect]) -> Unit {
|
||||
}
|
||||
}
|
||||
}
|
||||
UpdateDeclined(n) => {
|
||||
m.declined = n
|
||||
fx.push(SaveDeclined(n))
|
||||
}
|
||||
NoticeDone(gen) => if gen == m.notice_gen { m.notice = "" }
|
||||
Query(q) => m.query = q
|
||||
Clear => m.query = ""
|
||||
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds the launcher APK (MoonBit page + Java shell, android/build.sh) and publishes it as a
|
||||
# Gitea release: build-<versionCode>, holding ultra-launcher.apk and version.json, made a
|
||||
# draft first and published once both files are up, so the latest release never lacks them.
|
||||
# Runs in .gitea/workflows/launcher.yml's "apk" job (node:22-bookworm container, as root,
|
||||
# no docker). The installed app updates itself from the latest release (updater/ in MoonBit).
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Minutes since the epoch: always above every earlier build's versionCode (the Qt builds used
|
||||
# the same scale) and always rising.
|
||||
export VERSION_CODE=$(( $(date +%s) / 60 ))
|
||||
COMMIT="${GITHUB_SHA:-$(git rev-parse HEAD)}"
|
||||
|
||||
echo "== tools"
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends openjdk-17-jdk-headless unzip zip curl ca-certificates git >/dev/null
|
||||
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
|
||||
export PATH="$HOME/.moon/bin:$PATH"
|
||||
moon update
|
||||
|
||||
echo "== Android SDK (build-tools and the platform jar only)"
|
||||
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 "build-tools;35.0.0" >/dev/null
|
||||
# Only android.jar is needed from the platform: unzipping the whole thing (sdkmanager) is slow.
|
||||
curl -fsSL -o /tmp/platform.zip https://dl.google.com/android/repository/platform-35_r02.zip
|
||||
mkdir -p "$ANDROID_SDK_ROOT/platforms" && unzip -q /tmp/platform.zip 'android-35/android.jar' -d "$ANDROID_SDK_ROOT/platforms"
|
||||
|
||||
echo "== build (versionCode $VERSION_CODE)"
|
||||
android/build.sh ultra-launcher.apk
|
||||
|
||||
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\": \"MoonBit launcher built from $COMMIT.\"}" \
|
||||
| python3 -c 'import sys, json; print(json.load(sys.stdin)["id"])')
|
||||
curl -fsS "${auth[@]}" -F "attachment=@ultra-launcher.apk" "$api/releases/$id/assets?name=ultra-launcher.apk" >/dev/null
|
||||
curl -fsS "${auth[@]}" -F "attachment=@$(dirname ultra-launcher.apk)/version.json" "$api/releases/$id/assets?name=version.json" >/dev/null
|
||||
curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X PATCH "$api/releases/$id" -d '{"draft": false}' >/dev/null
|
||||
echo "published $tag to $server/$repo"
|
||||
@@ -0,0 +1,131 @@
|
||||
// Drives the page against a stub of the Java shell's window.Android bridge, to check the seam
|
||||
// between the MoonBit page and the shell (what the page asks of Android, and how it reacts when
|
||||
// Android calls window.launcher.*). The Java side itself needs a device; this is the page half.
|
||||
// scripts/build-web.sh --demo && node tests/android-sim.cjs
|
||||
const assert = require("assert");
|
||||
const fs = require("fs");
|
||||
const http = require("http");
|
||||
const path = require("path");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT || "playwright");
|
||||
|
||||
const RELEASE = JSON.stringify({ tag_name: "build-9", assets: [
|
||||
{ name: "version.json", browser_download_url: "https://x/version.json" },
|
||||
{ name: "ultra-launcher.apk", browser_download_url: "https://x/a.apk" }] });
|
||||
|
||||
(async () => {
|
||||
const root = path.join(__dirname, "..", "dist", "web");
|
||||
const types = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" };
|
||||
const srv = http.createServer((req, res) => {
|
||||
const u = req.url.split("?")[0] === "/" ? "/index.html" : req.url.split("?")[0];
|
||||
fs.readFile(path.join(root, u), (err, data) => {
|
||||
if (err) { res.writeHead(404); res.end(); return; }
|
||||
res.writeHead(200, { "content-type": types[path.extname(u)] || "application/octet-stream" }); res.end(data);
|
||||
});
|
||||
}).listen(0);
|
||||
const BASE = `http://localhost:${srv.address().port}`;
|
||||
const b = await chromium.launch();
|
||||
const p = await b.newPage({ viewport: { width: 390, height: 780 } });
|
||||
p.on("pageerror", (e) => { console.error("page error:", e.message); process.exitCode = 1; });
|
||||
await p.addInitScript((release) => {
|
||||
window.__calls = [];
|
||||
const rec = (n) => (...a) => { window.__calls.push([n, ...a]); };
|
||||
const disc = "data:image/svg+xml," + encodeURIComponent("<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><circle cx='4' cy='4' r='4' fill='red'/></svg>");
|
||||
window.Android = {
|
||||
launch: rec("launch"), appInfo: rec("appInfo"), uninstall: rec("uninstall"),
|
||||
addWidget: (prov) => { rec("addWidget")(prov); setTimeout(() => window.launcher.widgetAdded(77), 0); },
|
||||
removeWidget: rec("removeWidget"), placeWidgets: rec("placeWidgets"), coverWidgets: rec("coverWidgets"),
|
||||
excludeGestures: rec("excludeGestures"),
|
||||
widgetLimits: () => JSON.stringify({ w: 110, minW: 64, minH: 64, maxW: 0, maxH: 0, h: true, v: true }),
|
||||
loadIcons: (json) => { rec("loadIcons")(json); const o = {}; for (const k of JSON.parse(json)) o[k] = disc; setTimeout(() => window.launcher.icons(o), 0); },
|
||||
haptic: rec("haptic"), showKeyboard: rec("showKeyboard"), hideKeyboard: rec("hideKeyboard"),
|
||||
openSettings: rec("openSettings"), pickWallpaper: rec("pickWallpaper"), openRecents: rec("openRecents"),
|
||||
httpGet: (url, tag) => { rec("httpGet")(url, tag);
|
||||
setTimeout(() => window.launcher.httpResult(tag, true, url.endsWith("/latest") ? release : JSON.stringify({ versionCode: 9, commit: "abc" })), 0); },
|
||||
installApk: rec("installApk"), installedVersion: () => 5, declinedVersion: () => -1,
|
||||
};
|
||||
}, RELEASE);
|
||||
const calls = (n) => p.evaluate((n) => window.__calls.filter((c) => c[0] === n), n);
|
||||
const settle = () => p.waitForTimeout(250);
|
||||
const longpress = async (sel, fy = 0.5) => {
|
||||
const r = await p.locator(sel).first().boundingBox();
|
||||
await p.mouse.move(r.x + r.width / 2, r.y + r.height * fy);
|
||||
await p.mouse.down(); await p.waitForTimeout(650); await p.mouse.up(); await settle();
|
||||
};
|
||||
await p.goto(BASE + "/");
|
||||
await p.evaluate(() => localStorage.clear());
|
||||
await p.reload();
|
||||
await p.waitForSelector(".hint");
|
||||
assert.ok(!(await p.evaluate(() => document.documentElement.classList.contains("demo"))), "no demo backdrop on a phone");
|
||||
|
||||
// on start the page checks for an update: release API, then version.json, then installs build 9 over 5
|
||||
await p.waitForFunction(() => window.__calls.some((c) => c[0] === "installApk"));
|
||||
assert.deepEqual((await calls("httpGet")).map((c) => c[1]), [
|
||||
"https://git.site.latha.org/api/v1/repos/experiments/launcher/releases/latest", "https://x/version.json"]);
|
||||
assert.deepEqual((await calls("installApk"))[0].slice(1), ["https://x/a.apk", 9]);
|
||||
assert.equal(await p.textContent(".notice"), "Downloading launcher update (build 9)…");
|
||||
|
||||
// the drawer asks the shell for icons (batched, by key) and fills the images from its answer
|
||||
await p.evaluate(() => document.body.dispatchEvent(Object.assign(new Event("x"), {})));
|
||||
await longpress(".hint");
|
||||
await p.click(".sheet-item >> text=Add apps"); await settle();
|
||||
assert.ok((await calls("loadIcons")).length > 0, "icons are asked for");
|
||||
assert.ok(!(await calls("showKeyboard")).length, "no keyboard in pick mode");
|
||||
await p.click(".apps .tile:nth-child(4)"); await p.click(".drawer-head >> text=Done"); await settle();
|
||||
assert.ok((await p.getAttribute(".slots .icon", "src")).startsWith("data:image/svg+xml"), "the icon the shell drew");
|
||||
await p.click(".slots .tile"); await settle();
|
||||
assert.deepEqual((await calls("launch"))[0].slice(1), ["com.example.chrome/.MainActivity"]);
|
||||
|
||||
// Windows asks the shell for Recents; settings and wallpaper too
|
||||
await p.click(".panel-btn"); await settle();
|
||||
assert.equal((await calls("openRecents")).length, 1);
|
||||
|
||||
// add a widget: the shell binds it and the page places it over its slot (wid, x, y, w, h, editing)
|
||||
await longpress(".home", 0.95);
|
||||
await p.click(".sheet-item >> text=Add widget");
|
||||
await p.waitForSelector(".widget-list li");
|
||||
await p.click(".widget-list li:first-child"); await settle();
|
||||
assert.equal((await calls("addWidget")).length, 1);
|
||||
await p.waitForSelector(".widget-slot[data-wid='77']");
|
||||
await settle();
|
||||
const placed = (await calls("placeWidgets")).pop()[1];
|
||||
const [[wid, x, y, w, h, editing]] = JSON.parse(placed);
|
||||
assert.equal(wid, 77); assert.ok(w > 100 && h >= 64 && x >= 0 && y > 100, placed); assert.equal(editing, 0);
|
||||
const box = await p.locator(".widget-slot").boundingBox();
|
||||
assert.ok(Math.abs(box.x - x) < 2 && Math.abs(box.width - w) < 2, "placed where the slot is");
|
||||
assert.ok(w < 358, "starts at its natural width, not the whole row"); // 110px natural = 2 columns
|
||||
|
||||
// opening the drawer: the shell is told to cover the widgets, the keyboard comes up, widgets are unmarked
|
||||
await p.click(".search-pill"); await settle();
|
||||
await p.waitForSelector(".drawer");
|
||||
assert.ok((await calls("coverWidgets")).length > 0, "the shell hides widgets under the drawer");
|
||||
assert.ok((await calls("showKeyboard")).length > 0, "the search takes the keyboard");
|
||||
assert.equal(await p.$$eval("[data-wid]", (ws) => ws.length), 0);
|
||||
await p.click(".drawer-head >> text=Close"); await settle();
|
||||
assert.ok((await calls("hideKeyboard")).length > 0);
|
||||
assert.equal((await calls("coverWidgets")).pop()[1], 0, "the widgets are shown again");
|
||||
|
||||
// a long press on the native widget view reaches the page; letting go without moving shows handles,
|
||||
// and the shell is told to keep its edge swipes off them
|
||||
await p.evaluate(() => { window.launcher.widgetMenu(77); window.launcher.widgetDrop(false); }); await settle();
|
||||
assert.ok(await p.$(".widget-slot.resizing .resize-handle"), "handles");
|
||||
assert.ok(JSON.parse((await calls("excludeGestures")).pop()[1]).length === 3, "three handles excluded from system gestures");
|
||||
assert.equal(JSON.parse((await calls("placeWidgets")).pop()[1])[0][5], 1, "the shell is told which widget is being edited");
|
||||
// dragging it from the native view moves it to a cell (widgetDrag reports page px)
|
||||
await p.evaluate(() => { window.launcher.widgetGrab(77); window.launcher.widgetDrag(200, 300); window.launcher.widgetDrag(200, 420); window.launcher.widgetDrop(true); });
|
||||
await settle();
|
||||
const moved = await p.$eval(".widget-slot", (s) => s.style.gridRow);
|
||||
assert.ok(!moved.startsWith("1 "), `moved off the first row: ${moved}`);
|
||||
await p.click(".resize-bar >> text=Remove"); await settle();
|
||||
assert.equal((await calls("removeWidget"))[0][1], 77);
|
||||
|
||||
// a package change: the shell calls reload(), which fetches the app list again and re-asks for icons
|
||||
const before = (await calls("loadIcons")).length;
|
||||
await p.evaluate(() => window.launcher.reload()); await settle();
|
||||
assert.ok((await calls("loadIcons")).length > before, "icons are asked for again after a reload");
|
||||
// back and home close the drawer
|
||||
await p.click(".search-pill"); await p.waitForSelector(".drawer");
|
||||
await p.evaluate(() => window.launcher.back()); await settle();
|
||||
assert.ok(!(await p.$(".drawer")));
|
||||
console.log("android bridge ok");
|
||||
await b.close(); srv.close();
|
||||
})().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -314,6 +314,10 @@ extern "js" fn h_http_get(url : String, tag : Int) -> Unit =
|
||||
extern "js" fn h_install_apk(url : String, version : Int) -> Unit =
|
||||
#|(url, v) => window.Android.installApk(url, v)
|
||||
|
||||
///|
|
||||
extern "js" fn h_declined_version() -> Int =
|
||||
#|() => window.Android.declinedVersion()
|
||||
|
||||
///|
|
||||
extern "js" fn h_installed_version() -> Int =
|
||||
#|() => window.Android.installedVersion()
|
||||
|
||||
+2
-7
@@ -133,7 +133,6 @@ fn exec(e : @app.Effect) -> Unit {
|
||||
}
|
||||
SaveHome(json) => storage_set("launcher.home", json)
|
||||
SaveLastCheck(t) => storage_set("launcher.update.lastCheck", t.to_string())
|
||||
SaveDeclined(n) => storage_set("launcher.update.declined", n.to_string())
|
||||
Delay(ms, msg) => set_timeout(ms, fn() { dispatch(msg) })
|
||||
HoldTimer(ms, token) => set_timeout(ms, fn() { feed(Hold(token)) })
|
||||
FetchRelease(url) =>
|
||||
@@ -414,7 +413,6 @@ fn expose_api() -> Unit {
|
||||
state.val.placed = ""
|
||||
place()
|
||||
})
|
||||
expose1("updateDeclined", fn(n) { dispatch(UpdateDeclined(n)) })
|
||||
expose_json("icons", got_icons)
|
||||
expose_result("httpResult", fn(tag, ok, text) {
|
||||
if state.val.http.get(tag) is Some(f) {
|
||||
@@ -447,11 +445,8 @@ fn main {
|
||||
let legacy = if saved is None { Some(storage_legacy()) } else { None }
|
||||
dispatch(Restore(saved~, legacy~))
|
||||
if is_android() {
|
||||
let declined = if storage_has("launcher.update.declined") {
|
||||
num("launcher.update.declined").to_int()
|
||||
} else {
|
||||
-1
|
||||
}
|
||||
// the shell keeps the build whose install the user cancelled (-1: none)
|
||||
let declined = h_declined_version()
|
||||
dispatch(
|
||||
Started(
|
||||
now=now_ms().to_int64(),
|
||||
|
||||
Reference in new issue
Block a user