Rewrite the launcher in MoonBit (old code moves to legacy/) (#1)
Launcher / test (push) Successful in 1m20s
Launcher / apk (push) Successful in 37s

This commit was merged in pull request #1.
This commit is contained in:
nandi committed 2026-11-23 01:57:10 +00:00
1 parent 7d2bf5996f
commit 2fa7bd745b
150 files changed
+8319 -462

No files matched your search

@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 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:supportsRtl="true">
<activity
android:name=".MainActivity"
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>
@@ -0,0 +1,946 @@
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. The UI is the ultra app in web/ (LPython compiled
* to wasm), packaged as assets and served to a transparent WebView from a virtual https
* origin. This class answers the two dynamic URLs the app fetches:
*
* 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, addWidget, removeWidget, placeWidgets,
* widgetLimits, excludeGestures, openSettings, pickWallpaper, openRecents, checkUpdates,
* haptic)
* for the app's @jscall imports and index.html.
*
* 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.ultraHome.reload() / home() / back() / widgetAdded(id) /
* widgetMenu(id).
*
* Updater keeps the launcher itself up to date from the launcher-latest release.
*/
public class MainActivity 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();
Updater.check(this, false);
}
@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.ultraHome && ultraHome." + 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.ultraHome && ultraHome.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.ultraIcons && ultraIcons(" + 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(MainActivity a) { super(a, HOST_ID); }
@Override
protected AppWidgetHostView onCreateView(Context context, int id, AppWidgetProviderInfo info) {
return new WidgetView((MainActivity) 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 MainActivity 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(MainActivity 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(() -> 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));
}
/** 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 MainActivity.this.widgetLimits(id);
}
@JavascriptInterface public void excludeGestures(String json) {
main.post(() -> MainActivity.this.excludeGestures(json));
}
@JavascriptInterface public void loadIcons(String keys) {
MainActivity.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(MainActivity.this::openRecents);
}
@JavascriptInterface public void checkUpdates() {
Updater.check(MainActivity.this, true);
}
}
// ------------------------------------------------------------ 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,178 @@
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.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONObject;
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;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Updates the launcher from the rolling "launcher-latest" GitHub prerelease. CI uploads
* version.json ({"versionCode": N, "commit": SHA}) next to ultra-launcher.apk, with N the
* workflow run number, which is also the APK's versionCode. When N is newer than the installed
* build, the APK is streamed into a PackageInstaller session and committed. Android then asks
* the user to confirm (or, on Android 12+ once this app installed itself, may not ask at all).
*
* The home screen checks on start at most every CHECK_EVERY; the home menu's
* "Check for updates" checks now and reports what it found.
*/
final class Updater {
static final String BASE = "https://github.com/codegod100/launcher/releases/download/launcher-latest/";
static final long CHECK_EVERY = 6 * 60 * 60 * 1000L;
static final String EXTRA_VERSION = "dev.ultra.launcher.VERSION";
private static final AtomicBoolean busy = new AtomicBoolean();
private static final Handler main = new Handler(Looper.getMainLooper());
private Updater() {}
private static SharedPreferences prefs(Context c) {
return c.getSharedPreferences("updater", Context.MODE_PRIVATE);
}
/** Check in the background; manual checks always run and say what happened. */
static void check(Context ctx, boolean manual) {
Context c = ctx.getApplicationContext();
long now = System.currentTimeMillis();
if (!manual && now - prefs(c).getLong("lastCheck", 0) < CHECK_EVERY) return;
if (!busy.compareAndSet(false, true)) {
if (manual) toast(c, "Already checking for updates");
return;
}
prefs(c).edit().putLong("lastCheck", now).apply();
if (manual) toast(c, "Checking for updates…");
new Thread(() -> {
try {
run(c, manual);
} catch (Exception e) {
Log.w("ultra", "update check", e);
if (manual) toast(c, "Couldn't check for updates");
} finally {
busy.set(false);
}
}, "updater").start();
}
private static void run(Context c, boolean manual) throws Exception {
JSONObject v = new JSONObject(new String(get(BASE + "version.json"), StandardCharsets.UTF_8));
long latest = v.getLong("versionCode");
long installed = installedVersion(c);
if (latest <= installed) {
if (manual) toast(c, "ultra Home is up to date (build " + installed + ")");
return;
}
// An install the user cancelled isn't offered again until there is a newer one, or they ask.
if (!manual && latest == prefs(c).getLong("declined", -1)) return;
toast(c, "Downloading launcher update (build " + latest + ")…");
install(c, latest);
}
@SuppressWarnings("deprecation")
static long installedVersion(Context c) throws PackageManager.NameNotFoundException {
PackageInfo p = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
return Build.VERSION.SDK_INT >= 28 ? p.getLongVersionCode() : p.versionCode;
}
private static void install(Context c, long 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(BASE + "ultra-launcher.apk");
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, 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); // github.com redirects assets to its download host
int code = conn.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
conn.disconnect();
throw new IOException("HTTP " + code + " for " + url);
}
return conn;
}
private static byte[] get(String url) throws IOException {
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);
return out.toByteArray();
} finally {
conn.disconnect();
}
}
static void toast(Context c, String msg) {
main.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" />