first commit
This commit is contained in:
commit
f5f1c0928f
39 changed files with 4478 additions and 0 deletions
12
.gitignore
vendored
Normal file
12
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
.tools/
|
||||
build/
|
||||
.gradle/
|
||||
local.properties
|
||||
*.keystore
|
||||
*.jks
|
||||
__pycache__/
|
||||
*.pyc
|
||||
output/*.png
|
||||
output/*.xml
|
||||
output/*.txt
|
||||
output/*.log
|
||||
117
README.md
Normal file
117
README.md
Normal file
|
|
@ -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/).
|
||||
13
app/build.gradle
Normal file
13
app/build.gradle
Normal file
|
|
@ -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 }
|
||||
}
|
||||
33
app/src/main/AndroidManifest.xml
Normal file
33
app/src/main/AndroidManifest.xml
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tv.luma.launcher" android:versionCode="1" android:versionName="1.0.0">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="34" />
|
||||
<uses-feature android:name="android.software.leanback" android:required="true" />
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<queries>
|
||||
<intent><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LEANBACK_LAUNCHER" /></intent>
|
||||
<intent><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent>
|
||||
</queries>
|
||||
<application android:label="Luma" android:icon="@drawable/ic_luma" android:banner="@drawable/banner" android:theme="@style/AppTheme" android:allowBackup="false" android:supportsRtl="true" android:usesCleartextTraffic="true" android:hardwareAccelerated="true" android:largeHeap="false">
|
||||
<activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTask" android:screenOrientation="landscape" android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize" android:excludeFromRecents="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.HOME" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<service android:name=".LumaDreamService" android:exported="true" android:label="Luma screensaver" android:permission="android.permission.BIND_DREAM_SERVICE">
|
||||
<intent-filter><action android:name="android.service.dreams.DreamService" /><category android:name="android.intent.category.DEFAULT" /></intent-filter>
|
||||
</service>
|
||||
<service android:name=".LumaHomeService" android:process=":home" android:exported="true" android:label="@string/home_override_name" android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
|
||||
<intent-filter><action android:name="android.accessibilityservice.AccessibilityService" /></intent-filter>
|
||||
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_accessibility" />
|
||||
</service>
|
||||
<receiver android:name=".HomeControlReceiver" android:process=":home" android:exported="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
BIN
app/src/main/assets/alpine.jpg
Normal file
BIN
app/src/main/assets/alpine.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 461 KiB |
BIN
app/src/main/assets/saver/436105.jpg
Normal file
BIN
app/src/main/assets/saver/436105.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 282 KiB |
BIN
app/src/main/assets/saver/436535.jpg
Normal file
BIN
app/src/main/assets/saver/436535.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 823 KiB |
BIN
app/src/main/assets/saver/45434.jpg
Normal file
BIN
app/src/main/assets/saver/45434.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 598 KiB |
44
app/src/main/assets/saver/catalog.json
Normal file
44
app/src/main/assets/saver/catalog.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
]
|
||||
BIN
app/src/main/assets/saver/earth.jpg
Normal file
BIN
app/src/main/assets/saver/earth.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 239 KiB |
BIN
app/src/main/assets/saver/space.jpg
Normal file
BIN
app/src/main/assets/saver/space.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 192 KiB |
89
app/src/main/java/tv/luma/launcher/AppRepository.java
Normal file
89
app/src/main/java/tv/luma/launcher/AppRepository.java
Normal file
|
|
@ -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<String, Bitmap> icons =
|
||||
new LruCache<String, Bitmap>(3 * 1024 * 1024) {
|
||||
protected int sizeOf(String k, Bitmap b) {
|
||||
return b.getAllocationByteCount();
|
||||
}
|
||||
};
|
||||
|
||||
AppRepository(Context c) {
|
||||
context = c.getApplicationContext();
|
||||
}
|
||||
|
||||
List<App> discover() {
|
||||
PackageManager pm = context.getPackageManager();
|
||||
Map<String, App> 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<App> 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});
|
||||
}
|
||||
}
|
||||
188
app/src/main/java/tv/luma/launcher/AppTile.java
Normal file
188
app/src/main/java/tv/luma/launcher/AppTile.java
Normal file
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
55
app/src/main/java/tv/luma/launcher/FocusScrollView.java
Normal file
55
app/src/main/java/tv/luma/launcher/FocusScrollView.java
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
34
app/src/main/java/tv/luma/launcher/HomeControlReceiver.java
Normal file
34
app/src/main/java/tv/luma/launcher/HomeControlReceiver.java
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
41
app/src/main/java/tv/luma/launcher/LumaDreamService.java
Normal file
41
app/src/main/java/tv/luma/launcher/LumaDreamService.java
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
64
app/src/main/java/tv/luma/launcher/LumaHomeService.java
Normal file
64
app/src/main/java/tv/luma/launcher/LumaHomeService.java
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
1979
app/src/main/java/tv/luma/launcher/MainActivity.java
Normal file
1979
app/src/main/java/tv/luma/launcher/MainActivity.java
Normal file
File diff suppressed because it is too large
Load diff
385
app/src/main/java/tv/luma/launcher/PlexClient.java
Normal file
385
app/src/main/java/tv/luma/launcher/PlexClient.java
Normal file
|
|
@ -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<String> urls = new ArrayList<>();
|
||||
}
|
||||
|
||||
static final class Media {
|
||||
String key, title, subtitle, thumb, art, type;
|
||||
float progress;
|
||||
}
|
||||
|
||||
static final class Library {
|
||||
final List<Media> 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<String, Bitmap> images =
|
||||
new LruCache<String, Bitmap>(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<Server> 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<Server> 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<Media> out) throws JSONException {
|
||||
if (entries == null) return;
|
||||
Set<String> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
281
app/src/main/java/tv/luma/launcher/SaverMedia.java
Normal file
281
app/src/main/java/tv/luma/launcher/SaverMedia.java
Normal file
|
|
@ -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<Entry> entries(String album) {
|
||||
LinkedHashMap<String, Entry> 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();
|
||||
}
|
||||
}
|
||||
99
app/src/main/java/tv/luma/launcher/SaverPictureView.java
Normal file
99
app/src/main/java/tv/luma/launcher/SaverPictureView.java
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
240
app/src/main/java/tv/luma/launcher/SaverView.java
Normal file
240
app/src/main/java/tv/luma/launcher/SaverView.java
Normal file
|
|
@ -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<SaverMedia.Entry> 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();
|
||||
}
|
||||
}
|
||||
228
app/src/main/java/tv/luma/launcher/SceneView.java
Normal file
228
app/src/main/java/tv/luma/launcher/SceneView.java
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
57
app/src/main/java/tv/luma/launcher/Ui.java
Normal file
57
app/src/main/java/tv/luma/launcher/Ui.java
Normal file
|
|
@ -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});
|
||||
}
|
||||
}
|
||||
5
app/src/main/res/drawable/banner.xml
Normal file
5
app/src/main/res/drawable/banner.xml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="320dp" android:height="180dp" android:viewportWidth="320" android:viewportHeight="180">
|
||||
<path android:fillColor="#101A2D" android:pathData="M0,0h320v180h-320z" />
|
||||
<path android:fillColor="#E8CBA6" android:pathData="M126,49h14v65h53v14h-67z" />
|
||||
<path android:fillColor="#F5E8D5" android:pathData="M187,48a11,11 0,1 0,0.1,0z" />
|
||||
</vector>
|
||||
5
app/src/main/res/drawable/ic_luma.xml
Normal file
5
app/src/main/res/drawable/ic_luma.xml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
|
||||
<path android:fillColor="#101A2D" android:pathData="M0,0h108v108h-108z" />
|
||||
<path android:fillColor="#E8CBA6" android:pathData="M30,26h11v45h37v11h-48z" />
|
||||
<path android:fillColor="#F5E8D5" android:pathData="M70,26a9,9 0,1 0,0.1,0z" />
|
||||
</vector>
|
||||
4
app/src/main/res/values/strings.xml
Normal file
4
app/src/main/res/values/strings.xml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
<resources>
|
||||
<string name="home_override_name">Luma Home button</string>
|
||||
<string name="home_override_description">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.</string>
|
||||
</resources>
|
||||
12
app/src/main/res/values/styles.xml
Normal file
12
app/src/main/res/values/styles.xml
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<resources>
|
||||
<style name="AppTheme" parent="android:style/Theme.Material.NoActionBar">
|
||||
<item name="android:fontFamily">sans</item>
|
||||
<item name="android:windowActionModeOverlay">true</item>
|
||||
<item name="android:windowFullscreen">true</item>
|
||||
<item name="android:windowBackground">#080D18</item>
|
||||
<item name="android:colorAccent">#E8CBA6</item>
|
||||
<item name="android:windowLightStatusBar">false</item>
|
||||
<item name="android:windowLightNavigationBar">false</item>
|
||||
<item name="android:windowNoTitle">true</item>
|
||||
</style>
|
||||
</resources>
|
||||
10
app/src/main/res/xml/home_accessibility.xml
Normal file
10
app/src/main/res/xml/home_accessibility.xml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:accessibilityEventTypes="typeWindowStateChanged"
|
||||
android:packageNames="com.google.android.apps.tv.launcherx,com.spocky.projengmenu"
|
||||
android:accessibilityFeedbackType="feedbackGeneric"
|
||||
android:notificationTimeout="80"
|
||||
android:accessibilityFlags="flagRequestFilterKeyEvents"
|
||||
android:canRequestFilterKeyEvents="true"
|
||||
android:canRetrieveWindowContent="false"
|
||||
android:description="@string/home_override_description"
|
||||
android:settingsActivity="tv.luma.launcher.MainActivity" />
|
||||
1
build.gradle
Normal file
1
build.gradle
Normal file
|
|
@ -0,0 +1 @@
|
|||
plugins { id 'com.android.application' version '8.5.2' apply false }
|
||||
21
docs/ASSETS.md
Normal file
21
docs/ASSETS.md
Normal file
|
|
@ -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.
|
||||
41
docs/VALIDATION.md
Normal file
41
docs/VALIDATION.md
Normal file
|
|
@ -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`.
|
||||
BIN
output/Luma.apk
Normal file
BIN
output/Luma.apk
Normal file
Binary file not shown.
BIN
output/Luma.apk.idsig
Normal file
BIN
output/Luma.apk.idsig
Normal file
Binary file not shown.
30
scripts/bootstrap.sh
Executable file
30
scripts/bootstrap.sh
Executable file
|
|
@ -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.'
|
||||
26
scripts/build.sh
Executable file
26
scripts/build.sh
Executable file
|
|
@ -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"
|
||||
325
scripts/device_smoke.py
Normal file
325
scripts/device_smoke.py
Normal file
|
|
@ -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('<I',data,10)[0]
|
||||
width,height=struct.unpack_from('<ii',data,18);bits=struct.unpack_from('<H',data,28)[0]
|
||||
assert bits==32
|
||||
rowbytes=width*4
|
||||
def rgb(x,y):
|
||||
yy=y if height<0 else abs(height)-1-y
|
||||
b,g,r,_=data[offset+yy*rowbytes+x*4:offset+yy*rowbytes+x*4+4]
|
||||
return r,g,b
|
||||
luminance=[sum(rgb(x,y))/3 for y in range(8,42) for x in range(22,90)]
|
||||
assert statistics.pstdev(luminance)>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()
|
||||
35
scripts/plex_fixture.py
Normal file
35
scripts/plex_fixture.py
Normal file
|
|
@ -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()
|
||||
4
settings.gradle
Normal file
4
settings.gradle
Normal file
|
|
@ -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'
|
||||
Loading…
Add table
Add a link
Reference in a new issue