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

@ -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);
}
}