package tv.luma.launcher.tests; import android.app.Activity; import android.app.Instrumentation; import android.content.ComponentCallbacks2; import android.content.ComponentName; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.os.Bundle; import java.lang.reflect.Field; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** Same-signature test APK. Exercises real activity callbacks without shipping a test interface. */ public final class WakeRegressionInstrumentation extends Instrumentation { private Activity activity; private final StringBuilder results = new StringBuilder(); private boolean testMemorySaver; @Override public void onCreate(Bundle arguments) { super.onCreate(arguments); testMemorySaver = arguments != null && "true".equals(arguments.getString("memorySaver")); start(); } private Object field(Object owner, String name) throws Exception { Field field = owner.getClass().getDeclaredField(name); field.setAccessible(true); return field.get(owner); } private boolean imagesReady() throws Exception { Map tiles = (Map) field(activity, "tiles"); if (tiles.isEmpty()) return false; for (Object tile : tiles.values()) { Bitmap image = (Bitmap) field(field(tile, "art"), "bitmap"); if (image == null || image.isRecycled()) return false; } Object scene = field(activity, "scene"); Bitmap wallpaper = (Bitmap) field(scene, "wallpaper"); Bitmap frame = (Bitmap) field(scene, "frame"); Bitmap mask = (Bitmap) field(scene, "mask"); if ((boolean) field(scene, "useTintMask") && (mask == null || mask.getWidth() > 320 || mask.getHeight() > 180)) return false; if (frame == null || frame.isRecycled() || frame.getWidth() > 960 || frame.getHeight() > 540) return false; // A decoded source alone must not conceal a missing or blank composed background. if (frame.getPixel(frame.getWidth() * 3 / 4, frame.getHeight() / 4) == frame.getPixel(frame.getWidth() / 4, frame.getHeight() * 3 / 4)) return false; return wallpaper != null && !wallpaper.isRecycled(); } private void awaitImages(String message) throws Exception { long end = android.os.SystemClock.uptimeMillis() + 7000; boolean[] ready = {false}; while (android.os.SystemClock.uptimeMillis() < end) { runOnMainSync( () -> { try { ready[0] = imagesReady(); } catch (Exception e) { throw new RuntimeException(e); } }); if (ready[0]) { results.append("PASS: ").append(message).append('\n'); return; } Thread.sleep(50); } throw new AssertionError(message + ": app icons or wallpaper still missing"); } @Override public void onStart() { Bundle result = new Bundle(); SharedPreferences prefs = getTargetContext().getSharedPreferences("luma", 0); boolean hadSetting = prefs.contains("memorySaver"), original = prefs.getBoolean("memorySaver", false); int status = Activity.RESULT_OK; try { if (testMemorySaver && !prefs.edit().putBoolean("memorySaver", true).commit()) throw new AssertionError("could not save memory preference"); activity = startActivitySync( new Intent(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_HOME) .setComponent( new ComponentName("tv.luma.launcher", "tv.luma.launcher.MainActivity")) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); awaitImages("cold launch loads all app icons and wallpaper"); if (testMemorySaver && !(boolean) field(field(activity, "scene"), "useTintMask")) throw new AssertionError("saved memory preference was not loaded"); ThreadPoolExecutor worker = (ThreadPoolExecutor) field(activity, "work"); CountDownLatch blocked = new CountDownLatch(1), release = new CountDownLatch(1); worker.execute( () -> { blocked.countDown(); try { release.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); if (!blocked.await(3, TimeUnit.SECONDS)) throw new AssertionError("worker did not block"); // Recorded TV sequence: restart/start -> resume -> pause -> resume, with decoding // interrupted. runOnMainSync( () -> { callActivityOnPause(activity); callActivityOnStop(activity); callActivityOnRestart(activity); callActivityOnStart(activity); callActivityOnResume(activity); callActivityOnPause(activity); }); CountDownLatch drained = new CountDownLatch(1); worker.execute(drained::countDown); release.countDown(); if (!drained.await(3, TimeUnit.SECONDS)) throw new AssertionError("worker did not drain"); waitForIdleSync(); runOnMainSync(() -> callActivityOnResume(activity)); awaitImages("interrupted wake recovers without another onStart or app restart"); Object[] firstTile = new Object[1], firstBitmap = new Object[1]; runOnMainSync( () -> { try { firstTile[0] = ((Map) field(activity, "tiles")).values().iterator().next(); firstBitmap[0] = field(field(firstTile[0], "art"), "bitmap"); } catch (Exception e) { throw new RuntimeException(e); } callActivityOnPause(activity); activity.onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); callActivityOnResume(activity); }); awaitImages("pause-only memory trim restores wallpaper"); runOnMainSync( () -> { try { Object tile = ((Map) field(activity, "tiles")).values().iterator().next(); if (tile != firstTile[0] || field(field(tile, "art"), "bitmap") != firstBitmap[0]) throw new AssertionError( "pause-only resume unnecessarily rebuilt loaded app tiles"); } catch (Exception e) { throw new RuntimeException(e); } }); results.append("PASS: existing tile views and bitmaps survive pause-only resume\n"); // Let discovery render the real grid, but hold decoding until after the next pause. CountDownLatch beforeDiscovery = new CountDownLatch(1), discover = new CountDownLatch(1); CountDownLatch beforeIcons = new CountDownLatch(1), decode = new CountDownLatch(1); worker.execute(() -> block(beforeDiscovery, discover)); if (!beforeDiscovery.await(3, TimeUnit.SECONDS)) throw new AssertionError("discovery blocker"); runOnMainSync( () -> { callActivityOnPause(activity); callActivityOnStop(activity); callActivityOnRestart(activity); callActivityOnStart(activity); callActivityOnResume(activity); worker.execute(() -> block(beforeIcons, decode)); }); discover.countDown(); if (!beforeIcons.await(3, TimeUnit.SECONDS)) throw new AssertionError("icon blocker"); waitForIdleSync(); runOnMainSync( () -> { try { firstTile[0] = ((Map) field(activity, "tiles")).values().iterator().next(); if (field(field(firstTile[0], "art"), "bitmap") != null) throw new AssertionError("icons were not held before pause"); } catch (Exception e) { throw new RuntimeException(e); } callActivityOnPause(activity); activity.onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); }); CountDownLatch iconsDrained = new CountDownLatch(1); worker.execute(iconsDrained::countDown); decode.countDown(); if (!iconsDrained.await(3, TimeUnit.SECONDS)) throw new AssertionError("icon queue drain"); runOnMainSync(() -> callActivityOnResume(activity)); awaitImages("partially loaded app grid recovers after pause-only resume"); runOnMainSync( () -> { try { if (((Map) field(activity, "tiles")).values().iterator().next() != firstTile[0]) throw new AssertionError("partial-grid recovery rebuilt the tiles"); } catch (Exception e) { throw new RuntimeException(e); } }); runOnMainSync( () -> { callActivityOnPause(activity); callActivityOnStop(activity); try { for (Object tile : ((Map) field(activity, "tiles")).values()) { android.animation.ValueAnimator shadow = (android.animation.ValueAnimator) field(tile, "shadowAnimation"); if (shadow != null && shadow.isRunning()) throw new AssertionError("focus shadow still animating after stop"); } Object scene = field(activity, "scene"); for (String name : new String[] { "wallpaper", "mediaArt", "frame", "previousFrame", "mask", "previousMask" }) if (field(scene, name) != null) throw new AssertionError("background retained " + name); if (!((ThreadPoolExecutor) field(scene, "renderer")).getQueue().isEmpty()) throw new AssertionError("background work retained after stop"); } catch (Exception e) { throw new RuntimeException(e); } callActivityOnRestart(activity); callActivityOnStart(activity); callActivityOnResume(activity); }); awaitImages("composed background restores after all cached textures are released"); runOnMainSync( () -> { try { java.lang.reflect.Method start = activity.getClass().getDeclaredMethod("startSaver"); start.setAccessible(true); start.invoke(activity); Object scene = field(activity, "scene"); if ((boolean) field(scene, "active")) throw new AssertionError("scene active under saver"); java.lang.reflect.Method stop = activity.getClass().getDeclaredMethod("stopSaver", boolean.class); stop.setAccessible(true); stop.invoke(activity, true); if (!(boolean) field(scene, "active")) throw new AssertionError("scene paused after saver"); } catch (Exception e) { throw new RuntimeException(e); } }); awaitImages("screensaver dismissal resumes background rendering"); for (int i = 0; i < 5; i++) { runOnMainSync( () -> { callActivityOnPause(activity); callActivityOnStop(activity); callActivityOnRestart(activity); callActivityOnStart(activity); callActivityOnResume(activity); }); awaitImages("stop/start recovery cycle " + (i + 1)); } if (testMemorySaver) { for (boolean enabled : new boolean[] {false, true}) { runOnMainSync( () -> { try { Object scene = field(activity, "scene"); java.lang.reflect.Method method = scene.getClass().getDeclaredMethod("setMemorySaver", boolean.class); method.setAccessible(true); method.invoke(scene, enabled); } catch (Exception e) { throw new RuntimeException(e); } }); awaitImages("runtime memory saver switch " + enabled + " restores background"); } } } catch (Throwable error) { results.append("FAIL: ").append(error).append('\n'); status = Activity.RESULT_CANCELED; } finally { if (testMemorySaver) { SharedPreferences.Editor edit = prefs.edit(); if (hadSetting) edit.putBoolean("memorySaver", original); else edit.remove("memorySaver"); if (!edit.commit()) { results.append("FAIL: could not restore memory preference\n"); status = Activity.RESULT_CANCELED; } } } result.putString("stream", results.toString()); finish(status, result); } private void block(CountDownLatch entered, CountDownLatch release) { entered.countDown(); try { release.await(10, TimeUnit.SECONDS); } catch (InterruptedException error) { Thread.currentThread().interrupt(); } } }