Launcher: blank home with added apps and widgets, swipe-down drawer

The home screen now starts empty under the clock. Long-press it to add
apps (the drawer opens in a pick mode) or widgets, and long-press a slot
to move or remove it. Swiping down opens the drawer with every app and a
search; long-press there adds an app to home, swipe up closes it.

Widgets are real AppWidgetHostViews layered over the WebView at the
slots the page reports after each render, with Android's bind and
configure screens on add and native long-press for their menu.

ultra gains on_longpress(msg, arg) for this.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019EEjkJVV72Lu8ndDVWg5BT
This commit is contained in:
Claude committed 2026-10-21 18:01:25 +00:00
1 parent f766453bba
commit 3ed5afbafc
9 files changed
+1026 -230

No files matched your search

+2 -2
View File
@@ -25,8 +25,8 @@ android {
} }
androidResources { androidResources {
// app.py is the LPython source and apps.json is the browser demo's stand-in. // app.py is the LPython source; apps.json and widgets.json are the browser demo's stand-ins.
ignoreAssetsPattern = "!app.py:!apps.json:!__pycache__:!.*" ignoreAssetsPattern = "!app.py:!apps.json:!widgets.json:!__pycache__:!.*"
} }
buildTypes { buildTypes {
@@ -1,6 +1,11 @@
package dev.ultra.launcher; package dev.ultra.launcher;
import android.app.Activity; 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.ActivityNotFoundException;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Intent; import android.content.Intent;
@@ -20,7 +25,10 @@ import android.os.Process;
import android.os.UserHandle; import android.os.UserHandle;
import android.provider.Settings; import android.provider.Settings;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window; import android.view.Window;
import android.view.WindowInsets; import android.view.WindowInsets;
import android.webkit.JavascriptInterface; import android.webkit.JavascriptInterface;
@@ -30,6 +38,7 @@ import android.webkit.WebResourceResponse;
import android.webkit.WebSettings; import android.webkit.WebSettings;
import android.webkit.WebView; import android.webkit.WebView;
import android.webkit.WebViewClient; import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast; import android.widget.Toast;
import org.json.JSONArray; import org.json.JSONArray;
@@ -55,17 +64,31 @@ import java.util.concurrent.ConcurrentHashMap;
* *
* apps.json {"apps": [{"label", "component", "icon"}]}, every launchable activity * apps.json {"apps": [{"label", "component", "icon"}]}, every launchable activity
* icon?c=COMP the activity's icon as a PNG * icon?c=COMP the activity's icon as a PNG
* widgets.json {"widgets": [{"label", "provider", "icon", "h"}]}, every widget provider
* wicon?p=PROV the provider's icon as a PNG
* *
* and exposes window.Android (launch, appInfo, openSettings, pickWallpaper, is24Hour) for * and exposes window.Android (launch, appInfo, addWidget, removeWidget, placeWidgets,
* the app's @jscall imports. Package changes, the home button, back and resume are passed * openSettings, pickWallpaper, haptic, is24Hour) for the app's @jscall imports.
* to the page as window.ultraHome.reload() / home() / back() / tick(). *
* 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, resume, a new widget and a long press on a widget reach
* the page as window.ultraHome.reload() / home() / back() / tick() / widgetAdded(id) /
* widgetMenu(id).
*/ */
public class MainActivity extends Activity { public class MainActivity extends Activity {
static final String HOST = "appassets.androidplatform.net"; static final String HOST = "appassets.androidplatform.net";
static final String ORIGIN = "https://" + HOST + "/"; static final String ORIGIN = "https://" + HOST + "/";
static final int ICON_DP = 56; 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 WebView web;
private FrameLayout widgetLayer;
private AppWidgetManager widgets;
private AppWidgetHost widgetHost;
private final Map<Integer, AppWidgetHostView> widgetViews = new HashMap<>();
private int pendingWidget = -1;
private boolean ready; private boolean ready;
private int insetTop, insetBottom; // CSS px private int insetTop, insetBottom; // CSS px
private LauncherApps launcher; private LauncherApps launcher;
@@ -86,6 +109,8 @@ public class MainActivity extends Activity {
super.onCreate(state); super.onCreate(state);
launcher = getSystemService(LauncherApps.class); launcher = getSystemService(LauncherApps.class);
launcher.registerCallback(packages, main); launcher.registerCallback(packages, main);
widgets = AppWidgetManager.getInstance(this);
widgetHost = new Host(this);
Window w = getWindow(); Window w = getWindow();
if (Build.VERSION.SDK_INT >= 30) { if (Build.VERSION.SDK_INT >= 30) {
@@ -101,6 +126,9 @@ public class MainActivity extends Activity {
ready = false; ready = false;
web = new WebView(this); web = new WebView(this);
web.setBackgroundColor(Color.TRANSPARENT); 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.setVerticalScrollBarEnabled(false);
web.setOverScrollMode(View.OVER_SCROLL_NEVER); web.setOverScrollMode(View.OVER_SCROLL_NEVER);
WebSettings s = web.getSettings(); WebSettings s = web.getSettings();
@@ -127,10 +155,27 @@ public class MainActivity extends Activity {
pushInsets(); pushInsets();
return insets; return insets;
}); });
setContentView(web); widgetViews.clear();
widgetLayer = new FrameLayout(this);
FrameLayout root = new FrameLayout(this);
root.addView(web);
root.addView(widgetLayer);
setContentView(root);
web.loadUrl(ORIGIN + "index.html"); web.loadUrl(ORIGIN + "index.html");
} }
@Override
protected void onStart() {
super.onStart();
widgetHost.startListening();
}
@Override
protected void onStop() {
super.onStop();
widgetHost.stopListening();
}
@Override @Override
protected void onDestroy() { protected void onDestroy() {
launcher.unregisterCallback(packages); launcher.unregisterCallback(packages);
@@ -166,7 +211,7 @@ public class MainActivity extends Activity {
if (!ready) return; if (!ready) return;
web.evaluateJavascript("(s => { s.setProperty('--inset-top', '" + insetTop + "px');" web.evaluateJavascript("(s => { s.setProperty('--inset-top', '" + insetTop + "px');"
+ " s.setProperty('--inset-bottom', '" + insetBottom + "px'); })" + " s.setProperty('--inset-bottom', '" + insetBottom + "px'); })"
+ "(document.documentElement.style)", null); + "(document.documentElement.style); window.ultraHome && ultraHome.place()", null);
} }
private void reload() { private void reload() {
@@ -204,19 +249,226 @@ public class MainActivity extends Activity {
new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(cn), user); new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(cn), user);
if (info == null) return null; if (info == null) return null;
int dpi = getResources().getDisplayMetrics().densityDpi; int dpi = getResources().getDisplayMetrics().densityDpi;
Drawable d = info.getIcon(dpi); png = toPng(info.getIcon(dpi), Math.round(ICON_DP * dpi / 160f));
int size = Math.round(ICON_DP * dpi / 160f); icons.put(c, png);
return png;
}
private static byte[] toPng(Drawable d, int size) {
Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
d.setBounds(0, 0, size, size); d.setBounds(0, 0, size, size);
d.draw(new Canvas(bmp)); d.draw(new Canvas(bmp));
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
bmp.recycle(); bmp.recycle();
png = out.toByteArray(); return out.toByteArray();
icons.put(c, png); }
// ------------------------------------------------------------ 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("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();
}
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;
AppWidgetProviderInfo w = provider(p);
if (w == null) return null;
int dpi = getResources().getDisplayMetrics().densityDpi;
Drawable d = w.loadIcon(this, dpi);
if (d == null) return null;
png = toPng(d, Math.round(ICON_DP * dpi / 160f));
icons.put(k, png);
return 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);
widgetHost.deleteAppWidgetId(id);
}
/** Lay widget views over the page's live slots: [[id, x, y, w, h], ...] in CSS px. */
private void placeWidgets(String json) {
float d = getResources().getDisplayMetrics().density;
Map<Integer, int[]> want = new HashMap<>();
try {
JSONArray a = new JSONArray(json);
for (int i = 0; i < a.length(); i++) {
JSONArray r = a.getJSONArray(i);
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;
}
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);
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. */
static final class Host extends AppWidgetHost {
Host(MainActivity a) { super(a, HOST_ID); }
@Override
protected AppWidgetHostView onCreateView(Context context, int id, AppWidgetProviderInfo info) {
return new WidgetView((MainActivity) context, id);
}
}
static final class WidgetView extends AppWidgetHostView {
private final MainActivity home;
private final int id;
private float downX, downY;
private boolean longPressed;
private final Runnable fire = new Runnable() {
@Override public void run() {
longPressed = true;
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
home.js("widgetMenu(" + id + ")");
}
};
WidgetView(MainActivity home, int id) {
super(home);
this.home = home;
this.id = id;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
longPressed = false;
downX = e.getX();
downY = e.getY();
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);
break;
}
return longPressed; // once fired, take the gesture away from the widget
}
@Override
public boolean onTouchEvent(MotionEvent e) {
return longPressed || super.onTouchEvent(e);
}
}
private void start(String component) { private void start(String component) {
ComponentName cn = ComponentName.unflattenFromString(component); ComponentName cn = ComponentName.unflattenFromString(component);
try { try {
@@ -247,6 +499,23 @@ public class MainActivity extends Activity {
}); });
} }
@JavascriptInterface public void addWidget(String provider) {
main.post(() -> MainActivity.this.addWidget(provider));
}
@JavascriptInterface public void removeWidget(int id) {
main.post(() -> MainActivity.this.removeWidget(id));
}
@JavascriptInterface public void placeWidgets(String json) {
main.post(() -> MainActivity.this.placeWidgets(json));
}
@JavascriptInterface public void haptic() {
main.post(() -> web.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING));
}
@JavascriptInterface public void openSettings() { @JavascriptInterface public void openSettings() {
main.post(() -> startIntent(new Intent(Settings.ACTION_SETTINGS))); main.post(() -> startIntent(new Intent(Settings.ACTION_SETTINGS)));
} }
@@ -273,6 +542,12 @@ public class MainActivity extends Activity {
case "/apps.json": case "/apps.json":
return respond("application/json", return respond("application/json",
new ByteArrayInputStream(appsJson().getBytes(StandardCharsets.UTF_8))); 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": case "/icon":
byte[] png = iconPng(u.getQueryParameter("c")); byte[] png = iconPng(u.getQueryParameter("c"));
return png == null ? notFound() : respond("image/png", new ByteArrayInputStream(png)); return png == null ? notFound() : respond("image/png", new ByteArrayInputStream(png));
@@ -299,6 +574,7 @@ public class MainActivity extends Activity {
@Override @Override
public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) { public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
// The renderer was killed (e.g. under memory pressure): start over with a new WebView. // 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(); web.destroy();
createWebView(); createWebView();
return true; return true;
+60 -21
View File
@@ -178,31 +178,70 @@ const BASE = process.env.BASE || "http://localhost:8000";
assert.ok(await p.$(".page.dark")); assert.ok(await p.$(".page.dark"));
console.log("ui ok"); console.log("ui ok");
// launcher: the Android home screen, against the demo apps.json // launcher: the Android home screen, against the demo apps.json and widgets.json
const settle = () => p.waitForTimeout(250); // renders land on the next frame, which can lag here
await p.emulateMedia({ reducedMotion: "reduce" }); // no sliding drawer under the pointer
await p.goto(BASE + "/examples/launcher/"); await p.goto(BASE + "/examples/launcher/");
await p.evaluate(() => localStorage.clear()); await p.evaluate(() => localStorage.clear());
await p.reload(); await p.reload();
await p.waitForSelector(".tile"); await p.waitForSelector(".hint");
const names = () => p.$$eval(".tile .name", (ns) => ns.map((n) => n.textContent));
assert.equal((await names()).length, 16);
assert.match(await p.textContent(".clock .time"), /^\d{1,2}:\d\d$/); assert.match(await p.textContent(".clock .time"), /^\d{1,2}:\d\d$/);
await p.fill(".search input", "ca"); await tick(); const longpress = async (sel) => {
assert.deepEqual(await names(), ["Calculator", "Calendar", "Camera"]); const r = await p.locator(sel).first().boundingBox();
await p.press(".search input", "Enter"); await tick(); await p.mouse.move(r.x + r.width / 2, r.y + r.height / 2);
assert.equal(await p.textContent("#toast"), "Open com.example.calculator/.MainActivity"); await p.mouse.down(); await p.waitForTimeout(650); await p.mouse.up(); await settle();
assert.equal(await p.inputValue(".search input"), "", "launching clears the search"); };
await p.click("text=Edit dock"); await tick(); const homeApps = () => p.$$eval(".slots .name", (ns) => ns.map((n) => n.textContent));
await p.click(".tile:nth-child(4)", { force: true }); await p.click(".tile:nth-child(8)", { force: true }); await tick(); // long press on the blank home: add apps through the drawer's pick mode
assert.equal(await p.$$eval(".tile.pinned", (ts) => ts.length), 2); await longpress(".hint");
await p.click("text=Done"); await tick(); await p.click(".sheet-item >> text=Add apps"); await settle();
await p.reload(); await p.waitForSelector(".dock-app"); for (const i of [4, 8, 12]) await p.click(`.apps .tile:nth-child(${i})`);
assert.deepEqual(await p.$$eval(".dock-app", (ds) => ds.map((d) => d.getAttribute("aria-label"))), ["Chrome", "Gmail"]); await settle();
await p.click(".dock-app:first-child"); await tick(); assert.equal(await p.$$eval(".apps .tile.on", (ts) => ts.length), 3);
assert.equal(await p.textContent("#toast"), "Open com.example.chrome/.MainActivity"); await p.click(".drawer-head >> text=Done"); await settle();
await p.fill(".search input", "zzz"); await tick(); assert.deepEqual(await homeApps(), ["Chrome", "Gmail", "Phone"]);
assert.equal(await p.textContent(".empty"), "No apps match."); // add a widget
await p.evaluate(() => window.ultraHome.back()); await tick(); await longpress(".clock");
assert.equal((await names()).length, 16, "back clears the search"); 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 p.getAttribute(".widget-slot", "data-wid"), "100");
assert.equal(await p.textContent(".widget-label"), "Clock");
// long press a home app: reorder
await longpress(".slots .tile:nth-child(2)");
await p.click(".sheet-item >> text=Move earlier"); await settle();
assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]);
// swipe down opens the drawer (and takes the widget off screen), search, long press adds
const swipe = (y0, y1) => p.evaluate(([y0, y1]) => {
const at = (y) => new Touch({ identifier: 1, target: document.body, clientX: 200, clientY: y });
dispatchEvent(new TouchEvent("touchstart", { touches: [at(y0)], changedTouches: [at(y0)] }));
dispatchEvent(new TouchEvent("touchend", { touches: [], changedTouches: [at(y1)] }));
}, [y0, y1]);
await swipe(200, 500);
await p.waitForSelector(".drawer", { timeout: 2000 });
assert.equal(await p.$$eval("[data-wid]", (ws) => ws.length), 0);
await p.fill(".drawer input", "ma"); await settle();
assert.deepEqual(await p.$$eval(".apps .name", (ns) => ns.map((n) => n.textContent)), ["Gmail", "Maps"]);
await p.press(".drawer input", "Enter"); await settle();
assert.equal(await p.textContent("#toast"), "Open com.example.gmail/.MainActivity");
assert.ok(!(await p.$(".drawer")), "launching closes the drawer");
await swipe(200, 500);
await p.waitForSelector(".drawer .tile", { timeout: 2000 });
await longpress(".apps .tile:first-child");
assert.equal(await p.textContent(".notice"), "Added to home");
await swipe(600, 200);
await p.waitForSelector(".drawer", { state: "detached", timeout: 2000 }); // swipe up closes it
assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone", "Calculator"]);
// persisted; tap launches; remove
await p.reload(); await p.waitForSelector(".slots .tile");
assert.equal(await p.$$eval(".slots > li", (ls) => ls.length), 5);
await p.click(".slots .tile:first-child"); await settle();
assert.equal(await p.textContent("#toast"), "Open com.example.gmail/.MainActivity");
await longpress(".widget-slot");
await p.click(".sheet-item >> text=Remove widget"); await settle();
assert.ok(!(await p.$(".widget-slot")));
await p.evaluate(() => { window.ultraHome.reload(); }); await settle();
assert.equal(await p.$$eval(".slots > li", (ls) => ls.length), 4);
console.log("launcher ok"); console.log("launcher ok");
await b.close(); await b.close();
+503 -154
View File
@@ -1,15 +1,19 @@
from lpython import i32, Const from lpython import i32, Const
from numpy import empty, int32 from numpy import empty, int32
from ultra import (el, end, text, text_ref, cls, cls_if, attr, attr_ref, key, from ultra import (el, end, text, text_ref, num, cls, cls_if, attr, attr_ref, attr_num, key,
on_click, on_enter, on_escape, after, div, on_click, on_enter, on_escape, on_longpress, after, div,
s_new, s_dup, s_clear, s_free, s_copy, s_eq, s_has, s_len, s_new, s_dup, s_set, s_add, s_add_num, s_clear, s_free, s_copy, s_eq, s_has, s_len,
s_save_at, s_load_at, store_i32, load_i32, s_save_at, s_load_at, store_i32, load_i32, store_i32_at, load_i32_at,
http_get, j_ok, j_err, j_at, j_idx, j_len, j_str, j_free) http_get, j_ok, j_err, j_at, j_idx, j_len, j_int, j_str, j_free)
from ui import btn_open, input_open, alert from ui import btn_open, input_open, alert
# An Android home screen. The native shell (android/) serves this folder in a # An Android home screen. The home starts blank: you add apps and widgets to it
# WebView, answers apps.json with the installed launchable activities, and # with a long press. Swiping down opens the drawer with every app and a search.
# provides the imports below. In a desktop browser index.html supplies stand-ins. #
# The native shell (android/) serves this folder in a WebView, answers
# apps.json and widgets.json, hosts the widgets as native views over the
# slots this page lays out, and provides the imports below. In a desktop
# browser index.html supplies stand-ins.
@jscall @jscall
def launch(component: i32) -> None: def launch(component: i32) -> None:
@@ -20,6 +24,15 @@ def launch(component: i32) -> None:
def app_info(component: i32) -> None: def app_info(component: i32) -> None:
pass pass
@jscall
def add_widget(provider: i32) -> None:
"""Bind (and configure) a widget; the shell answers with WIDGET_ADDED(id)."""
pass
@jscall
def remove_widget(wid: i32) -> None:
pass
@jscall @jscall
def open_settings() -> None: def open_settings() -> None:
pass pass
@@ -28,6 +41,10 @@ def open_settings() -> None:
def pick_wallpaper() -> None: def pick_wallpaper() -> None:
pass pass
@jscall
def haptic() -> None:
pass
@jscall @jscall
def clock_time(dst: i32) -> None: def clock_time(dst: i32) -> None:
"""Write the local time ("15:04") into dst.""" """Write the local time ("15:04") into dst."""
@@ -38,57 +55,114 @@ def clock_date(dst: i32) -> None:
"""Write the local date ("Tuesday, October 21") into dst.""" """Write the local date ("Tuesday, October 21") into dst."""
pass pass
# ---- Msg (index.html and MainActivity.java send RELOAD, HOME, BACK and TICK) # ---- Msg (index.html and MainActivity.java send TICK through WIDGET_MENU)
LOADED: Const[i32] = 1 TICK: Const[i32] = 1
QUERY: Const[i32] = 2 RELOAD: Const[i32] = 2
CLEAR: Const[i32] = 3 HOME: Const[i32] = 3
OPEN: Const[i32] = 4 BACK: Const[i32] = 4
OPEN_FIRST: Const[i32] = 5 SWIPE_DOWN: Const[i32] = 5
EDIT: Const[i32] = 6 SWIPE_UP: Const[i32] = 6
PIN: Const[i32] = 7 WIDGET_ADDED: Const[i32] = 7
INFO: Const[i32] = 8 WIDGET_MENU: Const[i32] = 8
SETTINGS: Const[i32] = 9 LOADED: Const[i32] = 10
WALLPAPER: Const[i32] = 10 WIDGETS_LOADED: Const[i32] = 11
TICK: Const[i32] = 11 QUERY: Const[i32] = 12
RELOAD: Const[i32] = 12 CLEAR: Const[i32] = 13
HOME: Const[i32] = 13 OPEN_DRAWER: Const[i32] = 14
BACK: Const[i32] = 14 CLOSE_DRAWER: Const[i32] = 15
OPEN_APP: Const[i32] = 16 # arg: row in the app list
OPEN_FIRST: Const[i32] = 17
OPEN_HOME: Const[i32] = 18 # arg: home slot
ADD_HOME: Const[i32] = 19 # arg: row in the app list (long press in the drawer)
TOGGLE_HOME: Const[i32] = 20 # arg: row in the app list (drawer in pick mode)
MENU: Const[i32] = 21 # long press on the empty home
ITEM_MENU: Const[i32] = 22 # arg: home slot
CLOSE_SHEET: Const[i32] = 23
PICK_APPS: Const[i32] = 24
PICK_WIDGET: Const[i32] = 25
CHOOSE_WIDGET: Const[i32] = 26 # arg: row in the widget list
REMOVE: Const[i32] = 27 # arg: home slot
MOVE: Const[i32] = 28 # arg: home slot; moves it one earlier
INFO: Const[i32] = 29 # arg: home slot
SETTINGS: Const[i32] = 30
WALLPAPER: Const[i32] = 31
NOTICE_DONE: Const[i32] = 32
CAP: Const[i32] = 512 CAP: Const[i32] = 512
DOCK: Const[i32] = 5 HOME_CAP: Const[i32] = 40
WCAP: Const[i32] = 256
APP: Const[i32] = 0
WIDGET: Const[i32] = 1
NONE: Const[i32] = 0
SHEET_MENU: Const[i32] = 1
SHEET_ITEM: Const[i32] = 2
SHEET_WIDGETS: Const[i32] = 3
# ---- Model # ---- Model
# One row per launchable activity, as parallel columns of string handles. # Installed apps, as parallel columns of string handles, sorted by label.
labels: i32[512] = empty(512, dtype=int32) labels: i32[512] = empty(512, dtype=int32)
comps: i32[512] = empty(512, dtype=int32) comps: i32[512] = empty(512, dtype=int32)
icons: i32[512] = empty(512, dtype=int32) icons: i32[512] = empty(512, dtype=int32)
n: i32 = 0 n: i32 = 0
# Dock: pinned activities, kept by component name so they survive reloads. # The home screen, in order. An app slot keeps its component name in hstr;
pins: i32[5] = empty(5, dtype=int32) # a widget slot keeps the widget's label there, its host id in hwid and its
npin: i32 = 0 # height in CSS px in hh. hkey is a stable key for the DOM diff.
hkind: i32[40] = empty(40, dtype=int32)
hstr: i32[40] = empty(40, dtype=int32)
hwid: i32[40] = empty(40, dtype=int32)
hh: i32[40] = empty(40, dtype=int32)
hkey: i32[40] = empty(40, dtype=int32)
nh: i32 = 0
next_key: i32 = 1
# Widget providers, for the picker.
wlabels: i32[256] = empty(256, dtype=int32)
wprovs: i32[256] = empty(256, dtype=int32)
wicons: i32[256] = empty(256, dtype=int32)
wheights: i32[256] = empty(256, dtype=int32)
nw: i32 = 0
wloading: i32 = 0
chosen: i32 = -1 # widget row being added
query: i32 = 0 query: i32 = 0
now: i32 = 0 now: i32 = 0
today: i32 = 0 today: i32 = 0
err: i32 = 0 err: i32 = 0
notice: i32 = 0
notice_gen: i32 = 0
scratch: i32 = 0
loading: i32 = 1 loading: i32 = 1
editing: i32 = 0 drawer: i32 = 0
pending: i32 = 0 # JSON handle of the apps.json request in flight picking: i32 = 0 # drawer is in "add apps" mode: taps toggle home slots
sheet: i32 = 0
item: i32 = -1 # home slot the item sheet is about
pending: i32 = 0 # JSON handle of a request in flight
def init() -> None: def init() -> None:
global query, now, today, err, npin, pending global query, now, today, err, notice, scratch, nh, next_key, pending
i: i32 i: i32
h: i32 h: i32
k: i32
query = s_new() query = s_new()
now = s_new() now = s_new()
today = s_new() today = s_new()
err = s_new() err = s_new()
count: i32 = load_i32("ultra.launcher.npin", 0) notice = s_new()
scratch = s_new()
count: i32 = load_i32("ultra.home.n", 0)
for i in range(count): for i in range(count):
h = s_new() h = s_new()
if s_load_at("ultra.launcher.pin", i, h) == 1 and npin < DOCK: if s_load_at("ultra.home.str", i, h) == 1 and nh < HOME_CAP:
pins[npin] = h k = load_i32_at("ultra.home.kind", i, APP)
npin += 1 hkind[nh] = k
hstr[nh] = h
hwid[nh] = load_i32_at("ultra.home.wid", i, 0)
hh[nh] = load_i32_at("ultra.home.h", i, 120)
hkey[nh] = next_key
next_key += 1
nh += 1
else: else:
s_free(h) s_free(h)
clock_time(now) clock_time(now)
@@ -97,13 +171,24 @@ def init() -> None:
pending = http_get("apps.json", LOADED) pending = http_get("apps.json", LOADED)
def save_pins() -> None: def save_home() -> None:
i: i32 i: i32
store_i32("ultra.launcher.npin", npin) store_i32("ultra.home.n", nh)
for i in range(npin): for i in range(nh):
s_save_at("ultra.launcher.pin", i, pins[i]) store_i32_at("ultra.home.kind", i, hkind[i])
s_save_at("ultra.home.str", i, hstr[i])
store_i32_at("ultra.home.wid", i, hwid[i])
store_i32_at("ultra.home.h", i, hh[i])
def say(msg: str) -> None:
global notice_gen
s_set(notice, msg)
notice_gen += 1
after(1800, NOTICE_DONE, notice_gen)
# ---- apps
def clear_apps() -> None: def clear_apps() -> None:
global n global n
i: i32 i: i32
@@ -114,10 +199,10 @@ def clear_apps() -> None:
n = 0 n = 0
def load(doc: i32) -> None: def load_apps(doc: i32) -> None:
global n, loading global n, loading
arr: i32 arr: i32
item: i32 row: i32
cnt: i32 cnt: i32
i: i32 i: i32
ok: i32 ok: i32
@@ -133,50 +218,70 @@ def load(doc: i32) -> None:
if cnt > CAP: if cnt > CAP:
cnt = CAP cnt = CAP
for i in range(cnt): for i in range(cnt):
item = j_idx(arr, i) row = j_idx(arr, i)
labels[n] = s_new() labels[n] = s_new()
comps[n] = s_new() comps[n] = s_new()
icons[n] = s_new() icons[n] = s_new()
ok = j_str(item, "label", labels[n]) ok = j_str(row, "label", labels[n])
ok = j_str(item, "component", comps[n]) ok = j_str(row, "component", comps[n])
ok = j_str(item, "icon", icons[n]) ok = j_str(row, "icon", icons[n])
j_free(item) j_free(row)
n += 1 n += 1
j_free(arr) j_free(arr)
j_free(doc) j_free(doc)
def pin_of(i: i32) -> i32: def load_widgets(doc: i32) -> None:
"""Dock slot holding app i, or -1.""" global nw, wloading
p: i32 arr: i32
for p in range(npin): row: i32
if s_eq(pins[p], comps[i]) == 1: cnt: i32
return p i: i32
return -1 ok: i32
wloading = 0
for i in range(nw):
s_free(wlabels[i])
s_free(wprovs[i])
s_free(wicons[i])
nw = 0
if j_ok(doc) == 0:
j_free(doc)
return
arr = j_at(doc, "widgets")
cnt = j_len(doc, "widgets")
if cnt > WCAP:
cnt = WCAP
for i in range(cnt):
row = j_idx(arr, i)
wlabels[nw] = s_new()
wprovs[nw] = s_new()
wicons[nw] = s_new()
ok = j_str(row, "label", wlabels[nw])
ok = j_str(row, "provider", wprovs[nw])
ok = j_str(row, "icon", wicons[nw])
wheights[nw] = j_int(row, "h")
j_free(row)
nw += 1
j_free(arr)
j_free(doc)
def app_of(p: i32) -> i32: def app_of(comp: i32) -> i32:
"""App row for dock slot p, or -1 if it is not installed (any more).""" """Row in the app list for a component handle, or -1 if it is not installed."""
i: i32 i: i32
for i in range(n): for i in range(n):
if s_eq(pins[p], comps[i]) == 1: if s_eq(comps[i], comp) == 1:
return i return i
return -1 return -1
def toggle_pin(i: i32) -> None: def home_of(row: i32) -> i32:
global npin """Home slot holding app row, or -1."""
p: i32 = pin_of(i) i: i32
j: i32 for i in range(nh):
if p >= 0: if hkind[i] == APP and s_eq(hstr[i], comps[row]) == 1:
s_free(pins[p]) return i
for j in range(p, npin - 1): return -1
pins[j] = pins[j + 1]
npin -= 1
elif npin < DOCK:
pins[npin] = s_dup(comps[i])
npin += 1
save_pins()
def matches(i: i32) -> bool: def matches(i: i32) -> bool:
@@ -190,44 +295,176 @@ def first_match() -> i32:
return i return i
return -1 return -1
# ---- home slots
def reset() -> None: def push_slot(kind: i32, s: i32, wid: i32, h: i32) -> None:
global editing global nh, next_key
hkind[nh] = kind
hstr[nh] = s
hwid[nh] = wid
hh[nh] = h
hkey[nh] = next_key
next_key += 1
nh += 1
save_home()
def add_app(row: i32) -> None:
if home_of(row) >= 0:
say("Already on the home screen")
elif nh >= HOME_CAP:
say("The home screen is full")
else:
push_slot(APP, s_dup(comps[row]), 0, 0)
say("Added to home")
def remove_slot(at: i32) -> None:
global nh
j: i32
if hkind[at] == WIDGET:
remove_widget(hwid[at])
s_free(hstr[at])
for j in range(at, nh - 1):
hkind[j] = hkind[j + 1]
hstr[j] = hstr[j + 1]
hwid[j] = hwid[j + 1]
hh[j] = hh[j + 1]
hkey[j] = hkey[j + 1]
nh -= 1
save_home()
def swap_slots(a: i32, b: i32) -> None:
t: i32
t = hkind[a]
hkind[a] = hkind[b]
hkind[b] = t
t = hstr[a]
hstr[a] = hstr[b]
hstr[b] = t
t = hwid[a]
hwid[a] = hwid[b]
hwid[b] = t
t = hh[a]
hh[a] = hh[b]
hh[b] = t
t = hkey[a]
hkey[a] = hkey[b]
hkey[b] = t
save_home()
def slot_of_widget(wid: i32) -> i32:
i: i32
for i in range(nh):
if hkind[i] == WIDGET and hwid[i] == wid:
return i
return -1
def close_all() -> None:
global drawer, picking, sheet, item
s_clear(query) s_clear(query)
editing = 0 drawer = 0
picking = 0
sheet = NONE
item = -1
# ---- Update # ---- Update
def update(msg: i32, arg: i32) -> None: def update(msg: i32, arg: i32) -> None:
global loading, editing, pending global loading, drawer, picking, sheet, item, pending, wloading, chosen
i: i32 i: i32
if msg == LOADED: if msg == LOADED:
load(arg) load_apps(arg)
elif msg == WIDGETS_LOADED:
load_widgets(arg)
elif msg == QUERY: elif msg == QUERY:
s_copy(query, arg) s_copy(query, arg)
elif msg == CLEAR: elif msg == CLEAR:
s_clear(query) s_clear(query)
elif msg == OPEN: elif msg == OPEN_DRAWER or msg == SWIPE_DOWN:
if editing == 1: if sheet == NONE:
toggle_pin(arg) drawer = 1
else: elif msg == CLOSE_DRAWER or msg == SWIPE_UP:
if drawer == 1 and sheet == NONE:
drawer = 0
picking = 0
s_clear(query)
elif msg == OPEN_APP:
launch(comps[arg]) launch(comps[arg])
reset() close_all()
elif msg == OPEN_FIRST: elif msg == OPEN_FIRST:
i = first_match() i = first_match()
if i >= 0 and s_len(query) > 0: if i >= 0 and s_len(query) > 0:
launch(comps[i]) launch(comps[i])
reset() close_all()
elif msg == EDIT: elif msg == OPEN_HOME:
editing = 1 - editing launch(hstr[arg])
elif msg == PIN: elif msg == ADD_HOME:
toggle_pin(arg) haptic()
add_app(arg)
elif msg == TOGGLE_HOME:
i = home_of(arg)
if i >= 0:
remove_slot(i)
elif nh < HOME_CAP:
push_slot(APP, s_dup(comps[arg]), 0, 0)
elif msg == MENU:
haptic()
sheet = SHEET_MENU
elif msg == ITEM_MENU:
haptic()
item = arg
sheet = SHEET_ITEM
elif msg == WIDGET_MENU:
i = slot_of_widget(arg)
if i >= 0 and drawer == 0:
item = i
sheet = SHEET_ITEM
elif msg == CLOSE_SHEET:
sheet = NONE
item = -1
elif msg == PICK_APPS:
sheet = NONE
drawer = 1
picking = 1
elif msg == PICK_WIDGET:
sheet = SHEET_WIDGETS
wloading = 1
pending = http_get("widgets.json", WIDGETS_LOADED)
elif msg == CHOOSE_WIDGET:
if nh < HOME_CAP:
chosen = arg
add_widget(wprovs[arg])
else:
say("The home screen is full")
sheet = NONE
elif msg == WIDGET_ADDED:
if chosen >= 0 and nh < HOME_CAP:
push_slot(WIDGET, s_dup(wlabels[chosen]), arg, wheights[chosen])
chosen = -1
elif msg == REMOVE:
remove_slot(arg)
sheet = NONE
item = -1
elif msg == MOVE:
if arg > 0:
swap_slots(arg, arg - 1)
sheet = NONE
item = -1
elif msg == INFO: elif msg == INFO:
app_info(comps[arg]) app_info(hstr[arg])
sheet = NONE
elif msg == SETTINGS: elif msg == SETTINGS:
open_settings() open_settings()
sheet = NONE
elif msg == WALLPAPER: elif msg == WALLPAPER:
pick_wallpaper() pick_wallpaper()
sheet = NONE
elif msg == NOTICE_DONE:
if arg == notice_gen:
s_clear(notice)
elif msg == TICK: elif msg == TICK:
clock_time(now) clock_time(now)
clock_date(today) clock_date(today)
@@ -236,73 +473,72 @@ def update(msg: i32, arg: i32) -> None:
elif msg == RELOAD: elif msg == RELOAD:
pending = http_get("apps.json", LOADED) pending = http_get("apps.json", LOADED)
elif msg == HOME: elif msg == HOME:
reset() close_all()
elif msg == BACK: elif msg == BACK:
if editing == 1 or s_len(query) > 0: if sheet != NONE:
reset() sheet = NONE
item = -1
elif drawer == 1:
drawer = 0
picking = 0
s_clear(query)
# ---- View # ---- View
def view_icon(i: i32) -> None: def view_icon(h: i32) -> None:
el("img") el("img")
cls("icon") cls("icon")
attr("alt", "") attr("alt", "")
attr("loading", "lazy") attr("draggable", "false")
attr_ref("src", icons[i]) attr_ref("src", h)
end() end()
def view_tile(i: i32) -> None: def view_home_slot(i: i32) -> None:
row: i32
if hkind[i] == WIDGET:
el("li") el("li")
key(i + 1) key(hkey[i])
cls("widget-slot")
s_set(scratch, "height:")
s_add_num(scratch, hh[i])
s_add(scratch, "px")
attr_ref("style", scratch)
# The native widget view is laid over slots marked live, so only mark
# them while nothing covers the home screen.
if drawer == 0 and sheet == NONE:
attr_num("data-wid", hwid[i])
on_longpress(ITEM_MENU, i)
el("span")
cls("widget-label")
text_ref(hstr[i])
end()
end()
return
row = app_of(hstr[i])
if row < 0:
return
el("li")
key(hkey[i])
cls("tile") cls("tile")
cls_if("pinned", editing == 1 and pin_of(i) >= 0) on_click(OPEN_HOME, i)
on_click(OPEN, i) on_longpress(ITEM_MENU, i)
view_icon(i) view_icon(icons[row])
el("span") el("span")
cls("name") cls("name")
text_ref(labels[i]) text_ref(labels[row])
end()
if editing == 1:
el("button")
cls("info")
attr("aria-label", "App info")
on_click(INFO, i)
text("i")
end() end()
end() end()
def view_dock() -> None: def view_home() -> None:
p: i32
i: i32 i: i32
el("nav")
cls("dock")
for p in range(npin):
i = app_of(p)
if i >= 0:
el("button")
key(p + 1)
cls("dock-app")
attr_ref("aria-label", labels[i])
on_click(OPEN, i)
view_icon(i)
end()
end()
def small_btn(s: str, msg: i32) -> None:
btn_open("ghost", msg, 0)
cls("sm")
text(s)
end()
def view() -> None:
i: i32
shown: i32 = 0
div("home") div("home")
cls_if("editing", editing == 1) on_longpress(MENU, 0)
el("button")
cls("pull")
attr("aria-label", "All apps")
on_click(OPEN_DRAWER, 0)
end()
el("header") el("header")
cls("clock") cls("clock")
@@ -314,24 +550,68 @@ def view() -> None:
end() end()
end() end()
div("search") el("ul")
cls("slots")
for i in range(nh):
view_home_slot(i)
end()
if nh == 0:
el("p")
cls("hint")
text("Swipe down for all apps. Long-press to add apps and widgets.")
end()
end()
def view_drawer() -> None:
i: i32
shown: i32 = 0
div("drawer")
cls_if("picking", picking == 1)
div("drawer-head")
input_open("Search apps", query, QUERY) input_open("Search apps", query, QUERY)
attr("type", "search") attr("type", "search")
attr("enterkeyhint", "go") attr("enterkeyhint", "go")
on_enter(OPEN_FIRST, 0) on_enter(OPEN_FIRST, 0)
on_escape(CLEAR, 0) on_escape(CLEAR, 0)
end() end()
btn_open("ghost", CLOSE_DRAWER, 0)
cls("sm")
if picking == 1:
text("Done")
else:
text("Close")
end()
end()
if picking == 1:
el("p")
cls("drawer-note")
text("Tap apps to add them to the home screen or take them off.")
end() end()
if s_len(err) > 0: if s_len(err) > 0:
alert("Could not list apps", "", "destructive") alert("Could not list apps", "", "destructive")
el("ul") el("ul")
cls("grid") cls("apps")
for i in range(n): for i in range(n):
if matches(i): if matches(i):
view_tile(i)
shown += 1 shown += 1
el("li")
key(i + 1)
cls("tile")
if picking == 1:
cls_if("on", home_of(i) >= 0)
on_click(TOGGLE_HOME, i)
else:
on_click(OPEN_APP, i)
on_longpress(ADD_HOME, i)
view_icon(icons[i])
el("span")
cls("name")
text_ref(labels[i])
end()
end()
end() end()
if loading == 1: if loading == 1:
el("p") el("p")
@@ -343,27 +623,96 @@ def view() -> None:
cls("empty") cls("empty")
text("No apps match.") text("No apps match.")
end() end()
if editing == 1:
el("p")
cls("hint")
text("Tap apps to pin them to the dock (up to 5).")
end() end()
div("bar")
if s_len(query) == 0: def sheet_btn(s: str, msg: i32, arg: i32) -> None:
view_dock() el("button")
div("actions") cls("sheet-item")
btn_open("ghost", EDIT, 0) on_click(msg, arg)
cls("sm") text(s)
if editing == 1: end()
text("Done")
def view_sheet() -> None:
i: i32
row: i32
el("div")
cls("sheet-overlay")
on_click(CLOSE_SHEET, 0)
end()
el("div")
cls("sheet")
attr("role", "dialog")
attr("aria-modal", "true")
on_escape(CLOSE_SHEET, 0)
if sheet == SHEET_MENU:
el("h2")
cls("sheet-title")
text("Home screen")
end()
sheet_btn("Add apps", PICK_APPS, 0)
sheet_btn("Add widget", PICK_WIDGET, 0)
sheet_btn("Wallpaper", WALLPAPER, 0)
sheet_btn("Settings", SETTINGS, 0)
elif sheet == SHEET_ITEM and item >= 0:
el("h2")
cls("sheet-title")
if hkind[item] == WIDGET:
text_ref(hstr[item])
else: else:
text("Edit dock") row = app_of(hstr[item])
if row >= 0:
text_ref(labels[row])
end()
if item > 0:
sheet_btn("Move earlier", MOVE, item)
if item < nh - 1:
sheet_btn("Move later", MOVE, item + 1)
if hkind[item] == APP:
sheet_btn("App info", INFO, item)
sheet_btn("Remove from home", REMOVE, item)
else:
sheet_btn("Remove widget", REMOVE, item)
elif sheet == SHEET_WIDGETS:
el("h2")
cls("sheet-title")
text("Add a widget")
end()
if wloading == 1:
el("p")
cls("empty")
text("Loading widgets…")
end()
elif nw == 0:
el("p")
cls("empty")
text("No widgets installed.")
end()
el("ul")
cls("widget-list")
for i in range(nw):
el("li")
key(i + 1)
on_click(CHOOSE_WIDGET, i)
view_icon(wicons[i])
el("span")
text_ref(wlabels[i])
end()
end() end()
small_btn("Wallpaper", WALLPAPER)
small_btn("Settings", SETTINGS)
end() end()
end() end()
def view() -> None:
view_home()
if drawer == 1:
view_drawer()
if sheet != NONE:
view_sheet()
if s_len(notice) > 0:
el("div")
cls("notice")
attr("role", "status")
text_ref(notice)
end() end()
BIN
View File
Binary file not shown.
+50 -4
View File
@@ -13,18 +13,24 @@
<script type="module"> <script type="module">
import { mount } from "./ultra.js"; import { mount } from "./ultra.js";
// On a phone, MainActivity.java adds window.Android and serves apps.json. // On a phone, MainActivity.java adds window.Android, serves apps.json and
// In a desktop browser the demo apps.json is served and these stand-ins run. // widgets.json, and draws widgets over the slots reported by place().
// In a desktop browser the demo JSON files are served and these stand-ins run.
const toast = (s) => { const toast = (s) => {
const t = document.getElementById("toast"); const t = document.getElementById("toast");
t.textContent = s; t.classList.add("show"); t.textContent = s; t.classList.add("show");
clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove("show"), 1600); clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove("show"), 1600);
}; };
let demoWidget = 100;
const host = window.Android || { const host = window.Android || {
launch: (c) => toast("Open " + c), launch: (c) => toast("Open " + c),
appInfo: (c) => toast("App info for " + c), appInfo: (c) => toast("App info for " + c),
addWidget: () => setTimeout(() => window.ultraHome.widgetAdded(demoWidget++), 0),
removeWidget: () => {},
placeWidgets: () => {},
openSettings: () => toast("Open system settings"), openSettings: () => toast("Open system settings"),
pickWallpaper: () => toast("Pick a wallpaper"), pickWallpaper: () => toast("Pick a wallpaper"),
haptic: () => navigator.vibrate?.(10),
is24Hour: () => false, is24Hour: () => false,
}; };
if (!window.Android) document.documentElement.classList.add("demo"); if (!window.Android) document.documentElement.classList.add("demo");
@@ -37,26 +43,66 @@
}; };
formats(); formats();
// Tell the shell where the live widget slots are (CSS px, viewport-relative).
let placed = "";
const place = () => {
const slots = [...document.querySelectorAll(".widget-slot[data-wid]")].map((s) => {
const r = s.getBoundingClientRect();
return [+s.dataset.wid, Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)];
});
const j = JSON.stringify(slots);
if (j !== placed) { placed = j; host.placeWidgets(j); }
};
const app = await mount("#app", "./app.wasm", { const app = await mount("#app", "./app.wasm", {
onRender: place,
imports: ({ strs }) => ({ imports: ({ strs }) => ({
launch: (h) => host.launch(strs[h]), launch: (h) => host.launch(strs[h]),
app_info: (h) => host.appInfo(strs[h]), app_info: (h) => host.appInfo(strs[h]),
add_widget: (h) => host.addWidget(strs[h]),
remove_widget: (id) => host.removeWidget(id),
open_settings: () => host.openSettings(), open_settings: () => host.openSettings(),
pick_wallpaper: () => host.pickWallpaper(), pick_wallpaper: () => host.pickWallpaper(),
haptic: () => host.haptic(),
clock_time: (h) => { strs[h] = fmtTime.format(new Date()).replace(/\s?[AP]M$/i, ""); }, clock_time: (h) => { strs[h] = fmtTime.format(new Date()).replace(/\s?[AP]M$/i, ""); },
clock_date: (h) => { strs[h] = fmtDate.format(new Date()); }, clock_date: (h) => { strs[h] = fmtDate.format(new Date()); },
}), }),
}); });
// Messages the native side sends (keep in sync with app.py). // Messages the shell and the gestures below send (keep in sync with app.py).
const TICK = 11, RELOAD = 12, HOME = 13, BACK = 14; const TICK = 1, RELOAD = 2, HOME = 3, BACK = 4, SWIPE_DOWN = 5, SWIPE_UP = 6,
WIDGET_ADDED = 7, WIDGET_MENU = 8;
window.ultraHome = { window.ultraHome = {
tick: () => { formats(); app.dispatch(TICK, 1); }, tick: () => { formats(); app.dispatch(TICK, 1); },
reload: () => app.dispatch(RELOAD, 0), reload: () => app.dispatch(RELOAD, 0),
home: () => { app.dispatch(HOME, 0); window.scrollTo({ top: 0, behavior: "smooth" }); }, home: () => { app.dispatch(HOME, 0); window.scrollTo({ top: 0, behavior: "smooth" }); },
back: () => app.dispatch(BACK, 0), back: () => app.dispatch(BACK, 0),
widgetAdded: (id) => app.dispatch(WIDGET_ADDED, id),
widgetMenu: (id) => app.dispatch(WIDGET_MENU, id),
place: () => { placed = ""; place(); },
}; };
document.addEventListener("visibilitychange", () => { if (!document.hidden) window.ultraHome.tick(); }); document.addEventListener("visibilitychange", () => { if (!document.hidden) window.ultraHome.tick(); });
addEventListener("scroll", () => requestAnimationFrame(place), { passive: true });
addEventListener("resize", () => requestAnimationFrame(place));
// Swipe down on the home screen opens the drawer; swipe up closes it once its
// list is scrolled to the end (or doesn't scroll).
let start = null;
addEventListener("touchstart", (e) => {
const t = e.touches[0];
start = e.touches.length === 1 ? { x: t.clientX, y: t.clientY, at: Date.now() } : null;
}, { passive: true });
addEventListener("touchend", (e) => {
if (!start) return;
const t = e.changedTouches[0], dx = t.clientX - start.x, dy = t.clientY - start.y;
const quick = Date.now() - start.at < 700;
start = null;
if (!quick || Math.abs(dy) < 60 || Math.abs(dx) > Math.abs(dy)) return;
if (document.querySelector(".sheet")) return;
const list = document.querySelector(".drawer .apps");
if (dy > 0 && !list && window.scrollY <= 0) app.dispatch(SWIPE_DOWN, 0);
else if (dy < 0 && list && list.scrollTop + list.clientHeight >= list.scrollHeight - 2) app.dispatch(SWIPE_UP, 0);
}, { passive: true });
</script> </script>
</body> </body>
</html> </html>
+75 -40
View File
@@ -1,66 +1,101 @@
/* Home screen layout; the components come from ui.css. The page is transparent so the /* Home screen layout; the components come from ui.css. The page is transparent so the
system wallpaper shows through the WebView. MainActivity sets --inset-top and system wallpaper shows through the WebView. MainActivity sets --inset-top and
--inset-bottom to the status and navigation bar heights. */ --inset-bottom to the status and navigation bar (and keyboard) heights. */
:root { :root {
--top: var(--inset-top, env(safe-area-inset-top, 0px)); --top: var(--inset-top, env(safe-area-inset-top, 0px));
--bottom: var(--inset-bottom, env(safe-area-inset-bottom, 0px)); --bottom: var(--inset-bottom, env(safe-area-inset-bottom, 0px));
--shadow-text: 0 1px 4px rgb(0 0 0 / .6);
} }
html, body { background: transparent; } html, body { background: transparent; }
html.demo { background: linear-gradient(160deg, #1e293b, #4c1d95 55%, #0f172a) fixed; } html.demo { background: linear-gradient(160deg, #1e293b, #4c1d95 55%, #0f172a) fixed; }
body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: transparent; body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: transparent;
user-select: none; overscroll-behavior: none; } user-select: none; -webkit-user-select: none; -webkit-touch-callout: none;
overscroll-behavior: none; }
#app { max-width: 560px; margin: 0 auto; } #app { max-width: 560px; margin: 0 auto; }
.home { min-height: 100vh; display: flex; flex-direction: column; box-sizing: border-box; /* ---- home */
padding: calc(var(--top) + 2.5rem) 16px calc(var(--bottom) + 7.5rem); } .home { min-height: 100vh; box-sizing: border-box;
padding: calc(var(--top) + 2.5rem) 16px calc(var(--bottom) + 2rem); }
.pull { position: fixed; top: calc(var(--top) + .4rem); left: 50%; transform: translateX(-50%);
width: 3rem; height: 1.25rem; padding: 0; border: 0; background: none; cursor: pointer; }
.pull::before { content: ""; display: block; width: 2.25rem; height: .3rem; margin: auto;
border-radius: 999px; background: rgb(255 255 255 / .45); }
.clock { text-align: center; text-shadow: 0 1px 8px rgb(0 0 0 / .45); margin-bottom: 1.5rem; } .clock { text-align: center; text-shadow: 0 1px 8px rgb(0 0 0 / .45); margin-bottom: 2rem; }
.clock .time { font-size: 4rem; font-weight: 200; line-height: 1; letter-spacing: -.02em; .clock .time { font-size: 4rem; font-weight: 200; line-height: 1; letter-spacing: -.02em;
font-variant-numeric: tabular-nums; } font-variant-numeric: tabular-nums; }
.clock .date { margin-top: .5rem; font-size: 1rem; opacity: .9; } .clock .date { margin-top: .5rem; font-size: 1rem; opacity: .9; }
.search { margin-bottom: 1.25rem; } .slots, .apps { list-style: none; margin: 0; padding: 0; display: grid; gap: 1.25rem .5rem;
.search .input { height: 2.75rem; border-radius: 999px; padding: 0 1.25rem; font-size: 1rem;
background: rgb(0 0 0 / .35); border-color: rgb(255 255 255 / .15); color: #fff;
backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); }
.search .input::placeholder { color: rgb(255 255 255 / .65); }
.search .input::-webkit-search-cancel-button { filter: invert(1); }
.grid { list-style: none; margin: 0; padding: 0; display: grid; gap: 1.25rem .5rem;
grid-template-columns: repeat(4, minmax(0, 1fr)); } grid-template-columns: repeat(4, minmax(0, 1fr)); }
@media (min-width: 480px) { .grid { grid-template-columns: repeat(5, minmax(0, 1fr)); } } @media (min-width: 480px) { .slots, .apps { grid-template-columns: repeat(5, minmax(0, 1fr)); } }
.tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: .4rem; .tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: .4rem;
padding: .35rem .15rem; border-radius: calc(var(--radius) + 4px); cursor: pointer; } padding: .35rem .15rem; border-radius: calc(var(--radius) + 4px); cursor: pointer; }
.tile:active { background: rgb(255 255 255 / .12); } .tile:active { background: rgb(255 255 255 / .12); }
.icon { width: 3.25rem; height: 3.25rem; object-fit: contain; pointer-events: none; .icon { width: 3.25rem; height: 3.25rem; object-fit: contain; pointer-events: none;
filter: drop-shadow(0 2px 4px rgb(0 0 0 / .3)); } filter: drop-shadow(0 2px 4px rgb(0 0 0 / .3)); }
.name { max-width: 100%; font-size: .75rem; line-height: 1.2; text-align: center; .name { max-width: 100%; font-size: .75rem; line-height: 1.2; text-align: center;
text-shadow: 0 1px 4px rgb(0 0 0 / .6); overflow: hidden; text-overflow: ellipsis; text-shadow: var(--shadow-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
white-space: nowrap; }
.editing .tile { animation: wiggle .3s ease-in-out infinite alternate; }
.editing .tile.pinned { background: rgb(255 255 255 / .18); outline: 2px solid rgb(255 255 255 / .6); }
.info { position: absolute; top: -.2rem; right: .15rem; width: 1.4rem; height: 1.4rem; padding: 0;
border: 0; border-radius: 999px; background: #fff; color: #111; font: italic 600 .8rem/1 serif;
box-shadow: 0 1px 3px rgb(0 0 0 / .4); }
@keyframes wiggle { from { transform: rotate(-1.2deg); } to { transform: rotate(1.2deg); } }
@media (prefers-reduced-motion: reduce) { .editing .tile { animation: none; } }
.empty, .hint { text-align: center; opacity: .85; text-shadow: 0 1px 4px rgb(0 0 0 / .6); } /* A widget takes a whole row. On a phone the native widget view covers the slot;
.hint { font-size: .875rem; margin-top: 1.25rem; } the label only shows while the slot is not live (or in a desktop browser). */
.widget-slot { grid-column: 1 / -1; display: grid; place-items: center; box-sizing: border-box;
border-radius: 1.25rem; background: rgb(255 255 255 / .1);
border: 1px dashed rgb(255 255 255 / .3); }
.widget-label { font-size: .875rem; opacity: .75; text-shadow: var(--shadow-text); }
.bar { position: fixed; left: 0; right: 0; bottom: 0; display: grid; gap: .5rem; justify-items: center; .hint, .empty { text-align: center; opacity: .85; text-shadow: var(--shadow-text); }
padding: .75rem 16px calc(var(--bottom) + .5rem); .hint { margin-top: 30vh; padding: 0 2rem; font-size: .9rem; line-height: 1.5; }
background: linear-gradient(to top, rgb(0 0 0 / .45), transparent); }
.dock { display: flex; gap: 1rem; padding: .6rem 1rem; border-radius: 1.75rem;
background: rgb(255 255 255 / .14); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); }
.dock:empty { display: none; }
.dock-app { padding: 0; border: 0; background: none; cursor: pointer; }
.dock-app:active { transform: scale(.92); }
.actions { display: flex; gap: .25rem; }
.actions .btn.ghost { color: #fff; text-shadow: 0 1px 4px rgb(0 0 0 / .6); }
.actions .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; }
#toast { position: fixed; left: 50%; bottom: calc(var(--bottom) + 9rem); transform: translate(-50%, 1rem); /* ---- drawer: slides down over the home screen */
padding: .5rem 1rem; border-radius: 999px; background: rgb(0 0 0 / .8); color: #fff; .drawer { position: fixed; inset: 0; z-index: 10; display: flex; flex-direction: column;
font-size: .875rem; opacity: 0; transition: opacity .2s, transform .2s; pointer-events: none; } padding: calc(var(--top) + 1rem) 16px 0; background: rgb(10 10 14 / .72);
#toast.show { opacity: 1; transform: translate(-50%, 0); } backdrop-filter: blur(24px); -webkit-backdrop-filter: blur(24px);
animation: drop .22s cubic-bezier(.2, .8, .2, 1); }
@keyframes drop { from { transform: translateY(-100%); } to { transform: none; } }
.drawer-head { display: flex; gap: .5rem; align-items: center; margin-bottom: 1rem; }
.drawer-head .input { flex: 1; height: 2.75rem; border-radius: 999px; padding: 0 1.25rem; font-size: 1rem;
background: rgb(255 255 255 / .1); border-color: rgb(255 255 255 / .15); color: #fff; }
.drawer-head .input::placeholder { color: rgb(255 255 255 / .6); }
.drawer-head .input::-webkit-search-cancel-button { filter: invert(1); }
.drawer-head .btn.ghost { color: #fff; }
.drawer-head .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; }
.drawer-note { margin: 0 0 1rem; font-size: .875rem; opacity: .8; text-align: center; }
.drawer .apps { flex: 1; overflow-y: auto; align-content: start;
padding-bottom: calc(var(--bottom) + 1.5rem); overscroll-behavior: contain; }
.drawer .empty { flex: 1; }
.picking .tile::after { content: ""; position: absolute; top: .1rem; right: .6rem; width: 1.25rem; height: 1.25rem;
border-radius: 999px; border: 2px solid #fff; box-sizing: border-box;
background: rgb(0 0 0 / .35); }
.picking .tile.on::after { content: "✓"; display: grid; place-items: center; font-size: .75rem; font-weight: 700;
background: #fff; color: #111; }
/* ---- sheets (long-press menus, widget picker) */
.sheet-overlay { position: fixed; inset: 0; z-index: 20; background: rgb(0 0 0 / .45); animation: ui-fade .15s; }
.sheet { position: fixed; left: 0; right: 0; bottom: 0; z-index: 21; max-width: 560px; margin: 0 auto;
max-height: 70vh; overflow-y: auto; box-sizing: border-box;
padding: .75rem 1rem calc(var(--bottom) + 1rem); border-radius: 1.25rem 1.25rem 0 0;
background: var(--popover); color: var(--popover-foreground);
animation: rise .2s cubic-bezier(.2, .8, .2, 1); }
.sheet::before { content: ""; display: block; width: 2.25rem; height: .3rem; margin: 0 auto .75rem;
border-radius: 999px; background: var(--border); }
@keyframes rise { from { transform: translateY(100%); } to { transform: none; } }
.sheet-title { margin: 0 .5rem .5rem; font-size: 1rem; font-weight: 600; }
.sheet-item { display: block; width: 100%; padding: .85rem .5rem; border: 0; border-radius: var(--radius);
background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
.sheet-item:hover, .sheet-item:active { background: var(--accent); }
.sheet .empty { text-shadow: none; color: var(--muted-foreground); }
.widget-list { list-style: none; margin: 0; padding: 0; display: grid; }
.widget-list li { display: flex; align-items: center; gap: .75rem; padding: .5rem; border-radius: var(--radius);
cursor: pointer; }
.widget-list li:hover, .widget-list li:active { background: var(--accent); }
.widget-list .icon { width: 2.5rem; height: 2.5rem; filter: none; }
.notice, #toast { position: fixed; left: 50%; bottom: calc(var(--bottom) + 2rem); z-index: 30;
transform: translateX(-50%); padding: .5rem 1rem; border-radius: 999px;
background: rgb(0 0 0 / .8); color: #fff; font-size: .875rem; white-space: nowrap;
pointer-events: none; animation: ui-fade .15s; }
#toast { opacity: 0; transition: opacity .2s; animation: none; }
#toast.show { opacity: 1; }
@media (prefers-reduced-motion: reduce) { .drawer, .sheet { animation: none; } }
+23
View File
@@ -124,6 +124,7 @@ export async function mount(root, url, opts = {}) {
on_input: (m) => setEv("input", [m, EVENT]), on_input: (m) => setEv("input", [m, EVENT]),
on_enter: (m, a) => setEv("enter", [m, a]), on_enter: (m, a) => setEv("enter", [m, a]),
on_escape: (m, a) => setEv("escape", [m, a]), on_escape: (m, a) => setEv("escape", [m, a]),
on_longpress: (m, a) => setEv("longpress", [m, a]),
after: (ms, m, a) => setTimeout(() => dispatch(m, a), ms), after: (ms, m, a) => setTimeout(() => dispatch(m, a), ms),
frame: (m, a) => { frameQ.push(m, a); schedule(); }, frame: (m, a) => { frameQ.push(m, a); schedule(); },
@@ -380,6 +381,28 @@ export async function mount(root, url, opts = {}) {
on("keydown", "enter", (e) => e.key === "Enter" && !e.isComposing); on("keydown", "enter", (e) => e.key === "Enter" && !e.isComposing);
on("keydown", "escape", (e) => e.key === "Escape"); on("keydown", "escape", (e) => e.key === "Escape");
// Long press: hold a pointer still for 500 ms. The click that ends the press is
// swallowed, and the browser's own context menu is suppressed where a handler exists.
let press = null, pressed = false;
const unpress = () => { if (press) { clearTimeout(press.t); press = null; } };
root.addEventListener("pointerdown", (e) => {
pressed = false;
unpress();
if (e.button > 0) return;
const h = find(e.target, "longpress");
if (!h) return;
press = { x: e.clientX, y: e.clientY,
t: setTimeout(() => { press = null; pressed = true; dispatch(h[0], h[1]); }, 500) };
});
root.addEventListener("pointermove", (e) => {
if (press && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 10) unpress();
});
for (const t of ["pointerup", "pointercancel", "pointerleave"]) root.addEventListener(t, unpress);
root.addEventListener("click", (e) => {
if (pressed) { pressed = false; e.stopImmediatePropagation(); e.preventDefault(); }
}, true);
root.addEventListener("contextmenu", (e) => { if (find(e.target, "longpress")) e.preventDefault(); });
// Run module-level code (which calls init()), then first render. // Run module-level code (which calls init()), then first render.
ex.__main__global_stmts(); ex.__main__global_stmts();
render(); render();
+28
View File
@@ -0,0 +1,28 @@
{
"widgets": [
{
"label": "Clock",
"provider": "com.example.clock/.Widget",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%230ea5e9%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E",
"h": 140
},
{
"label": "Weather",
"provider": "com.example.weather/.Widget",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%2338bdf8%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E",
"h": 120
},
{
"label": "Calendar",
"provider": "com.example.calendar/.Widget",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%233b82f6%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E",
"h": 200
},
{
"label": "Music",
"provider": "com.example.music/.Widget",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%23ec4899%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E",
"h": 110
}
]
}