Reuse Home tiles and Plex artwork to reduce allocation

This commit is contained in:
Elijah Kuntz 2026-10-19 13:19:56 -07:00
parent 5f035d909a
commit ac0a892c5f
14 changed files with 741 additions and 40 deletions

View file

@ -8,4 +8,7 @@
<instrumentation android:name=".NavigationInstrumentation" android:targetPackage="tv.luma.launcher" android:functionalTest="true" />
<instrumentation android:name=".TileRenderingInstrumentation" android:targetPackage="tv.luma.launcher" android:functionalTest="true" />
<instrumentation android:name=".AccentSchedulingInstrumentation" android:targetPackage="tv.luma.launcher" android:functionalTest="true" />
<instrumentation android:name=".WarmReturnInstrumentation" android:targetPackage="tv.luma.launcher" android:functionalTest="true" />
<instrumentation android:name="tv.luma.launcher.PlexArtworkInstrumentation" android:targetPackage="tv.luma.launcher" android:functionalTest="true" />
<instrumentation android:name=".GridReuseInstrumentation" android:targetPackage="tv.luma.launcher" android:functionalTest="true" />
</manifest>

View file

@ -0,0 +1,145 @@
package tv.luma.launcher.tests;
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import java.lang.reflect.*;
import java.util.*;
/**
* Exercises user layout changes and focus callbacks against a reused grid, restoring preferences.
*/
public final class GridReuseInstrumentation extends Instrumentation {
private Activity activity;
private Object get(Object o, String name) throws Exception {
Field f = o.getClass().getDeclaredField(name);
f.setAccessible(true);
return f.get(o);
}
private Map<String, View> tiles() throws Exception {
return new LinkedHashMap<>((Map<String, View>) get(activity, "tiles"));
}
private void render() throws Exception {
Method m = activity.getClass().getDeclaredMethod("renderApps");
m.setAccessible(true);
runOnMainSync(
() -> {
try {
m.invoke(activity);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
Thread.sleep(150);
waitForIdleSync();
}
private void check(boolean value, String message) {
if (!value) throw new AssertionError(message);
}
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
start();
}
@Override
public void onStart() {
Bundle result = new Bundle();
StringBuilder report = new StringBuilder();
int status = Activity.RESULT_OK;
SharedPreferences prefs = getTargetContext().getSharedPreferences("luma", 0);
Map<String, ?> original = new HashMap<>(prefs.getAll());
try {
activity =
startActivitySync(
new Intent(Intent.ACTION_MAIN)
.setComponent(
new ComponentName("tv.luma.launcher", "tv.luma.launcher.MainActivity"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
Thread.sleep(2500);
Map<String, View> before = tiles();
check(before.size() > 2, "insufficient apps");
String first = before.keySet().iterator().next();
prefs.edit().putString("labels", "never").commit();
render();
Map<String, View> after = tiles();
for (String p : before.keySet()) {
check(before.get(p) == after.get(p), "label setting rebuilt tiles");
check(
((View) get(after.get(p), "label")).getVisibility() == View.GONE,
"labels still visible");
}
View last = new ArrayList<>(after.values()).get(after.size() - 1);
runOnMainSync(last::requestFocus);
Thread.sleep(350);
check(
last.getTag().equals(get(activity, "selected")), "reused focus callback lost selection");
// Stop halfway through a focus animation; a reused focused tile must resume at its final
// scale.
runOnMainSync(
() -> {
after.get(first).requestFocus();
callActivityOnPause(activity);
callActivityOnStop(activity);
});
check(
Math.abs(after.get(first).getScaleX() - 1.065f) < .001f,
"interrupted lift left wrong scale");
runOnMainSync(
() -> {
callActivityOnStart(activity);
callActivityOnResume(activity);
});
Thread.sleep(800);
report.append(
"PASS: label updates reuse views; rebound callbacks retain selection; interrupted focus"
+ " lift normalizes\n");
Set<String> hidden = new HashSet<>(prefs.getStringSet("hidden", Collections.emptySet()));
hidden.add(first);
prefs.edit().putStringSet("hidden", hidden).commit();
render();
check(
!tiles().containsKey(first) && tiles().size() == before.size() - 1,
"hidden app remained in reused grid");
List<String> reverse = new ArrayList<>(before.keySet());
Collections.reverse(reverse);
SharedPreferences.Editor edit = prefs.edit().putString("order", String.join(",", reverse));
if (original.containsKey("hidden"))
edit.putStringSet("hidden", new HashSet<>((Set<String>) original.get("hidden")));
else edit.remove("hidden");
edit.commit();
render();
check(new ArrayList<>(tiles().keySet()).equals(reverse), "reordering ignored");
Map<String, View> reordered = tiles();
int cols = prefs.getInt("columns", 6);
prefs.edit().putInt("columns", cols == 6 ? 7 : 6).commit();
render();
check(tiles().get(first) != reordered.get(first), "column change reused stale dimensions");
report.append("PASS: hiding, reordering, and column changes rebuild the correct grid\n");
} catch (Throwable error) {
report.append("FAIL: ").append(error).append('\n');
status = Activity.RESULT_CANCELED;
} finally {
SharedPreferences.Editor edit = prefs.edit();
for (String k : new String[] {"labels", "hidden", "order", "columns"}) {
Object v = original.get(k);
if (!original.containsKey(k)) edit.remove(k);
else if (v instanceof String) edit.putString(k, (String) v);
else if (v instanceof Integer) edit.putInt(k, (Integer) v);
else edit.putStringSet(k, new HashSet<>((Set<String>) v));
}
if (!edit.commit()) {
status = Activity.RESULT_CANCELED;
report.append("FAIL: preferences not restored\n");
} else report.append("PASS: original layout preferences restored\n");
}
result.putString("stream", report.toString());
finish(status, result);
}
}

View file

@ -0,0 +1,322 @@
package tv.luma.launcher;
import android.app.*;
import android.content.*;
import android.content.pm.*;
import android.os.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
/** On-device loopback fixture; preserves credentials without printing them or needing a network. */
public final class PlexArtworkInstrumentation extends Instrumentation {
private Activity activity;
private SceneView scene;
private boolean optimized;
private final StringBuilder report = new StringBuilder();
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
optimized = b != null && "true".equals(b.getString("optimized"));
start();
}
private Object get(Object target, String name) throws Exception {
Field f = target.getClass().getDeclaredField(name);
f.setAccessible(true);
return f.get(target);
}
private void invoke(String name, Class<?> type, Object value) throws Exception {
Method method = activity.getClass().getDeclaredMethod(name, type);
method.setAccessible(true);
runOnMainSync(
() -> {
try {
method.invoke(activity, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
private void settle() throws Exception {
Thread.sleep(650);
waitForIdleSync();
}
private void awaitArt() throws Exception {
long until = SystemClock.uptimeMillis() + 6000;
while (SystemClock.uptimeMillis() < until) {
boolean[] ready = {false};
runOnMainSync(() -> ready[0] = scene.hasMediaArt());
if (ready[0]) {
settle();
return;
}
Thread.sleep(10);
}
throw new AssertionError("fixture artwork did not load");
}
private void awaitPath(String path) throws Exception {
long until = SystemClock.uptimeMillis() + 6000;
while (SystemClock.uptimeMillis() < until) {
boolean[] ready = {false};
runOnMainSync(
() -> {
try {
ready[0] =
get(activity, "requestedArtPath").equals("")
&& (path == null
|| (scene.hasMediaArt()
&& path.equals(get(activity, "displayedArtPath"))));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
if (ready[0]) {
settle();
return;
}
Thread.sleep(10);
}
throw new AssertionError("artwork request did not settle");
}
private static void restore(SharedPreferences prefs, Map<String, ?> values) {
SharedPreferences.Editor edit = prefs.edit().clear();
for (Map.Entry<String, ?> entry : values.entrySet()) {
Object v = entry.getValue();
String k = entry.getKey();
if (v instanceof String) edit.putString(k, (String) v);
else if (v instanceof Boolean) edit.putBoolean(k, (Boolean) v);
else if (v instanceof Integer) edit.putInt(k, (Integer) v);
else if (v instanceof Long) edit.putLong(k, (Long) v);
else if (v instanceof Float) edit.putFloat(k, (Float) v);
else if (v instanceof Set) edit.putStringSet(k, new HashSet<>((Set<String>) v));
else throw new AssertionError("unexpected preference type");
}
if (!edit.commit()) throw new AssertionError("preferences not restored");
}
private AppRepository.App fixtureApp(String pkg) {
ResolveInfo info = new ResolveInfo();
info.activityInfo = new ActivityInfo();
info.activityInfo.applicationInfo = new ApplicationInfo();
info.activityInfo.packageName = pkg;
info.activityInfo.name = pkg + ".Main";
info.nonLocalizedLabel = "Fixture app";
return new AppRepository.App(info, getTargetContext().getPackageManager());
}
private final class Fixture implements AutoCloseable {
private final ServerSocket server = new ServerSocket(0, 4, InetAddress.getByName("127.0.0.1"));
private final Thread thread;
private final byte[] image;
Fixture() throws Exception {
try (InputStream in = getTargetContext().getAssets().open("alpine.jpg");
ByteArrayOutputStream data = new ByteArrayOutputStream()) {
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) != -1) data.write(buffer, 0, count);
image = data.toByteArray();
}
thread =
new Thread(
() -> {
while (!server.isClosed()) {
try (Socket socket = server.accept()) {
socket.setSoTimeout(3000);
BufferedReader input =
new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
String first = input.readLine(), header;
int bytes = 0;
boolean authenticated = false;
if (first == null) continue;
while ((header = input.readLine()) != null && !header.isEmpty()) {
if ((bytes += header.length()) > 16384)
throw new IOException("oversized fixture request");
if (header.equalsIgnoreCase("X-Plex-Token: luma-test-fixture"))
authenticated = true;
}
int status = !authenticated ? 401 : first.contains("failure") ? 404 : 200;
boolean photo = first.startsWith("GET /photo/");
byte[] body =
status != 200
? new byte[0]
: photo
? image
: "{\"MediaContainer\":{\"machineIdentifier\":\"luma-local-fixture\"}}"
.getBytes(StandardCharsets.UTF_8);
OutputStream out = socket.getOutputStream();
out.write(
("HTTP/1.1 "
+ status
+ " Fixture\r\nContent-Type: "
+ (photo ? "image/jpeg" : "application/json")
+ "\r\nContent-Length: "
+ body.length
+ "\r\nConnection: close\r\n\r\n")
.getBytes(StandardCharsets.UTF_8));
out.write(body);
out.flush();
} catch (IOException ignored) {
/* close() interrupts accept; client may cancel a request. */
}
}
},
"plex-artwork-fixture");
thread.start();
}
String url() {
return "http://127.0.0.1:" + server.getLocalPort();
}
@Override
public void close() throws IOException {
server.close();
thread.interrupt();
}
}
@Override
public void onStart() {
Bundle result = new Bundle();
SharedPreferences credentials = getTargetContext().getSharedPreferences("plex", 0);
SharedPreferences prefs = getTargetContext().getSharedPreferences("luma", 0);
Map<String, ?> saved = new HashMap<>(credentials.getAll());
boolean hadMedia = prefs.contains("media"), media = prefs.getBoolean("media", false);
int status = Activity.RESULT_OK;
Fixture fixture = null;
try {
fixture = new Fixture();
if (!prefs.edit().putBoolean("media", false).commit())
throw new AssertionError("test setting");
activity =
startActivitySync(
new Intent(Intent.ACTION_MAIN)
.setComponent(
new ComponentName("tv.luma.launcher", "tv.luma.launcher.MainActivity"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
Thread.sleep(2200);
scene = (SceneView) get(activity, "scene");
PlexClient plex = (PlexClient) get(activity, "plex");
plex.connect(fixture.url(), "luma-test-fixture");
PlexClient.Media featured = new PlexClient.Media();
featured.art = "/library/art/alpine";
Field field = activity.getClass().getDeclaredField("plexFeatured");
field.setAccessible(true);
runOnMainSync(
() -> {
try {
field.set(activity, featured);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
AppRepository.App app = fixtureApp("com.plexapp.android");
invoke("updateHero", AppRepository.App.class, app);
awaitArt();
int generation = (int) get(scene, "generation");
Object frame = get(scene, "frame"), art = get(scene, "mediaArt");
for (int i = 0; i < 4; i++) {
invoke("updateHero", AppRepository.App.class, app);
settle();
}
int extra = (int) get(scene, "generation") - generation;
report
.append("duplicateSelections=4 extraSceneCompositions=")
.append(extra)
.append(" frameReused=")
.append(frame == get(scene, "frame"))
.append(" artworkReused=")
.append(art == get(scene, "mediaArt"))
.append('\n');
if (optimized) {
if (extra != 0 || frame != get(scene, "frame"))
throw new AssertionError("duplicate recomposition");
invoke("updateHero", AppRepository.App.class, fixtureApp("com.edde746.plezy"));
settle();
if (get(scene, "frame") != frame) throw new AssertionError("shared Plex artwork rebuilt");
report.append("PASS: Plex/Plezy retain unchanged frame and artwork\n");
invoke("featureArtwork", String.class, "/library/art/obsolete");
Thread.sleep(50);
invoke("featureArtwork", String.class, "/library/art/latest");
awaitPath("/library/art/latest");
if (!"/library/art/latest".equals(get(activity, "displayedArtPath")))
throw new AssertionError("latest artwork request lost");
art = get(scene, "mediaArt");
invoke("featureArtwork", String.class, "/library/art/failure");
awaitPath(null);
if (get(scene, "mediaArt") != art)
throw new AssertionError("failed image cleared valid art");
invoke("featureArtwork", String.class, "/library/art/after-pause");
runOnMainSync(() -> callActivityOnPause(activity));
settle();
if (get(scene, "mediaArt") != art || !(get(activity, "requestedArtPath").equals("")))
throw new AssertionError("pending artwork escaped pause");
android.view.View focused = activity.getCurrentFocus();
Object originalTag = focused.getTag();
PlexClient.Media pending = new PlexClient.Media();
pending.art = "/library/art/after-pause";
runOnMainSync(
() -> {
focused.setTag(pending);
callActivityOnResume(activity);
});
awaitPath("/library/art/after-pause");
runOnMainSync(() -> focused.setTag(originalTag));
if (!"/library/art/after-pause".equals(get(activity, "displayedArtPath")))
throw new AssertionError("pause did not permit retry");
invoke("featureArtwork", String.class, "/library/art/stale");
invoke("updateHero", AppRepository.App.class, fixtureApp("com.netflix.ninja"));
settle();
if (scene.hasMediaArt() || !get(activity, "requestedArtPath").equals(""))
throw new AssertionError("non-Plex selection accepted stale image");
runOnMainSync(
() -> {
callActivityOnPause(activity);
callActivityOnStop(activity);
});
if (scene.hasMediaArt() || get(scene, "frame") != null)
throw new AssertionError("stop retained images");
runOnMainSync(
() -> {
callActivityOnStart(activity);
callActivityOnResume(activity);
});
invoke("featureArtwork", String.class, "/library/art/alpine");
awaitPath("/library/art/alpine");
report.append(
"PASS: latest request wins; failed image retains art; pause cancels and permits retry;"
+ " stale completion rejected; stop releases and restores images\n");
}
} catch (Throwable error) {
report.append("FAIL: ").append(error).append('\n');
status = Activity.RESULT_CANCELED;
} finally {
try {
if (fixture != null) fixture.close();
if (activity != null) runOnMainSync(() -> callActivityOnPause(activity));
restore(credentials, saved);
SharedPreferences.Editor edit = prefs.edit();
if (hadMedia) edit.putBoolean("media", media);
else edit.remove("media");
if (!edit.commit()) throw new AssertionError("media setting not restored");
report.append("PASS: original Plex credentials and media preference restored\n");
} catch (Throwable error) {
report.append("FAIL: preference restoration\n");
status = Activity.RESULT_CANCELED;
}
}
result.putString("stream", report.toString());
finish(status, result);
}
}

View file

@ -0,0 +1,126 @@
package tv.luma.launcher.tests;
import android.app.*;
import android.content.*;
import android.graphics.Bitmap;
import android.os.*;
import java.lang.reflect.*;
import java.util.*;
/** Measures complete stop/start image recovery, including Java allocation and view reuse. */
public final class WarmReturnInstrumentation extends Instrumentation {
private Activity activity;
private Object get(Object o, String name) throws Exception {
Field f = o.getClass().getDeclaredField(name);
f.setAccessible(true);
return f.get(o);
}
private void awaitImages() throws Exception {
long until = SystemClock.uptimeMillis() + 8000;
boolean[] ready = {false};
while (SystemClock.uptimeMillis() < until) {
runOnMainSync(
() -> {
try {
Map<?, ?> tiles = (Map<?, ?>) get(activity, "tiles");
ready[0] =
!tiles.isEmpty()
&& !(boolean) get(activity, "appsNeedRefresh")
&& get(get(activity, "scene"), "frame") != null;
for (Object tile : tiles.values()) {
Bitmap b = (Bitmap) get(get(tile, "art"), "bitmap");
ready[0] &= b != null && !b.isRecycled();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
});
if (ready[0]) {
waitForIdleSync();
return;
}
Thread.sleep(5);
}
throw new AssertionError("images not restored");
}
private long allocated() {
return Long.parseLong(Debug.getRuntimeStat("art.gc.bytes-allocated"));
}
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
start();
}
@Override
public void onStart() {
Bundle result = new Bundle();
StringBuilder report = new StringBuilder();
try {
activity =
startActivitySync(
new Intent(Intent.ACTION_MAIN)
.setComponent(
new ComponentName("tv.luma.launcher", "tv.luma.launcher.MainActivity"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
awaitImages();
Thread.sleep(600);
List<Long> elapsed = new ArrayList<>(), allocations = new ArrayList<>();
for (int round = 0; round < 8; round++) {
Map<?, ?> before = new LinkedHashMap<>((Map<?, ?>) get(activity, "tiles"));
runOnMainSync(
() -> {
callActivityOnPause(activity);
callActivityOnStop(activity);
});
long bytes = allocated(), start = SystemClock.elapsedRealtimeNanos();
runOnMainSync(
() -> {
callActivityOnRestart(activity);
callActivityOnStart(activity);
callActivityOnResume(activity);
});
awaitImages();
long ms = (SystemClock.elapsedRealtimeNanos() - start) / 1000000;
long used = allocated() - bytes;
Map<?, ?> after = (Map<?, ?>) get(activity, "tiles");
int reused = 0;
for (Object key : before.keySet()) if (before.get(key) == after.get(key)) reused++;
if (round >= 2) {
elapsed.add(ms);
allocations.add(used);
}
report
.append("cycle=")
.append(round)
.append(" readyMs=")
.append(ms)
.append(" javaAllocatedBytes=")
.append(used)
.append(" reusedTiles=")
.append(reused)
.append('/')
.append(after.size())
.append('\n');
Thread.sleep(350);
}
Collections.sort(elapsed);
Collections.sort(allocations);
report
.append("medianReadyMs=")
.append(elapsed.get(elapsed.size() / 2))
.append(" medianJavaAllocatedBytes=")
.append(allocations.get(allocations.size() / 2))
.append("\nPASS: eight complete warm returns restored all images\n");
result.putString("stream", report.toString());
finish(Activity.RESULT_OK, result);
} catch (Throwable t) {
result.putString("stream", report + "FAIL: " + t + "\n");
finish(Activity.RESULT_CANCELED, result);
}
}
}