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

+11
View File
@@ -0,0 +1,11 @@
__pycache__/
node_modules/
.pixi/
android/.gradle/
android/build/
android/app/build/
android/local.properties
build/
build-*/
android-wasm/target/
android-wasm/assets/*.wasm
+41
View File
@@ -0,0 +1,41 @@
> **This is the previous implementation.** The launcher is now written in MoonBit at the repository root (see the top-level README). This folder keeps the ultra WebView build (`web/`, `android/`), the Qt rewrite (`qt/`) and the experiments (`wasi/`, `android-wasm/`) with paths fixed so they still build from here; nothing in it is maintained beyond that. Its CI runs only by hand (`.gitea/workflows/legacy.yml`, `.github/workflows/legacy.yml`).
# ultra launcher
An Android home screen written as an [ultra](https://github.com/nandi-conda/ultra) app (LPython compiled to WebAssembly, Elm-style). The home starts blank (add a clock widget if you want one): long-press it to add apps (the drawer opens in a pick mode) or widgets, and long-press anything on it to drag it somewhere else; let go without moving to get its menu, or, for a widget, handles on its edges that resize it to the grid. Swipe down for the drawer with every app and a search (Enter opens the first match); long-press an app there for its menu (add to home, app info, uninstall; system apps have no uninstall), and swipe up to close it. The panel at the top has a **Windows** button that opens Recents. The layout is saved in localStorage.
## Install
Releases now come from the MoonBit build at the repository root; see the top-level README. Open it once, press Home, and pick **ultra Home** as the default. Builds are signed with the committed `android/app/debug.keystore`, so each one installs over the last.
The **Windows** button uses an accessibility service (`RecentsService`, which only performs the Recents action). Enable it once under Settings → Accessibility; on Android 13+ a sideloaded APK may first need App info → ⋮ → Allow restricted settings.
## Layout
- `web/` is the UI: `app.py` is the ultra app and `app.wasm` its committed build, with `index.html`, `style.css` and the `ultra.js` / `ui.css` runtime the build copies in. `apps.json` and `widgets.json` are demo data for desktop browsers.
- `android/` is a small native shell (Java, no dependencies) that serves `web/` to a transparent WebView over the wallpaper. It answers `apps.json` from `LauncherApps` and `widgets.json` from the installed widget providers, hands icons to the page through the `window.Android` bridge, and draws real `AppWidgetHostView`s over the slots the page reports.
- The ultra framework comes from the `ultra` conda package on [prefix.dev/nandi-testing](https://prefix.dev/channels/nandi-testing), which pixi installs.
- `tests/e2e.cjs` is a Playwright test of the browser demo.
## Build
```sh
pixi run build # web/app.py -> web/app.wasm
pixi run install-playwright && pixi run test
cd android && ./gradlew assembleDebug # needs JDK 17 and the Android SDK
```
`pixi run serve` serves `web/` on http://localhost:8000. In a desktop browser the launcher runs against the demo JSON files, shows a toast instead of launching, and draws widgets as labelled placeholders. Click the bar at the top to open the drawer.
Every push to ultra's main publishes a new `ultra` package. To pick it up, run `pixi update ultra`, rebuild, and commit the rebuilt `web/` files.
## Qt rewrite (in progress)
`qt/` is the launcher rewritten as a Qt Quick (QML) app for Android, replacing ultra and the WebView. `qt/qml` is the UI (`Main.qml`, with the grid packing in `Layout.js`), `qt/src` a thin C++ backend, and `qt/android` the Java side (`HomeActivity`, a `QtActivity` that lists apps, draws icons, launches, and hosts the native widget views over the QML slots). It uses the same package (`dev.ultra.launcher`) and key as the WebView build, so it installs over it, from the releases on the Gitea forge ([experiments/launcher](https://git.site.latha.org/experiments/launcher)), where `.gitea/workflows/launcher.yml` tests, builds and publishes an APK on every push to main (`ci/gitea-apk.sh`); the installed app updates itself from the latest release there.
```sh
node qt/tests/layout.test.mjs # grid packing
cmake -S qt -B build && cmake --build build # desktop build, needs Qt 6.8+
build/ultrahome # try it against the demo apps
QT_QPA_PLATFORM=offscreen build/ultrahome_e2e # end-to-end test of the UI
```
+2137
View File
File diff suppressed because it is too large. Load diff
+64
View File
@@ -0,0 +1,64 @@
[package]
name = "ultra-launcher-wasm"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
crate-type = ["cdylib"]
path = "src/lib.rs"
[dependencies]
android-activity = { version = "0.6", features = ["native-activity"] }
android_logger = "0.14"
base64 = "0.22"
jni = "0.21"
log = "0.4"
ndk = "0.9"
sha2 = "0.10"
wasmtime = { version = "50", default-features = false, features = ["component-model", "cranelift", "runtime", "std"] }
wasmtime-wasi = "50"
[profile.release]
opt-level = 3
debug = false
lto = "thin"
codegen-units = 16
strip = true
[package.metadata.android]
package = "dev.ultra.launcher.wasm"
apk_name = "ultra-launcher-wasm"
build_targets = ["aarch64-linux-android"]
resources = "res"
assets = "assets"
[package.metadata.android.sdk]
min_sdk_version = 30
target_sdk_version = 35
[package.metadata.android.application]
label = "ultra Wasm"
icon = "@mipmap/ic_launcher"
theme = "@style/HomeWasm"
extract_native_libs = true
has_code = true
[package.metadata.android.application.activity]
name = "dev.ultra.launcher.wasm.LauncherActivity"
config_changes = "orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation|mcc|mnc|density"
launch_mode = "singleTask"
state_not_needed = true
clear_task_on_launch = true
exclude_from_recents = true
orientation = "unspecified"
[[package.metadata.android.application.activity.intent_filter]]
actions = ["android.intent.action.MAIN"]
categories = ["android.intent.category.HOME", "android.intent.category.DEFAULT", "android.intent.category.LAUNCHER"]
[[package.metadata.android.uses_permission]]
name = "android.permission.REQUEST_DELETE_PACKAGES"
[[package.metadata.android.uses_permission]]
name = "android.permission.QUERY_ALL_PACKAGES"
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
if [ -z "${ANDROID_HOME:-}" ] || [ ! -d "$ANDROID_HOME/ndk" ]; then
export ANDROID_HOME="/home/nandi/Android/Sdk"
fi
export ANDROID_SDK_ROOT="$ANDROID_HOME"
if [ -z "${ANDROID_NDK_ROOT:-}" ]; then
ANDROID_NDK_ROOT=$(ls -1d "$ANDROID_HOME/ndk/"* | tail -n 1)
export ANDROID_NDK_ROOT
fi
BUILD_TOOLS=$(ls -1d "$ANDROID_HOME/build-tools/"* | tail -n 1)
PLATFORM=$(ls -1d "$ANDROID_HOME/platforms/"* | tail -n 1)
KEYSTORE="${CARGO_APK_RELEASE_KEYSTORE:-$PWD/../android/app/debug.keystore}"
export CARGO_APK_RELEASE_KEYSTORE="$KEYSTORE"
export CARGO_APK_RELEASE_KEYSTORE_PASSWORD="${CARGO_APK_RELEASE_KEYSTORE_PASSWORD:-android}"
cargo apk build --release
apk="target/release/apk/ultra-launcher-wasm.apk"
manifest="target/release/apk/AndroidManifest.xml"
work="target/java-build"
rm -rf "$work"
mkdir -p "$work/classes" "$work/dex" "$work/res"
python3 - "$manifest" "$work/AndroidManifest.xml" <<'PY'
import sys
src, dst = sys.argv[1], sys.argv[2]
xml = open(src, "r", encoding="utf-8").read()
service = """ <service
android:name="dev.ultra.launcher.wasm.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>
"""
if "dev.ultra.launcher.wasm.RecentsService" not in xml:
xml = xml.replace("</application>", service + " </application>")
open(dst, "w", encoding="utf-8").write(xml)
PY
"$BUILD_TOOLS/aapt2" compile --dir res -o "$work/res.zip"
"$BUILD_TOOLS/aapt2" link \
--manifest "$work/AndroidManifest.xml" \
-I "$PLATFORM/android.jar" \
"$work/res.zip" \
-o "$work/res.apk" \
--auto-add-overlay
javac --release 11 -classpath "$PLATFORM/android.jar" \
-d "$work/classes" \
java/dev/ultra/launcher/wasm/LauncherActivity.java \
java/dev/ultra/launcher/wasm/RecentsService.java
"$BUILD_TOOLS/d8" --min-api 30 --output "$work/dex" \
$(find "$work/classes" -name '*.class')
python3 - "$apk" "$work/res.apk" "$work/dex/classes.dex" "$work/unaligned.apk" <<'PY'
import sys, zipfile
src, res_apk, dex, dst = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
with zipfile.ZipFile(src, "r") as zsrc, \
zipfile.ZipFile(res_apk, "r") as zres, \
zipfile.ZipFile(dst, "w") as zout:
for info in zres.infolist():
if info.filename == "resources.arsc":
zout.writestr(info, zres.read(info.filename), compress_type=zipfile.ZIP_STORED)
else:
zout.writestr(info, zres.read(info.filename))
for info in zsrc.infolist():
if (info.filename.startswith("META-INF/")
or info.filename == "classes.dex"
or info.filename == "AndroidManifest.xml"
or info.filename == "resources.arsc"
or info.filename.startswith("res/")):
continue
zout.writestr(info, zsrc.read(info.filename))
zout.write(dex, "classes.dex", compress_type=zipfile.ZIP_DEFLATED)
PY
"$BUILD_TOOLS/zipalign" -f -p 4 "$work/unaligned.apk" "$work/aligned.apk"
"$BUILD_TOOLS/apksigner" sign \
--ks "$KEYSTORE" --ks-pass pass:android --key-pass pass:android --ks-key-alias androiddebugkey \
--out "$apk" "$work/aligned.apk"
echo "Built $PWD/$apk ($(stat -c%s "$apk") bytes)"
@@ -0,0 +1,694 @@
package dev.ultra.launcher.wasm;
import android.app.NativeActivity;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
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.PixelFormat;
import android.graphics.drawable.ColorDrawable;
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.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SizeF;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.text.Collator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class LauncherActivity extends NativeActivity {
private static final String TAG = "ultra-wasm";
static {
System.loadLibrary("ultra_launcher_wasm");
}
private static native void nativeOnEvent(String event);
private static native void nativeOnInsets(int top, int bottom);
private final Handler main = new Handler(Looper.getMainLooper());
private LauncherApps launcher;
private final UserHandle user = Process.myUserHandle();
private final Map<String, LauncherActivityInfo> activities = new ConcurrentHashMap<>();
private final Object iconLock = new Object();
private static final int WIDGET_HOST_ID = 369;
private static final int REQ_BIND_WIDGET = 101;
private static final int REQ_CONFIGURE_WIDGET = 102;
private AppWidgetManager widgets;
private AppWidgetHost widgetHost;
private FrameLayout widgetLayer;
private final Map<Integer, AppWidgetHostView> widgetViews = new HashMap<>();
private final Map<Integer, Long> widgetSizes = new HashMap<>();
private final int[] layerAt = new int[2];
private int pendingWidget = -1;
private String pendingProvider = "";
private EditText searchInput;
private boolean suppressSearchWatch = false;
private final LauncherApps.Callback packages = new LauncherApps.Callback() {
@Override public void onPackageRemoved(String pkg, UserHandle u) { appsChanged(pkg); }
@Override public void onPackageAdded(String pkg, UserHandle u) { appsChanged(pkg); }
@Override public void onPackageChanged(String pkg, UserHandle u) { appsChanged(pkg); }
@Override public void onPackagesAvailable(String[] pkgs, UserHandle u, boolean replacing) {
appsChanged(String.join(",", pkgs));
}
@Override public void onPackagesUnavailable(String[] pkgs, UserHandle u, boolean replacing) {
appsChanged(String.join(",", pkgs));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFormat(PixelFormat.TRANSLUCENT);
super.onCreate(savedInstanceState);
launcher = getSystemService(LauncherApps.class);
launcher.registerCallback(packages, main);
widgets = AppWidgetManager.getInstance(this);
widgetHost = new AppWidgetHost(this, WIDGET_HOST_ID) {
@Override
protected AppWidgetHostView onCreateView(android.content.Context context, int appWidgetId,
AppWidgetProviderInfo appWidget) {
return new DraggableWidgetView(appWidgetId);
}
};
widgetLayer = new FrameLayout(this);
searchInput = new EditText(this);
searchInput.setAlpha(0f);
searchInput.setBackgroundColor(Color.TRANSPARENT);
searchInput.setTextColor(Color.TRANSPARENT);
searchInput.setCursorVisible(false);
searchInput.setSingleLine(true);
searchInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
searchInput.setImeOptions(EditorInfo.IME_ACTION_GO);
searchInput.setFocusable(false);
searchInput.setFocusableInTouchMode(false);
searchInput.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) {
if (!suppressSearchWatch) {
nativeOnEvent("search:" + s.toString());
}
}
});
searchInput.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_DONE
|| (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
&& event.getAction() == KeyEvent.ACTION_DOWN)) {
nativeOnEvent("search-submit");
return true;
}
return false;
});
getWindow().addContentView(searchInput, new ViewGroup.LayoutParams(1, 1));
seeThrough();
getWindow().getDecorView().setOnApplyWindowInsetsListener((v, insets) -> {
onInsets(insets);
return v.onApplyWindowInsets(insets);
});
getWindow().getDecorView().requestApplyInsets();
}
@Override
protected void onStart() {
super.onStart();
if (widgetHost != null) widgetHost.startListening();
}
@Override
protected void onStop() {
super.onStop();
if (widgetHost != null) {
try { widgetHost.stopListening(); } catch (RuntimeException ignored) { }
}
}
private void seeThrough() {
Window w = getWindow();
w.setFormat(PixelFormat.TRANSLUCENT);
w.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
w.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
w.setStatusBarColor(Color.TRANSPARENT);
w.setNavigationBarColor(Color.TRANSPARENT);
if (Build.VERSION.SDK_INT >= 30) {
w.setDecorFitsSystemWindows(false);
}
}
private void onInsets(WindowInsets 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();
}
nativeOnInsets(top, bottom);
nativeOnEvent("insets");
}
@Override
protected void onDestroy() {
if (launcher != null) launcher.unregisterCallback(packages);
super.onDestroy();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
nativeOnEvent("home");
}
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (e.getAction() == KeyEvent.ACTION_UP && !e.isCanceled()) {
nativeOnEvent("back");
}
return true;
}
return super.dispatchKeyEvent(e);
}
private void appsChanged(String pkgs) {
if (pkgs != null && !pkgs.isEmpty()) {
for (String pkg : pkgs.split(",")) {
if (pkg.isEmpty()) continue;
String prefix = pkg + "/";
activities.keySet().removeIf(k -> k.startsWith(prefix));
}
}
nativeOnEvent("apps-changed:" + (pkgs == null ? "" : pkgs));
}
// ---- Called from Rust via JNI ----
public String apps() {
try {
List<LauncherActivityInfo> list = new ArrayList<>(launcher.getActivityList(null, user));
Map<LauncherActivityInfo, String> labels = new HashMap<>();
for (LauncherActivityInfo i : list) labels.put(i, String.valueOf(i.getLabel()));
Collator by = Collator.getInstance();
list.sort((x, y) -> by.compare(labels.get(x), labels.get(y)));
JSONArray out = new JSONArray();
Set<String> seen = new HashSet<>();
for (LauncherActivityInfo i : list) {
ComponentName cn = i.getComponentName();
if (cn.getPackageName().equals(getPackageName())) continue;
String c = cn.flattenToShortString();
seen.add(c);
activities.put(c, i);
JSONObject o = new JSONObject().put("label", labels.get(i)).put("component", c);
if ((i.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) != 0) o.put("system", true);
out.put(o);
}
activities.keySet().retainAll(seen);
return new JSONObject().put("apps", out).toString();
} catch (JSONException | RuntimeException e) {
Log.w(TAG, "listing apps", e);
return "{\"apps\":[]}";
}
}
public byte[] icon(String key, int size) {
if (key == null || key.length() < 3) return null;
size = Math.max(16, Math.min(size, 512));
File f = iconFile(key, size);
if (f != null && f.length() == (long) size * size * 4) {
try {
return Files.readAllBytes(f.toPath());
} catch (java.io.IOException e) {
f.delete();
}
}
byte[] px;
synchronized (iconLock) {
try {
Drawable d = appIcon(key.substring(2));
px = d == null ? null : toPixels(d, size);
} catch (RuntimeException | OutOfMemoryError e) {
Log.w(TAG, "icon for " + key, e);
return null;
}
}
if (px != null && f != null) {
File tmp = new File(f.getPath() + ".tmp");
try (FileOutputStream out = new FileOutputStream(tmp)) {
out.write(px);
} catch (java.io.IOException e) {
tmp.delete();
tmp = null;
}
if (tmp != null && !tmp.renameTo(f)) tmp.delete();
}
return px;
}
private File iconFile(String key, int size) {
try {
String pkg = key.substring(2).split("/", 2)[0];
long stamp = getPackageManager().getPackageInfo(pkg, 0).lastUpdateTime;
String id = "v2|" + key + "|" + size + "|" + stamp + "|" + getResources().getDisplayMetrics().densityDpi;
byte[] h = MessageDigest.getInstance("SHA-1").digest(id.getBytes(java.nio.charset.StandardCharsets.UTF_8));
StringBuilder name = new StringBuilder();
for (byte b : h) name.append(String.format("%02x", b));
File dir = new File(getCacheDir(), "icons");
if (!dir.isDirectory() && !dir.mkdirs()) return null;
return new File(dir, name.toString());
} catch (Exception e) {
return null;
}
}
private Drawable appIcon(String c) {
ComponentName cn = ComponentName.unflattenFromString(c);
if (cn == null) return null;
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) return null;
Drawable d = info.getIcon(getResources().getDisplayMetrics().densityDpi);
return d != null ? d : getPackageManager().getDefaultActivityIcon();
}
private static byte[] toPixels(Drawable d, int size) {
d = d.mutate();
Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
d.setBounds(0, 0, size, size);
d.draw(new Canvas(bmp));
ByteBuffer buf = ByteBuffer.allocate(size * size * 4);
bmp.copyPixelsToBuffer(buf);
bmp.recycle();
return buf.array();
}
public void launch(String component) {
main.post(() -> {
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();
}
});
}
public void appInfo(String component) {
main.post(() -> {
ComponentName cn = ComponentName.unflattenFromString(component);
if (cn != null) launcher.startAppDetailsActivity(cn, user, null, null);
});
}
public void uninstall(String component) {
main.post(() -> {
ComponentName cn = ComponentName.unflattenFromString(component);
if (cn != null) {
try {
startActivity(new Intent(Intent.ACTION_DELETE,
Uri.fromParts("package", cn.getPackageName(), null))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Not available", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openSettings() {
main.post(() -> startActivity(new Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)));
}
public void pickWallpaper() {
main.post(() -> startActivity(Intent.createChooser(
new Intent(Intent.ACTION_SET_WALLPAPER), "Wallpaper").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)));
}
public void openRecents() {
main.post(() -> {
if (RecentsService.showRecents()) return;
Toast.makeText(this, "Turn on \"ultra Wasm window list\" 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);
try {
startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
.putExtra(":settings:fragment_args_key", me)
.putExtra(":settings:show_fragment_args", args)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Not available on this device", Toast.LENGTH_SHORT).show();
}
});
}
public void haptic() {
main.post(() -> getWindow().getDecorView().performHapticFeedback(
HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING));
}
public void setTextInput(boolean active) {
main.post(() -> {
InputMethodManager imm = getSystemService(InputMethodManager.class);
if (imm == null || searchInput == null) return;
if (active) {
searchInput.setFocusable(true);
searchInput.setFocusableInTouchMode(true);
searchInput.requestFocus();
imm.showSoftInput(searchInput, InputMethodManager.SHOW_IMPLICIT);
} else {
imm.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
suppressSearchWatch = true;
searchInput.setText("");
suppressSearchWatch = false;
searchInput.clearFocus();
searchInput.setFocusableInTouchMode(false);
searchInput.setFocusable(false);
}
});
}
public String widgetProviders() {
JSONArray out = new JSONArray();
PackageManager pm = getPackageManager();
for (AppWidgetProviderInfo info : widgets.getInstalledProvidersForProfile(user)) {
if (info.provider == null) continue;
JSONObject o = new JSONObject();
try {
o.put("provider", info.provider.flattenToString());
o.put("label", info.loadLabel(pm));
o.put("w", Math.max(1, Math.min(5, (info.minWidth + 69) / 70)));
o.put("h", Math.max(1, Math.min(5, (info.minHeight + 69) / 70)));
out.put(o);
} catch (JSONException ignored) {
}
}
return out.toString();
}
public void addWidget(String provider) {
main.post(() -> {
ComponentName cn = ComponentName.unflattenFromString(provider);
if (cn == null) return;
AppWidgetProviderInfo target = null;
for (AppWidgetProviderInfo info : widgets.getInstalledProvidersForProfile(user)) {
if (cn.equals(info.provider)) { target = info; break; }
}
if (target == null) return;
int id = widgetHost.allocateAppWidgetId();
pendingWidget = id;
pendingProvider = provider;
if (widgets.bindAppWidgetIdIfAllowed(id, user, target.provider, null)) {
configureWidget(id);
} else {
Intent i = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, target.provider)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, user);
try {
startActivityForResult(i, REQ_BIND_WIDGET);
} catch (ActivityNotFoundException e) {
dropPendingWidget();
}
}
});
}
private void configureWidget(int id) {
AppWidgetProviderInfo w = widgets.getAppWidgetInfo(id);
if (w != null && w.configure != null) {
try {
widgetHost.startAppWidgetConfigureActivityForResult(this, id, 0, REQ_CONFIGURE_WIDGET, null);
return;
} catch (ActivityNotFoundException | SecurityException ignored) {
}
}
finishPendingWidget(id);
}
private void finishPendingWidget(int id) {
String prov = pendingProvider;
pendingWidget = -1;
pendingProvider = "";
nativeOnEvent("widget-added:" + id + ":" + prov);
}
private void dropPendingWidget() {
if (pendingWidget != -1) widgetHost.deleteAppWidgetId(pendingWidget);
pendingWidget = -1;
pendingProvider = "";
}
@Override
protected void onActivityResult(int req, int result, Intent data) {
super.onActivityResult(req, result, data);
if (pendingWidget == -1 || (req != REQ_BIND_WIDGET && req != REQ_CONFIGURE_WIDGET)) return;
if (result != RESULT_OK) {
dropPendingWidget();
} else if (req == REQ_BIND_WIDGET) {
configureWidget(pendingWidget);
} else {
finishPendingWidget(pendingWidget);
}
}
private boolean widgetsVisible = true;
private String lastPlacedWidgetsJson = "[]";
public void removeWidget(int id) {
main.post(() -> {
AppWidgetHostView v = widgetViews.remove(id);
if (v != null && v.isAttachedToWindow()) {
try { getWindowManager().removeViewImmediate(v); } catch (RuntimeException ignored) { }
}
widgetSizes.remove(id);
widgetHost.deleteAppWidgetId(id);
});
}
public void setWidgetsVisible(boolean visible) {
main.post(() -> {
widgetsVisible = visible;
for (AppWidgetHostView v : widgetViews.values()) {
v.setVisibility(visible ? View.VISIBLE : View.GONE);
}
});
}
private final class DraggableWidgetView extends AppWidgetHostView {
private final int widgetId;
private final int touchSlop;
private boolean lifted = false;
private float downRawX, downRawY, lastRawX, lastRawY;
private int startWinX, startWinY;
private final Runnable longPress;
DraggableWidgetView(int widgetId) {
super(LauncherActivity.this);
this.widgetId = widgetId;
this.touchSlop = ViewConfiguration.get(LauncherActivity.this).getScaledTouchSlop();
this.longPress = () -> {
lifted = true;
requestDisallowInterceptTouchEvent(true);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
setAlpha(0.88f);
setScaleX(1.04f);
setScaleY(1.04f);
WindowManager.LayoutParams lp = (WindowManager.LayoutParams) getLayoutParams();
startWinX = lp.x;
startWinY = lp.y;
nativeOnEvent("widget-lift:" + this.widgetId + ":" + startWinX + ":" + startWinY);
};
}
boolean isLifted() { return lifted; }
private void handleMove(MotionEvent ev) {
lastRawX = ev.getRawX();
lastRawY = ev.getRawY();
if (lifted) {
WindowManager.LayoutParams lp = (WindowManager.LayoutParams) getLayoutParams();
int nx = Math.round(startWinX + (lastRawX - downRawX));
int ny = Math.round(startWinY + (lastRawY - downRawY));
if (nx != lp.x || ny != lp.y) {
lp.x = nx;
lp.y = ny;
getWindowManager().updateViewLayout(this, lp);
nativeOnEvent("widget-drag:" + nx + ":" + ny);
}
} else if (Math.hypot(lastRawX - downRawX, lastRawY - downRawY) > touchSlop) {
main.removeCallbacks(longPress);
}
}
private void handleEnd(MotionEvent ev) {
main.removeCallbacks(longPress);
if (lifted) {
lifted = false;
setAlpha(1.0f);
setScaleX(1.0f);
setScaleY(1.0f);
int finalX = Math.round(startWinX + (ev.getRawX() - downRawX));
int finalY = Math.round(startWinY + (ev.getRawY() - downRawY));
float dist = (float) Math.hypot(ev.getRawX() - downRawX, ev.getRawY() - downRawY);
nativeOnEvent("widget-drop:" + widgetId + ":" + finalX + ":" + finalY + ":" + dist);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
lifted = false;
downRawX = lastRawX = ev.getRawX();
downRawY = lastRawY = ev.getRawY();
main.removeCallbacks(longPress);
main.postDelayed(longPress, 450);
super.dispatchTouchEvent(ev);
return true;
case MotionEvent.ACTION_MOVE:
handleMove(ev);
if (lifted) return true;
return super.dispatchTouchEvent(ev);
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
boolean wasLifted = lifted;
handleEnd(ev);
if (wasLifted) return true;
return super.dispatchTouchEvent(ev);
}
return super.dispatchTouchEvent(ev);
}
}
public void placeWidgets(String json) {
main.post(() -> {
lastPlacedWidgetsJson = json;
if (getWindow().getDecorView().getWindowToken() == null) {
getWindow().getDecorView().post(() -> placeWidgets(lastPlacedWidgetsJson));
return;
}
float d = getResources().getDisplayMetrics().density;
Map<Integer, int[]> want = new HashMap<>();
try {
JSONArray arr = new JSONArray(json);
for (int i = 0; i < arr.length(); i++) {
JSONArray r = arr.getJSONArray(i);
want.put(r.getInt(0), new int[] {
r.getInt(1),
r.getInt(2),
r.getInt(3),
r.getInt(4)
});
}
} catch (JSONException e) {
return;
}
WindowManager wm = getWindowManager();
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();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
r[2],
r[3],
WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
lp.gravity = Gravity.TOP | Gravity.LEFT;
lp.x = r[0];
lp.y = r[1];
lp.token = getWindow().getDecorView().getWindowToken();
AppWidgetHostView v = widgetViews.get(id);
if (v instanceof DraggableWidgetView && ((DraggableWidgetView) v).isLifted()) {
continue;
}
if (v == null) {
AppWidgetProviderInfo info = widgets.getAppWidgetInfo(id);
if (info == null) continue;
v = widgetHost.createView(this, id, info);
widgetViews.put(id, v);
v.setVisibility(widgetsVisible ? View.VISIBLE : View.GONE);
wm.addView(v, lp);
} else {
v.setVisibility(widgetsVisible ? View.VISIBLE : View.GONE);
wm.updateViewLayout(v, lp);
}
int wdp = Math.round(r[2] / d), hdp = Math.round(r[3] / d);
long size = ((long) wdp << 32) | hdp;
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(wdp, hdp));
v.updateAppWidgetSize(new Bundle(), sizes);
} else {
v.updateAppWidgetSize(new Bundle(), wdp, hdp, wdp, hdp);
}
}
}
});
}
}
@@ -0,0 +1,38 @@
package dev.ultra.launcher.wasm;
import android.accessibilityservice.AccessibilityService;
import android.content.Intent;
import android.view.accessibility.AccessibilityEvent;
/**
* Accessibility service that opens Recents (the system's list of open windows)
* for the home screen's Windows button.
*/
public class RecentsService extends AccessibilityService {
private static volatile RecentsService running;
public 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() { }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="recents_service_label">ultra Wasm 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 Wasm 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>
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="HomeWasm" parent="@android:style/Theme.Wallpaper.NoTitleBar">
<item name="android:windowShowWallpaper">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
</style>
</resources>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityFlags="flagDefault"
android:canRetrieveWindowContent="false"
android:description="@string/recents_service_description"
android:summary="@string/recents_service_summary" />
+681
View File
@@ -0,0 +1,681 @@
use android_activity::input::{InputEvent, KeyAction, Keycode, MotionAction};
use android_activity::{AndroidApp, AndroidAppWaker, InputStatus, MainEvent, PollEvent};
use base64::Engine as _;
use jni::objects::{GlobalRef, JByteArray, JObject, JString, JValue};
use jni::sys::jint;
use jni::{JNIEnv, JavaVM};
use ndk::hardware_buffer_format::HardwareBufferFormat;
use ndk::native_window::NativeWindow;
use sha2::{Digest, Sha256};
use std::collections::VecDeque;
use std::ffi::CString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use wasmtime::component::{Component, HasSelf, Linker, ResourceTable};
use wasmtime::{Config, Engine, Store};
use wasmtime_wasi::{FsPerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
wasmtime::component::bindgen!({
path: "../wasi/wit",
world: "gui",
});
use latha::gui::types as wt;
const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
const MIN_FRAME: Duration = Duration::from_millis(16);
static EVENTS: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());
static WAKER: Mutex<Option<AndroidAppWaker>> = Mutex::new(None);
static INSET_TOP: AtomicU32 = AtomicU32::new(0);
static INSET_BOTTOM: AtomicU32 = AtomicU32::new(0);
#[no_mangle]
pub extern "system" fn Java_dev_ultra_launcher_wasm_LauncherActivity_nativeOnEvent(
mut env: JNIEnv,
_class: JObject,
event: JString,
) {
if let Ok(s) = env.get_string(&event) {
if let Ok(mut q) = EVENTS.lock() {
q.push_back(s.to_string_lossy().into_owned());
}
if let Ok(w) = WAKER.lock() {
if let Some(waker) = w.as_ref() {
waker.wake();
}
}
}
}
#[no_mangle]
pub extern "system" fn Java_dev_ultra_launcher_wasm_LauncherActivity_nativeOnInsets(
_env: JNIEnv,
_class: JObject,
top: jint,
bottom: jint,
) {
INSET_TOP.store(top.max(0) as u32, Ordering::Relaxed);
INSET_BOTTOM.store(bottom.max(0) as u32, Ordering::Relaxed);
}
struct HostState {
wasi: WasiCtx,
table: ResourceTable,
vm: JavaVM,
activity: GlobalRef,
frame_wanted: bool,
tick_at: Option<Instant>,
quit: Option<i32>,
clipboard: String,
primary: String,
dark: bool,
}
impl WasiView for HostState {
fn ctx(&mut self) -> WasiCtxView<'_> {
WasiCtxView {
ctx: &mut self.wasi,
table: &mut self.table,
}
}
}
impl HostState {
fn call_void(&self, method: &str, sig: &str, args: &[JValue]) {
if let Ok(mut env) = self.vm.attach_current_thread() {
if let Err(e) = env.call_method(&self.activity, method, sig, args) {
log::warn!("JNI {method} failed: {e}");
}
}
}
fn call_void_str(&self, method: &str, arg: &str) {
if let Ok(mut env) = self.vm.attach_current_thread() {
if let Ok(js) = env.new_string(arg) {
if let Err(e) = env.call_method(
&self.activity,
method,
"(Ljava/lang/String;)V",
&[JValue::Object(&js)],
) {
log::warn!("JNI {method}({arg}) failed: {e}");
}
}
}
}
}
impl latha::gui::host::Host for HostState {
fn request_frame(&mut self) {
self.frame_wanted = true;
}
fn request_tick(&mut self, delay_ms: u32) {
self.tick_at = Some(Instant::now() + Duration::from_millis(delay_ms as u64));
}
fn set_title(&mut self, title: String) {
log::info!("title: {title}");
}
fn set_cursor(&mut self, _shape: latha::gui::host::Cursor) {}
fn set_min_size(&mut self, _min: latha::gui::host::Size) {}
fn clipboard_text(&mut self) -> String {
self.clipboard.clone()
}
fn set_clipboard_text(&mut self, text: String) {
self.clipboard = text;
}
fn primary_text(&mut self) -> String {
self.primary.clone()
}
fn set_primary_text(&mut self, text: String) {
self.primary = text;
}
fn prefers_dark(&mut self) -> bool {
self.dark
}
fn accent_color(&mut self) -> Option<u32> {
None
}
fn bell(&mut self) {}
fn set_text_input(&mut self, active: bool) {
self.call_void("setTextInput", "(Z)V", &[JValue::Bool(active as u8)]);
}
fn open_url(&mut self, _url: String) -> bool {
false
}
fn quit(&mut self, code: i32) {
self.quit = Some(code);
}
}
impl ultra::launcher::android::Host for HostState {
fn apps(&mut self) -> String {
let Ok(mut env) = self.vm.attach_current_thread() else {
return "{\"apps\":[]}".to_owned();
};
let Ok(res) = env.call_method(&self.activity, "apps", "()Ljava/lang/String;", &[]) else {
return "{\"apps\":[]}".to_owned();
};
let Ok(obj) = res.l() else {
return "{\"apps\":[]}".to_owned();
};
let js: JString = obj.into();
env.get_string(&js)
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|_| "{\"apps\":[]}".to_owned())
}
fn icon(&mut self, key: String, size: u32) -> Option<String> {
let mut env = self.vm.attach_current_thread().ok()?;
let js = env.new_string(&key).ok()?;
let res = env
.call_method(
&self.activity,
"icon",
"(Ljava/lang/String;I)[B",
&[JValue::Object(&js), JValue::Int(size as jint)],
)
.ok()?;
let obj = res.l().ok()?;
if obj.is_null() {
return None;
}
let arr: JByteArray = obj.into();
let bytes = env.convert_byte_array(arr).ok()?;
Some(B64.encode(&bytes))
}
fn launch(&mut self, component: String) {
self.call_void_str("launch", &component);
}
fn app_info(&mut self, component: String) {
self.call_void_str("appInfo", &component);
}
fn uninstall(&mut self, component: String) {
self.call_void_str("uninstall", &component);
}
fn open_settings(&mut self) {
self.call_void("openSettings", "()V", &[]);
}
fn pick_wallpaper(&mut self) {
self.call_void("pickWallpaper", "()V", &[]);
}
fn open_recents(&mut self) {
self.call_void("openRecents", "()V", &[]);
}
fn haptic(&mut self) {
self.call_void("haptic", "()V", &[]);
}
fn insets(&mut self) -> (u32, u32) {
(
INSET_TOP.load(Ordering::Relaxed),
INSET_BOTTOM.load(Ordering::Relaxed),
)
}
fn poll_events(&mut self) -> Vec<String> {
let mut out = Vec::new();
if let Ok(mut q) = EVENTS.lock() {
while let Some(ev) = q.pop_front() {
out.push(ev);
}
}
out
}
fn widget_providers(&mut self) -> String {
let Ok(mut env) = self.vm.attach_current_thread() else {
return "[]".to_owned();
};
let Ok(res) = env.call_method(&self.activity, "widgetProviders", "()Ljava/lang/String;", &[]) else {
return "[]".to_owned();
};
let Ok(obj) = res.l() else {
return "[]".to_owned();
};
let js: JString = obj.into();
env.get_string(&js)
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|_| "[]".to_owned())
}
fn add_widget(&mut self, provider: String) {
self.call_void_str("addWidget", &provider);
}
fn remove_widget(&mut self, id: i32) {
self.call_void("removeWidget", "(I)V", &[JValue::Int(id as jint)]);
}
fn place_widgets(&mut self, json: String) {
self.call_void_str("placeWidgets", &json);
}
fn set_widgets_visible(&mut self, visible: bool) {
self.call_void(
"setWidgetsVisible",
"(Z)V",
&[JValue::Bool(if visible { 1 } else { 0 })],
);
}
}
struct FrameBuf {
width: u32,
height: u32,
pixels: Vec<u8>, // RGBA8888 premultiplied
}
impl FrameBuf {
fn new() -> Self {
Self {
width: 0,
height: 0,
pixels: Vec::new(),
}
}
fn resize(&mut self, w: u32, h: u32) {
if self.width != w || self.height != h {
self.width = w;
self.height = h;
self.pixels.resize((w as usize) * (h as usize) * 4, 0);
}
}
fn apply_damage(&mut self, store: &mut Store<HostState>, app: &Gui, dmg: &wt::Damage) {
let fw = self.width as i32;
let fh = self.height as i32;
for m in &dmg.moves {
let x0 = m.area.x.max(0);
let y0 = m.area.y.max(0);
let x1 = (m.area.x + m.area.width as i32).min(fw);
let y1 = (m.area.y + m.area.height as i32).min(fh);
if x1 <= x0 || y1 <= y0 {
continue;
}
let w = (x1 - x0) as usize;
let h = (y1 - y0) as usize;
let stride = (self.width as usize) * 4;
let mut tmp = vec![0u8; w * h * 4];
for row in 0..h {
let src_off = ((y0 as usize + row) * stride) + (x0 as usize) * 4;
tmp[row * w * 4..(row + 1) * w * 4]
.copy_from_slice(&self.pixels[src_off..src_off + w * 4]);
}
for row in 0..h {
let dy = y0 + row as i32 + m.dy;
if dy < 0 || dy >= fh {
continue;
}
for col in 0..w {
let dx = x0 + col as i32 + m.dx;
if dx < 0 || dx >= fw {
continue;
}
let dst_off = ((dy as usize) * stride) + (dx as usize) * 4;
let src_off = (row * w + col) * 4;
self.pixels[dst_off..dst_off + 4]
.copy_from_slice(&tmp[src_off..src_off + 4]);
}
}
}
for r in &dmg.rects {
if r.width == 0 || r.height == 0 {
continue;
}
let Ok(b64) = app.latha_gui_app().call_frame_pixels(&mut *store, *r) else {
continue;
};
let Ok(bgra) = B64.decode(b64.as_bytes()) else {
continue;
};
let rw = r.width as usize;
let rh = r.height as usize;
if bgra.len() < rw * rh * 4 {
continue;
}
let stride = (self.width as usize) * 4;
for row in 0..rh {
let py = r.y + row as i32;
if py < 0 || py >= fh {
continue;
}
for col in 0..rw {
let px = r.x + col as i32;
if px < 0 || px >= fw {
continue;
}
let src = (row * rw + col) * 4;
let dst = (py as usize) * stride + (px as usize) * 4;
// BGRA -> RGBA (premultiplied)
self.pixels[dst] = bgra[src + 2];
self.pixels[dst + 1] = bgra[src + 1];
self.pixels[dst + 2] = bgra[src];
self.pixels[dst + 3] = bgra[src + 3];
}
}
}
}
fn present(&self, win: &NativeWindow) {
if self.width == 0 || self.height == 0 {
return;
}
let _ = win.set_buffers_geometry(
self.width as i32,
self.height as i32,
Some(HardwareBufferFormat::R8G8B8A8_UNORM),
);
if let Ok(mut buf) = win.lock(None) {
let dst_stride = buf.stride() * 4;
let src_stride = (self.width as usize) * 4;
let ptr = buf.bits() as *mut u8;
for row in 0..(self.height as usize) {
unsafe {
std::ptr::copy_nonoverlapping(
self.pixels.as_ptr().add(row * src_stride),
ptr.add(row * dst_stride),
src_stride,
);
}
}
}
}
}
fn keycode_text(code: Keycode, shift: bool) -> String {
let ch = match code {
Keycode::A => Some(if shift { 'A' } else { 'a' }),
Keycode::B => Some(if shift { 'B' } else { 'b' }),
Keycode::C => Some(if shift { 'C' } else { 'c' }),
Keycode::D => Some(if shift { 'D' } else { 'd' }),
Keycode::E => Some(if shift { 'E' } else { 'e' }),
Keycode::F => Some(if shift { 'F' } else { 'f' }),
Keycode::G => Some(if shift { 'G' } else { 'g' }),
Keycode::H => Some(if shift { 'H' } else { 'h' }),
Keycode::I => Some(if shift { 'I' } else { 'i' }),
Keycode::J => Some(if shift { 'J' } else { 'j' }),
Keycode::K => Some(if shift { 'K' } else { 'k' }),
Keycode::L => Some(if shift { 'L' } else { 'l' }),
Keycode::M => Some(if shift { 'M' } else { 'm' }),
Keycode::N => Some(if shift { 'N' } else { 'n' }),
Keycode::O => Some(if shift { 'O' } else { 'o' }),
Keycode::P => Some(if shift { 'P' } else { 'p' }),
Keycode::Q => Some(if shift { 'Q' } else { 'q' }),
Keycode::R => Some(if shift { 'R' } else { 'r' }),
Keycode::S => Some(if shift { 'S' } else { 's' }),
Keycode::T => Some(if shift { 'T' } else { 't' }),
Keycode::U => Some(if shift { 'U' } else { 'u' }),
Keycode::V => Some(if shift { 'V' } else { 'v' }),
Keycode::W => Some(if shift { 'W' } else { 'w' }),
Keycode::X => Some(if shift { 'X' } else { 'x' }),
Keycode::Y => Some(if shift { 'Y' } else { 'y' }),
Keycode::Z => Some(if shift { 'Z' } else { 'z' }),
Keycode::Keycode0 => Some('0'),
Keycode::Keycode1 => Some('1'),
Keycode::Keycode2 => Some('2'),
Keycode::Keycode3 => Some('3'),
Keycode::Keycode4 => Some('4'),
Keycode::Keycode5 => Some('5'),
Keycode::Keycode6 => Some('6'),
Keycode::Keycode7 => Some('7'),
Keycode::Keycode8 => Some('8'),
Keycode::Keycode9 => Some('9'),
Keycode::Space => Some(' '),
Keycode::Period => Some('.'),
Keycode::Minus => Some(if shift { '_' } else { '-' }),
_ => None,
};
ch.map(|c| c.to_string()).unwrap_or_default()
}
fn load_wasm_bytes(app: &AndroidApp) -> Result<Vec<u8>, String> {
if let Some(ext) = app.external_data_path() {
let override_path = ext.join("launcher.wasm");
if let Ok(bytes) = std::fs::read(&override_path) {
log::info!("Loaded override wasm from {}", override_path.display());
return Ok(bytes);
}
}
let mgr = app.asset_manager();
let cname = CString::new("launcher.wasm").unwrap();
let mut asset = mgr
.open(&cname)
.ok_or_else(|| "assets/launcher.wasm not found".to_owned())?;
asset
.buffer()
.map(|b| b.to_vec())
.map_err(|e| format!("reading assets/launcher.wasm: {e}"))
}
fn load_component(engine: &Engine, app: &AndroidApp) -> Result<Component, String> {
let bytes = load_wasm_bytes(app)?;
let hash = format!("{:x}", Sha256::digest(&bytes));
let cache_dir = app
.internal_data_path()
.unwrap_or_else(|| PathBuf::from("/data/local/tmp"));
let cache_file = cache_dir.join(format!("launcher-{}.cwasm", &hash[..16]));
if let Ok(cwasm) = std::fs::read(&cache_file) {
if let Ok(comp) = unsafe { Component::deserialize(engine, &cwasm) } {
log::info!("Loaded cached AOT component {}", cache_file.display());
return Ok(comp);
}
}
let comp = Component::from_binary(engine, &bytes).map_err(|e| format!("compile wasm: {e}"))?;
if let Ok(serialized) = comp.serialize() {
let _ = std::fs::write(&cache_file, serialized);
}
Ok(comp)
}
#[no_mangle]
fn android_main(app: AndroidApp) {
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Info)
.with_tag("ultra-wasm"),
);
if let Ok(mut w) = WAKER.lock() {
*w = Some(app.create_waker());
}
let vm = unsafe { JavaVM::from_raw(app.vm_as_ptr() as *mut _) }.expect("JavaVM");
let activity = {
let env = vm.attach_current_thread().expect("JNI attach");
let obj = unsafe { JObject::from_raw(app.activity_as_ptr() as *mut _) };
env.new_global_ref(obj).expect("global ref")
};
let data_dir = app
.internal_data_path()
.unwrap_or_else(|| PathBuf::from("/data/local/tmp"));
let _ = std::fs::create_dir_all(&data_dir);
let mut cfg = Config::new();
cfg.wasm_component_model(true);
let engine = Engine::new(&cfg).expect("wasmtime engine");
let component = match load_component(&engine, &app) {
Ok(c) => c,
Err(e) => {
log::error!("Failed to load launcher.wasm: {e}");
return;
}
};
let mut linker: Linker<HostState> = Linker::new(&engine);
wasmtime_wasi::p2::add_to_linker_sync(&mut linker).expect("wasi p2 linker");
latha::gui::host::add_to_linker::<_, HasSelf<_>>(&mut linker, |s| s).expect("gui host linker");
ultra::launcher::android::add_to_linker::<_, HasSelf<_>>(&mut linker, |s| s)
.expect("android host linker");
let mut wasi_builder = WasiCtxBuilder::new();
wasi_builder.inherit_stdio();
wasi_builder.env("QT_QPA_PLATFORM", "qt2wasmgui");
wasi_builder.env("LATHA_GUI_TEXT_INPUT", "1");
let _ = wasi_builder.preopened_dir(&data_dir, "/data", FsPerms::ReadWrite);
let state = HostState {
wasi: wasi_builder.build(),
table: ResourceTable::new(),
vm,
activity,
frame_wanted: true,
tick_at: None,
quit: None,
clipboard: String::new(),
primary: String::new(),
dark: true,
};
let mut store = Store::new(&engine, state);
let gui = Gui::instantiate(&mut store, &component, &linker).expect("instantiate launcher");
if let Err(e) = gui
.latha_gui_app()
.call_start(&mut store, &["ultra-home".to_owned()])
{
log::error!("app.start failed: {e}");
return;
}
let mut fb = FrameBuf::new();
let mut last_paint = Instant::now() - MIN_FRAME;
let mut running = true;
while running && store.data().quit.is_none() {
let wait = store
.data()
.tick_at
.map(|t| t.saturating_duration_since(Instant::now()))
.unwrap_or(Duration::from_millis(50));
app.poll_events(Some(wait.min(Duration::from_millis(50))), |ev| match ev {
PollEvent::Main(MainEvent::Destroy) => running = false,
PollEvent::Main(MainEvent::InitWindow { .. })
| PollEvent::Main(MainEvent::WindowResized { .. }) => {
if let Some(win) = app.native_window() {
let w = win.width().max(1) as u32;
let h = win.height().max(1) as u32;
let scale = (app.config().density().unwrap_or(420) as f64) / 160.0;
fb.resize(w, h);
let _ = gui.latha_gui_app().call_resize(&mut store, w, h, scale);
store.data_mut().frame_wanted = true;
}
}
PollEvent::Main(MainEvent::GainedFocus) => {
let _ = gui.latha_gui_app().call_focus(&mut store, true);
}
PollEvent::Main(MainEvent::LostFocus) => {
let _ = gui.latha_gui_app().call_focus(&mut store, false);
}
PollEvent::Main(MainEvent::InputAvailable) => {
if let Ok(mut iter) = app.input_events_iter() {
loop {
let read = iter.next(|event| {
match event {
InputEvent::MotionEvent(me) => {
let p = me.pointer_at_index(0);
let x = p.x() as f64;
let y = p.y() as f64;
let kind = match me.action() {
MotionAction::Down => Some((
wt::PointerKind::Press,
wt::Button::Left,
wt::Buttons::LEFT,
)),
MotionAction::Up => Some((
wt::PointerKind::Release,
wt::Button::Left,
wt::Buttons::empty(),
)),
MotionAction::Move => Some((
wt::PointerKind::Move,
wt::Button::None,
wt::Buttons::LEFT,
)),
MotionAction::Cancel => Some((
wt::PointerKind::Leave,
wt::Button::None,
wt::Buttons::empty(),
)),
_ => None,
};
if let Some((kind, button, buttons)) = kind {
let pe = wt::PointerEvent {
kind,
button,
buttons,
modifiers: wt::Modifiers::empty(),
x,
y,
clicks: 1,
};
let _ = gui.latha_gui_app().call_pointer(&mut store, pe);
store.data_mut().frame_wanted = true;
}
InputStatus::Handled
}
InputEvent::KeyEvent(ke) => {
let pressed = ke.action() == KeyAction::Down;
let keysym = match ke.key_code() {
Keycode::Del => 0xff08,
Keycode::Enter => 0xff0d,
Keycode::Escape => 0xff1b,
_ => 0,
};
let text = if pressed {
keycode_text(ke.key_code(), ke.meta_state().shift_on())
} else {
String::new()
};
if keysym != 0 || !text.is_empty() {
let ev = wt::KeyEvent {
pressed,
repeat: ke.repeat_count() > 0,
keysym,
scancode: ke.scan_code() as u32,
modifiers: wt::Modifiers::empty(),
text,
};
let _ = gui.latha_gui_app().call_key(&mut store, &ev);
store.data_mut().frame_wanted = true;
}
InputStatus::Unhandled
}
_ => InputStatus::Unhandled,
}
});
if !read {
break;
}
}
}
}
_ => {}
});
let has_events = EVENTS.lock().map(|q| !q.is_empty()).unwrap_or(false);
let due = store
.data()
.tick_at
.map(|t| Instant::now() >= t)
.unwrap_or(false);
if due || has_events {
store.data_mut().tick_at = None;
if let Ok(next) = gui.latha_gui_app().call_tick(&mut store) {
if let Some(ms) = next {
store.data_mut().tick_at = Some(Instant::now() + Duration::from_millis(ms as u64));
}
}
}
if store.data().frame_wanted && last_paint.elapsed() >= MIN_FRAME {
store.data_mut().frame_wanted = false;
last_paint = Instant::now();
if let Some(win) = app.native_window() {
if let Ok(dmg) = gui.latha_gui_app().call_paint(&mut store) {
fb.apply_damage(&mut store, &gui, &dmg);
fb.present(&win);
}
}
}
}
}
+53
View File
@@ -0,0 +1,53 @@
plugins {
id "com.android.application"
}
android {
namespace "dev.ultra.launcher"
compileSdk 35
defaultConfig {
applicationId "dev.ultra.launcher"
minSdk 26
targetSdk 35
// CI passes -PversionCode=<workflow run number>; the in-app updater compares it
// with the versionCode in the launcher-latest release's version.json.
versionCode((project.findProperty("versionCode") ?: "1") as Integer)
versionName("0.1." + versionCode)
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
sourceSets {
// The home screen UI is the ultra app in web/, served from assets.
main.assets.srcDirs = ["$rootDir/../web"]
}
androidResources {
// app.py is the LPython source; apps.json and widgets.json are the browser demo's stand-ins.
ignoreAssetsPattern = "!app.py:!apps.json:!widgets.json:!__pycache__:!.*"
}
signingConfigs {
// One committed debug key, so every CI build installs over the last one.
// (A fresh runner would otherwise sign with a newly generated debug key.)
debug {
storeFile file("debug.keystore")
storePassword "android"
keyAlias "androiddebugkey"
keyPassword "android"
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
minifyEnabled false
}
}
}
Binary file not shown.
@@ -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" />
+3
View File
@@ -0,0 +1,3 @@
plugins {
id "com.android.application" version "8.7.3" apply false
}
+3
View File
@@ -0,0 +1,3 @@
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
android.useAndroidX=false
android.nonTransitiveRClass=true
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+16
View File
@@ -0,0 +1,16 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "ultra-launcher"
include ":app"
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env bash
# Tests the Qt launcher (qt/), builds its APK and publishes it as a Gitea release:
# build-<versionCode>, holding ultra-launcher.apk and version.json, made a draft first
# and published once both files are up, so the latest release never lacks them.
# Runs in .gitea/workflows/legacy.yml (JDK 17 container, as root), from legacy/; publishes only
# when LEGACY_PUBLISH=true, so it does not compete with the MoonBit build's releases.
set -euo pipefail
cd "$(dirname "$0")/.."
QT_VERSION=6.8.3
NDK=26.1.10909125
# Minutes since the epoch: always above the GitHub builds' run numbers and always rising.
VERSION_CODE=$(( $(date +%s) / 60 ))
COMMIT="${GITHUB_SHA:-$(git rev-parse HEAD)}"
echo "== tools"
apt-get update -qq
# The host Qt tools (moc, qmlimportscanner, qmlcachegen) need glib, GL and friends;
# g++ builds the desktop test and nodejs runs the layout test.
apt-get install -y -qq --no-install-recommends python3-pip python3-venv ninja-build cmake g++ nodejs unzip curl ca-certificates git \
libglib2.0-0t64 libgl1 libegl1 libopengl0 libgl-dev libglx-dev libopengl-dev libegl-dev libxkbcommon-dev \
libfontconfig1 libfreetype6 libxkbcommon0 libdbus-1-3 >/dev/null
python3 -m venv /opt/aqt && /opt/aqt/bin/pip install -q aqtinstall
echo "== Qt $QT_VERSION (android arm64 + host)"
/opt/aqt/bin/aqt install-qt linux android "$QT_VERSION" android_arm64_v8a -O /opt/Qt --autodesktop >/dev/null
QT_ROOT=/opt/Qt/$QT_VERSION/android_arm64_v8a
QT_HOST=/opt/Qt/$QT_VERSION/gcc_64
echo "== tests (desktop Qt)"
node qt/tests/layout.test.mjs
cmake -S qt -B build-desktop -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$QT_HOST"
cmake --build build-desktop
QT_QPA_PLATFORM=offscreen build-desktop/ultrahome_e2e
echo "== Android SDK + NDK $NDK"
export ANDROID_SDK_ROOT=/opt/android-sdk
mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools"
curl -fsSL -o /tmp/cmdline.zip https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
unzip -q /tmp/cmdline.zip -d "$ANDROID_SDK_ROOT/cmdline-tools" && mv "$ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools" "$ANDROID_SDK_ROOT/cmdline-tools/latest"
yes | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null || true
"$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --install "platform-tools" "ndk;$NDK" "platforms;android-35" "build-tools;35.0.0" >/dev/null
export ANDROID_NDK_ROOT=$ANDROID_SDK_ROOT/ndk/$NDK
echo "== build (versionCode $VERSION_CODE)"
# Signed with the committed key, like every earlier build, so it installs over them.
export QT_ANDROID_KEYSTORE_PATH="$PWD/android/app/debug.keystore"
export QT_ANDROID_KEYSTORE_ALIAS=androiddebugkey
export QT_ANDROID_KEYSTORE_STORE_PASS=android
export QT_ANDROID_KEYSTORE_KEY_PASS=android
"$QT_ROOT/bin/qt-cmake" -S qt -B build-android -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DANDROID_SDK_ROOT="$ANDROID_SDK_ROOT" -DANDROID_NDK_ROOT="$ANDROID_NDK_ROOT" \
-DQT_HOST_PATH="$QT_HOST" -DQT_ANDROID_SIGN_APK=ON -DVERSION_CODE="$VERSION_CODE"
cmake --build build-android --target apk
apk=$(find build-android -name "*-signed.apk" | head -1)
test -n "$apk" || { find build-android -name "*.apk"; exit 1; }
cp "$apk" ultra-launcher.apk
printf '{"versionCode": %s, "commit": "%s"}\n' "$VERSION_CODE" "$COMMIT" > version.json
if [ "${LEGACY_PUBLISH:-false}" != "true" ]; then
echo "built legacy/ultra-launcher.apk; not publishing (LEGACY_PUBLISH != true)"
exit 0
fi
echo "== release build-$VERSION_CODE"
server="${GITHUB_SERVER_URL:-https://git.site.latha.org}"
repo="${GITHUB_REPOSITORY:-experiments/launcher}"
api="${server%/}/api/v1/repos/$repo"
token="${GITEA_TOKEN:-${GITHUB_TOKEN:-}}"
test -n "$token" || { echo "no GITEA_TOKEN/GITHUB_TOKEN in the environment"; exit 1; }
auth=(-H "Authorization: token $token")
tag="build-$VERSION_CODE"
id=$(curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X POST "$api/releases" \
-d "{\"tag_name\": \"$tag\", \"name\": \"ultra Home build $VERSION_CODE\", \"target_commitish\": \"$COMMIT\", \"draft\": true, \"body\": \"Qt launcher built from $COMMIT.\"}" \
| python3 -c 'import sys, json; print(json.load(sys.stdin)["id"])')
curl -fsS "${auth[@]}" -F "attachment=@ultra-launcher.apk" "$api/releases/$id/assets?name=ultra-launcher.apk" >/dev/null
curl -fsS "${auth[@]}" -F "attachment=@version.json" "$api/releases/$id/assets?name=version.json" >/dev/null
curl -fsS "${auth[@]}" -H "Content-Type: application/json" -X PATCH "$api/releases/$id" -d '{"draft": false}' >/dev/null
echo "published $tag to $server/$repo"
+17
View File
@@ -0,0 +1,17 @@
[workspace]
name = "launcher"
description = "Android home-screen launcher written as an ultra app (LPython -> wasm)"
channels = ["https://conda.anaconda.org/conda-forge", "https://prefix.dev/nandi-testing"]
platforms = ["linux-64", "osx-64", "osx-arm64", "win-64"]
# ultra (the framework and its `ultra` build CLI, with lpython) comes from prefix.dev/nandi-testing.
[dependencies]
python = "3.12.*"
ultra = ">=0.1.19"
nodejs = ">=22"
[tasks]
build = { cmd = "ultra build web/app.py", description = "Compile web/app.py to web/app.wasm" }
serve = { cmd = "ultra serve web", description = "Serve the launcher's browser demo on http://localhost:8000" }
install-playwright = { cmd = "npm install --no-save --no-package-lock playwright@1.56.1 && npx playwright install chromium", description = "Fetch Playwright and Chromium for the browser test" }
test = { cmd = "python tests/run.py", depends-on = ["build"], description = "Build, then run the browser test against a local server" }
+67
View File
@@ -0,0 +1,67 @@
cmake_minimum_required(VERSION 3.21)
project(ultrahome VERSION 0.2 LANGUAGES CXX)
# The ultra launcher, as a Qt Quick app. qt/qml is the UI; qt/src is a thin C++ backend
# over HomeActivity.java (qt/android), which does what only Android can.
# desktop: cmake -S qt -B build && cmake --build build && build/ultrahome
# android: qt-cmake -S qt -B build -DANDROID_SDK_ROOT=... -DANDROID_NDK_ROOT=...
# cmake --build build --target apk
set(VERSION_CODE 1 CACHE STRING "Android versionCode (CI passes the workflow run number)")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 6.8 REQUIRED COMPONENTS Quick)
if(NOT ANDROID)
find_package(Qt6 6.8 COMPONENTS Test)
endif()
qt_standard_project_setup(REQUIRES 6.8)
# The UI and the backend, as a static QML module both the app and its test link.
qt_add_library(launcher_ui STATIC
src/backend.cpp src/backend.h
src/iconprovider.cpp src/iconprovider.h
)
target_include_directories(launcher_ui PUBLIC src)
qt_add_qml_module(launcher_ui
URI Launcher
VERSION 1.0
QML_FILES
qml/Main.qml
qml/Layout.js
qml/AppIcon.qml
qml/Tile.qml
qml/Drawer.qml
qml/Sheet.qml
qml/SheetButton.qml
qml/SearchField.qml
qml/PillButton.qml
RESOURCES
demo/apps.json
demo/widgets.json
)
target_link_libraries(launcher_ui PUBLIC Qt6::Quick)
qt_add_executable(ultrahome src/main.cpp)
target_link_libraries(ultrahome PRIVATE launcher_uiplugin launcher_ui Qt6::Quick)
set_target_properties(ultrahome PROPERTIES
QT_ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android"
QT_ANDROID_PACKAGE_NAME "dev.ultra.launcher"
QT_ANDROID_VERSION_CODE "${VERSION_CODE}"
QT_ANDROID_VERSION_NAME "0.2.${VERSION_CODE}"
QT_ANDROID_MIN_SDK_VERSION 28
QT_ANDROID_TARGET_SDK_VERSION 35
)
# The end-to-end test (desktop only): QT_QPA_PLATFORM=offscreen build/ultrahome_e2e
if(NOT ANDROID AND TARGET Qt6::Test)
qt_add_executable(ultrahome_e2e tests/e2e.cpp)
target_link_libraries(ultrahome_e2e PRIVATE launcher_uiplugin launcher_ui Qt6::Quick Qt6::Test)
endif()
if(NOT ANDROID)
install(TARGETS ultrahome BUNDLE DESTINATION . RUNTIME DESTINATION bin)
endif()
+83
View File
@@ -0,0 +1,83 @@
<?xml version="1.0"?>
<!-- Qt fills in the %%INSERT_...%% markers when it builds the APK (androiddeployqt). -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dev.ultra.launcher"
android:installLocation="auto"
android:versionCode="-- %%INSERT_VERSION_CODE%% --"
android:versionName="-- %%INSERT_VERSION_NAME%% --">
<!-- %%INSERT_PERMISSIONS -->
<!-- %%INSERT_FEATURES -->
<!-- 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>
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true" />
<application
android:name="org.qtproject.qt.android.bindings.QtApplication"
android:hardwareAccelerated="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:theme="@style/Home"
android:supportsRtl="true"
android:allowBackup="false">
<activity
android:name="dev.ultra.launcher.HomeActivity"
android:exported="true"
android:launchMode="singleTask"
android:stateNotNeeded="true"
android:clearTaskOnLaunch="true"
android:excludeFromRecents="true"
android:screenOrientation="unspecified"
android:windowSoftInputMode="adjustNothing"
android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation|mcc|mnc|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>
<meta-data
android:name="android.app.lib_name"
android:value="-- %%INSERT_APP_LIB_NAME%% --" />
<meta-data
android:name="android.app.arguments"
android:value="-- %%INSERT_APP_ARGUMENTS%% --" />
</activity>
<receiver
android:name="dev.ultra.launcher.Updater$InstallReceiver"
android:exported="false" />
<!-- Opens Recents for the Windows button; the user turns it on in Accessibility. -->
<service
android:name="dev.ultra.launcher.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,4 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:angle="315" android:startColor="#4C1D95" android:endColor="#1E293B" />
</shape>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A 3x3 grid of app dots inside the adaptive icon's 72dp safe zone. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp" android:height="108dp"
android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#FFFFFF"
android:pathData="M36,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M36,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M36,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0" />
</vector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ultra Home</string>
<string name="recents_service_label">ultra Home window list</string>
<string name="recents_service_summary">Lets the home screen\'s Windows button open Recents</string>
<string name="recents_service_description">Turn this on so the Windows button on the ultra Home screen can show your open windows (Recents). Android only lets accessibility services open Recents. This service reads nothing on screen and does nothing else.</string>
</resources>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- The wallpaper shows through the transparent window and Qt's surface. -->
<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:windowIsTranslucent">false</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" />
@@ -0,0 +1,898 @@
package dev.ultra.launcher;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
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.ColorDrawable;
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.Log;
import android.util.SizeF;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.qtproject.qt.android.bindings.QtActivity;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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;
/**
* The home screen activity. The UI is the QML app in qt/qml, run by Qt; this class is the
* Android side of it. The C++ backend (qt/src/backend.cpp) calls the static methods below
* from Qt's thread, and this class calls back through {@link Native} once Qt is ready.
*
* All geometry crossing between QML and Java is in physical screen pixels: QML maps its
* items to global coordinates and the backend scales them by the device pixel ratio.
*
* Widgets are real AppWidgetHostViews in a layer above Qt's surface. QML reports where its
* live widget slots are (placeWidgets) and this class moves the views there.
*/
public class HomeActivity extends QtActivity {
// The WebView build's host id: its widgets are bound to it, so they carry over.
static final int HOST_ID = 0x0171;
static final int REQ_BIND = 1, REQ_CONFIGURE = 2;
private static volatile HomeActivity self;
private static volatile boolean qtReady;
private final Handler main = new Handler(Looper.getMainLooper());
private LauncherApps launcher;
private final UserHandle user = Process.myUserHandle();
private final Map<String, LauncherActivityInfo> activities = new ConcurrentHashMap<>();
private AppWidgetManager widgets;
private AppWidgetHost widgetHost;
private CoverLayer widgetLayer;
private final Map<Integer, AppWidgetHostView> widgetViews = new HashMap<>();
private final Map<Integer, Long> widgetSizes = new HashMap<>();
private int pendingWidget = -1;
private volatile int editingWidget = -1;
private int insetTop, insetBottom;
private final int[] layerAt = new int[2];
private final LauncherApps.Callback packages = new LauncherApps.Callback() {
@Override public void onPackageRemoved(String pkg, UserHandle u) { appsChanged(pkg); }
@Override public void onPackageAdded(String pkg, UserHandle u) { appsChanged(pkg); }
@Override public void onPackageChanged(String pkg, UserHandle u) { appsChanged(pkg); }
@Override public void onPackagesAvailable(String[] pkgs, UserHandle u, boolean replacing) { appsChanged(String.join(",", pkgs)); }
@Override public void onPackagesUnavailable(String[] pkgs, UserHandle u, boolean replacing) { appsChanged(String.join(",", pkgs)); }
};
@Override
public void onCreate(Bundle state) {
self = this;
super.onCreate(state);
launcher = getSystemService(LauncherApps.class);
launcher.registerCallback(packages, main);
widgets = AppWidgetManager.getInstance(this);
widgetHost = new Host(this);
seeThrough();
}
/** The wallpaper shows through the window and Qt's surface. */
private void seeThrough() {
Window w = getWindow();
w.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
w.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
w.setStatusBarColor(Color.TRANSPARENT);
w.setNavigationBarColor(Color.TRANSPARENT);
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);
}
}
/** Called once QML is up: add the widget layer over Qt's views and start talking to it. */
static void ready() {
HomeActivity a = self;
if (a == null) return;
a.main.post(() -> {
a.seeThrough();
if (a.widgetLayer == null) {
a.widgetLayer = new CoverLayer(a);
ViewGroup content = a.findViewById(android.R.id.content);
content.addView(a.widgetLayer, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
content.setOnApplyWindowInsetsListener((v, insets) -> {
a.onInsets(insets);
return v.onApplyWindowInsets(insets);
});
content.requestApplyInsets();
}
qtReady = true;
Native.insets(a.insetTop, a.insetBottom);
a.readLegacyHome();
});
}
/**
* The WebView build kept its home screen in its page's localStorage, which lives on in
* this app's data dir. Read it once, through a throwaway WebView on the same origin,
* and hand the ultra.home.* keys to QML, which merges them into the Qt home.
*/
private void readLegacyHome() {
final android.content.SharedPreferences prefs = getSharedPreferences("qt", MODE_PRIVATE);
if (prefs.getBoolean("legacyRead", false)) return;
final android.webkit.WebView w;
try {
w = new android.webkit.WebView(this);
} catch (RuntimeException e) {
Log.w("ultra", "no WebView to read the old home from", e);
return;
}
w.getSettings().setJavaScriptEnabled(true);
w.getSettings().setDomStorageEnabled(true);
final boolean[] done = {false};
w.setWebViewClient(new android.webkit.WebViewClient() {
@Override
public android.webkit.WebResourceResponse shouldInterceptRequest(
android.webkit.WebView v, android.webkit.WebResourceRequest r) {
return new android.webkit.WebResourceResponse("text/html", "utf-8",
new java.io.ByteArrayInputStream("<!doctype html><title>.</title>".getBytes()));
}
@Override
public void onPageFinished(android.webkit.WebView v, String url) {
if (done[0]) return;
done[0] = true;
v.evaluateJavascript(LEGACY_JS, value -> {
String json = null;
try {
json = new JSONArray("[" + value + "]").optString(0, null);
} catch (JSONException e) {
Log.w("ultra", "old home unreadable: " + value);
}
prefs.edit().putBoolean("legacyRead", true).apply();
if (json != null && json.startsWith("{")) Native.legacyHome(json);
v.destroy();
});
}
});
w.loadUrl("https://appassets.androidplatform.net/index.html");
}
private static final String LEGACY_JS =
"(function(){var o={};for(var i=0;i<localStorage.length;i++){var k=localStorage.key(i);"
+ "if(k.indexOf('ultra.home.')===0)o[k]=localStorage.getItem(k);}return JSON.stringify(o);})()";
private void onInsets(WindowInsets insets) {
if (Build.VERSION.SDK_INT >= 30) {
Insets bars = insets.getInsets(WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout());
Insets ime = insets.getInsets(WindowInsets.Type.ime());
insetTop = bars.top;
insetBottom = Math.max(bars.bottom, ime.bottom);
} else {
insetTop = insets.getSystemWindowInsetTop();
insetBottom = insets.getSystemWindowInsetBottom();
}
if (qtReady) Native.insets(insetTop, insetBottom);
}
@Override
public void onStart() {
super.onStart();
Log.i("ultra", "onStart");
widgetHost.startListening();
Updater.check(this, false);
}
@Override
public void onStop() {
super.onStop();
Log.i("ultra", "onStop");
widgetHost.stopListening();
}
@Override
public void onDestroy() {
launcher.unregisterCallback(packages);
if (self == this) self = null;
super.onDestroy();
}
// The home button while we are already in front.
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (qtReady) Native.homePressed();
}
// A home screen has nowhere to go back to: back clears the drawer, a sheet or edit mode.
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (e.getAction() == KeyEvent.ACTION_UP && !e.isCanceled() && qtReady) Native.backPressed();
return true;
}
return super.dispatchKeyEvent(e);
}
@Override
@SuppressWarnings("deprecation")
public void onBackPressed() {
if (qtReady) Native.backPressed();
}
/** packages: the ones that changed, comma-separated, so only their icons are redrawn. */
private void appsChanged(String packages) {
if (packages != null && !packages.isEmpty()) {
for (String pkg : packages.split(",")) {
if (pkg.isEmpty()) continue;
String prefix = pkg + "/";
activities.keySet().removeIf(k -> k.startsWith(prefix));
}
}
if (qtReady) Native.appsChanged(packages == null ? "" : packages);
}
// ------------------------------------------------------------ called from Qt
/** {"apps": [{"label", "component", "system"}]}, every launchable activity, by label. */
private static final ExecutorService lister = Executors.newSingleThreadExecutor();
/** apps(), worked out off Qt's thread (it takes a while), then handed to Native.appList. */
static void listApps() {
lister.execute(() -> Native.appList(apps()));
}
static String apps() {
HomeActivity a = self;
if (a == null) return "{\"apps\":[]}";
try {
List<LauncherActivityInfo> list = new ArrayList<>(a.launcher.getActivityList(null, a.user));
Map<LauncherActivityInfo, String> labels = new HashMap<>();
for (LauncherActivityInfo i : list) labels.put(i, String.valueOf(i.getLabel()));
Collator by = Collator.getInstance();
list.sort((x, y) -> by.compare(labels.get(x), labels.get(y)));
JSONArray out = new JSONArray();
java.util.Set<String> seen = new java.util.HashSet<>();
for (LauncherActivityInfo i : list) {
ComponentName cn = i.getComponentName();
if (cn.getPackageName().equals(a.getPackageName())) continue;
String c = cn.flattenToShortString();
seen.add(c);
a.activities.put(c, i);
JSONObject o = new JSONObject().put("label", labels.get(i)).put("component", c);
// System apps can't be uninstalled, so the drawer offers no Uninstall for them.
if ((i.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) != 0) o.put("system", true);
out.put(o);
}
a.activities.keySet().retainAll(seen);
return new JSONObject().put("apps", out).toString();
} catch (JSONException | RuntimeException e) {
Log.w("ultra", "listing apps", e);
return "{\"apps\":[]}";
}
}
/** {"widgets": [{"label", "app", "provider", "h"}]}, every widget provider; h in dp. */
static String widgetProviders() {
HomeActivity a = self;
if (a == null) return "{\"widgets\":[]}";
try {
List<AppWidgetProviderInfo> list = new ArrayList<>(a.widgets.getInstalledProvidersForProfile(a.user));
Map<AppWidgetProviderInfo, String> labels = new HashMap<>();
for (AppWidgetProviderInfo w : list) labels.put(w, w.loadLabel(a.getPackageManager()));
Collator by = Collator.getInstance();
list.sort((x, y) -> by.compare(labels.get(x), labels.get(y)));
float d = a.getResources().getDisplayMetrics().density;
JSONArray out = new JSONArray();
for (AppWidgetProviderInfo w : list) {
int h = Math.round(w.minHeight / d);
out.put(new JSONObject()
.put("label", labels.get(w))
.put("app", a.appLabel(w.provider.getPackageName()))
.put("provider", w.provider.flattenToShortString())
.put("h", Math.max(80, Math.min(h + 16, 420))));
}
return new JSONObject().put("widgets", out).toString();
} catch (JSONException | RuntimeException e) {
Log.w("ultra", "listing widgets", e);
return "{\"widgets\":[]}";
}
}
private String appLabel(String pkg) {
try {
PackageManager pm = getPackageManager();
return pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString();
} catch (PackageManager.NameNotFoundException e) {
return "";
}
}
// Some icon drawables don't survive being loaded and drawn concurrently.
private static final Object iconLock = new Object();
/**
* An icon as premultiplied RGBA pixels, size px square: key "a:COMPONENT" (an app) or
* "w:PROVIDER" (a widget). Drawn icons are kept on disk, keyed by the app's last update,
* so a fresh start reads them back instead of drawing every one again.
*/
static byte[] icon(String key, int size) {
HomeActivity a = self;
if (a == null || key == null || key.length() < 3) return null;
size = Math.max(16, Math.min(size, 512));
File f = a.iconFile(key, size);
if (f != null && f.length() == (long) size * size * 4) {
try {
return Files.readAllBytes(f.toPath());
} catch (java.io.IOException e) {
f.delete();
}
}
byte[] px;
synchronized (iconLock) {
try {
Drawable d = key.startsWith("w:") ? a.widgetIcon(key.substring(2)) : a.appIcon(key.substring(2));
px = d == null ? null : toPixels(d, size);
} catch (RuntimeException | OutOfMemoryError e) {
Log.w("ultra", "icon for " + key, e);
return null;
}
}
if (px != null && f != null) {
File tmp = new File(f.getPath() + ".tmp");
try (FileOutputStream out = new FileOutputStream(tmp)) {
out.write(px);
} catch (java.io.IOException e) {
tmp.delete();
tmp = null;
}
if (tmp != null && !tmp.renameTo(f)) tmp.delete();
}
return px;
}
private File iconFile(String key, int size) {
try {
String pkg = key.substring(2).split("/", 2)[0];
long stamp = getPackageManager().getPackageInfo(pkg, 0).lastUpdateTime;
String id = "v2|" + key + "|" + size + "|" + stamp + "|" + getResources().getDisplayMetrics().densityDpi;
byte[] h = MessageDigest.getInstance("SHA-1").digest(id.getBytes(java.nio.charset.StandardCharsets.UTF_8));
StringBuilder name = new StringBuilder();
for (byte b : h) name.append(String.format("%02x", b));
File dir = new File(getCacheDir(), "icons");
if (!dir.isDirectory() && !dir.mkdirs()) return null;
return new File(dir, name.toString());
} catch (Exception e) {
return null;
}
}
private Drawable appIcon(String c) {
ComponentName cn = ComponentName.unflattenFromString(c);
if (cn == null) return null;
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) return null;
Drawable d = info.getIcon(getResources().getDisplayMetrics().densityDpi);
return d != null ? d : getPackageManager().getDefaultActivityIcon();
}
private Drawable widgetIcon(String p) {
AppWidgetProviderInfo w = provider(p);
if (w == null) return null;
Drawable d = null;
try {
d = w.loadIcon(this, getResources().getDisplayMetrics().densityDpi);
} catch (RuntimeException e) {
Log.w("ultra", "widget icon for " + p, e);
}
if (d == null) {
try {
d = getPackageManager().getApplicationIcon(w.provider.getPackageName());
} catch (PackageManager.NameNotFoundException | RuntimeException e) {
d = getPackageManager().getDefaultActivityIcon();
}
}
return d;
}
// ARGB_8888 bitmaps hold premultiplied RGBA bytes: Qt takes them as they are, with no
// PNG to encode here and decode there.
private static byte[] toPixels(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));
ByteBuffer buf = ByteBuffer.allocate(size * size * 4);
bmp.copyPixelsToBuffer(buf);
bmp.recycle();
return buf.array();
}
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 static void onMain(java.util.function.Consumer<HomeActivity> f) {
HomeActivity a = self;
if (a != null) a.main.post(() -> f.accept(a));
}
static void launch(String component) {
onMain(a -> {
ComponentName cn = ComponentName.unflattenFromString(component);
try {
a.launcher.startMainActivity(cn, a.user, null, null);
} catch (ActivityNotFoundException | SecurityException | NullPointerException e) {
Toast.makeText(a, "Can't open " + component, Toast.LENGTH_SHORT).show();
}
});
}
static void appInfo(String component) {
onMain(a -> {
ComponentName cn = ComponentName.unflattenFromString(component);
if (cn != null) a.launcher.startAppDetailsActivity(cn, a.user, null, null);
});
}
/** The system asks the user to confirm; the app list reloads when the package goes. */
static void uninstall(String component) {
onMain(a -> {
ComponentName cn = ComponentName.unflattenFromString(component);
if (cn != null) a.startIntent(new Intent(Intent.ACTION_DELETE,
Uri.fromParts("package", cn.getPackageName(), null)));
});
}
static void openSettings() { onMain(a -> a.startIntent(new Intent(Settings.ACTION_SETTINGS))); }
static void pickWallpaper() {
onMain(a -> a.startIntent(Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER), "Wallpaper")));
}
static void checkUpdates() {
HomeActivity a = self;
if (a != null) Updater.check(a, true);
}
static void haptic() {
onMain(a -> a.getWindow().getDecorView().performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING));
}
/**
* 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.
*/
static void openRecents() {
onMain(a -> {
if (RecentsService.showRecents()) return;
Toast.makeText(a, "Turn on \"ultra Home window list\" to show open windows", Toast.LENGTH_LONG).show();
String me = new ComponentName(a, RecentsService.class).flattenToString();
Bundle args = new Bundle();
args.putString(":settings:fragment_args_key", me);
a.startIntent(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
.putExtra(":settings:fragment_args_key", me)
.putExtra(":settings:show_fragment_args", args));
});
}
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();
}
}
// ------------------------------------------------------------ widgets
/** Bind a widget for provider p, then configure it if it asks to be; see onActivityResult. */
static void addWidget(String p) {
onMain(a -> a.bindWidget(p));
}
private void bindWidget(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;
if (qtReady) Native.widgetAdded(id);
}
private void dropPending() {
if (pendingWidget != -1) widgetHost.deleteAppWidgetId(pendingWidget);
pendingWidget = -1;
}
@Override
public void onActivityResult(int req, int result, Intent data) {
super.onActivityResult(req, result, data);
if (pendingWidget == -1 || (req != REQ_BIND && req != REQ_CONFIGURE)) return;
if (result != RESULT_OK) {
dropPending();
} else if (req == REQ_BIND) {
configureWidget(pendingWidget);
} else {
widgetReady(pendingWidget);
}
}
static void removeWidget(int id) {
onMain(a -> {
AppWidgetHostView v = a.widgetViews.remove(id);
if (v != null && a.widgetLayer != null) a.widgetLayer.removeView(v);
a.widgetSizes.remove(id);
a.widgetHost.deleteAppWidgetId(id);
});
}
/**
* A placed widget's natural width and how far it may be resized, in physical px:
* {"w", "minW", "minH", "maxW", "maxH" (0 = no limit), "h", "v" (whether it resizes
* horizontally / vertically)}.
*/
static String widgetLimits(int id) {
HomeActivity a = self;
JSONObject o = new JSONObject();
if (a == null) return o.toString();
try {
AppWidgetProviderInfo w = a.widgets.getAppWidgetInfo(id);
if (w == null) return o.toString();
// 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", w.minWidth).put("minW", minW).put("minH", minH).put("maxW", maxW).put("maxH", maxH)
.put("h", (w.resizeMode & AppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0)
.put("v", (w.resizeMode & AppWidgetProviderInfo.RESIZE_VERTICAL) != 0);
} catch (JSONException | RuntimeException e) {
Log.w("ultra", "widget limits", e);
}
return o.toString();
}
/** Keep the system's edge gestures off these rects ([[x, y, w, h], ...] screen px). */
static void excludeGestures(String json) {
if (Build.VERSION.SDK_INT < 29) return;
onMain(a -> {
View root = a.getWindow().getDecorView();
int[] at = new int[2];
root.getLocationOnScreen(at);
List<Rect> rects = new ArrayList<>();
try {
JSONArray arr = new JSONArray(json);
for (int i = 0; i < arr.length(); i++) {
JSONArray r = arr.getJSONArray(i);
int x = r.getInt(0) - at[0], y = r.getInt(1) - at[1];
rects.add(new Rect(x, y, x + r.getInt(2), y + r.getInt(3)));
}
} catch (JSONException e) {
return;
}
root.setSystemGestureExclusionRects(rects);
});
}
/** The drawer covers the screen down to y (screen px); -1 is all of it, 0 none. */
static void coverWidgets(int y) {
onMain(a -> {
if (a.widgetLayer == null) return;
if (y <= 0) { a.widgetLayer.cover(y); return; }
a.widgetLayer.getLocationOnScreen(a.layerAt);
a.widgetLayer.cover(Math.max(1, y - a.layerAt[1]));
});
}
/** A sheet covers the screen from y (screen px) down, and dims the rest; y 0: no sheet. */
static void sheetWidgets(int y, boolean dim) {
onMain(a -> {
if (a.widgetLayer == null) return;
if (y <= 0) { a.widgetLayer.sheet(0, dim); return; }
a.widgetLayer.getLocationOnScreen(a.layerAt);
a.widgetLayer.sheet(Math.max(1, y - a.layerAt[1]), dim);
});
}
/**
* Lay widget views over QML's live slots: [[id, x, y, w, h, editing], ...] in screen
* px, where editing is 1 for the one showing resize handles.
*/
static void placeWidgets(String json) {
onMain(a -> a.place(json));
}
private void place(String json) {
if (widgetLayer == null) return;
float d = getResources().getDisplayMetrics().density;
widgetLayer.getLocationOnScreen(layerAt);
Map<Integer, int[]> want = new HashMap<>();
int editing = -1;
try {
JSONArray arr = new JSONArray(json);
for (int i = 0; i < arr.length(); i++) {
JSONArray r = arr.getJSONArray(i);
if (r.optInt(5) == 1) editing = r.getInt(0);
want.put(r.getInt(0), new int[] {r.getInt(1) - layerAt[0], r.getInt(2) - layerAt[1],
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 (dp).
int wdp = Math.round(r[2] / d), hdp = Math.round(r[3] / d);
long size = ((long) wdp << 32) | hdp;
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(wdp, hdp));
v.updateAppWidgetSize(new Bundle(), sizes);
} else {
v.updateAppWidgetSize(new Bundle(), wdp, hdp, wdp, hdp);
}
}
}
}
/**
* Widget views that report a long press to QML instead of to the widget. The press
* lifts the widget's slot; the moves and the release that follow go to QML as
* widgetDrag(x, y) in screen 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).
*/
static final class Host extends AppWidgetHost {
Host(HomeActivity a) { super(a, HOST_ID); }
@Override
protected AppWidgetHostView onCreateView(Context context, int id, AppWidgetProviderInfo info) {
return new WidgetView(context, id);
}
}
/**
* Holds the widget views. Qt can't draw over them, so the layer clips them itself:
* the app drawer slides down over the home screen, so cover(top) hides them above
* its edge (-1 all of them, 0 none); a sheet rises from the bottom, so sheet(bottom,
* dim) hides them below its top edge (0: no sheet) and dims the rest like the
* sheet's backdrop, which then takes their touches (a tap closes the sheet). Touches
* that land on no widget fall through to Qt underneath.
*/
static final class CoverLayer extends FrameLayout {
private int top, bottom;
private boolean dim;
CoverLayer(Context c) { super(c); }
void cover(int y) {
if (y == top) return;
top = y;
apply();
}
void sheet(int y, boolean dimmed) {
if (y == bottom && dimmed == dim) return;
bottom = y;
dim = dimmed;
apply();
}
private void apply() {
setVisibility(top < 0 ? View.INVISIBLE : View.VISIBLE);
setAlpha(dim ? .55f : 1f);
if (top <= 0 && bottom <= 0) {
setClipBounds(null);
} else {
int t = Math.max(top, 0), b = bottom > 0 ? bottom : Math.max(getHeight(), t + 1);
setClipBounds(new Rect(0, t, Math.max(getWidth(), 1), Math.max(b, t + 1)));
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN
&& (dim || top < 0 || (top > 0 && ev.getY() < top) || (bottom > 0 && ev.getY() >= bottom))) {
return false;
}
return super.dispatchTouchEvent(ev);
}
}
static final class WidgetView extends AppWidgetHostView {
private final int id;
private float downX, downY;
private boolean longPressed, moved;
private final Runnable fire = new Runnable() {
@Override public void run() {
longPressed = true;
moved = false;
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
setAlpha(.85f);
if (qtReady) Native.widgetMenu(id);
}
};
WidgetView(Context c, int id) {
super(c);
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);
}
private int slop() { return ViewConfiguration.get(getContext()).getScaledTouchSlop(); }
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
longPressed = false;
downX = e.getX();
downY = e.getY();
HomeActivity a = self;
if (a != null && a.editingWidget == id) {
// Being resized: the press moves it, without a long press first.
longPressed = true;
moved = false;
setAlpha(.85f);
if (qtReady) Native.widgetGrab(id);
return true;
}
postDelayed(fire, ViewConfiguration.getLongPressTimeout());
break;
case MotionEvent.ACTION_MOVE:
if (Math.hypot(e.getX() - downX, e.getY() - downY) > slop()) 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);
if (qtReady) Native.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 act = e.getActionMasked();
if (act == MotionEvent.ACTION_UP || act == MotionEvent.ACTION_CANCEL
|| (act == MotionEvent.ACTION_MOVE && Math.hypot(e.getX() - downX, e.getY() - downY) > slop())) {
removeCallbacks(fire);
}
return super.onTouchEvent(e) || act == MotionEvent.ACTION_DOWN;
}
switch (e.getActionMasked()) {
case MotionEvent.ACTION_MOVE:
if (!moved && Math.hypot(e.getX() - downX, e.getY() - downY) > slop()) moved = true;
// Raw screen coordinates: this view moves as QML reorders slots.
if (moved && qtReady) Native.widgetDrag(Math.round(e.getRawX()), Math.round(e.getRawY()));
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
drop();
break;
}
return true;
}
}
}
@@ -0,0 +1,22 @@
package dev.ultra.launcher;
/**
* Calls into the C++ backend (qt/src/backend.cpp registers these). HomeActivity only calls
* them once the backend has said it is ready, so they are never called unregistered.
* Geometry is in physical screen px.
*/
final class Native {
private Native() {}
static native void appsChanged(String packages); // comma-separated
static native void appList(String json); // HomeActivity.listApps' answer
static native void homePressed();
static native void backPressed();
static native void insets(int top, int bottom);
static native void widgetAdded(int id);
static native void widgetMenu(int id);
static native void widgetGrab(int id);
static native void widgetDrag(int x, int y);
static native void widgetDrop(boolean moved);
static native void legacyHome(String json); // the WebView build's ultra.home.* keys
}
@@ -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,195 @@
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.JSONArray;
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 newest release on the Gitea forge (experiments/launcher
* on git.site.latha.org), which .gitea/workflows/launcher.yml builds on every commit to
* main. Each release holds version.json ({"versionCode": N, "commit": SHA}) next to
* ultra-launcher.apk, with N the APK's versionCode; the latest-release API names their
* download URLs. 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 LATEST =
"https://git.site.latha.org/api/v1/repos/experiments/launcher/releases/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 release = new JSONObject(new String(get(LATEST), StandardCharsets.UTF_8));
String versionUrl = assetUrl(release, "version.json");
String apkUrl = assetUrl(release, "ultra-launcher.apk");
JSONObject v = new JSONObject(new String(get(versionUrl), 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, apkUrl, latest);
}
/** The download URL of the named asset in a release's JSON. */
private static String assetUrl(JSONObject release, String name) throws Exception {
JSONArray assets = release.getJSONArray("assets");
for (int i = 0; i < assets.length(); i++) {
JSONObject a = assets.getJSONObject(i);
if (name.equals(a.getString("name"))) return a.getString("browser_download_url");
}
throw new IOException("no " + name + " asset in the latest release");
}
@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, String apkUrl, 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(apkUrl);
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); // asset downloads redirect to their storage 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();
}
}
}
}
+87
View File
@@ -0,0 +1,87 @@
{
"apps": [
{
"label": "Calculator",
"component": "com.example.calculator/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f59e0b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Calendar",
"component": "com.example.calendar/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%233b82f6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Camera",
"component": "com.example.camera/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2364748b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Chrome",
"component": "com.example.chrome/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2322c55e%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Clock",
"component": "com.example.clock/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%230ea5e9%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Contacts",
"component": "com.example.contacts/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%236366f1%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Files",
"component": "com.example.files/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23eab308%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EF%3C/text%3E%3C/svg%3E"
},
{
"label": "Gmail",
"component": "com.example.gmail/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ef4444%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EG%3C/text%3E%3C/svg%3E"
},
{
"label": "Maps",
"component": "com.example.maps/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2310b981%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E"
},
{
"label": "Messages",
"component": "com.example.messages/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%238b5cf6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E"
},
{
"label": "Music",
"component": "com.example.music/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ec4899%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E"
},
{
"label": "Phone",
"system": true,
"component": "com.example.phone/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2314b8a6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E"
},
{
"label": "Photos",
"component": "com.example.photos/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f97316%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E"
},
{
"label": "Play Store",
"system": true,
"component": "com.example.playstore/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2306b6d4%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E"
},
{
"label": "Settings",
"system": true,
"component": "com.example.settings/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2371717a%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3ES%3C/text%3E%3C/svg%3E"
},
{
"label": "Weather",
"component": "com.example.weather/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2338bdf8%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EW%3C/text%3E%3C/svg%3E"
}
]
}
+32
View File
@@ -0,0 +1,32 @@
{
"widgets": [
{
"label": "Clock",
"app": "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",
"app": "Google",
"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",
"app": "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",
"app": "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
}
]
}
+31
View File
@@ -0,0 +1,31 @@
import QtQuick
// An app's or widget's icon from HomeActivity (image://icon/KEY), or a blank disc
// until it arrives or if it can't be drawn.
Item {
id: root
property string key: "" // "a:COMPONENT" or "w:PROVIDER"
property int generation: 0 // bumped when the app list changes, so icons reload
property real size: 40
width: size
height: size
Rectangle {
anchors.fill: parent
radius: width / 2
color: Qt.rgba(1, 1, 1, .18)
visible: img.status !== Image.Ready
}
Image {
id: img
anchors.fill: parent
asynchronous: true
fillMode: Image.PreserveAspectFit
smooth: true
mipmap: true
sourceSize.width: Math.ceil(root.size * Screen.devicePixelRatio)
sourceSize.height: Math.ceil(root.size * Screen.devicePixelRatio)
onStatusChanged: if (status === Image.Ready || status === Image.Error) console.info("ultra.icon shown", root.key, status === Image.Ready)
source: root.key ? "image://icon/" + encodeURIComponent(root.key) + "?" + root.generation : ""
}
}
+148
View File
@@ -0,0 +1,148 @@
import QtQuick
// Every app, with a search. It slides down over the home screen; swiping up past the
// end of the list (or Close, or back) puts it away. In pick mode a tap adds an app to
// the home screen or takes it off, and the keyboard stays down.
Item {
id: root
property bool open: false
property bool picking: false
property var apps: [] // [{label, component, system}]
property var homeSet: ({}) // component -> true: on the home screen
property bool loading: true
property bool warm: true // false: hold off making icons until it opens
property var iconGen: ({}) // package -> n, see Main.gen
property real insetTop: 0
property real insetBottom: 0
property alias query: search.text
readonly property real edge: y + height // the drawer's bottom edge, for covering widgets
readonly property var shown: {
const q = search.shown.toLowerCase();
const out = [];
for (let i = 0; i < apps.length; i++)
if (!q || apps[i].label.toLowerCase().indexOf(q) >= 0) out.push(i);
return out;
}
signal openApp(int row)
signal toggleApp(int row)
signal appMenu(int row)
signal closeRequested()
width: parent.width
height: parent.height
y: open ? 0 : -height
visible: y > -height
Behavior on y { NumberAnimation { duration: 220; easing.type: Easing.OutCubic } }
function openFirst() {
if (shown.length > 0 && search.shown.length > 0) openApp(shown[0]);
}
onOpenChanged: {
if (open && !picking) search.focusNow();
if (!open) {
search.input.focus = false;
Qt.inputMethod.hide();
search.text = "";
grid.positionViewAtBeginning();
}
}
Rectangle {
anchors.fill: parent
color: Qt.rgba(10 / 255, 10 / 255, 14 / 255, .9)
}
MouseArea { anchors.fill: parent } // nothing under the drawer takes its touches
Column {
id: head
x: Math.max(16, (root.width - 560) / 2 + 16)
width: Math.min(root.width, 560) - 32
y: root.insetTop + 16
spacing: 16
Row {
width: parent.width
spacing: 8
SearchField {
id: search
width: parent.width - close.width - 8
placeholder: "Search apps"
onAccepted: root.openFirst()
onEscaped: text = ""
}
PillButton {
id: close
anchors.verticalCenter: search.verticalCenter
text: root.picking ? "Done" : "Close"
onClicked: root.closeRequested()
}
}
Text {
visible: root.picking
width: parent.width
text: "Tap apps to add them to the home screen or take them off."
color: "white"
opacity: .8
font.pixelSize: 14
wrapMode: Text.Wrap
horizontalAlignment: Text.AlignHCenter
}
}
GridView {
id: grid
objectName: "drawerGrid"
x: head.x
width: head.width
anchors.top: head.bottom
anchors.topMargin: 16
anchors.bottom: parent.bottom
readonly property int cols: root.width >= 480 ? 5 : 4
cellWidth: width / cols
cellHeight: 104
clip: true
bottomMargin: root.insetBottom + 24
boundsBehavior: Flickable.DragOverBounds
model: root.warm || root.visible ? root.shown : []
// Swiping up once the list is at its end puts the drawer away.
onDragEnded: if (verticalOvershoot > 48) root.closeRequested()
delegate: Item {
id: cell
required property int index
required property var modelData
readonly property var app: root.apps[modelData] || ({})
width: grid.cellWidth
height: grid.cellHeight
Tile {
width: parent.width
height: 84
key: "a:" + (cell.app.component || "")
label: cell.app.label || ""
generation: root.iconGen[(cell.app.component || "").split("/")[0]] || 0
iconSize: 52
fontSize: 12
spacing: 6
checkable: root.picking
checked: root.picking && root.homeSet[cell.app.component] === true
pressed: area.pressed
}
MouseArea {
id: area
width: parent.width
height: 84
pressAndHoldInterval: 450
onClicked: root.picking ? root.toggleApp(cell.modelData) : root.openApp(cell.modelData)
onPressAndHold: if (!root.picking) root.appMenu(cell.modelData)
}
}
}
Text {
anchors.centerIn: grid
visible: root.loading || root.shown.length === 0
text: root.loading ? "Loading apps…" : "No apps match."
color: "white"
opacity: .85
font.pixelSize: 15
}
}
+161
View File
@@ -0,0 +1,161 @@
.pragma library
// The home grid, as plain functions over the home list so they can be tested on their
// own (tests/layout.test.mjs). A slot is
// {kind: "app", str: COMPONENT, x, y}
// {kind: "widget", str: LABEL, wid: HOST_ID, w: COLUMNS (0: whole row), rows, x, y}
// where x, y is the cell it was dropped into (column, row from 0), or -1, -1: placed in
// order into the first free cells that fit it ("dense" packing, so apps fill the cells
// beside a widget and the grid has no holes).
var CELL = 64; // row height, px
var RGAP = 8; // gap between rows
var CGAP = 8; // gap between columns
// Rows of app tiles nearest to a widget height in px, at least one.
function widgetRows(px) {
return Math.max(1, Math.floor((px + RGAP + (CELL + RGAP) / 2) / (CELL + RGAP)));
}
function slotW(s, cols) {
if (s.kind !== "widget") return 1;
return (s.w <= 0 || s.w > cols) ? cols : s.w;
}
function slotH(s) {
return s.kind === "widget" ? Math.max(1, s.rows | 0) : 1;
}
function pinned(s, cols) {
return s.x >= 0 && s.y >= 0 && s.x + slotW(s, cols) <= cols;
}
// Where each slot goes: [{col, row, w, h}] (null for a hidden slot), and the rows used,
// at least nrows (the rows that fill the screen).
function pack(home, cols, nrows, hidden) {
var occ = [];
function taken(c, r) { return occ[r] !== undefined && occ[r][c] === true; }
function fits(c, r, w, h) {
if (c < 0 || c + w > cols) return false;
for (var y = r; y < r + h; y++)
for (var x = c; x < c + w; x++)
if (taken(x, y)) return false;
return true;
}
function mark(c, r, w, h) {
for (var y = r; y < r + h; y++) {
if (occ[y] === undefined) occ[y] = [];
for (var x = c; x < c + w; x++) occ[y][x] = true;
}
}
var cells = new Array(home.length);
var rows = Math.max(0, nrows | 0);
var i, s, w, h;
// Pinned slots first, where they were put (they may overlap each other).
for (i = 0; i < home.length; i++) {
s = home[i];
cells[i] = null;
if ((hidden && hidden[i]) || !pinned(s, cols)) continue;
w = slotW(s, cols); h = slotH(s);
cells[i] = {col: s.x, row: s.y, w: w, h: h};
mark(s.x, s.y, w, h);
rows = Math.max(rows, s.y + h);
}
// The rest in order, each into the first free cells that fit it.
for (i = 0; i < home.length; i++) {
s = home[i];
if ((hidden && hidden[i]) || cells[i] !== null) continue;
w = slotW(s, cols); h = slotH(s);
for (var r = 0; cells[i] === null; r++) {
for (var c = 0; c + w <= cols; c++) {
if (fits(c, r, w, h)) {
cells[i] = {col: c, row: r, w: w, h: h};
mark(c, r, w, h);
rows = Math.max(rows, r + h);
break;
}
}
}
}
return {cells: cells, rows: rows};
}
// A cell's box in px, given the column width.
function box(cell, colW) {
return {x: cell.col * (colW + CGAP), y: cell.row * (CELL + RGAP),
w: cell.w * colW + (cell.w - 1) * CGAP, h: cell.h * CELL + (cell.h - 1) * RGAP};
}
// The cell nearest to the top left of a box at x, y (px in the grid).
function cellAt(x, y, colW) {
return [Math.max(0, Math.round(x / (colW + CGAP))), Math.max(0, Math.round(y / (CELL + RGAP)))];
}
// Slot i pinned with its top left at col, row (kept on the screen's grid).
function pin(home, i, col, row, cols, nrows) {
var s = home[i];
var x = col, y = row;
if (x + slotW(s, cols) > cols) x = cols - slotW(s, cols);
if (nrows > 0 && y + slotH(s) > nrows) y = nrows - slotH(s);
s.x = Math.max(0, x);
s.y = Math.max(0, y);
}
// Unpin the slots under pinned slot i, so they flow into free cells.
function clearCells(home, i, cols) {
var a = home[i];
for (var j = 0; j < home.length; j++) {
var b = home[j];
if (j === i || b.x < 0) continue;
if (b.x < a.x + slotW(a, cols) && a.x < b.x + slotW(b, cols)
&& b.y < a.y + slotH(a) && a.y < b.y + slotH(b)) {
b.x = -1;
b.y = -1;
}
}
}
// Take slot a out and put it back at b, shifting the slots between.
function move(home, a, b) {
var s = home.splice(a, 1)[0];
home.splice(b, 0, s);
}
// Resize steps: the number of cells (of size px, gap apart) nearest to want px, kept
// within [min, max] px where it can be (max 0: no limit), and within [lo, hi] cells.
function span(k, size, gap) { return k * size + (k - 1) * gap; }
function fit(want, lo, hi, size, gap, min, max) {
var k = Math.round((want + gap) / (size + gap));
while (k < hi && span(k, size, gap) < min - 8) k++;
while (k > lo && max > 0 && span(k, size, gap) > max + 8) k--;
return Math.max(lo, Math.min(hi, k));
}
// Columns a new widget of natural width px starts at (0: the whole row).
function widgetCols(px, colW, cols) {
if (!px) return 0;
var k = Math.max(1, Math.ceil((px + CGAP - 8) / (colW + CGAP)));
return k >= cols ? 0 : k;
}
// The WebView build's saved home (its ultra.home.* localStorage keys) as Qt slots.
// Widget heights were px; they become whole rows.
function legacy(kv) {
var out = [];
var n = parseInt(kv["ultra.home.n"], 10) || 0;
var num = function (k, i, d) {
var v = parseInt(kv["ultra.home." + k + "." + i], 10);
return isNaN(v) ? d : v;
};
for (var i = 0; i < n; i++) {
var str = kv["ultra.home.str." + i];
if (typeof str !== "string" || !str) continue;
var x = num("cx", i, -1), y = num("cy", i, -1);
if (num("kind", i, 0) === 1)
out.push({kind: "widget", str: str, wid: num("wid", i, 0), w: Math.max(0, num("w", i, 0)),
rows: widgetRows(num("h", i, 120)), x: x, y: y});
else
out.push({kind: "app", str: str, x: x, y: y});
}
return out;
}
File diff suppressed because it is too large. Load diff
+27
View File
@@ -0,0 +1,27 @@
import QtQuick
// A rounded text button: "ghost" (clear until pressed) or "primary" (filled).
Rectangle {
id: root
property alias text: label.text
property bool primary: false
property real fontSize: 14
signal clicked()
implicitWidth: label.implicitWidth + 28
implicitHeight: 36
radius: height / 2
color: primary ? (area.pressed ? "#d4d4d8" : "white")
: (area.pressed ? Qt.rgba(1, 1, 1, .18) : "transparent")
Text {
id: label
anchors.centerIn: parent
color: root.primary ? "#111" : "white"
font.pixelSize: root.fontSize
font.weight: Font.Medium
}
MouseArea {
id: area
anchors.fill: parent
onClicked: root.clicked()
}
}
+89
View File
@@ -0,0 +1,89 @@
import QtQuick
// A rounded search box. Enter is "accepted"; the text is "text", and "shown" is what
// the box shows, including a word the keyboard is still composing (Android keyboards
// keep it out of "text" until it is committed).
Rectangle {
id: root
property alias text: input.text
property alias placeholder: hint.text
property alias input: input
readonly property string shown: input.displayText
property real fontSize: 16
signal accepted()
signal escaped()
implicitHeight: 44
radius: height / 2
color: Qt.rgba(1, 1, 1, .1)
border.color: Qt.rgba(1, 1, 1, .15)
border.width: 1
function focusNow() { input.forceActiveFocus(); Qt.inputMethod.show() }
// Empty the box, including a word still being composed, and keep typing in it.
// Android commits a composing word asynchronously, so it can land after the clear:
// clear again once it has.
function clearText() {
Qt.inputMethod.commit();
input.clear();
input.forceActiveFocus();
clearAgain.restart();
}
Timer { id: clearAgain; interval: 120; onTriggered: input.clear() }
TextInput {
id: input
anchors.left: parent.left
anchors.right: clear.left
anchors.leftMargin: 20
anchors.rightMargin: 0
anchors.verticalCenter: parent.verticalCenter
color: "white"
selectionColor: Qt.rgba(1, 1, 1, .35)
font.pixelSize: root.fontSize
clip: true
// No suggestions: Android keyboards then type straight into the box rather than
// composing words, so the list filters on every key.
inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhSensitiveData | Qt.ImhNoAutoUppercase
onAccepted: root.accepted()
Keys.onEscapePressed: root.escaped()
Text {
id: hint
anchors.fill: parent
verticalAlignment: Text.AlignVCenter
color: Qt.rgba(1, 1, 1, .6)
font.pixelSize: root.fontSize
visible: input.displayText.length === 0
}
}
// The clear button: a finger-sized target at the right end of the box.
Item {
id: clear
objectName: "searchClear"
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
width: visible ? 44 : 0
visible: input.displayText.length > 0
z: 1
// Drawn, not a glyph: phone fonts may have no ✕.
Repeater {
model: [45, -45]
Rectangle {
required property var modelData
anchors.centerIn: parent
width: 14
height: 2
radius: 1
rotation: modelData
antialiasing: true
color: Qt.rgba(1, 1, 1, .7)
}
}
MouseArea {
anchors.fill: parent
preventStealing: true
onPressed: (m) => m.accepted = true
onClicked: { root.clearText(); root.escaped() }
}
}
}
+71
View File
@@ -0,0 +1,71 @@
import QtQuick
// A panel that rises from the bottom over a dimmed screen (long-press menus, the
// widget picker). Its children go in a column; tapping outside closes it.
Item {
id: root
property bool open: false
property string title: ""
property real bottomInset: 0
property real maxWidth: 560
default property alias content: column.data
// Where the panel's top edge is, for hiding native widgets under it.
readonly property real edge: panel.y
signal closeRequested()
anchors.fill: parent
visible: open || panel.y < height
enabled: open
Rectangle {
anchors.fill: parent
color: "black"
opacity: root.open ? .45 : 0
Behavior on opacity { NumberAnimation { duration: 150 } }
MouseArea { anchors.fill: parent; onClicked: root.closeRequested() }
}
Rectangle {
id: panel
width: Math.min(root.width, root.maxWidth)
anchors.horizontalCenter: parent.horizontalCenter
height: Math.min(root.height * .7, column.implicitHeight + 36 + root.bottomInset + 16)
y: root.open ? root.height - height : root.height
Behavior on y { NumberAnimation { duration: 200; easing.type: Easing.OutCubic } }
radius: 20
color: "#18181b"
MouseArea { anchors.fill: parent } // keep taps on the sheet off the overlay
// square off the bottom corners
Rectangle { anchors.bottom: parent.bottom; width: parent.width; height: 20; color: parent.color }
Rectangle {
width: 36; height: 5; radius: 3
anchors.horizontalCenter: parent.horizontalCenter
y: 12
color: "#3f3f46"
}
Flickable {
id: flick
anchors.fill: parent
anchors.topMargin: 28
anchors.leftMargin: 16
anchors.rightMargin: 16
anchors.bottomMargin: root.bottomInset + 16
contentHeight: column.implicitHeight
clip: true
boundsBehavior: Flickable.StopAtBounds
Column {
id: column
width: flick.width
Text {
visible: root.title.length > 0
text: root.title
color: "#fafafa"
font.pixelSize: 16
font.weight: Font.DemiBold
leftPadding: 8
bottomPadding: 8
width: parent.width
elide: Text.ElideRight
}
}
}
}
}
+25
View File
@@ -0,0 +1,25 @@
import QtQuick
// A row in a sheet's menu.
Rectangle {
id: root
property alias text: label.text
signal clicked()
width: parent ? parent.width : 0
height: 48
radius: 8
color: area.pressed ? "#2e2e36" : "transparent"
Text {
id: label
anchors.left: parent.left
anchors.leftMargin: 8
anchors.verticalCenter: parent.verticalCenter
color: "#fafafa"
font.pixelSize: 16
}
MouseArea {
id: area
anchors.fill: parent
onClicked: root.clicked()
}
}
+61
View File
@@ -0,0 +1,61 @@
import QtQuick
// An app: its icon over its name.
Item {
id: root
property string key: ""
property string label: ""
property int generation: 0
property real iconSize: 40
property real fontSize: 11
property real spacing: 4
property bool checkable: false // the drawer's pick mode: a check circle in the corner
property bool checked: false
property bool pressed: false
Rectangle {
anchors.fill: parent
radius: 12
color: Qt.rgba(1, 1, 1, .12)
visible: root.pressed
}
Column {
anchors.centerIn: parent
width: parent.width
spacing: root.spacing
AppIcon {
anchors.horizontalCenter: parent.horizontalCenter
key: root.key
generation: root.generation
size: root.iconSize
}
Text {
width: parent.width - 4
anchors.horizontalCenter: parent.horizontalCenter
text: root.label
color: "white"
font.pixelSize: root.fontSize
horizontalAlignment: Text.AlignHCenter
elide: Text.ElideRight
style: Text.Raised
styleColor: Qt.rgba(0, 0, 0, .55)
}
}
Rectangle {
visible: root.checkable
width: 20; height: 20; radius: 10
x: parent.width / 2 + root.iconSize / 2 - 12
y: 2
color: root.checked ? "white" : Qt.rgba(0, 0, 0, .35)
border.color: "white"
border.width: 2
Text {
anchors.centerIn: parent
visible: root.checked
text: "✓"
color: "#111"
font.pixelSize: 12
font.bold: true
}
}
}
+302
View File
@@ -0,0 +1,302 @@
#include "backend.h"
#include <QFile>
#include <QGuiApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QScreen>
#include <QSettings>
#include <QTimer>
#include <cmath>
#ifdef Q_OS_ANDROID
#include <QJniEnvironment>
#include <QJniObject>
#endif
namespace {
Backend *g_backend = nullptr;
#ifdef Q_OS_ANDROID
constexpr char kActivity[] = "dev/ultra/launcher/HomeActivity";
QString callString(const char *method) {
return QJniObject::callStaticObjectMethod(kActivity, method, "()Ljava/lang/String;").toString();
}
void callWithString(const char *method, const QString &s) {
QJniObject::callStaticMethod<void>(kActivity, method, "(Ljava/lang/String;)V",
QJniObject::fromString(s).object<jstring>());
}
void callVoid(const char *method) {
QJniObject::callStaticMethod<void>(kActivity, method, "()V");
}
// Called by HomeActivity on Android's main thread: hop over to Qt's.
template <typename F>
void post(F f) {
if (g_backend) QMetaObject::invokeMethod(g_backend, f, Qt::QueuedConnection);
}
void jAppsChanged(JNIEnv *env, jclass, jstring packages) {
const char *c = env->GetStringUTFChars(packages, nullptr);
const QString s = QString::fromUtf8(c);
env->ReleaseStringUTFChars(packages, c);
post([=] { emit g_backend->appsChanged(s); });
}
void jHomePressed(JNIEnv *, jclass) { post([] { emit g_backend->homePressed(); }); }
void jBackPressed(JNIEnv *, jclass) { post([] { emit g_backend->backPressed(); }); }
void jInsets(JNIEnv *, jclass, jint top, jint bottom) { post([=] { g_backend->setInsets(top, bottom); }); }
void jWidgetAdded(JNIEnv *, jclass, jint id) { post([=] { emit g_backend->widgetAdded(id); }); }
void jWidgetMenu(JNIEnv *, jclass, jint id) { post([=] { emit g_backend->widgetMenu(id); }); }
void jWidgetGrab(JNIEnv *, jclass, jint id) { post([=] { emit g_backend->widgetGrab(id); }); }
void jWidgetDrag(JNIEnv *, jclass, jint x, jint y) {
post([=] {
const qreal r = QGuiApplication::primaryScreen()->devicePixelRatio();
emit g_backend->widgetDrag(x / r, y / r);
});
}
void jWidgetDrop(JNIEnv *, jclass, jboolean moved) { post([=] { emit g_backend->widgetDrop(moved); }); }
void jLegacyHome(JNIEnv *env, jclass, jstring json) {
const char *c = env->GetStringUTFChars(json, nullptr);
const QString s = QString::fromUtf8(c);
env->ReleaseStringUTFChars(json, c);
post([=] { emit g_backend->legacyHome(s); });
}
void jAppList(JNIEnv *env, jclass, jstring json) {
const char *c = env->GetStringUTFChars(json, nullptr);
const QByteArray s(c);
env->ReleaseStringUTFChars(json, c);
post([=] { g_backend->takeAppList(s); });
}
void registerNatives() {
static bool done = false;
if (done) return;
done = true;
const JNINativeMethod methods[] = {
{"appsChanged", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jAppsChanged)},
{"homePressed", "()V", reinterpret_cast<void *>(jHomePressed)},
{"backPressed", "()V", reinterpret_cast<void *>(jBackPressed)},
{"insets", "(II)V", reinterpret_cast<void *>(jInsets)},
{"widgetAdded", "(I)V", reinterpret_cast<void *>(jWidgetAdded)},
{"widgetMenu", "(I)V", reinterpret_cast<void *>(jWidgetMenu)},
{"widgetGrab", "(I)V", reinterpret_cast<void *>(jWidgetGrab)},
{"widgetDrag", "(II)V", reinterpret_cast<void *>(jWidgetDrag)},
{"widgetDrop", "(Z)V", reinterpret_cast<void *>(jWidgetDrop)},
{"appList", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jAppList)},
{"legacyHome", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jLegacyHome)},
};
QJniEnvironment env;
env.registerNativeMethods("dev/ultra/launcher/Native", methods, int(std::size(methods)));
}
#endif
QJsonDocument demo(const QString &name) {
QFile f(QStringLiteral(":/qt/qml/Launcher/demo/") + name);
if (!f.open(QIODevice::ReadOnly)) return {};
return QJsonDocument::fromJson(f.readAll());
}
} // namespace
Backend::Backend(QObject *parent) : QObject(parent) { g_backend = this; }
Backend *Backend::instance() { return g_backend; }
bool Backend::isAndroid() const {
#ifdef Q_OS_ANDROID
return true;
#else
return false;
#endif
}
qreal Backend::dpr() const {
QScreen *s = QGuiApplication::primaryScreen();
return s ? s->devicePixelRatio() : 1.0;
}
void Backend::setInsets(int top, int bottom) {
m_insetTop = top / dpr();
m_insetBottom = bottom / dpr();
emit insetsChanged();
}
void Backend::ready() {
#ifdef Q_OS_ANDROID
registerNatives();
callVoid("ready");
#endif
}
static QVariantList appList(const QJsonDocument &doc) {
QVariantList out;
for (const QJsonValue &v : doc.object().value(QStringLiteral("apps")).toArray()) {
const QJsonObject o = v.toObject();
out.append(QVariantMap{{"label", o.value("label").toString()},
{"component", o.value("component").toString()},
{"system", o.value("system").toBool()}});
}
return out;
}
// The app list, and a copy kept for the next start: listing (and labelling) every app
// takes a while on a phone, so the home screen starts from the copy meanwhile.
QVariantList Backend::apps() const {
#ifdef Q_OS_ANDROID
const QByteArray json = callString("apps").toUtf8();
#else
const QByteArray json = demo(QStringLiteral("apps.json")).toJson(QJsonDocument::Compact);
#endif
const QVariantList out = appList(QJsonDocument::fromJson(json));
if (!out.isEmpty()) QSettings().setValue(QStringLiteral("apps"), QString::fromUtf8(json));
return out;
}
// apps(), without holding up the UI thread meanwhile: the list arrives as appsLoaded.
void Backend::requestApps() {
#ifdef Q_OS_ANDROID
callVoid("listApps");
#else
QTimer::singleShot(0, this, [this] { takeAppList(demo(QStringLiteral("apps.json")).toJson(QJsonDocument::Compact)); });
#endif
}
void Backend::takeAppList(const QByteArray &json) {
const QVariantList out = appList(QJsonDocument::fromJson(json));
if (!out.isEmpty()) QSettings().setValue(QStringLiteral("apps"), QString::fromUtf8(json));
emit appsLoaded(out);
}
QVariantList Backend::savedApps() const {
return appList(QJsonDocument::fromJson(QSettings().value(QStringLiteral("apps")).toString().toUtf8()));
}
QVariantList Backend::widgetProviders() const {
#ifdef Q_OS_ANDROID
const QJsonDocument doc = QJsonDocument::fromJson(callString("widgetProviders").toUtf8());
#else
const QJsonDocument doc = demo(QStringLiteral("widgets.json"));
#endif
QVariantList out;
for (const QJsonValue &v : doc.object().value(QStringLiteral("widgets")).toArray()) {
const QJsonObject o = v.toObject();
out.append(QVariantMap{{"label", o.value("label").toString()},
{"app", o.value("app").toString()},
{"provider", o.value("provider").toString()},
{"h", o.value("h").toInt(120)}});
}
return out;
}
#ifdef Q_OS_ANDROID
void Backend::launch(const QString &c) { callWithString("launch", c); }
void Backend::appInfo(const QString &c) { callWithString("appInfo", c); }
void Backend::uninstall(const QString &c) { callWithString("uninstall", c); }
void Backend::openSettings() { callVoid("openSettings"); }
void Backend::pickWallpaper() { callVoid("pickWallpaper"); }
void Backend::openRecents() { callVoid("openRecents"); }
void Backend::checkUpdates() { callVoid("checkUpdates"); }
void Backend::haptic() { callVoid("haptic"); }
void Backend::addWidget(const QString &p) { callWithString("addWidget", p); }
void Backend::removeWidget(int id) { QJniObject::callStaticMethod<void>(kActivity, "removeWidget", "(I)V", jint(id)); }
#else
void Backend::launch(const QString &c) { emit toast("Open " + c); }
void Backend::appInfo(const QString &c) { emit toast("App info for " + c); }
void Backend::uninstall(const QString &c) { emit toast("Uninstall " + c); }
void Backend::openSettings() { emit toast("Open system settings"); }
void Backend::pickWallpaper() { emit toast("Pick a wallpaper"); }
void Backend::openRecents() { emit toast("Show open windows"); }
void Backend::checkUpdates() { emit toast("Check for updates"); }
void Backend::haptic() {}
void Backend::addWidget(const QString &) {
const int id = m_demoWidget++;
QTimer::singleShot(0, this, [this, id] { emit widgetAdded(id); });
}
void Backend::removeWidget(int) {}
#endif
void Backend::placeWidgets(const QVariantList &list) {
#ifdef Q_OS_ANDROID
const qreal r = dpr();
QJsonArray out;
for (const QVariant &v : list) {
const QVariantMap m = v.toMap();
const qreal x = m.value("x").toReal() * r, y = m.value("y").toReal() * r;
const qreal w = m.value("w").toReal() * r, h = m.value("h").toReal() * r;
out.append(QJsonArray{m.value("id").toInt(), qRound(x), qRound(y), qRound(x + w) - qRound(x),
qRound(y + h) - qRound(y), m.value("editing").toBool() ? 1 : 0});
}
callWithString("placeWidgets", QString::fromUtf8(QJsonDocument(out).toJson(QJsonDocument::Compact)));
#else
Q_UNUSED(list);
#endif
}
void Backend::coverWidgets(qreal y) {
#ifdef Q_OS_ANDROID
const int py = y <= 0 ? int(y) : int(std::ceil(y * dpr()));
QJniObject::callStaticMethod<void>(kActivity, "coverWidgets", "(I)V", jint(py));
#else
Q_UNUSED(y);
#endif
}
void Backend::sheetWidgets(qreal y, bool dim) {
#ifdef Q_OS_ANDROID
const int py = y <= 0 ? 0 : int(std::floor(y * dpr()));
QJniObject::callStaticMethod<void>(kActivity, "sheetWidgets", "(IZ)V", jint(py), jboolean(dim));
#else
Q_UNUSED(y);
Q_UNUSED(dim);
#endif
}
QVariantMap Backend::widgetLimits(int id) const {
#ifdef Q_OS_ANDROID
const QJsonObject o = QJsonDocument::fromJson(
QJniObject::callStaticObjectMethod(kActivity, "widgetLimits", "(I)Ljava/lang/String;", jint(id))
.toString().toUtf8()).object();
const qreal r = dpr();
QVariantMap m;
for (const char *k : {"w", "minW", "minH", "maxW", "maxH"}) {
if (o.contains(k)) m.insert(k, o.value(k).toDouble() / r);
}
for (const char *k : {"h", "v"}) {
if (o.contains(k)) m.insert(k, o.value(k).toBool());
}
return m;
#else
Q_UNUSED(id);
return {{"minW", 120}, {"minH", 80}, {"maxW", 0}, {"maxH", 0}, {"h", true}, {"v", true}};
#endif
}
void Backend::excludeGestures(const QVariantList &rects) {
#ifdef Q_OS_ANDROID
const qreal r = dpr();
QJsonArray out;
for (const QVariant &v : rects) {
const QVariantMap m = v.toMap();
out.append(QJsonArray{qRound(m.value("x").toReal() * r), qRound(m.value("y").toReal() * r),
qRound(m.value("w").toReal() * r), qRound(m.value("h").toReal() * r)});
}
callWithString("excludeGestures", QString::fromUtf8(QJsonDocument(out).toJson(QJsonDocument::Compact)));
#else
Q_UNUSED(rects);
#endif
}
QString Backend::loadHome() const {
QSettings s;
return s.value(QStringLiteral("home")).toString();
}
void Backend::saveHome(const QString &json) {
QSettings s;
s.setValue(QStringLiteral("home"), json);
}
+89
View File
@@ -0,0 +1,89 @@
#pragma once
#include <QObject>
#include <QString>
#include <QVariantList>
#include <QVariantMap>
#include <QtQml/qqmlregistration.h>
// The QML app's window onto Android (HomeActivity.java). On a phone each call goes
// through JNI; on a desktop the backend serves demo data from qt/demo and turns the
// actions into toasts, so the UI can be tried and tested without a device.
//
// Geometry in and out of QML is in logical (QML) px; the backend scales it to the
// physical screen px HomeActivity works in.
class Backend : public QObject {
Q_OBJECT
Q_PROPERTY(bool android READ isAndroid CONSTANT)
Q_PROPERTY(qreal insetTop READ insetTop NOTIFY insetsChanged)
Q_PROPERTY(qreal insetBottom READ insetBottom NOTIFY insetsChanged)
public:
explicit Backend(QObject *parent = nullptr);
static Backend *instance();
bool isAndroid() const;
qreal insetTop() const { return m_insetTop; }
qreal insetBottom() const { return m_insetBottom; }
// Lists: [{label, component, system}] and [{label, app, provider, h}].
Q_INVOKABLE QVariantList apps() const;
Q_INVOKABLE void requestApps(); // answers with appsLoaded
Q_INVOKABLE QVariantList savedApps() const; // the last list apps() returned, for a quick start
Q_INVOKABLE QVariantList widgetProviders() const;
Q_INVOKABLE void launch(const QString &component);
Q_INVOKABLE void appInfo(const QString &component);
Q_INVOKABLE void uninstall(const QString &component);
Q_INVOKABLE void openSettings();
Q_INVOKABLE void pickWallpaper();
Q_INVOKABLE void openRecents();
Q_INVOKABLE void checkUpdates();
Q_INVOKABLE void haptic();
// Widgets: addWidget answers with widgetAdded(id) once bound (and configured).
Q_INVOKABLE void addWidget(const QString &provider);
Q_INVOKABLE void removeWidget(int id);
// [{id, x, y, w, h, editing}] in global logical px.
Q_INVOKABLE void placeWidgets(const QVariantList &list);
// The drawer covers the screen down to global logical y; -1 all of it, 0 none.
Q_INVOKABLE void coverWidgets(qreal y);
// A sheet covers the screen from global logical y down (0: none) and dims the rest.
Q_INVOKABLE void sheetWidgets(qreal y, bool dim);
// {w, minW, minH, maxW, maxH (0: no limit), h, v} in logical px.
Q_INVOKABLE QVariantMap widgetLimits(int id) const;
// [{x, y, w, h}] in global logical px: no system back swipe there.
Q_INVOKABLE void excludeGestures(const QVariantList &rects);
// The home layout, as JSON, kept in the app's settings.
Q_INVOKABLE QString loadHome() const;
Q_INVOKABLE void saveHome(const QString &json);
// Tell HomeActivity QML is up (it then adds the widget layer and starts calling back).
Q_INVOKABLE void ready();
// From HomeActivity (on Android's thread; queued to Qt's).
void setInsets(int top, int bottom);
signals:
void insetsChanged();
void appsLoaded(const QVariantList &apps);
void appsChanged(const QString &packages); // comma-separated; empty: any
void homePressed();
void backPressed();
void widgetAdded(int id);
void widgetMenu(int id);
void widgetGrab(int id);
void widgetDrag(qreal x, qreal y); // global logical px
void widgetDrop(bool moved);
void legacyHome(const QString &json); // the WebView build's saved home, read once
void toast(const QString &text); // desktop stand-in for an action
public:
void takeAppList(const QByteArray &json); // HomeActivity's answer to requestApps
private:
qreal dpr() const;
qreal m_insetTop = 0, m_insetBottom = 0;
mutable int m_demoWidget = 100;
};
+67
View File
@@ -0,0 +1,67 @@
#include "iconprovider.h"
#include <QColor>
#include <QPainter>
#include <QUrl>
#include <QElapsedTimer>
#include <QLoggingCategory>
#include <QThread>
Q_LOGGING_CATEGORY(lcIcon, "ultra.icon")
#include <cmath>
#ifdef Q_OS_ANDROID
#include <QJniEnvironment>
#include <QJniObject>
#endif
QImage IconProvider::requestImage(const QString &id, QSize *size, const QSize &requested) {
QString key = id;
const int q = key.lastIndexOf(QLatin1Char('?'));
if (q >= 0) key.truncate(q);
key = QUrl::fromPercentEncoding(key.toUtf8());
const int px = requested.width() > 0 ? requested.width() : 144;
QElapsedTimer took;
took.start();
QImage img;
#ifdef Q_OS_ANDROID
// Premultiplied RGBA, side x side, straight from an Android bitmap.
QJniObject pixels = QJniObject::callStaticObjectMethod(
"dev/ultra/launcher/HomeActivity", "icon", "(Ljava/lang/String;I)[B",
QJniObject::fromString(key).object<jstring>(), jint(px));
if (pixels.isValid()) {
QJniEnvironment env;
auto arr = pixels.object<jbyteArray>();
const jsize n = env->GetArrayLength(arr);
const int side = int(std::lround(std::sqrt(n / 4.0)));
if (side > 0 && jsize(side) * side * 4 == n) {
img = QImage(side, side, QImage::Format_RGBA8888_Premultiplied);
env->GetByteArrayRegion(arr, 0, n, reinterpret_cast<jbyte *>(img.bits()));
}
}
#else
// A disc in a colour picked from the key, with the name's first letter.
img = QImage(px, px, QImage::Format_ARGB32_Premultiplied);
img.fill(Qt::transparent);
QPainter p(&img);
p.setRenderHint(QPainter::Antialiasing);
const QColor c = QColor::fromHsv(int(qHash(key) % 360), 160, 220);
const bool widget = key.startsWith(QLatin1String("w:"));
p.setBrush(c);
p.setPen(Qt::NoPen);
if (widget) p.drawRoundedRect(QRectF(0, 0, px, px), px / 4.0, px / 4.0);
else p.drawEllipse(QRectF(0, 0, px, px));
QString name = key.mid(2).section(QLatin1Char('/'), 0, 0).section(QLatin1Char('.'), -1);
p.setPen(Qt::white);
QFont f;
f.setPixelSize(px * 5 / 12);
f.setBold(true);
p.setFont(f);
p.drawText(QRectF(0, 0, px, px), Qt::AlignCenter, name.left(1).toUpper());
#endif
if (size) *size = img.size();
// Timing, to find what holds icons up on a phone: adb logcat -s ultrahome:*
qCInfo(lcIcon, "icon %s %dpx %lldms%s", qPrintable(key), px, took.elapsed(), img.isNull() ? " (none)" : "");
return img;
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <QQuickImageProvider>
// image://icon/a:COMPONENT is an app's icon, image://icon/w:PROVIDER a widget's.
// On a phone HomeActivity draws them; on a desktop they are lettered discs.
// QML asks with the key percent-encoded and an optional "?n" suffix that only
// busts the pixmap cache after the app list changes.
class IconProvider : public QQuickImageProvider {
public:
IconProvider() : QQuickImageProvider(QQuickImageProvider::Image) {}
QImage requestImage(const QString &id, QSize *size, const QSize &requested) override;
};
+44
View File
@@ -0,0 +1,44 @@
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml/qqmlextensionplugin.h>
#include <QQuickWindow>
#include <QSurfaceFormat>
#include "backend.h"
#include "iconprovider.h"
Q_IMPORT_QML_PLUGIN(LauncherPlugin)
int main(int argc, char *argv[]) {
// The window is see-through: the wallpaper shows behind the home screen.
QQuickWindow::setDefaultAlphaBuffer(true);
QSurfaceFormat fmt = QSurfaceFormat::defaultFormat();
fmt.setAlphaBufferSize(8);
QSurfaceFormat::setDefaultFormat(fmt);
QGuiApplication app(argc, argv);
QGuiApplication::setOrganizationName(QStringLiteral("ultra"));
QGuiApplication::setApplicationName(QStringLiteral("home"));
Backend backend;
QQmlApplicationEngine engine;
engine.addImageProvider(QStringLiteral("icon"), new IconProvider);
qmlRegisterSingletonInstance("Launcher.Host", 1, 0, "Host", &backend);
QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, &app,
[] { QCoreApplication::exit(1); }, Qt::QueuedConnection);
engine.loadFromModule("Launcher", "Main");
if (engine.rootObjects().isEmpty()) return 1;
// Timing of the window's lifecycle, next to the icon timings (category ultra.icon).
QObject::connect(&app, &QGuiApplication::applicationStateChanged, [](Qt::ApplicationState s) {
qInfo("ultra.state %d", int(s));
});
if (auto *win = qobject_cast<QQuickWindow *>(engine.rootObjects().first())) {
QObject::connect(win, &QQuickWindow::sceneGraphInitialized, [] { qInfo("ultra.sg initialized"); });
QObject::connect(win, &QQuickWindow::sceneGraphInvalidated, [] { qInfo("ultra.sg invalidated"); });
QObject::connect(win, &QQuickWindow::frameSwapped, win, [win] {
static int n = 0;
if (n++ < 3) qInfo("ultra.sg frame %d", n);
});
}
return app.exec();
}
+390
View File
@@ -0,0 +1,390 @@
// End-to-end test of the QML launcher against the desktop backend's demo data
// (qt/demo): it drives the window with synthetic touches the way a finger would.
// cmake -S qt -B build && cmake --build build && QT_QPA_PLATFORM=offscreen build/ultrahome_e2e
// ULTRA_SHOTS=dir also saves a screenshot at each step.
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml/qqmlextensionplugin.h>
#include <QQmlContext>
#include <QQmlExpression>
#include <QQuickItem>
#include <QQuickWindow>
#include <QSettings>
#include <QStandardPaths>
#include <QTest>
#include "backend.h"
#include "iconprovider.h"
namespace {
QQuickWindow *win = nullptr;
int failures = 0;
int shot = 0;
QVariant js(const QString &code) {
QQmlExpression e(qmlContext(win), win, code);
QVariant v = e.evaluate();
if (e.hasError()) {
qWarning().noquote() << "JS error in" << code << ":" << e.error().toString();
++failures;
}
if (v.canConvert<QJSValue>()) v = v.value<QJSValue>().toVariant();
return v;
}
void check(bool ok, const QString &what) {
if (!ok) {
++failures;
qWarning().noquote() << "FAIL:" << what;
} else {
qInfo().noquote() << "ok " << what;
}
}
void eq(const QVariant &got, const QVariant &want, const QString &what) {
const bool ok = got == want || got.toString() == want.toString();
check(ok, what + (ok ? QString() : QStringLiteral(" (got %1, want %2)").arg(got.toString(), want.toString())));
}
void settle(int ms = 60) { QTest::qWait(ms); }
void snap(const char *name) {
const QByteArray dir = qgetenv("ULTRA_SHOTS");
if (dir.isEmpty()) return;
win->grabWindow().save(QStringLiteral("%1/%2-%3.png").arg(QString::fromLocal8Bit(dir)).arg(++shot, 2, 10, QLatin1Char('0')).arg(name));
}
QPointF center(const QString &rectJs) {
const QVariantMap r = js(rectJs).toMap();
return {r.value("x").toReal() + r.value("w").toReal() / 2, r.value("y").toReal() + r.value("h").toReal() / 2};
}
// The window rect of home slot i.
QString slotRect(int i) {
return QStringLiteral("(() => { const b = boxOf(%1); return {x: gridX + b.x, y: gridTop + b.y - scrollY, w: b.w, h: b.h}; })()").arg(i);
}
QPoint pt(QPointF p) { return p.toPoint(); }
void press(QPointF p) { QTest::mousePress(win, Qt::LeftButton, {}, pt(p)); }
void release(QPointF p) { QTest::mouseRelease(win, Qt::LeftButton, {}, pt(p)); }
void moveTo(QPointF from, QPointF to, int steps = 8) {
for (int i = 1; i <= steps; ++i) {
QTest::mouseMove(win, pt(from + (to - from) * (qreal(i) / steps)));
QTest::qWait(10);
}
}
void tap(QPointF p) { press(p); settle(30); release(p); settle(); }
void hold(QPointF p) { press(p); QTest::qWait(560); }
void swipe(QPointF from, QPointF to) { press(from); moveTo(from, to, 6); release(to); settle(300); }
QPointF itemCenter(const char *objectName) {
auto *it = win->findChild<QQuickItem *>(QString::fromLatin1(objectName));
if (!it) { qWarning() << "no item" << objectName; ++failures; return {}; }
return it->mapToScene(QPointF(it->width() / 2, it->height() / 2));
}
QString homeLabels() {
return js("home.map(s => s.kind === 'widget' ? '[' + s.str + ']' : apps[appRow[s.str]].label).join(',')").toString();
}
// Tap a sheet's button by its text.
void sheetButton(const QString &text) {
QQuickItem *found = nullptr;
const auto items = win->findChildren<QQuickItem *>();
for (QQuickItem *it : items) {
if (QString::fromLatin1(it->metaObject()->className()).startsWith("SheetButton") && it->isVisible()
&& it->property("text").toString() == text && it->property("enabled").toBool()) {
// only buttons in an open sheet
QQuickItem *p = it->parentItem();
bool open = false;
while (p) {
if (p->property("open").isValid()) { open = p->property("open").toBool(); break; }
p = p->parentItem();
}
if (open) { found = it; break; }
}
}
if (!found) {
qWarning().noquote() << "no sheet button" << text;
for (QQuickItem *it : items)
if (it->property("text").isValid() && it->isVisible())
qWarning() << " " << it->metaObject()->className() << it->property("text").toString();
++failures;
return;
}
settle(250); // let the sheet rise
tap(found->mapToScene(QPointF(found->width() / 2, found->height() / 2)));
}
QStringList sheetButtons() {
QStringList out;
const auto items = win->findChildren<QQuickItem *>();
for (QQuickItem *it : items) {
if (!QString::fromLatin1(it->metaObject()->className()).startsWith("SheetButton") || !it->isVisible()) continue;
QQuickItem *p = it->parentItem();
while (p && !p->property("open").isValid()) p = p->parentItem();
if (p && p->property("open").toBool()) out << it->property("text").toString();
}
return out;
}
} // namespace
Q_IMPORT_QML_PLUGIN(LauncherPlugin)
int main(int argc, char *argv[]) {
QStandardPaths::setTestModeEnabled(true);
QGuiApplication app(argc, argv);
QGuiApplication::setOrganizationName(QStringLiteral("ultra-test"));
QGuiApplication::setApplicationName(QStringLiteral("home-e2e"));
QSettings().clear();
Backend backend;
QQmlApplicationEngine engine;
engine.addImageProvider(QStringLiteral("icon"), new IconProvider);
qmlRegisterSingletonInstance("Launcher.Host", 1, 0, "Host", &backend);
engine.loadFromModule("Launcher", "Main");
if (engine.rootObjects().isEmpty()) return 2;
win = qobject_cast<QQuickWindow *>(engine.rootObjects().first());
win->resize(412, 892);
win->show();
if (!QTest::qWaitForWindowExposed(win)) return 2;
settle(300);
snap("blank");
const QPointF blank(206, 700);
eq(js("home.length"), 0, "home starts blank");
check(js("apps.length").toInt() > 5, "apps load from the demo list");
// the home menu's update check goes to the host and closes the menu
hold(blank); release(blank); settle(300);
eq(js("sheet"), "menu", "a long press on the blank home opens its menu");
snap("menu");
sheetButton("Check for updates");
eq(js("notice"), "Check for updates", "update check goes to the host");
eq(js("sheet"), "", "the menu closes");
// add apps through the drawer's pick mode
hold(blank); release(blank); settle(300);
sheetButton("Add apps");
settle(300);
check(js("drawerOpen && picking").toBool(), "Add apps opens the drawer to pick");
for (const char *name : {"Chrome", "Gmail", "Phone"}) {
js(QStringLiteral("drawer.query = '%1'").arg(name));
settle(100);
auto *grid = win->findChild<QQuickItem *>("drawerGrid");
tap(grid->mapToScene(QPointF(grid->width() / 8, 42)));
js("drawer.query = ''");
}
snap("picking");
eq(js("home.length"), 3, "three apps picked");
js("closeDrawer()");
settle(300);
eq(homeLabels(), "Chrome,Gmail,Phone", "picked apps are on home in order");
snap("three-apps");
// add a widget: long press on blank home, below the apps; search the picker
hold(blank); release(blank); settle(300);
sheetButton("Add widget");
settle(200);
eq(js("sheet"), "widgets", "the widget picker opens");
js("widgetSearch.text = 'cal'");
eq(js("shownProviders.map(i => providers[i].label).join(',')"), "Calendar", "search the picker by widget name");
js("widgetSearch.text = 'weather'");
eq(js("shownProviders.map(i => providers[i].label).join(',')"), "Weather", "or by its app");
js("widgetSearch.text = 'zzz'");
snap("picker-empty");
js("widgetSearch.text = 'clock'");
js("chooseWidget(shownProviders[0])");
settle(100);
eq(homeLabels(), "Chrome,Gmail,Phone,[Clock]", "the widget is added after the apps");
eq(js("home[3].wid"), 100, "with the host's widget id");
snap("widget");
// hold a home app and drag it over another: reorder
hold(center(slotRect(0)));
eq(js("lifted"), 0, "a long press lifts the slot");
moveTo(center(slotRect(0)), center(slotRect(1)));
release(center(slotRect(1)));
settle();
eq(homeLabels(), "Gmail,Chrome,Phone,[Clock]", "dragging over the next app swaps them");
eq(js("sheet"), "", "a drag doesn't open the menu");
eq(js("lifted"), -1, "letting go drops it");
// hold without moving: the menu, and Move later
hold(center(slotRect(0))); release(center(slotRect(0))); settle(300);
eq(js("sheet"), "item", "holding an app without moving opens its menu");
snap("item-menu");
sheetButton("Move later");
eq(homeLabels(), "Chrome,Gmail,Phone,[Clock]", "Move later");
// the grid runs down the screen; an app dropped in an empty cell there stays in it
check(js("nrows").toInt() >= 8, QStringLiteral("rows fill the screen (%1)").arg(js("nrows").toInt()));
{
const QPointF from = center(slotRect(1));
const QPointF to = from + QPointF(10, 6 * 72);
hold(from);
moveTo(from, to, 1); // a quick move, straight past the widget
release(to);
settle();
eq(js("[home[1].x, home[1].y].join(',')"), "1,6", "Gmail is left six rows down");
eq(js("packed.cells[0].col"), 0, "Chrome stays in the first cell");
eq(js("packed.cells[2].col"), 1, "Phone flows up into the cell Gmail left");
snap("pinned");
// dragging it back over an app puts it back in the packed order
const QPointF back = center(slotRect(0));
hold(to);
moveTo(to, back);
release(back);
settle();
eq(homeLabels(), "Gmail,Chrome,Phone,[Clock]", "dragged back over Chrome, it takes its place");
eq(js("home[0].x"), -1, "and is in the flow again");
}
// swipe down opens the drawer; search; Enter opens the first match
swipe(QPointF(206, 400), QPointF(206, 600));
check(js("drawerOpen").toBool(), "swipe down opens the drawer");
eq(js("liveSlots.length"), 0, "no live widget slots under the drawer");
snap("drawer");
js("drawer.query = 'ma'");
eq(js("drawer.shown.map(i => apps[i].label).join(',')"), "Gmail,Maps", "the search filters the list");
{
// the clear button empties the search and shows every app again
settle(100);
snap("search");
auto *clear = win->findChild<QQuickItem *>("searchClear");
check(clear && clear->isVisible(), "the search shows a clear button");
if (clear) tap(clear->mapToScene(QPointF(clear->width() / 2, clear->height() / 2)));
eq(js("drawer.query"), "", "tapping it clears the search");
eq(js("drawer.shown.length === apps.length"), true, "and every app shows again");
check(clear && !clear->isVisible(), "the clear button goes");
js("drawer.query = 'ma'");
}
js("drawer.openFirst()");
settle(300);
eq(js("notice"), "Open com.example.gmail/.MainActivity", "opening the first match launches it");
check(!js("drawerOpen").toBool(), "launching closes the drawer");
// the drawer's long-press menu: Uninstall, not for system apps
swipe(QPointF(206, 400), QPointF(206, 600));
js("drawer.query = 'calc'");
settle(100);
{
auto *grid = win->findChild<QQuickItem *>("drawerGrid");
const QPointF p = grid->mapToScene(QPointF(grid->width() / 8, 42));
hold(p); release(p); settle(300);
}
eq(sheetButtons().join(','), "Add to home,App info,Uninstall", "an app's menu in the drawer");
snap("app-menu");
sheetButton("Uninstall");
eq(js("notice"), "Uninstall com.example.calculator/.MainActivity", "Uninstall goes to the host");
check(js("sheet === '' && drawerOpen").toBool(), "uninstalling closes the menu, not the drawer");
js("appSheetRow = drawer.shown[0]; sheet = 'app'");
settle(250);
sheetButton("Add to home");
eq(js("notice"), "Added to home", "Add to home says so");
js("back()");
settle(300);
eq(homeLabels(), "Gmail,Chrome,Phone,[Clock],Calculator", "added at the end");
// the uninstalled app leaves home once it is gone from the list
js("apps = apps.filter(a => a.label !== 'Calculator'); const r = {}; apps.forEach((a, i) => r[a.component] = i); appRow = r; dropGone()");
eq(homeLabels(), "Gmail,Chrome,Phone,[Clock]", "uninstalled apps leave home");
// tap launches
tap(center(slotRect(0)));
eq(js("notice"), "Open com.example.gmail/.MainActivity", "tapping a home app opens it");
// the search pill on the front page opens the drawer (its search focuses there)
tap(itemCenter("homeSearch"));
check(js("drawerOpen").toBool(), "tapping the home search opens the drawer");
snap("home-search");
js("closeDrawer()");
settle(300);
check(!js("drawerOpen").toBool(), "and it closes again");
// hold a widget without moving: resize handles; drag them to snap it to the grid
hold(center(slotRect(3))); release(center(slotRect(3))); settle(200);
eq(js("resizing"), 3, "a widget gets handles, not the menu");
eq(js("sheet"), "", "and no menu");
snap("resizing");
{
auto *rb = win->findChild<QQuickItem *>("handleRB");
const QPointF from = rb->mapToScene(QPointF(rb->width() / 2, rb->height() / 2));
const QVariantMap r = js(slotRect(3)).toMap();
const qreal colW = js("colW").toReal();
const QPointF to(r.value("x").toReal() + colW * 2.1, r.value("y").toReal() + 140);
press(from);
moveTo(from, to);
release(to);
settle();
eq(js("[home[3].w, home[3].rows].join(',')"), "2,2", "snapped to two columns, two rows");
eq(js("resizing"), 3, "letting go of a handle keeps the handles");
snap("resized");
}
// while it shows handles, dragging the widget itself moves it, without another long press
{
const QPointF from = center(slotRect(3));
const QVariantMap r = js(slotRect(3)).toMap();
const QPointF grabAt(r.value("x").toReal() + 20, r.value("y").toReal() + 20);
const QPointF to(js("gridX").toReal() + 20, js("gridTop").toReal() + 20);
Q_UNUSED(from);
press(grabAt);
settle(30);
eq(js("lifted"), 3, "pressing a widget with handles picks it up");
moveTo(grabAt, to);
release(to);
settle();
eq(js("[home[3].x, home[3].y].join(',')"), "0,0", "dragged onto the top row, first cell");
eq(js("packed.cells.filter((c, i) => i !== 3 && c.row < 2).length"), 3, "the apps fill the cells beside it");
eq(js("resizing"), 3, "it keeps its handles after the move");
snap("moved-widget");
}
// Done, then Remove from its menu
js("resizing = -1");
hold(center(slotRect(3)));
eq(js("lifted"), 3, "hold lifts the widget");
release(center(slotRect(3)));
settle(100);
eq(js("resizing"), 3, "and letting go shows the handles");
js("removeSlot(resizing); resizing = -1");
eq(homeLabels(), "Gmail,Chrome,Phone", "the widget is removed");
// saved, and loaded again
js("loadHome()");
eq(homeLabels(), "Gmail,Chrome,Phone", "the layout is saved");
// Starting again: the saved app list names the home tiles before the real list loads,
// and nothing is hidden meanwhile.
js("apps = []; appRow = ({}); loading = true; setApps(Host.savedApps())");
eq(homeLabels(), "Gmail,Chrome,Phone", "home tiles come from the saved app list");
js("apps = []; appRow = ({})");
eq(js("hidden.some(h => h)"), false, "nothing is hidden before the list loads");
js("loadApps()");
// A changed package reloads only its own icons.
emit backend.appsChanged(QStringLiteral("com.example.chrome"));
settle(50);
eq(js("gen('com.example.chrome/.MainActivity') + ',' + gen('com.example.gmail/.MainActivity')"), "1,0",
"a changed app's icons reload, the rest stay");
// The WebView build's saved home merges in: new slots go after, unpinned.
emit backend.legacyHome(QStringLiteral(
"{\"ultra.home.n\":\"3\",\"ultra.home.str.0\":\"com.example.clock/.MainActivity\","
"\"ultra.home.cx.0\":\"4\",\"ultra.home.cy.0\":\"4\",\"ultra.home.str.1\":\"com.example.chrome/.MainActivity\","
"\"ultra.home.kind.2\":\"1\",\"ultra.home.str.2\":\"Weather\",\"ultra.home.wid.2\":\"7\",\"ultra.home.h.2\":\"200\"}"));
settle(50);
eq(homeLabels(), "Gmail,Chrome,Phone,Clock,[Weather]", "the old home is brought over");
eq(js("home[3].x"), -1, "unpinned when merged");
eq(js("home[4].rows"), 3, "widget px become rows");
// back closes things in order; home closes everything
swipe(QPointF(206, 400), QPointF(206, 600));
js("back()");
settle(300);
check(!js("drawerOpen").toBool(), "back closes the drawer");
snap("end");
if (failures) qWarning() << failures << "failures";
else qInfo() << "e2e ok";
return failures ? 1 : 0;
}
+76
View File
@@ -0,0 +1,76 @@
// node qt/tests/layout.test.mjs: checks the home grid packing in qml/Layout.js.
import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
const src = readFileSync(new URL("../qml/Layout.js", import.meta.url), "utf8").replace(".pragma library", "");
const L = new Function(src + "; return {widgetRows, slotW, slotH, pack, box, cellAt, pin, clearCells, move, fit, widgetCols, legacy};")();
const app = (x = -1, y = -1) => ({ kind: "app", str: "a", x, y });
const widget = (w, rows, x = -1, y = -1) => ({ kind: "widget", str: "W", wid: 1, w, rows, x, y });
const cells = (home, cols = 5, nrows = 0) => L.pack(home, cols, nrows).cells.map((c) => c && [c.col, c.row, c.w, c.h]);
// Apps fill rows left to right.
assert.deepEqual(cells([app(), app(), app(), app(), app(), app()]),
[[0, 0, 1, 1], [1, 0, 1, 1], [2, 0, 1, 1], [3, 0, 1, 1], [4, 0, 1, 1], [0, 1, 1, 1]]);
// A whole-row widget takes its rows; apps after it go below.
assert.deepEqual(cells([widget(0, 2), app()]), [[0, 0, 5, 2], [0, 2, 1, 1]]);
// Dense: apps fill the cells beside a narrow widget, before and after it in order.
assert.deepEqual(cells([widget(3, 2), app(), app(), app(), app(), app()]),
[[0, 0, 3, 2], [3, 0, 1, 1], [4, 0, 1, 1], [3, 1, 1, 1], [4, 1, 1, 1], [0, 2, 1, 1]]);
// A widget too wide for what's left of a row starts the next one, and apps backfill.
assert.deepEqual(cells([app(), app(), app(), widget(3, 1), app()]),
[[0, 0, 1, 1], [1, 0, 1, 1], [2, 0, 1, 1], [0, 1, 3, 1], [3, 0, 1, 1]]);
// Pinned slots keep their cell; the rest flow around them.
assert.deepEqual(cells([app(), app(2, 3), app()]), [[0, 0, 1, 1], [2, 3, 1, 1], [1, 0, 1, 1]]);
// Rows: at least nrows, more if the slots need them.
assert.equal(L.pack([app()], 5, 9).rows, 9);
assert.equal(L.pack([app(0, 12)], 5, 9).rows, 13);
// A pin that no longer fits the columns flows instead.
assert.deepEqual(cells([widget(3, 1, 3, 0)], 5), [[0, 0, 3, 1]]);
// Hidden slots (apps no longer installed) take no cell.
assert.deepEqual(L.pack([app(), app()], 5, 0, [true, false]).cells.map((c) => c && c.col), [null, 0]);
// Pinning stays on the grid; dropping a pinned slot moves pinned slots off its cells.
{
const h = [widget(2, 2), app(1, 1), app(4, 4)];
L.pin(h, 0, 4, 9, 5, 8);
assert.deepEqual([h[0].x, h[0].y], [3, 6]);
L.pin(h, 0, 0, 0, 5, 8);
L.clearCells(h, 0, 5);
assert.deepEqual([h[1].x, h[1].y, h[2].x, h[2].y], [-1, -1, 4, 4]);
}
// Moving in the order.
{
const h = ["a", "b", "c", "d"];
L.move(h, 0, 2);
assert.deepEqual(h, ["b", "c", "a", "d"]);
L.move(h, 3, 0);
assert.deepEqual(h, ["d", "b", "c", "a"]);
}
// Widget heights in px to rows (64px rows, 8px gaps), as the old launcher stored them.
assert.deepEqual([40, 64, 100, 136, 208, 420].map(L.widgetRows), [1, 1, 2, 2, 3, 6]);
// Resize steps snap to cells within the widget's limits.
assert.equal(L.fit(150, 1, 5, 64, 8, 0, 0), 2);
assert.equal(L.fit(10, 1, 5, 64, 8, 200, 0), 3);
assert.equal(L.fit(400, 1, 5, 64, 8, 0, 150), 2);
// A new widget's columns from its natural width.
assert.equal(L.widgetCols(0, 70, 5), 0);
assert.equal(L.widgetCols(110, 70, 5), 2);
assert.equal(L.widgetCols(400, 70, 5), 0);
// Boxes and cells in px.
assert.deepEqual(L.box({ col: 1, row: 2, w: 2, h: 1 }, 70), { x: 78, y: 144, w: 148, h: 64 });
assert.deepEqual(L.cellAt(80, 150, 70), [1, 2]);
console.log("layout ok");
// The WebView build's saved home converts: apps by component, widgets with px heights to rows.
assert.deepEqual(L.legacy({
"ultra.home.n": "3",
"ultra.home.kind.0": "0", "ultra.home.str.0": "com.a/.Main", "ultra.home.cx.0": "-1", "ultra.home.cy.0": "-1",
"ultra.home.kind.1": "1", "ultra.home.str.1": "Clock", "ultra.home.wid.1": "12", "ultra.home.h.1": "136",
"ultra.home.w.1": "3", "ultra.home.cx.1": "1", "ultra.home.cy.1": "2",
"ultra.home.kind.2": "0",
}), [
{ kind: "app", str: "com.a/.Main", x: -1, y: -1 },
{ kind: "widget", str: "Clock", wid: 12, w: 3, rows: 2, x: 1, y: 2 },
]);
assert.deepEqual(L.legacy({}), []);
+189
View File
@@ -0,0 +1,189 @@
// Browser smoke test for the launcher's web UI, against the demo apps.json and widgets.json.
// pixi run test (or: pixi run serve & then node tests/e2e.cjs)
const assert = require("assert");
const { chromium } = require(process.env.PLAYWRIGHT || "playwright");
const BASE = process.env.BASE || "http://localhost:8000";
(async () => {
const b = await chromium.launch();
const p = await b.newPage();
p.on("pageerror", (e) => { console.error("page error:", e.message); process.exitCode = 1; });
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 + "/");
await p.evaluate(() => localStorage.clear());
await p.reload();
await p.waitForSelector(".hint");
assert.ok(!(await p.$(".clock")), "home has no built-in clock");
const longpress = async (sel, fy = 0.5) => {
const r = await p.locator(sel).first().boundingBox();
await p.mouse.move(r.x + r.width / 2, r.y + r.height * fy);
await p.mouse.down(); await p.waitForTimeout(650); await p.mouse.up(); await settle();
};
// the home menu's update check goes to the shell and closes the menu
await longpress(".hint");
await p.click(".sheet-item >> text=Check for updates"); await settle();
assert.equal(await p.textContent("#toast"), "Check for updates");
assert.ok(!(await p.$(".sheet")), "the menu closes");
const homeApps = () => p.$$eval(".slots .name", (ns) => ns.map((n) => n.textContent));
// long press on the blank home: add apps through the drawer's pick mode
await longpress(".hint");
await p.click(".sheet-item >> text=Add apps"); await settle();
for (const i of [4, 8, 12]) await p.click(`.apps .tile:nth-child(${i})`);
await settle();
assert.equal(await p.$$eval(".apps .tile.on", (ts) => ts.length), 3);
await p.click(".drawer-head >> text=Done"); await settle();
assert.deepEqual(await homeApps(), ["Chrome", "Gmail", "Phone"]);
// add a widget: long press on blank home, below the apps
await longpress(".home", 0.95);
await p.click(".sheet-item >> text=Add widget");
await p.waitForSelector(".widget-list li");
// search the picker by widget name and by the app it comes from
const widgetNames = () => p.$$eval(".widget-list .widget-name", (ns) => ns.map((n) => n.firstChild.textContent));
await p.fill(".widget-search", "cal"); await settle();
assert.deepEqual(await widgetNames(), ["Calendar"]);
await p.fill(".widget-search", "goo"); await settle();
assert.deepEqual(await widgetNames(), ["Weather"]);
await p.fill(".widget-search", "zzz"); await settle();
assert.equal(await p.textContent(".sheet .empty"), "No widgets match.");
await p.fill(".widget-search", ""); await settle();
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");
// hold a home app and drag it: reorder
const drag = async (from, to) => {
const a = await p.locator(from).first().boundingBox(), z = await p.locator(to).first().boundingBox();
await p.mouse.move(a.x + a.width / 2, a.y + a.height / 2);
await p.mouse.down(); await p.waitForTimeout(650); await settle();
assert.ok(await p.$(".slots > .lifted"), "a long press lifts the slot");
await p.mouse.move(z.x + z.width / 2, z.y + z.height / 2, { steps: 5 }); await settle();
await p.mouse.up(); await settle();
};
await drag(".slots .tile:nth-child(2)", ".slots .tile:nth-child(1)");
assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]);
assert.ok(!(await p.$(".sheet")), "a drag doesn't open the menu");
assert.ok(!(await p.$(".slots > .lifted")));
await drag(".slots .tile:nth-child(1)", ".slots .tile:nth-child(3)");
assert.deepEqual(await homeApps(), ["Chrome", "Phone", "Gmail"]);
// hold without moving: the menu
await longpress(".slots .tile:nth-child(3)");
await p.click(".sheet-item >> text=Move earlier"); await settle();
assert.deepEqual(await homeApps(), ["Chrome", "Gmail", "Phone"]);
await longpress(".slots .tile:nth-child(1)");
await p.click(".sheet-item >> text=Move later"); await settle();
assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]);
// the grid runs down the screen; an app dropped in an empty cell there stays in it,
// and the rest stay packed
const rows = await p.$eval(".slots", (s) => getComputedStyle(s).gridTemplateRows.split(" ").length);
assert.ok(rows >= 5, `rows fill the screen: ${rows}`);
const tileAt = (n) => p.locator(`.slots .tile:has-text("${n}")`).boundingBox();
const g0 = await tileAt("Gmail"), c0 = await tileAt("Chrome"), pitch = 64 + 8;
await p.mouse.move(g0.x + g0.width / 2, g0.y + g0.height / 2);
await p.mouse.down(); await p.waitForTimeout(650); await settle();
await p.mouse.move(g0.x + g0.width / 2 + 10, g0.y + g0.height / 2 + 4 * pitch, { steps: 6 }); await settle();
await p.mouse.up(); await settle();
const g1 = await tileAt("Gmail"), c1 = await tileAt("Chrome");
assert.ok(Math.abs(g1.y - g0.y - 4 * pitch) < 3, `left four rows down: ${g1.y - g0.y}`);
assert.equal(Math.round(c1.x), Math.round(g0.x), "Chrome moves up into the packed first cell");
await p.reload(); await p.waitForSelector(".slots .tile");
assert.ok(Math.abs((await tileAt("Gmail")).y - g1.y) < 3, "its cell is saved");
// dragging it back over an app puts it back in the packed order
const c2 = await tileAt("Chrome");
await p.mouse.move(g1.x + g1.width / 2, g1.y + g1.height / 2);
await p.mouse.down(); await p.waitForTimeout(650); await settle();
await p.mouse.move(c2.x + c2.width / 2, c2.y + c2.height / 2, { steps: 6 }); await settle();
await p.mouse.up(); await settle();
assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]);
assert.ok(Math.abs((await tileAt("Gmail")).y - c0.y) < 3, "back in the first row");
await p.mouse.click(5, 300); await settle(); // a tap on empty home ends the drag gesture
// 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);
assert.ok(await p.$eval(".drawer input", (i) => i === document.activeElement), "opening the drawer focuses its search");
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.deepEqual(await p.$$eval(".sheet-item", (bs) => bs.map((b) => b.textContent)), ["Add to home", "App info", "Uninstall"]);
await p.click(".sheet-item:has-text('Uninstall')"); await settle();
assert.equal(await p.textContent("#toast"), "Uninstall com.example.calculator/.MainActivity");
assert.ok(!(await p.$(".sheet")) && (await p.$(".drawer")), "uninstalling closes the menu, not the drawer");
await p.fill(".drawer input", "phone"); await settle();
await longpress(".apps .tile:first-child");
assert.ok(!(await p.$(".sheet-item:has-text('Uninstall')")), "system apps can't be uninstalled");
await p.click(".sheet-overlay", { position: { x: 10, y: 10 } }); await p.fill(".drawer input", ""); await settle();
await longpress(".apps .tile:first-child");
await p.click(".sheet-item:has-text('Add to home')"); await settle();
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");
// hold a widget without moving: resize handles; drag them to snap it to the grid
await longpress(".widget-slot");
assert.ok(!(await p.$(".sheet")), "a widget gets handles, not the menu");
assert.ok(await p.$(".widget-slot.resizing .resize-handle[data-edge=rb]"));
const size = () => p.$eval(".widget-slot", (w) => [Math.round(w.getBoundingClientRect().width), Math.round(w.getBoundingClientRect().height)]);
const [w0] = await size();
const tile = await p.locator(".slots .tile").first().boundingBox();
const hd = await p.locator(".resize-handle[data-edge=rb]").boundingBox();
await p.mouse.move(hd.x + hd.width / 2, hd.y + hd.height / 2);
await p.mouse.down();
const ws = await p.locator(".widget-slot").boundingBox();
await p.mouse.move(ws.x + tile.width * 2.1, ws.y + 140, { steps: 8 }); await settle();
await p.mouse.up(); await settle();
const [w1, h1] = await size();
assert.ok(w1 < w0 && Math.abs(w1 - (2 * tile.width + 8)) < 3, `two columns wide: ${w1} (tile ${tile.width})`);
assert.equal(h1, 2 * 64 + 8, "snapped to two whole rows of tiles");
assert.ok(await p.$(".widget-slot.resizing"), "letting go of a handle keeps the handles");
await p.click(".resize-bar >> text=Done"); await settle();
assert.ok(!(await p.$(".resize-handle")));
await p.reload(); await p.waitForSelector(".widget-slot");
assert.deepEqual(await size(), [w1, h1], "the size is saved");
// while it shows handles, dragging the widget itself moves it, without another long press
await longpress(".widget-slot");
const atStart = () => p.$eval(".widget-slot", (w) => {
const r = w.getBoundingClientRect(), s = w.parentElement.getBoundingClientRect();
return Math.abs(r.left - s.left) < 2 && Math.abs(r.top - s.top) < 2;
});
assert.ok(!(await atStart()));
const wb = await p.locator(".widget-slot").boundingBox(), first = await p.locator(".slots > li").first().boundingBox();
await p.mouse.move(wb.x + wb.width / 2, wb.y + wb.height / 2);
await p.mouse.down(); await settle();
assert.ok(await p.$(".widget-slot.lifted"), "pressing a widget with handles picks it up");
await p.mouse.move(first.x + first.width / 2, first.y + first.height / 2, { steps: 8 }); await settle();
await p.mouse.up(); await settle();
assert.ok(await atStart(), "dragged onto the top row, first cell");
// the apps flow into the cells beside it: a 2x2 widget in 5 columns leaves room for all four
const beside = await p.$eval(".widget-slot", (w) => {
const r = w.getBoundingClientRect();
return [...document.querySelectorAll(".slots .tile")].filter((t) => {
const b = t.getBoundingClientRect(); return b.top >= r.top - 1 && b.bottom <= r.bottom + 1;
}).length;
});
assert.equal(beside, 4, "apps fill the cells beside the widget");
assert.ok(await p.$(".widget-slot.resizing"), "it keeps its handles after the move");
assert.ok(!(await p.$(".sheet")));
await p.click(".resize-bar >> text=Remove"); 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");
await b.close();
})().catch((e) => { console.error(e); process.exit(1); });
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python3
"""Serve web/ on a free port and run tests/e2e.cjs against it (`pixi run test`)."""
import os
import subprocess
import sys
import threading
from ultra_tool import make_server
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
srv = make_server(os.path.join(ROOT, "web"), 0, quiet=True)
threading.Thread(target=srv.serve_forever, daemon=True).start()
r = subprocess.run(["node", os.path.join(ROOT, "tests", "e2e.cjs")], cwd=ROOT,
env={**os.environ, "BASE": f"http://localhost:{srv.server_address[1]}"})
srv.shutdown()
sys.exit(r.returncode)
+27
View File
@@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.21)
project(launcher_wasi C CXX)
include(${QT2WASM_ROOT}/cmake/Qt2Wasm.cmake)
set(FONTS_QRC_CPP "${CMAKE_CURRENT_BINARY_DIR}/qrc_fonts.cpp")
add_custom_command(
OUTPUT "${FONTS_QRC_CPP}"
COMMAND "${QT2WASM_QT_PREFIX}/../host/libexec/rcc"
--name fonts
-o "${FONTS_QRC_CPP}"
"${CMAKE_CURRENT_SOURCE_DIR}/fonts.qrc"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/fonts.qrc"
"${CMAKE_CURRENT_SOURCE_DIR}/fonts/DejaVuSans.ttf"
"${CMAKE_CURRENT_SOURCE_DIR}/fonts/DejaVuSans-Bold.ttf"
COMMENT "Compiling fonts.qrc"
)
qt2wasm_add_component(launcher GUI
SOURCES
src/main.cpp
src/launcher_window.cpp
src/layout.cpp
"${FONTS_QRC_CPP}"
INCLUDE_DIRS
src
)
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
QT2WASM_ROOT="${QT2WASM_ROOT:-$(python3 -c 'import qt2wasm, pathlib; print(pathlib.Path(qt2wasm.__file__).parent / "_data")')}"
QT2WASM_COMPAT_DIR="${QT2WASM_COMPAT_DIR:-$CONDA_PREFIX/opt/qt6-wasi/compat}"
MOC="${QT2WASM_MOC:-$QT_WASI_HOST_PATH/libexec/moc}"
BUILD_DIR="build"
GEN_DIR="$PWD/$BUILD_DIR/gen"
mkdir -p "$GEN_DIR/bindings" "$GEN_DIR/runtime"
# 1. Generate C guest bindings for `world gui` (latha:gui/gui + ultra:launcher/android).
wit-bindgen c --world gui --out-dir "$GEN_DIR/bindings" wit
# 2. Run moc on qt2wasm runtime headers and our window class.
"$MOC" "$QT2WASM_ROOT/runtime/wasieventdispatcher.h" -o "$GEN_DIR/runtime/moc_wasieventdispatcher.cpp"
"$MOC" "$QT2WASM_ROOT/gui/qt2wasmgui.h" -o "$GEN_DIR/runtime/moc_qt2wasmgui.cpp"
"$MOC" "src/launcher_window.h" -o "$GEN_DIR/moc_launcher_window.cpp"
# 3. Configure and link the core WASI reactor module.
cmake -S . -B "$BUILD_DIR" -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE="$QT2WASM_QT_TOOLCHAIN" \
-DQT2WASM_ROOT="$QT2WASM_ROOT" \
-DQT2WASM_QT_PREFIX="$QT2WASM_QT_PREFIX" \
-DQT2WASM_GEN_DIR="$GEN_DIR" \
-DQT2WASM_COMPAT_DIR="$QT2WASM_COMPAT_DIR" \
-DQT2WASM_GUI_WORLD=gui \
-DQT2WASM_QPA_PLATFORM=qt2wasmgui
cmake --build "$BUILD_DIR"
# 4. Wrap as a WASI Preview 2 component.
wasm-tools component new "$BUILD_DIR/launcher.core.wasm" \
--adapt "wasi_snapshot_preview1=$QT2WASM_ADAPTER" \
-o "$BUILD_DIR/launcher.wasm"
echo "Built $PWD/$BUILD_DIR/launcher.wasm ($(stat -c%s "$BUILD_DIR/launcher.wasm") bytes)"
+6
View File
@@ -0,0 +1,6 @@
<RCC>
<qresource prefix="/qt2wasm/fonts">
<file alias="DejaVuSans.ttf">fonts/DejaVuSans.ttf</file>
<file alias="DejaVuSans-Bold.ttf">fonts/DejaVuSans-Bold.ttf</file>
</qresource>
</RCC>
Binary file not shown.
Binary file not shown.
+1000
View File
@@ -0,0 +1,1000 @@
version: 7
platforms:
- name: linux-64
virtual-packages:
- __unix=0=0
- __linux=4.18
- __glibc=2.28
- __archspec=0=x86_64
environments:
default:
channels:
- url: https://prefix.dev/nandi-testing/
- url: https://conda.anaconda.org/conda-forge/
packages:
linux-64:
- conda: https://conda.anaconda.org/conda-forge/linux-64/binaryen-121-h5888daf_0.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/brotli-1.2.1-h505cf86_0.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/brotli-bin-1.2.1-h9908984_0.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/cmake-4.5.0-hff7ac6b_0.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/fonttools-4.68.0-py315h4d0d421_0.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/markupsafe-3.0.4-py315h4aa9e2b_4.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/ninja-1.13.2-h171cf75_1.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/pyyaml-6.0.3-py315h178884a_3.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/rhash-1.4.6-hb03c661_2.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/yaml-0.2.5-hebe6cf0_3.conda
- conda: https://conda.anaconda.org/conda-forge/linux-64/zensical-0.1.1-py311h7b25dd4_0.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/_python_abi3_support-1.0-hd8ed1ab_3.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/click-8.5.1-pyh5ded981_0.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/cpython-3.15.2-py315hd8ed1ab_100.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/jinja2-3.1.6-pyhcf101f3_1.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/markdown-3.11.3-pyh5ded981_0.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/munkres-1.1.4-pyhd8ed1ab_1.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/pathspec-1.1.1-pyhd8ed1ab_0.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/pygments-2.21.0-pyhcf101f3_0.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/pymdown-extensions-13.1-pyhd8ed1ab_0.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/python-gil-3.15.2-h4df99d1_100.conda
- conda: https://conda.anaconda.org/conda-forge/noarch/zensical-ui-0.0.42-pyh5ded981_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/_openmp_mutex-4.5-20_gnu.conda
- conda: https://prefix.dev/nandi-testing/linux-64/bzip2-1.0.8-hda65f42_10.conda
- conda: https://prefix.dev/nandi-testing/linux-64/c-ares-1.34.9-hebe6cf0_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/icu-78.3-py310h44b86e0_2.conda
- conda: https://prefix.dev/nandi-testing/linux-64/jco-1.41.0-hb0f4dca_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/keyutils-1.6.3-h7cc23a3_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/krb5-1.22.2-hbc21106_2.conda
- conda: https://prefix.dev/nandi-testing/linux-64/ld_impl_linux-64-2.46.1-default_hbd61a6d_103.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libabseil-20260526.0-cxx17_h0dc7533_2.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libbrotlicommon-1.2.1-h39a168f_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libbrotlidec-1.2.1-ha411449_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libbrotlienc-1.2.1-h018ffa1_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libcurl-8.23.0-ha042cf0_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libedit-3.1.20260512-pl5321h373387f_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libev-4.33-h280c20c_3.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libexpat-2.9.0-hd2095e1_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libffi-3.7.0-h81df57d_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libgcc-16.2.0-ha9f2e26_7.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libgomp-16.2.0-he0feb66_7.conda
- conda: https://prefix.dev/nandi-testing/linux-64/liblzma-5.8.3-hb03c661_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libmpdec-4.0.0-hb03c661_2.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libnghttp2-1.71.0-hc5e5977_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libpsl-0.23.1-hd9e3e90_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libsqlite-3.54.1-h13e7031_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libssh2-1.11.1-h6154650_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libstdcxx-16.2.0-h934c35e_7.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libuuid-2.42.4-hcfc3c73_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libuv-1.52.1-h280c20c_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/libzlib-1.3.2-h25fd6f3_3.conda
- conda: https://prefix.dev/nandi-testing/linux-64/ncurses-6.6-hdb14827_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/nodejs-26.10.0-ha5cdc1e_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/openssl-3.6.5-h781a0a9_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/python-3.15.2-h6e52b48_100_cp315.conda
- conda: https://prefix.dev/nandi-testing/linux-64/qt6-wasi-6.8.3-hb0f4dca_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/tk-8.6.13-noxft_h1df4ec4_4.conda
- conda: https://prefix.dev/nandi-testing/linux-64/wasi-sdk-27.0-hb0f4dca_1.conda
- conda: https://prefix.dev/nandi-testing/linux-64/wasm-tools-1.239.0-hb0f4dca_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/wit-bindgen-0.46.0-hb0f4dca_0.conda
- conda: https://prefix.dev/nandi-testing/linux-64/zstd-1.5.7-hb78ec9c_7.conda
- conda: https://prefix.dev/nandi-testing/noarch/ca-certificates-2026.10.23-hbd8a1cb_0.conda
- conda: https://prefix.dev/nandi-testing/noarch/importlib-metadata-9.0.1-pyhcf101f3_0.conda
- conda: https://prefix.dev/nandi-testing/noarch/python_abi-3.15-9_cp315.conda
- conda: https://prefix.dev/nandi-testing/noarch/qt2wasm-0.10.6-pyh4616a5c_0.conda
- conda: https://prefix.dev/nandi-testing/noarch/tomli-2.5.0-pyh5ded981_0.conda
- conda: https://prefix.dev/nandi-testing/noarch/tzdata-2026e-h5d301ff_0.conda
- conda: https://prefix.dev/nandi-testing/noarch/wasi-preview1-adapter-36.0.0-h4616a5c_0.conda
- conda: https://prefix.dev/nandi-testing/noarch/zipp-4.1.2-pyh5ded981_0.conda
packages:
- conda: https://conda.anaconda.org/conda-forge/linux-64/binaryen-121-h5888daf_0.conda
sha256: 01233c9dc409bd6285c03598409d6f9b86aaad88005088b2d72de54ed06d44f1
md5: c331a601e8643b96889adbd82961c290
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=13
- libstdcxx >=13
license: Apache-2.0
license_family: APACHE
run_exports: {}
size: 6054210
timestamp: 1734410441026
- conda: https://conda.anaconda.org/conda-forge/linux-64/brotli-1.2.1-h505cf86_0.conda
sha256: 3efb8e6ac07f12773f02e876567700f554965e33a8e30ee05ddd891c303f7aa3
md5: 65f1fc5f6a3a984a8a25641d0e60fc25
depends:
- __glibc >=2.17,<3.0.a0
- brotli-bin 1.2.1 h9908984_0
- libbrotlidec 1.2.1 ha411449_0
- libbrotlienc 1.2.1 h018ffa1_0
- libgcc >=15
license: MIT
license_family: MIT
run_exports:
weak:
- libbrotlicommon >=1.2.1,<1.3.0a0
- libbrotlienc >=1.2.1,<1.3.0a0
- libbrotlidec >=1.2.1,<1.3.0a0
size: 20477
timestamp: 1792653712185
- conda: https://conda.anaconda.org/conda-forge/linux-64/brotli-bin-1.2.1-h9908984_0.conda
sha256: c64939f0ade0fea29525d2f549a700841a331c0886b3694083d08eb4769936ce
md5: 903eceb31743f0ce070abb9b9f879714
depends:
- __glibc >=2.17,<3.0.a0
- libbrotlidec 1.2.1 ha411449_0
- libbrotlienc 1.2.1 h018ffa1_0
- libgcc >=15
license: MIT
license_family: MIT
run_exports: {}
size: 21494
timestamp: 1792653706181
- conda: https://conda.anaconda.org/conda-forge/linux-64/cmake-4.5.0-hff7ac6b_0.conda
sha256: 515262118596cd67037b345048d2c7d5a400ef218894f749973960b39e5c2a76
md5: b57a771ac5a81aa791dbeab4263e92fa
depends:
- libstdcxx >=15
- libgcc >=15
- __glibc >=2.17,<3.0.a0
- bzip2 >=1.0.8,<2.0a0
- rhash >=1.4.6,<2.0a0
- libexpat >=2.9.0,<3.0a0
- liblzma >=5.8.3,<6.0a0
- ncurses >=6.6,<7.0a0
- zstd >=1.5.7,<1.6.0a0
- libcurl >=8.23.0,<9.0a0
- libuv >=1.52.1,<2.0a0
- libzlib >=1.3.2,<2.0a0
license: BSD-3-Clause
license_family: BSD
run_exports: {}
size: 27320556
timestamp: 1794549486278
- conda: https://conda.anaconda.org/conda-forge/linux-64/fonttools-4.68.0-py315h4d0d421_0.conda
sha256: f1ca91b02a5153c27e400a6537d6413850da54d4ba0913e3f7f1a0cf42f1e38f
md5: 68744252efceeeb7f55638d9d549b0f4
depends:
- __glibc >=2.17,<3.0.a0
- brotli
- libgcc >=15
- munkres
- python >=3.15,<3.16.0a0
- python_abi 3.15.* *_cp315
license: MIT
license_family: MIT
run_exports: {}
size: 3349521
timestamp: 1793164830929
- conda: https://conda.anaconda.org/conda-forge/linux-64/markupsafe-3.0.4-py315h4aa9e2b_4.conda
sha256: 5295ef9c4510cc8365c39db60f78b636ab46b925b944f552b1259848cc16927d
md5: 718ebfa70a24dd938f999bae19220b7b
depends:
- python
- __glibc >=2.17,<3.0.a0
- libgcc >=15
- python_abi 3.15.* *_cp315
constrains:
- jinja2 >=3.0.0
license: BSD-3-Clause
license_family: BSD
run_exports: {}
size: 29174
timestamp: 1793707103879
- conda: https://conda.anaconda.org/conda-forge/linux-64/ninja-1.13.2-h171cf75_1.conda
sha256: 2b5f2e865122f9fc0637f520a7cb22e16b9727b2db6761ee16cb5e6404412c81
md5: 2db7a395d7dc2b6ed5effaf68fb99443
depends:
- __glibc >=2.17,<3.0.a0
- libstdcxx >=14
- libgcc >=14
license: Apache-2.0
license_family: APACHE
run_exports: {}
size: 186767
timestamp: 1786713048064
- conda: https://conda.anaconda.org/conda-forge/linux-64/pyyaml-6.0.3-py315h178884a_3.conda
sha256: 740a7f3a4ce68b31984909cb2412be177e4f8581f0eb28d8cbb19e5ad78f1b3f
md5: 8a07113e62a8e7977bb0ff67506442a7
depends:
- python
- yaml
- libgcc >=15
- __glibc >=2.17,<3.0.a0
- yaml >=0.2.5,<0.3.0a0
- python_abi 3.15.* *_cp315
license: MIT
license_family: MIT
run_exports: {}
size: 226096
timestamp: 1793655133957
- conda: https://conda.anaconda.org/conda-forge/linux-64/rhash-1.4.6-hb03c661_2.conda
sha256: 186a5b225077ad5f4656966da947d43307101950751ef4a239b455588756b4e1
md5: 007602d697e07c11ff9864964eba5ee3
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=14
license: MIT
license_family: MIT
run_exports:
weak:
- rhash >=1.4.6,<2.0a0
size: 194994
timestamp: 1786731436520
- conda: https://conda.anaconda.org/conda-forge/linux-64/yaml-0.2.5-hebe6cf0_3.conda
sha256: d164dfa75ecd538f6fd68765defcc06aa875bc697b9b215362d79a2a73125dd0
md5: e741576fb8f89821ac7c1c537322a33d
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=15
license: MIT
license_family: MIT
run_exports:
weak:
- yaml >=0.2.5,<0.3.0a0
size: 84936
timestamp: 1787228426393
- conda: https://conda.anaconda.org/conda-forge/linux-64/zensical-0.1.1-py311h7b25dd4_0.conda
noarch: python
sha256: ebc742d9fb379736ce379d6e1d2750450548ccae25c518b5317e11a9f03168bd
md5: 5e4b7d9df92a14258ffed0c31be2abe9
depends:
- python
- click >=8.1.8
- markdown >=3.7
- pygments >=2.20
- pymdown-extensions >=11.0
- pyyaml >=6.0.2
- tomli >=2.4.0
- jinja2 >=3.1
- pathspec >=1.0.4
- zensical-ui ==0.0.42
- __glibc >=2.17,<3.0.a0
- libgcc >=15
- _python_abi3_support 1.*
- cpython >=3.11
constrains:
- __glibc >=2.17
license: MIT
license_family: MIT
run_exports: {}
size: 7813059
timestamp: 1794378251094
- conda: https://conda.anaconda.org/conda-forge/noarch/_python_abi3_support-1.0-hd8ed1ab_3.conda
sha256: 2a7204314663eeda5dec482a956f0e2eaf289bd5b9953eaaaad0e81aa64638f2
md5: 3845f3d75991bae0fb90884662f4327c
depends:
- cpython
- python-gil
license: MIT
license_family: MIT
run_exports: {}
size: 8144
timestamp: 1784221492234
- conda: https://conda.anaconda.org/conda-forge/noarch/click-8.5.1-pyh5ded981_0.conda
sha256: f26981878e8ccdc82fc9025d25997aff119080486e5d089948cb718d428d8cb0
md5: d996564510ceb5744c225b93891316dc
depends:
- python >=3.11
- python
license: BSD-3-Clause
license_family: BSD
run_exports: {}
size: 112921
timestamp: 1794046236533
- conda: https://conda.anaconda.org/conda-forge/noarch/cpython-3.15.2-py315hd8ed1ab_100.conda
noarch: generic
sha256: 5433d0f101e153f35b99809cf81bd04ebf8d6a97c07af9ea2f5c998d624d6fe7
md5: 6c0b7c2ddf16d1a1dabfa0847641b518
depends:
- python >=3.15,<3.16.0a0
- python_abi * *_cp315
license: Python-2.0
run_exports: {}
size: 52891
timestamp: 1793014812118
- conda: https://conda.anaconda.org/conda-forge/noarch/jinja2-3.1.6-pyhcf101f3_1.conda
sha256: fc9ca7348a4f25fed2079f2153ecdcf5f9cf2a0bc36c4172420ca09e1849df7b
md5: 04558c96691bed63104678757beb4f8d
depends:
- markupsafe >=2.0
- python >=3.10
- python
license: BSD-3-Clause
license_family: BSD
run_exports: {}
size: 120685
timestamp: 1764517220861
- conda: https://conda.anaconda.org/conda-forge/noarch/markdown-3.11.3-pyh5ded981_0.conda
sha256: 00d8eab9985c4c23b4a6f3c4e6c89e220b18a54e80b07fcc73fba3fac007f067
md5: 3b24b328ea4593136b77ec4b7b2bec74
depends:
- importlib-metadata >=4.4
- python >=3.11
- python
license: BSD-3-Clause
license_family: BSD
run_exports: {}
size: 91718
timestamp: 1793922176577
- conda: https://conda.anaconda.org/conda-forge/noarch/munkres-1.1.4-pyhd8ed1ab_1.conda
sha256: d09c47c2cf456de5c09fa66d2c3c5035aa1fa228a1983a433c47b876aa16ce90
md5: 37293a85a0f4f77bbd9cf7aaefc62609
depends:
- python >=3.9
license: Apache-2.0
license_family: Apache
run_exports: {}
size: 15851
timestamp: 1749895533014
- conda: https://conda.anaconda.org/conda-forge/noarch/pathspec-1.1.1-pyhd8ed1ab_0.conda
sha256: 6eaee417d33f298db79bc7185ab1208604c0e6cf51dade34cd513c6f9db9c6f3
md5: 11adc78451c998c0fd162584abfa3559
depends:
- python >=3.10
license: MPL-2.0
license_family: MOZILLA
run_exports: {}
size: 56559
timestamp: 1777271601895
- conda: https://conda.anaconda.org/conda-forge/noarch/pygments-2.21.0-pyhcf101f3_0.conda
sha256: f5f015ff1bc3e1b7fc08eee096b1865234189ae0b82bebdb86a5369116e42fa0
md5: 2882dee445dfa45b0c5afce3ffb7730a
depends:
- python >=3.10
- python
license: BSD-2-Clause
license_family: BSD
run_exports: {}
size: 959376
timestamp: 1786995678795
- conda: https://conda.anaconda.org/conda-forge/noarch/pymdown-extensions-13.1-pyhd8ed1ab_0.conda
sha256: 78804f8a554cee0dc29545760a8ac92f798c35ded9623496f7d0a0f7e77b3004
md5: 76c6f01aa602a93377f74b246caf4fb5
depends:
- markdown >=3.10.3
- python >=3.11
- pyyaml
license: MIT
license_family: MIT
run_exports: {}
size: 185558
timestamp: 1794435013218
- conda: https://conda.anaconda.org/conda-forge/noarch/python-gil-3.15.2-h4df99d1_100.conda
sha256: 631a77b41660202c5d4d551aa1816ce550cc6921352ca3d57ac58d0364cab670
md5: beef54f8f4201e9f86f8733cef15506d
depends:
- cpython 3.15.2.*
- python_abi * *_cp315
license: Python-2.0
run_exports: {}
size: 52881
timestamp: 1793014838911
- conda: https://conda.anaconda.org/conda-forge/noarch/zensical-ui-0.0.42-pyh5ded981_0.conda
sha256: ffcf5a93a8d57d248f2ec4b817fd7025ec38a4ad320acb3e382e22b6f2705edd
md5: d66c10adf1915fd628db043f3aed8715
depends:
- python >=3.11
- python
license: MIT
license_family: MIT
run_exports: {}
size: 4721527
timestamp: 1794336711109
- conda: https://prefix.dev/nandi-testing/linux-64/_openmp_mutex-4.5-20_gnu.conda
build_number: 20
sha256: 1dd3fffd892081df9726d7eb7e0dea6198962ba775bd88842135a4ddb4deb3c9
md5: a9f577daf3de00bca7c3c76c0ecbd1de
depends:
- __glibc >=2.17,<3.0.a0
- libgomp >=7.5.0
constrains:
- openmp_impl <0.0a0
license: BSD-3-Clause
run_exports:
strong:
- _openmp_mutex >=4.5
size: 28948
timestamp: 1770939786096
- conda: https://prefix.dev/nandi-testing/linux-64/bzip2-1.0.8-hda65f42_10.conda
sha256: 1a0d382c515ebf55f8ee1f38c8b81bc95af5c2acc42ad53b66bc5df932032f96
md5: e675fabcf81499adc7edf58124fb1e01
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=14
license: bzip2-1.0.6
license_family: BSD
run_exports:
weak:
- bzip2 >=1.0.8,<2.0a0
size: 257808
timestamp: 1785906269155
- conda: https://prefix.dev/nandi-testing/linux-64/c-ares-1.34.9-hebe6cf0_0.conda
sha256: bd95dd25b80b5c4faf5349542377bf89b2794e23d0f7aa7f1c431e4f3b633f3c
md5: 78b505af04bf7a87ca957ef0cb5946f5
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=15
license: MIT
run_exports:
weak:
- c-ares >=1.34.9,<2.0a0
size: 233759
timestamp: 1792507024648
- conda: https://prefix.dev/nandi-testing/linux-64/icu-78.3-py310h44b86e0_2.conda
sha256: 9f07834f0c546ab14d885ce0366285f61f44e326c0edd1fc63b8294e113ae432
md5: 72a381cbad04f24b1c2a43ef707f45b4
depends:
- __glibc >=2.17,<3.0.a0
- libstdcxx >=14
- libgcc >=14
license: MIT
run_exports:
weak:
- icu >=78.3,<79.0a0
size: 14459115
timestamp: 1786545741408
- conda: https://prefix.dev/nandi-testing/linux-64/jco-1.41.0-hb0f4dca_0.conda
sha256: a1d13934c0deda1fe1b87477b09bdfbbe0a15f7d0853e86770298f99a48d0eb1
md5: f604ca17ec935c985f91a5efe179be06
depends:
- nodejs >=20
license: Apache-2.0 WITH LLVM-exception
run_exports: {}
size: 76812028
timestamp: 1794351630770
- conda: https://prefix.dev/nandi-testing/linux-64/keyutils-1.6.3-h7cc23a3_1.conda
sha256: dd053c96dcb0dcfd59422aefea9d2fe937a190167f34fba7893ec1e10a7e8963
md5: ba55d1b89fd7775e67de8291029b4059
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=15
license: LGPL-2.1-or-later
run_exports:
weak:
- keyutils >=1.6.3,<2.0a0
size: 135295
timestamp: 1786739238128
- conda: https://prefix.dev/nandi-testing/linux-64/krb5-1.22.2-hbc21106_2.conda
sha256: 2a5c38c85e63df84c4e69ee71439841ce570d259ae3060627bb9a49a938d66f4
md5: 53318d715316929a574f83591308b1f8
depends:
- __glibc >=2.17,<3.0.a0
- keyutils >=1.6.3,<2.0a0
- libedit >=3.1.20250104,<3.2.0a0
- libedit >=3.1.20250104,<4.0a0
- libgcc >=15
- libstdcxx >=15
- openssl >=3.5.7,<4.0a0
license: MIT
run_exports:
weak:
- krb5 >=1.22.2,<1.23.0a0
size: 1394333
timestamp: 1786762112514
- conda: https://prefix.dev/nandi-testing/linux-64/ld_impl_linux-64-2.46.1-default_hbd61a6d_103.conda
sha256: 901649b1edbe841fd4ee7e2d491a05184ed540eb01cdae506872f344babc1d28
md5: 2362c70e7e79827c32db35547d9c179b
depends:
- __glibc >=2.17,<3.0.a0
- zstd >=1.5.7,<1.6.0a0
constrains:
- binutils_impl_linux-64 2.46.1
license: GPL-3.0-only
run_exports: {}
size: 742109
timestamp: 1791565468810
- conda: https://prefix.dev/nandi-testing/linux-64/libabseil-20260526.0-cxx17_h0dc7533_2.conda
sha256: 7bb3d495411b7059e85225aae500d84e7846a4bb02ebd77e4450200b20c180f0
md5: 6983bfe8e09992014b9cf393769c7a84
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=14
- libstdcxx >=14
constrains:
- abseil-cpp =20260526.0
- libabseil-static =20260526.0=cxx17*
license: Apache-2.0
license_family: Apache
run_exports:
weak:
- libabseil >=20260526.0,<20260527.0a0
- libabseil =*=cxx17*
size: 1436888
timestamp: 1787217011773
- conda: https://prefix.dev/nandi-testing/linux-64/libbrotlicommon-1.2.1-h39a168f_0.conda
sha256: 8eccfbfdb8ecba32eabfb6ee92f70e818e5f3a35a01c507f7b6bd56e00e4c617
md5: 9460bdde20bcdf9e6bbef0232b14ad2d
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=15
license: MIT
run_exports:
weak:
- libbrotlicommon >=1.2.1,<1.3.0a0
size: 80370
timestamp: 1792653685570
- conda: https://prefix.dev/nandi-testing/linux-64/libbrotlidec-1.2.1-ha411449_0.conda
sha256: 4b4bda6f70ad511bdff95fdd958dca74b6e0534ae335ddcb1d8c6569774d2429
md5: 6d934e235f4d452ebec720ec7c3638a6
depends:
- __glibc >=2.17,<3.0.a0
- libbrotlicommon 1.2.1 h39a168f_0
- libgcc >=15
license: MIT
run_exports:
weak:
- libbrotlidec >=1.2.1,<1.3.0a0
size: 34703
timestamp: 1792653694124
- conda: https://prefix.dev/nandi-testing/linux-64/libbrotlienc-1.2.1-h018ffa1_0.conda
sha256: 61974cf9bb07115ed6725dacf83d0d985443d78dd123cc4f2758856fda5376ec
md5: 8f3078564b4a4cd9602ebaafe78e0b87
depends:
- __glibc >=2.17,<3.0.a0
- libbrotlicommon 1.2.1 h39a168f_0
- libgcc >=15
license: MIT
run_exports:
weak:
- libbrotlienc >=1.2.1,<1.3.0a0
size: 298098
timestamp: 1792653699767
- conda: https://prefix.dev/nandi-testing/linux-64/libcurl-8.23.0-ha042cf0_0.conda
sha256: d2db14d80efb4f2e76e76561c633f1767f7543987f2bcb54a067a9d264d432ab
md5: 0ad16151226df493aed967f0efce0e80
depends:
- __glibc >=2.17,<3.0.a0
- krb5 >=1.22.2,<1.23.0a0
- libgcc >=15
- libnghttp2 >=1.68.1,<2.0a0
- libpsl >=0.23.1,<0.24.0a0
- libssh2 >=1.11.1,<2.0a0
- libzlib >=1.3.2,<2.0a0
- openssl >=3.5.9,<4.0a0
- zstd >=1.5.7,<1.6.0a0
license: curl
license_family: MIT
run_exports:
weak:
- libcurl >=8.23.0,<9.0a0
size: 505683
timestamp: 1791990900844
- conda: https://prefix.dev/nandi-testing/linux-64/libedit-3.1.20260512-pl5321h373387f_0.conda
sha256: 45301f14f4eb66da57cfaf2d265f3eeee73f8b07e99614ee3afc5b26eea91126
md5: 27dbd7e2984b8fe48e069379636ccfdd
depends:
- ncurses
- __glibc >=2.17,<3.0.a0
- libgcc >=14
- ncurses >=6.6,<7.0a0
license: BSD-2-Clause
run_exports:
weak:
- libedit >=3.1.20260512,<3.2.0a0
size: 135877
timestamp: 1791327370514
- conda: https://prefix.dev/nandi-testing/linux-64/libev-4.33-h280c20c_3.conda
sha256: e4418f68d01a6307c4431b585c71b584f40189877364e542ee87deb777f5e85b
md5: 7bc31538d6e3fb349e897353969237ec
depends:
- libgcc >=14
- __glibc >=2.17,<3.0.a0
license: BSD-2-Clause OR GPL-2.0-or-later
run_exports:
weak:
- libev >=4.33,<4.34.0a0
size: 43220
timestamp: 1785917328200
- conda: https://prefix.dev/nandi-testing/linux-64/libexpat-2.9.0-hd2095e1_0.conda
sha256: 7b930a8b6bc6553cb754b4977a11f9c862c719a652fc2d128d89270992ce8beb
md5: 317ecabe4a58b3068c7958dc5eb89e43
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=15
constrains:
- expat 2.9.0.*
license: MIT
license_family: MIT
run_exports: {}
size: 78894
timestamp: 1793054221966
- conda: https://prefix.dev/nandi-testing/linux-64/libffi-3.7.0-h81df57d_1.conda
sha256: c8c7583ef063bc3c430f1d48298e5ad24f796a35c22ed5b14183325825a61106
md5: 6525a0b06aa4fd390795f0740636a9dd
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=15
license: MIT
run_exports:
weak:
- libffi >=3.7.0,<3.8.0a0
size: 68004
timestamp: 1787753412298
- conda: https://prefix.dev/nandi-testing/linux-64/libgcc-16.2.0-ha9f2e26_7.conda
sha256: e031634c3a928f9594eba868bc46ef5230d6571a364a0c63215b06c4563bfcea
md5: 735629b400b70eeab21a2ba8f5b1c2ce
depends:
- __glibc >=2.17,<3.0.a0
- _openmp_mutex >=4.5
constrains:
- libgcc-ng ==16.2.0=*_7
- libgomp 16.2.0 he0feb66_7
license: GPL-3.0-only WITH GCC-exception-3.1
run_exports: {}
size: 1058444
timestamp: 1790303109576
- conda: https://prefix.dev/nandi-testing/linux-64/libgomp-16.2.0-he0feb66_7.conda
sha256: 92a0bb350c7be6a4eedcb4e111c60aefd176018e6b1c009a6e025dbe9bbcd758
md5: d904c7ddd95e026254b4b80808ee9e12
depends:
- __glibc >=2.17,<3.0.a0
license: GPL-3.0-only WITH GCC-exception-3.1
run_exports:
strong:
- _openmp_mutex >=4.5
size: 640566
timestamp: 1790303046034
- conda: https://prefix.dev/nandi-testing/linux-64/liblzma-5.8.3-hb03c661_1.conda
sha256: 9787df8c22a59c9a70d3e5a10db9ad663485e75e9ccc3f09bd092cb7b95e0dab
md5: 1390b7c5ac0b1d8e447bc5efa6d3c8c2
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=14
constrains:
- xz 5.8.3.*
license: 0BSD
run_exports:
weak:
- liblzma >=5.8.3,<6.0a0
size: 112995
timestamp: 1786348617826
- conda: https://prefix.dev/nandi-testing/linux-64/libmpdec-4.0.0-hb03c661_2.conda
sha256: 46820b4a835e175940ae20bec00fdddaff804cda27a1408ab1b95e77a2196437
md5: fcfed1dc5053eb1901b66e7b1fc32588
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=14
license: BSD-2-Clause
run_exports: {}
size: 92759
timestamp: 1786650399772
- conda: https://prefix.dev/nandi-testing/linux-64/libnghttp2-1.71.0-hc5e5977_0.conda
sha256: a4386712ad6d5bc18943b198407c39e2f8ae2fa9c6418bb37bba96f1d382f109
md5: 726df214814a8b06135a6a674bc54589
depends:
- libev >=4.33,<5.0a0
- __glibc >=2.17,<3.0.a0
- libgcc >=15
- libstdcxx >=15
- libev >=4.33,<4.34.0a0
- c-ares >=1.34.9,<2.0a0
- libzlib >=1.3.2,<2.0a0
- openssl >=3.5.9,<4.0a0
license: MIT
run_exports:
weak:
- libnghttp2 >=1.71.0,<2.0a0
size: 822778
timestamp: 1793628201366
- conda: https://prefix.dev/nandi-testing/linux-64/libpsl-0.23.1-hd9e3e90_1.conda
sha256: 09e8effdc89bc5d021349318d32b85594f5b8d8e3ab8f90a85b81f8fe695a566
md5: 77be60417aa572afcb48cbe0f967401d
depends:
- libstdcxx >=15
- libgcc >=15
- __glibc >=2.17,<3.0.a0
- icu >=78.3,<79.0a0
license: MIT
license_family: MIT
run_exports:
weak:
- libpsl >=0.23.1,<0.24.0a0
size: 72519
timestamp: 1786970753847
- conda: https://prefix.dev/nandi-testing/linux-64/libsqlite-3.54.1-h13e7031_0.conda
sha256: 07b3c98282022f05781122d073f84e944bfb4299946e8457ece3ce6c384ff78e
md5: 8f15f0ec9b69344df5c3bb5cce1751a1
depends:
- __glibc >=2.17,<3.0.a0
- icu >=78.3,<79.0a0
- libgcc >=15
- libzlib >=1.3.2,<2.0a0
license: blessing
run_exports:
weak:
- libsqlite >=3.54.1,<4.0a0
size: 983668
timestamp: 1792175587601
- conda: https://prefix.dev/nandi-testing/linux-64/libssh2-1.11.1-h6154650_1.conda
sha256: 7e463000fa1cba3f3a6597b776f6ab301d425a96e3bc20d0d9d76a3b9f237aa3
md5: 5c526561e1d2a2e071941174eae84557
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=14
- libzlib >=1.3.2,<2.0a0
- openssl >=3.5.7,<4.0a0
license: BSD-3-Clause
license_family: BSD
run_exports:
weak:
- libssh2 >=1.11.1,<2.0a0
size: 306045
timestamp: 1786713107897
- conda: https://prefix.dev/nandi-testing/linux-64/libstdcxx-16.2.0-h934c35e_7.conda
sha256: fa7018298629fc429971fffd6ecba3d27a7b02e4e890d6a93ea01ffebe8cb745
md5: 9b6707e0caca917fa6ea9ee473f37a5d
depends:
- __glibc >=2.17,<3.0.a0
- libgcc 16.2.0 ha9f2e26_7
constrains:
- libstdcxx-ng ==16.2.0=*_7
license: GPL-3.0-only WITH GCC-exception-3.1
run_exports: {}
size: 6615436
timestamp: 1790303132935
- conda: https://prefix.dev/nandi-testing/linux-64/libuuid-2.42.4-hcfc3c73_1.conda
sha256: 0e2e8f2daa9306e67f046e31092d637431d8cf0a26c407ab22401d108c2d4631
md5: d852293faea3c04a6e896b908b43aded
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=15
license: BSD-3-Clause
run_exports:
weak:
- libuuid >=2.42.4,<3.0a0
size: 36134
timestamp: 1793891599274
- conda: https://prefix.dev/nandi-testing/linux-64/libuv-1.52.1-h280c20c_1.conda
sha256: 67761d0206f84140047a367eaf9befe03a7e157a29ee25aee0047b40801cc6b6
md5: 01c4ed87826af55996768af6dbc936b4
depends:
- libgcc >=14
- __glibc >=2.17,<3.0.a0
license: MIT
run_exports:
weak:
- libuv >=1.52.1,<2.0a0
size: 420040
timestamp: 1785914567661
- conda: https://prefix.dev/nandi-testing/linux-64/libzlib-1.3.2-h25fd6f3_3.conda
sha256: eb8a0db0aa570124f7d2a93d7c7f596e3390df5e047818d873baad32985fc736
md5: 0de0122d9570a8ab637c6b73db268389
depends:
- __glibc >=2.17,<3.0.a0
constrains:
- zlib 1.3.2 *_3
license: Zlib
license_family: Other
run_exports:
weak:
- libzlib >=1.3.2,<2.0a0
size: 63713
timestamp: 1785362952714
- conda: https://prefix.dev/nandi-testing/linux-64/ncurses-6.6-hdb14827_1.conda
sha256: 5d46557214ed184381dafe835b7c94a474a1c3b307a08a250b1ea4779b44ffb3
md5: ee6c0cd80a60961a1f48aa3e0b91f986
depends:
- __glibc >=2.17,<3.0.a0
- libgcc >=14
license: X11 AND BSD-3-Clause
run_exports:
weak:
- ncurses >=6.6,<7.0a0
size: 911196
timestamp: 1786355078102
- conda: https://prefix.dev/nandi-testing/linux-64/nodejs-26.10.0-ha5cdc1e_0.conda
sha256: ea1ae98c7352198d6d6a4027f4a60d2b634e05d5fd6f0b97e72fc6c16712b2c7
md5: 46a3d9861f49b845fbd54897ff07fe4f
depends:
- libgcc >=15
- __glibc >=2.28,<3.0.a0
- libstdcxx >=15
- zstd >=1.5.7,<1.6.0a0
- libzlib >=1.3.2,<2.0a0
- libuv >=1.52.1,<2.0a0
- openssl >=3.5.8,<4.0a0
- libnghttp2 >=1.68.1,<2.0a0
- libabseil >=20260526.0,<20260527.0a0
- libabseil * cxx17*
- icu >=78.3,<79.0a0
- c-ares >=1.34.8,<2.0a0
- libsqlite >=3.53.4,<4.0a0
- libbrotlicommon >=1.2.0,<1.3.0a0
- libbrotlienc >=1.2.0,<1.3.0a0
- libbrotlidec >=1.2.0,<1.3.0a0
license: MIT
run_exports:
weak:
- nodejs >=26.10.0,<27.0a0
size: 20474429
timestamp: 1790238478566
- conda: https://prefix.dev/nandi-testing/linux-64/openssl-3.6.5-h781a0a9_0.conda
sha256: 9c1533f1cf784f0e250919c0c9762d0b0e6bc727a79290ffb7cea1ceca1d038c
md5: 5a51a2ea653f120240b1a9bf76e0aae9
depends:
- __glibc >=2.17,<3.0.a0
- ca-certificates
- libgcc >=15
license: Apache-2.0
license_family: Apache
run_exports:
weak:
- openssl >=3.6.5,<4.0a0
size: 3195299
timestamp: 1791098052301
- conda: https://prefix.dev/nandi-testing/linux-64/python-3.15.2-h6e52b48_100_cp315.conda
build_number: 100
sha256: dd6fdef748df5636029673a834ca3632ce44c86d71e4986d70bcdb2ae5607a25
md5: 38c3edc23439db3ca383be02ae2b702e
depends:
- __glibc >=2.17,<3.0.a0
- bzip2 >=1.0.8,<2.0a0
- ld_impl_linux-64 >=2.36.1
- libedit >=3.1.20260512,<3.2.0a0
- libexpat >=2.8.5,<3.0a0
- libffi >=3.7.0,<3.8.0a0
- libgcc >=15
- liblzma >=5.8.3,<6.0a0
- libmpdec >=4.0.0,<5.0a0
- libsqlite >=3.54.1,<4.0a0
- libuuid >=2.42.4,<3.0a0
- libzlib >=1.3.2,<2.0a0
- ncurses >=6.6,<7.0a0
- openssl >=3.5.9,<4.0a0
- python_abi 3.15.* *_cp315
- tk >=8.6.13,<8.7.0a0
- tzdata
- zstd >=1.5.7,<1.6.0a0
license: Python-2.0
run_exports:
weak:
- python_abi 3.15.* *_cp315
noarch:
- python
size: 29327137
timestamp: 1793015518763
python_site_packages_path: lib/python3.15/site-packages
- conda: https://prefix.dev/nandi-testing/linux-64/qt6-wasi-6.8.3-hb0f4dca_0.conda
sha256: 2e4fbae5c9cadf88828935715572474256cb6500d664f0b3214df98b49fa84e9
md5: 1f76619fb958e5df8dcc62480912857d
depends:
- wasi-sdk 27.*
- cmake >=3.21
- ninja
- libgcc >=16
- libstdcxx >=16
license: LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
run_exports: {}
size: 20849123
timestamp: 1794274326934
- conda: https://prefix.dev/nandi-testing/linux-64/tk-8.6.13-noxft_h1df4ec4_4.conda
build_number: 104
sha256: a1a241d172c1ccab067ba245206dd048bc3c2d1b84504b53c9468e99adfc16a1
md5: 676a2f9b1c4fcf57b70aa5c65f6c60d0
depends:
- libgcc >=15
- __glibc >=2.17,<3.0.a0
- libzlib >=1.3.2,<2.0a0
constrains:
- xorg-libx11 >=1.8.13,<2.0a0
license: TCL
run_exports:
weak:
- tk >=8.6.13,<8.7.0a0
size: 3566806
timestamp: 1787272857910
- conda: https://prefix.dev/nandi-testing/linux-64/wasi-sdk-27.0-hb0f4dca_1.conda
sha256: e8f23f48de592aadf0ae773bc0feda1a46de174b8f49b85006c6ea06e86b8a5b
md5: 0054d5f0e3da6fc37d6510157fbcc03b
license: Apache-2.0 WITH LLVM-exception
run_exports: {}
size: 100198008
timestamp: 1794273876363
- conda: https://prefix.dev/nandi-testing/linux-64/wasm-tools-1.239.0-hb0f4dca_0.conda
sha256: 649e7ba5b6476e7ffb4b1d093bc1c22355258693013145e7659e3ee29d8ee40c
md5: aea1c6d0cc71e9027022bcd2856e6b61
license: Apache-2.0 WITH LLVM-exception
run_exports: {}
size: 5669897
timestamp: 1794274014481
- conda: https://prefix.dev/nandi-testing/linux-64/wit-bindgen-0.46.0-hb0f4dca_0.conda
sha256: 48132c985e85cc499e9dc9c899a6da0947c923938d6d0595a78ea780f0941df5
md5: e54e97c7f9a0690d2a13c2e1e2cf82d1
license: Apache-2.0 WITH LLVM-exception
run_exports: {}
size: 5453568
timestamp: 1794273951520
- conda: https://prefix.dev/nandi-testing/linux-64/zstd-1.5.7-hb78ec9c_7.conda
sha256: 47d682b9f6d6ec9eb1a6e6c3e75ea6273e899e78fb7fc59f81d39745009fbc60
md5: aa459086047c0e5e27023ab19f8cb86a
depends:
- __glibc >=2.17,<3.0.a0
- libzlib >=1.3.2,<2.0a0
license: BSD-3-Clause
run_exports:
weak:
- zstd >=1.5.7,<1.6.0a0
size: 601301
timestamp: 1786599621503
- conda: https://prefix.dev/nandi-testing/noarch/ca-certificates-2026.10.23-hbd8a1cb_0.conda
sha256: 95619b9c1184be7175392eeb0ee7eeb5ccf25d280951f4225f2d62e725790be3
md5: 3fd02989038a1e1cee627c14c2d73f29
depends:
- __unix
license: ISC
run_exports: {}
size: 130057
timestamp: 1792772446739
- conda: https://prefix.dev/nandi-testing/noarch/importlib-metadata-9.0.1-pyhcf101f3_0.conda
sha256: 95a074a7d3f58b3494c068d4789c364dcb591c56b70ca6b12f149a540f9aeea4
md5: 77ec68e0aa61c3fff9ecbf840f93d64e
depends:
- python >=3.10
- zipp >=3.20
- python
license: Apache-2.0
run_exports: {}
size: 34920
timestamp: 1787943971257
- conda: https://prefix.dev/nandi-testing/noarch/python_abi-3.15-9_cp315.conda
build_number: 9
sha256: 976c4a6db967a62385aa633daaab19a929f986b979a7ad836b8b70e15ca7aefd
md5: b23461631fe2abdbade0cb64babe7344
constrains:
- python 3.15.* *_cp315
license: BSD-3-Clause
license_family: BSD
run_exports: {}
size: 6800
timestamp: 1788302827589
- conda: https://prefix.dev/nandi-testing/noarch/qt2wasm-0.10.6-pyh4616a5c_0.conda
sha256: 54c4ee91b29d1052cc2c95881b45b3ed7282665e9ca3fdf76820dd102cd8e202
md5: 09279c4ecd79abf9642ae733faaf4ebb
depends:
- python >=3.10
- python *
- cmake >=3.21
- ninja
- binaryen
- fonttools
- qt6-wasi 6.8.3.*
- wit-bindgen 0.46.*
- wasm-tools 1.239.*
- wasi-preview1-adapter 36.*
- zensical >=0.1
- jco 1.41.*
run_exports: {}
size: 74111
timestamp: 1794580144578
- conda: https://prefix.dev/nandi-testing/noarch/tomli-2.5.0-pyh5ded981_0.conda
sha256: 93b6f517fb7adff00b62be02b798d384a1b34d0e368fdb576fb248bcb3bb9ec7
md5: 36d6a162326c52d6339c8b606f43932d
depends:
- python >=3.11
- python
license: MIT
run_exports: {}
size: 21687
timestamp: 1791394576814
- conda: https://prefix.dev/nandi-testing/noarch/tzdata-2026e-h5d301ff_0.conda
sha256: 2b7ca858879f183ce2dcc65b300f48a0133d5430550f35b23d80d405a0788dbf
md5: abccc3810d2b97e570dee487f2b46e38
license: LicenseRef-Public-Domain
run_exports: {}
size: 119208
timestamp: 1792758382821
- conda: https://prefix.dev/nandi-testing/noarch/wasi-preview1-adapter-36.0.0-h4616a5c_0.conda
sha256: 0b1610b24de6cc92d12db20b13e14fe1f989bc43543c972a1b372c0f069a797b
md5: b9137fc4706585a3da7f55c72f93d309
license: Apache-2.0 WITH LLVM-exception
run_exports: {}
size: 19423
timestamp: 1794274078296
- conda: https://prefix.dev/nandi-testing/noarch/zipp-4.1.2-pyh5ded981_0.conda
sha256: 4e5c50cf5ecc00d83a20b987c52d49b78fa96026437ab09b11f4b7c46b7fc061
md5: 3a99defa674883e167603f141728de7e
depends:
- python >=3.11
- python
license: MIT
license_family: MIT
run_exports: {}
size: 24791
timestamp: 1792622774790
+12
View File
@@ -0,0 +1,12 @@
[workspace]
name = "ultra-launcher-wasi"
channels = ["https://prefix.dev/nandi-testing", "conda-forge"]
platforms = ["linux-64"]
[dependencies]
qt2wasm = "*"
cmake = "*"
ninja = "*"
[tasks]
build = { cmd = "bash build.sh", description = "Build launcher.wasm (WASI component)" }
File diff suppressed because it is too large. Load diff
+122
View File
@@ -0,0 +1,122 @@
#pragma once
#include "layout.h"
#include <QBasicTimer>
#include <QHash>
#include <QImage>
#include <QPointF>
#include <QRasterWindow>
#include <QSet>
#include <QString>
#include <QVector>
#include <QElapsedTimer>
struct AppInfo {
QString label;
QString component;
bool system = false;
};
struct WidgetProviderInfo {
QString provider;
QString label;
int w = 2;
int h = 2;
};
class LauncherWindow : public QRasterWindow {
Q_OBJECT
public:
LauncherWindow();
protected:
void paintEvent(QPaintEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void timerEvent(QTimerEvent *event) override;
private:
enum class SheetKind { None, Menu, HomeItem, DrawerApp, Widgets };
void pollHostEvents();
void refreshInsets();
void refreshApps();
void refreshWidgetProviders();
void loadHome();
void seedDefaultHome();
void saveHome() const;
QImage iconFor(const QString &component, int px);
// Geometry helpers (logical px)
qreal insetTop() const;
qreal insetBottom() const;
qreal contentW() const;
qreal contentX() const;
qreal gridX() const;
qreal gridW() const;
int homeCols() const;
qreal homeColW() const;
qreal panelY() const;
qreal gridTop() const;
QRectF appsPillRect() const;
QRectF drawerSearchRect() const;
QRectF drawerCloseRect() const;
QRectF drawerClearRect() const;
QVector<AppInfo> filteredApps() const;
int hitHomeSlot(const QPointF &pos) const;
int hitDrawerApp(const QPointF &pos) const;
int hitSheetButton(const QPointF &pos) const;
void openDrawer();
void closeDrawer();
void openSheet(SheetKind kind, int index);
void closeSheet();
void triggerSheetAction(int actionIdx);
void drawHome(QPainter &p);
void drawDrawer(QPainter &p);
void drawSheet(QPainter &p);
void drawIconAndLabel(QPainter &p, const QRectF &box, const QString &component,
const QString &label, int iconSize, bool lifted);
// Host state
int m_physInsetTop = 0;
int m_physInsetBottom = 0;
QVector<AppInfo> m_apps;
QHash<QString, int> m_appIndex;
QVector<Layout::HomeSlot> m_home;
QVector<WidgetProviderInfo> m_providers;
QHash<QString, QImage> m_icons;
QSet<QString> m_missingIcons;
QString m_lastPlacedWidgets;
bool m_lastWidgetsVisible = true;
// UI state
bool m_drawerOpen = false;
qreal m_drawerScroll = 0.0;
qreal m_homeScroll = 0.0;
QString m_search;
bool m_searchFocused = false;
SheetKind m_sheet = SheetKind::None;
int m_sheetIndex = -1;
// Pointer / gesture tracking
bool m_pressed = false;
bool m_dragging = false;
bool m_longPressed = false;
int m_pressedHome = -1;
int m_pressedDrawer = -1;
int m_liftedHome = -1;
QPointF m_pressPos;
QPointF m_lastPos;
QPointF m_liftPos;
QElapsedTimer m_pressTimer;
QBasicTimer m_pollTimer;
QBasicTimer m_longPressTimer;
};
+87
View File
@@ -0,0 +1,87 @@
#include "layout.h"
#include <algorithm>
#include <vector>
namespace Layout {
PackedGrid packHome(const QVector<HomeSlot> &items, int cols, const QSet<QString> &hidden) {
PackedGrid out;
out.cells.resize(items.size(), {-1, -1});
if (cols <= 0) return out;
// Occupancy grid grows dynamically as rows are needed.
std::vector<std::vector<bool>> occ;
auto ensureRow = [&](int r) {
while (static_cast<int>(occ.size()) <= r) occ.emplace_back(cols, false);
};
auto isFree = [&](int c, int r, int w, int h) -> bool {
if (c < 0 || c + w > cols || r < 0) return false;
for (int dr = 0; dr < h; ++dr) {
const int rr = r + dr;
if (rr >= static_cast<int>(occ.size())) continue;
for (int dc = 0; dc < w; ++dc) {
if (occ[rr][c + dc]) return false;
}
}
return true;
};
auto occupy = [&](int c, int r, int w, int h) {
for (int dr = 0; dr < h; ++dr) {
const int rr = r + dr;
ensureRow(rr);
for (int dc = 0; dc < w; ++dc) {
occ[rr][c + dc] = true;
}
out.rows = std::max(out.rows, rr + 1);
}
};
// Pass 1: place pinned slots first (widgets before apps) if their area is free.
QVector<bool> placed(items.size(), false);
for (int pass = 0; pass < 2; ++pass) {
const bool wantWidget = (pass == 0);
for (int i = 0; i < items.size(); ++i) {
const auto &s = items[i];
if (s.isWidget() != wantWidget) continue;
if (!s.isWidget() && hidden.contains(s.component)) continue;
const int w = std::clamp(s.w, 1, cols);
const int h = std::max(1, s.h);
if (s.x >= 0 && s.y >= 0 && isFree(s.x, s.y, w, h)) {
occupy(s.x, s.y, w, h);
out.cells[i] = {s.x, s.y};
placed[i] = true;
}
}
}
// Pass 2: pack remaining visible slots into the earliest free area.
for (int i = 0; i < items.size(); ++i) {
const auto &s = items[i];
if (placed[i] || (!s.isWidget() && hidden.contains(s.component))) continue;
const int w = std::clamp(s.w, 1, cols);
const int h = std::max(1, s.h);
int r = 0, c = 0;
while (!isFree(c, r, w, h)) {
++c;
if (c + w > cols) {
c = 0;
++r;
}
}
occupy(c, r, w, h);
out.cells[i] = {c, r};
}
return out;
}
QRectF cellBox(const CellPos &cell, qreal colW, int spanW, int spanH) {
const qreal x = cell.col * (colW + kColGap);
const qreal y = cell.row * (kCellH + kRowGap);
const qreal w = spanW * colW + std::max(0, spanW - 1) * kColGap;
const qreal h = spanH * kCellH + std::max(0, spanH - 1) * kRowGap;
return QRectF(x, y, w, h);
}
} // namespace Layout
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include <QRectF>
#include <QSet>
#include <QString>
#include <QVector>
namespace Layout {
inline constexpr qreal kCellH = 92.0;
inline constexpr qreal kColGap = 6.0;
inline constexpr qreal kRowGap = 12.0;
struct HomeSlot {
QString component; // non-empty for app slots
int widgetId = -1; // >= 0 for Android AppWidget slots
QString provider; // widget provider component
int x = -1;
int y = -1;
int w = 1;
int h = 1;
bool isWidget() const { return widgetId >= 0 || !provider.isEmpty(); }
};
struct CellPos {
int col = 0;
int row = 0;
};
struct PackedGrid {
QVector<CellPos> cells; // Same length as slots; invalid (-1, -1) if hidden.
int rows = 0;
};
PackedGrid packHome(const QVector<HomeSlot> &items, int cols, const QSet<QString> &hidden);
QRectF cellBox(const CellPos &cell, qreal colW, int spanW = 1, int spanH = 1);
} // namespace Layout
+9
View File
@@ -0,0 +1,9 @@
#include "launcher_window.h"
#include <qt2wasm/gui.h>
int qt2wasm_gui_main(int, char **) {
auto *w = new LauncherWindow;
w->show();
return 0;
}
+268
View File
@@ -0,0 +1,268 @@
/// latha:gui: a GUI app as one WebAssembly component.
///
/// The app draws its window into a frame buffer and the host shows it: the
/// host owns the native window, its event loop and the clock; the app is a
/// reactor and only runs inside an export call. A host is a small, generic
/// loader (perry-gui in kwi-wasm: a GTK4 window), and any component that
/// exports `app` and imports nothing but `host` (plus `pty`, and WASI) runs
/// in it. qt2wasm builds such components from QtGui programs
/// (`qt2wasm build --gui`, its `qt2wasmgui` platform plugin).
///
/// Life of an app:
/// 1. `start(args)`: build the UI. The host then calls `resize` with the
/// real surface size before the first `paint`.
/// 2. input arrives as `key` / `text` / `pointer` / `wheel` / `focus`;
/// 3. after anything that may have changed the picture, and whenever the
/// app asked with `host.request-frame`, the host calls `paint`, which
/// returns the pixels to move (scrolling) and the damaged rectangles;
/// the host moves those in its own copy, then copies each damaged
/// rectangle with `frame-pixels`;
/// 4. `tick` runs due timers and queued work; it returns how long until the
/// app next wants one (none: only when something happens);
/// 5. `close` when the user closes the window; the app answers whether the
/// host may close now (it can also leave any time with `host.quit`).
///
/// Coordinates and sizes are device pixels, origin top left. Pixels cross the
/// boundary base64 encoded in a string: hosts lift a `list<u8>` element by
/// element, a string in one copy.
package latha:gui@0.2.3;
interface types {
/// A rectangle in device pixels.
record rect {
x: s32,
y: s32,
width: u32,
height: u32,
}
record size {
width: u32,
height: u32,
}
/// Move the pixels inside `area` by (`dx`, `dy`), as a scrolled view
/// does: the host copies them within the frame it already shows, so they
/// need not cross the boundary again. Only `area` changes: what moves out
/// of it is dropped, and the strip it uncovers keeps its old pixels until
/// a damaged rectangle repaints it.
record move {
area: rect,
dx: s32,
dy: s32,
}
/// What changed since the last `paint`: first apply `moves`, in order,
/// to the shown frame, then copy each of `rects` with `frame-pixels`.
record damage {
moves: list<move>,
rects: list<rect>,
}
/// Keyboard modifiers held during an event. `keypad` marks a key on the
/// numeric keypad.
flags modifiers {
shift,
ctrl,
alt,
meta,
keypad,
}
/// Mouse buttons held during an event.
flags buttons {
left,
right,
middle,
back,
forward,
}
enum button {
none,
left,
right,
middle,
back,
forward,
}
enum pointer-kind {
press,
release,
move,
/// The pointer entered the surface.
enter,
/// The pointer left the surface.
leave,
}
record pointer-event {
kind: pointer-kind,
/// The button that changed (`press` / `release`), else `none`.
button: button,
/// The buttons held after the event.
buttons: buttons,
modifiers: modifiers,
x: f64,
y: f64,
/// For `press`: 1 for a single click, 2 for a double click, ...
clicks: u32,
}
record key-event {
/// true on press (and auto-repeat), false on release.
pressed: bool,
repeat: bool,
/// The X11 / xkbcommon keysym (XK_*, e.g. 0xff0d Return, 0x61 `a`),
/// as GDK, Wayland and X11 report it; 0 if unknown.
keysym: u32,
/// The hardware key code (evdev + 8 on Linux), 0 if unknown.
scancode: u32,
modifiers: modifiers,
/// The text the press types, if any (control characters included,
/// e.g. "\r" for Return, "\u{3}" for Ctrl+C). Text from an input
/// method arrives through `app.text` instead.
text: string,
}
record wheel-event {
x: f64,
y: f64,
/// Wheel notches (1.0 = one notch; positive = down / right).
steps-x: f64,
steps-y: f64,
/// Smooth scrolling (touchpads), in device pixels; 0 if not known.
pixels-x: f64,
pixels-y: f64,
modifiers: modifiers,
}
/// Pointer shapes (CSS cursor names).
enum cursor {
default,
text,
pointer,
crosshair,
wait,
progress,
help,
move,
not-allowed,
grab,
grabbing,
ew-resize,
ns-resize,
nesw-resize,
nwse-resize,
col-resize,
row-resize,
none,
}
}
/// What the host gives the app.
interface host {
use types.{cursor, size};
/// The picture changed: call `paint` soon (once per host frame at most).
request-frame: func();
/// Call `tick` after `delay-ms` (0: as soon as possible), e.g. for a
/// timer the app just started. A later request replaces an earlier one.
request-tick: func(delay-ms: u32);
set-title: func(title: string);
set-cursor: func(shape: cursor);
/// The smallest window size the app can use (device pixels); 0 x 0: any.
set-min-size: func(min: size);
/// The clipboard's text, empty if it holds none.
clipboard-text: func() -> string;
set-clipboard-text: func(text: string);
/// The X11 primary selection (middle-click paste); hosts without one
/// return "" and ignore the set.
primary-text: func() -> string;
set-primary-text: func(text: string);
/// Whether the desktop prefers a dark color scheme.
prefers-dark: func() -> bool;
/// The desktop's accent color (selection, focus, active tab) as
/// 0xRRGGBB, none if the desktop has none. Since 0.2.1; a change arrives
/// as `app.color-scheme`.
accent-color: func() -> option<u32>;
bell: func();
set-text-input: func(active: bool);
/// Open `url` (http, https, mailto, file, ...) the desktop's way: in
/// the user's browser, mail client, file manager. False if the host
/// cannot or will not. Since 0.2.2.
open-url: func(url: string) -> bool;
/// Leave: the host closes the window and exits with `code`.
quit: func(code: s32);
}
/// What the app gives the host.
interface app {
use types.{rect, size, damage, key-event, pointer-event, wheel-event};
/// Build the UI. `args` are the command line after the component's
/// path, with the app's name (the wasm file's stem) first. Returns the
/// window size the app would like (device pixels at scale 1), 0 x 0 for
/// the host's default, or an error that makes the host exit.
start: func(args: list<string>) -> result<size, string>;
/// The surface is now `width` x `height` device pixels at `scale`
/// device pixels per logical pixel.
resize: func(width: u32, height: u32, scale: f64);
key: func(event: key-event);
/// Text committed by an input method (compose, dead keys, CJK, ...).
text: func(text: string);
pointer: func(event: pointer-event);
wheel: func(event: wheel-event);
focus: func(focused: bool);
/// The desktop's appearance changed: the dark / light preference (see
/// `host.prefers-dark`) or the accent color (`host.accent-color`, read it
/// again).
color-scheme: func(dark: bool);
/// The user asked to close the window: true lets the host close it.
close: func() -> bool;
/// Run due timers and queued work. Returns the delay in ms until the app
/// next needs a tick, none if only an event or `request-tick` will.
tick: func() -> option<u32>;
/// Bring the frame up to date. Returns what changed since the last
/// `paint`: pixels that moved, then rectangles to copy (both empty:
/// nothing changed). The frame is the surface's size once `resize` was
/// called; after a resize the first paint reports the whole frame and no
/// moves.
paint: func() -> damage;
frame-size: func() -> size;
/// `r`'s pixels, base64: `r.height` rows of `r.width` pixels, each
/// 4 bytes B, G, R, A with premultiplied alpha (little-endian 0xAARRGGBB:
/// cairo's ARGB32, Qt's ARGB32_Premultiplied).
frame-pixels: func(r: rect) -> string;
}
/// Pseudo-terminals, for apps that run programs (terminal emulators).
/// Output is polled: the host calls `app.tick` when a pty has data or ends.
interface pty {
/// Start `argv` (argv[0] looked up in PATH; empty: the user's shell) on a
/// new pty of `cols` x `rows`, with `env` added to the host's
/// environment and `cwd` (none: the user's home). Returns its id.
spawn: func(argv: list<string>, env: list<tuple<string, string>>, cwd: option<string>,
cols: u16, rows: u16) -> result<u32, string>;
write: func(id: u32, data: list<u8>);
/// Everything the program wrote since the last read, base64 ("" = nothing).
read: func(id: u32) -> string;
resize: func(id: u32, cols: u16, rows: u16);
/// Its exit code once it has ended and its output was read, else none.
exit-code: func(id: u32) -> option<s32>;
/// Hang up (SIGHUP) and forget it.
close: func(id: u32);
}
/// A GUI app.
world gui {
import host;
export app;
}
/// A GUI app that also runs programs on pseudo-terminals.
world gui-pty {
include gui;
import pty;
}
+32
View File
@@ -0,0 +1,32 @@
package ultra:launcher@0.1.0;
interface android {
/// JSON array of {"label": string, "component": string, "system"?: bool}.
apps: func() -> string;
/// Base64-encoded premultiplied RGBA8888 pixels (size * size * 4 bytes) for "a:COMPONENT".
icon: func(key: string, size: u32) -> option<string>;
launch: func(component: string);
app-info: func(component: string);
uninstall: func(component: string);
open-settings: func();
pick-wallpaper: func();
open-recents: func();
haptic: func();
/// System bar insets in physical screen pixels: (top, bottom).
insets: func() -> tuple<u32, u32>;
/// Drain queued host events ("home", "back", "insets", "apps-changed:<pkgs>", "widget-added:<id>:<provider>").
poll-events: func() -> list<string>;
/// JSON array of {"provider": string, "label": string, "w": u32, "h": u32}.
widget-providers: func() -> string;
/// Bind a widget for provider; emits "widget-added:<id>:<provider>".
add-widget: func(provider: string);
remove-widget: func(id: s32);
/// Place live widget views: JSON [[id, x, y, w, h], ...] in physical screen px.
place-widgets: func(json: string);
set-widgets-visible: func(visible: bool);
}
world gui {
include latha:gui/gui@0.2.3;
import android;
}
+1074
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+87
View File
@@ -0,0 +1,87 @@
{
"apps": [
{
"label": "Calculator",
"component": "com.example.calculator/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f59e0b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Calendar",
"component": "com.example.calendar/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%233b82f6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Camera",
"component": "com.example.camera/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2364748b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Chrome",
"component": "com.example.chrome/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2322c55e%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Clock",
"component": "com.example.clock/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%230ea5e9%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Contacts",
"component": "com.example.contacts/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%236366f1%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E"
},
{
"label": "Files",
"component": "com.example.files/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23eab308%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EF%3C/text%3E%3C/svg%3E"
},
{
"label": "Gmail",
"component": "com.example.gmail/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ef4444%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EG%3C/text%3E%3C/svg%3E"
},
{
"label": "Maps",
"component": "com.example.maps/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2310b981%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E"
},
{
"label": "Messages",
"component": "com.example.messages/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%238b5cf6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E"
},
{
"label": "Music",
"component": "com.example.music/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ec4899%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E"
},
{
"label": "Phone",
"system": true,
"component": "com.example.phone/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2314b8a6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E"
},
{
"label": "Photos",
"component": "com.example.photos/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f97316%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E"
},
{
"label": "Play Store",
"system": true,
"component": "com.example.playstore/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2306b6d4%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E"
},
{
"label": "Settings",
"system": true,
"component": "com.example.settings/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2371717a%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3ES%3C/text%3E%3C/svg%3E"
},
{
"label": "Weather",
"component": "com.example.weather/.MainActivity",
"icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2338bdf8%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EW%3C/text%3E%3C/svg%3E"
}
]
}
+360
View File
@@ -0,0 +1,360 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>ultra · Launcher</title>
<link rel="stylesheet" href="ui.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<main id="app"></main>
<div id="toast" role="status"></div>
<script type="module">
import { mount } from "./ultra.js";
// On a phone, MainActivity.java adds window.Android, serves apps.json and
// 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 t = document.getElementById("toast");
t.textContent = s; t.classList.add("show");
clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove("show"), 1600);
};
let demoWidget = 100;
const host = window.Android || {
launch: (c) => toast("Open " + c),
appInfo: (c) => toast("App info for " + c),
uninstall: (c) => toast("Uninstall " + c),
addWidget: () => setTimeout(() => window.ultraHome.widgetAdded(demoWidget++), 0),
removeWidget: () => {},
placeWidgets: () => {},
widgetLimits: () => JSON.stringify({ minW: 120, minH: 80, maxW: 0, maxH: 0, h: true, v: true }),
openSettings: () => toast("Open system settings"),
pickWallpaper: () => toast("Pick a wallpaper"),
openRecents: () => toast("Show open windows"),
checkUpdates: () => toast("Check for updates"),
showKeyboard: () => {},
hideKeyboard: () => {},
haptic: () => navigator.vibrate?.(10),
};
if (!window.Android) document.documentElement.classList.add("demo");
// 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),
s.classList.contains("resizing") ? 1 : 0]; // its body moves it instead of taking touches
});
const j = JSON.stringify(slots);
// The drawer unmarks the slots, but the home screen under it doesn't move, so the
// widgets stay where they were and cover() hides them as it slides over them.
const underDrawer = document.querySelector(".drawer") && !document.querySelector(".sheet-overlay");
if (j !== placed && !underDrawer) { placed = j; host.placeWidgets(j); }
// Keep the system's edge swipes (back) off the resize handles.
const handles = JSON.stringify([...document.querySelectorAll(".resize-handle")].map((h) => {
const r = h.getBoundingClientRect();
return [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)];
}));
if (handles !== excluded) { excluded = handles; host.excludeGestures?.(handles); }
};
let excluded = "[]";
// Native widgets sit above the page, so the drawer can't cover them by itself. While it
// slides down the shell hides them above its bottom edge each frame (coverWidgets(y),
// CSS px; -1 once it covers the screen), so they stay until the drawer reaches them.
// The edge is reported a little ahead (by its speed), since the shell trails a frame.
let coverY = 0, coverLast = 0, coverLoop = false;
const cover = () => {
const d = document.querySelector(".drawer");
let y = 0;
if (d) {
const b = d.getBoundingClientRect().bottom;
y = b >= innerHeight - 1 ? -1 : Math.max(0, Math.ceil(b + 2 * Math.max(0, b - coverLast)));
coverLast = b;
if (y >= innerHeight) y = innerHeight - 1;
} else coverLast = 0;
if (y !== coverY) { coverY = y; host.coverWidgets?.(y); }
if (d && y !== -1 && !coverLoop) {
coverLoop = true;
requestAnimationFrame(() => { coverLoop = false; cover(); });
}
};
// Opening the drawer puts the cursor in its search box and raises the keyboard
// (a WebView won't show it for a focus() the user didn't tap, so the shell does).
// Picking apps to add is for scrolling, so that stays keyboard-free.
let drawerOpen = false;
const watchDrawer = () => {
const d = document.querySelector(".drawer");
if (!!d === drawerOpen) return;
drawerOpen = !!d;
if (d) {
if (d.classList.contains("picking")) return;
d.querySelector(".drawer-head input")?.focus({ preventScroll: true });
host.showKeyboard?.();
} else {
document.activeElement?.blur?.();
host.hideKeyboard?.();
}
};
// Icons: each <img class="icon" data-icon=KEY> gets its src from here. On a phone the
// shell draws icons on its own thread and hands them back as data: URIs in batches
// (ultraIcons), so the WebView never loads icons through request interception.
// In a desktop browser the key is already a URL.
const iconSrc = new Map(), asked = new Set();
const setIcon = (img, src) => {
if (src) { img.src = src; img.classList.remove("missing"); } else img.classList.add("missing");
};
const fillIcons = () => {
const want = [];
for (const img of document.querySelectorAll("img.icon[data-icon]")) {
const k = img.dataset.icon;
if (img.__icon === k) continue;
if (iconSrc.has(k)) { img.__icon = k; setIcon(img, iconSrc.get(k)); }
else if (!asked.has(k)) { asked.add(k); want.push(k); }
}
if (!want.length) return;
if (host.loadIcons) host.loadIcons(JSON.stringify(want));
else gotIcons(Object.fromEntries(want.map((k) => [k, k])));
};
// An icon the shell couldn't draw ("") is asked for again, up to 3 times, with backoff;
// until then, and after, it shows as a blank disc.
const tries = new Map();
const gotIcons = (batch) => {
const again = [];
for (const k in batch) {
iconSrc.set(k, batch[k]); asked.delete(k);
const n = tries.get(k) || 0;
if (!batch[k] && n < 3) { tries.set(k, n + 1); again.push(k); }
}
fillIcons();
if (again.length) setTimeout(() => {
for (const k of again) iconSrc.delete(k);
for (const img of document.querySelectorAll("img.icon[data-icon]"))
if (again.includes(img.dataset.icon)) img.__icon = undefined;
fillIcons();
}, 800 * (tries.get(again[0]) || 1));
};
window.ultraIcons = gotIcons; // the shell calls this before ultraHome exists, too
let ready = false; // the grid code below exists and app is mounted
const app = await mount("#app", "./app.wasm", {
onRender: () => { fillIcons(); place(); cover(); watchDrawer(); if (ready) measureGrid(); },
imports: ({ strs }) => ({
launch: (h) => host.launch(strs[h]),
app_info: (h) => host.appInfo(strs[h]),
uninstall: (h) => host.uninstall(strs[h]),
add_widget: (h) => host.addWidget(strs[h]),
remove_widget: (id) => host.removeWidget(id),
open_settings: () => host.openSettings(),
pick_wallpaper: () => host.pickWallpaper(),
open_recents: () => host.openRecents(),
check_updates: () => host.checkUpdates(),
haptic: () => host.haptic(),
}),
});
ready = true;
// Messages the shell and the gestures below send (keep in sync with app.py).
const RELOAD = 2, HOME = 3, BACK = 4, SWIPE_DOWN = 5, SWIPE_UP = 6,
WIDGET_ADDED = 7, WIDGET_MENU = 8, DRAG_TO = 35, DROP = 36, RESIZE = 40, GRAB = 42, WIDGET_COLS = 44,
GRID = 45, MOVE_CELL = 47;
// The home grid: its columns, and as many rows as fit down to the bottom of the
// screen (app.py lays those out, so the empty cells there are real cells).
const grid = () => {
const slots = document.querySelector(".slots");
if (!slots) return null;
const cs = getComputedStyle(slots), r = slots.getBoundingClientRect();
const colW = parseFloat(cs.gridTemplateColumns), gap = parseFloat(cs.columnGap) || 0;
return { left: r.left, top: r.top, cols: cs.gridTemplateColumns.split(" ").length,
colW, gap, cell: parseFloat(cs.gridAutoRows) || 64, rgap: parseFloat(cs.rowGap) || 0,
rows: cs.gridTemplateRows.split(" ").length };
};
let gridSent = -1;
const measureGrid = () => {
const g = grid(), home = document.querySelector(".home");
if (!g || !home) return;
const bottom = innerHeight - parseFloat(getComputedStyle(home).paddingBottom); // of the first screen
const rows = Math.max(1, Math.floor((bottom - (g.top + scrollY) + g.rgap) / (g.cell + g.rgap)));
const v = g.cols * 4096 + rows;
if (v !== gridSent) { gridSent = v; app.dispatch(GRID, v); }
};
const cellAt = (g, x, y) => [Math.max(0, Math.round((x - g.left) / (g.colW + g.gap))),
Math.max(0, Math.round((y - g.top) / (g.cell + g.rgap)))];
// Dragging a home slot. A long press lifts it (app.py marks it .lifted). Moving the
// finger over another slot moves it there in the order (the grid stays packed);
// over an empty cell it is left in that cell (top left by where it was held), and
// letting go drops it; whatever it then covers moves on to free cells.
// Letting go without moving opens its menu instead. A widget showing resize handles
// needs no long press: pressing its body picks it up right away (GRAB), and it keeps
// its handles when let go. Native widget views take their own touches, so the shell
// reports those through widgetGrab/widgetDrag/widgetDrop.
let drag = null, dragged = false; // drag: { x, y, moved } from pointerdown
let carry = null; // { dx, dy, cell }: where the lifted slot was held, the cell sent last
const inside = (r, x, y) => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;
const slotAt = (x, y) => {
for (const li of document.querySelectorAll(".slots > li[data-slot]:not(.lifted)"))
if (inside(li.getBoundingClientRect(), x, y)) return +li.dataset.slot;
return -1;
};
const dragTo = (x, y, x0 = x, y0 = y) => { // x0, y0: where the finger went down
const lifted = document.querySelector(".slots > .lifted"), g = grid();
if (!lifted || !g) return;
if (!carry) {
const r = lifted.getBoundingClientRect();
carry = { dx: x0 - r.left, dy: y0 - r.top, cell: -1 };
}
// A widget goes to the cell under it wherever that is (apps flow around it), so it
// can sit on any row; an app over another app takes its place in the order.
const widget = lifted.classList.contains("widget-slot");
if (!widget && inside(lifted.getBoundingClientRect(), x, y)) return;
// the cell under the finger: a slot there takes the lifted one's place in the order
const [fc, fr] = cellAt(g, x - g.colW / 2, y - g.cell / 2);
const to = slotAt(x, y) >= 0 ? slotAt(x, y)
: slotAt(g.left + fc * (g.colW + g.gap) + g.colW / 2, g.top + fr * (g.cell + g.rgap) + g.cell / 2);
if (to >= 0 && !widget) { carry.cell = -1; app.dispatch(DRAG_TO, to); return; }
if (y > g.top + g.rows * (g.cell + g.rgap)) return; // below the grid
const [col, row] = cellAt(g, x - carry.dx, y - carry.dy);
const cell = row * 64 + Math.min(col, 63);
if (cell !== carry.cell) { carry.cell = cell; app.dispatch(MOVE_CELL, cell); }
};
const drop = (moved) => {
carry = null;
if (document.querySelector(".slots > .lifted")) app.dispatch(DROP, moved ? 1 : 0);
};
let grabbed = false;
const grab = (li) => { grabbed = true; app.dispatch(GRAB, +li.dataset.slot); };
addEventListener("pointerdown", (e) => {
const li = e.isPrimary && !e.target.closest?.(".resize-handle") && e.target.closest?.(".slots > li.resizing");
if (li) grab(li);
}, true);
addEventListener("pointerdown", (e) => {
drag = e.isPrimary && e.target.closest?.(".slots > li") ? { x: e.clientX, y: e.clientY, moved: false } : null;
dragged = false;
});
addEventListener("pointermove", (e) => {
if (!drag || !document.querySelector(".slots > .lifted")) return;
if (!drag.moved && Math.hypot(e.clientX - drag.x, e.clientY - drag.y) < 10) return;
drag.moved = dragged = true;
dragTo(e.clientX, e.clientY, drag.x, drag.y);
});
addEventListener("pointerup", () => { if (drag) drop(drag.moved); drag = null; });
addEventListener("pointercancel", () => { if (drag) drop(drag.moved); drag = null; });
// Keep the page from scrolling under a lifted slot.
addEventListener("touchmove", (e) => {
if (drag && document.querySelector(".slots > .lifted") && e.cancelable) e.preventDefault();
}, { passive: false });
// Resizing a widget. Holding a widget and letting go without moving shows handles on
// its right edge, bottom edge and corner (app.py). Dragging one snaps the widget to
// whole grid columns and rows, within the shell's limits for that widget
// (widgetLimits, CSS px: min/max size, 0 = no max, and whether it resizes h and v).
let rs = null, swallowClick = false;
const span = (k, size, gap) => k * size + (k - 1) * gap;
const fit = (want, lo, hi, size, gap, min, max) => {
// the step nearest to want, kept within [min, max] px where it can be
let k = Math.round((want + gap) / (size + gap));
while (k < hi && span(k, size, gap) < min - 8) k++;
while (k > lo && max > 0 && span(k, size, gap) > max + 8) k--;
return Math.max(lo, Math.min(hi, k));
};
addEventListener("pointerdown", (e) => {
const h = e.target.closest?.(".resize-handle");
if (!h || !e.isPrimary) return;
e.stopPropagation(); e.preventDefault(); // not a long press on the slot under it
const li = h.closest("li"), slots = li.parentElement, cs = getComputedStyle(slots);
const cols = cs.gridTemplateColumns.split(" ").map(parseFloat);
const wid = +li.dataset.wid || 0;
let lim = {};
try { lim = JSON.parse(host.widgetLimits?.(wid) || "{}"); } catch {}
const r = li.getBoundingClientRect();
rs = { li, edge: h.dataset.edge, left: r.left, top: r.top, lim, n: cols.length, colW: cols[0],
gap: parseFloat(cs.columnGap) || 0, rgap: parseFloat(cs.rowGap) || 0,
cell: parseFloat(cs.gridAutoRows) || 88, // a row of app tiles
cols: Math.round((r.width + (parseFloat(cs.columnGap) || 0)) / (cols[0] + (parseFloat(cs.columnGap) || 0))),
h: Math.round(r.height) };
dragged = true;
h.setPointerCapture?.(e.pointerId);
}, true);
addEventListener("pointermove", (e) => {
if (!rs) return;
const { lim, n, colW, gap, rgap, cell } = rs;
let cols = rs.cols, h = rs.h;
if (rs.edge !== "b" && lim.h !== false)
cols = fit(e.clientX - rs.left, 1, n, colW, gap, lim.minW || 0, lim.maxW || 0);
if (rs.edge !== "r" && lim.v !== false) {
const k = fit(e.clientY - rs.top, 1, 20, cell, rgap, lim.minH || 0, lim.maxH || 0);
h = Math.round(span(k, cell, rgap));
}
if (cols === rs.cols && h === rs.h) return;
rs.cols = cols; rs.h = h;
host.haptic();
app.dispatch(RESIZE, (cols >= n ? 0 : cols) * 4096 + h);
}, true);
const endResize = () => { if (rs || grabbed) { rs = null; grabbed = false; swallowClick = true; setTimeout(() => swallowClick = false, 0); } };
addEventListener("pointerup", endResize, true);
addEventListener("pointercancel", endResize, true);
addEventListener("click", (e) => { // the click that ends a handle drag or a move isn't a tap beside the widget
if (swallowClick || e.target.closest?.(".resize-handle")) { swallowClick = false; e.stopPropagation(); e.preventDefault(); }
}, true);
addEventListener("touchmove", (e) => { if (rs && e.cancelable) e.preventDefault(); }, { passive: false });
// A new widget starts as many columns wide as its natural width needs (widgetLimits
// "w", CSS px), like its height starts at whole rows; 0 is the whole row.
const widgetCols = (id) => {
let lim = {};
try { lim = JSON.parse(host.widgetLimits?.(id) || "{}"); } catch {}
const slots = document.querySelector(".slots");
if (!lim.w || !slots) return 0;
const cs = getComputedStyle(slots), cols = cs.gridTemplateColumns.split(" ").map(parseFloat);
const gap = parseFloat(cs.columnGap) || 0;
const k = Math.max(1, Math.ceil((lim.w + gap - 8) / (cols[0] + gap)));
return k >= cols.length ? 0 : k;
};
window.ultraHome = {
reload: () => app.dispatch(RELOAD, 0),
home: () => { app.dispatch(HOME, 0); window.scrollTo({ top: 0, behavior: "smooth" }); },
back: () => app.dispatch(BACK, 0),
widgetAdded: (id) => { app.dispatch(WIDGET_ADDED, id); app.dispatch(WIDGET_COLS, widgetCols(id)); },
widgetMenu: (id) => app.dispatch(WIDGET_MENU, id),
widgetGrab: (id) => { const li = document.querySelector(`.widget-slot.resizing[data-wid="${id}"]`);
if (li) app.dispatch(GRAB, +li.dataset.slot); },
widgetDrag: (x, y) => { dragged = true; dragTo(x, y); },
widgetDrop: (moved) => drop(moved),
place: () => { placed = ""; place(); },
resetIcons: () => { iconSrc.clear(); asked.clear(); tries.clear();
for (const img of document.querySelectorAll("img.icon")) img.__icon = undefined; },
};
addEventListener("scroll", () => requestAnimationFrame(place), { passive: true });
addEventListener("resize", () => requestAnimationFrame(() => { place(); measureGrid(); }));
measureGrid();
// 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 || dragged || document.querySelector(".slots > .lifted")) { start = null; 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>
</body>
</html>
+153
View File
@@ -0,0 +1,153 @@
/* 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
--inset-bottom to the status and navigation bar (and keyboard) heights. */
:root {
--top: var(--inset-top, env(safe-area-inset-top, 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.demo { background: linear-gradient(160deg, #1e293b, #4c1d95 55%, #0f172a) fixed; }
body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: transparent;
user-select: none; -webkit-user-select: none; -webkit-touch-callout: none;
overscroll-behavior: none; }
#app { max-width: 560px; margin: 0 auto; }
/* ---- home */
.home { min-height: 100vh; box-sizing: border-box;
padding: calc(var(--top) + 1rem) 16px calc(var(--bottom) + 1.5rem); }
.panel { display: flex; gap: .5rem; margin: 0 auto 1rem; padding: .4rem; max-width: 22rem;
border-radius: 1.25rem; background: rgb(255 255 255 / .12); border: 1px solid rgb(255 255 255 / .16);
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); }
.panel-btn { flex: 1; display: flex; align-items: center; justify-content: center; gap: .6rem;
min-height: 2.5rem; padding: .4rem 1rem; border: 0; border-radius: .9rem;
background: rgb(255 255 255 / .1); color: #fff; font: inherit; font-weight: 500;
cursor: pointer; text-shadow: 0 1px 4px rgb(0 0 0 / .35); }
.panel-btn:hover, .panel-btn:active { background: rgb(255 255 255 / .22); }
.windows-glyph { position: relative; width: 1.1rem; height: 1.1rem; }
.windows-glyph::before, .windows-glyph::after { content: ""; position: absolute; border: 2px solid currentColor;
border-radius: .25rem; box-sizing: border-box; }
.windows-glyph::before { inset: 0 .3rem .3rem 0; opacity: .6; }
.windows-glyph::after { inset: .3rem 0 0 .3rem; background: rgb(255 255 255 / .15); }
.slots, .apps { list-style: none; margin: 0; padding: 0; display: grid; gap: 1.25rem .5rem;
grid-template-columns: repeat(4, minmax(0, 1fr)); }
/* The home grid is denser than the drawer: an extra column, smaller tiles. Its rows are
all one height, so a widget spans whole rows of app tiles, and apps fill the cells
beside a widget rather than leaving holes (dense packing). Keep the row height and
row gap in sync with widget_rows in app.py. */
.slots { grid-template-columns: repeat(5, minmax(0, 1fr)); grid-auto-rows: 4rem; row-gap: .5rem;
grid-auto-flow: row dense; }
@media (min-width: 480px) { .apps { grid-template-columns: repeat(5, minmax(0, 1fr)); }
.slots { grid-template-columns: repeat(6, minmax(0, 1fr)); } }
.tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: .4rem;
padding: .35rem .15rem; border-radius: calc(var(--radius) + 4px); cursor: pointer; }
.tile:active { background: rgb(255 255 255 / .12); }
.icon { width: 3.25rem; height: 3.25rem; object-fit: contain; pointer-events: none;
filter: drop-shadow(0 2px 4px rgb(0 0 0 / .3)); }
.icon.missing { border-radius: 999px; background: rgb(255 255 255 / .18); object-position: -999px 0; }
.name { max-width: 100%; font-size: .75rem; line-height: 1.2; text-align: center;
text-shadow: var(--shadow-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.slots .tile { gap: .25rem; padding: .2rem .1rem; }
.slots .icon { width: 2.5rem; height: 2.5rem; }
.slots .name { font-size: .68rem; }
/* A widget takes whole rows. On a phone the native widget view covers the slot;
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);
max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
/* The native view can be narrower than the slot, so the label would peek out at its sides. */
.widget-slot[data-wid] .widget-label { visibility: hidden; }
/* A live widget sits bare on the wallpaper; the frame only comes back while it is picked
up or resized (or while its native view is away, e.g. another widget is being resized). */
.widget-slot[data-wid]:not(.lifted):not(.resizing) { background: none; border-color: transparent; }
/* A widget being resized: handles sit just outside its right and bottom edges, where the
native widget view doesn't cover them; the bottom one sits in the gap below the row. */
.widget-slot { position: relative; }
.widget-slot.resizing { z-index: 2; outline: 2px solid rgb(255 255 255 / .85);
outline-offset: 3px; transition: none; }
.resize-handle { position: absolute; z-index: 2; touch-action: none; cursor: nwse-resize; }
.resize-handle::after { content: ""; position: absolute; border-radius: 999px; background: #fff;
box-shadow: 0 1px 6px rgb(0 0 0 / .45); }
.resize-handle[data-edge="r"] { top: 0; bottom: 0; right: -16px; width: 16px; cursor: ew-resize; }
.resize-handle[data-edge="r"]::after { top: 50%; left: 6px; width: 6px; height: 2.5rem; transform: translateY(-50%); }
.resize-handle[data-edge="b"] { left: 0; right: 0; bottom: -1rem; height: 1rem; cursor: ns-resize; }
.resize-handle[data-edge="b"]::after { left: 50%; top: 5px; width: 2.5rem; height: 6px; transform: translateX(-50%); }
.resize-handle[data-edge="rb"] { right: -16px; bottom: -1rem; width: 2.75rem; height: 1rem; }
.resize-handle[data-edge="rb"]::after { right: 4px; top: 1px; width: 14px; height: 14px; border-radius: 4px; }
.resize-bar { position: fixed; left: 50%; bottom: calc(var(--bottom) + 1rem); z-index: 15; transform: translateX(-50%);
display: flex; align-items: center; gap: .5rem; padding: .4rem .4rem .4rem 1rem; border-radius: 999px;
background: rgb(0 0 0 / .8); color: #fff; font-size: .875rem; white-space: nowrap;
animation: ui-fade .15s; }
.resize-bar .btn.ghost { color: #fff; }
.resize-bar .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; }
/* A slot picked up by a long press, while it is dragged (index.html moves it). */
.slots > li { transition: transform .15s ease-out; }
.slots > .lifted { z-index: 1; transform: scale(1.12); background: rgb(255 255 255 / .16);
box-shadow: 0 8px 24px rgb(0 0 0 / .35); }
.slots.dragging > li:not(.lifted) { opacity: .8; }
.slots.dragging .tile:active { background: none; }
.hint, .empty { text-align: center; opacity: .85; text-shadow: var(--shadow-text); }
.hint { margin-top: 30vh; padding: 0 2rem; font-size: .9rem; line-height: 1.5; }
/* ---- drawer: slides down over the home screen */
.drawer { position: fixed; inset: 0; z-index: 10; display: flex; flex-direction: column;
padding: calc(var(--top) + 1rem) 16px 0; background: rgb(10 10 14 / .72);
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; }
.widget-name { display: grid; }
.widget-name small { color: var(--muted-foreground); font-size: .8rem; }
.widget-search { width: 100%; margin-bottom: .5rem; }
.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; } }
+224
View File
@@ -0,0 +1,224 @@
/* ultra/ui.css: shadcn/ui's look as plain CSS, for the helpers in ui.py.
*
* The tokens are shadcn's "neutral" theme (https://ui.shadcn.com/docs/theming)
* and the component rules follow its Tailwind classes. Override any token on
* :root to retheme. Dark mode follows the OS, or force it with class="dark"
* (or "light") on any element; this needs CSS light-dark() (2024+ browsers).
* `build` copies this file next to app.wasm.
*/
/* Each token is light-dark(light, dark), so it follows color-scheme. */
:root {
color-scheme: light dark;
--radius: .625rem;
--background: light-dark(oklch(1 0 0), oklch(.145 0 0));
--foreground: light-dark(oklch(.145 0 0), oklch(.985 0 0));
--card: light-dark(oklch(1 0 0), oklch(.205 0 0));
--card-foreground: var(--foreground);
--popover: var(--card);
--popover-foreground: var(--foreground);
--primary: light-dark(oklch(.205 0 0), oklch(.922 0 0));
--primary-foreground: light-dark(oklch(.985 0 0), oklch(.205 0 0));
--secondary: light-dark(oklch(.97 0 0), oklch(.269 0 0));
--secondary-foreground: light-dark(oklch(.205 0 0), oklch(.985 0 0));
--muted: var(--secondary);
--muted-foreground: light-dark(oklch(.556 0 0), oklch(.708 0 0));
--accent: var(--secondary);
--accent-foreground: var(--secondary-foreground);
--destructive: light-dark(oklch(.577 .245 27.325), oklch(.704 .191 22.216));
--border: light-dark(oklch(.922 0 0), oklch(1 0 0 / 10%));
--input: light-dark(oklch(.922 0 0), oklch(1 0 0 / 15%));
--input-bg: light-dark(transparent, oklch(1 0 0 / 4.5%));
--ring: light-dark(oklch(.708 0 0), oklch(.556 0 0));
--shadow-xs: 0 1px 2px 0 rgb(0 0 0 / .05);
--shadow-sm: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);
--font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
--font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.light { color-scheme: light; }
.dark { color-scheme: dark; }
/* ---------------------------------------------------------------- base */
*, ::before, ::after { box-sizing: border-box; }
body {
margin: 0; background: var(--background); color: var(--foreground);
font: 14px/1.5 var(--font-sans); -webkit-font-smoothing: antialiased;
}
.light, .dark { background: var(--background); color: var(--foreground); }
button, input { font: inherit; color: inherit; margin: 0; }
button { border: 0; background: none; padding: 0; }
:focus-visible { outline: none; }
.muted { color: var(--muted-foreground); }
.mono { font-family: var(--font-mono); }
.stack { display: grid; gap: 1rem; }
.row { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; }
.grow { flex: 1; }
/* ---------------------------------------------------------------- button */
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: .5rem;
height: 2.25rem; padding: .5rem 1rem; border-radius: calc(var(--radius) - 2px);
font-size: .875rem; font-weight: 500; line-height: 1; white-space: nowrap;
border: 1px solid transparent; cursor: pointer; user-select: none;
background: var(--primary); color: var(--primary-foreground); box-shadow: var(--shadow-xs);
transition: background-color .15s, color .15s, box-shadow .15s, opacity .15s;
}
.btn:hover { background: color-mix(in oklab, var(--primary) 90%, transparent); }
.btn:disabled { opacity: .5; pointer-events: none; }
.btn:focus-visible, .input:focus-visible, .checkbox:focus-visible, .switch:focus-visible,
.tab:focus-visible, .toggle:focus-visible {
border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent);
}
.btn.secondary { background: var(--secondary); color: var(--secondary-foreground); }
.btn.secondary:hover { background: color-mix(in oklab, var(--secondary) 80%, transparent); }
.btn.outline {
background: light-dark(var(--background), var(--input-bg)); color: var(--foreground);
border-color: light-dark(var(--border), var(--input));
}
.btn.outline:hover, .btn.ghost:hover { background: var(--accent); color: var(--accent-foreground); }
.btn.ghost { background: transparent; color: var(--foreground); box-shadow: none; }
.btn.destructive { background: light-dark(var(--destructive), color-mix(in oklab, var(--destructive) 60%, transparent)); color: #fff; }
.btn.destructive:hover { background: color-mix(in oklab, var(--destructive) 90%, transparent); }
.btn.link { background: none; color: var(--primary); box-shadow: none; text-underline-offset: 4px; }
.btn.link:hover { text-decoration: underline; }
.btn.sm { height: 2rem; padding: 0 .75rem; gap: .375rem; }
.btn.lg { height: 2.5rem; padding: 0 1.5rem; }
.btn.icon { width: 2.25rem; padding: 0; }
.btn.icon.sm { width: 2rem; }
/* ---------------------------------------------------------------- card */
.card {
display: flex; flex-direction: column; gap: 1.5rem; padding: 1.5rem 0;
background: var(--card); color: var(--card-foreground);
border: 1px solid var(--border); border-radius: calc(var(--radius) + 4px); box-shadow: var(--shadow-sm);
}
.card-header { display: grid; gap: .375rem; padding: 0 1.5rem; }
.card-title { margin: 0; font-size: 1rem; font-weight: 600; line-height: 1; }
.card-description { margin: 0; font-size: .875rem; color: var(--muted-foreground); }
.card-content { padding: 0 1.5rem; }
.card-footer { display: flex; align-items: center; gap: .5rem; padding: 0 1.5rem; }
/* ---------------------------------------------------------------- input, label */
.input {
display: flex; width: 100%; min-width: 0; height: 2.25rem; padding: .25rem .75rem;
border: 1px solid var(--input); border-radius: calc(var(--radius) - 2px);
background: var(--input-bg); box-shadow: var(--shadow-xs); font-size: .875rem;
transition: box-shadow .15s, border-color .15s;
}
.input::placeholder { color: var(--muted-foreground); }
.label { display: flex; align-items: center; gap: .5rem; font-size: .875rem; font-weight: 500; line-height: 1; user-select: none; }
.field { display: inline-flex; align-items: center; gap: .5rem; cursor: pointer; }
/* ---------------------------------------------------------------- badge */
.badge {
display: inline-flex; align-items: center; justify-content: center; gap: .25rem; width: fit-content;
padding: .125rem .5rem; border: 1px solid transparent; border-radius: calc(var(--radius) - 2px);
font-size: .75rem; font-weight: 500; white-space: nowrap;
background: var(--primary); color: var(--primary-foreground);
}
.badge.secondary { background: var(--secondary); color: var(--secondary-foreground); }
.badge.destructive { background: light-dark(var(--destructive), color-mix(in oklab, var(--destructive) 60%, transparent)); color: #fff; }
.badge.outline { background: none; color: var(--foreground); border-color: var(--border); }
/* ---------------------------------------------------------------- checkbox, switch */
.checkbox {
position: relative; flex: none; width: 1rem; height: 1rem; padding: 0; cursor: pointer;
border: 1px solid var(--input); border-radius: 4px; background: var(--input-bg); box-shadow: var(--shadow-xs);
transition: box-shadow .15s;
}
.checkbox[aria-checked="true"] { background: var(--primary); border-color: var(--primary); }
.checkbox[aria-checked="true"]::after {
content: ""; position: absolute; left: 4.5px; top: 1.5px; width: 4px; height: 8px;
border: solid var(--primary-foreground); border-width: 0 2px 2px 0; transform: rotate(45deg);
}
.switch {
display: inline-flex; flex: none; align-items: center; width: 2rem; height: 1.15rem; padding: 0;
border: 1px solid transparent; border-radius: 999px; background: var(--input); cursor: pointer;
box-shadow: var(--shadow-xs); transition: background-color .15s;
}
.switch::after {
content: ""; width: 1rem; height: 1rem; border-radius: 999px; background: var(--background);
transition: transform .15s;
}
.switch:not([aria-checked="true"])::after { background: light-dark(var(--background), var(--foreground)); }
.switch[aria-checked="true"] { background: var(--primary); }
.switch[aria-checked="true"]::after { transform: translateX(calc(100% - 2px)); }
/* ---------------------------------------------------------------- tabs, toggle group */
.tabs-list {
display: inline-flex; align-items: center; height: 2.25rem; width: fit-content; padding: 3px;
border-radius: var(--radius); background: var(--muted); color: var(--muted-foreground);
}
.tab {
display: inline-flex; flex: 1; align-items: center; justify-content: center; height: 100%;
padding: .25rem .5rem; border: 1px solid transparent; border-radius: calc(var(--radius) - 2px);
background: none; font-size: .875rem; font-weight: 500; white-space: nowrap; cursor: pointer;
color: light-dark(var(--foreground), var(--muted-foreground)); transition: color .15s, box-shadow .15s;
}
.tab[aria-selected="true"] {
background: light-dark(var(--background), var(--input-bg)); border-color: light-dark(transparent, var(--input));
color: var(--foreground); box-shadow: var(--shadow-sm);
}
.toggle-group { display: inline-flex; width: fit-content; border-radius: calc(var(--radius) - 2px); box-shadow: var(--shadow-xs); }
.toggle {
display: inline-flex; align-items: center; justify-content: center; height: 2.25rem; min-width: 2.25rem;
padding: 0 .75rem; border: 1px solid var(--input); background: none; font-size: .875rem; font-weight: 500;
cursor: pointer; transition: background-color .15s;
}
.toggle:hover { background: var(--muted); color: var(--muted-foreground); }
.toggle[aria-pressed="true"] { background: var(--accent); color: var(--accent-foreground); }
.toggle-group .toggle { border-radius: 0; }
.toggle-group .toggle + .toggle { border-left: 0; }
.toggle-group .toggle:first-child { border-radius: calc(var(--radius) - 2px) 0 0 calc(var(--radius) - 2px); }
.toggle-group .toggle:last-child { border-radius: 0 calc(var(--radius) - 2px) calc(var(--radius) - 2px) 0; }
/* ---------------------------------------------------------------- dialog */
.dialog-overlay { position: fixed; inset: 0; z-index: 50; background: rgb(0 0 0 / .5); animation: ui-fade .15s; }
.dialog {
position: fixed; z-index: 50; top: 50%; left: 50%; transform: translate(-50%, -50%);
display: grid; gap: 1rem; width: calc(100% - 2rem); max-width: 32rem; padding: 1.5rem;
border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow-lg);
background: var(--background); color: var(--foreground); animation: ui-zoom .15s;
}
.dialog-header { display: grid; gap: .5rem; }
.dialog-title { margin: 0; font-size: 1.125rem; font-weight: 600; line-height: 1; }
.dialog-description { margin: 0; font-size: .875rem; color: var(--muted-foreground); }
.dialog-footer { display: flex; flex-wrap: wrap-reverse; justify-content: flex-end; gap: .5rem; }
.dialog-close {
position: absolute; top: 1rem; right: 1rem; width: 1.25rem; height: 1.25rem; padding: 0;
border-radius: 4px; background: none; font-size: 1.125rem; line-height: 1; opacity: .7; cursor: pointer;
}
.dialog-close:hover { opacity: 1; }
@keyframes ui-fade { from { opacity: 0; } }
@keyframes ui-zoom { from { opacity: 0; transform: translate(-50%, -50%) scale(.95); } }
/* ---------------------------------------------------------------- alert, separator, progress, kbd */
.alert {
display: grid; gap: .125rem; width: 100%; padding: .75rem 1rem; font-size: .875rem;
border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); color: var(--card-foreground);
}
.alert-title { font-weight: 500; }
.alert-description { color: var(--muted-foreground); }
.alert.destructive { color: var(--destructive); }
.alert.destructive .alert-description { color: color-mix(in oklab, var(--destructive) 90%, transparent); }
.separator { flex: none; height: 1px; width: 100%; margin: 0; border: 0; background: var(--border); }
.progress {
display: block; width: 100%; height: .5rem; overflow: hidden; border: 0; border-radius: 999px;
appearance: none; background: color-mix(in oklab, var(--primary) 20%, transparent);
}
.progress::-webkit-progress-bar { background: transparent; }
.progress::-webkit-progress-value { background: var(--primary); transition: width .2s; }
.progress::-moz-progress-bar { background: var(--primary); }
.kbd {
display: inline-flex; align-items: center; justify-content: center; height: 1.25rem; min-width: 1.25rem;
padding: 0 .25rem; border-radius: 4px; background: var(--muted); color: var(--muted-foreground);
font: 500 .75rem var(--font-sans);
}
/* ---------------------------------------------------------------- table */
.table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.table th { height: 2.5rem; padding: 0 .5rem; text-align: left; font-weight: 500; white-space: nowrap; }
.table td { padding: .5rem; }
.table tr { border-bottom: 1px solid var(--border); }
.table tbody tr:hover { background: color-mix(in oklab, var(--muted) 50%, transparent); }
.table tr[aria-selected="true"] { background: var(--muted); }
+410
View File
@@ -0,0 +1,410 @@
// ultra.js: the DOM glue for ultra apps written in LPython.
//
// The wasm module calls into the "js" imports below while view() runs; those
// calls build a lightweight vnode tree. After view() returns we diff the new
// tree against the last one and patch the DOM. Events are delegated from the
// mount point and turned into update(msg, arg) calls.
const EVENT = 0;
export async function mount(root, url, opts = {}) {
if (typeof root === "string") root = document.querySelector(root);
let mem, ex;
const td = new TextDecoder();
const cache = new Map();
// LPython strings are a pointer to { data: i32, len: i32 }.
// Literals live in static data, so decoding is cached by (data, len).
let dv = null;
const str = (p) => {
if (dv === null || dv.buffer !== mem.buffer) dv = new DataView(mem.buffer);
const a = dv.getInt32(p, true), l = dv.getInt32(p + 4, true);
const k = a * 4096 + l;
let s = cache.get(k);
if (s === undefined) {
s = td.decode(new Uint8Array(mem.buffer, a, l));
if (l < 4096) cache.set(k, s);
}
return s;
};
const K = (k) => (typeof k === "object" ? k.k : str(k)); // storage key
// ------------------------------------------------------------ string store
const strs = [""];
const free = [];
const sNew = (v = "") => {
if (free.length) { const h = free.pop(); strs[h] = v; return h; }
strs.push(v); return strs.length - 1;
};
// ------------------------------------------------------------ vnode builder
// vnode: { t, k, a, cls, p, ev, c, n } text: { t: "#", s, n }
let stack, cur;
const node = (t) => ({ t, k: null, a: null, cls: "", p: null, ev: null, c: [], n: null });
let nodes = 0;
const push = (v) => { nodes++; cur.c.push(v); };
const txt = (s) => push({ t: "#", k: null, s: String(s), n: null });
const setA = (k, v) => ((cur.a ||= {})[k] = v);
const setP = (k, v) => ((cur.p ||= {})[k] = v);
const setEv = (k, v) => ((cur.ev ||= {})[k] = v);
// ------------------------------------------------------------ scheduling
// Messages are applied immediately; the re-render is batched onto the next
// animation frame. frame(msg, arg) messages are held until that frame and
// applied just before view(), so an animation steps once per rendered frame.
let queued = false;
let frameQ = [];
let since = 0, tUpdate = 0; // first dispatch since the last render, time in update()
const schedule = () => {
if (queued) return;
queued = true;
if (!since) since = performance.now();
requestAnimationFrame(render);
};
const dispatch = (msg, arg) => {
const t = performance.now();
if (!since) since = t;
ex.update(msg, arg);
tUpdate += performance.now() - t;
schedule();
};
// ------------------------------------------------------------ json store
// Decoded JSON values live here too; LPython holds i32 handles and reads
// fields by dotted path ("repos.3.did"). Handle 0 is "nothing".
const vals = [undefined];
const vfree = [];
const vNew = (v) => {
if (v === undefined) return 0;
if (vfree.length) { const h = vfree.pop(); vals[h] = v; return h; }
vals.push(v); return vals.length - 1;
};
const walk = (h, p) => {
let v = vals[h];
const path = str(p);
if (path) for (const k of path.split(".")) { if (v == null) return undefined; v = v[k]; }
return v;
};
const asText = (v) => (typeof v === "string" ? v : JSON.stringify(v, null, 2));
const httpGet = (url, msg) => {
const h = vNew(null);
fetch(url, { headers: { accept: "application/json" } })
.then(async (r) => {
const body = await r.json().catch(() => null);
vals[h] = r.ok ? body
: { __error: (body && (body.message || body.error)) || "HTTP " + r.status };
})
.catch((e) => { vals[h] = { __error: String(e.message || e) }; })
.then(() => dispatch(msg, h));
return h;
};
const js = {
el: (p) => { const v = node(str(p)); push(v); stack.push(cur); cur = v; },
end: () => { cur = stack.pop(); },
text: (p) => txt(str(p)),
num: (x) => txt(x),
fnum: (x, d) => txt(x.toFixed(d)),
text_ref: (h) => txt(strs[h] ?? ""),
attr: (k, v) => setA(str(k), str(v)),
attr_num: (k, v) => setA(str(k), String(v)),
attr_ref: (k, h) => setA(str(k), strs[h] ?? ""),
cls: (p) => { const c = str(p); if (c) cur.cls = cur.cls ? cur.cls + " " + c : c; },
cls_if: (p, on) => { if (on) js.cls(p); },
key: (k) => { cur.k = k; },
value_ref: (h) => setP("value", strs[h] ?? ""),
checked: (on) => setP("checked", !!on),
autofocus: () => setP("__focus", true),
on_click: (m, a) => setEv("click", [m, a]),
on_dblclick: (m, a) => setEv("dblclick", [m, a]),
on_input: (m) => setEv("input", [m, EVENT]),
on_enter: (m, a) => setEv("enter", [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),
frame: (m, a) => { frameQ.push(m, a); schedule(); },
now_ms: () => performance.now(),
log: (x) => console.log("[ultra]", x),
s_new: () => sNew(),
s_dup: (h) => sNew(strs[h]),
s_copy: (d, s) => { strs[d] = strs[s]; },
s_clear: (h) => { strs[h] = ""; },
s_free: (h) => { if (h > 0) { strs[h] = ""; free.push(h); } },
s_len: (h) => (strs[h] ?? "").trim().length,
s_set: (h, p) => { strs[h] = str(p); },
s_add: (h, p) => { strs[h] += str(p); },
s_add_ref: (h, s) => { strs[h] += strs[s] ?? ""; },
s_add_num: (h, x) => { strs[h] += String(x); },
s_eq: (a, b) => (strs[a] === strs[b] ? 1 : 0),
s_has: (h, n) => ((strs[h] ?? "").toLowerCase().includes((strs[n] ?? "").trim().toLowerCase()) ? 1 : 0),
s_save: (k, h) => { try { localStorage.setItem(K(k), strs[h]); } catch {} },
s_load: (k, h) => {
let v = null;
try { v = localStorage.getItem(K(k)); } catch {}
if (v === null) return 0;
strs[h] = v; return 1;
},
store_i32: (k, v) => { try { localStorage.setItem(K(k), String(v)); } catch {} },
load_i32: (k, d) => {
let v = null;
try { v = localStorage.getItem(K(k)); } catch {}
return v === null ? d : v | 0;
},
http_get: (p, m) => httpGet(str(p), m),
http_get_ref: (h, m) => httpGet(strs[h], m),
j_ok: (h) => (vals[h] != null && !(typeof vals[h] === "object" && "__error" in vals[h]) ? 1 : 0),
j_err: (h, d) => { const v = vals[h]; strs[d] = v && v.__error ? v.__error : v == null ? "no response" : ""; },
j_at: (h, p) => vNew(walk(h, p)),
j_idx: (h, i) => vNew((vals[h] ?? [])[i]),
j_has: (h, p) => (walk(h, p) != null ? 1 : 0),
j_len: (h, p) => {
const v = walk(h, p);
return Array.isArray(v) || typeof v === "string" ? v.length : v && typeof v === "object" ? Object.keys(v).length : 0;
},
j_int: (h, p) => { const v = walk(h, p); return typeof v === "boolean" ? +v : Number(v) | 0; },
j_str: (h, p, d) => { const v = walk(h, p); strs[d] = v == null ? "" : asText(v); return v == null ? 0 : 1; },
j_key: (h, i, d) => { strs[d] = Object.keys(vals[h] ?? {})[i] ?? ""; },
j_free: (h) => { if (h > 0) { vals[h] = undefined; vfree.push(h); } },
};
// Apps can declare their own @jscall imports and supply them here.
if (opts.imports) Object.assign(js, opts.imports({ str, strs, vals, sNew, dispatch, text: txt }));
for (const f of ["s_save", "s_load", "store_i32", "load_i32"]) {
const base = js[f];
js[f + "_at"] = (k, i, x) => base({ k: str(k) + "." + i }, x);
}
// Minimal WASI so print() works and _start-style exits don't crash.
const wasi = {
proc_exit: () => {},
fd_write: (fd, iovs, n, out) => {
const dv = new DataView(mem.buffer);
let s = "", total = 0;
for (let i = 0; i < n; i++) {
const p = dv.getInt32(iovs + i * 8, true), l = dv.getInt32(iovs + i * 8 + 4, true);
s += td.decode(new Uint8Array(mem.buffer, p, l)); total += l;
}
(fd === 2 ? console.error : console.log)(s.replace(/\n$/, ""));
dv.setInt32(out, total, true);
return 0;
},
};
const imports = { js, wasi_snapshot_preview1: wasi };
let instance;
if (typeof url === "string") {
const res = await fetch(url);
// Streaming compile needs the application/wasm MIME type; fall back if absent.
({ instance } = (res.headers.get("content-type") || "").startsWith("application/wasm")
? await WebAssembly.instantiateStreaming(res, imports)
: await WebAssembly.instantiate(await res.arrayBuffer(), imports));
} else {
({ instance } = await WebAssembly.instantiate(url, imports));
}
ex = instance.exports;
mem = ex.memory;
// ------------------------------------------------------------ diff / patch
const create = (v) => {
if (v.t === "#") return (v.n = document.createTextNode(v.s));
const n = (v.n = document.createElement(v.t));
if (v.cls) n.className = v.cls;
if (v.a) for (const k in v.a) n.setAttribute(k, v.a[k]);
if (v.p) setProps(n, null, v.p);
n.__ev = v.ev;
for (const c of v.c) n.appendChild(create(c));
return n;
};
const setProps = (n, o, p) => {
for (const k in p) {
if (k === "__focus") { if (!o || !o.__focus) queueMicrotask(() => n.focus()); continue; }
if (n[k] !== p[k]) n[k] = p[k];
}
};
const patch = (o, v) => {
if (o.t !== v.t || o.k !== v.k) {
const n = create(v);
o.n.replaceWith(n);
return;
}
const n = (v.n = o.n);
if (v.t === "#") { if (o.s !== v.s) n.data = v.s; return; }
if (o.cls !== v.cls) n.className = v.cls;
if (o.a !== v.a) {
const oa = o.a || {}, va = v.a || {};
for (const k in oa) if (!(k in va)) n.removeAttribute(k);
for (const k in va) if (oa[k] !== va[k]) n.setAttribute(k, va[k]);
}
if (v.p) setProps(n, o.p, v.p);
n.__ev = v.ev;
patchChildren(n, o.c, v.c);
};
const patchChildren = (parent, oc, vc) => {
if (oc.length === 0 && vc.length === 0) return;
const keyed = vc.length > 0 && vc[0].k !== null && oc.length > 0 && oc[0].k !== null;
if (vc.length === 0 && parent.childNodes.length === oc.length) {
parent.textContent = ""; // clearing a whole list: one DOM op
return;
}
if (!keyed) {
const m = Math.min(oc.length, vc.length);
for (let i = 0; i < m; i++) patch(oc[i], vc[i]);
for (let i = m; i < vc.length; i++) parent.appendChild(create(vc[i]));
for (let i = m; i < oc.length; i++) oc[i].n.remove();
return;
}
patchKeyed(parent, oc, vc);
};
// Keyed children: skip the common prefix and suffix, then match the middle by
// key and move only the nodes outside the longest increasing subsequence of
// old positions. Swapping two rows of 1,000 moves 2 nodes, not 998.
const patchKeyed = (parent, oc, vc) => {
let os = 0, oe = oc.length - 1, vs = 0, ve = vc.length - 1;
while (os <= oe && vs <= ve && oc[os].k === vc[vs].k) patch(oc[os++], vc[vs++]);
while (os <= oe && vs <= ve && oc[oe].k === vc[ve].k) patch(oc[oe--], vc[ve--]);
const anchor = ve + 1 < vc.length ? vc[ve + 1].n : null;
if (os > oe) {
for (let i = vs; i <= ve; i++) parent.insertBefore(create(vc[i]), anchor);
return;
}
if (vs > ve) {
for (let i = os; i <= oe; i++) oc[i].n.remove();
return;
}
const at = new Map();
for (let i = vs; i <= ve; i++) at.set(vc[i].k, i);
if (os === 0 && oe === oc.length - 1 && parent.childNodes.length === oc.length &&
!oc.some((o) => at.has(o.k))) {
// Nothing reused (e.g. replacing every row): drop all, build all.
parent.textContent = "";
for (const v of vc) parent.appendChild(create(v));
return;
}
const src = new Int32Array(ve - vs + 1).fill(-1); // new slot -> old index
let moved = false, last = -1;
for (let i = os; i <= oe; i++) {
const o = oc[i], j = at.get(o.k);
if (j === undefined) { o.n.remove(); continue; }
src[j - vs] = i;
patch(o, vc[j]);
if (j < last) moved = true; else last = j;
}
const keep = moved ? lis(src) : null;
let li = keep ? keep.length - 1 : -1;
let next = anchor;
for (let j = ve; j >= vs; j--) {
const v = vc[j], p = j - vs;
if (src[p] === -1) parent.insertBefore(create(v), next);
else if (moved) {
if (li >= 0 && keep[li] === p) li--;
else parent.insertBefore(v.n, next);
}
next = v.n;
}
};
// Positions (into a) of a longest strictly increasing subsequence, skipping -1.
const lis = (a) => {
const prev = new Int32Array(a.length), tails = [];
for (let i = 0; i < a.length; i++) {
const x = a[i];
if (x === -1) continue;
let lo = 0, hi = tails.length;
while (lo < hi) { const m = (lo + hi) >> 1; if (a[tails[m]] < x) lo = m + 1; else hi = m; }
prev[i] = lo > 0 ? tails[lo - 1] : -1;
tails[lo] = i;
}
const out = new Array(tails.length);
for (let k = tails.length - 1, i = tails[k]; k >= 0; k--, i = prev[i]) out[k] = i;
return out;
};
// ------------------------------------------------------------ render
let prev = null;
// opts.onRender(stats) runs after each patch with timings in ms:
// { start, update, view, patch, end, nodes }
// where start is the first dispatch since the previous render.
function render() {
queued = false;
const t0 = performance.now();
if (frameQ.length) {
const q = frameQ; frameQ = [];
for (let i = 0; i < q.length; i += 2) ex.update(q[i], q[i + 1]);
}
const t1 = performance.now();
const top = node("#root");
stack = []; cur = top; nodes = 0;
ex.view();
const t2 = performance.now();
if (prev === null) {
root.textContent = "";
for (const c of top.c) root.appendChild(create(c));
} else {
patchChildren(root, prev.c, top.c);
}
prev = top;
const t3 = performance.now();
const stats = { start: since || t0, update: tUpdate + (t1 - t0),
view: t2 - t1, patch: t3 - t2, end: t3, nodes };
since = 0; tUpdate = 0;
if (opts.onRender) opts.onRender(stats);
}
// ------------------------------------------------------------ events
const find = (t, kind) => {
for (let n = t; n && n !== root; n = n.parentNode) if (n.__ev && n.__ev[kind]) return n.__ev[kind];
return null;
};
const on = (type, kind, pre) =>
root.addEventListener(type, (e) => {
if (pre && !pre(e)) return;
const h = find(e.target, kind);
if (!h) return;
if (kind === "input") strs[EVENT] = e.target.value;
dispatch(h[0], h[1]);
});
on("click", "click");
on("dblclick", "dblclick");
on("input", "input");
on("keydown", "enter", (e) => e.key === "Enter" && !e.isComposing);
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.
ex.__main__global_stmts();
render();
return { dispatch, render, exports: ex, strs, vals };
}
+32
View File
@@ -0,0 +1,32 @@
{
"widgets": [
{
"label": "Clock",
"app": "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",
"app": "Google",
"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",
"app": "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",
"app": "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
}
]
}