commit f5f1c0928f58544f1b3344a04b1467f7a7363205 Author: Elijah Kuntz Date: Sat Oct 17 22:38:45 2026 -0700 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6bf23e8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.tools/ +build/ +.gradle/ +local.properties +*.keystore +*.jks +__pycache__/ +*.pyc +output/*.png +output/*.xml +output/*.txt +output/*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..8f11770 --- /dev/null +++ b/README.md @@ -0,0 +1,117 @@ +# 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. + +## Use it + +Press **Home**, or open **Luma** from Projectivy's app list. It can also be opened with: + +```sh +.tools/platform-tools/adb -s 192.168.50.195:35635 shell am start -n tv.luma.launcher/.MainActivity +``` + +- D-pad navigates the installed app grid; OK opens an app. +- Hold OK on an app to move it, move it to the front, hide it, or open Android app info. +- In move mode, arrows move the app; OK saves and Back restores the previous order. +- Menu or the gear opens Luma settings. **All apps** includes hidden apps so they can be restored. +- Back scrolls to the first row and stays on Luma. Home returns to Luma. + +## Default launcher and Home routing + +**Settings → Default launcher** provides Android's Home app chooser, a Home button override toggle, and a direct Projectivy fallback. Enabling the override opens Android Accessibility settings; enable **Luma Home button** there. Turning it off in Luma disables only Luma's accessibility service. + +On this onn. device, Android records Luma as the Home role holder but still resolves Home to Google's launcher. Luma's accessibility workaround redirects that stock Home window and handles Home key events where Android delivers them. It runs in a separate small `:home` process so the launcher UI and its artwork can still be reclaimed while another app runs. It requests window-state events only from Google Home and Projectivy, without permission to retrieve window content. It has no polling loop or network work. + +Projectivy's **Settings → General → Override current launcher** is switched off to avoid competing Home handlers. Projectivy's application and accessibility service, and Button Mapper's accessibility service, remain enabled. The Projectivy app tile and **Open Projectivy** deliberately allow the fallback to remain open until the next Home press. Back stays on Luma. + +To return to the previous routing, turn off Luma's Home override, then open Projectivy and re-enable **Override current launcher**. No launcher needs to be disabled or uninstalled. The native chooser uses Android's [Home role API](https://developer.android.com/reference/android/app/role/RoleManager); the workaround uses the documented [AccessibilityService callbacks](https://developer.android.com/reference/android/accessibilityservice/AccessibilityService). + +## Appearance + +**Settings → Appearance → Banner** offers: + +| Mode | Behavior | +| --- | --- | +| Artwork only (default) | Original spacious composition, cinematic wallpaper, no headline or supporting text; one full app row and a partial second row at the top | +| Dynamic | Same spacious layout, with selected-app headlines and descriptions; connected Plex media can provide artwork | +| Minimal | Removes the featured area's reserved space and moves the app grid higher | + +**App labels** offers Always, Focused only (default), and Never. Accessibility app names remain available in all modes. Other settings include 5/6/7 columns, background dimming, automatic or fixed accent colors, reduced motion, clock visibility, and 90-second scene rotation. Alpine uses the bundled original wallpaper; Aurora and Midnight are inexpensive procedural gradients. + +Focus uses a 6.5% scale increase, a 160 ms transition, and an app-colored native shadow. Wallpaper/artwork crossfades last 320 ms. The launcher has no continuously rendered blur or background video. Optional screensaver video runs only while the screensaver is visible. + +The app grid uses one 260 ms scroll animation for remote focus movement. **App section text** can hide the heading, installed count, and customization hint; it is hidden by default without changing the original spacing. + +## Screensaver + +Open **Settings → Screensaver**. The home-screen idle timer defaults to **10 minutes** and offers Off, 1, 3, 5, 10, 15, 30, and 60 minutes. Any remote button or touch wakes it without launching the selected app. It is stopped when Luma leaves the foreground, so it does not interrupt other applications. + +- **Scenic:** bundled NASA Earth/space photos and Luma's original alpine scene; fully offline. +- **Art gallery:** bundled public-domain works by Van Gogh, Hokusai, and Jacques Louis David, with an optional download of a larger curated Met collection. +- **Nature video:** a locally saved video, a user-selected file through Android's document picker, or a direct MP4/HLS URL. A built-in action downloads an 85-second NPS bird clip at 720p (about 40 MB) and loops it locally. Muted by default; muted playback does not claim audio focus. + +Customize photo duration (15–300 seconds), shuffle, captions, clock, framing, dimming, and video audio. Auto framing preserves complete paintings against **pure black** mattes and fills the screen for scenic photos. Fit and Fill are explicit alternatives. A caption gradient and shadows preserve contrast over bright art. The next image is decoded before an 800 ms Canvas crossfade; at most two sampled images are in use. Invalid images are skipped without clearing the displayed artwork. + +Video downloads are capped at 250 MB, stored privately on the TV, and can be removed from the same panel. Downloads run only while requested and are canceled when leaving the download panel or Luma. HLS streams can play directly but cannot be saved as one offline MP4. Webpage/YouTube links are not direct video sources. If a video cannot play, the screensaver falls back to scenic photos. + +When Luma's idle timer is enabled, its window stays awake so Android's own idle timeout cannot preempt the selected timeout. Leaving Luma releases this flag; the power button still works. Off defers to Android's own power/screen behavior. A permission-protected Android DreamService is registered for devices that allow selecting third-party system screensavers. This onn. TV does not expose the standard Dream settings activity, and its system screensaver selection has not been changed. + +Media provenance and source links are in [docs/ASSETS.md](docs/ASSETS.md). + +## Optional Plex rows + +Choose **Settings → Plex media rows → Connect with Plex** and enter the TV's short code at [plex.tv/link](https://plex.tv/link). Select a server available to your account. Alternatively, enter your server URL and Plex token manually. HTTPS is required for remote addresses; HTTP is supported for local network servers. + +The integration reads Continue Watching and Recently Added from your server, with at most 12 items per row. Selecting Plex/Plezy can show the first Continue Watching item's artwork; focusing a media tile shows its artwork. Selecting media opens the official Plex Android app's title link. Plex controls playback. The connection is separate from Plex's own login and does not inspect another app's private data. + +Tokens are encrypted with AES-GCM using a key held in Android Keystore. **Disconnect Plex** removes the saved server and encrypted credential. API requests send credentials in headers, not URLs or logs. Android backup is disabled for this app. There are no analytics or advertising endpoints. + +Media rendering and the connection/disconnection flow were checked against a temporary local Plex fixture. A real Plex server and account have not been connected, so account authorization and actual title playback remain to be verified with your library. Pairing is user initiated; no background account polling occurs. + +## Performance design + +- Platform Java/Android views and Canvas; no WebView, Compose runtime, playback engine, or third-party runtime dependencies. +- Single sampled RGB565 wallpaper (960 × 540 for the bundled 1920 × 1080 image). +- App artwork is rasterized to 288 × 162. Icon cache is capped at 3 MiB; visible tiles also hold their displayed images. +- Plex image cache is capped at 3 MiB. Hero images are sampled to at most roughly 1280 × 720; rows and network response sizes are bounded. +- At most the current and previous artwork are retained during a short crossfade. A focus debounce avoids loading artwork for every passing selection. +- No boot receivers, alarms, PowerManager wake locks, or periodic background jobs. The optional Home override is an event-driven accessibility service in a separate process; turning it off removes that bound service. The optional DreamService runs only when Android explicitly binds it as a system screensaver. +- Clock updates once per minute; optional scene rotation runs only while Luma is visible. +- On pause, networking and scene animations are canceled. On stop, queued work, image references, and caches are cleared. Worker threads time out after ten idle seconds. +- Android can reclaim the cached launcher process while another app is running. It is not kept alive artificially. + +Measurements are in [docs/VALIDATION.md](docs/VALIDATION.md). PSS includes Android framework and graphics overhead and varies with device state; the APK's size does not represent RAM consumption. + +## Build and install + +The signed APK is [output/Luma.apk](output/Luma.apk). Source is in `app/src/main/java/tv/luma/launcher`. + +The current workspace already contains a local JDK 17 and Android SDK under `.tools`. Rebuild without Gradle: + +```sh +scripts/build.sh +.tools/platform-tools/adb -s 192.168.50.195:35635 install -r output/Luma.apk +``` + +For a fresh macOS checkout, run `scripts/bootstrap.sh`, review/accept the SDK licenses, then build. Alternatively use the included Gradle project with JDK 17, Gradle 8.7 and Android SDK 34. No third-party app dependencies are needed. + +The local build creates and reuses `.tools/luma-development.keystore`. Preserve that file to install future updates over the existing APK. It is ignored by source control. This is a development signing identity for your sideloaded build; configure your own signing identity before distributing it. + +To remove only Luma, run `adb uninstall tv.luma.launcher`; Projectivy remains installed. No command in the build/install scripts disables another launcher or changes the default Home app. + +## Device checks + +```sh +python3 scripts/device_smoke.py --part navigation +python3 scripts/device_smoke.py --part home-routing +python3 scripts/device_smoke.py --part customization +python3 scripts/device_smoke.py --part appearance-modes +python3 scripts/device_smoke.py --part performance +python3 scripts/device_smoke.py --part screensaver +python3 scripts/device_smoke.py --part screensaver-video +python3 scripts/device_smoke.py --part screensaver-timeout +``` + +The scripts operate the TV through ADB. Run one at a time with the TV awake. The customization checks expect the documented defaults. The Plex fixture requires `python3 scripts/plex_fixture.py` running on the host, followed by `python3 scripts/device_smoke.py --part plex`. It uses temporary ADB reverse forwarding to a loopback server and disconnects the fixture when finished. + +See [docs/ASSETS.md](docs/ASSETS.md) for the wallpaper generation prompt and asset provenance. Android TV intent handling follows [Android's TV app guidance](https://developer.android.com/training/tv/get-started/create); Plex integration follows the [official Plex Media Server API documentation](https://developer.plex.tv/pms/). diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..c6220de --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,13 @@ +plugins { id 'com.android.application' } +android { + namespace 'tv.luma.launcher' + compileSdk 34 + defaultConfig { + applicationId 'tv.luma.launcher' + minSdk 26 + targetSdk 34 + versionCode 1 + versionName '1.0.0' + } + 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 new file mode 100644 index 0000000..e95cbf6 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/assets/alpine.jpg b/app/src/main/assets/alpine.jpg new file mode 100644 index 0000000..43153df Binary files /dev/null and b/app/src/main/assets/alpine.jpg differ diff --git a/app/src/main/assets/saver/436105.jpg b/app/src/main/assets/saver/436105.jpg new file mode 100644 index 0000000..1f8e13b Binary files /dev/null and b/app/src/main/assets/saver/436105.jpg differ diff --git a/app/src/main/assets/saver/436535.jpg b/app/src/main/assets/saver/436535.jpg new file mode 100644 index 0000000..5070391 Binary files /dev/null and b/app/src/main/assets/saver/436535.jpg differ diff --git a/app/src/main/assets/saver/45434.jpg b/app/src/main/assets/saver/45434.jpg new file mode 100644 index 0000000..3b21948 Binary files /dev/null and b/app/src/main/assets/saver/45434.jpg differ diff --git a/app/src/main/assets/saver/catalog.json b/app/src/main/assets/saver/catalog.json new file mode 100644 index 0000000..0ecec79 --- /dev/null +++ b/app/src/main/assets/saver/catalog.json @@ -0,0 +1,44 @@ +[ + { + "album": "art", + "file": "saver/436535.jpg", + "title": "Wheat Field with Cypresses", + "credit": "Vincent van Gogh · 1889 · The Met, CC0", + "source": "https://www.metmuseum.org/art/collection/search/436535" + }, + { + "album": "art", + "file": "saver/45434.jpg", + "title": "The Great Wave", + "credit": "Katsushika Hokusai · ca. 1830–32 · The Met, CC0", + "source": "https://www.metmuseum.org/art/collection/search/45434" + }, + { + "album": "art", + "file": "saver/436105.jpg", + "title": "The Death of Socrates", + "credit": "Jacques Louis David · 1787 · The Met, CC0", + "source": "https://www.metmuseum.org/art/collection/search/436105" + }, + { + "album": "scenic", + "file": "saver/earth.jpg", + "title": "Earth · Blue Marble", + "credit": "NASA/NOAA", + "source": "https://images.nasa.gov/details/PIA18033" + }, + { + "album": "scenic", + "file": "saver/space.jpg", + "title": "Cosmic Cliffs · Carina Nebula", + "credit": "NASA, ESA, CSA, STScI", + "source": "https://images.nasa.gov/details/carina_nebula" + }, + { + "album": "scenic", + "file": "alpine.jpg", + "title": "Alpine at blue hour", + "credit": "Luma · Original artwork", + "source": "docs/ASSETS.md" + } +] \ No newline at end of file diff --git a/app/src/main/assets/saver/earth.jpg b/app/src/main/assets/saver/earth.jpg new file mode 100644 index 0000000..c179738 Binary files /dev/null and b/app/src/main/assets/saver/earth.jpg differ diff --git a/app/src/main/assets/saver/space.jpg b/app/src/main/assets/saver/space.jpg new file mode 100644 index 0000000..cd66bf1 Binary files /dev/null and b/app/src/main/assets/saver/space.jpg differ diff --git a/app/src/main/java/tv/luma/launcher/AppRepository.java b/app/src/main/java/tv/luma/launcher/AppRepository.java new file mode 100644 index 0000000..2ebcf4d --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/AppRepository.java @@ -0,0 +1,89 @@ +package tv.luma.launcher; + +import android.content.*; +import android.content.pm.*; +import android.graphics.*; +import android.graphics.drawable.Drawable; +import android.util.LruCache; +import java.util.*; + +final class AppRepository { + static final class App { + final String pkg, label; + final ComponentName component; + final ResolveInfo info; + + App(ResolveInfo r, PackageManager pm) { + info = r; + pkg = r.activityInfo.packageName; + component = new ComponentName(pkg, r.activityInfo.name); + label = r.loadLabel(pm).toString(); + } + } + + private final Context context; + final LruCache icons = + new LruCache(3 * 1024 * 1024) { + protected int sizeOf(String k, Bitmap b) { + return b.getAllocationByteCount(); + } + }; + + AppRepository(Context c) { + context = c.getApplicationContext(); + } + + List discover() { + PackageManager pm = context.getPackageManager(); + Map map = new HashMap<>(); + for (String cat : new String[] {Intent.CATEGORY_LEANBACK_LAUNCHER, Intent.CATEGORY_LAUNCHER}) { + Intent i = new Intent(Intent.ACTION_MAIN).addCategory(cat); + for (ResolveInfo r : pm.queryIntentActivities(i, 0)) { + if (!r.activityInfo.enabled || r.activityInfo.packageName.equals(context.getPackageName())) + continue; + if (!map.containsKey(r.activityInfo.packageName)) + map.put(r.activityInfo.packageName, new App(r, pm)); + } + } + List apps = new ArrayList<>(map.values()); + apps.sort((a, b) -> a.label.compareToIgnoreCase(b.label)); + return apps; + } + + Bitmap icon(App app) { + Bitmap old = icons.get(app.pkg); + if (old != null) return old; + try { + PackageManager pm = context.getPackageManager(); + Drawable d = app.info.activityInfo.loadBanner(pm); + if (d == null) d = pm.getApplicationBanner(app.pkg); + boolean banner = d != null; + if (d == null) d = app.info.loadIcon(pm); + Bitmap b = Bitmap.createBitmap(288, 162, Bitmap.Config.ARGB_8888); + Canvas c = new Canvas(b); + c.drawColor(color(app.pkg)); + if (banner) { + d.setBounds(0, 0, 288, 162); + } else { + d.setBounds(97, 34, 191, 128); + } + d.draw(c); + icons.put(app.pkg, b); + return b; + } catch (Exception e) { + return null; + } + } + + static int color(String pkg) { + String p = pkg.toLowerCase(Locale.ROOT); + if (p.contains("plex") || p.contains("plezy")) return 0xFF5B4125; + if (p.contains("netflix")) return 0xFF681B2C; + if (p.contains("spotify")) return 0xFF164F45; + if (p.contains("disney")) return 0xFF193C6A; + if (p.contains("youtube") || p.contains("smarttube")) return 0xFF62352D; + if (p.contains("twitch")) return 0xFF4A3267; + if (p.contains("moon") || p.contains("limelight")) return 0xFF244E68; + return Color.HSVToColor(new float[] {Math.abs(pkg.hashCode() % 360), .42f, .31f}); + } +} diff --git a/app/src/main/java/tv/luma/launcher/AppTile.java b/app/src/main/java/tv/luma/launcher/AppTile.java new file mode 100644 index 0000000..7ba0030 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/AppTile.java @@ -0,0 +1,188 @@ +package tv.luma.launcher; + +import android.content.Context; +import android.graphics.*; +import android.view.*; +import android.view.animation.DecelerateInterpolator; +import android.widget.*; + +/** Real focusable view: native D-pad navigation and accessibility labels. */ +final class AppTile extends LinearLayout { + private final ArtView art; + private final TextView label; + private boolean motion = true; + private String labelMode = "always"; + + interface Focus { + void changed(boolean hasFocus); + } + + AppTile(Context c, String name, int width, boolean compact) { + super(c); + setOrientation(VERTICAL); + setGravity(Gravity.CENTER_HORIZONTAL); + setFocusable(true); + setClickable(true); + setClipChildren(false); + setClipToPadding(false); + setContentDescription(name); + setPadding(Ui.dp(c, 5), Ui.dp(c, 7), Ui.dp(c, 5), Ui.dp(c, 7)); + art = new ArtView(c, name); + int height = Math.round((width - 10) * 9f / 16f); + addView(art, new LinearLayout.LayoutParams(Ui.dp(c, width - 10), Ui.dp(c, height))); + label = Ui.text(c, name, compact ? 11 : 12, Ui.MUTED); + label.setSingleLine(true); + label.setEllipsize(android.text.TextUtils.TruncateAt.END); + label.setGravity(Gravity.CENTER); + label.setPadding(0, Ui.dp(c, 9), 0, 0); + addView(label, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, Ui.dp(c, 28))); + setOnFocusChangeListener( + (v, f) -> { + animate().cancel(); + animate() + .scaleX(f ? 1.065f : 1f) + .scaleY(f ? 1.065f : 1f) + .translationZ(f ? Ui.dp(c, 8) : 0) + .setDuration(motion ? 160 : 0) + .setInterpolator(new DecelerateInterpolator()) + .start(); + label.setTextColor(f ? Ui.WHITE : Ui.MUTED); + updateLabel(); + art.focus = f; + art.animate().translationZ(Ui.dp(c, f ? 8 : 1)).setDuration(motion ? 160 : 0).start(); + art.invalidate(); + if (focus != null) focus.changed(f); + }); + } + + private Focus focus; + + void onFocused(Focus f) { + focus = f; + } + + void setMotion(boolean enabled) { + motion = enabled; + } + + void setLabelMode(String mode) { + labelMode = mode; + updateLabel(); + } + + private void updateLabel() { + label.setVisibility( + labelMode.equals("never") + ? View.GONE + : labelMode.equals("focused") && !hasFocus() ? View.INVISIBLE : View.VISIBLE); + } + + void setAccent(int color) { + if (android.os.Build.VERSION.SDK_INT >= 28) { + art.setOutlineAmbientShadowColor(color); + art.setOutlineSpotShadowColor(color); + } + } + + void stopAnimations() { + animate().cancel(); + art.animate().cancel(); + } + + void bitmap(Bitmap b) { + art.bitmap = b; + art.invalidate(); + } + + void progress(float value) { + art.progress = value; + art.invalidate(); + } + + private static final class ArtView extends View { + final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); + final RectF rect = new RectF(); + final Path clip = new Path(); + Bitmap bitmap; + boolean focus; + String fallback; + float progress; + + ArtView(Context c, String s) { + super(c); + fallback = s; + setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); + setElevation(Ui.dp(c, 2)); + setOutlineProvider( + new ViewOutlineProvider() { + @Override + public void getOutline(View view, Outline outline) { + outline.setRoundRect( + 2, + 2, + Math.max(3, view.getWidth() - 2), + Math.max(3, view.getHeight() - 2), + Ui.dp(c, 12)); + } + }); + } + + protected void onSizeChanged(int w, int h, int ow, int oh) { + rect.set( + Ui.dp(getContext(), 2), + Ui.dp(getContext(), 2), + w - Ui.dp(getContext(), 2), + h - Ui.dp(getContext(), 2)); + clip.reset(); + clip.addRoundRect(rect, Ui.dp(getContext(), 12), Ui.dp(getContext(), 12), Path.Direction.CW); + } + + protected void onDraw(Canvas c) { + c.save(); + c.clipPath(clip); + p.setColor(0xFF1B263B); + c.drawRect(rect, p); + if (bitmap != null) { + float scale = + Math.max(rect.width() / bitmap.getWidth(), rect.height() / bitmap.getHeight()); + float w = bitmap.getWidth() * scale, h = bitmap.getHeight() * scale; + c.drawBitmap( + bitmap, + null, + new RectF( + rect.centerX() - w / 2, + rect.centerY() - h / 2, + rect.centerX() + w / 2, + rect.centerY() + h / 2), + p); + } else { + p.setColor(Ui.WHITE); + p.setTextSize(Ui.dp(getContext(), 17)); + p.setTypeface(Typeface.create("sans-serif-medium", 0)); + p.setTextAlign(Paint.Align.CENTER); + c.drawText( + fallback.length() > 15 ? fallback.substring(0, 14) + "…" : fallback, + rect.centerX(), + rect.centerY() + Ui.dp(getContext(), 5), + p); + } + if (progress > 0) { + p.setColor(0xA0080D18); + c.drawRect(rect.left, rect.bottom - Ui.dp(getContext(), 4), rect.right, rect.bottom, p); + p.setColor(Ui.GOLD); + c.drawRect( + rect.left, + rect.bottom - Ui.dp(getContext(), 4), + rect.left + rect.width() * progress, + rect.bottom, + p); + } + c.restore(); + p.setStyle(Paint.Style.STROKE); + p.setStrokeWidth(Ui.dp(getContext(), focus ? 1.5f : 1)); + p.setColor(focus ? 0xDBF4E8D8 : 0x26FFFFFF); + c.drawRoundRect(rect, Ui.dp(getContext(), 12), Ui.dp(getContext(), 12), p); + p.setStyle(Paint.Style.FILL); + } + } +} diff --git a/app/src/main/java/tv/luma/launcher/FocusScrollView.java b/app/src/main/java/tv/luma/launcher/FocusScrollView.java new file mode 100644 index 0000000..ff6839a --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/FocusScrollView.java @@ -0,0 +1,55 @@ +package tv.luma.launcher; + +import android.animation.ValueAnimator; +import android.content.Context; +import android.graphics.Rect; +import android.view.KeyEvent; +import android.view.View; +import android.view.animation.DecelerateInterpolator; +import android.widget.ScrollView; + +/** One scroll animator owns remote focus movement; native focus scrolling must not snap first. */ +class FocusScrollView extends ScrollView { + private ValueAnimator scrollAnimation; + + FocusScrollView(Context context) { + super(context); + } + + @Override + protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { + return 0; + } + + @Override + public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { + return false; + } + + @Override + public boolean executeKeyEvent(KeyEvent event) { + if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP + || event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) return false; + return super.executeKeyEvent(event); + } + + void animateToY(int y, boolean motion) { + stopAnimation(); + int maximum = getChildCount() == 0 ? 0 : Math.max(0, getChildAt(0).getHeight() - getHeight()); + int target = Math.min(maximum, Math.max(0, y)); + if (target == getScrollY()) return; + if (!motion) { + scrollTo(0, target); + return; + } + scrollAnimation = ValueAnimator.ofInt(getScrollY(), target); + scrollAnimation.setDuration(260); + scrollAnimation.setInterpolator(new DecelerateInterpolator(1.6f)); + scrollAnimation.addUpdateListener(a -> scrollTo(0, (int) a.getAnimatedValue())); + scrollAnimation.start(); + } + + void stopAnimation() { + if (scrollAnimation != null) scrollAnimation.cancel(); + } +} diff --git a/app/src/main/java/tv/luma/launcher/HomeControlReceiver.java b/app/src/main/java/tv/luma/launcher/HomeControlReceiver.java new file mode 100644 index 0000000..07ffd7c --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/HomeControlReceiver.java @@ -0,0 +1,34 @@ +package tv.luma.launcher; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +/** Private, explicit cross-process controls; only Luma's own UID can call this receiver. */ +public final class HomeControlReceiver extends BroadcastReceiver { + static final String FALLBACK = "tv.luma.launcher.ALLOW_PROJECTIVY"; + static final String DISABLE = "tv.luma.launcher.DISABLE_HOME_OVERRIDE"; + + static void setFallback(Context context, boolean allow) { + if (isFallback(context) == allow) return; + context + .getSharedPreferences("home-routing", Context.MODE_PRIVATE) + .edit() + .putBoolean("fallback", allow) + .apply(); + } + + static boolean isFallback(Context context) { + return context + .getSharedPreferences("home-routing", Context.MODE_PRIVATE) + .getBoolean("fallback", false); + } + + @Override + public void onReceive(Context context, Intent intent) { + if (FALLBACK.equals(intent.getAction())) setFallback(context, true); + else if (DISABLE.equals(intent.getAction()) && LumaHomeService.active != null) { + LumaHomeService.active.disableSelf(); + } + } +} diff --git a/app/src/main/java/tv/luma/launcher/LumaDreamService.java b/app/src/main/java/tv/luma/launcher/LumaDreamService.java new file mode 100644 index 0000000..ebf28b0 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/LumaDreamService.java @@ -0,0 +1,41 @@ +package tv.luma.launcher; + +import android.service.dreams.DreamService; + +/** Optional system screensaver. Android binds it only when explicitly selected and dreaming. */ +public final class LumaDreamService extends DreamService { + private SaverView saver; + + @Override + public void onAttachedToWindow() { + super.onAttachedToWindow(); + setInteractive(false); + setFullscreen(true); + setScreenBright(false); + } + + @Override + public void onDreamingStarted() { + super.onDreamingStarted(); + saver = new SaverView(this); + setContentView(saver); + } + + @Override + public void onDreamingStopped() { + if (saver != null) { + saver.stop(); + saver = null; + } + super.onDreamingStopped(); + } + + @Override + public void onDetachedFromWindow() { + if (saver != null) { + saver.stop(); + saver = null; + } + super.onDetachedFromWindow(); + } +} diff --git a/app/src/main/java/tv/luma/launcher/LumaHomeService.java b/app/src/main/java/tv/luma/launcher/LumaHomeService.java new file mode 100644 index 0000000..5fb5876 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/LumaHomeService.java @@ -0,0 +1,64 @@ +package tv.luma.launcher; + +import android.accessibilityservice.AccessibilityService; +import android.content.Intent; +import android.view.KeyEvent; +import android.view.accessibility.AccessibilityEvent; + +/** Event-driven Home routing. Runs separately so it cannot retain the launcher's image heap. */ +public final class LumaHomeService extends AccessibilityService { + static LumaHomeService active; + + @Override + protected void onServiceConnected() { + active = this; + } + + @Override + public boolean onKeyEvent(KeyEvent event) { + if (event.getKeyCode() != KeyEvent.KEYCODE_HOME) return false; + if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { + HomeControlReceiver.setFallback(this, false); + openLuma(); + } + return true; + } + + @Override + public void onAccessibilityEvent(AccessibilityEvent event) { + if (event.getEventType() != AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) return; + String pkg = String.valueOf(event.getPackageName()); + String cls = String.valueOf(event.getClassName()); + // Class names only: no view hierarchy, text, screenshots, or content inspection. + if (pkg.equals("com.google.android.apps.tv.launcherx") + && cls.equals("com.google.android.apps.tv.launcherx.home.HomeActivity")) { + HomeControlReceiver.setFallback(this, false); + openLuma(); + } else if (pkg.equals("com.spocky.projengmenu") + && cls.equals("com.spocky.projengmenu.ui.home.MainActivity") + && !HomeControlReceiver.isFallback(this)) { + openLuma(); + } + } + + private void openLuma() { + try { + startActivity( + new Intent(this, MainActivity.class) + .setAction(Intent.ACTION_MAIN) + .addCategory(Intent.CATEGORY_HOME) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP)); + } catch (RuntimeException ignored) { + // The original Home remains usable if an OEM rejects an activity start. + } + } + + @Override + public void onInterrupt() {} + + @Override + public void onDestroy() { + if (active == this) active = null; + super.onDestroy(); + } +} diff --git a/app/src/main/java/tv/luma/launcher/MainActivity.java b/app/src/main/java/tv/luma/launcher/MainActivity.java new file mode 100644 index 0000000..4bc8ca0 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/MainActivity.java @@ -0,0 +1,1979 @@ +package tv.luma.launcher; + +import android.app.*; +import android.content.*; +import android.graphics.*; +import android.net.Uri; +import android.os.*; +import android.provider.Settings; +import android.text.InputType; +import android.view.*; +import android.widget.*; +import java.util.*; +import java.util.concurrent.*; + +public final class MainActivity extends Activity { + private final Handler handler = new Handler(Looper.getMainLooper()); + private final ThreadPoolExecutor work = + new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); + private final ThreadPoolExecutor network = + new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); + private SharedPreferences prefs; + private AppRepository repository; + private SceneView scene; + private FocusScrollView scroll; + private LinearLayout content, appsContainer, mediaContainer, hero, sectionHeading; + private PlexClient.Media plexFeatured; + private TextView clock, eyebrow, headline, description, openHint, appCount, settingsButton; + private final List allApps = new ArrayList<>(), + visibleApps = new ArrayList<>(); + private final Map tiles = new LinkedHashMap<>(); + private final List mediaTiles = new ArrayList<>(); + private String selected = "", sceneName = "alpine"; + private volatile int generation = 0; + private volatile int iconGeneration = 0; + private volatile int artGeneration = 0; + private int rotation = 0; + private volatile boolean foreground = false; + private boolean moving = false; + private volatile Dialog currentDialog; + private PlexClient plex; + private FrameLayout root; + private SaverView saver; + private boolean saverWakePending; + private boolean saverDownloading; + private boolean refreshHomeSettings; + private SaverMedia saverMedia; + private final Runnable idleSaver = + () -> { + if (foreground && currentDialog == null && !moving) startSaver(); + }; + private final Runnable minuteTick = + new Runnable() { + public void run() { + if (!foreground) return; + updateClock(); + handler.postDelayed(this, 60000 - System.currentTimeMillis() % 60000); + } + }; + private final Runnable rotateScene = + new Runnable() { + public void run() { + if (!foreground || !prefs.getBoolean("rotate", false)) return; + String[] scenes = {"alpine", "aurora", "midnight"}; + scene.configure(scenes[++rotation % 3], darkness()); + handler.postDelayed(this, 90000); + } + }; + + @Override + public void onCreate(Bundle state) { + super.onCreate(state); + work.allowCoreThreadTimeOut(true); + network.allowCoreThreadTimeOut(true); + prefs = getSharedPreferences("luma", MODE_PRIVATE); + repository = new AppRepository(this); + plex = new PlexClient(this); + saverMedia = new SaverMedia(this); + getWindow().getDecorView().setSystemUiVisibility(5894); + getWindow().setNavigationBarColor(Ui.BG); + buildShell(); + } + + private int d(float n) { + return Ui.dp(this, n); + } + + private boolean motion() { + return prefs.getBoolean("motion", true); + } + + private float darkness() { + return prefs.getInt("darkness", 20) / 100f; + } + + private LinearLayout column() { + LinearLayout v = new LinearLayout(this); + v.setOrientation(LinearLayout.VERTICAL); + return v; + } + + private void buildShell() { + root = new FrameLayout(this); + root.getViewTreeObserver() + .addOnTouchModeChangeListener( + inTouchMode -> { + if (!inTouchMode && saver != null) { + stopSaver(true); + saverWakePending = true; + } + }); + scene = new SceneView(this); + root.addView(scene, new FrameLayout.LayoutParams(-1, -1)); + scroll = + new FocusScrollView(this) { + @Override + public void requestChildFocus(View child, View focused) { + super.requestChildFocus(child, focused); + if (focused != null) post(() -> keepFocusVisible(focused)); + } + }; + scroll.setFillViewport(true); + scroll.setClipToPadding(false); + scroll.setVerticalScrollBarEnabled(false); + scroll.setOverScrollMode(View.OVER_SCROLL_NEVER); + scroll.setSmoothScrollingEnabled(true); + content = column(); + content.setPadding(d(51), d(25), d(51), d(35)); + content.setClipChildren(false); + content.setClipToPadding(false); + scroll.addView(content, new ScrollView.LayoutParams(-1, -2)); + root.addView(scroll, new FrameLayout.LayoutParams(-1, -1)); + LinearLayout header = new LinearLayout(this); + header.setGravity(Gravity.CENTER_VERTICAL); + header.setClipChildren(false); + TextView brand = Ui.text(this, "luma", 26, Ui.WHITE); + brand.setTypeface(Typeface.create("sans-serif-medium", 0)); + brand.setLetterSpacing(-.04f); + header.addView(brand); + TextView dot = Ui.text(this, "•", 22, Ui.GOLD); + LinearLayout.LayoutParams dotLp = new LinearLayout.LayoutParams(d(20), -2); + dotLp.leftMargin = d(2); + header.addView(dot, dotLp); + View spacer = new View(this); + header.addView(spacer, new LinearLayout.LayoutParams(0, 1, 1)); + clock = Ui.text(this, "", 13, Ui.WHITE); + clock.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL); + header.addView(clock, new LinearLayout.LayoutParams(d(125), d(32))); + settingsButton = chip("⚙", v -> showSettings()); + settingsButton.setTextSize(19); + settingsButton.setContentDescription("Luma settings"); + settingsButton.setId(View.generateViewId()); + LinearLayout.LayoutParams settingsLp = new LinearLayout.LayoutParams(d(39), d(34)); + settingsLp.leftMargin = d(17); + header.addView(settingsButton, settingsLp); + content.addView(header, new LinearLayout.LayoutParams(-1, d(34))); + hero = column(); + hero.setPadding(d(4), d(42), 0, 0); + eyebrow = Ui.text(this, "YOUR SPACE. YOUR SCREEN.", 10, Ui.GOLD); + eyebrow.setLetterSpacing(.18f); + Ui.medium(eyebrow); + hero.addView(eyebrow); + headline = Ui.text(this, "Something good\nstarts here.", 43, Ui.WHITE); + headline.setTypeface(Typeface.create("sans-serif-light", 0)); + headline.setLetterSpacing(-.035f); + headline.setLineSpacing(d(-2), 1); + headline.setMaxLines(2); + LinearLayout.LayoutParams titleLp = new LinearLayout.LayoutParams(d(505), d(104)); + titleLp.topMargin = d(12); + hero.addView(headline, titleLp); + description = Ui.text(this, "All your favorites. A little more cinematic.", 12, 0xFFB9C3D1); + description.setMaxLines(2); + LinearLayout.LayoutParams descLp = new LinearLayout.LayoutParams(d(470), d(34)); + descLp.topMargin = d(6); + hero.addView(description, descLp); + openHint = Ui.text(this, "", 11, 0xFFE9DECF); + openHint.setPadding(0, d(8), 0, 0); + hero.addView(openHint, new LinearLayout.LayoutParams(d(490), d(30))); + content.addView(hero, new LinearLayout.LayoutParams(-1, d(267))); + LinearLayout gridHeading = new LinearLayout(this); + sectionHeading = gridHeading; + gridHeading.setGravity(Gravity.CENTER_VERTICAL); + gridHeading.setPadding(d(4), 0, d(4), 0); + TextView title = Ui.text(this, "Your apps", 18, Ui.WHITE); + Ui.medium(title); + gridHeading.addView(title); + appCount = Ui.text(this, "", 10, Ui.MUTED); + LinearLayout.LayoutParams countLp = new LinearLayout.LayoutParams(0, -2, 1); + countLp.leftMargin = d(12); + gridHeading.addView(appCount, countLp); + TextView hint = Ui.text(this, "HOLD OK TO CUSTOMIZE", 9, 0xFF8C9AAE); + hint.setLetterSpacing(.12f); + gridHeading.addView(hint); + content.addView(gridHeading, new LinearLayout.LayoutParams(-1, d(34))); + appsContainer = column(); + appsContainer.setClipChildren(false); + appsContainer.setClipToPadding(false); + content.addView(appsContainer, new LinearLayout.LayoutParams(-1, -2)); + mediaContainer = column(); + mediaContainer.setClipChildren(false); + mediaContainer.setPadding(d(4), d(19), d(4), 0); + content.addView(mediaContainer, new LinearLayout.LayoutParams(-1, -2)); + LinearLayout footer = new LinearLayout(this); + footer.setGravity(Gravity.CENTER_VERTICAL); + footer.setPadding(d(4), d(24), d(4), 0); + TextView all = chip("All apps", v -> showAllApps()); + footer.addView(all, new LinearLayout.LayoutParams(d(95), d(35))); + TextView customize = chip("Personalize", v -> showSettings()); + LinearLayout.LayoutParams customizeLp = new LinearLayout.LayoutParams(d(112), d(35)); + customizeLp.leftMargin = d(10); + footer.addView(customize, customizeLp); + content.addView(footer, new LinearLayout.LayoutParams(-1, d(66))); + setContentView(root); + configureScene(); + updateFeaturedText(); + updateSectionText(); + updateClock(); + } + + private TextView chip(String label, View.OnClickListener click) { + TextView t = Ui.text(this, label, 12, Ui.WHITE); + t.setGravity(Gravity.CENTER); + t.setFocusable(true); + t.setClickable(true); + t.setTextColor(Ui.textColors()); + Ui.glass(t, 18); + t.setOnClickListener(click); + return t; + } + + private void configureScene() { + sceneName = prefs.getString("scene", "alpine"); + scene.configure(sceneName, darkness()); + scene.setMotion(motion()); + } + + private String bannerMode() { + return prefs.getString( + "bannerMode", prefs.getBoolean("featuredText", false) ? "dynamic" : "artwork"); + } + + private void updateFeaturedText() { + String mode = bannerMode(); + int visibility = mode.equals("dynamic") ? View.VISIBLE : View.INVISIBLE; + eyebrow.setVisibility(visibility); + headline.setVisibility(visibility); + description.setVisibility(visibility); + openHint.setVisibility(moving ? View.VISIBLE : visibility); + int height = d(mode.equals("minimal") ? 12 : 267); + appCount.setText( + moving ? "Move with arrows · OK saves · Back cancels" : visibleApps.size() + " installed"); + if (hero.getLayoutParams().height != height) { + hero.getLayoutParams().height = height; + hero.requestLayout(); + } + } + + private void updateSectionText() { + sectionHeading.setVisibility( + prefs.getBoolean("sectionText", false) ? View.VISIBLE : View.INVISIBLE); + } + + private void keepFocusVisible(View focused) { + if (!focused.hasFocus() || content == null) return; + Rect bounds = new Rect(); + focused.getDrawingRect(bounds); + content.offsetDescendantRectToMyCoords(focused, bounds); + int index = + focused.getTag() instanceof String + ? visibleApps.indexOf(findApp((String) focused.getTag())) + : -1; + int target = scroll.getScrollY(); + if (index >= 0 && index < columns()) target = 0; + else if (bounds.bottom > target + scroll.getHeight() - d(36)) + target = bounds.bottom - scroll.getHeight() + d(36); + else if (bounds.top < target + d(44)) target = bounds.top - d(44); + scroll.animateToY(Math.max(0, target), motion()); + } + + private void updateClock() { + boolean show = prefs.getBoolean("clock", true); + clock.setVisibility(show ? View.VISIBLE : View.GONE); + clock.setText(android.text.format.DateFormat.getTimeFormat(this).format(new Date())); + } + + @Override + protected void onStart() { + super.onStart(); + foreground = true; + plex.resume(); + int g = ++generation; + loadApps(g); + work.execute( + () -> { + Bitmap b = SceneView.decodeWallpaper(this); + handler.post( + () -> { + if (foreground && g == generation) scene.setWallpaper(b); + }); + }); + } + + @Override + protected void onResume() { + super.onResume(); + foreground = true; + plex.resume(); + handler.removeCallbacks(minuteTick); + handler.post(minuteTick); + handler.removeCallbacks(rotateScene); + if (prefs.getBoolean("rotate", false)) handler.postDelayed(rotateScene, 90000); + resetSaverTimer(); + if (refreshHomeSettings) { + refreshHomeSettings = false; + defaultLauncherSettings(); + } + } + + @Override + protected void onPause() { + super.onPause(); + foreground = false; + handler.removeCallbacks(minuteTick); + handler.removeCallbacks(rotateScene); + plex.cancel(); + saverMedia.cancel(); + if (saverDownloading && currentDialog != null) { + currentDialog.dismiss(); + currentDialog = null; + saverDownloading = false; + } + getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + handler.removeCallbacks(idleSaver); + stopSaver(false); + scene.stopAnimations(); + scroll.stopAnimation(); + } + + @Override + protected void onStop() { + super.onStop(); + generation++; + artGeneration++; + work.getQueue().clear(); + network.getQueue().clear(); + repository.icons.evictAll(); + for (AppTile t : tiles.values()) { + t.animate().cancel(); + t.stopAnimations(); + t.bitmap(null); + } + for (AppTile t : mediaTiles) { + t.animate().cancel(); + t.stopAnimations(); + t.bitmap(null); + } + scene.release(); + plex.releaseImages(); + } + + @Override + public void onTrimMemory(int level) { + super.onTrimMemory(level); + if (level >= TRIM_MEMORY_RUNNING_LOW) { + repository.icons.evictAll(); + plex.releaseImages(); + if (!foreground) scene.release(); + } + } + + @Override + protected void onDestroy() { + handler.removeCallbacksAndMessages(null); + plex.cancel(); + work.shutdownNow(); + network.shutdownNow(); + super.onDestroy(); + } + + private void loadApps(int g) { + work.execute( + () -> { + List found = repository.discover(); + handler.post( + () -> { + if (!foreground || g != generation) return; + allApps.clear(); + allApps.addAll(found); + renderApps(); + loadMedia(); + }); + }); + } + + private int columns() { + return prefs.getInt("columns", 6); + } + + private List savedOrder() { + String s = prefs.getString("order", ""); + return new ArrayList<>(Arrays.asList(s.split(","))); + } + + private Set hidden() { + return new HashSet<>(prefs.getStringSet("hidden", Collections.emptySet())); + } + + private void renderApps() { + iconGeneration++; + Set hidden = hidden(); + List order = savedOrder(); + List defaults = + Arrays.asList( + "com.plexapp.android", + "com.edde746.plezy", + "org.smarttube.beta", + "com.netflix.ninja", + "com.disney.disneyplus", + "com.spotify.tv.android", + "com.limelight", + "com.valvesoftware.steamlink", + "com.amazon.amazonvideo.livingroom", + "com.crunchyroll.crunchyroid", + "com.fgl27.twitch", + "tv.twitch.android.app"); + visibleApps.clear(); + for (AppRepository.App a : allApps) if (!hidden.contains(a.pkg)) visibleApps.add(a); + visibleApps.sort( + (a, b) -> { + int ai = order.indexOf(a.pkg), bi = order.indexOf(b.pkg); + if (ai < 0) ai = 1000 + (defaults.contains(a.pkg) ? defaults.indexOf(a.pkg) : 100); + 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; + LinearLayout row = null; + int index = 0; + for (AppRepository.App app : visibleApps) { + if (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()); + 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) { + selected = app.pkg; + updateHero(app); + } + }); + tile.setOnClickListener(v -> launch(app)); + tile.setOnLongClickListener( + v -> { + appActions(app); + return true; + }); + index++; + } + if (visibleApps.isEmpty()) { + TextView empty = chip("No visible apps · Open all apps", v -> showAllApps()); + appsContainer.addView(empty, new LinearLayout.LayoutParams(-1, d(70))); + } + appCount.setText(visibleApps.size() + " installed"); + if (!tiles.isEmpty()) + settingsButton.setNextFocusDownId(tiles.values().iterator().next().getId()); + String restore = + tiles.containsKey(selected) + ? selected + : (visibleApps.isEmpty() ? "" : visibleApps.get(0).pkg); + AppTile target = tiles.get(restore); + if (target != null) { + target.requestFocus(); + updateHero(findApp(restore)); + } + reloadIcons(); + } + + private AppRepository.App findApp(String pkg) { + for (AppRepository.App a : allApps) if (a.pkg.equals(pkg)) return a; + return null; + } + + private void reloadIcons() { + int g = generation; + int ig = iconGeneration; + for (AppRepository.App a : visibleApps) { + final AppTile t = tiles.get(a.pkg); + work.execute( + () -> { + if (!foreground || g != generation || ig != iconGeneration) return; + Bitmap b = repository.icon(a); + handler.post( + () -> { + if (foreground && g == generation && tiles.get(a.pkg) == t) t.bitmap(b); + }); + }); + } + } + + private void updateHero(AppRepository.App a) { + if (a == null) return; + artGeneration++; + scene.setMediaArt(null); + String p = a.pkg; + String title = a.label; + String body = "Your next favorite moment is one click away."; + String tag = "READY WHEN YOU ARE"; + if (p.contains("plex") || p.contains("plezy")) { + title = "Your library.\nYour kind of night."; + body = "Pick up a story. Find your next obsession."; + tag = a.label.toUpperCase(Locale.getDefault()) + " / YOUR LIBRARY"; + } else if (p.contains("spotify")) { + title = "Set the mood."; + body = "A soundtrack for whatever comes next."; + tag = "SPOTIFY / LISTEN"; + } else if (p.contains("limelight") || p.contains("steam")) { + title = "A bigger\nway to play."; + body = "Your games. The best seat in the house."; + tag = a.label.toUpperCase(Locale.getDefault()) + " / PLAY"; + } else if (p.contains("youtube") || p.contains("smarttube")) { + title = "Follow your\ncuriosity."; + body = "The creators, music, and moments you love."; + tag = a.label.toUpperCase(Locale.getDefault()) + " / DISCOVER"; + } else if (p.contains("netflix") + || p.contains("disney") + || p.contains("amazon") + || p.contains("hulu") + || p.contains("crunchy")) { + title = "Stay for\none more."; + body = "Make tonight a good story."; + tag = a.label.toUpperCase(Locale.getDefault()) + " / WATCH"; + } else if (p.contains("twitch")) { + title = "Be there\nfor the moment."; + body = "Your favorite communities, live."; + tag = a.label.toUpperCase(Locale.getDefault()) + " / LIVE"; + } + eyebrow.setText(tag); + headline.setText(title); + description.setText(body); + openHint.setText("● OK Open " + a.label); + 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(); + } + + private void launch(AppRepository.App a) { + if (a.component.getPackageName().equals("com.spocky.projengmenu")) { + fallback(); + return; + } + try { + Intent i = + new Intent(Intent.ACTION_MAIN) + .addCategory(Intent.CATEGORY_LAUNCHER) + .setComponent(a.component) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); + startActivity(i); + } catch (Exception e) { + toast("Unable to open " + a.label); + } + } + + private void fallback() { + // Wait for the private router process to allow this explicit fallback launch. + sendOrderedBroadcast( + new Intent(this, HomeControlReceiver.class).setAction(HomeControlReceiver.FALLBACK), + null, + new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + openProjectivy(); + } + }, + handler, + Activity.RESULT_OK, + null, + null); + } + + private void openProjectivy() { + try { + Intent i = getPackageManager().getLeanbackLaunchIntentForPackage("com.spocky.projengmenu"); + if (i == null) i = getPackageManager().getLaunchIntentForPackage("com.spocky.projengmenu"); + if (i != null) startActivity(i); + else toast("Projectivy is not available"); + } catch (Exception e) { + toast("Unable to open Projectivy"); + } + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + setIntent(intent); + if (intent.hasCategory(Intent.CATEGORY_HOME)) { + refreshHomeSettings = false; + dismiss(); + stopSaver(true); + scroll.animateToY(0, motion()); + if (!tiles.isEmpty()) tiles.values().iterator().next().requestFocus(); + } + } + + private void toast(String text) { + Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); + } + + @Override + public boolean onKeyDown(int key, KeyEvent e) { + if (key == KeyEvent.KEYCODE_MENU || key == KeyEvent.KEYCODE_SETTINGS) { + if (e.getRepeatCount() == 0) showSettings(); + return true; + } + return super.onKeyDown(key, e); + } + + @Override + public void onBackPressed() { + if (saver != null) { + stopSaver(true); + return; + } + if (scroll.getScrollY() > d(30)) { + scroll.animateToY(0, motion()); + if (!tiles.isEmpty()) tiles.values().iterator().next().requestFocus(); + } + } + + private LinearLayout panel(String title, String subtitle) { + if (currentDialog != null) currentDialog.dismiss(); + Dialog dialog = new Dialog(this); + currentDialog = dialog; + LinearLayout outer = column(); + outer.setPadding(d(24), d(24), d(24), d(18)); + outer.setBackground(Ui.round(0xFA131D2D, d(22))); + TextView heading = Ui.text(this, title, 24, Ui.WHITE); + Ui.medium(heading); + outer.addView(heading, new LinearLayout.LayoutParams(-1, -2)); + if (subtitle != null) { + TextView sub = Ui.text(this, subtitle, 12, Ui.MUTED); + sub.setLineSpacing(d(3), 1); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, -2); + lp.topMargin = d(9); + lp.bottomMargin = d(16); + outer.addView(sub, lp); + } + ScrollView sc = new ScrollView(this); + sc.setVerticalScrollBarEnabled(false); + sc.setFillViewport(false); + LinearLayout actions = column(); + actions.setPadding(d(2), d(2), d(2), d(4)); + sc.addView(actions); + outer.addView(sc, new LinearLayout.LayoutParams(-1, 0, 1)); + dialog.setContentView(outer); + Window window = dialog.getWindow(); + if (window != null) { + window.setBackgroundDrawableResource(android.R.color.transparent); + window.setDimAmount(.64f); + window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); + window.setLayout(d(470), d(440)); + } + dialog.setOnDismissListener( + v -> { + if (currentDialog == dialog) { + currentDialog = null; + resetSaverTimer(); + } + }); + handler.removeCallbacks(idleSaver); + dialog.show(); + if (window != null) window.setLayout(d(470), d(440)); + return actions; + } + + private TextView action(LinearLayout panel, String title, String detail, Runnable run) { + TextView t = Ui.text(this, title + (detail == null ? "" : "\n" + detail), 14, Ui.WHITE); + t.setTextColor(Ui.textColors()); + t.setLineSpacing(d(5), 1); + t.setGravity(Gravity.CENTER_VERTICAL); + t.setPadding(d(16), d(12), d(16), d(12)); + t.setFocusable(true); + t.setClickable(true); + Ui.glass(t, 12); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, -2); + lp.bottomMargin = d(7); + panel.addView(t, lp); + t.setOnClickListener(v -> run.run()); + if (panel.getChildCount() == 1) t.requestFocus(); + return t; + } + + private void dismiss() { + if (currentDialog != null) currentDialog.dismiss(); + } + + private void showSettings() { + LinearLayout p = panel("Make it yours", "A quieter home for everything you love."); + action(p, "Appearance", "Wallpaper, spacing, and atmosphere", this::appearance); + action( + p, + "Screensaver", + "Idle timeout, art, scenic photos, and nature video", + this::screensaverSettings); + action(p, "App library", "Reorder, hide, or restore your apps", this::showAllApps); + action( + p, "Default launcher", "Home button routing and fallback", this::defaultLauncherSettings); + action( + p, + "Plex media rows", + prefs.getBoolean("media", false) + ? "Enabled · Continue Watching & Recently Added" + : "Optional · Connect your own library", + this::plexSettings); + action( + p, + "Open Android settings", + null, + () -> { + dismiss(); + try { + startActivity(new Intent(Settings.ACTION_SETTINGS)); + } catch (Exception e) { + toast("Settings unavailable"); + } + }); + action( + p, + "Open Projectivy", + "Your existing launcher is always available", + () -> { + dismiss(); + fallback(); + }); + action(p, "About Luma", "Version 1.0 · Native Android TV", this::about); + action(p, "Done", null, this::dismiss); + } + + private boolean homeOverrideEnabled() { + String enabled = + Settings.Secure.getString( + getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); + ComponentName service = new ComponentName(this, LumaHomeService.class); + if (enabled != null) + for (String entry : enabled.split(":")) { + if (service.equals(ComponentName.unflattenFromString(entry))) return true; + } + return false; + } + + private void defaultLauncherSettings() { + boolean enabled = homeOverrideEnabled(); + Intent home = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME); + android.content.pm.ResolveInfo resolved = getPackageManager().resolveActivity(home, 0); + boolean nativeHome = + resolved != null + && resolved.activityInfo != null + && getPackageName().equals(resolved.activityInfo.packageName); + LinearLayout p = + panel( + "Default launcher", + "System Home: " + + (nativeHome ? "Luma" : "Managed by this TV") + + "\nHome button override: " + + (enabled ? "On" : "Off") + + "\nProjectivy stays installed and available as your fallback."); + action( + p, + "Choose default Home app", + "Select Luma in Android's Home app chooser", + () -> { + refreshHomeSettings = true; + dismiss(); + try { + if (Build.VERSION.SDK_INT >= 29) { + android.app.role.RoleManager roles = + getSystemService(android.app.role.RoleManager.class); + if (roles != null + && roles.isRoleAvailable(android.app.role.RoleManager.ROLE_HOME) + && !roles.isRoleHeld(android.app.role.RoleManager.ROLE_HOME)) { + startActivityForResult( + roles.createRequestRoleIntent(android.app.role.RoleManager.ROLE_HOME), 41); + return; + } + } + startActivity(new Intent(Settings.ACTION_HOME_SETTINGS)); + } catch (RuntimeException e) { + refreshHomeSettings = false; + defaultLauncherSettings(); + toast("This TV manages its Home app. Use the Home button override below."); + } + }); + action( + p, + "Home button override · " + (enabled ? "On" : "Off"), + enabled + ? "Turn off Luma's accessibility Home routing" + : "Enable Luma Home button in Android Accessibility settings", + () -> { + if (enabled) { + sendOrderedBroadcast( + new Intent(this, HomeControlReceiver.class).setAction(HomeControlReceiver.DISABLE), + null, + new BroadcastReceiver() { + @Override + public void onReceive(Context c, Intent i) { + handler.postDelayed(() -> defaultLauncherSettings(), 350); + } + }, + handler, + Activity.RESULT_OK, + null, + null); + } else { + LinearLayout help = + panel( + "Enable Home routing", + "In Android Accessibility, enable Luma Home button.\n\n" + + "In Projectivy settings → General, turn off Override current launcher to" + + " avoid competing Home handlers. Projectivy itself stays available."); + action( + help, + "Open Accessibility settings", + null, + () -> { + refreshHomeSettings = true; + dismiss(); + try { + startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)); + } catch (RuntimeException e) { + refreshHomeSettings = false; + defaultLauncherSettings(); + toast("Open Android settings → Accessibility → Luma Home button"); + } + }); + action(help, "Back", null, this::defaultLauncherSettings); + } + }); + action( + p, + "Open Projectivy", + "Use your fallback without turning Luma off", + () -> { + dismiss(); + fallback(); + }); + action(p, "Back", null, this::showSettings); + } + + private void appearance() { + LinearLayout p = panel("Appearance", "Small details. Your atmosphere."); + action( + p, + "Banner · " + + (bannerMode().equals("dynamic") + ? "Dynamic" + : bannerMode().equals("minimal") ? "Minimal" : "Artwork only"), + "Control the featured area above your apps", + this::bannerPicker); + action( + p, + "App labels · " + labelName(prefs.getString("labels", "focused")), + null, + this::labelPicker); + action( + p, + "App section text · " + on(prefs.getBoolean("sectionText", false)), + "Your apps, installed count, and customization hint", + () -> { + prefs.edit().putBoolean("sectionText", !prefs.getBoolean("sectionText", false)).apply(); + updateSectionText(); + appearance(); + }); + String s = prefs.getString("scene", "alpine"); + action( + p, + "Wallpaper · " + + (s.equals("alpine") ? "Alpine" : s.equals("aurora") ? "Aurora" : "Midnight"), + null, + () -> scenePicker()); + action( + p, + "Rotate scenes · " + on(prefs.getBoolean("rotate", false)), + "Changes every 90 seconds while Luma is visible", + () -> { + prefs.edit().putBoolean("rotate", !prefs.getBoolean("rotate", false)).apply(); + handler.removeCallbacks(rotateScene); + if (prefs.getBoolean("rotate", false)) handler.postDelayed(rotateScene, 90000); + else configureScene(); + appearance(); + }); + action( + p, + "App spacing · " + columns() + " columns", + null, + () -> { + LinearLayout q = panel("App spacing", null); + for (int n : new int[] {5, 6, 7}) + action( + q, + n == 5 + ? "Spacious · 5 columns" + : n == 6 ? "Balanced · 6 columns" : "Compact · 7 columns", + null, + () -> { + prefs.edit().putInt("columns", n).apply(); + renderApps(); + appearance(); + }); + }); + action( + p, + "Background dimming · " + prefs.getInt("darkness", 20) + "%", + null, + () -> { + LinearLayout q = panel("Background dimming", null); + for (int n : new int[] {0, 20, 40, 60}) + action( + q, + n + "%", + null, + () -> { + prefs.edit().putInt("darkness", n).apply(); + configureScene(); + appearance(); + }); + }); + action( + p, + "Accent color", + prefs.getInt("accent", 0) == 0 ? "Follows the selected app" : "Custom color", + () -> { + LinearLayout q = panel("Accent color", null); + String[] names = {"Follow app", "Ocean", "Iris", "Amber"}; + int[] colors = {0, 0xFF1E5266, 0xFF513866, 0xFF634627}; + for (int i = 0; i < 4; i++) { + final int c = colors[i]; + action( + q, + names[i], + null, + () -> { + prefs.edit().putInt("accent", c).apply(); + updateHero(findApp(selected)); + appearance(); + }); + } + }); + action( + p, + "Focus animations · " + on(motion()), + null, + () -> { + prefs.edit().putBoolean("motion", !motion()).apply(); + for (AppTile t : tiles.values()) t.setMotion(motion()); + for (AppTile t : mediaTiles) t.setMotion(motion()); + scene.setMotion(motion()); + appearance(); + }); + action( + p, + "Clock · " + on(prefs.getBoolean("clock", true)), + null, + () -> { + prefs.edit().putBoolean("clock", !prefs.getBoolean("clock", true)).apply(); + updateClock(); + appearance(); + }); + action(p, "Back", null, this::showSettings); + } + + private void bannerPicker() { + LinearLayout p = panel("Featured area", "Choose how much room to give your apps."); + String[] values = {"dynamic", "artwork", "minimal"}; + String[] titles = {"Dynamic", "Artwork only", "Minimal"}; + String[] details = { + "Artwork, app headlines, and descriptions", + "Cinematic artwork with the original spacious layout", + "Remove the featured area and raise the grid" + }; + for (int i = 0; i < values.length; i++) { + final String value = values[i]; + action( + p, + titles[i], + details[i], + () -> { + prefs.edit().putString("bannerMode", value).apply(); + updateFeaturedText(); + scroll.animateToY(0, motion()); + appearance(); + }); + } + } + + private String labelName(String mode) { + return mode.equals("always") ? "Always" : mode.equals("never") ? "Never" : "Focused only"; + } + + private void labelPicker() { + LinearLayout p = + panel("App labels", "Names remain available to accessibility services in every mode."); + for (String mode : new String[] {"always", "focused", "never"}) + action( + p, + labelName(mode), + null, + () -> { + prefs.edit().putString("labels", mode).apply(); + renderApps(); + appearance(); + }); + } + + private String on(boolean enabled) { + return enabled ? "On" : "Off"; + } + + private void scenePicker() { + LinearLayout p = panel("Choose your atmosphere", null); + String[] names = { + "Alpine · Cinematic mountain light", "Aurora · Soft teal & indigo", "Midnight · Quiet blue" + }; + String[] values = {"alpine", "aurora", "midnight"}; + for (int i = 0; i < 3; i++) { + final String v = values[i]; + action( + p, + names[i], + null, + () -> { + prefs.edit().putString("scene", v).apply(); + scene.setMediaArt(null); + configureScene(); + appearance(); + }); + } + } + + private void about() { + LinearLayout p = panel("Luma", "Designed for the living room. Built to stay light."); + TextView t = + Ui.text( + this, + "No ads or analytics." + + " Artwork and network requests stop when another app opens. Image caches are" + + " bounded and cleared when Luma leaves the screen.\n\n" + + "Menu opens settings. Hold OK on an app to customize it. Back stays on Luma." + + " Open Projectivy from Settings or its app tile.\n\n" + + "Manage the Home button in Settings → Default launcher.", + 13, + Ui.MUTED); + t.setLineSpacing(d(5), 1); + p.addView(t); + action(p, "Back", null, this::showSettings); + } + + private void showAllApps() { + LinearLayout p = + panel("App library", "Select an app to launch, move, or change its visibility."); + Set h = hidden(); + for (AppRepository.App a : allApps) + action(p, a.label + (h.contains(a.pkg) ? " · Hidden" : ""), null, () -> appActions(a)); + action(p, "Back", null, this::showSettings); + } + + private void appActions(AppRepository.App app) { + LinearLayout p = panel(app.label, "Make space for your favorites."); + action( + p, + "Open", + null, + () -> { + dismiss(); + launch(app); + }); + action( + p, + "Move to front", + null, + () -> { + List order = new ArrayList<>(); + order.add(app.pkg); + for (AppRepository.App a : visibleApps) if (!a.pkg.equals(app.pkg)) order.add(a.pkg); + saveOrder(order); + selected = app.pkg; + renderApps(); + dismiss(); + }); + if (tiles.containsKey(app.pkg)) + action( + p, + "Move in grid", + "Use left / right / up / down; OK saves; Back cancels", + () -> { + dismiss(); + beginMove(app); + }); + boolean h = hidden().contains(app.pkg); + action( + p, + h ? "Show on home" : "Hide from home", + null, + () -> { + Set set = hidden(); + if (h) set.remove(app.pkg); + else set.add(app.pkg); + prefs.edit().putStringSet("hidden", set).apply(); + renderApps(); + dismiss(); + }); + action( + p, + "Android app info", + null, + () -> { + dismiss(); + startActivity( + new Intent( + Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + app.pkg))); + }); + action(p, "Done", null, this::dismiss); + } + + private void saveOrder(List order) { + prefs.edit().putString("order", android.text.TextUtils.join(",", order)).apply(); + } + + private List moveOriginal; + + private void beginMove(AppRepository.App app) { + moving = true; + updateFeaturedText(); + selected = app.pkg; + moveOriginal = new ArrayList<>(); + for (AppRepository.App a : visibleApps) moveOriginal.add(a.pkg); + openHint.setText("↔ ↕ Move " + app.label + " · OK saves · Back cancels"); + toast("Move with arrows · OK saves · Back cancels"); + } + + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + if (saverWakePending) { + if (event.getAction() == KeyEvent.ACTION_UP) saverWakePending = false; + return true; + } + if (saver != null) { + if (event.getAction() == KeyEvent.ACTION_DOWN) { + stopSaver(true); + saverWakePending = true; + } + return true; + } + if (moving) { + int key = event.getKeyCode(); + if (event.getAction() == KeyEvent.ACTION_DOWN) { + if (key == KeyEvent.KEYCODE_BACK) { + saveOrder(moveOriginal); + moving = false; + renderApps(); + return true; + } + if (key == KeyEvent.KEYCODE_DPAD_CENTER || key == KeyEvent.KEYCODE_ENTER) { + moving = false; + updateHero(findApp(selected)); + toast("App order saved"); + return true; + } + int index = -1; + for (int i = 0; i < visibleApps.size(); i++) + if (visibleApps.get(i).pkg.equals(selected)) index = i; + int delta = + key == KeyEvent.KEYCODE_DPAD_LEFT + ? -1 + : key == KeyEvent.KEYCODE_DPAD_RIGHT + ? 1 + : key == KeyEvent.KEYCODE_DPAD_UP + ? -columns() + : key == KeyEvent.KEYCODE_DPAD_DOWN ? columns() : 0; + if (delta != 0 && index >= 0) { + int next = Math.max(0, Math.min(visibleApps.size() - 1, index + delta)); + Collections.swap(visibleApps, index, next); + List order = new ArrayList<>(); + for (AppRepository.App a : visibleApps) order.add(a.pkg); + saveOrder(order); + renderApps(); + openHint.setText( + "↔ ↕ Move " + + findApp(selected).label + + " · OK saves · Back cancels"); + return true; + } + } + return true; + } + return super.dispatchKeyEvent(event); + } + + private void plexSettings() { + LinearLayout p = panel("Your Plex library", "Optional rows from your own Plex Media Server."); + action(p, "Connect with Plex", "Use a short code at plex.tv/link", this::pairPlex); + action(p, "Enter server manually", "Server URL and Plex token", this::manualPlex); + action( + p, + "Media rows · " + on(prefs.getBoolean("media", false)), + null, + () -> { + prefs.edit().putBoolean("media", !prefs.getBoolean("media", false)).apply(); + loadMedia(); + plexSettings(); + }); + action( + p, + "Refresh library", + null, + () -> { + dismiss(); + loadMedia(); + }); + if (plex.configured()) + action( + p, + "Disconnect Plex", + "Removes saved credentials from this device", + () -> { + plex.disconnect(); + plexFeatured = null; + scene.setMediaArt(null); + prefs.edit().putBoolean("media", false).apply(); + mediaContainer.removeAllViews(); + plexSettings(); + }); + action(p, "Back", null, this::showSettings); + } + + private void manualPlex() { + LinearLayout p = + panel( + "Connect your server", + "Use HTTPS, or a local HTTP address. Credentials stay on this TV."); + EditText url = new EditText(this); + url.setTextColor(Ui.WHITE); + url.setTextSize(14); + url.setSingleLine(true); + url.setHint("https://your-server:32400"); + url.setHintTextColor(Ui.MUTED); + url.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); + url.setText(plex.server()); + p.addView(url, new LinearLayout.LayoutParams(-1, d(50))); + EditText token = new EditText(this); + token.setTextColor(Ui.WHITE); + token.setTextSize(14); + token.setSingleLine(true); + token.setHint("Plex token"); + token.setHintTextColor(Ui.MUTED); + token.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + p.addView(token, new LinearLayout.LayoutParams(-1, d(50))); + TextView status = Ui.text(this, "", 12, Ui.GOLD); + p.addView(status); + Dialog dialog = currentDialog; + action( + p, + "Connect", + null, + () -> { + String u = url.getText().toString().trim(), t = token.getText().toString().trim(); + status.setText("Checking server…"); + network.execute( + () -> { + try { + plex.connect(u, t); + handler.post( + () -> { + if (currentDialog != dialog || !foreground) return; + prefs.edit().putBoolean("media", true).apply(); + dismiss(); + loadMedia(); + toast("Plex connected"); + }); + } catch (Exception e) { + handler.post( + () -> { + if (currentDialog == dialog) + status.setText( + "Could not connect. Check the address, token, and server access."); + }); + } + }); + }); + action(p, "Cancel", null, this::plexSettings); + url.requestFocus(); + } + + private void pairPlex() { + LinearLayout p = + panel("Connect with Plex", "On your phone, visit plex.tv/link and enter this code."); + TextView code = Ui.text(this, "Getting a code…", 32, Ui.GOLD); + code.setGravity(Gravity.CENTER); + p.addView(code, new LinearLayout.LayoutParams(-1, d(78))); + TextView status = Ui.text(this, "", 12, Ui.MUTED); + status.setGravity(Gravity.CENTER); + p.addView(status); + Dialog dialog = currentDialog; + action(p, "Cancel", null, this::plexSettings); + network.execute( + () -> { + try { + PlexClient.Pin pin = plex.createPin(); + handler.post( + () -> { + if (currentDialog == dialog) code.setText(pin.code); + }); + long end = System.currentTimeMillis() + Math.min(pin.expires, 300) * 1000L; + while (foreground && currentDialog == dialog && System.currentTimeMillis() < end) { + String auth = plex.checkPin(pin); + if (auth != null) { + List servers = plex.servers(auth); + handler.post( + () -> { + if (currentDialog != dialog || !foreground) return; + chooseServer(servers); + }); + return; + } + Thread.sleep(3000); + } + handler.post( + () -> { + if (currentDialog == dialog) + status.setText("Code expired. Close this panel and try again."); + }); + } catch (Exception e) { + handler.post( + () -> { + if (currentDialog == dialog) { + code.setText("Plex is unavailable"); + status.setText("Try again, or enter your server manually."); + } + }); + } + }); + } + + private void chooseServer(List servers) { + LinearLayout p = + panel("Choose a Plex server", "Luma checks available connections before saving."); + if (servers.isEmpty()) + action( + p, + "No servers found", + "Your Plex account needs access to a Media Server", + this::plexSettings); + Dialog dialog = currentDialog; + for (PlexClient.Server s : servers) + action( + p, + s.name, + null, + () -> { + toast("Connecting to " + s.name); + network.execute( + () -> { + try { + plex.connect(s); + handler.post( + () -> { + if (currentDialog != dialog || !foreground) return; + prefs.edit().putBoolean("media", true).apply(); + dismiss(); + loadMedia(); + toast("Plex connected"); + }); + } catch (Exception e) { + handler.post(() -> toast("Server unavailable. Check that it is online.")); + } + }); + }); + action(p, "Cancel", null, this::plexSettings); + } + + private void loadMedia() { + mediaContainer.removeAllViews(); + mediaTiles.clear(); + if (!prefs.getBoolean("media", false) || !plex.configured() || !foreground) return; + int g = generation; + network.execute( + () -> { + try { + PlexClient.Library library = plex.library(); + handler.post( + () -> { + if (!foreground || g != generation) return; + mediaContainer.removeAllViews(); + mediaTiles.clear(); + plexFeatured = + !library.continueWatching.isEmpty() + ? library.continueWatching.get(0) + : !library.recent.isEmpty() ? library.recent.get(0) : null; + AppRepository.App current = findApp(selected); + if (plexFeatured != null + && current != null + && (current.pkg.contains("plex") || current.pkg.contains("plezy"))) + featurePlexArtwork(); + addMediaRow("Continue watching", library.continueWatching, g); + addMediaRow("Recently added", library.recent, g); + if (library.continueWatching.isEmpty() && library.recent.isEmpty()) { + TextView empty = + Ui.text(this, "Your Plex library has no items to display.", 12, Ui.MUTED); + mediaContainer.addView(empty); + } + }); + } catch (Exception e) { + handler.post( + () -> { + if (!foreground || g != generation) return; + TextView retry = chip("Plex unavailable · Select to retry", v -> loadMedia()); + mediaContainer.addView(retry, new LinearLayout.LayoutParams(-1, d(45))); + }); + } + }); + } + + private void addMediaRow(String title, List items, int g) { + if (items.isEmpty()) return; + TextView heading = Ui.text(this, title, 18, Ui.WHITE); + Ui.medium(heading); + LinearLayout.LayoutParams h = new LinearLayout.LayoutParams(-1, d(36)); + h.topMargin = d(12); + mediaContainer.addView(heading, h); + HorizontalScrollView horizontal = new HorizontalScrollView(this); + horizontal.setHorizontalScrollBarEnabled(false); + horizontal.setClipChildren(false); + horizontal.setClipToPadding(false); + horizontal.setOverScrollMode(View.OVER_SCROLL_NEVER); + LinearLayout row = new LinearLayout(this); + row.setClipChildren(false); + row.setPadding(d(4), d(5), d(4), d(8)); + horizontal.addView(row); + mediaContainer.addView(horizontal, new LinearLayout.LayoutParams(-1, -2)); + for (PlexClient.Media m : items) { + AppTile tile = new AppTile(this, m.title, 170, false); + tile.setMotion(motion()); + tile.setAccent(Ui.GOLD); + tile.progress(m.progress); + tile.setContentDescription( + m.title + + (m.progress > 0 ? ", " + Math.round(m.progress * 100) + " percent watched" : "")); + row.addView(tile, new LinearLayout.LayoutParams(d(170), -2)); + mediaTiles.add(tile); + tile.setOnClickListener(v -> openMedia(m)); + tile.onFocused( + f -> { + if (f) { + eyebrow.setText("PLEX / " + title.toUpperCase(Locale.getDefault())); + headline.setText(m.title); + description.setText(m.subtitle); + openHint.setText("● OK Open in Plex"); + int art = ++artGeneration; + handler.postDelayed( + () -> { + if (!foreground || g != generation || art != artGeneration) return; + network.execute( + () -> { + if (!foreground || g != generation || art != artGeneration) return; + Bitmap b = plex.image(m.art, true); + handler.post( + () -> { + if (foreground && g == generation && art == artGeneration) + scene.setMediaArt(b); + }); + }); + }, + 180); + } + }); + network.execute( + () -> { + if (!foreground || g != generation) return; + Bitmap b = plex.image(m.thumb, false); + handler.post( + () -> { + if (foreground && g == generation && mediaTiles.contains(tile)) tile.bitmap(b); + }); + }); + } + } + + private void featurePlexArtwork() { + if (plexFeatured == null || !foreground) return; + final String path = plexFeatured.art; + final int g = generation, art = ++artGeneration; + handler.postDelayed( + () -> { + if (!foreground || g != generation || art != artGeneration) return; + network.execute( + () -> { + if (!foreground || g != generation || art != artGeneration) return; + Bitmap bitmap = plex.image(path, true); + handler.post( + () -> { + if (foreground && g == generation && art == artGeneration) + scene.setMediaArt(bitmap); + }); + }); + }, + 180); + } + + @Override + public void onUserInteraction() { + super.onUserInteraction(); + if (saver == null) resetSaverTimer(); + } + + @Override + public boolean dispatchTouchEvent(android.view.MotionEvent event) { + if (saver != null) { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) stopSaver(true); + return true; + } + return super.dispatchTouchEvent(event); + } + + private void resetSaverTimer() { + handler.removeCallbacks(idleSaver); + int minutes = prefs.getInt("saverTimeout", 10); + if (foreground && (minutes > 0 || saver != null)) + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + if (foreground && saver == null && currentDialog == null && minutes > 0) + handler.postDelayed(idleSaver, minutes * 60000L); + } + + private void startSaver() { + if (!foreground || saver != null || currentDialog != null || moving) return; + handler.removeCallbacks(idleSaver); + handler.removeCallbacks(minuteTick); + handler.removeCallbacks(rotateScene); + scene.stopAnimations(); + scroll.stopAnimation(); + saver = new SaverView(this); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + root.addView(saver, new FrameLayout.LayoutParams(-1, -1)); + saver.requestFocus(); + } + + private void stopSaver(boolean resume) { + if (saver == null) return; + saver.stop(); + root.removeView(saver); + saver = null; + getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + if (resume && foreground) { + AppTile tile = tiles.get(selected); + if (tile != null) tile.requestFocus(); + handler.removeCallbacks(minuteTick); + handler.post(minuteTick); + handler.removeCallbacks(rotateScene); + if (prefs.getBoolean("rotate", false)) handler.postDelayed(rotateScene, 90000); + resetSaverTimer(); + } + } + + private void screensaverSettings() { + LinearLayout p = + panel("Screensaver", "Starts only while Luma is on screen. Any remote button wakes it."); + action( + p, + "Preview now", + null, + () -> { + dismiss(); + handler.post(this::startSaver); + }); + int minutes = prefs.getInt("saverTimeout", 10); + action( + p, + "Idle timeout · " + (minutes == 0 ? "Off" : minutes + " min"), + null, + () -> { + LinearLayout choices = + panel("Idle timeout", "Other apps keep their own playback and idle behavior."); + for (int n : new int[] {0, 1, 3, 5, 10, 15, 30, 60}) + action( + choices, + n == 0 ? "Off" : n + " min", + null, + () -> { + prefs.edit().putInt("saverTimeout", n).apply(); + screensaverSettings(); + }); + }); + String mode = prefs.getString("saverMode", "scenic"); + action( + p, + "Mode · " + saverModeName(mode), + null, + () -> { + LinearLayout choices = + panel( + "Screensaver mode", + "Photos work offline. Nature video uses your saved clip or stream."); + String[] modes = {"scenic", "art", "video"}; + String[] details = { + "Earth, space, and mountain scenes", + "Public-domain masterpieces from The Met", + "Loop a local nature video, or use a direct stream" + }; + for (int i = 0; i < modes.length; i++) { + final String value = modes[i]; + action( + choices, + saverModeName(value), + details[i], + () -> { + prefs.edit().putString("saverMode", value).apply(); + screensaverSettings(); + }); + } + }); + action( + p, + "Photo duration · " + prefs.getInt("saverInterval", 30) + " sec", + null, + () -> { + LinearLayout choices = panel("Photo duration", null); + for (int n : new int[] {15, 30, 60, 120, 300}) + action( + choices, + n + " sec", + null, + () -> { + prefs.edit().putInt("saverInterval", n).apply(); + screensaverSettings(); + }); + }); + saverToggle(p, "Shuffle photos", "saverShuffle", true); + saverToggle(p, "Show artwork captions", "saverCaptions", true); + saverToggle(p, "Show clock", "saverClock", false); + action( + p, + "Photo framing · " + prefs.getString("saverFraming", "auto"), + null, + () -> { + LinearLayout choices = + panel( + "Photo framing", + "Auto preserves complete paintings and fills the screen for scenic photos."); + for (String value : new String[] {"auto", "fit", "fill"}) + action( + choices, + value.equals("auto") + ? "Auto" + : value.equals("fit") ? "Fit complete image" : "Fill screen", + null, + () -> { + prefs.edit().putString("saverFraming", value).apply(); + screensaverSettings(); + }); + }); + action( + p, + "Screensaver dimming · " + prefs.getInt("saverDim", 0) + "%", + null, + () -> { + LinearLayout choices = panel("Screensaver dimming", null); + for (int n : new int[] {0, 10, 25, 40}) + action( + choices, + n + "%", + null, + () -> { + prefs.edit().putInt("saverDim", n).apply(); + screensaverSettings(); + }); + }); + action( + p, + "Nature video", + saverMedia.videoBytes() > 0 + ? "Offline video saved · " + (saverMedia.videoBytes() / 1024 / 1024) + " MB" + : "Download a nature loop or choose your own source", + this::videoSettings); + action( + p, + "Download more artwork", + "Six Met works · maximum 12 MB · public domain only", + () -> downloadSaverMedia(false, null, null)); + action(p, "Back", null, this::showSettings); + } + + private String saverModeName(String mode) { + return mode.equals("art") ? "Art gallery" : mode.equals("video") ? "Nature video" : "Scenic"; + } + + private void saverToggle(LinearLayout panel, String title, String key, boolean initial) { + action( + panel, + title + " · " + on(prefs.getBoolean(key, initial)), + null, + () -> { + prefs.edit().putBoolean(key, !prefs.getBoolean(key, initial)).apply(); + screensaverSettings(); + }); + } + + private void videoSettings() { + LinearLayout p = + panel( + "Nature video", + "Platform video playback. Muted by default. 720p/1080p works well on this device."); + if (saverMedia.videoBytes() > 0) + action( + p, + "Use downloaded video", + (saverMedia.videoBytes() / 1024 / 1024) + " MB saved on this TV", + () -> { + prefs + .edit() + .putString("saverVideoSource", "local") + .putString("saverMode", "video") + .apply(); + screensaverSettings(); + }); + action( + p, + "Download bird nature loop", + "Steller’s Jay · NPS · 85 sec · 720p · about 40 MB", + () -> + downloadSaverMedia( + true, SaverMedia.NATURE_URL, "Steller’s Jay · Mount Rainier · NPS, public domain")); + action( + p, + "Use a video URL", + "Direct MP4 or HLS stream; webpage links cannot play", + this::videoUrl); + action( + p, + "Choose a local video file", + null, + () -> { + dismiss(); + try { + startActivityForResult( + new Intent(Intent.ACTION_OPEN_DOCUMENT) + .setType("video/*") + .addCategory(Intent.CATEGORY_OPENABLE) + .addFlags( + Intent.FLAG_GRANT_READ_URI_PERMISSION + | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION), + 41); + } catch (Exception e) { + toast("No file picker available. Use a direct video URL instead."); + screensaverSettings(); + } + }); + action( + p, + "Video audio · " + on(prefs.getBoolean("saverVideoAudio", false)), + null, + () -> { + prefs + .edit() + .putBoolean("saverVideoAudio", !prefs.getBoolean("saverVideoAudio", false)) + .apply(); + videoSettings(); + }); + if (saverMedia.videoBytes() > 0) + action( + p, + "Remove downloaded video", + "Frees " + (saverMedia.videoBytes() / 1024 / 1024) + " MB", + () -> { + saverMedia.videoFile().delete(); + if (prefs.getString("saverVideoSource", "local").equals("local")) + prefs.edit().putString("saverMode", "scenic").apply(); + videoSettings(); + }); + action(p, "Back", null, this::screensaverSettings); + } + + private void videoUrl() { + LinearLayout p = + panel( + "Video source", + "Use a direct MP4 or HLS URL. Offline downloads require a video file, up to 250 MB."); + EditText url = new EditText(this); + url.setTextColor(Ui.WHITE); + url.setTextSize(13); + url.setSingleLine(true); + url.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); + url.setHintTextColor(Ui.MUTED); + url.setHint("https://…/nature.mp4"); + url.setText(prefs.getString("saverVideoUrl", "")); + p.addView(url, new LinearLayout.LayoutParams(-1, d(50))); + TextView status = Ui.text(this, "", 12, Ui.GOLD); + p.addView(status); + Dialog dialog = currentDialog; + action( + p, + "Stream this URL", + "MP4 or HLS; no offline copy", + () -> { + String value = url.getText().toString().trim(); + status.setText("Checking address…"); + network.execute( + () -> { + try { + SaverMedia.validateUrl(value); + handler.post( + () -> { + if (!foreground || currentDialog != dialog) return; + prefs + .edit() + .putString("saverVideoUrl", value) + .putString("saverVideoSource", "stream") + .putString("saverMode", "video") + .apply(); + screensaverSettings(); + }); + } catch (Exception e) { + handler.post( + () -> { + if (currentDialog == dialog) + status.setText("Use HTTPS, or a local network HTTP address."); + }); + } + }); + }); + action( + p, + "Download for offline playback", + null, + () -> + downloadSaverMedia( + true, url.getText().toString().trim(), "Your downloaded nature video")); + action(p, "Cancel", null, this::videoSettings); + url.requestFocus(); + } + + private void downloadSaverMedia(boolean video, String url, String credit) { + LinearLayout p = + panel( + video ? "Saving your nature video" : "Building your art gallery", + "Keep this panel open. Leaving Luma cancels the download."); + TextView status = Ui.text(this, "Connecting…", 15, Ui.GOLD); + status.setPadding(0, d(18), 0, d(18)); + p.addView(status, new LinearLayout.LayoutParams(-1, -2)); + Dialog dialog = currentDialog; + int job = saverMedia.newJob(); + saverDownloading = true; + dialog.setOnDismissListener( + v -> { + saverMedia.cancel(); + if (currentDialog == dialog) { + currentDialog = null; + saverDownloading = false; + resetSaverTimer(); + } + }); + action( + p, + "Cancel", + null, + () -> { + saverMedia.cancel(); + screensaverSettings(); + }); + network.execute( + () -> { + SaverMedia.Progress progress = + message -> + handler.post( + () -> { + if (foreground && currentDialog == dialog) status.setText(message); + }); + try { + if (video) saverMedia.downloadVideo(url, job, progress); + else saverMedia.downloadArt(job, progress); + handler.post( + () -> { + if (!foreground || currentDialog != dialog) return; + saverDownloading = false; + if (video) + prefs + .edit() + .putString("saverVideoSource", "local") + .putString("saverVideoCredit", credit) + .putString("saverMode", "video") + .apply(); + toast(video ? "Nature video saved offline" : "Art gallery downloaded"); + screensaverSettings(); + }); + } catch (Exception e) { + handler.post( + () -> { + if (foreground && currentDialog == dialog) { + saverDownloading = false; + status.setText( + "Download stopped. " + + (e.getMessage() == null + ? "Check the source and try again." + : e.getMessage())); + } + }); + } + }); + } + + @Override + protected void onActivityResult(int request, int result, Intent data) { + super.onActivityResult(request, result, data); + if (request != 41 || result != RESULT_OK || data == null || data.getData() == null) return; + Uri uri = data.getData(); + try { + getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION); + String previous = prefs.getString("saverVideoUri", ""); + if (!previous.isEmpty() && !previous.equals(uri.toString())) + try { + getContentResolver() + .releasePersistableUriPermission( + Uri.parse(previous), Intent.FLAG_GRANT_READ_URI_PERMISSION); + } catch (Exception ignored) { + } + prefs + .edit() + .putString("saverVideoUri", uri.toString()) + .putString("saverVideoSource", "document") + .putString("saverMode", "video") + .apply(); + handler.post(this::screensaverSettings); + } catch (Exception e) { + toast("The file provider could not keep access to this video."); + } + } + + private void openMedia(PlexClient.Media m) { + try { + String key = "/library/metadata/" + m.key; + String type = + m.type.equals("movie") + ? "1" + : m.type.equals("show") ? "2" : m.type.equals("season") ? "3" : "4"; + Uri uri = + Uri.parse("plex://server/" + Uri.encode(plex.machine()) + "/com.plexapp.plugins.library") + .buildUpon() + .appendQueryParameter("key", key) + .appendQueryParameter("metadataType", type) + .build(); + Intent intent = + new Intent(Intent.ACTION_VIEW, uri) + .setPackage("com.plexapp.android") + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + } catch (Exception e) { + AppRepository.App a = findApp("com.plexapp.android"); + if (a != null) { + launch(a); + toast("Choose " + m.title + " in Plex"); + } else toast("Install Plex to open this title"); + } + } +} diff --git a/app/src/main/java/tv/luma/launcher/PlexClient.java b/app/src/main/java/tv/luma/launcher/PlexClient.java new file mode 100644 index 0000000..bf11668 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/PlexClient.java @@ -0,0 +1,385 @@ +package tv.luma.launcher; + +import android.content.*; +import android.graphics.*; +import android.net.Uri; +import android.security.keystore.*; +import android.util.Base64; +import android.util.LruCache; +import java.io.*; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.util.*; +import javax.crypto.*; +import javax.crypto.spec.GCMParameterSpec; +import org.json.*; + +/** Optional, read-only Plex client. No playback engine or background service. */ +final class PlexClient { + static final class Pin { + String code, id; + int expires; + } + + static final class Server { + String name, token; + final List urls = new ArrayList<>(); + } + + static final class Media { + String key, title, subtitle, thumb, art, type; + float progress; + } + + static final class Library { + final List continueWatching = new ArrayList<>(), recent = new ArrayList<>(); + } + + private final SharedPreferences prefs; + private final String clientId; + private volatile boolean cancelled; + private volatile HttpURLConnection active; + private final LruCache images = + new LruCache(3 * 1024 * 1024) { + protected int sizeOf(String k, Bitmap b) { + return b.getAllocationByteCount(); + } + }; + + PlexClient(Context c) { + prefs = c.getSharedPreferences("plex", Context.MODE_PRIVATE); + String id = prefs.getString("clientId", null); + if (id == null) { + id = UUID.randomUUID().toString(); + prefs.edit().putString("clientId", id).apply(); + } + clientId = id; + } + + void resume() { + cancelled = false; + } + + void cancel() { + cancelled = true; + HttpURLConnection c = active; + if (c != null) c.disconnect(); + } + + void releaseImages() { + images.evictAll(); + } + + boolean configured() { + return !server().isEmpty() && !prefs.getString("credential", "").isEmpty(); + } + + String server() { + return prefs.getString("server", ""); + } + + String machine() { + return prefs.getString("machine", ""); + } + + void disconnect() { + cancel(); + prefs.edit().remove("server").remove("machine").remove("credential").apply(); + releaseImages(); + resume(); + } + + private javax.crypto.SecretKey key() throws Exception { + KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); + ks.load(null); + if (ks.containsAlias("luma.plex")) return (javax.crypto.SecretKey) ks.getKey("luma.plex", null); + KeyGenerator gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + gen.init( + new KeyGenParameterSpec.Builder( + "luma.plex", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .build()); + return gen.generateKey(); + } + + private String seal(String value) throws Exception { + Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); + c.init(Cipher.ENCRYPT_MODE, key()); + return Base64.encodeToString(c.getIV(), Base64.NO_WRAP) + + ":" + + Base64.encodeToString(c.doFinal(value.getBytes(StandardCharsets.UTF_8)), Base64.NO_WRAP); + } + + private String token() throws Exception { + String[] parts = prefs.getString("credential", "").split(":"); + if (parts.length != 2) throw new IOException("No credential"); + Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); + c.init( + Cipher.DECRYPT_MODE, + key(), + new GCMParameterSpec(128, Base64.decode(parts[0], Base64.NO_WRAP))); + return new String(c.doFinal(Base64.decode(parts[1], Base64.NO_WRAP)), StandardCharsets.UTF_8); + } + + private String normalize(String value) throws Exception { + URI uri = new URI(value); + if (uri.getHost() == null + || uri.getUserInfo() != null + || uri.getQuery() != null + || uri.getFragment() != null) throw new IOException("Invalid server address"); + if (!uri.getScheme().equals("https") && !uri.getScheme().equals("http")) + throw new IOException("HTTP or HTTPS required"); + if (uri.getScheme().equals("http")) { + boolean local = false; + for (InetAddress a : InetAddress.getAllByName(uri.getHost())) + if (a.isSiteLocalAddress() || a.isLoopbackAddress() || a.isLinkLocalAddress()) local = true; + if (!local) throw new IOException("Use HTTPS for remote servers"); + } + return value.replaceAll("/+$", ""); + } + + void connect(String url, String t) throws Exception { + if (t.isEmpty()) throw new IOException("Token required"); + String base = normalize(url); + JSONObject root = + json(base + "/?includeCollections=0", "GET", null, t).getJSONObject("MediaContainer"); + String machine = root.optString("machineIdentifier"); + if (machine.isEmpty()) throw new IOException("Not a Plex server"); + String secret = seal(t); + if (cancelled) throw new InterruptedIOException(); + prefs + .edit() + .putString("server", base) + .putString("machine", machine) + .putString("credential", secret) + .apply(); + releaseImages(); + } + + void connect(Server s) throws Exception { + Exception last = null; + for (String url : s.urls) { + if (cancelled) throw new InterruptedIOException(); + try { + connect(url, s.token); + return; + } catch (Exception e) { + last = e; + } + } + throw new IOException("No reachable connection", last); + } + + Pin createPin() throws Exception { + JSONObject j = json("https://clients.plex.tv/api/v2/pins", "POST", "strong=false", null); + Pin p = new Pin(); + p.id = j.get("id").toString(); + p.code = j.getString("code"); + p.expires = j.optInt("expiresIn", 300); + return p; + } + + String checkPin(Pin pin) throws Exception { + JSONObject j = + json( + "https://clients.plex.tv/api/v2/pins/" + + Uri.encode(pin.id) + + "?code=" + + Uri.encode(pin.code), + "GET", + null, + null); + String t = j.optString("authToken", ""); + return t.isEmpty() || t.equals("null") ? null : t; + } + + List servers(String auth) throws Exception { + JSONArray array = + new JSONArray( + new String( + request( + "https://clients.plex.tv/api/v2/resources?includeHttps=1&includeRelay=1", + "GET", + null, + auth, + 2 * 1024 * 1024), + StandardCharsets.UTF_8)); + List result = new ArrayList<>(); + for (int i = 0; i < array.length(); i++) { + JSONObject r = array.getJSONObject(i); + if (!r.optString("provides").contains("server")) continue; + Server s = new Server(); + s.name = r.optString("name", "Plex server"); + s.token = r.optString("accessToken"); + JSONArray connections = r.optJSONArray("connections"); + if (connections == null || s.token.isEmpty()) continue; + for (int local = 1; local >= 0; local--) + for (int n = 0; n < connections.length(); n++) { + JSONObject c = connections.getJSONObject(n); + if (c.optBoolean("local") == (local == 1)) { + String url = c.optString("uri"); + if (!url.isEmpty()) s.urls.add(url); + } + } + if (!s.urls.isEmpty()) result.add(s); + } + return result; + } + + Library library() throws Exception { + String auth = token(), base = server(); + Library lib = new Library(); + // Hubs exposes a small, bounded set of personalized rows across server versions. + JSONObject container = + json(base + "/hubs?count=12&includeExternalMedia=0", "GET", null, auth) + .getJSONObject("MediaContainer"); + JSONArray hubs = container.optJSONArray("Hub"); + if (hubs != null) + for (int i = 0; i < hubs.length(); i++) { + JSONObject hub = hubs.getJSONObject(i); + String id = hub.optString("hubIdentifier").toLowerCase(Locale.ROOT), + name = hub.optString("title").toLowerCase(Locale.ROOT); + JSONArray entries = hub.optJSONArray("Metadata"); + if (id.contains("continuewatching") + || id.contains("ondeck") + || name.equals("continue watching")) parse(entries, lib.continueWatching); + else if (id.contains("recentlyadded") || name.contains("recently added")) + parse(entries, lib.recent); + } + if (lib.recent.isEmpty()) { + try { + JSONObject recent = + json( + base + + "/library/recentlyAdded?X-Plex-Container-Start=0&X-Plex-Container-Size=12", + "GET", + null, + auth) + .getJSONObject("MediaContainer"); + parse(recent.optJSONArray("Metadata"), lib.recent); + } catch (IOException ignored) { + } + } + return lib; + } + + private void parse(JSONArray entries, List out) throws JSONException { + if (entries == null) return; + Set keys = new HashSet<>(); + for (Media m : out) keys.add(m.key); + for (int i = 0; i < entries.length() && out.size() < 12; i++) { + JSONObject j = entries.getJSONObject(i); + String key = j.optString("ratingKey"); + if (key.isEmpty() || !keys.add(key)) continue; + String type = j.optString("type"); + if (!Arrays.asList("movie", "episode", "show", "season").contains(type)) continue; + Media m = new Media(); + m.key = key; + m.type = type; + m.title = j.optString("title", "Untitled"); + String show = j.optString("grandparentTitle"); + if (!show.isEmpty()) m.title = show + " · " + m.title; + String year = j.optInt("year", 0) > 0 ? String.valueOf(j.optInt("year")) : ""; + String rating = j.optString("contentRating"); + String summary = j.optString("summary"); + m.subtitle = + year + + (rating.isEmpty() ? "" : " · " + rating) + + (summary.isEmpty() ? "" : " · " + summary); + if (m.subtitle.length() > 180) m.subtitle = m.subtitle.substring(0, 177) + "…"; + m.art = j.optString("art", j.optString("grandparentArt", "")); + m.thumb = m.art.isEmpty() ? j.optString("thumb", j.optString("grandparentThumb", "")) : m.art; + long duration = j.optLong("duration", 0); + m.progress = duration > 0 ? Math.min(1, j.optLong("viewOffset", 0) / (float) duration) : 0; + out.add(m); + } + } + + Bitmap image(String path, boolean hero) { + if (path == null + || path.isEmpty() + || cancelled + || !path.startsWith("/") + || path.startsWith("//")) return null; + String cacheKey = (hero ? "h:" : "t:") + path; + Bitmap cached = images.get(cacheKey); + if (cached != null) return cached; + try { + int w = hero ? 1280 : 320, h = hero ? 720 : 180; + String url = + server() + + "/photo/:/transcode?width=" + + w + + "&height=" + + h + + "&minSize=1&upscale=0&url=" + + Uri.encode(path); + byte[] data = request(url, "GET", null, token(), 3 * 1024 * 1024); + BitmapFactory.Options opts = new BitmapFactory.Options(); + opts.inJustDecodeBounds = true; + BitmapFactory.decodeByteArray(data, 0, data.length, opts); + opts.inJustDecodeBounds = false; + opts.inSampleSize = 1; + while (opts.outWidth / opts.inSampleSize > w * 1.5 + || opts.outHeight / opts.inSampleSize > h * 1.5) opts.inSampleSize *= 2; + opts.inPreferredConfig = Bitmap.Config.RGB_565; + Bitmap b = BitmapFactory.decodeByteArray(data, 0, data.length, opts); + if (b != null && !cancelled) images.put(cacheKey, b); + return cancelled ? null : b; + } catch (Exception e) { + return null; + } + } + + private JSONObject json(String url, String method, String body, String auth) throws Exception { + return new JSONObject( + new String(request(url, method, body, auth, 2 * 1024 * 1024), StandardCharsets.UTF_8)); + } + + private byte[] request(String url, String method, String body, String auth, int limit) + throws IOException { + if (cancelled || Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); + HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection(); + active = c; + try { + c.setConnectTimeout(4000); + c.setReadTimeout(5000); + c.setInstanceFollowRedirects(false); + c.setRequestMethod(method); + c.setRequestProperty("Accept", "application/json"); + c.setRequestProperty("X-Plex-Product", "Luma"); + c.setRequestProperty("X-Plex-Version", "1.0.0"); + c.setRequestProperty("X-Plex-Platform", "Android"); + c.setRequestProperty("X-Plex-Device", "Android TV"); + c.setRequestProperty("X-Plex-Client-Identifier", clientId); + if (auth != null) c.setRequestProperty("X-Plex-Token", auth); + if (body != null) { + c.setDoOutput(true); + c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + try (OutputStream out = c.getOutputStream()) { + out.write(body.getBytes(StandardCharsets.UTF_8)); + } + } + int status = c.getResponseCode(); + if (status < 200 || status >= 300) throw new IOException("Plex HTTP " + status); + if (c.getContentLength() > limit) throw new IOException("Response too large"); + try (InputStream in = c.getInputStream(); + ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) != -1) { + if (cancelled || Thread.currentThread().isInterrupted()) + throw new InterruptedIOException(); + if (out.size() + n > limit) throw new IOException("Response too large"); + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } finally { + c.disconnect(); + if (active == c) active = null; + } + } +} diff --git a/app/src/main/java/tv/luma/launcher/SaverMedia.java b/app/src/main/java/tv/luma/launcher/SaverMedia.java new file mode 100644 index 0000000..34526f2 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/SaverMedia.java @@ -0,0 +1,281 @@ +package tv.luma.launcher; + +import android.content.Context; +import android.graphics.*; +import android.media.MediaMetadataRetriever; +import java.io.*; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import org.json.*; + +/** Bounded, explicitly requested offline downloads. No background service or scheduled fetches. */ +final class SaverMedia { + static final String NATURE_URL = + "https://www.nps.gov/nps-audiovideo/audiovideo/4dc17e98-b3ae-4bcf-be9e-1179190717f5720p.mp4"; + + static final class Entry { + String file, title, credit, source; + + Entry(JSONObject j) { + file = j.optString("file"); + title = j.optString("title"); + credit = j.optString("credit"); + source = j.optString("source", file); + } + } + + interface Progress { + void update(String message); + } + + private final Context context; + private volatile int generation; + private volatile HttpURLConnection connection; + + SaverMedia(Context c) { + context = c.getApplicationContext(); + } + + int newJob() { + cancel(); + return generation; + } + + void cancel() { + generation++; + HttpURLConnection c = connection; + if (c != null) c.disconnect(); + } + + File videoFile() { + return new File(context.getFilesDir(), "saver-nature.mp4"); + } + + long videoBytes() { + return videoFile().length(); + } + + List entries(String album) { + LinkedHashMap entries = new LinkedHashMap<>(); + try (InputStream in = context.getAssets().open("saver/catalog.json")) { + JSONArray list = new JSONArray(new String(read(in, 128 * 1024), StandardCharsets.UTF_8)); + for (int i = 0; i < list.length(); i++) { + JSONObject j = list.getJSONObject(i); + if (j.optString("album").equals(album)) { + Entry e = new Entry(j); + entries.put(e.source, e); + } + } + } catch (Exception ignored) { + } + File catalog = new File(context.getFilesDir(), "saver-art/catalog.json"); + if (album.equals("art") && catalog.exists()) + try (InputStream in = new FileInputStream(catalog)) { + JSONArray list = new JSONArray(new String(read(in, 128 * 1024), StandardCharsets.UTF_8)); + for (int i = 0; i < list.length(); i++) { + Entry e = new Entry(list.getJSONObject(i)); + if (new File(e.file).isFile()) entries.put(e.source, e); + } + } catch (Exception ignored) { + } + return new ArrayList<>(entries.values()); + } + + Bitmap bitmap(Entry entry) { + try { + BitmapFactory.Options o = new BitmapFactory.Options(); + o.inJustDecodeBounds = true; + try (InputStream in = open(entry.file)) { + BitmapFactory.decodeStream(in, null, o); + } + o.inJustDecodeBounds = false; + o.inSampleSize = 1; + o.inPreferredConfig = Bitmap.Config.RGB_565; + while (o.outWidth / o.inSampleSize > 1280 || o.outHeight / o.inSampleSize > 1000) + o.inSampleSize *= 2; + try (InputStream in = open(entry.file)) { + return BitmapFactory.decodeStream(in, null, o); + } + } catch (Exception e) { + return null; + } + } + + private InputStream open(String path) throws IOException { + return path.startsWith("/") ? new FileInputStream(path) : context.getAssets().open(path); + } + + void downloadVideo(String url, int job, Progress progress) throws Exception { + if (url.toLowerCase(Locale.ROOT).contains(".m3u8")) + throw new IOException( + "Live/HLS playlists can stream, but cannot be saved as a single offline video."); + File temp = new File(context.getFilesDir(), "saver-video-" + job + ".part"); + try { + if (context.getFilesDir().getUsableSpace() < 350L * 1024 * 1024) + throw new IOException("Not enough free space for a video download."); + download(url, temp, 250L * 1024 * 1024, job, progress); + MediaMetadataRetriever metadata = new MediaMetadataRetriever(); + try { + metadata.setDataSource(temp.getAbsolutePath()); + if (!"yes".equals(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO))) + throw new IOException("The address did not return a playable video file."); + } finally { + metadata.release(); + } + check(job); + if (!temp.renameTo(videoFile())) throw new IOException("Unable to save the video."); + } finally { + temp.delete(); + } + } + + void downloadArt(int job, Progress progress) throws Exception { + File dir = new File(context.getFilesDir(), "saver-art"); + if (!dir.exists() && !dir.mkdirs()) throw new IOException("Unable to create gallery."); + JSONArray catalog = new JSONArray(); + int[] ids = {436535, 45434, 436105, 436532, 437880, 436121}; + for (int i = 0; i < ids.length; i++) { + check(job); + progress.update("Getting museum artwork " + (i + 1) + " of " + ids.length + "…"); + try { + byte[] bytes = + get( + "https://collectionapi.metmuseum.org/public/collection/v1/objects/" + ids[i], + 1024 * 1024, + job); + JSONObject object = new JSONObject(new String(bytes, StandardCharsets.UTF_8)); + String image = object.optString("primaryImageSmall"); + if (!object.optBoolean("isPublicDomain") || image.isEmpty()) continue; + File target = new File(dir, ids[i] + ".jpg"), temp = new File(dir, ids[i] + ".part"); + try { + download(image, temp, 2 * 1024 * 1024, job, message -> {}); + check(job); + if (!temp.renameTo(target)) continue; + } finally { + temp.delete(); + } + JSONObject e = new JSONObject(); + e.put("file", target.getAbsolutePath()); + e.put("title", object.optString("title")); + e.put( + "credit", + object.optString("artistDisplayName") + + " · " + + object.optString("objectDate") + + " · The Met, CC0"); + e.put("source", object.optString("objectURL")); + catalog.put(e); + } catch (InterruptedIOException e) { + throw e; + } catch (Exception ignored) { + } + } + check(job); + if (catalog.length() == 0) + throw new IOException( + "Museum images are unavailable. The bundled gallery still works offline."); + File temp = new File(dir, "catalog.part"); + try (FileOutputStream out = new FileOutputStream(temp)) { + out.write(catalog.toString().getBytes(StandardCharsets.UTF_8)); + } + check(job); + if (!temp.renameTo(new File(dir, "catalog.json"))) + throw new IOException("Unable to save gallery."); + } + + static void validateUrl(String value) throws Exception { + URL url = new URL(value); + if (url.getUserInfo() != null) throw new IOException("Use a direct video URL."); + if (url.getProtocol().equals("https")) return; + if (url.getProtocol().equals("http")) + for (InetAddress a : InetAddress.getAllByName(url.getHost())) + if (a.isSiteLocalAddress() || a.isLoopbackAddress() || a.isLinkLocalAddress()) return; + throw new IOException("Use HTTPS, or HTTP on your local network."); + } + + private void check(int job) throws InterruptedIOException { + if (job != generation || Thread.currentThread().isInterrupted()) + throw new InterruptedIOException("Canceled"); + } + + private HttpURLConnection connect(String value, int job) throws Exception { + for (int redirects = 0; redirects < 5; redirects++) { + check(job); + validateUrl(value); + HttpURLConnection c = (HttpURLConnection) new URL(value).openConnection(); + connection = c; + c.setConnectTimeout(6000); + c.setReadTimeout(12000); + c.setInstanceFollowRedirects(false); + c.setRequestProperty("User-Agent", "Luma/1.0 AndroidTV"); + int status = c.getResponseCode(); + if (status >= 300 && status < 400) { + String location = c.getHeaderField("Location"); + value = new URL(new URL(value), location).toString(); + c.disconnect(); + continue; + } + if (status != 200) { + c.disconnect(); + throw new IOException("Source unavailable (HTTP " + status + ")."); + } + return c; + } + throw new IOException("Too many redirects."); + } + + private byte[] get(String value, int limit, int job) throws Exception { + HttpURLConnection c = connect(value, job); + try (InputStream in = c.getInputStream()) { + check(job); + return read(in, limit); + } finally { + c.disconnect(); + if (connection == c) connection = null; + } + } + + private void download(String value, File file, long limit, int job, Progress progress) + throws Exception { + HttpURLConnection c = connect(value, job); + try { + if (c.getContentLengthLong() > limit) + throw new IOException("Download exceeds the " + (limit / 1024 / 1024) + " MB limit."); + String type = c.getContentType(); + if (type != null && (type.contains("text/html") || type.contains("mpegurl"))) + throw new IOException("Use a direct MP4 file for offline playback."); + try (InputStream in = c.getInputStream(); + FileOutputStream out = new FileOutputStream(file)) { + byte[] buf = new byte[32768]; + long total = 0, lastUpdate = 0; + int n; + while ((n = in.read(buf)) != -1) { + check(job); + total += n; + if (total > limit) throw new IOException("Download is too large."); + out.write(buf, 0, n); + long now = System.currentTimeMillis(); + if (now - lastUpdate > 750) { + progress.update("Downloaded " + (total / 1024 / 1024) + " MB…"); + lastUpdate = now; + } + } + } + } finally { + c.disconnect(); + if (connection == c) connection = null; + } + } + + private static byte[] read(InputStream in, int limit) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) != -1) { + if (out.size() + n > limit) throw new IOException("Response too large"); + out.write(buf, 0, n); + } + return out.toByteArray(); + } +} diff --git a/app/src/main/java/tv/luma/launcher/SaverPictureView.java b/app/src/main/java/tv/luma/launcher/SaverPictureView.java new file mode 100644 index 0000000..d350290 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/SaverPictureView.java @@ -0,0 +1,99 @@ +package tv.luma.launcher; + +import android.animation.*; +import android.content.Context; +import android.graphics.*; +import android.view.View; + +/** One Canvas owns the complete crossfade, so clearing a view cannot erase incoming artwork. */ +final class SaverPictureView extends View { + private final Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG); + private final RectF destination = new RectF(); + private Bitmap current, incoming; + private float mix = 1; + private final boolean fit; + private ValueAnimator fade; + + SaverPictureView(Context context, boolean fit) { + super(context); + this.fit = fit; + setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); + } + + void display(Bitmap bitmap) { + if (bitmap == null) return; + current = bitmap; + incoming = null; + mix = 1; + invalidate(); + } + + void transition(Bitmap bitmap, boolean motion, Runnable finished) { + if (bitmap == null) { + finished.run(); + return; + } + if (fade != null) fade.cancel(); + if (current == null || !motion) { + display(bitmap); + finished.run(); + return; + } + incoming = bitmap; + mix = 0; + fade = ValueAnimator.ofFloat(0, 1); + fade.setDuration(800); + fade.addUpdateListener( + a -> { + mix = (float) a.getAnimatedValue(); + invalidate(); + }); + fade.addListener( + new AnimatorListenerAdapter() { + boolean canceled; + + @Override + public void onAnimationCancel(Animator a) { + canceled = true; + } + + @Override + public void onAnimationEnd(Animator a) { + if (canceled) return; + current = incoming; + incoming = null; + mix = 1; + invalidate(); + finished.run(); + } + }); + fade.start(); + } + + @Override + protected void onDraw(Canvas canvas) { + canvas.drawColor(Color.BLACK); + draw(canvas, current, incoming == null ? 255 : (int) (255 * (1 - mix))); + if (incoming != null) draw(canvas, incoming, (int) (mix * 255)); + } + + private void draw(Canvas canvas, Bitmap bitmap, int alpha) { + if (bitmap == null || bitmap.isRecycled()) return; + float sx = getWidth() / (float) bitmap.getWidth(), + sy = getHeight() / (float) bitmap.getHeight(); + float scale = fit ? Math.min(sx, sy) : Math.max(sx, sy); + float w = bitmap.getWidth() * scale, h = bitmap.getHeight() * scale; + destination.set( + (getWidth() - w) / 2, (getHeight() - h) / 2, (getWidth() + w) / 2, (getHeight() + h) / 2); + paint.setAlpha(alpha); + canvas.drawBitmap(bitmap, null, destination, paint); + paint.setAlpha(255); + } + + void release() { + if (fade != null) fade.cancel(); + current = null; + incoming = null; + invalidate(); + } +} diff --git a/app/src/main/java/tv/luma/launcher/SaverView.java b/app/src/main/java/tv/luma/launcher/SaverView.java new file mode 100644 index 0000000..77a5105 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/SaverView.java @@ -0,0 +1,240 @@ +package tv.luma.launcher; + +import android.content.*; +import android.graphics.Bitmap; +import android.graphics.Color; +import android.graphics.drawable.GradientDrawable; +import android.net.Uri; +import android.os.*; +import android.view.*; +import android.widget.*; +import java.util.*; +import java.util.concurrent.*; + +/** Runs only while displayed. Two sampled images maximum, or one platform video decoder. */ +final class SaverView extends FrameLayout { + private final SharedPreferences prefs; + private final SaverMedia media; + private final Handler handler = new Handler(Looper.getMainLooper()); + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + private final SaverPictureView picture; + private VideoView video; + private TextView title, credit, clock; + private List entries; + private Bitmap preloaded; + private int nextIndex = 0, generation = 1, failed = 0; + private boolean running = true, transitioning = false; + private final Runnable next = + () -> { + if (running) advance(); + }; + private final Runnable tick = + new Runnable() { + public void run() { + if (!running) return; + clock.setText( + android.text.format.DateFormat.getTimeFormat(getContext()).format(new Date())); + FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) clock.getLayoutParams(); + lp.bottomMargin = Ui.dp(getContext(), 28 + (System.currentTimeMillis() / 60000 % 3) * 5); + clock.setLayoutParams(lp); + handler.postDelayed(this, 60000 - System.currentTimeMillis() % 60000); + } + }; + + SaverView(Context context) { + super(context); + prefs = context.getSharedPreferences("luma", Context.MODE_PRIVATE); + media = new SaverMedia(context); + String mode = prefs.getString("saverMode", "scenic"); + setBackgroundColor(Color.BLACK); + setContentDescription("Luma screensaver"); + setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); + setFocusableInTouchMode(true); + setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS); + String framing = prefs.getString("saverFraming", "auto"); + picture = + new SaverPictureView( + context, framing.equals("fit") || framing.equals("auto") && mode.equals("art")); + addView(picture, new LayoutParams(-1, -1)); + View dim = new View(context); + dim.setBackgroundColor(Color.BLACK); + dim.setAlpha(prefs.getInt("saverDim", 0) / 100f); + addView(dim, new LayoutParams(-1, -1)); + View scrim = new View(context); + scrim.setBackground( + new GradientDrawable( + GradientDrawable.Orientation.TOP_BOTTOM, new int[] {0x00000000, 0xD9000000})); + addView(scrim, new LayoutParams(-1, Ui.dp(context, 170), Gravity.BOTTOM)); + LinearLayout captions = new LinearLayout(context); + captions.setOrientation(LinearLayout.VERTICAL); + title = Ui.text(context, "", 17, Ui.WHITE); + title.setMaxLines(2); + credit = Ui.text(context, "", 10, 0xFFDEE3EB); + credit.setMaxLines(2); + credit.setPadding(0, Ui.dp(context, 7), 0, 0); + title.setShadowLayer(Ui.dp(context, 3), 0, Ui.dp(context, 1), Color.BLACK); + credit.setShadowLayer(Ui.dp(context, 2), 0, Ui.dp(context, 1), Color.BLACK); + captions.addView(title); + captions.addView(credit); + LayoutParams captionLp = + new LayoutParams(Ui.dp(context, 650), -2, Gravity.BOTTOM | Gravity.LEFT); + captionLp.leftMargin = Ui.dp(context, 32); + captionLp.bottomMargin = Ui.dp(context, 30); + addView(captions, captionLp); + captions.setVisibility(prefs.getBoolean("saverCaptions", true) ? VISIBLE : GONE); + clock = Ui.text(context, "", 27, Ui.WHITE); + clock.setShadowLayer(Ui.dp(context, 3), 0, Ui.dp(context, 1), Color.BLACK); + LayoutParams clockLp = new LayoutParams(-2, -2, Gravity.BOTTOM | Gravity.RIGHT); + clockLp.rightMargin = Ui.dp(context, 32); + clockLp.bottomMargin = Ui.dp(context, 28); + addView(clock, clockLp); + clock.setVisibility(prefs.getBoolean("saverClock", false) ? VISIBLE : GONE); + if (clock.getVisibility() == VISIBLE) handler.post(tick); + if (!prefs.getBoolean("saverCaptions", true) && !prefs.getBoolean("saverClock", false)) + scrim.setVisibility(GONE); + if (mode.equals("video") && startVideo()) return; + startPhotos(mode.equals("art") ? "art" : "scenic"); + } + + private void startPhotos(String album) { + entries = media.entries(album); + if (entries.isEmpty()) entries = media.entries("scenic"); + if (prefs.getBoolean("saverShuffle", true)) Collections.shuffle(entries); + loadInitial(); + } + + private void loadInitial() { + if (entries.isEmpty()) return; + int g = generation; + worker.execute( + () -> { + for (int i = 0; i < entries.size(); i++) { + Bitmap bitmap = media.bitmap(entries.get(i)); + if (bitmap == null) continue; + final int index = i; + handler.post( + () -> { + if (!running || g != generation) return; + picture.display(bitmap); + caption(entries.get(index)); + nextIndex = (index + 1) % entries.size(); + preload(); + }); + return; + } + handler.post( + () -> { + if (running && g == generation) { + title.setText("Artwork unavailable"); + credit.setText("Choose another collection in screensaver settings."); + } + }); + }); + } + + private void caption(SaverMedia.Entry e) { + title.setText(e.title); + credit.setText(e.credit); + } + + private void preload() { + if (!running || entries.isEmpty()) return; + int g = generation, index = nextIndex; + worker.execute( + () -> { + Bitmap b = media.bitmap(entries.get(index)); + handler.post( + () -> { + if (!running || g != generation) return; + if (b == null) { + nextIndex = (index + 1) % entries.size(); + if (++failed < entries.size()) preload(); + return; + } + failed = 0; + preloaded = b; + handler.removeCallbacks(next); + handler.postDelayed(next, prefs.getInt("saverInterval", 30) * 1000L); + }); + }); + } + + private void advance() { + if (transitioning || preloaded == null) return; + transitioning = true; + Bitmap ready = preloaded; + preloaded = null; + SaverMedia.Entry entry = entries.get(nextIndex); + nextIndex = (nextIndex + 1) % entries.size(); + picture.transition( + ready, + prefs.getBoolean("motion", true), + () -> { + if (!running) return; + caption(entry); + transitioning = false; + preload(); + }); + } + + private boolean startVideo() { + Uri uri = null; + String source = prefs.getString("saverVideoSource", "local"); + if (source.equals("local") && media.videoFile().isFile()) uri = Uri.fromFile(media.videoFile()); + else if (source.equals("document")) uri = Uri.parse(prefs.getString("saverVideoUri", "")); + else if (source.equals("stream")) uri = Uri.parse(prefs.getString("saverVideoUrl", "")); + if (uri == null || uri.toString().isEmpty()) return false; + video = new VideoView(getContext()); + video.setAudioFocusRequest( + prefs.getBoolean("saverVideoAudio", false) + ? android.media.AudioManager.AUDIOFOCUS_GAIN_TRANSIENT + : android.media.AudioManager.AUDIOFOCUS_NONE); + addView(video, 0, new LayoutParams(-1, -1, Gravity.CENTER)); + picture.setVisibility(GONE); + title.setText("Nature loop"); + credit.setText( + source.equals("local") + ? prefs.getString("saverVideoCredit", "Local video") + : "Your video source"); + video.setOnPreparedListener( + player -> { + if (!running || video == null) return; + player.setLooping(true); + boolean audio = prefs.getBoolean("saverVideoAudio", false); + player.setVolume(audio ? 1 : 0, audio ? 1 : 0); + video.start(); + }); + video.setOnErrorListener( + (player, what, extra) -> { + if (!running || video == null) return true; + video.stopPlayback(); + removeView(video); + video = null; + picture.setVisibility(VISIBLE); + startPhotos("scenic"); + return true; + }); + video.setVideoURI(uri); + return true; + } + + void stop() { + if (!running) return; + running = false; + generation++; + handler.removeCallbacksAndMessages(null); + picture.release(); + preloaded = null; + if (video != null) { + video.stopPlayback(); + video = null; + } + worker.shutdownNow(); + } + + @Override + protected void onDetachedFromWindow() { + stop(); + super.onDetachedFromWindow(); + } +} diff --git a/app/src/main/java/tv/luma/launcher/SceneView.java b/app/src/main/java/tv/luma/launcher/SceneView.java new file mode 100644 index 0000000..f1892b5 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/SceneView.java @@ -0,0 +1,228 @@ +package tv.luma.launcher; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ValueAnimator; +import android.content.Context; +import android.graphics.*; +import android.view.View; +import java.io.InputStream; + +/** Single sampled bitmap, cached shaders; nothing redraws when the screen is idle. */ +final class SceneView extends View { + private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); + private Bitmap wallpaper, mediaArt, previousArt; + private float artMix = 1; + private boolean motion = true; + private ValueAnimator imageAnimator; + private final RectF destination = new RectF(); + private int accent = 0xFF5B4125, from = accent, to = accent; + private ValueAnimator animator; + private Shader left, bottom, glow, base; + private String scene = "alpine"; + private float dim = .24f; + + SceneView(Context c) { + super(c); + setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); + } + + static Bitmap decodeWallpaper(Context c) { + try (InputStream in = c.getAssets().open("alpine.jpg")) { + BitmapFactory.Options o = new BitmapFactory.Options(); + o.inPreferredConfig = Bitmap.Config.RGB_565; + try (InputStream bounds = c.getAssets().open("alpine.jpg")) { + o.inJustDecodeBounds = true; + BitmapFactory.decodeStream(bounds, null, o); + } + o.inJustDecodeBounds = false; + o.inSampleSize = 1; + while (o.outWidth / o.inSampleSize > 1600 || o.outHeight / o.inSampleSize > 1000) + o.inSampleSize *= 2; + return BitmapFactory.decodeStream(in, null, o); + } catch (Exception e) { + return null; + } + } + + void setWallpaper(Bitmap b) { + Bitmap previous = currentArt(); + wallpaper = b; + transitionArt(previous); + } + + void setMediaArt(Bitmap b) { + if (mediaArt == b) return; + Bitmap previous = currentArt(); + mediaArt = b; + transitionArt(previous); + } + + private Bitmap currentArt() { + return mediaArt != null ? mediaArt : scene.equals("alpine") ? wallpaper : null; + } + + void setMotion(boolean enabled) { + motion = enabled; + if (!motion) stopAnimations(); + } + + private void transitionArt(Bitmap previous) { + if (imageAnimator != null) imageAnimator.cancel(); + if (!motion || previous == currentArt()) { + previousArt = null; + artMix = 1; + invalidate(); + return; + } + previousArt = previous; + artMix = 0; + imageAnimator = ValueAnimator.ofFloat(0, 1); + imageAnimator.setDuration(320); + imageAnimator.addUpdateListener( + a -> { + artMix = (float) a.getAnimatedValue(); + invalidate(); + }); + imageAnimator.addListener( + new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + previousArt = null; + artMix = 1; + invalidate(); + } + }); + imageAnimator.start(); + } + + void configure(String s, float darkness) { + Bitmap previous = currentArt(); + scene = s; + dim = darkness; + shaders(); + transitionArt(previous); + } + + void accent(int color, boolean animate) { + if (animator != null) animator.cancel(); + from = accent; + to = color; + if (!animate) { + accent = color; + shaders(); + invalidate(); + return; + } + animator = ValueAnimator.ofFloat(0, 1); + animator.setDuration(280); + animator.addUpdateListener( + a -> { + float f = (float) a.getAnimatedValue(); + accent = blend(from, to, f); + glowShader(); + invalidate(); + }); + animator.start(); + } + + private int blend(int a, int b, float f) { + return Color.rgb( + (int) (Color.red(a) * (1 - f) + Color.red(b) * f), + (int) (Color.green(a) * (1 - f) + Color.green(b) * f), + (int) (Color.blue(a) * (1 - f) + Color.blue(b) * f)); + } + + protected void onSizeChanged(int w, int h, int ow, int oh) { + shaders(); + } + + private void glowShader() { + if (getWidth() > 0) + glow = + new RadialGradient( + getWidth() * .76f, + getHeight() * .25f, + getWidth() * .8f, + new int[] {(accent & 0x00FFFFFF) | 0xA0000000, 0x00000000}, + null, + Shader.TileMode.CLAMP); + } + + private void shaders() { + if (getWidth() == 0) return; + float w = getWidth(), h = getHeight(); + left = + new LinearGradient( + 0, + 0, + w * .88f, + 0, + new int[] {0xE0080D18, 0x9C080D18, 0x00080D18}, + new float[] {0, .48f, 1}, + Shader.TileMode.CLAMP); + bottom = + new LinearGradient( + 0, + h * .24f, + 0, + h, + new int[] {0x00080D18, 0xA8080D18, 0xFC080D18, 0xFF080D18}, + new float[] {0, .47f, .82f, 1}, + Shader.TileMode.CLAMP); + int top = scene.equals("aurora") ? 0xFF143B49 : 0xFF152037; + base = + new LinearGradient( + w, 0, 0, h, new int[] {top, 0xFF151A32, Ui.BG}, null, Shader.TileMode.CLAMP); + glowShader(); + } + + protected void onDraw(Canvas c) { + if (base == null) shaders(); + p.setShader(base); + c.drawRect(0, 0, getWidth(), getHeight(), p); + p.setShader(null); + Bitmap art = currentArt(); + if (previousArt != null) + drawArt(c, previousArt, art == null ? (int) (255 * (1 - artMix)) : 255); + drawArt(c, art, (int) (255 * artMix)); + if (art != null || previousArt != null) { + c.drawColor(((int) (dim * 255) << 24) | 0x00040810); + } + p.setShader(glow); + p.setAlpha(art == null ? 150 : 65); + c.drawRect(0, 0, getWidth(), getHeight(), p); + p.setAlpha(255); + p.setShader(left); + c.drawRect(0, 0, getWidth(), getHeight(), p); + p.setShader(bottom); + c.drawRect(0, 0, getWidth(), getHeight(), p); + p.setShader(null); + } + + private void drawArt(Canvas canvas, Bitmap art, int alpha) { + if (art == null || art.isRecycled() || alpha == 0) return; + float scale = + Math.max(getWidth() / (float) art.getWidth(), getHeight() / (float) art.getHeight()); + float w = art.getWidth() * scale, h = art.getHeight() * scale; + destination.set( + (getWidth() - w) / 2, (getHeight() - h) / 2, (getWidth() + w) / 2, (getHeight() + h) / 2); + p.setAlpha(alpha); + canvas.drawBitmap(art, null, destination, p); + p.setAlpha(255); + } + + void stopAnimations() { + if (animator != null) animator.cancel(); + if (imageAnimator != null) imageAnimator.cancel(); + previousArt = null; + artMix = 1; + } + + void release() { + stopAnimations(); + wallpaper = null; + mediaArt = null; + invalidate(); + } +} diff --git a/app/src/main/java/tv/luma/launcher/Ui.java b/app/src/main/java/tv/luma/launcher/Ui.java new file mode 100644 index 0000000..e2fd8d6 --- /dev/null +++ b/app/src/main/java/tv/luma/launcher/Ui.java @@ -0,0 +1,57 @@ +package tv.luma.launcher; + +import android.content.Context; +import android.graphics.Color; +import android.graphics.Typeface; +import android.graphics.drawable.GradientDrawable; +import android.graphics.drawable.StateListDrawable; +import android.view.View; +import android.widget.TextView; + +final class Ui { + static final int WHITE = Color.rgb(245, 247, 252), MUTED = Color.rgb(167, 178, 197); + static final int GOLD = Color.rgb(232, 203, 166), BG = Color.rgb(8, 13, 24); + + static int dp(Context c, float n) { + return Math.round(n * c.getResources().getDisplayMetrics().density); + } + + static GradientDrawable round(int color, float radius) { + GradientDrawable d = new GradientDrawable(); + d.setColor(color); + d.setCornerRadius(radius); + return d; + } + + static TextView text(Context c, String s, float size, int color) { + TextView t = new TextView(c); + t.setText(s); + t.setTextSize(size); + t.setTextColor(color); + t.setFontFeatureSettings("kern"); + t.setIncludeFontPadding(false); + return t; + } + + static void medium(TextView t) { + t.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + } + + static void glass(View v, int radius) { + Context c = v.getContext(); + GradientDrawable normal = round(0x30222E43, dp(c, radius)); + normal.setStroke(dp(c, 1), 0x22FFFFFF); + GradientDrawable focused = round(0xE6E6DFD3, dp(c, radius)); + focused.setStroke(dp(c, 1), 0xFFFFFFFF); + StateListDrawable state = new StateListDrawable(); + state.addState(new int[] {android.R.attr.state_focused}, focused); + state.addState(new int[] {}, normal); + v.setBackground(state); + } + + static android.content.res.ColorStateList textColors() { + return new android.content.res.ColorStateList( + new int[][] {new int[] {android.R.attr.state_focused}, new int[] {}}, + new int[] {BG, WHITE}); + } +} diff --git a/app/src/main/res/drawable/banner.xml b/app/src/main/res/drawable/banner.xml new file mode 100644 index 0000000..6db449b --- /dev/null +++ b/app/src/main/res/drawable/banner.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_luma.xml b/app/src/main/res/drawable/ic_luma.xml new file mode 100644 index 0000000..d4b98f4 --- /dev/null +++ b/app/src/main/res/drawable/ic_luma.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..6ee8671 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + Luma Home button + Opens Luma when you press Home or the stock launcher appears. Does not read screen content. Projectivy remains available from Luma settings. Turn off other launcher Home overrides to avoid conflicts. + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..269b4a2 --- /dev/null +++ b/app/src/main/res/values/styles.xml @@ -0,0 +1,12 @@ + + + diff --git a/app/src/main/res/xml/home_accessibility.xml b/app/src/main/res/xml/home_accessibility.xml new file mode 100644 index 0000000..2da87d4 --- /dev/null +++ b/app/src/main/res/xml/home_accessibility.xml @@ -0,0 +1,10 @@ + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..bb97a9a --- /dev/null +++ b/build.gradle @@ -0,0 +1 @@ +plugins { id 'com.android.application' version '8.5.2' apply false } diff --git a/docs/ASSETS.md b/docs/ASSETS.md new file mode 100644 index 0000000..0c38aca --- /dev/null +++ b/docs/ASSETS.md @@ -0,0 +1,21 @@ +# Original artwork + +The bundled wallpaper is `app/src/main/assets/alpine.jpg`. It was generated with the built-in imagegen tool, then resized/encoded as a 1920 × 1080 JPEG for the TV. No remote wallpaper service is contacted by the launcher. + +Final generation prompt: + +> Use case: photorealistic-natural. Asset type: original cinematic wallpaper for a premium Android TV launcher. Create a 16:9 landscape image, 2560x1440 if possible, of a tranquil otherworldly alpine lake at blue hour, a monumental jagged mountain ridge on the right two thirds, subtle warm rose gold sunlight touching snowy peaks, tiny atmospheric mist and crisp reflections in deep indigo water. Rich midnight navy, muted teal and soft warm peach highlights, filmic realism and exquisite landscape photography, restrained contrast. Composition: left third is very dark open sky and calm shadow water for white UI title overlay. Bottom third is dark uncluttered water fading into navy for app icons. Main lit mountain subject is upper right. No people, no buildings, no text, no UI, no logos, no watermark. This is background artwork only, not a mockup. + +App banners and icons are loaded from installed Android packages and retain their respective owners' branding. Plex artwork is retrieved from the user's connected server. Aurora and Midnight scenes are code-native gradients. + +# Screensaver media + +The offline image catalog is `app/src/main/assets/saver/catalog.json`, with titles, credits, and source links. The Met's object API marked each included painting `isPublicDomain=true` at retrieval; only works with that flag and an available image are eligible for in-app gallery downloads. See [The Met Open Access API and CC0 description](https://metmuseum.github.io/). + +- [Van Gogh, Wheat Field with Cypresses](https://www.metmuseum.org/art/collection/search/436535) +- [Hokusai, The Great Wave](https://www.metmuseum.org/art/collection/search/45434) +- [Jacques Louis David, The Death of Socrates](https://www.metmuseum.org/art/collection/search/436105) +- [NASA, Earth / Blue Marble](https://images.nasa.gov/details/PIA18033), NASA/NOAA +- [Webb, Cosmic Cliffs in Carina Nebula](https://images.nasa.gov/details/carina_nebula), NASA/ESA/CSA/STScI + +Optional bird video: [Mountain Moment: Steller’s Jay, Mount Rainier National Park](https://www.nps.gov/media/video/view.htm?id=5F3DC793-5998-42A6-B7AE-5165B7C12EA2). The source credits NPS and identifies NPS-credited media without a copyright symbol as public domain. The 720p MP4 is downloaded directly from NPS only when requested, and is not bundled into the APK. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md new file mode 100644 index 0000000..8e787a9 --- /dev/null +++ b/docs/VALIDATION.md @@ -0,0 +1,41 @@ +# Device validation + +Validated on the user’s onn. 4K Plus Streaming device over ADB, October 17, 2026 (America/Phoenix). Android 14 / API 34, approximately 1.88 GiB physical RAM, 1920 × 1080 render override on a 4K display. + +## Functional checks + +- Native app discovery, D-pad focus across rows, OK launch, long-press management menu, and settings navigation. +- Artwork only, Dynamic, and Minimal banner modes; original spacious layout restored as the default. Focused-only labels and hidden app-section text are the defaults. +- Smooth focus scrolling across all app rows, including the All apps footer, and back to the first row. +- Plex connection, bounded rows, artwork, encrypted token storage, and disconnect verified against a temporary local fixture. Fixture credentials were removed. A real Plex account/server has not been connected; actual Plex authorization and title playback remain unverified. +- Art screensaver: all three bundled paintings decoded and displayed, sampled for nonblank pixels, with pure-black side mattes. Captions have a dark gradient and text shadows. Paintings retain their full aspect ratio in Auto/Fit. +- Scenic photo preview, single-button wake, and real one-minute idle activation passed. Idle timeout was restored to ten minutes, photo duration to thirty seconds, and mode to Scenic. +- NPS bird video downloaded to private device storage (about 40 MB), played locally in a loop, and stopped on leaving Luma. The local file remains available in Nature video mode; no ongoing stream/download is active. +- Home routing: Android reports Luma as HOME role holder but the OEM resolver still chooses Google Home. The enabled Luma accessibility service routes Home to Luma. Repeated Home presses, return from Android settings and SmartTube, and screensaver dismissal were checked. +- Projectivy fallback stays open when explicitly selected through its app tile or Settings. Back stays on Luma; from lower rows it returns to the first row. Home returns to Luma. Projectivy remains installed and enabled; only its competing “Override current launcher” preference is off. Its accessibility service and Button Mapper’s service are retained. +- Luma’s override Off control removes only its own accessibility service. Re-enabling through Android’s actual Accessibility settings was verified. The service is system-bound in a separate `tv.luma.launcher:home` process. No view-content retrieval capability is requested. + +## Performance + +Final device sample with the Home override enabled: + +| Measurement | Result | +| --- | --- | +| Launcher UI foreground PSS | 95,566 KiB (93.3 MiB) | +| Launcher UI cached/background PSS | 66,635 KiB (65.1 MiB), reclaimable | +| Separate Home router PSS | 6,348 KiB (6.2 MiB) | +| Launcher background CPU | 0 CPU ticks over 10 seconds | +| Home router idle CPU | 0 CPU ticks over 10 seconds | +| Focus navigation rendering | 84 frames, 4 janky (4.76%); 95th percentile 24 ms | + +The separate Home router avoids retaining the UI image heap. Android can reclaim the UI while the router stays bound; Home then creates the UI again. This is not a guarantee of perfect 60 fps. + +Raw measurements are recorded in `../output/luma-*-memory.txt`, `../output/luma-background-cpu.txt`, and `../output/luma-focus-frames.txt`. PSS includes framework/graphics allocations and fluctuates with system state. Short CPU samples indicate idle behavior, not a guarantee covering all usage. + +## Scope + +No launcher application was disabled or uninstalled. Screensaver selection at the Android system level was not changed. Standard Android Dream settings are unavailable on this TV, so the customizable idle screensaver runs while Luma is foreground. No real Plex credentials were extracted or used. The UI-reclaim test explicitly killed the cached UI process while leaving the Home router bound, then verified that Home restored Luma. No reboot test was performed. + +Build validation uses aapt2, javac, D8, zipalign, and apksigner signature verification. There are no third-party runtime libraries. + +Final APK: 2,737,238 bytes. SHA-256: `46ca53681ff7fc34651402a8e4e806aa0fde7f7e49516aa94d8342ee762472a3`. diff --git a/output/Luma.apk b/output/Luma.apk new file mode 100644 index 0000000..105ed04 Binary files /dev/null and b/output/Luma.apk differ diff --git a/output/Luma.apk.idsig b/output/Luma.apk.idsig new file mode 100644 index 0000000..c68ccef Binary files /dev/null and b/output/Luma.apk.idsig differ diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh new file mode 100755 index 0000000..a0b1814 --- /dev/null +++ b/scripts/bootstrap.sh @@ -0,0 +1,30 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +if [ "$(uname -s)" != Darwin ]; then + echo 'This bootstrap script targets macOS. On other platforms install JDK 17 and Android SDK 34, then set JAVA_HOME and ANDROID_HOME.' >&2 + exit 1 +fi +mkdir -p .tools/sdk/cmdline-tools .tools/jdk +if [ ! -x .tools/jdk/Contents/Home/bin/java ]; then + ARCH=aarch64 + if [ "$(uname -m)" = x86_64 ]; then ARCH=x64; fi + curl -L --fail "https://api.adoptium.net/v3/binary/latest/17/ga/mac/$ARCH/jdk/hotspot/normal/eclipse" -o .tools/jdk.tar.gz + tar -xzf .tools/jdk.tar.gz -C .tools/jdk --strip-components=1 + rm .tools/jdk.tar.gz +fi +if [ ! -x .tools/platform-tools/adb ]; then + curl -L --fail https://dl.google.com/android/repository/platform-tools-latest-darwin.zip -o .tools/platform-tools.zip + unzip -q .tools/platform-tools.zip -d .tools + rm .tools/platform-tools.zip +fi +if [ ! -x .tools/sdk/cmdline-tools/latest/bin/sdkmanager ]; then + curl -L --fail https://dl.google.com/android/repository/commandlinetools-mac-11076708_latest.zip -o .tools/cmdline-tools.zip + unzip -q .tools/cmdline-tools.zip -d .tools/sdk/cmdline-tools + mv .tools/sdk/cmdline-tools/cmdline-tools .tools/sdk/cmdline-tools/latest + rm .tools/cmdline-tools.zip +fi +export JAVA_HOME="$PWD/.tools/jdk/Contents/Home" +.tools/sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root="$PWD/.tools/sdk" --licenses +.tools/sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root="$PWD/.tools/sdk" 'platforms;android-34' 'build-tools;34.0.0' +echo 'Toolchain ready. Run scripts/build.sh.' diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100755 index 0000000..3b1e53a --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +ROOT="$PWD" +export JAVA_HOME="${JAVA_HOME:-$ROOT/.tools/jdk/Contents/Home}" +export ANDROID_HOME="${ANDROID_HOME:-$ROOT/.tools/sdk}" +export PATH="$JAVA_HOME/bin:$PATH" +BT="$ANDROID_HOME/build-tools/34.0.0" +ANDROID_JAR="$ANDROID_HOME/platforms/android-34/android.jar" +mkdir -p build/classes build/dex output .tools +rm -rf build/classes/* build/dex/* +"$BT/aapt2" compile --dir app/src/main/res -o build/resources.zip +"$BT/aapt2" link -o build/unsigned.apk -I "$ANDROID_JAR" --manifest app/src/main/AndroidManifest.xml --java build/generated -A app/src/main/assets --auto-add-overlay build/resources.zip +find app/src/main/java build/generated -name '*.java' > build/sources.txt +javac -encoding UTF-8 -source 8 -target 8 -Xlint:unchecked -bootclasspath "$ANDROID_JAR:$BT/core-lambda-stubs.jar" -d build/classes @build/sources.txt +find build/classes -name '*.class' > build/classes.txt +"$BT/d8" --lib "$ANDROID_JAR" --min-api 26 --output build/dex @build/classes.txt +cp build/unsigned.apk build/with-dex.apk +(cd build/dex && zip -q -u ../with-dex.apk classes*.dex) +"$BT/zipalign" -f 4 build/with-dex.apk build/aligned.apk +if [ ! -f .tools/luma-development.keystore ]; then + keytool -genkeypair -keystore .tools/luma-development.keystore -storepass android -keypass android -alias luma -keyalg RSA -keysize 2048 -validity 10000 -dname 'CN=Luma Development' -noprompt +fi +"$BT/apksigner" sign --ks .tools/luma-development.keystore --ks-key-alias luma --ks-pass pass:android --key-pass pass:android --out output/Luma.apk build/aligned.apk +"$BT/apksigner" verify output/Luma.apk +echo "Built $ROOT/output/Luma.apk" diff --git a/scripts/device_smoke.py b/scripts/device_smoke.py new file mode 100644 index 0000000..b4839e7 --- /dev/null +++ b/scripts/device_smoke.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python3 +"""On-device integration checks. Operates only Luma UI and launches installed apps. +Run with the TV awake. Keeps Projectivy installed as a fallback. +""" +import argparse +import re +import subprocess +import time +import struct +import statistics +import xml.etree.ElementTree as ET +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +ADB = str(ROOT / '.tools/platform-tools/adb') +parser = argparse.ArgumentParser() +parser.add_argument('--device', default='192.168.50.195:35635') +parser.add_argument('--part', choices=['navigation', 'home-routing', 'customization', 'performance', 'plex', 'appearance-modes', 'final-defaults', 'screensaver', 'screensaver-video', 'screensaver-timeout'], default='navigation') +args = parser.parse_args() + +def adb(*cmd): + r = subprocess.run([ADB, '-s', args.device, *map(str,cmd)], capture_output=True, check=True) + return r.stdout.decode(errors='replace') + +def key(*keys): + adb('shell','input','keyevent',*keys) + time.sleep(.35) + +def tree(): + adb('shell','uiautomator','dump','/sdcard/luma-test.xml') + return ET.fromstring(adb('shell','cat','/sdcard/luma-test.xml')) + +def tap_text(text): + for attempt in range(9): + root = tree() + for n in root.iter('node'): + if n.get('text','').split('\n')[0] == text: + x1,y1,x2,y2=map(int,re.findall(r'\d+',n.get('bounds'))) + if y2-y1<35: continue + adb('shell','input','tap',(x1+x2)//2,(y1+y2)//2) + time.sleep(.45) + return + adb('shell','input','swipe',1200,850,1200,380,250) + time.sleep(.2) + raise AssertionError('Missing control: '+text) + +def text_exists(text): + assert any(text in n.get('text','') for n in tree().iter('node')),text + +def focus(): + for n in tree().iter('node'): + if n.get('focused')=='true': + return n.get('content-desc') or n.get('text') + +def start(): + adb('shell','am','start','-W','-a','android.intent.action.MAIN','-c','android.intent.category.HOME','-n','tv.luma.launcher/.MainActivity') + time.sleep(1) + +def package(): + out=adb('shell','dumpsys','activity','activities') + m=re.search(r'topResumedActivity=.*? u0 ([^/]+)/',out) + return m.group(1) if m else None + +def ok(label): print('PASS: '+label,flush=True) + +if args.part=='navigation': + start() + assert package()=='tv.luma.launcher' + ok('Luma launches directly') + key(82);text_exists('Make it yours');key(4) + ok('Menu opens settings; Back closes it') + # Return to the first icon using Back and directional navigation. + key(4);time.sleep(.4) + start();key(19) + assert 'settings' in focus().lower() + key(20) + assert focus()=='Plex',focus() + key(22);assert focus()=='Plezy',focus() + key(22);assert focus()=='SmartTube beta',focus() + key(20);assert focus()=='Prime Video',focus() + key(19);assert focus()=='SmartTube beta',focus() + ok('D-pad moves horizontally and between app rows') + key(23);time.sleep(2) + assert package()=='org.smarttube.beta',package() + ok('OK launches the selected app') + key(3);time.sleep(2) + assert package()=='tv.luma.launcher',package() + ok('Home returns to Luma') + start();key(4,4,4);time.sleep(1) + assert package()=='tv.luma.launcher',package() + ok('Repeated Back at home stays on Luma') + key(20,20);key(4) + assert focus()=='Plex',focus() + assert package()=='tv.luma.launcher',package() + ok('Back from lower rows returns to the first row and stays on Luma') + start() + +elif args.part=='home-routing': + start();key(82);tap_text('Default launcher') + text_exists('Home button override: On') + tap_text('Open Projectivy');time.sleep(2) + assert package()=='com.spocky.projengmenu',package() + time.sleep(3) + assert package()=='com.spocky.projengmenu',package() + ok('Explicit Projectivy fallback remains open without a redirect loop') + key(3);time.sleep(1) + assert package()=='tv.luma.launcher',package() + for _ in range(5):key(3) + assert package()=='tv.luma.launcher',package() + ok('Home returns from fallback and repeated Home presses stay in Luma') + adb('shell','am','start','-a','android.settings.SETTINGS');time.sleep(1) + assert package()!='tv.luma.launcher' + key(3);time.sleep(1) + assert package()=='tv.luma.launcher',package() + ok('Home returns to Luma from Android settings') + key(82);tap_text('Screensaver');tap_text('Preview now');time.sleep(1) + assert any(n.get('content-desc')=='Luma screensaver' for n in tree().iter('node')) + key(3);time.sleep(1) + assert not any(n.get('content-desc')=='Luma screensaver' for n in tree().iter('node')) + assert package()=='tv.luma.launcher',package() + ok('Home dismisses the screensaver and returns to the app grid') + assert 'LumaHomeService' in adb('shell','dumpsys','activity','services','tv.luma.launcher') + assert 'com.spocky.projengmenu' in adb('shell','pm','list','packages','-e','com.spocky.projengmenu') + ok('Home override is bound; Projectivy remains enabled') + +elif args.part=='customization': + start();key(82);tap_text('Appearance') + tap_text('App spacing · 6 columns');tap_text('Spacious · 5 columns') + text_exists('App spacing · 5 columns');key(4) + # Settings Back closes the whole dialog, then reopen and restore default. + key(82);tap_text('Appearance');tap_text('App spacing · 5 columns');tap_text('Balanced · 6 columns') + tap_text('Wallpaper · Alpine');tap_text('Aurora · Soft teal & indigo') + text_exists('Wallpaper · Aurora') + key(4);key(3);time.sleep(1);start();key(82);tap_text('Appearance') + text_exists('Wallpaper · Aurora') + ok('Wallpaper preference persists across leaving and resuming') + tap_text('Wallpaper · Aurora');tap_text('Alpine · Cinematic mountain light') + tap_text('Focus animations · On');text_exists('Focus animations · Off');tap_text('Focus animations · Off') + tap_text('Clock · On');text_exists('Clock · Off');tap_text('Clock · Off');key(4) + ok('Spacing, wallpaper, reduced motion, and clock controls work') + # Long press on a focused tile exposes actual app actions. + key(19);key(20) + adb('shell','input','keyevent','--longpress',23);time.sleep(.5) + text_exists('Move to front');text_exists('Hide from home');key(4) + ok('Hold OK exposes app management') + +elif args.part=='plex': + # Requires scripts/plex_fixture.py running on the host. + adb('reverse','tcp:8765','tcp:8765') + start();key(82);tap_text('Plex media rows');tap_text('Enter server manually') + inputs=[n for n in tree().iter('node') if n.get('class')=='android.widget.EditText'] + assert len(inputs)==2 + for node,value in zip(inputs,['http://127.0.0.1:8765','luma-test-fixture']): + x1,y1,x2,y2=map(int,re.findall(r'\d+',node.get('bounds'))) + adb('shell','input','tap',(x1+x2)//2,(y1+y2)//2) + adb('shell','input','text',value) + key(4) + tap_text('Connect');time.sleep(2) + assert package()=='tv.luma.launcher' + # Move from app grid into optional rows. + key(19);key(20);key(20,20,20,20) + text_exists('Continue watching');text_exists('Alpine at dusk') + (ROOT/'output/luma-media-fixture.png').write_bytes(subprocess.run([ADB,'-s',args.device,'exec-out','screencap','-p'],capture_output=True,check=True).stdout) + ok('Plex connection, encrypted credential storage, Continue Watching, and artwork rendering') + # Open settings and ensure fixture credentials are removed before finishing. + key(82);tap_text('Plex media rows');tap_text('Disconnect Plex') + text_exists('Media rows · Off') + key(4);key(4) + adb('reverse','--remove','tcp:8765') + ok('Disconnect clears test connection and disables media rows') + +elif args.part=='appearance-modes': + start();key(82);tap_text('Appearance') + nodes=list(tree().iter('node')) + label_control=next(n.get('text').split('\n')[0] for n in nodes if n.get('text','').startswith('App labels · ')) + if label_control!='App labels · Focused only': + tap_text(label_control);tap_text('Focused only') + tap_text('Banner · Artwork only');tap_text('Dynamic') + text_exists('Banner · Dynamic');key(4) + assert any('Your library.' in n.get('text','') for n in tree().iter('node')) + key(82);tap_text('Appearance');tap_text('Banner · Dynamic');tap_text('Minimal') + text_exists('Banner · Minimal');key(4) + nodes=list(tree().iter('node')) + first=next(n for n in nodes if n.get('content-desc')=='Plex' and n.get('focusable')=='true') + assert int(re.findall(r'\d+',first.get('bounds'))[1]) < 250 + key(82);tap_text('Appearance');tap_text('Banner · Minimal');tap_text('Artwork only') + tap_text('App labels · Focused only');tap_text('Always') + text_exists('App labels · Always');key(4) + assert any(n.get('text')=='Plezy' for n in tree().iter('node')) + key(82);tap_text('Appearance');tap_text('App labels · Always');tap_text('Never') + text_exists('App labels · Never');key(4) + assert not any(n.get('text')=='Plex' for n in tree().iter('node')) + key(82);tap_text('Appearance');tap_text('App labels · Never');tap_text('Focused only');key(4);key(19,19,20) + nodes=list(tree().iter('node')) + assert any(n.get('text')=='Plex' for n in nodes) + assert not any(n.get('text')=='Plezy' for n in nodes) + assert not any('Your library.' in n.get('text','') for n in nodes) + # Original spacious layout: first full row and a partial second row. + first=next(n for n in nodes if n.get('content-desc')=='Plex' and n.get('focusable')=='true') + assert int(re.findall(r'\d+',first.get('bounds'))[1]) >= 650 + key(3);time.sleep(1);start();key(82);tap_text('Appearance') + text_exists('Banner · Artwork only');text_exists('App labels · Focused only');key(4) + ok('All banner and label modes work; original spacious layout and clean defaults persist') + +elif args.part=='final-defaults': + start();key(82);tap_text('Appearance') + text_exists('Banner · Artwork only');text_exists('App labels · Focused only');key(4);key(19,19,20) + nodes=list(tree().iter('node')) + assert not any('Your library.' in n.get('text','') for n in nodes) + assert any(n.get('text')=='Plex' for n in nodes) + assert not any(n.get('text')=='Plezy' for n in nodes) + first=next(n for n in nodes if n.get('content-desc')=='Plex' and n.get('focusable')=='true') + assert first.get('focused')=='true' + assert int(re.findall(r'\d+',first.get('bounds'))[1]) >= 650 + ok('Artwork only, Focused only labels, and original spacious layout are active') + +elif args.part=='screensaver': + adb('shell','am','force-stop','tv.luma.launcher') + start();key(82);tap_text('Screensaver') + nodes=list(tree().iter('node')) + mode_control=next(n.get('text') for n in nodes if n.get('text','').startswith('Mode · ')) + tap_text(mode_control);tap_text('Art gallery') + nodes=list(tree().iter('node')) + interval_control=next(n.get('text') for n in nodes if n.get('text','').startswith('Photo duration · ')) + tap_text(interval_control);tap_text('15 sec') + tap_text('Preview now');time.sleep(2) + nodes=list(tree().iter('node')) + assert any(n.get('content-desc')=='Luma screensaver' for n in nodes) + titles=['Wheat Field with Cypresses','The Great Wave','The Death of Socrates'] + seen=[] + for index in range(3): + nodes=list(tree().iter('node')) + seen.append(next(n.get('text') for n in nodes if n.get('text') in titles)) + path=ROOT/f'output/luma-art-{index}.png' + path.write_bytes(subprocess.run([ADB,'-s',args.device,'exec-out','screencap','-p'],capture_output=True,check=True).stdout) + bmp=Path('/tmp/luma-frame-check.bmp') + subprocess.run(['sips','-z','64','112','-s','format','bmp',str(path),'--out',str(bmp)],stdout=subprocess.DEVNULL,check=True) + data=bmp.read_bytes();offset=struct.unpack_from('8,('Blank artwork frame',seen[-1]) + assert max(rgb(0,5))<=2,('Matte is not black',rgb(0,5)) + if index<2: + for _ in range(10): + time.sleep(2) + next_nodes=list(tree().iter('node')) + next_title=next((n.get('text') for n in next_nodes if n.get('text') in titles),None) + if next_title and next_title!=seen[-1]:break + assert len(set(seen))==3,seen + ok('All three artwork images render, crossfade, and use pure-black mattes') + key(20) + assert not any(n.get('content-desc')=='Luma screensaver' for n in tree().iter('node')) + assert package()=='tv.luma.launcher' + key(82);tap_text('Screensaver');tap_text('Mode · Art gallery');tap_text('Scenic') + tap_text('Photo duration · 15 sec');tap_text('30 sec');tap_text('Preview now');time.sleep(2) + assert any(n.get('content-desc')=='Luma screensaver' for n in tree().iter('node')) + (ROOT/'output/luma-scenic-screensaver.png').write_bytes(subprocess.run([ADB,'-s',args.device,'exec-out','screencap','-p'],capture_output=True,check=True).stdout) + key(23) + ok('Scenic preview works; D-pad and OK wake without launching an app') + +elif args.part=='screensaver-video': + start();key(82);tap_text('Screensaver');tap_text('Nature video');tap_text('Download bird nature loop') + for _ in range(24): + time.sleep(2) + nodes=list(tree().iter('node')) + if any(n.get('text')=='Screensaver' for n in nodes):break + error=next((n.get('text') for n in nodes if n.get('text','').startswith('Download stopped.')),None) + assert error is None,error + text_exists('Mode · Nature video');tap_text('Preview now');time.sleep(4) + nodes=list(tree().iter('node')) + assert any(n.get('content-desc')=='Luma screensaver' for n in nodes) + assert any(n.get('text')=='Nature loop' for n in nodes) + (ROOT/'output/luma-nature-screensaver.png').write_bytes(subprocess.run([ADB,'-s',args.device,'exec-out','screencap','-p'],capture_output=True,check=True).stdout) + ok('NPS nature video downloads locally and plays in the screensaver') + key(3);time.sleep(3) + assert package()=='tv.luma.launcher' + start();key(82);tap_text('Screensaver');tap_text('Mode · Nature video');tap_text('Scenic');key(4);key(19,19,20) + ok('Home exits video to Luma; scenic mode restored and local video retained for use') + +elif args.part=='screensaver-timeout': + start();key(82);tap_text('Screensaver');tap_text('Idle timeout · 10 min');tap_text('1 min');key(4) + print('Waiting for the 1 minute idle timeout…',flush=True) + time.sleep(63) + assert any(n.get('content-desc')=='Luma screensaver' for n in tree().iter('node')) + key(20);key(82);tap_text('Screensaver');tap_text('Idle timeout · 1 min');tap_text('10 min');key(4);key(19,19,20) + ok('Real 1 minute idle activation works; 10 minute default restored') + +elif args.part=='performance': + start();key(20,20,20,20) + assert focus()=='All apps',focus() + key(19,19,19,19) + assert focus()=='Plex',focus() + ok('Focus scrolls through all rows to the footer and back') + adb('shell','dumpsys','gfxinfo','tv.luma.launcher','reset') + for _ in range(4):key(22,22,20,21,21,19) + (ROOT/'output/luma-focus-frames.txt').write_text(adb('shell','dumpsys','gfxinfo','tv.luma.launcher')) + time.sleep(2) + (ROOT/'output/luma-foreground-memory.txt').write_text(adb('shell','dumpsys','meminfo','tv.luma.launcher')) + adb('shell','am','start','-a','android.settings.SETTINGS');time.sleep(12) + pid=adb('shell','pidof','tv.luma.launcher').strip() + first=adb('shell','cat',f'/proc/{pid}/stat').split() + time.sleep(10) + second=adb('shell','cat',f'/proc/{pid}/stat').split() + ticks=sum(int(second[i])-int(first[i]) for i in [13,14]) + assert ticks==0, f'Background CPU ticks: {ticks}' + ok('Zero background CPU ticks over a 10 second sample') + services=adb('shell','dumpsys','activity','services','tv.luma.launcher') + assert 'LumaHomeService' in services and 'LumaDreamService' not in services + router_pid=adb('shell','pidof','tv.luma.launcher:home').strip() + first=adb('shell','cat',f'/proc/{router_pid}/stat').split() + time.sleep(10) + second=adb('shell','cat',f'/proc/{router_pid}/stat').split() + router_ticks=sum(int(second[i])-int(first[i]) for i in [13,14]) + assert router_ticks==0, f'Idle Home router CPU ticks: {router_ticks}' + (ROOT/'output/luma-home-router-memory.txt').write_text(adb('shell','dumpsys','meminfo',router_pid)) + (ROOT/'output/luma-background-memory.txt').write_text(adb('shell','dumpsys','meminfo','tv.luma.launcher')) + (ROOT/'output/luma-background-cpu.txt').write_text(f'Launcher background CPU ticks in 10 seconds: {ticks}\nHome router idle CPU ticks in 10 seconds: {router_ticks}\n'+services) + ok('Only the separate Home router service is bound; zero idle CPU ticks over 10 seconds') + start() diff --git a/scripts/plex_fixture.py b/scripts/plex_fixture.py new file mode 100644 index 0000000..5fa8b1f --- /dev/null +++ b/scripts/plex_fixture.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Local integration fixture, never used by the shipping launcher. +Serve on loopback and use `adb reverse tcp:8765 tcp:8765` for TV integration QA. +""" +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +import json + +ART = Path(__file__).resolve().parents[1]/'app/src/main/assets/alpine.jpg' + +class Fixture(BaseHTTPRequestHandler): + def log_message(self, *args): pass + def do_GET(self): + if self.headers.get('X-Plex-Token') != 'luma-test-fixture': + self.send_response(401); self.end_headers(); return + if self.path.startswith('/photo/'): + data=ART.read_bytes(); mime='image/jpeg' + elif self.path.startswith('/hubs'): + def item(key,title,progress=0): + return dict(ratingKey=str(key), title=title, type='movie', year=2026, + duration=600000, viewOffset=progress, art='/library/art/alpine', + summary='Local integration test artwork. Not connected to a real Plex library.') + data=json.dumps({'MediaContainer':{'Hub':[ + {'hubIdentifier':'home.continueWatching', 'title':'Continue Watching', + 'Metadata':[item(1,'Alpine at dusk',240000),item(2,'The quiet shore',80000)]}, + {'hubIdentifier':'movie.recentlyAdded', 'title':'Recently Added', + 'Metadata':[item(3,'Beyond the ridge'),item(4,'Blue hour')]} + ]}}).encode(); mime='application/json' + else: + data=json.dumps({'MediaContainer':{'machineIdentifier':'luma-local-fixture'}}).encode();mime='application/json' + self.send_response(200);self.send_header('Content-Type',mime);self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data) + +if __name__=='__main__': + print('Plex test fixture on 127.0.0.1:8765',flush=True) + HTTPServer(('127.0.0.1',8765),Fixture).serve_forever() diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..8e2d6af --- /dev/null +++ b/settings.gradle @@ -0,0 +1,4 @@ +pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } } +dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } } +rootProject.name = 'Luma' +include ':app'