first commit

This commit is contained in:
Elijah Kuntz 2026-10-17 22:38:45 -07:00
commit f5f1c0928f
39 changed files with 4478 additions and 0 deletions

View 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>

Binary file not shown.

After

Width:  |  Height:  |  Size: 461 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 823 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 598 KiB

View 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"
}
]

Binary file not shown.

After

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

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

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

View 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();
}
}

View 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();
}
}
}

View 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();
}
}

View 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();
}
}

File diff suppressed because it is too large Load diff

View 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;
}
}
}

View 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();
}
}

View 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();
}
}

View 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();
}
}

View 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();
}
}

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

View 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>

View 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>

View 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>

View 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>

View 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" />