diff --git a/README.md b/README.md index ddd7d21..2e86bf8 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@ # Luma for Android TV -A native, remote-first launcher built for the onn. 4K Plus Streaming device (Android 14, 2 GB RAM). It is installed alongside Projectivy as `tv.luma.launcher`. Home now opens Luma; Projectivy remains installed and enabled as a fallback. +A native, remote-first Android TV launcher designed for limited-memory streamers and integrated TVs. It is installed alongside Projectivy as `tv.luma.launcher`; Projectivy remains available as a fallback. -Version **1.1.5** adds updates directly from the TV and includes the wake fix introduced in 1.0.1. Every resume restores missing images, including when Android briefly pauses the launcher without stopping it. Already-loaded tiles and images are kept on pause-only resumes; leaving the launcher still releases image memory. +Version **1.1.11** reuses unchanged app tiles when returning Home and avoids reloading already displayed Plex artwork. Every resume restores missing images, including when Android briefly pauses the launcher without stopping it. Leaving the launcher releases image memory. Updates can be installed directly from the TV; physical-input controls appear on compatible TVs. ## Use it -Press **Home**, or open **Luma** from Projectivy's app list. It can also be opened with: +Press **Home**, or open **Luma** from Projectivy's app list. Set `LUMA_ADB_DEVICE` to your connected ADB device address to open it from a computer: ```sh -.tools/platform-tools/adb -s 192.168.50.195:35635 shell am start -n tv.luma.launcher/.MainActivity +.tools/platform-tools/adb -s "$LUMA_ADB_DEVICE" shell am start -n tv.luma.launcher/.MainActivity ``` - D-pad navigates the installed app grid; OK opens an app. diff --git a/app/build.gradle b/app/build.gradle index 14fd91d..d03f1ba 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -6,8 +6,8 @@ android { applicationId 'tv.luma.launcher' minSdk 26 targetSdk 34 - versionCode 13 - versionName '1.1.10' + versionCode 14 + versionName '1.1.11' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8; targetCompatibility JavaVersion.VERSION_1_8 } } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 5205a5d..dd99523 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,4 +1,4 @@ - + diff --git a/app/src/main/java/tv/luma/launcher/AppTile.java b/app/src/main/java/tv/luma/launcher/AppTile.java index 4b8ddf7..21657a9 100644 --- a/app/src/main/java/tv/luma/launcher/AppTile.java +++ b/app/src/main/java/tv/luma/launcher/AppTile.java @@ -128,6 +128,8 @@ final class AppTile extends LinearLayout { art.animate().cancel(); if (shadowAnimation != null) shadowAnimation.cancel(); shadowAmount = hasFocus() ? 1 : 0; + setScaleX(hasFocus() ? 1.065f : 1f); + setScaleY(hasFocus() ? 1.065f : 1f); } void bitmap(Bitmap b) { diff --git a/app/src/main/java/tv/luma/launcher/MainActivity.java b/app/src/main/java/tv/luma/launcher/MainActivity.java index e0e7061..f864080 100644 --- a/app/src/main/java/tv/luma/launcher/MainActivity.java +++ b/app/src/main/java/tv/luma/launcher/MainActivity.java @@ -38,9 +38,12 @@ public final class MainActivity extends Activity { private volatile int generation = 0; private volatile int iconGeneration = 0; private volatile int artGeneration = 0; + private String displayedArtPath = "", requestedArtPath = ""; + private Runnable artworkTask; private int rotation = 0; private volatile boolean foreground = false; private boolean appsNeedRefresh = true; + private int gridColumns, gridWidth; private boolean moving = false; private volatile Dialog currentDialog; private PlexClient plex; @@ -296,7 +299,7 @@ public final class MainActivity extends Activity { } private void keepFocusVisible(View focused) { - if (!focused.hasFocus() || content == null) return; + if (!foreground || !focused.hasFocus() || content == null) return; Rect bounds = new Rect(); focused.getDrawingRect(bounds); content.offsetDescendantRectToMyCoords(focused, bounds); @@ -368,7 +371,7 @@ public final class MainActivity extends Activity { handler.removeCallbacks(refreshInputTask); inputGeneration++; generation++; - artGeneration++; + cancelArtworkRequest(); work.getQueue().clear(); network.getQueue().clear(); handler.removeCallbacks(minuteTick); @@ -398,7 +401,7 @@ public final class MainActivity extends Activity { super.onStop(); generation++; appsNeedRefresh = true; - artGeneration++; + cancelArtworkRequest(); work.getQueue().clear(); network.getQueue().clear(); repository.icons.evictAll(); @@ -480,12 +483,10 @@ public final class MainActivity extends Activity { if (!tile.hasImage() && tile.getTag() instanceof PlexClient.Media) loadMediaThumbnail(tile, (PlexClient.Media) tile.getTag(), g); } - if (!scene.hasMediaArt()) { - View focused = getCurrentFocus(); - if (focused != null && focused.getTag() instanceof PlexClient.Media) - featureArtwork(((PlexClient.Media) focused.getTag()).art); - else if (selected.contains("plex") || selected.contains("plezy")) featurePlexArtwork(); - } + View focused = getCurrentFocus(); + if (focused != null && focused.getTag() instanceof PlexClient.Media) + featureArtwork(((PlexClient.Media) focused.getTag()).art); + else if (selected.contains("plex") || selected.contains("plezy")) featurePlexArtwork(); } private int columns() { @@ -503,6 +504,7 @@ public final class MainActivity extends Activity { private void renderApps() { iconGeneration++; + List previous = new ArrayList<>(visibleApps); Set hidden = hidden(); List order = savedOrder(); List defaults = @@ -528,32 +530,55 @@ public final class MainActivity extends Activity { if (bi < 0) bi = 1000 + (defaults.contains(b.pkg) ? defaults.indexOf(b.pkg) : 100); return ai == bi ? a.label.compareToIgnoreCase(b.label) : Integer.compare(ai, bi); }); - appsContainer.removeAllViews(); - tiles.clear(); int cols = columns(); int screen = (int) (getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().density); int width = (screen - 102) / cols; + boolean reuse = + gridColumns == cols + && gridWidth == width + && previous.size() == visibleApps.size() + && tiles.size() == visibleApps.size(); + for (int i = 0; reuse && i < previous.size(); i++) { + AppRepository.App old = previous.get(i), current = visibleApps.get(i); + reuse = + old.pkg.equals(current.pkg) + && old.label.equals(current.label) + && old.component.equals(current.component) + && Objects.equals( + old.info.activityInfo.applicationInfo.sourceDir, + current.info.activityInfo.applicationInfo.sourceDir); + } + if (!reuse) { + appsContainer.removeAllViews(); + tiles.clear(); + } + gridColumns = cols; + gridWidth = width; LinearLayout row = null; int index = 0; for (AppRepository.App app : visibleApps) { - if (index % cols == 0) { + if (!reuse && index % cols == 0) { row = new LinearLayout(this); row.setClipChildren(false); row.setClipToPadding(false); appsContainer.addView(row, new LinearLayout.LayoutParams(-1, -2)); } - AppTile tile = new AppTile(this, app.label, width, cols > 6); - tile.setId(View.generateViewId()); + AppTile tile; + if (reuse) tile = tiles.get(app.pkg); + else { + tile = new AppTile(this, app.label, width, cols > 6); + tile.setId(View.generateViewId()); + row.addView(tile, new LinearLayout.LayoutParams(d(width), -2)); + tiles.put(app.pkg, tile); + } tile.setTag(app.pkg); tile.setMotion(motion()); tile.setLabelMode(prefs.getString("labels", "focused")); tile.setAccent(AppRepository.color(app.pkg)); if (index < cols) tile.setNextFocusUpId(settingsButton.getId()); - row.addView(tile, new LinearLayout.LayoutParams(d(width), -2)); - tiles.put(app.pkg, tile); tile.onFocused( f -> { if (f) { @@ -569,7 +594,7 @@ public final class MainActivity extends Activity { }); index++; } - if (visibleApps.isEmpty()) { + if (!reuse && visibleApps.isEmpty()) { TextView empty = chip("No visible apps · Open all apps", v -> showAllApps()); appsContainer.addView(empty, new LinearLayout.LayoutParams(-1, d(70))); } @@ -586,6 +611,7 @@ public final class MainActivity extends Activity { if (target != null) { target.requestFocus(); updateHero(findApp(restore)); + if (reuse) target.post(() -> keepFocusVisible(target)); } reloadIcons(); } @@ -607,7 +633,10 @@ public final class MainActivity extends Activity { Bitmap b = repository.icon(a); handler.post( () -> { - if (foreground && g == generation && tiles.get(a.pkg) == t) t.bitmap(b); + if (foreground + && g == generation + && ig == iconGeneration + && tiles.get(a.pkg) == t) t.bitmap(b); }); }); } @@ -615,9 +644,9 @@ public final class MainActivity extends Activity { private void updateHero(AppRepository.App a) { if (a == null) return; - artGeneration++; - scene.setMediaArt(null); String p = a.pkg; + boolean plexApp = p.contains("plex") || p.contains("plezy"); + if (!plexApp || plexFeatured == null) clearFeaturedArtwork(); String title = a.label; String body = "Your next favorite moment is one click away."; String tag = "READY WHEN YOU ARE"; @@ -657,7 +686,7 @@ public final class MainActivity extends Activity { int accent = prefs.getInt("accent", 0); scene.accent(accent == 0 ? AppRepository.color(a.pkg) : accent, motion()); updateFeaturedText(); - if ((p.contains("plex") || p.contains("plezy")) && plexFeatured != null) featurePlexArtwork(); + if (plexApp && plexFeatured != null) featurePlexArtwork(); } private void launch(AppRepository.App a) { @@ -1448,7 +1477,7 @@ public final class MainActivity extends Activity { null, () -> { prefs.edit().putString("scene", v).apply(); - scene.setMediaArt(null); + clearFeaturedArtwork(); configureScene(); appearance(); }); @@ -1642,7 +1671,7 @@ public final class MainActivity extends Activity { () -> { plex.disconnect(); plexFeatured = null; - scene.setMediaArt(null); + clearFeaturedArtwork(); prefs.edit().putBoolean("media", false).apply(); mediaContainer.removeAllViews(); plexSettings(); @@ -1689,6 +1718,8 @@ public final class MainActivity extends Activity { handler.post( () -> { if (currentDialog != dialog || !foreground) return; + clearFeaturedArtwork(); + plexFeatured = null; prefs.edit().putBoolean("media", true).apply(); dismiss(); loadMedia(); @@ -1782,6 +1813,8 @@ public final class MainActivity extends Activity { handler.post( () -> { if (currentDialog != dialog || !foreground) return; + clearFeaturedArtwork(); + plexFeatured = null; prefs.edit().putBoolean("media", true).apply(); dismiss(); loadMedia(); @@ -1897,10 +1930,37 @@ public final class MainActivity extends Activity { featureArtwork(plexFeatured.art); } + private void cancelArtworkRequest() { + artGeneration++; + if (artworkTask != null) handler.removeCallbacks(artworkTask); + artworkTask = null; + requestedArtPath = ""; + } + + private void clearFeaturedArtwork() { + cancelArtworkRequest(); + displayedArtPath = ""; + scene.setMediaArt(null); + } + private void featureArtwork(String path) { - final int g = generation, art = ++artGeneration; - handler.postDelayed( + if (!foreground) return; + if (path == null || path.isEmpty()) { + clearFeaturedArtwork(); + return; + } + if (path.equals(displayedArtPath) && scene.hasMediaArt()) { + // Cancel a different pending selection without clearing an already displayed image. + if (!requestedArtPath.isEmpty()) cancelArtworkRequest(); + return; + } + if (path.equals(requestedArtPath)) return; + cancelArtworkRequest(); + requestedArtPath = path; + final int g = generation, art = artGeneration; + artworkTask = () -> { + artworkTask = null; if (!foreground || g != generation || art != artGeneration) return; network.execute( () -> { @@ -1908,12 +1968,16 @@ public final class MainActivity extends Activity { Bitmap bitmap = plex.image(path, true); handler.post( () -> { - if (foreground && g == generation && art == artGeneration) + if (!foreground || g != generation || art != artGeneration) return; + requestedArtPath = ""; + if (bitmap != null) { + displayedArtPath = path; scene.setMediaArt(bitmap); + } }); }); - }, - 180); + }; + handler.postDelayed(artworkTask, 180); } @Override diff --git a/docs/UPDATE_NOTES.md b/docs/UPDATE_NOTES.md index 957b13b..ecdf249 100644 --- a/docs/UPDATE_NOTES.md +++ b/docs/UPDATE_NOTES.md @@ -1 +1 @@ -Adds a TV-input button beside Settings on devices that expose physical inputs. Choose an HDMI or other supported input with the remote. The button stays hidden on streamers without inputs. Detects Android capabilities automatically, with no device-specific configuration. +Reduces allocation when returning Home by reusing unchanged app tiles. Reuses Plex artwork that is already displayed and avoids redundant background rebuilds. Keeps the previous artwork while a replacement loads, cancels obsolete requests, and restores interrupted artwork loads after resume. Layout, image quality, and device-independent rendering defaults are unchanged. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 37f6a4d..26ffb7f 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -180,3 +180,42 @@ The platform interfaces are documented in [TvInputManager](https://developer.and Final 1.1.10 package/version checks passed on both devices, with the input button visible only on the TV. After settling with Android settings foreground, both UIs and the onn Home helper consumed zero CPU ticks over five seconds. The diagnostic APKs and temporary on-device files were removed. The onn's original Home/accessibility service list was restored after instrumentation; Home returned from Android settings, and Back stayed in Luma. The TV's existing Home override remains off. Projectivy remains installed/enabled on both devices, and both devices were returned to Luma. Raw local checks are in ignored `output/performance/input-switching/`. + +## Warm Home returns and Plex artwork reuse — October 19, 2026 + +Version 1.1.11 keeps two reductions in unnecessary work, with the same defaults and rendering implementation on both devices: + +- Reuse the app grid when its ordered packages, labels, launch components, APK source paths, column count, and tile widths are unchanged. Rediscover installed apps and rebind listeners to the new models. Layout changes rebuild the grid; icon completions check the current binding generation. A paused focus animation is normalized before reuse. +- Reuse an already displayed Plex image and composed scene for the same artwork path, including Plex/Plezy selections sharing that artwork. Keep the previous image while a different one loads; a failed replacement retains that image. Coalesce identical pending requests, cancel obsolete delayed callbacks, reject stale completions, and retry the focused artwork after resume. Changing the Plex connection or selecting another app clears the previous source appropriately. + +Images and image caches are still released on stop. Retained views already existed while backgrounded before this change; this avoids replacing them on return rather than retaining additional bitmap memory. Image resolution, layout, animation timing, and the optional Memory saver default are unchanged. There are no device/model/manufacturer/IP branches. + +`WarmReturnInstrumentation` invokes eight complete pause/stop/start/resume cycles, waiting for all app icons and the scene to be present. The first two cycles are excluded from the medians below. Allocation is the target process's ART Java allocated-byte counter during resume-to-image-ready, including concurrent target-process work. This is a controlled lifecycle workload, not physical app-switch latency, peak RAM, or a GPU allocation measurement. + +| Device | 1.1.10 Java bytes per return | 1.1.11 Java bytes per return | Reduction | Image-ready median, before → after | +| --- | ---: | ---: | ---: | ---: | +| onn, 21 app tiles | 344,776 | 197,320 | 42.8% | 182 → 181 ms | +| Integrated TV, 14 app tiles | 295,816 | 197,512 | 33.2% | 167 → 165 ms | + +All tiles were reused in every candidate cycle. Image-ready times are effectively unchanged; the demonstrated benefit is less Java allocation and view construction. A prior candidate run gave 184 ms on the onn and 165 ms on the TV, consistent with that interpretation. + +Four repeated selections of the same featured Plex app produced eight extra scene compositions on 1.1.10 on each device. The candidate produces zero, retaining both the same artwork bitmap and the same finished background frame. `PlexArtworkInstrumentation` uses an authenticated loopback-only HTTP fixture running inside the test process, with the bundled wallpaper as fixture artwork. It requires no home Plex server or network connection. Original encrypted credential preferences and the media-row setting are restored in finally; no real credential values are printed. Earlier host-forwarded fixture attempts were interrupted by the TV's intermittent ADB connection, so the final fixture runs on-device. + +`GridReuseInstrumentation` verifies label changes retain views, rebound focus callbacks retain selection, interrupted focus lifts finish at the correct scale, and hiding/reordering/changing columns produces the correct grid. Layout preferences are restored after testing. The complete wake suite passes with default rendering and Memory saver on both devices, including partial/interrupted loads, pause-only image reuse, memory trimming, screensaver dismissal, five stop/start cycles, runtime renderer switching, and removal of TV-input listeners while paused. + +An exact-pixel background damage experiment was rejected: the bounding rectangle of changed RGB pixels still covered 93.1–97.6% of the screen across tested accent pairs, while scanning the bounded 960 × 540 image cost roughly 12–14 ms after warmup. No clipping or image-quality approximation was added to the launcher. The already rejected custom GPU shader from the earlier round remains absent. + +The final signed-build comparison reinstalls 1.1.10, runs the native 42-key normal/rapid navigation workload, installs 1.1.11, and repeats it. The device runs the script locally so ADB connection interruptions do not interrupt the measurements: + +| Device / pace | 1.1.10 median / p90 | 1.1.11 median / p90 | Missed deadlines, before → after | +| --- | ---: | ---: | ---: | +| onn, normal | 10.44 / 13.35 ms | 10.25 / 13.61 ms | 14/740 → 10/741 | +| onn, rapid | 11.01 / 14.84 ms | 11.36 / 15.00 ms | 1/256 → 1/255 | +| TV, normal | 23.87 / 24.72 ms | 23.85 / 24.72 ms | 35/803 → 32/807 | +| TV, rapid | 24.06 / 24.78 ms | 24.05 / 24.83 ms | 27/217 → 27/219 | + +These show essentially unchanged navigation frame times rather than a consistent frame-rate gain. Earlier candidate samples fluctuated: TV rapid p90 was 24.82 ms in one run and 40.91 ms in another; the final consecutive baseline/release comparison returned to about 24.8 ms. onn candidate rapid p90 ranged from 14.37 to 15.22 ms versus the initial baseline's 14.49 ms. All captures had zero dropped FrameMetrics callbacks. FrameMetrics totals include graphics-pipeline waits; these samples neither establish a hardware ceiling nor compare identical installed-app grids across devices. The changes are retained for the demonstrated reduction in allocations and redundant scene composition, without claiming to solve the TV's remaining graphics-pipeline timing. + +The final 1.1.11 APK retains the existing signing certificate and was installed on both devices. The self-contained Plex fixture passes on both, including latest-request selection, failed-image retention, cancellation on pause, automatic focused-artwork retry on resume, rejection of obsolete selections, and image release/restoration across stop/start. Raw local reports are under ignored `output/performance/round4/`. + +Final screenshots confirm wallpaper, app artwork, focus styling, and the original spacious layout on both devices. UI hierarchy checks show the input button on the TV only. With Android settings foreground after settling, each launcher process consumed zero CPU ticks over five seconds. Back from Luma stayed in Luma on both. Projectivy remains installed and enabled. The enabled accessibility lists match the start of this round: Button Mapper only on the onn, and null on the TV. Both system Home resolvers point to Google TV; the onn's Luma Home override was already off at this round's initial capture and remains off. This round preserves that configuration rather than enabling a helper that was absent initially. Both devices were returned to Luma. Temporary diagnostics, reverse ports, and this round's on-device APKs/scripts/reports were removed after validation. diff --git a/output/Luma.apk b/output/Luma.apk index 43475a9..844f651 100644 Binary files a/output/Luma.apk and b/output/Luma.apk differ diff --git a/output/Luma.apk.idsig b/output/Luma.apk.idsig index 3e0bca3..3bcddc0 100644 Binary files a/output/Luma.apk.idsig and b/output/Luma.apk.idsig differ diff --git a/output/update.json b/output/update.json index 5d39cea..f686ffe 100644 --- a/output/update.json +++ b/output/update.json @@ -1,11 +1,11 @@ { "schema": 1, "packageName": "tv.luma.launcher", - "versionCode": 13, - "versionName": "1.1.10", + "versionCode": 14, + "versionName": "1.1.11", "minSdk": 26, "apk": "Luma.apk", "size": 2761885, - "sha256": "d0bdcb6cecc43ecd6652d9c3da6b704f6f4586f07c2273e8694f31b6a96e0f9a", - "notes": "Adds a TV-input button beside Settings on devices that expose physical inputs. Choose an HDMI or other supported input with the remote. The button stays hidden on streamers without inputs. Detects Android capabilities automatically, with no device-specific configuration." + "sha256": "a60a01942b4c64f6af3fa49d71441f85eb956a6f199e3c95c8cd6106af74470a", + "notes": "Reduces allocation when returning Home by reusing unchanged app tiles. Reuses Plex artwork that is already displayed and avoids redundant background rebuilds. Keeps the previous artwork while a replacement loads, cancels obsolete requests, and restores interrupted artwork loads after resume. Layout, image quality, and device-independent rendering defaults are unchanged." } diff --git a/tests/device/AndroidManifest.xml b/tests/device/AndroidManifest.xml index dd0d994..2fe1032 100644 --- a/tests/device/AndroidManifest.xml +++ b/tests/device/AndroidManifest.xml @@ -8,4 +8,7 @@ + + + diff --git a/tests/device/GridReuseInstrumentation.java b/tests/device/GridReuseInstrumentation.java new file mode 100644 index 0000000..f97d775 --- /dev/null +++ b/tests/device/GridReuseInstrumentation.java @@ -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 tiles() throws Exception { + return new LinkedHashMap<>((Map) 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 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 before = tiles(); + check(before.size() > 2, "insufficient apps"); + String first = before.keySet().iterator().next(); + prefs.edit().putString("labels", "never").commit(); + render(); + Map 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 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 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) original.get("hidden"))); + else edit.remove("hidden"); + edit.commit(); + render(); + check(new ArrayList<>(tiles().keySet()).equals(reverse), "reordering ignored"); + Map 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) 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); + } +} diff --git a/tests/device/PlexArtworkInstrumentation.java b/tests/device/PlexArtworkInstrumentation.java new file mode 100644 index 0000000..5c0d3b9 --- /dev/null +++ b/tests/device/PlexArtworkInstrumentation.java @@ -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 values) { + SharedPreferences.Editor edit = prefs.edit().clear(); + for (Map.Entry 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) 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 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); + } +} diff --git a/tests/device/WarmReturnInstrumentation.java b/tests/device/WarmReturnInstrumentation.java new file mode 100644 index 0000000..f10d975 --- /dev/null +++ b/tests/device/WarmReturnInstrumentation.java @@ -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 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); + } + } +}