Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
Launcher: module cards, a card an app declares for its tile and the owner approves on the TV
udhaykumarbalaa33b65fb919d
diff --git a/launcher/app/src/main/AndroidManifest.xml b/launcher/app/src/main/AndroidManifest.xmlindex 6c35fd86e..51bc9fa13 100644--- a/launcher/app/src/main/AndroidManifest.xml+++ b/launcher/app/src/main/AndroidManifest.xml@@ -11,12 +11,17 @@<!-- Needed on Android 10 to read the Wi-Fi network name; granted over adb at install time. --><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />- <!-- Android 11+ package visibility: lets the launcher list the TV apps it shows as tiles. -->+ <!-- Android 11+ package visibility: lets the launcher list the TV apps it shows as tiles, and the+ apps that declare a module card (docs/specs/card.md). --><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="com.gathin.tvhome.category.DOCK_CARD" />+ </intent></queries><applicationdiff --git a/launcher/app/src/main/java/com/gathin/tvhome/AppAdapter.java b/launcher/app/src/main/java/com/gathin/tvhome/AppAdapter.javaindex 7b7b88c3a..489e74250 100644--- a/launcher/app/src/main/java/com/gathin/tvhome/AppAdapter.java+++ b/launcher/app/src/main/java/com/gathin/tvhome/AppAdapter.java@@ -30,13 +30,15 @@ import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;+import java.util.HashMap;import java.util.HashSet;import java.util.List;+import java.util.Map;import java.util.Set;/*** App tiles. The first {@link MainActivity#COLUMNS} positions are the pinned dock (favourites, fixed order),- * the rest is alphabetical.+ * then the module cards the owner chose to show (by label), the rest is alphabetical.*/public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {@@ -48,19 +50,32 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {}static final class Entry {+ static final int APP = 0, HOME_SETTINGS = 1, CARD = 2;++ final int kind;final String label;final ComponentName component;final String pkg;final Drawable banner;final Drawable icon;+ /** Text under the tile when it is focused in the grid: the label, plus the caption for a card. */+ final String name;+ /** Ambient glow colour; 0 until sampled from the banner, or the card's accent from the start. */int ambient;Entry(String label, ComponentName component, Drawable banner, Drawable icon) {+ this(APP, label, component, banner, icon, null, 0);+ }++ Entry(int kind, String label, ComponentName component, Drawable banner, Drawable icon, String caption, int accent) {+ this.kind = kind;this.label = label;this.component = component;this.pkg = component.getPackageName();this.banner = banner;this.icon = icon;+ this.name = caption == null ? label : label + " \u00B7 " + caption;+ this.ambient = accent;}}@@ -111,20 +126,32 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {setHasStableIds(true);}- void reload() {+ /**+ * Rebuilds the tiles. A shown module card stands in for every tile of its package (same component,+ * so focus follows it); hidden_apps wins over a card, and a card's package in dock_apps takes that slot.+ */+ void reload(List<Cards.Card> cards) {PackageManager pm = ctx.getPackageManager();Intent probe = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER);List<ResolveInfo> found = pm.queryIntentActivities(probe, 0);+ Map<String, Cards.Card> cardByPkg = new HashMap<>();+ for (Cards.Card c : cards) cardByPkg.put(c.pkg, c);List<Entry> fresh = new ArrayList<>();for (ResolveInfo ri : found) {if (ri.activityInfo == null) continue;String pkg = ri.activityInfo.packageName;if (pkg.equals(ctx.getPackageName()) || hidden.contains(pkg)) continue;+ ComponentName component = new ComponentName(pkg, ri.activityInfo.name);+ Cards.Card card = cardByPkg.get(pkg);+ if (card != null && !card.component.equals(component)) continue; // the card stands in for this tileDrawable banner = ri.activityInfo.loadBanner(pm);if (banner == null) banner = ri.activityInfo.applicationInfo.loadBanner(pm);Drawable icon = ri.loadIcon(pm);- String label = String.valueOf(ri.loadLabel(pm));- fresh.add(new Entry(label, new ComponentName(pkg, ri.activityInfo.name), banner, icon));+ if (card != null) {+ fresh.add(new Entry(Entry.CARD, card.label, component, banner, icon, card.caption, card.accent));+ } else {+ fresh.add(new Entry(String.valueOf(ri.loadLabel(pm)), component, banner, icon));+ }}Collections.sort(fresh, (a, b) -> {int fa = favourites.indexOf(a.pkg), fb = favourites.indexOf(b.pkg);@@ -133,14 +160,17 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {if (fb < 0) return -1;return Integer.compare(fa, fb);}+ // Cards come right after the configured dock apps, before the alphabetical grid.+ boolean ca = a.kind == Entry.CARD, cb = b.kind == Entry.CARD;+ if (ca != cb) return ca ? -1 : 1;return a.label.compareToIgnoreCase(b.label);});// Optional "Default home" tile (config.xml), only when this TV actually has a home-screen picker.if (showHomeSettings&& pm.resolveActivity(new Intent(Settings.ACTION_HOME_SETTINGS), 0) != null) {- fresh.add(new Entry(ctx.getString(R.string.home_settings),+ fresh.add(new Entry(Entry.HOME_SETTINGS, ctx.getString(R.string.home_settings),new ComponentName(ctx, HomeSettingsActivity.class), null,- ctx.getDrawable(R.drawable.ic_home_settings)));+ ctx.getDrawable(R.drawable.ic_home_settings), null, 0));}items.clear();items.addAll(fresh);@@ -171,7 +201,7 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {@Overridepublic void onBindViewHolder(@NonNull Holder h, int position) {Entry e = items.get(position);- h.name.setText(e.label);+ h.name.setText(e.name);h.name.setVisibility(position < dockSize ? View.INVISIBLE : View.VISIBLE); // the dock has no labelsboolean focused = h.card.isFocused(); // a rebind after reload() can hit the focused tileh.name.setAlpha(focused ? 1f : 0f);@@ -202,8 +232,9 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {});}+ /** Opens the tile's activity by explicit component, with no extras: a card can name nothing else. */private void launch(Entry e) {- if (e.component.equals(new ComponentName(ctx, HomeSettingsActivity.class))) {+ if (e.kind == Entry.HOME_SETTINGS) {ctx.startActivity(new Intent(ctx, HomeSettingsActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));return;@@ -247,7 +278,7 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {return position >= 0 && position < items.size() ? items.get(position).label : "";}- /** A vivid colour sampled from the app's banner (or icon), cached per entry. */+ /** A vivid colour sampled from the app's banner (or icon), cached per entry; a card's accent when it set one. */int ambientColorAt(int position) {if (position < 0 || position >= items.size()) return 0xFF444444;Entry e = items.get(position);diff --git a/launcher/app/src/main/java/com/gathin/tvhome/CardFeature.java b/launcher/app/src/main/java/com/gathin/tvhome/CardFeature.javanew file mode 100644index 000000000..89fc0f3a3--- /dev/null+++ b/launcher/app/src/main/java/com/gathin/tvhome/CardFeature.java@@ -0,0 +1,55 @@+package com.gathin.tvhome;++import android.util.Log;++/**+ * The guard around the module card feature: every call from the home screen into {@link Cards}+ * goes through {@link #run}. The first failure of any kind that is safe to catch (an exception, or+ * the class failing to load or initialise) is logged once and switches cards off for the rest of+ * the process, so Home keeps working exactly as with module_cards false. Out of memory and other+ * virtual machine errors are not caught.+ */+final class CardFeature {++ interface Step<T> {+ T run() throws Exception;+ }++ interface Reporter {+ void failed(Throwable t);+ }++ private static boolean broken;+ /** Where the one failure line goes; tests replace it, since android.util.Log is not available there. */+ static Reporter reporter = t -> Log.w(Cards.TAG, "module cards switched off for this session: " + t);++ private CardFeature() {+ }++ /** True while the feature has not failed in this process. */+ static boolean working() {+ return !broken;+ }++ /** Runs one step and returns its value, or the fallback once the feature is off or the step fails. */+ static <T> T run(Step<T> step, T fallback) {+ if (broken) return fallback;+ try {+ return step.run();+ } catch (Exception | LinkageError e) {+ // LinkageError covers ExceptionInInitializerError and NoClassDefFoundError: a static+ // initialiser that throws on this device's runtime must not take the home screen down.+ broken = true;+ try {+ reporter.failed(e);+ } catch (Exception ignored) {+ }+ return fallback;+ }+ }++ /** For tests only: forget a failure. */+ static void reset() {+ broken = false;+ }+}diff --git a/launcher/app/src/main/java/com/gathin/tvhome/Cards.java b/launcher/app/src/main/java/com/gathin/tvhome/Cards.javanew file mode 100644index 000000000..2f085cc62--- /dev/null+++ b/launcher/app/src/main/java/com/gathin/tvhome/Cards.java@@ -0,0 +1,834 @@+package com.gathin.tvhome;++import android.content.ComponentName;+import android.content.Context;+import android.content.Intent;+import android.content.pm.ActivityInfo;+import android.content.pm.ApplicationInfo;+import android.content.pm.PackageInfo;+import android.content.pm.PackageManager;+import android.content.pm.ResolveInfo;+import android.content.pm.Signature;+import android.content.pm.SigningInfo;+import android.content.res.Resources;+import android.content.res.XmlResourceParser;+import android.os.Build;+import android.util.AtomicFile;+import android.util.Log;++import org.xmlpull.v1.XmlPullParser;++import java.io.File;+import java.io.FileOutputStream;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.security.MessageDigest;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.TreeMap;++/**+ * Module cards (docs/specs/card.md): an installed app can declare a card for its tile, with its own+ * label, caption and glow colour. Nothing is shown until the TV owner says so on the prompt; the+ * decision is pinned to the app's signing certificate in the launcher's private storage.+ *+ * Discovery, parsing, the signer digest and the decision file live here, with no UI code, so the+ * part that reads untrusted input can be read on its own. Every module input is bounded and every+ * card is read inside its own try: a bad card is dropped with one log line, never a crash.+ *+ * No regular expressions and nothing in a static initialiser that can throw: the launcher's regex+ * engine (ICU) differs from the desktop JVM's, and a failure while loading this class would take+ * Home down. Every check is a plain character loop; see {@link CardFeature} for the guard around+ * every call into this class.+ */+final class Cards {++ /** One place for the names a module declares; see docs/specs/card.md. */+ static final String CATEGORY = "com.gathin.tvhome.category.DOCK_CARD";+ static final String META_DATA = "com.gathin.tvhome.card";+ static final int SPEC_SUPPORTED = 1;+ /** logcat tag for every rejection: `logcat -s TvHomeCards`. */+ static final String TAG = "TvHomeCards";++ // Limits. Declared: cards read per resume. Shown: cards rendered as tiles. Records: decisions remembered.+ static final int MAX_DECLARED = 32;+ static final int MAX_SHOWN = 8;+ static final int MAX_RECORDS = 128;+ // XML: events walked and nesting depth before the card is rejected; attributes read on the root.+ static final int MAX_EVENTS = 64;+ static final int MAX_DEPTH = 2;+ static final int MAX_ATTRIBUTES = 16;+ static final int LABEL_MAX = 24;+ static final int CAPTION_MAX = 32;++ static final String STORE_FILE = "cards.json";+ static final String DECISION_SHOW = "show";+ static final String DECISION_HIDE = "hide";++ /** Label and caption punctuation; letters, digits and the space are the rest of the alphabet (ASCII only). */+ private static final String TEXT_PUNCTUATION = ".&+'-";++ /** Words that imply endorsement: rejected anywhere in a label (folded form). */+ private static final String[] RESERVED_ANYWHERE = {"verified", "official"};+ /** Names the launcher's own UI renders (pills, tiles, the Inputs menu): rejected as a whole label. */+ private static final Set<String> RESERVED_EXACT = new HashSet<>(Arrays.asList(+ "tvvibehack", "settings", "inputs", "livetv", "home", "defaulthome", "wifi", "av"));+ /** "HDMI", "HDMI 1", "HDMI2"... */+ private static final String RESERVED_PREFIX = "hdmi";++ enum State {+ /** No record for this package: the prompt is due. */+ NEW,+ /** The record was made for a different signing key: it no longer applies and the prompt is due. */+ RESIGNED,+ SHOWN,+ HIDDEN+ }++ /** A valid card found on this TV, with the owner's decision for its current signer. */+ static final class Card {+ final String pkg;+ final ComponentName component;+ final String label;+ /** The app's own label, the one Settings shows. */+ final String appLabel;+ /** Null when the card has none. */+ final String caption;+ /** Opaque ARGB, or 0 when the card sets none. */+ final int accent;+ /** SHA-256 of the signing certificate, 64 lower case hex characters. */+ final String digest;+ final State state;++ Card(String pkg, ComponentName component, String label, String appLabel, String caption, int accent,+ String digest, State state) {+ this.pkg = pkg;+ this.component = component;+ this.label = label;+ this.appLabel = appLabel;+ this.caption = caption;+ this.accent = accent;+ this.digest = digest;+ this.state = state;+ }++ boolean pending() {+ return state == State.NEW || state == State.RESIGNED;+ }+ }++ /** The owner's decision for one package, valid only while the package is signed with this key. */+ static final class Record {+ final String pkg;+ final String digest;+ final String decision;+ final long firstSeen;+ final long decidedAt;++ Record(String pkg, String digest, String decision, long firstSeen, long decidedAt) {+ this.pkg = pkg;+ this.digest = digest;+ this.decision = decision;+ this.firstSeen = firstSeen;+ this.decidedAt = decidedAt;+ }+ }++ /** The attributes of a `<card>` element after the limits were checked. */+ static final class Declared {+ final int spec;+ final String label;+ final String caption;+ final int accent;++ Declared(int spec, String label, String caption, int accent) {+ this.spec = spec;+ this.label = label;+ this.caption = caption;+ this.accent = accent;+ }+ }++ /** A card rejected for a stated reason; the reason goes to logcat under {@link #TAG}. */+ static final class CardException extends Exception {+ CardException(String reason) {+ super(reason);+ }+ }++ private Cards() {+ }++ // ---- discovery -------------------------------------------------------------------------------++ /**+ * Every valid card installed on this TV, with its state under the given records. One cheap+ * PackageManager query when no app declares a card; the app list is only walked when one does.+ * hidden is the launcher's hidden_apps as in force (config.xml or a theme overlay): no card for those.+ */+ static List<Card> discover(Context ctx, Set<String> hidden, Map<String, Record> records) {+ if ((ctx.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) selfCheck();+ List<Card> out = new ArrayList<>();+ PackageManager pm = ctx.getPackageManager();+ List<ResolveInfo> declared;+ try {+ declared = pm.queryIntentActivities(new Intent(Intent.ACTION_MAIN).addCategory(CATEGORY),+ PackageManager.GET_META_DATA);+ } catch (Exception e) {+ Log.w(TAG, "card query failed: " + e);+ return out;+ }+ if (declared.isEmpty()) return out;++ // What the card must agree with: the activities shown as tiles, and the names already on screen.+ Set<String> tiles = new HashSet<>();+ Map<String, Set<String>> names = new HashMap<>();+ for (ResolveInfo ri : pm.queryIntentActivities(+ new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER), 0)) {+ if (ri.activityInfo == null) continue;+ String pkg = ri.activityInfo.packageName;+ tiles.add(new ComponentName(pkg, ri.activityInfo.name).flattenToString());+ try {+ addName(names, String.valueOf(ri.loadLabel(pm)), pkg);+ addName(names, String.valueOf(ri.activityInfo.applicationInfo.loadLabel(pm)), pkg);+ } catch (Exception e) {+ Log.w(TAG, pkg + ": label unreadable, " + e); // an app with broken resources; not a card problem+ }+ }+ Set<String> uiNames = uiNames(ctx.getResources());+ Set<String> seen = new HashSet<>();++ int n = 0;+ for (ResolveInfo ri : declared) {+ if (++n > MAX_DECLARED) {+ Log.w(TAG, "more than " + MAX_DECLARED + " cards declared; the rest are ignored");+ break;+ }+ String pkg = ri.activityInfo != null ? ri.activityInfo.packageName : "?";+ try {+ Card card = read(ctx, pm, ri, tiles, names, uiNames, hidden, seen, records);+ seen.add(card.pkg);+ out.add(card);+ } catch (CardException e) {+ Log.w(TAG, pkg + ": " + e.getMessage());+ } catch (Exception e) {+ // Package gone between the query and the read, a resource that is not XML, and anything else.+ Log.w(TAG, pkg + ": " + e);+ }+ }++ List<Card> kept = resolveClashes(out, records);+ for (Card c : out) {+ if (!kept.contains(c)) Log.w(TAG, c.pkg + ": another card is also named '" + c.label + "'");+ }+ return kept;+ }++ /**+ * Cards that share a folded label: the one the owner already decided on keeps its name (the+ * oldest decision wins, then the smaller package name), every other card in the group is+ * dropped. A group without a decided card is dropped entirely, so nobody is asked about a+ * contested name. A decision the owner made is never undone by a newer install.+ */+ static List<Card> resolveClashes(List<Card> cards, Map<String, Record> records) {+ Map<String, List<Card>> groups = new HashMap<>();+ for (Card c : cards) {+ String key = fold(c.label);+ List<Card> group = groups.get(key);+ if (group == null) groups.put(key, group = new ArrayList<>());+ group.add(c);+ }+ List<Card> kept = new ArrayList<>();+ for (Card c : cards) {+ List<Card> group = groups.get(fold(c.label));+ if (group.size() == 1) {+ kept.add(c);+ continue;+ }+ Card winner = null;+ for (Card g : group) {+ if (g.pending()) continue;+ if (winner == null || olderDecision(g, winner, records)) winner = g;+ }+ if (winner == c) kept.add(c);+ }+ return kept;+ }++ /** True when a's record was made before b's (tie: smaller package name). */+ private static boolean olderDecision(Card a, Card b, Map<String, Record> records) {+ Record ra = records.get(a.pkg), rb = records.get(b.pkg);+ long fa = ra != null ? ra.firstSeen : Long.MAX_VALUE, fb = rb != null ? rb.firstSeen : Long.MAX_VALUE;+ if (fa != fb) return fa < fb;+ return a.pkg.compareTo(b.pkg) < 0;+ }++ private static Card read(Context ctx, PackageManager pm, ResolveInfo ri, Set<String> tiles,+ Map<String, Set<String>> names, Set<String> uiNames, Set<String> hidden,+ Set<String> seen, Map<String, Record> records) throws Exception {+ ActivityInfo ai = ri.activityInfo;+ if (ai == null) throw new CardException("not an activity");+ String pkg = ai.packageName;+ if (pkg.equals(ctx.getPackageName())) throw new CardException("the launcher itself");+ if (hidden.contains(pkg)) throw new CardException("listed in hidden_apps");+ if (seen.contains(pkg)) throw new CardException("declares a second card; one per package is read");+ if (!ai.exported || !ai.enabled || !ai.applicationInfo.enabled) {+ throw new CardException("card activity is not exported and enabled");+ }+ ComponentName component = new ComponentName(pkg, ai.name);+ if (!tiles.contains(component.flattenToString())) {+ throw new CardException("card activity has no LEANBACK_LAUNCHER intent filter");+ }++ XmlResourceParser xml = ai.loadXmlMetaData(pm, META_DATA);+ if (xml == null) throw new CardException("no <meta-data android:name=\"" + META_DATA + "\" android:resource=...>");+ Declared d;+ try {+ d = parse(xml);+ } finally {+ xml.close();+ }+ if (d.spec != SPEC_SUPPORTED) throw new CardException("spec " + d.spec + " is not supported (this launcher reads spec " + SPEC_SUPPORTED + ")");++ String digest = digest(pm, pkg);+ Record r = records.get(pkg);+ State state;+ if (r == null) state = State.NEW;+ else if (!r.digest.equals(digest)) state = State.RESIGNED;+ else state = DECISION_SHOW.equals(r.decision) ? State.SHOWN : State.HIDDEN;+ boolean pending = state == State.NEW || state == State.RESIGNED;++ // Reserved words are policy and always apply. Name collisions only matter while the prompt is+ // due: they stop a newcomer from borrowing a name, and never undo a decision the owner made.+ String folded = fold(d.label);+ if (isReserved(folded, uiNames)) throw new CardException("label '" + d.label + "' is reserved");+ if (pending && isTaken(folded, pkg, names)) throw new CardException("label '" + d.label + "' is the name of another installed app");+ String appLabel = cleanLabel(String.valueOf(ai.applicationInfo.loadLabel(pm)), pkg);+ if (pending && isTaken(fold(appLabel), pkg, names)) throw new CardException("app label '" + appLabel + "' is the name of another installed app");++ return new Card(pkg, component, d.label, appLabel, d.caption, d.accent, digest, state);+ }++ private static void addName(Map<String, Set<String>> names, String label, String pkg) {+ String key = fold(label);+ if (key.isEmpty()) return;+ Set<String> pkgs = names.get(key);+ if (pkgs == null) names.put(key, pkgs = new HashSet<>());+ pkgs.add(pkg);+ }++ /** The launcher's own UI names in the TV's language, folded. */+ private static Set<String> uiNames(Resources res) {+ int[] ids = {R.string.app_name, R.string.settings, R.string.inputs, R.string.choose_input, R.string.wifi,+ R.string.live_tv, R.string.home_settings, R.string.dream_name};+ Set<String> out = new HashSet<>();+ for (int id : ids) out.add(fold(res.getString(id)));+ return out;+ }++ /** Shown cards in the order they take on screen: by label, at most {@link #MAX_SHOWN}. */+ static List<Card> shown(List<Card> cards) {+ List<Card> out = new ArrayList<>();+ for (Card c : cards) if (c.state == State.SHOWN) out.add(c);+ Collections.sort(out, Cards::byLabel);+ return out.size() > MAX_SHOWN ? new ArrayList<>(out.subList(0, MAX_SHOWN)) : out;+ }++ /** The card whose prompt is due next, or null. Package order, so repeated prompts come in one order. */+ static Card firstPending(List<Card> cards) {+ Card best = null;+ for (Card c : cards) {+ if (c.pending() && (best == null || c.pkg.compareTo(best.pkg) < 0)) best = c;+ }+ return best;+ }++ static int byLabel(Card a, Card b) {+ int c = a.label.compareToIgnoreCase(b.label);+ return c != 0 ? c : a.pkg.compareTo(b.pkg);+ }++ // ---- parser ----------------------------------------------------------------------------------++ /**+ * Reads one `<card spec="1" label=".." caption=".." accent="#RRGGBB"/>`. The document may hold at+ * most {@link #MAX_EVENTS} events and nest at most {@link #MAX_DEPTH} deep; child elements and+ * unknown attributes are ignored. Rejects, never guesses.+ */+ static Declared parse(XmlPullParser p) throws Exception {+ int events = 0;+ Declared found = null;+ for (int type = p.getEventType(); type != XmlPullParser.END_DOCUMENT; type = p.next()) {+ if (++events > MAX_EVENTS) throw new CardException("more than " + MAX_EVENTS + " XML events");+ if (type != XmlPullParser.START_TAG) continue;+ if (p.getDepth() > MAX_DEPTH) throw new CardException("XML nested deeper than " + MAX_DEPTH);+ if (p.getDepth() != 1) continue;+ if (found != null) throw new CardException("more than one root element");+ String name = p.getName();+ if (!"card".equals(name)) throw new CardException("root element is <" + name + ">, expected <card>");+ found = readCard(p);+ }+ if (found == null) throw new CardException("no <card> element");+ return found;+ }++ private static Declared readCard(XmlPullParser p) throws Exception {+ int count = p.getAttributeCount();+ if (count > MAX_ATTRIBUTES) throw new CardException("more than " + MAX_ATTRIBUTES + " attributes on <card>");+ String spec = null, label = null, caption = null, accent = null;+ for (int i = 0; i < count; i++) {+ String ns = p.getAttributeNamespace(i);+ if (ns != null && !ns.isEmpty()) continue;+ String name = p.getAttributeName(i);+ if (name == null || name.length() > 8) continue;+ switch (name) {+ case "spec":+ spec = p.getAttributeValue(i);+ break;+ case "label":+ label = p.getAttributeValue(i);+ break;+ case "caption":+ caption = p.getAttributeValue(i);+ break;+ case "accent":+ accent = p.getAttributeValue(i);+ break;+ default:+ break;+ }+ }+ // Lengths first, before any pattern or comparison touches the value.+ // The compiler stores spec="1" as an integer; the parser hands it back as the decimal text "1".+ if (spec == null || spec.isEmpty() || spec.length() > 3 || !isDigits(spec)) throw new CardException("spec is missing or not a small integer");+ String reason = checkLabel(label);+ if (reason != null) throw new CardException(reason);+ reason = checkCaption(caption);+ if (reason != null) throw new CardException(reason);+ int colour = 0;+ if (accent != null && !accent.isEmpty()) {+ if (isReference(accent)) throw new CardException("accent is a resource reference; write #RRGGBB itself");+ colour = parseAccent(accent);+ if (colour == 0) throw new CardException("accent is not #RRGGBB");+ }+ return new Declared(Integer.parseInt(spec), label, caption == null || caption.isEmpty() ? null : caption, colour);+ }++ // ---- validators (pure Java, unit tested) -----------------------------------------------------++ /** Null when the label is acceptable, else the reason. */+ static String checkLabel(String label) {+ if (label == null || label.isEmpty()) return "label is missing";+ if (label.length() > LABEL_MAX) return "label is longer than " + LABEL_MAX + " characters";+ if (isReference(label)) return "label is a resource reference; write the text itself";+ if (!isText(label)) return "label has characters outside A-Z a-z 0-9 space . & + ' -";+ if (label.charAt(0) == ' ' || label.charAt(label.length() - 1) == ' ') return "label starts or ends with a space";+ if (fold(label).isEmpty()) return "label has no letter or digit";+ return null;+ }++ /** Null when the caption is acceptable (absent counts as acceptable), else the reason. */+ static String checkCaption(String caption) {+ if (caption == null || caption.isEmpty()) return null;+ if (caption.length() > CAPTION_MAX) return "caption is longer than " + CAPTION_MAX + " characters";+ if (isReference(caption)) return "caption is a resource reference; write the text itself";+ if (!isText(caption)) return "caption has characters outside A-Z a-z 0-9 space . & + ' -";+ if (caption.charAt(0) == ' ' || caption.charAt(caption.length() - 1) == ' ') return "caption starts or ends with a space";+ return null;+ }++ /**+ * An app's own label as the prompt shows it: control, format (bidi overrides, zero width joiners),+ * line and paragraph separator characters become spaces, runs of spaces collapse, at most 40+ * characters (never cutting a surrogate pair), the fallback (package name) when nothing is left.+ */+ static String cleanLabel(String s, String fallback) {+ if (s == null) return fallback;+ StringBuilder b = new StringBuilder(Math.min(s.length(), 48));+ boolean space = true; // leading spaces are dropped too+ for (int i = 0; i < s.length(); i++) {+ char c = s.charAt(i);+ int type = Character.getType(c);+ boolean blank = c == ' ' || Character.isISOControl(c) || Character.isWhitespace(c) || type == Character.FORMAT+ || type == Character.LINE_SEPARATOR || type == Character.PARAGRAPH_SEPARATOR+ || type == Character.SPACE_SEPARATOR;+ if (blank) {+ if (!space) b.append(' ');+ space = true;+ continue;+ }+ boolean pair = Character.isHighSurrogate(c) && i + 1 < s.length() && Character.isLowSurrogate(s.charAt(i + 1));+ if (b.length() + (pair ? 2 : 1) > 40) break;+ b.append(c);+ if (pair) b.append(s.charAt(++i));+ space = false;+ }+ String out = b.toString().trim();+ return out.isEmpty() ? fallback : out;+ }++ /**+ * A compiled `@string/x` or `?attr/x` reference: the resource compiler stores it as an id and the+ * parser hands back "@2131..." or "?2130...". Spec 1 takes literal text only.+ */+ static boolean isReference(String value) {+ return value.startsWith("@") || value.startsWith("?");+ }++ /** Lower case with everything but ASCII letters and digits removed: the form every name comparison uses. */+ static String fold(String s) {+ if (s == null) return "";+ StringBuilder b = new StringBuilder(s.length());+ for (int i = 0; i < s.length(); i++) {+ char c = Character.toLowerCase(s.charAt(i));+ if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) b.append(c);+ }+ return b.toString();+ }++ /** True when a folded label claims endorsement or a name the launcher's UI uses (uiNames are folded too). */+ static boolean isReserved(String folded, Set<String> uiNames) {+ if (folded.isEmpty()) return true;+ for (String word : RESERVED_ANYWHERE) if (folded.contains(word)) return true;+ if (folded.startsWith(RESERVED_PREFIX)) return true;+ return RESERVED_EXACT.contains(folded) || uiNames.contains(folded);+ }++ /** True when another package than pkg already uses this folded name. */+ static boolean isTaken(String folded, String pkg, Map<String, Set<String>> names) {+ Set<String> pkgs = names.get(folded);+ if (pkgs == null) return false;+ for (String p : pkgs) if (!p.equals(pkg)) return true;+ return false;+ }++ /** Opaque ARGB for `#RRGGBB` (or the compiled `#AARRGGBB` form, alpha dropped), 0 when it is anything else. */+ static int parseAccent(String s) {+ if (s == null || (s.length() != 7 && s.length() != 9) || s.charAt(0) != '#') return 0;+ String hex = s.substring(1);+ if (!isHex(hex, false)) return 0;+ // `#RRGGBB` as written, or `#AARRGGBB` as the resource compiler stores a colour attribute (it+ // compiles `#E8A33D` to the colour value and the parser hands back `#ffe8a33d`). The alpha is dropped.+ return 0xFF000000 | Integer.parseInt(hex.substring(hex.length() - 6), 16);+ }++ // ---- character checks (no regular expressions, see the class comment) -----------------------++ /** Every character is an ASCII letter, digit, space or one of {@link #TEXT_PUNCTUATION}. */+ static boolean isText(String s) {+ for (int i = 0; i < s.length(); i++) {+ char c = s.charAt(i);+ boolean ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == ' '+ || TEXT_PUNCTUATION.indexOf(c) >= 0;+ if (!ok) return false;+ }+ return true;+ }++ static boolean isDigits(String s) {+ if (s.isEmpty()) return false;+ for (int i = 0; i < s.length(); i++) {+ char c = s.charAt(i);+ if (c < '0' || c > '9') return false;+ }+ return true;+ }++ /** Hex digits; lower case only when lowerOnly (the decision file keeps digests lower case). */+ static boolean isHex(String s, boolean lowerOnly) {+ if (s.isEmpty()) return false;+ for (int i = 0; i < s.length(); i++) {+ char c = s.charAt(i);+ boolean ok = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (!lowerOnly && c >= 'A' && c <= 'F');+ if (!ok) return false;+ }+ return true;+ }++ /** A Java style package name: two or more dot separated segments, each a letter then letters, digits or _. */+ static boolean isPackageName(String s) {+ if (s == null || s.isEmpty() || s.length() > 255) return false;+ int segments = 0;+ int i = 0;+ while (i < s.length()) {+ char c = s.charAt(i);+ if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) return false;+ i++;+ while (i < s.length() && s.charAt(i) != '.') {+ c = s.charAt(i);+ if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_')) return false;+ i++;+ }+ segments++;+ if (i < s.length()) i++; // skip the dot; a trailing dot leaves an empty segment below+ else break;+ if (i == s.length()) return false;+ }+ return segments >= 2;+ }++ static boolean isDigest(String s) {+ return s != null && s.length() == 64 && isHex(s, true);+ }++ static String hex(byte[] bytes) {+ char[] digits = "0123456789abcdef".toCharArray();+ char[] out = new char[bytes.length * 2];+ for (int i = 0; i < bytes.length; i++) {+ out[i * 2] = digits[(bytes[i] >> 4) & 0xF];+ out[i * 2 + 1] = digits[bytes[i] & 0xF];+ }+ return new String(out);+ }++ /** The first 12 hex characters in groups of four, as shown on the prompt: "7f3a 91c0 b2e4". */+ static String shortDigest(String digest) {+ return grouped(digest.length() >= 12 ? digest.substring(0, 12) : digest, 3);+ }++ /** The whole digest in groups of four, eight groups per line, as shown in the Module cards list. */+ static String longDigest(String digest) {+ return grouped(digest, 8);+ }++ private static String grouped(String hex, int groupsPerLine) {+ StringBuilder b = new StringBuilder(hex.length() + hex.length() / 4 + 2);+ for (int i = 0; i < hex.length(); i += 4) {+ if (i > 0) b.append(i / 4 % groupsPerLine == 0 ? '\n' : ' ');+ b.append(hex, i, Math.min(hex.length(), i + 4));+ }+ return b.toString();+ }++ // ---- signer ----------------------------------------------------------------------------------++ /**+ * SHA-256 of the DER certificate of the package's one signer: the value apksigner verify (with+ * print-certs) prints as the certificate SHA-256 digest. A package with more than one signer+ * is rejected, because the order of its certificates is not defined.+ */+ @SuppressWarnings("deprecation")+ static String digest(PackageManager pm, String pkg) throws Exception {+ Signature[] sigs;+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {+ PackageInfo pi = pm.getPackageInfo(pkg, PackageManager.GET_SIGNING_CERTIFICATES);+ SigningInfo info = pi.signingInfo;+ if (info == null) throw new CardException("package has no signing certificate");+ if (info.hasMultipleSigners()) throw new CardException("package has more than one signer");+ sigs = info.getApkContentsSigners();+ } else {+ PackageInfo pi = pm.getPackageInfo(pkg, PackageManager.GET_SIGNATURES);+ sigs = pi.signatures;+ }+ if (sigs == null || sigs.length != 1) {+ throw new CardException("package has " + (sigs == null ? 0 : sigs.length) + " signing certificates, expected one");+ }+ return hex(MessageDigest.getInstance("SHA-256").digest(sigs[0].toByteArray()));+ }++ // ---- decision file (cards.json) --------------------------------------------------------------++ static File storeFile(Context ctx) {+ return new File(ctx.getFilesDir(), STORE_FILE);+ }++ /**+ * The records in cards.json, or an empty map. A file that does not decode is moved aside to+ * cards.json.bad (kept, not deleted) and the launcher continues as if no decision had been made.+ */+ static Map<String, Record> load(File file) {+ if (!file.exists()) return new TreeMap<>();+ String text;+ try {+ text = new String(new AtomicFile(file).readFully(), StandardCharsets.UTF_8);+ } catch (IOException e) {+ Log.w(TAG, "cannot read " + file.getName() + ": " + e);+ return new TreeMap<>();+ }+ Map<String, Record> records = decode(text);+ if (records == null) {+ Log.w(TAG, file.getName() + " is not valid; moved to " + STORE_FILE + ".bad");+ quarantine(file);+ return new TreeMap<>();+ }+ return records;+ }++ /** Writes the records atomically. False (and a log line) when the write failed. */+ static boolean save(File file, Map<String, Record> records) {+ AtomicFile af = new AtomicFile(file);+ FileOutputStream out = null;+ try {+ out = af.startWrite();+ out.write(encode(records).getBytes(StandardCharsets.UTF_8));+ af.finishWrite(out);+ return true;+ } catch (IOException e) {+ Log.w(TAG, "cannot write " + file.getName() + ": " + e);+ if (out != null) af.failWrite(out);+ return false;+ }+ }++ /** Records the owner's decision for the card's package under its current signer and saves. */+ static boolean decide(File file, Card card, boolean show) {+ Map<String, Record> records = load(file);+ Record old = records.get(card.pkg);+ long now = System.currentTimeMillis();+ long firstSeen = old != null && old.digest.equals(card.digest) ? old.firstSeen : now;+ records.put(card.pkg, new Record(card.pkg, card.digest, show ? DECISION_SHOW : DECISION_HIDE, firstSeen, now));+ return save(file, records);+ }++ /** Moves a bad decision file to `<name>.bad`, replacing an older .bad. Returns true when the file is out of the way. */+ static boolean quarantine(File file) {+ File bad = new File(file.getParentFile(), file.getName() + ".bad");+ if (bad.exists() && !bad.delete()) return false;+ return file.renameTo(bad) || file.delete();+ }++ private static final String HEADER = "{\"version\":1,\"records\":[";+ private static final String FOOTER = "]}";+ private static final String F_PACKAGE = "{\"package\":\"";+ private static final String F_DIGEST = "\",\"signer_sha256\":\"";+ private static final String F_DECISION = "\",\"decision\":\"";+ private static final String F_FIRST_SEEN = "\",\"first_seen\":";+ private static final String F_DECIDED_AT = ",\"decided_at\":";++ /**+ * cards.json: one record per line, in the exact layout {@link #encode} writes. Anything else,+ * including more than {@link #MAX_RECORDS} records or a package listed twice, is invalid (null).+ */+ static Map<String, Record> decode(String text) {+ if (text == null || text.length() > 64 * 1024) return null;+ List<String> lines = new ArrayList<>();+ int start = 0;+ for (int i = 0; i <= text.length(); i++) {+ if (i == text.length() || text.charAt(i) == '\n') {+ lines.add(text.substring(start, i));+ start = i + 1;+ }+ }+ if (lines.size() < 2 || !lines.get(0).equals(HEADER)) return null;+ int last = lines.size() - 1;+ if (lines.get(last).isEmpty()) last -= 1; // a trailing newline is fine+ if (last < 1 || !lines.get(last).equals(FOOTER)) return null;+ int count = last - 1;+ if (count > MAX_RECORDS) return null;+ Map<String, Record> out = new TreeMap<>();+ for (int i = 1; i < last; i++) {+ String line = lines.get(i);+ boolean lastRecord = i == last - 1;+ if (!lastRecord) {+ if (!line.endsWith(",")) return null;+ line = line.substring(0, line.length() - 1);+ }+ Record r = decodeRecord(line);+ if (r == null || out.containsKey(r.pkg)) return null;+ out.put(r.pkg, r);+ }+ return out;+ }++ /** One record line, or null when it is not exactly what {@link #encode} writes. */+ static Record decodeRecord(String line) {+ int[] at = {0};+ if (!take(line, at, F_PACKAGE)) return null;+ String pkg = until(line, at, '"');+ if (pkg == null || !isPackageName(pkg) || !take(line, at, F_DIGEST)) return null;+ String digest = until(line, at, '"');+ if (digest == null || !isDigest(digest) || !take(line, at, F_DECISION)) return null;+ String decision = until(line, at, '"');+ if (decision == null || !(DECISION_SHOW.equals(decision) || DECISION_HIDE.equals(decision))) return null;+ if (!take(line, at, F_FIRST_SEEN)) return null;+ String firstSeen = until(line, at, ',');+ if (firstSeen == null || firstSeen.length() > 18 || !isDigits(firstSeen)) return null;+ if (!take(line, at, F_DECIDED_AT)) return null;+ String decidedAt = until(line, at, '}');+ if (decidedAt == null || decidedAt.length() > 18 || !isDigits(decidedAt)) return null;+ if (!take(line, at, "}") || at[0] != line.length()) return null;+ return new Record(pkg, digest, decision, Long.parseLong(firstSeen), Long.parseLong(decidedAt));+ }++ /** Consumes the literal at the cursor, or returns false. */+ private static boolean take(String s, int[] at, String literal) {+ if (!s.startsWith(literal, at[0])) return false;+ at[0] += literal.length();+ return true;+ }++ /** The text from the cursor up to the next stop character, which stays for the next literal; null when there is none. */+ private static String until(String s, int[] at, char stop) {+ int end = s.indexOf(stop, at[0]);+ if (end < 0) return null;+ String out = s.substring(at[0], end);+ at[0] = end;+ return out;+ }++ /** The decision file text for these records, by package; the oldest decisions are dropped beyond {@link #MAX_RECORDS}. */+ static String encode(Map<String, Record> records) {+ List<Record> list = new ArrayList<>(records.values());+ if (list.size() > MAX_RECORDS) {+ Collections.sort(list, (a, b) -> Long.compare(b.decidedAt, a.decidedAt));+ list = new ArrayList<>(list.subList(0, MAX_RECORDS));+ }+ Collections.sort(list, (a, b) -> a.pkg.compareTo(b.pkg));+ StringBuilder b = new StringBuilder(HEADER).append('\n');+ for (int i = 0; i < list.size(); i++) {+ Record r = list.get(i);+ // Every field is validated before it gets here, so no JSON escaping is ever needed.+ if (!isPackageName(r.pkg) || !isDigest(r.digest)+ || !(DECISION_SHOW.equals(r.decision) || DECISION_HIDE.equals(r.decision))+ || r.firstSeen < 0 || r.decidedAt < 0) {+ throw new IllegalArgumentException("record for " + r.pkg + " is not valid");+ }+ b.append(F_PACKAGE).append(r.pkg).append(F_DIGEST).append(r.digest).append(F_DECISION).append(r.decision)+ .append(F_FIRST_SEEN).append(r.firstSeen).append(F_DECIDED_AT).append(r.decidedAt).append('}');+ if (i < list.size() - 1) b.append(',');+ b.append('\n');+ }+ return b.append(FOOTER).append('\n').toString();+ }++ /** The folded forms of the English UI names, for callers without resources (tests). */+ static Set<String> englishUiNames() {+ return new HashSet<>(Arrays.asList(fold("Home"), fold("Settings"), fold("Inputs"), fold("Wi-Fi"),+ fold("Live TV"), fold("Default home"), fold("Clock")));+ }++ // ---- self-check ------------------------------------------------------------------------------++ private static boolean selfChecked;++ /**+ * Debuggable builds only, once per process: runs the validators and the decision file codec on fixed+ * input and logs "self-check ok" or what differs, so a device run shows at once whether this+ * class behaves on the TV's runtime the way the JVM tests say it does.+ */+ static void selfCheck() {+ if (selfChecked) return;+ selfChecked = true;+ List<String> bad = new ArrayList<>();+ if (checkLabel("Retro") != null) bad.add("label Retro rejected");+ if (checkLabel("Verified\u202E") == null) bad.add("control character accepted");+ if (checkCaption("NES games") != null) bad.add("caption rejected");+ if (parseAccent("#E8A33D") != 0xFFE8A33D || parseAccent("#ffe8a33d") != 0xFFE8A33D) bad.add("accent");+ if (!"livetv".equals(fold("Live TV")) || !isReserved("hdmi2", englishUiNames())) bad.add("fold or reserved");+ if (!"Netflix".equals(cleanLabel("Netflix\u202E\n", "x"))) bad.add("cleanLabel");+ if (!isPackageName("io.example.a") || isPackageName("example")) bad.add("package name");+ Map<String, Record> one = new TreeMap<>();+ String digest = hex(new byte[32]);+ one.put("io.example.a", new Record("io.example.a", digest, DECISION_SHOW, 1, 2));+ Map<String, Record> back = decode(encode(one));+ if (back == null || back.size() != 1 || back.get("io.example.a").decidedAt != 2) bad.add("store round trip");+ if (decode("{}") != null) bad.add("bad store accepted");+ Log.w(TAG, bad.isEmpty() ? "self-check ok" : "self-check FAILED: " + bad);+ }+}diff --git a/launcher/app/src/main/java/com/gathin/tvhome/MainActivity.java b/launcher/app/src/main/java/com/gathin/tvhome/MainActivity.javaindex b03823724..f11b31b8c 100644--- a/launcher/app/src/main/java/com/gathin/tvhome/MainActivity.java+++ b/launcher/app/src/main/java/com/gathin/tvhome/MainActivity.java@@ -1,6 +1,7 @@package com.gathin.tvhome;import android.app.Activity;+import android.app.Dialog;import android.content.ActivityNotFoundException;import android.content.ComponentName;import android.content.Context;@@ -29,6 +30,7 @@ import android.view.Gravity;import android.view.KeyEvent;import android.view.View;import android.view.ViewGroup;+import android.view.Window;import android.view.animation.AnimationUtils;import android.view.animation.LayoutAnimationController;import android.widget.FrameLayout;@@ -50,8 +52,10 @@ import java.io.File;import java.util.ArrayList;import java.util.Calendar;import java.util.Collections;+import java.util.HashSet;import java.util.List;import java.util.Locale;+import java.util.Set;/*** tvOS style home: black, a pinned dock row, an app grid, and one glass highlight that springs between tiles.@@ -93,6 +97,18 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {/** App of the last focused tile, so focus follows it when the app list changes. */private static String lastFocusedKey;private float density;+ /** Module cards (res/values/config.xml, module_cards): discovered on resume, shown only after the owner's Show. */+ private boolean moduleCards;+ /** hidden_apps as the adapter sees them (config.xml or a theme's config.json): a hidden app gets no card either. */+ private Set<String> hiddenApps = Collections.emptySet();+ private List<Cards.Card> cards = Collections.emptyList();+ /** The grid has been laid out and focused since the last resume; the card prompt waits for this. */+ private boolean tilesReady;+ private Dialog cardPrompt;+ /** Set when a decision could not be saved: no more prompts until the next resume, instead of asking in a loop. */+ private boolean promptsPaused;+ /** The Inputs or Module cards dropdown while one is open, so onPause can close it. */+ private PopupWindow openPopup;private final Handler handler = new Handler(Looper.getMainLooper());/** Refreshes the network pill when the connection changes: at boot Wi-Fi often connects after Home is shown. */@@ -176,6 +192,8 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {date.setPadding(0, (int) (4 * density), 0, 0);}vpnApp = cfg.vpnApp;+ moduleCards = getResources().getBoolean(R.bool.module_cards);+ hiddenApps = new HashSet<>(cfg.hiddenApps);grid = findViewById(R.id.grid);grid.setLayoutManager(new GridLayoutManager(this, COLUMNS));@@ -240,6 +258,10 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {return true;});btnSettings.setOnClickListener(v -> open(new Intent(Settings.ACTION_SETTINGS)));+ btnSettings.setOnLongClickListener(v -> {+ showModuleCards();+ return true;+ });// Keep focus on the top bar at its ends and at the top: Android's focus finder would otherwise// jump to a tile far below when there is nothing in that direction.@@ -309,21 +331,45 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {heroShown = false;heroName.setAlpha(0f);ambient.setAlpha(0f);- // Read these before reload(): rebinding can move focus to the first tile and overwrite them.- final String returnKey = lastFocusedKey;- final int returnSlot = lastFocused;- adapter.reload();+ tilesReady = false;+ promptsPaused = false;+ reloadTiles();grid.scheduleLayoutAnimation();updateGreeting();updateWifiLabel();updateInputsButton();handler.postDelayed(minuteTick, MINUTE_MS);+ restoreFocus();+ }++ /**+ * Rebuilds the tiles; the module cards the owner chose to show stand in for their app's tile.+ * Every step into the card code runs under CardFeature: if it fails, the tiles are the ordinary+ * ones and cards stay off for this process.+ */+ private void reloadTiles() {+ // Read these before reload(): rebinding can move focus to the first tile and overwrite them.+ final String returnKey = lastFocusedKey;+ final int returnSlot = lastFocused;+ final List<Cards.Card> none = Collections.emptyList();+ cards = moduleCards ? CardFeature.run(() -> Cards.discover(this, hiddenApps, Cards.load(Cards.storeFile(this))), none) : none;+ adapter.reload(cards.isEmpty() ? none : CardFeature.run(() -> Cards.shown(cards), none));+ lastFocusedKey = returnKey;+ lastFocused = returnSlot;+ }- // Return to the app we left from, or the same slot if that app is gone. Always refocus: after- // reload() the view that holds focus may no longer show the app it had.+ /**+ * Return to the app we left from, or the same slot if that app is gone. Always refocus: after+ * reload() the view that holds focus may no longer show the app it had.+ */+ private void restoreFocus() {+ final String returnKey = lastFocusedKey;+ final int returnSlot = lastFocused;grid.post(() -> {int pos = adapter.positionOf(returnKey);focusTile(pos >= 0 ? pos : returnSlot);+ tilesReady = true;+ showCardPrompt();});}@@ -331,6 +377,15 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {protected void onPause() {super.onPause();handler.removeCallbacks(minuteTick);+ // Nothing of ours stays on screen over another app; an undecided prompt simply returns next time.+ if (cardPrompt != null) cardPrompt.dismiss();+ if (openPopup != null) openPopup.dismiss();+ }++ @Override+ public void onWindowFocusChanged(boolean hasFocus) {+ super.onWindowFocusChanged(hasFocus);+ if (hasFocus) showCardPrompt();}@Override@@ -626,11 +681,7 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {// Compact: as wide as the Inputs pill (a touch wider so "HDMI 1" fits), hanging right below it.int width = Math.max(anchor.getWidth(), (int) (150 * density));- final PopupWindow popup = new PopupWindow(panel, width, ViewGroup.LayoutParams.WRAP_CONTENT, true);- popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // needed for Back to dismiss- popup.setOutsideTouchable(true);- popup.setAnimationStyle(0);- popup.setElevation(0f);+ final PopupWindow popup = glassPopup(panel, width);TvInputManager tim = (TvInputManager) getSystemService(TV_INPUT_SERVICE);boolean sawNonHdmi = false;@@ -702,15 +753,32 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {panel.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);popup.setWidth(Math.max(width, panel.getMeasuredWidth()));- // Drop in: fade and unfold from the top edge.+ dropIn(popup, panel, anchor, Gravity.START);+ rows.getChildAt(0).requestFocus();+ }++ private PopupWindow glassPopup(View panel, int width) {+ final PopupWindow popup = new PopupWindow(panel, width, ViewGroup.LayoutParams.WRAP_CONTENT, true);+ popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // needed for Back to dismiss+ popup.setOutsideTouchable(true);+ popup.setAnimationStyle(0);+ popup.setElevation(0f);+ popup.setOnDismissListener(() -> {+ if (openPopup == popup) openPopup = null;+ });+ openPopup = popup;+ return popup;+ }++ /** Drop in: fade and unfold from the top edge, hanging under the anchor pill. */+ private void dropIn(PopupWindow popup, View panel, View anchor, int gravity) {panel.setAlpha(0f);panel.setPivotY(0f);panel.setScaleY(0.92f);panel.setTranslationY(-8 * density);- popup.showAsDropDown(anchor, 0, (int) (10 * density), Gravity.START);+ popup.showAsDropDown(anchor, 0, (int) (10 * density), gravity);panel.animate().alpha(1f).scaleY(1f).translationY(0f).setDuration(220).setInterpolator(new android.view.animation.DecelerateInterpolator(1.6f)).start();- rows.getChildAt(0).requestFocus();}private void addSeparator(LinearLayout rows) {@@ -746,4 +814,170 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {});rows.addView(row);}++ // ---- module cards ----------------------------------------------------------------------------++ /**+ * Asks about the next card that has no decision for its current signing key. One prompt at a+ * time, only over a laid out grid with window focus (not under a popup or another app), and+ * the next one follows as soon as this one is answered. Nothing is shown until the owner says Show.+ */+ private void showCardPrompt() {+ if (!moduleCards || !tilesReady || promptsPaused || cardPrompt != null || !hasWindowFocus() || isFinishing()) return;+ if (cards.isEmpty() || !CardFeature.working()) return;+ CardFeature.run(() -> {+ showCardPromptNow();+ return null;+ }, null);+ }++ private void showCardPromptNow() {+ final Cards.Card card = Cards.firstPending(cards);+ if (card == null) return;++ View panel = getLayoutInflater().inflate(R.layout.dialog_card_prompt, root, false);+ ((TextView) panel.findViewById(R.id.title)).setText(getString(R.string.card_prompt_title, card.appLabel));+ ((TextView) panel.findViewById(R.id.body)).setText(card.state == Cards.State.RESIGNED+ ? getString(R.string.card_prompt_resigned, card.appLabel)+ : getString(R.string.card_prompt_body, card.appLabel));+ TextView names = panel.findViewById(R.id.names);+ if (Cards.fold(card.label).equals(Cards.fold(card.appLabel))) names.setVisibility(View.GONE);+ else names.setText(getString(R.string.card_prompt_names, card.label, card.appLabel));+ ((TextView) panel.findViewById(R.id.identity)).setText(+ getString(R.string.card_prompt_identity, card.pkg, Cards.shortDigest(card.digest)));+ TextView keep = panel.findViewById(R.id.btnKeep);+ TextView show = panel.findViewById(R.id.btnShow);++ final Dialog dialog = new Dialog(this);+ dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);+ dialog.setContentView(panel);+ dialog.setCanceledOnTouchOutside(false);+ Window w = dialog.getWindow();+ if (w != null) {+ w.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));+ w.setLayout((int) (440 * density), ViewGroup.LayoutParams.WRAP_CONTENT);+ w.setDimAmount(0.6f);+ }+ // One decision per prompt: the buttons and Back (cancel) all end here.+ final boolean[] decided = {false};+ View.OnClickListener choose = v -> {+ if (decided[0]) return;+ decided[0] = true;+ cardPrompt = null;+ dialog.dismiss();+ CardFeature.run(() -> {+ decideCard(card, v.getId() == R.id.btnShow);+ return null;+ }, null);+ restoreFocus(); // the tiles changed under the prompt; this also chains the next prompt+ };+ keep.setOnClickListener(choose);+ show.setOnClickListener(choose);+ dialog.setOnCancelListener(d -> choose.onClick(keep));+ dialog.setOnDismissListener(d -> {+ if (cardPrompt == dialog) cardPrompt = null;+ });+ // Left and Right move between the two buttons; Up and Down stay put; the ends don't wrap.+ View.OnKeyListener keys = (v, keyCode, event) -> {+ if (event.getAction() != KeyEvent.ACTION_DOWN) return false;+ if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) return true;+ if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) return v.getId() == R.id.btnKeep;+ return keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && v.getId() == R.id.btnShow;+ };+ keep.setOnKeyListener(keys);+ show.setOnKeyListener(keys);+ cardPrompt = dialog;+ dialog.show();+ keep.requestFocus();+ }++ /** Writes the owner's decision and rebuilds the tiles; focus is left where it is. */+ private void decideCard(Cards.Card card, boolean show) {+ boolean saved = CardFeature.run(() -> Cards.decide(Cards.storeFile(this), card, show), false);+ if (!saved) {+ Toast.makeText(this, R.string.card_not_saved, Toast.LENGTH_SHORT).show();+ promptsPaused = true;+ }+ reloadTiles();+ }++ /** Dropdown under the Settings pill (hold OK): every discovered card, its package and key; OK toggles Shown and Hidden. */+ private void showModuleCards() {+ if (cards.isEmpty() || !CardFeature.working()) {+ Toast.makeText(this, R.string.no_module_cards, Toast.LENGTH_SHORT).show();+ return;+ }+ CardFeature.run(() -> {+ showModuleCardsNow();+ return null;+ }, null);+ }++ private void showModuleCardsNow() {+ View anchor = findViewById(R.id.btnSettings);+ View panel = getLayoutInflater().inflate(R.layout.popup_cards, root, false);+ LinearLayout rows = panel.findViewById(R.id.rows);+ final PopupWindow popup = glassPopup(panel, (int) (400 * density));+ List<Cards.Card> listed = new ArrayList<>(cards);+ Collections.sort(listed, Cards::byLabel);+ for (Cards.Card card : listed) {+ View row = getLayoutInflater().inflate(R.layout.item_card_row, rows, false);+ row.setTag(card.pkg);+ ((TextView) row.findViewById(R.id.title)).setText(card.label);+ TextView app = row.findViewById(R.id.app);+ if (Cards.fold(card.label).equals(Cards.fold(card.appLabel))) app.setVisibility(View.GONE);+ else app.setText(getString(R.string.card_app_name, card.appLabel));+ ((TextView) row.findViewById(R.id.pkg)).setText(card.pkg);+ ((TextView) row.findViewById(R.id.digest)).setText(Cards.longDigest(card.digest));+ final String pkg = card.pkg;+ row.setOnClickListener(v -> CardFeature.run(() -> {+ // The list stays open; the decision is for the card as it is now, not as it was listed.+ Cards.Card now = cardFor(pkg);+ if (now == null) return null;+ decideCard(now, now.state != Cards.State.SHOWN);+ // Every row, not only this one: a toggle can move another card across the limit of 8.+ updateCardStates(rows);+ return null;+ }, null));+ rows.addView(row);+ }+ updateCardStates(rows);+ // Scroll inside the panel instead of running off the bottom of a 720p screen.+ panel.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);+ int[] at = new int[2];+ anchor.getLocationInWindow(at);+ int room = root.getHeight() - (at[1] + anchor.getHeight()) - (int) (34 * density);+ popup.setHeight(Math.min(panel.getMeasuredHeight(), Math.max(room, (int) (120 * density))));+ dropIn(popup, panel, anchor, Gravity.END);+ rows.getChildAt(0).requestFocus();+ }++ private Cards.Card cardFor(String pkg) {+ for (Cards.Card c : cards) if (c.pkg.equals(pkg)) return c;+ return null;+ }++ /** Writes the state of every row in the Module cards list from the current card list. */+ private void updateCardStates(LinearLayout rows) {+ List<Cards.Card> drawn = Cards.shown(cards);+ for (int i = 0; i < rows.getChildCount(); i++) {+ View row = rows.getChildAt(i);+ Cards.Card card = row.getTag() instanceof String ? cardFor((String) row.getTag()) : null;+ ((TextView) row.findViewById(R.id.state)).setText(card != null ? stateText(card, drawn.contains(card)) : "");+ }+ }++ /** The row's state: a card the owner set to Shown but which is beyond the eight drawn says so. */+ private String stateText(Cards.Card card, boolean drawn) {+ switch (card.state) {+ case SHOWN:+ return getString(drawn ? R.string.card_state_shown : R.string.card_state_over_limit);+ case HIDDEN:+ return getString(R.string.card_state_hidden);+ case RESIGNED:+ return getString(R.string.card_state_new_key);+ default:+ return getString(R.string.card_state_new);+ }+ }}diff --git a/launcher/app/src/main/res/drawable/pill_text_mid.xml b/launcher/app/src/main/res/drawable/pill_text_mid.xmlnew file mode 100644index 000000000..12ca60184--- /dev/null+++ b/launcher/app/src/main/res/drawable/pill_text_mid.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Secondary lines of a focused list row (package, signing key): dark enough to read on the white+ focused background at 10sp; unfocused the same as pill_text_dim. -->+<selector xmlns:android="http://schemas.android.com/apk/res/android">+ <item android:state_focused="true" android:color="#E6111111" />+ <item android:color="#73FFFFFF" />+</selector>diff --git a/launcher/app/src/main/res/layout/dialog_card_prompt.xml b/launcher/app/src/main/res/layout/dialog_card_prompt.xmlnew file mode 100644index 000000000..96a685d11--- /dev/null+++ b/launcher/app/src/main/res/layout/dialog_card_prompt.xml@@ -0,0 +1,93 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- The module card prompt: who is asking (app label, package, signing key) and two buttons.+ Keep hidden is focused first; Back means Keep hidden too. -->+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="vertical"+ android:background="@drawable/glass_panel"+ android:paddingStart="26dp"+ android:paddingEnd="26dp"+ android:paddingTop="22dp"+ android:paddingBottom="20dp"+ android:elevation="12dp">++ <TextView+ android:id="@+id/title"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:singleLine="true"+ android:ellipsize="end"+ android:textColor="#FFFFFFFF"+ android:textSize="22sp"+ android:fontFamily="@font/outfit"+ android:fontVariationSettings="'wght' 500"+ android:letterSpacing="-0.01" />++ <TextView+ android:id="@+id/body"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="10dp"+ android:textColor="#D9FFFFFF"+ android:textSize="15sp"+ android:lineSpacingExtra="3sp"+ android:fontFamily="@font/outfit" />++ <TextView+ android:id="@+id/names"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="6dp"+ android:textColor="#D9FFFFFF"+ android:textSize="15sp"+ android:lineSpacingExtra="3sp"+ android:fontFamily="@font/outfit" />++ <TextView+ android:id="@+id/hint"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:text="@string/card_prompt_hint"+ android:textColor="#99FFFFFF"+ android:textSize="13sp"+ android:fontFamily="@font/outfit" />++ <TextView+ android:id="@+id/identity"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:maxLines="2"+ android:textColor="#80FFFFFF"+ android:textSize="12sp"+ android:letterSpacing="0.03"+ android:fontFamily="@font/outfit" />++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="18dp"+ android:orientation="horizontal"+ android:gravity="end">++ <TextView+ android:id="@+id/btnKeep"+ style="@style/TopButton"+ android:text="@string/card_keep_hidden"+ android:nextFocusUp="@+id/btnKeep"+ android:nextFocusDown="@+id/btnKeep"+ android:nextFocusLeft="@+id/btnKeep"+ android:nextFocusRight="@+id/btnShow" />++ <TextView+ android:id="@+id/btnShow"+ style="@style/TopButton"+ android:text="@string/card_show"+ android:nextFocusUp="@+id/btnShow"+ android:nextFocusDown="@+id/btnShow"+ android:nextFocusLeft="@+id/btnKeep"+ android:nextFocusRight="@+id/btnShow" />+ </LinearLayout>+</LinearLayout>diff --git a/launcher/app/src/main/res/layout/item_card_row.xml b/launcher/app/src/main/res/layout/item_card_row.xmlnew file mode 100644index 000000000..ae2ca6790--- /dev/null+++ b/launcher/app/src/main/res/layout/item_card_row.xml@@ -0,0 +1,80 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- One row of the Module cards list: label and state, then the app's name, package and full signing key. -->+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="vertical"+ android:paddingStart="12dp"+ android:paddingEnd="12dp"+ android:paddingTop="7dp"+ android:paddingBottom="8dp"+ android:background="@drawable/input_row_bg"+ android:focusable="true"+ android:clickable="true">++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="horizontal"+ android:gravity="center_vertical"+ android:duplicateParentState="true">++ <TextView+ android:id="@+id/title"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:layout_marginEnd="12dp"+ android:textColor="@drawable/pill_text"+ android:duplicateParentState="true"+ android:textSize="15sp"+ android:fontFamily="@font/outfit"+ android:fontVariationSettings="'wght' 500"+ android:singleLine="true"+ android:ellipsize="end" />++ <TextView+ android:id="@+id/state"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:textColor="@drawable/pill_text"+ android:duplicateParentState="true"+ android:textSize="11sp"+ android:fontFamily="@font/outfit"+ android:letterSpacing="0.04" />+ </LinearLayout>++ <TextView+ android:id="@+id/app"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:textColor="@drawable/pill_text_mid"+ android:duplicateParentState="true"+ android:textSize="11sp"+ android:fontFamily="@font/outfit"+ android:singleLine="true"+ android:ellipsize="end" />++ <TextView+ android:id="@+id/pkg"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:textColor="@drawable/pill_text_mid"+ android:duplicateParentState="true"+ android:textSize="11sp"+ android:fontFamily="@font/outfit"+ android:singleLine="true"+ android:ellipsize="middle" />++ <TextView+ android:id="@+id/digest"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp"+ android:textColor="@drawable/pill_text_mid"+ android:duplicateParentState="true"+ android:textSize="10sp"+ android:letterSpacing="0.03"+ android:fontFamily="@font/outfit"+ android:maxLines="2" />+</LinearLayout>diff --git a/launcher/app/src/main/res/layout/popup_cards.xml b/launcher/app/src/main/res/layout/popup_cards.xmlnew file mode 100644index 000000000..2818a689b--- /dev/null+++ b/launcher/app/src/main/res/layout/popup_cards.xml@@ -0,0 +1,40 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Module cards list under the Settings pill; scrolls when the rows don't fit on a 720p screen. -->+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/panel"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="vertical"+ android:background="@drawable/glass_panel"+ android:padding="6dp"+ android:elevation="12dp">++ <TextView+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:paddingStart="12dp"+ android:paddingEnd="12dp"+ android:paddingTop="8dp"+ android:paddingBottom="6dp"+ android:text="@string/module_cards"+ android:textColor="#8CFFFFFF"+ android:textSize="11sp"+ android:fontFamily="@font/outfit"+ android:fontVariationSettings="'wght' 500"+ android:letterSpacing="0.18"+ android:textAllCaps="true" />++ <ScrollView+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_weight="1"+ android:scrollbars="none"+ android:overScrollMode="never">++ <LinearLayout+ android:id="@+id/rows"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="vertical" />+ </ScrollView>+</LinearLayout>diff --git a/launcher/app/src/main/res/values/config.xml b/launcher/app/src/main/res/values/config.xmlindex 9f0c57a75..85aeb826e 100644--- a/launcher/app/src/main/res/values/config.xml+++ b/launcher/app/src/main/res/values/config.xml@@ -51,4 +51,8 @@<!-- "Default home" tile that opens Android's home-screen picker, for TVs whose settings have one(most Android TVs don't; the tile only appears when the page exists). Off by default. --><bool name="show_home_settings_shortcut">false</bool>++ <!-- Module cards: an app that declares a card (docs/specs/card.md) can stand in for its tile with its own+ label, caption and glow colour, once you answer Show on the prompt. false: never look for cards or ask. -->+ <bool name="module_cards">true</bool></resources>diff --git a/launcher/app/src/main/res/values/strings.xml b/launcher/app/src/main/res/values/strings.xmlindex c2a91674a..1c570f9b9 100644--- a/launcher/app/src/main/res/values/strings.xml+++ b/launcher/app/src/main/res/values/strings.xml@@ -26,4 +26,21 @@<string name="input_key_service_description">Opens the input switcher when the remote\'s Input button is pressed.</string><string name="home_key_name">Home button</string><string name="home_key_description">Makes the remote\'s Home button open this launcher.</string>+ <string name="card_prompt_title">New card from %1$s</string>+ <string name="card_prompt_body">%1$s can show a card on your home screen. Keeping it hidden leaves the app\'s normal tile as it is.</string>+ <string name="card_prompt_names">The card is named \'%1$s\'. The app is \'%2$s\'.</string>+ <string name="card_prompt_resigned">%1$s was updated with a different signing key. Show its card again?</string>+ <string name="card_prompt_hint">You can change this later: hold OK on Settings.</string>+ <string name="card_prompt_identity">%1$s, key %2$s</string>+ <string name="card_keep_hidden">Keep hidden</string>+ <string name="card_show">Show card</string>+ <string name="card_not_saved">Couldn\'t save the choice</string>+ <string name="module_cards">Module cards</string>+ <string name="no_module_cards">No module cards installed</string>+ <string name="card_app_name">App: %1$s</string>+ <string name="card_state_shown">Shown</string>+ <string name="card_state_over_limit">Shown, over the limit of 8</string>+ <string name="card_state_hidden">Hidden</string>+ <string name="card_state_new">New</string>+ <string name="card_state_new_key">New key</string></resources>