Rewrite the launcher in MoonBit (old code moves to legacy/) (#1)
This commit was merged in pull request #1.
This commit is contained in:
1 parent
7d2bf5996f
commit
2fa7bd745b
150 files changed
+8319
-462
No files matched your search
Generated
+2137
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
@@ -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>
|
||||
@@ -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" />
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user