diff --git a/qt/android/src/dev/ultra/launcher/HomeActivity.java b/qt/android/src/dev/ultra/launcher/HomeActivity.java index d9edba4..f549b09 100644 --- a/qt/android/src/dev/ultra/launcher/HomeActivity.java +++ b/qt/android/src/dev/ultra/launcher/HomeActivity.java @@ -47,6 +47,13 @@ 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; @@ -260,6 +267,13 @@ public class HomeActivity extends QtActivity { // ------------------------------------------------------------ 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\":[]}"; @@ -326,19 +340,60 @@ public class HomeActivity extends QtActivity { // Some icon drawables don't survive being loaded and drawn concurrently. private static final Object iconLock = new Object(); - /** An icon as a PNG, size px square: key "a:COMPONENT" (an app) or "w:PROVIDER" (a widget). */ + /** + * 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)); - return d == null ? null : toPng(d, Math.max(16, Math.min(size, 512))); + 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 = 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) { @@ -373,15 +428,17 @@ public class HomeActivity extends QtActivity { return d; } - private static byte[] toPng(Drawable d, int size) { + // 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)); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - bmp.compress(Bitmap.CompressFormat.PNG, 100, out); + ByteBuffer buf = ByteBuffer.allocate(size * size * 4); + bmp.copyPixelsToBuffer(buf); bmp.recycle(); - return out.toByteArray(); + return buf.array(); } private AppWidgetProviderInfo provider(String p) { diff --git a/qt/android/src/dev/ultra/launcher/Native.java b/qt/android/src/dev/ultra/launcher/Native.java index 625ccfd..4cb2f86 100644 --- a/qt/android/src/dev/ultra/launcher/Native.java +++ b/qt/android/src/dev/ultra/launcher/Native.java @@ -9,6 +9,7 @@ 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); diff --git a/qt/qml/Drawer.qml b/qt/qml/Drawer.qml index 41eb2ca..6ef6a00 100644 --- a/qt/qml/Drawer.qml +++ b/qt/qml/Drawer.qml @@ -10,6 +10,7 @@ Item { 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 @@ -102,7 +103,7 @@ Item { clip: true bottomMargin: root.insetBottom + 24 boundsBehavior: Flickable.DragOverBounds - model: root.shown + 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 { diff --git a/qt/qml/Main.qml b/qt/qml/Main.qml index 1a94da1..dc9b46c 100644 --- a/qt/qml/Main.qml +++ b/qt/qml/Main.qml @@ -114,7 +114,8 @@ Window { say("Brought over your home screen"); } - function loadApps() { setApps(Host.apps()); loading = false; dropGone(); } + function loadApps() { gotApps(Host.apps()) } + function gotApps(list) { setApps(list); loading = false; dropGone(); } function setApps(list) { const rows = {}; @@ -127,7 +128,7 @@ Window { const g = Object.assign({}, iconGen); for (const p of (packages || "").split(",")) if (p) g[p] = (g[p] || 0) + 1; iconGen = g; - loadApps(); + Host.requestApps(); if (sheet === "app") { sheet = ""; appSheetRow = -1; } } @@ -400,6 +401,7 @@ Window { Connections { target: Host function onAppsChanged(packages) { root.reload(packages) } + function onAppsLoaded(list) { root.gotApps(list) } function onHomePressed() { root.goHome() } function onBackPressed() { root.back() } function onWidgetAdded(id) { root.widgetAdded(id) } @@ -418,11 +420,15 @@ Window { function onLegacyHome(json) { root.importLegacy(json) } } + // The drawer's icons load once home's have had a head start (or when it opens). + Timer { id: drawerWarm; interval: 1500 } + Component.onCompleted: { loadHome(); setApps(Host.savedApps()); // icons and names show at once; the real list follows Host.ready(); - Qt.callLater(loadApps); + Host.requestApps(); + drawerWarm.start(); } // ---- view @@ -783,6 +789,7 @@ Window { homeSet: root.homeSet loading: root.loading iconGen: root.iconGen + warm: !drawerWarm.running insetTop: root.insetTop insetBottom: root.insetBottom onEdgeChanged: root.cover() diff --git a/qt/src/backend.cpp b/qt/src/backend.cpp index 8bf27bb..d2cb517 100644 --- a/qt/src/backend.cpp +++ b/qt/src/backend.cpp @@ -67,6 +67,13 @@ void jLegacyHome(JNIEnv *env, jclass, jstring json) { 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; @@ -81,6 +88,7 @@ void registerNatives() { {"widgetGrab", "(I)V", reinterpret_cast(jWidgetGrab)}, {"widgetDrag", "(II)V", reinterpret_cast(jWidgetDrag)}, {"widgetDrop", "(Z)V", reinterpret_cast(jWidgetDrop)}, + {"appList", "(Ljava/lang/String;)V", reinterpret_cast(jAppList)}, {"legacyHome", "(Ljava/lang/String;)V", reinterpret_cast(jLegacyHome)}, }; QJniEnvironment env; @@ -149,6 +157,21 @@ QVariantList Backend::apps() const { 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())); } diff --git a/qt/src/backend.h b/qt/src/backend.h index b854b7d..0754543 100644 --- a/qt/src/backend.h +++ b/qt/src/backend.h @@ -28,6 +28,7 @@ public: // 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; @@ -66,6 +67,7 @@ public: signals: void insetsChanged(); + void appsLoaded(const QVariantList &apps); void appsChanged(const QString &packages); // comma-separated; empty: any void homePressed(); void backPressed(); @@ -77,6 +79,9 @@ signals: 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; diff --git a/qt/src/iconprovider.cpp b/qt/src/iconprovider.cpp index a4344ff..ff55412 100644 --- a/qt/src/iconprovider.cpp +++ b/qt/src/iconprovider.cpp @@ -4,6 +4,8 @@ #include #include +#include + #ifdef Q_OS_ANDROID #include #include @@ -17,16 +19,19 @@ QImage IconProvider::requestImage(const QString &id, QSize *size, const QSize &r const int px = requested.width() > 0 ? requested.width() : 144; QImage img; #ifdef Q_OS_ANDROID - QJniObject png = QJniObject::callStaticObjectMethod( + // 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(), jint(px)); - if (png.isValid()) { + if (pixels.isValid()) { QJniEnvironment env; - auto arr = png.object(); + auto arr = pixels.object(); const jsize n = env->GetArrayLength(arr); - QByteArray bytes(n, Qt::Uninitialized); - env->GetByteArrayRegion(arr, 0, n, reinterpret_cast(bytes.data())); - img.loadFromData(bytes, "PNG"); + 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(img.bits())); + } } #else // A disc in a colour picked from the key, with the name's first letter.