Launcher: deliver icons through the bridge instead of intercepted image requests

Icons loaded as <img src="icon?c=..."> through shouldInterceptRequest
kept failing on a real phone for the first screenful of apps and for
every widget, even with retries. The page now asks the shell for icons
by key (Android.loadIcons); the shell draws them on one background
thread and returns them in batches of data: URIs via ultraIcons(). An
icon that can't be drawn shows as a blank disc.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019EEjkJVV72Lu8ndDVWg5BT
This commit is contained in:
Claude committed 2026-10-21 19:01:50 +00:00
1 parent d34b753434
commit a52108e95f
4 files changed
+75 -17

No files matched your search

@@ -25,6 +25,7 @@ import android.os.Process;
import android.os.UserHandle; import android.os.UserHandle;
import android.provider.Settings; import android.provider.Settings;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log; import android.util.Log;
import android.view.HapticFeedbackConstants; import android.view.HapticFeedbackConstants;
import android.view.MotionEvent; import android.view.MotionEvent;
@@ -57,6 +58,8 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; 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 examples/launcher (LPython compiled * The home screen activity. The UI is the ultra app in examples/launcher (LPython compiled
@@ -96,6 +99,7 @@ public class MainActivity extends Activity {
private final UserHandle user = Process.myUserHandle(); private final UserHandle user = Process.myUserHandle();
private final Map<String, byte[]> icons = new ConcurrentHashMap<>(); private final Map<String, byte[]> icons = new ConcurrentHashMap<>();
private final Handler main = new Handler(Looper.getMainLooper()); private final Handler main = new Handler(Looper.getMainLooper());
private final ExecutorService iconThread = Executors.newSingleThreadExecutor();
private final LauncherApps.Callback packages = new LauncherApps.Callback() { private final LauncherApps.Callback packages = new LauncherApps.Callback() {
@Override public void onPackageRemoved(String pkg, UserHandle u) { reload(); } @Override public void onPackageRemoved(String pkg, UserHandle u) { reload(); }
@@ -180,6 +184,7 @@ public class MainActivity extends Activity {
@Override @Override
protected void onDestroy() { protected void onDestroy() {
launcher.unregisterCallback(packages); launcher.unregisterCallback(packages);
iconThread.shutdownNow();
web.destroy(); web.destroy();
super.onDestroy(); super.onDestroy();
} }
@@ -217,9 +222,45 @@ public class MainActivity extends Activity {
private void reload() { private void reload() {
icons.clear(); icons.clear();
js("resetIcons()");
js("reload()"); 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 // ------------------------------------------------------------ apps
private String appsJson() throws JSONException { private String appsJson() throws JSONException {
@@ -551,6 +592,10 @@ public class MainActivity extends Activity {
main.post(() -> MainActivity.this.placeWidgets(json)); main.post(() -> MainActivity.this.placeWidgets(json));
} }
@JavascriptInterface public void loadIcons(String keys) {
MainActivity.this.loadIcons(keys);
}
@JavascriptInterface public void haptic() { @JavascriptInterface public void haptic() {
main.post(() -> web.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, main.post(() -> web.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING)); HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING));
+1 -1
View File
@@ -489,7 +489,7 @@ def view_icon(h: i32) -> None:
cls("icon") cls("icon")
attr("alt", "") attr("alt", "")
attr("draggable", "false") attr("draggable", "false")
attr_ref("src", h) attr_ref("data-icon", h) # index.html turns this into a src
end() end()
BIN
View File
Binary file not shown.
+29 -16
View File
@@ -54,8 +54,34 @@
if (j !== placed) { placed = j; host.placeWidgets(j); } if (j !== placed) { placed = j; host.placeWidgets(j); }
}; };
// 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])));
};
const gotIcons = (batch) => {
for (const k in batch) { iconSrc.set(k, batch[k]); asked.delete(k); }
fillIcons();
};
window.ultraIcons = gotIcons; // the shell calls this before ultraHome exists, too
const app = await mount("#app", "./app.wasm", { const app = await mount("#app", "./app.wasm", {
onRender: place, onRender: () => { fillIcons(); place(); },
imports: ({ strs }) => ({ imports: ({ strs }) => ({
launch: (h) => host.launch(strs[h]), launch: (h) => host.launch(strs[h]),
app_info: (h) => host.appInfo(strs[h]), app_info: (h) => host.appInfo(strs[h]),
@@ -80,22 +106,9 @@
widgetAdded: (id) => app.dispatch(WIDGET_ADDED, id), widgetAdded: (id) => app.dispatch(WIDGET_ADDED, id),
widgetMenu: (id) => app.dispatch(WIDGET_MENU, id), widgetMenu: (id) => app.dispatch(WIDGET_MENU, id),
place: () => { placed = ""; place(); }, place: () => { placed = ""; place(); },
resetIcons: () => { iconSrc.clear(); asked.clear();
for (const img of document.querySelectorAll("img.icon")) img.__icon = undefined; },
}; };
// An icon that fails to load is retried twice with backoff, then drawn as a blank
// disc instead of the browser's broken-image box.
document.addEventListener("error", (e) => {
const img = e.target;
if (!(img instanceof HTMLImageElement) || !img.classList.contains("icon")) return;
const n = (img.__retries = (img.__retries || 0) + 1);
if (n > 2) { img.classList.add("missing"); return; }
setTimeout(() => {
const base = img.getAttribute("src").replace(/[?&]retry=\d+$/, "");
img.src = base + (base.includes("?") ? "&" : "?") + "retry=" + n;
}, 300 * n);
}, true);
document.addEventListener("load", (e) => {
if (e.target instanceof HTMLImageElement) e.target.classList.remove("missing");
}, true);
document.addEventListener("visibilitychange", () => { if (!document.hidden) window.ultraHome.tick(); }); document.addEventListener("visibilitychange", () => { if (!document.hidden) window.ultraHome.tick(); });
addEventListener("scroll", () => requestAnimationFrame(place), { passive: true }); addEventListener("scroll", () => requestAnimationFrame(place), { passive: true });
addEventListener("resize", () => requestAnimationFrame(place)); addEventListener("resize", () => requestAnimationFrame(place));