Qt: faster app icons on start

Three things still held icons up:
- The app list was built on Qt's thread, so nothing on screen could paint
  (icons included) until every app was listed and labelled. HomeActivity
  now lists apps on its own thread and answers through Native.appList.
- Each icon was drawn, PNG-encoded in Java and decoded again in C++. Icons
  now cross as raw premultiplied RGBA, and drawn ones are kept in the cache
  dir, keyed by the app's last update, so a fresh start just reads them.
- The closed drawer made its icons at the same time as home. It now waits
  1.5s, or until it opens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiQsCq11CwCPnKPp9D
This commit is contained in:
Claude committed 2026-11-03 20:42:04 +00:00
1 parent 8abe104dda
commit 56a4ae4347
7 files changed
+115 -16

No files matched your search

@@ -47,6 +47,13 @@ import org.json.JSONObject;
import org.qtproject.qt.android.bindings.QtActivity; import org.qtproject.qt.android.bindings.QtActivity;
import java.io.ByteArrayOutputStream; 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.text.Collator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@@ -260,6 +267,13 @@ public class HomeActivity extends QtActivity {
// ------------------------------------------------------------ called from Qt // ------------------------------------------------------------ called from Qt
/** {"apps": [{"label", "component", "system"}]}, every launchable activity, by label. */ /** {"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() { static String apps() {
HomeActivity a = self; HomeActivity a = self;
if (a == null) return "{\"apps\":[]}"; 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. // Some icon drawables don't survive being loaded and drawn concurrently.
private static final Object iconLock = new Object(); 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) { static byte[] icon(String key, int size) {
HomeActivity a = self; HomeActivity a = self;
if (a == null || key == null || key.length() < 3) return null; 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) { synchronized (iconLock) {
try { try {
Drawable d = key.startsWith("w:") ? a.widgetIcon(key.substring(2)) : a.appIcon(key.substring(2)); 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) { } catch (RuntimeException | OutOfMemoryError e) {
Log.w("ultra", "icon for " + key, e); Log.w("ultra", "icon for " + key, e);
return null; 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) { private Drawable appIcon(String c) {
@@ -373,15 +428,17 @@ public class HomeActivity extends QtActivity {
return d; 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 d = d.mutate(); // setBounds on a drawable shared with other callers would move theirs
Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
d.setBounds(0, 0, size, size); d.setBounds(0, 0, size, size);
d.draw(new Canvas(bmp)); d.draw(new Canvas(bmp));
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteBuffer buf = ByteBuffer.allocate(size * size * 4);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); bmp.copyPixelsToBuffer(buf);
bmp.recycle(); bmp.recycle();
return out.toByteArray(); return buf.array();
} }
private AppWidgetProviderInfo provider(String p) { private AppWidgetProviderInfo provider(String p) {
@@ -9,6 +9,7 @@ final class Native {
private Native() {} private Native() {}
static native void appsChanged(String packages); // comma-separated static native void appsChanged(String packages); // comma-separated
static native void appList(String json); // HomeActivity.listApps' answer
static native void homePressed(); static native void homePressed();
static native void backPressed(); static native void backPressed();
static native void insets(int top, int bottom); static native void insets(int top, int bottom);
+2 -1
View File
@@ -10,6 +10,7 @@ Item {
property var apps: [] // [{label, component, system}] property var apps: [] // [{label, component, system}]
property var homeSet: ({}) // component -> true: on the home screen property var homeSet: ({}) // component -> true: on the home screen
property bool loading: true 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 var iconGen: ({}) // package -> n, see Main.gen
property real insetTop: 0 property real insetTop: 0
property real insetBottom: 0 property real insetBottom: 0
@@ -102,7 +103,7 @@ Item {
clip: true clip: true
bottomMargin: root.insetBottom + 24 bottomMargin: root.insetBottom + 24
boundsBehavior: Flickable.DragOverBounds 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. // Swiping up once the list is at its end puts the drawer away.
onDragEnded: if (verticalOvershoot > 48) root.closeRequested() onDragEnded: if (verticalOvershoot > 48) root.closeRequested()
delegate: Item { delegate: Item {
+10 -3
View File
@@ -114,7 +114,8 @@ Window {
say("Brought over your home screen"); 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) { function setApps(list) {
const rows = {}; const rows = {};
@@ -127,7 +128,7 @@ Window {
const g = Object.assign({}, iconGen); const g = Object.assign({}, iconGen);
for (const p of (packages || "").split(",")) if (p) g[p] = (g[p] || 0) + 1; for (const p of (packages || "").split(",")) if (p) g[p] = (g[p] || 0) + 1;
iconGen = g; iconGen = g;
loadApps(); Host.requestApps();
if (sheet === "app") { sheet = ""; appSheetRow = -1; } if (sheet === "app") { sheet = ""; appSheetRow = -1; }
} }
@@ -400,6 +401,7 @@ Window {
Connections { Connections {
target: Host target: Host
function onAppsChanged(packages) { root.reload(packages) } function onAppsChanged(packages) { root.reload(packages) }
function onAppsLoaded(list) { root.gotApps(list) }
function onHomePressed() { root.goHome() } function onHomePressed() { root.goHome() }
function onBackPressed() { root.back() } function onBackPressed() { root.back() }
function onWidgetAdded(id) { root.widgetAdded(id) } function onWidgetAdded(id) { root.widgetAdded(id) }
@@ -418,11 +420,15 @@ Window {
function onLegacyHome(json) { root.importLegacy(json) } 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: { Component.onCompleted: {
loadHome(); loadHome();
setApps(Host.savedApps()); // icons and names show at once; the real list follows setApps(Host.savedApps()); // icons and names show at once; the real list follows
Host.ready(); Host.ready();
Qt.callLater(loadApps); Host.requestApps();
drawerWarm.start();
} }
// ---- view // ---- view
@@ -783,6 +789,7 @@ Window {
homeSet: root.homeSet homeSet: root.homeSet
loading: root.loading loading: root.loading
iconGen: root.iconGen iconGen: root.iconGen
warm: !drawerWarm.running
insetTop: root.insetTop insetTop: root.insetTop
insetBottom: root.insetBottom insetBottom: root.insetBottom
onEdgeChanged: root.cover() onEdgeChanged: root.cover()
+23
View File
@@ -67,6 +67,13 @@ void jLegacyHome(JNIEnv *env, jclass, jstring json) {
post([=] { emit g_backend->legacyHome(s); }); 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() { void registerNatives() {
static bool done = false; static bool done = false;
if (done) return; if (done) return;
@@ -81,6 +88,7 @@ void registerNatives() {
{"widgetGrab", "(I)V", reinterpret_cast<void *>(jWidgetGrab)}, {"widgetGrab", "(I)V", reinterpret_cast<void *>(jWidgetGrab)},
{"widgetDrag", "(II)V", reinterpret_cast<void *>(jWidgetDrag)}, {"widgetDrag", "(II)V", reinterpret_cast<void *>(jWidgetDrag)},
{"widgetDrop", "(Z)V", reinterpret_cast<void *>(jWidgetDrop)}, {"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)}, {"legacyHome", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jLegacyHome)},
}; };
QJniEnvironment env; QJniEnvironment env;
@@ -149,6 +157,21 @@ QVariantList Backend::apps() const {
return out; 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 { QVariantList Backend::savedApps() const {
return appList(QJsonDocument::fromJson(QSettings().value(QStringLiteral("apps")).toString().toUtf8())); return appList(QJsonDocument::fromJson(QSettings().value(QStringLiteral("apps")).toString().toUtf8()));
} }
+5
View File
@@ -28,6 +28,7 @@ public:
// Lists: [{label, component, system}] and [{label, app, provider, h}]. // Lists: [{label, component, system}] and [{label, app, provider, h}].
Q_INVOKABLE QVariantList apps() const; 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 savedApps() const; // the last list apps() returned, for a quick start
Q_INVOKABLE QVariantList widgetProviders() const; Q_INVOKABLE QVariantList widgetProviders() const;
@@ -66,6 +67,7 @@ public:
signals: signals:
void insetsChanged(); void insetsChanged();
void appsLoaded(const QVariantList &apps);
void appsChanged(const QString &packages); // comma-separated; empty: any void appsChanged(const QString &packages); // comma-separated; empty: any
void homePressed(); void homePressed();
void backPressed(); void backPressed();
@@ -77,6 +79,9 @@ signals:
void legacyHome(const QString &json); // the WebView build's saved home, read once void legacyHome(const QString &json); // the WebView build's saved home, read once
void toast(const QString &text); // desktop stand-in for an action void toast(const QString &text); // desktop stand-in for an action
public:
void takeAppList(const QByteArray &json); // HomeActivity's answer to requestApps
private: private:
qreal dpr() const; qreal dpr() const;
qreal m_insetTop = 0, m_insetBottom = 0; qreal m_insetTop = 0, m_insetBottom = 0;
+11 -6
View File
@@ -4,6 +4,8 @@
#include <QPainter> #include <QPainter>
#include <QUrl> #include <QUrl>
#include <cmath>
#ifdef Q_OS_ANDROID #ifdef Q_OS_ANDROID
#include <QJniEnvironment> #include <QJniEnvironment>
#include <QJniObject> #include <QJniObject>
@@ -17,16 +19,19 @@ QImage IconProvider::requestImage(const QString &id, QSize *size, const QSize &r
const int px = requested.width() > 0 ? requested.width() : 144; const int px = requested.width() > 0 ? requested.width() : 144;
QImage img; QImage img;
#ifdef Q_OS_ANDROID #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", "dev/ultra/launcher/HomeActivity", "icon", "(Ljava/lang/String;I)[B",
QJniObject::fromString(key).object<jstring>(), jint(px)); QJniObject::fromString(key).object<jstring>(), jint(px));
if (png.isValid()) { if (pixels.isValid()) {
QJniEnvironment env; QJniEnvironment env;
auto arr = png.object<jbyteArray>(); auto arr = pixels.object<jbyteArray>();
const jsize n = env->GetArrayLength(arr); const jsize n = env->GetArrayLength(arr);
QByteArray bytes(n, Qt::Uninitialized); const int side = int(std::lround(std::sqrt(n / 4.0)));
env->GetByteArrayRegion(arr, 0, n, reinterpret_cast<jbyte *>(bytes.data())); if (side > 0 && jsize(side) * side * 4 == n) {
img.loadFromData(bytes, "PNG"); img = QImage(side, side, QImage::Format_RGBA8888_Premultiplied);
env->GetByteArrayRegion(arr, 0, n, reinterpret_cast<jbyte *>(img.bits()));
}
} }
#else #else
// A disc in a colour picked from the key, with the name's first letter. // A disc in a colour picked from the key, with the name's first letter.