Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

Add optional installed-app library

Harsh Singha6ac88722de2
diff --git a/.gitignore b/.gitignore
index a2a8c877d..82c624430 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,9 @@ launcher/local.properties
# your own TV's dumps (serial, android_id, device names) stay local
backup/
.DS_Store
+
+# Generated install bundles and JVM crash reports stay out of contributions.
+*.apk
+*.aab
+launcher/hs_err_pid*.log
+launcher/replay_pid*.log
diff --git a/README.md b/README.md
index f322f078b..daa417929 100644
--- a/README.md
+++ b/README.md
@@ -267,6 +267,7 @@ network, no background services. It needs JDK 17 and Android SDK platform 34 to
the install script finds `~/Android/Sdk` and the `java` on your PATH.
- **Configure** in [`config.xml`](launcher/app/src/main/res/values/config.xml): dock order, hidden apps, the Live TV package, columns (tiles shrink from 5 up), rows under the dock, an optional VPN app for the network pill, and `reduced_motion` for TVs whose GPU cannot keep up.
+- **App library (optional):** enable `app_library` in config.xml or a theme to browse installed apps and add or remove Home shortcuts with the remote. See [the app library guide](docs/app-library.md).
- **On-TV launcher settings:** click Settings for the TV's system settings, or hold OK on Settings and choose Launcher settings to set 4, 5, 6 or 7 apps per row, turn animations on or off, and opt into advanced effects. The advanced option adds tile lift, icon zoom and smooth ambient-colour transitions; it may use more memory. Use Follow theme to clear on-TV choices. Pushing or resetting a theme also clears them.
- **Change the default home:** Launcher settings and the optional Default-home tile (`show_home_settings_shortcut`) open Android's home picker. Choose the original launcher to stop using CleanYourTV as Home, or CleanYourTV to return. The original launcher must be enabled. If the install script disabled it, use the restore script below first. Some TVs provide no home picker.
- **Themes** set the same keys plus a background colour and a wallpaper from a `config.json` pushed to the TV, no rebuild. Four ship in [`themes/`](themes/), documented there.
diff --git a/docs/app-library.md b/docs/app-library.md
new file mode 100644
index 000000000..d5971e556
--- /dev/null
+++ b/docs/app-library.md
@@ -0,0 +1,42 @@
+# App library
+
+Set `"app_library": true` in a theme’s `config.json`, or enable the `app_library`
+bool in `config.xml`. It is off by default. A small glass pill appears after the
+last row of Home apps.
+
+The horizontal library lists installed apps with a TV or ordinary Android launch
+activity, preferring the TV entry when both exist. It excludes services and apps
+without a launch activity. Ordinary Android apps may still need touch or a mouse.
+
+Apps missing from Home come first. Apps first installed within the last seven
+days lead that group, newest first, with a green dot; older missing apps are
+alphabetical. Apps already on Home follow alphabetically, with a checkmark and a
+subtle tint. Updating an existing app does not mark it as new.
+
+- Press OK on a missing app to add it to Home. Focus advances to the next missing
+ app without following the new shortcut across the catalogue.
+- Press OK on a checked app to open it.
+- Hold OK for Open, Add to Home or Remove from Home, and App info. The menu uses
+ the existing Inputs dropdown resources and stays over the selected card.
+- Back closes the menu first, then the library. Down from the last Home row or
+ Right from the final app reaches the library pill; Up returns to the last row.
+ Hebrew mirrors the horizontal direction, so Left from the final app reaches it.
+
+Every checked app can be removed from Home, including the theme’s default apps.
+It stays installed and remains in the library, where one press adds it back.
+There is no hidden-app section and no uninstall action.
+
+Choices are stored in the launcher’s private `library_apps.txt` and
+`library_home_removed.txt`, with at most 128 entries in each. Each file is written
+atomically. An unreadable file is left unchanged if an edit fails. Choices
+survive restarts and app updates; missing or disabled packages are omitted until
+they return. Explicit Home removals override theme defaults until re-added.
+Theme config, dock ordering, module-card decisions and other saved tile order
+are not edited. Disabling the library button keeps existing Home choices.
+
+The library uses the existing package receiver to refresh after app changes.
+Labels and Home membership are cached for each refresh; icons load only for
+bound cards. The highlight follows the launcher's animation setting, including
+instant movement when animations are off. There is no polling, network, backdrop capture, new service,
+permission or dependency. The additional manifest query covers ordinary
+LAUNCHER activities on Android 11 and later.
diff --git a/launcher/app/src/main/AndroidManifest.xml b/launcher/app/src/main/AndroidManifest.xml
index bc71caba5..fbf0f9eee 100644
--- a/launcher/app/src/main/AndroidManifest.xml
+++ b/launcher/app/src/main/AndroidManifest.xml
@@ -18,6 +18,10 @@
<!-- 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.LAUNCHER" />
+ </intent>
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
diff --git a/launcher/app/src/main/java/com/gathin/tvhome/AppAdapter.java b/launcher/app/src/main/java/com/gathin/tvhome/AppAdapter.java
index 1c351396f..193ffb0c6 100644
--- a/launcher/app/src/main/java/com/gathin/tvhome/AppAdapter.java
+++ b/launcher/app/src/main/java/com/gathin/tvhome/AppAdapter.java
@@ -45,13 +45,17 @@ import java.util.Set;
* then empty slots up to a full row, see {@link DockSlots}), then the module cards the owner chose to show
* (by label), the rest is alphabetical.
*/
-public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
+public class AppAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
interface TileListener {
void onTileFocused(int position, View card);
/** Called for a D-pad direction key on a tile. Return true when handled (focus stays put). */
boolean onTileVerticalKey(int position, int keyCode);
+
+ void onLibraryRequested();
+ void onLibraryFocused();
+ void onLibraryUp();
}
static final class Entry {
@@ -122,6 +126,7 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
private final Set<String> hidden;
private final boolean animations;
private final boolean advancedEffects;
+ private final boolean showLibrary;
private final boolean showHomeSettings;
/** Calmer motion for weak GPUs (config.xml, reduced_motion): no overshoot, shorter fades. */
private final boolean reducedMotion;
@@ -137,6 +142,7 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
this.animations = cfg.animations;
this.advancedEffects = cfg.animations && cfg.advancedEffects;
this.showHomeSettings = cfg.showHomeSettingsShortcut;
+ this.showLibrary = cfg.appLibrary;
this.reducedMotion = cfg.reducedMotion;
// Tiles keep their identity across reload(), so a focused tile stays on its app instead of
// its view being rebound to whatever app now sits in that slot.
@@ -150,14 +156,27 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
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);
+ List<ResolveInfo> found = new ArrayList<>(pm.queryIntentActivities(probe, 0));
+ Set<String> tvPackages = new HashSet<>();
+ for (ResolveInfo ri : found) if (ri.activityInfo != null) tvPackages.add(ri.activityInfo.packageName);
+ Set<String> added = LibraryApps.load(ctx);
+ Set<String> removed = LibraryApps.loadRemoved(ctx);
+ if (!added.isEmpty()) {
+ Set<String> seen = new HashSet<>(tvPackages);
+ for (ResolveInfo ri : pm.queryIntentActivities(
+ new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER), 0)) {
+ if (ri.activityInfo != null && added.contains(ri.activityInfo.packageName)
+ && seen.add(ri.activityInfo.packageName)) found.add(ri);
+ }
+ }
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;
+ if (pkg.equals(ctx.getPackageName()) || !ri.activityInfo.exported
+ || !LibraryApps.visible(tvPackages.contains(pkg), hidden.contains(pkg), added.contains(pkg), removed.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 tile
@@ -219,7 +238,20 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
@NonNull
@Override
- public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ if (viewType == 1) {
+ View row = LayoutInflater.from(ctx).inflate(R.layout.row_app_library, parent, false);
+ View button = row.findViewById(R.id.btnLibrary);
+ button.setOnClickListener(v -> listener.onLibraryRequested());
+ button.setOnFocusChangeListener((v, focused) -> { if (focused) listener.onLibraryFocused(); });
+ button.setOnKeyListener((v, key, event) -> {
+ if (event.getAction() != KeyEvent.ACTION_DOWN) return false;
+ if (key == KeyEvent.KEYCODE_DPAD_UP) listener.onLibraryUp();
+ return key == KeyEvent.KEYCODE_DPAD_UP || key == KeyEvent.KEYCODE_DPAD_DOWN
+ || key == KeyEvent.KEYCODE_DPAD_LEFT || key == KeyEvent.KEYCODE_DPAD_RIGHT;
+ });
+ return new RecyclerView.ViewHolder(row) { };
+ }
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_app, parent, false);
float density = parent.getResources().getDisplayMetrics().density;
int width = parent.getWidth() > 0 ? parent.getWidth() : parent.getMeasuredWidth();
@@ -239,7 +271,9 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
}
@Override
- public void onBindViewHolder(@NonNull Holder h, int position) {
+ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
+ if (isLibraryAt(position)) return;
+ Holder h = (Holder) holder;
Entry e = items.get(position);
if (e.kind == Entry.EMPTY) {
// A free dock slot keeps its place in the row and the band, but shows nothing and takes no focus.
@@ -297,7 +331,6 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
return;
}
Intent i = new Intent(Intent.ACTION_MAIN)
- .addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER)
.setComponent(e.component)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
try {
@@ -312,12 +345,23 @@ public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
@Override
public int getItemCount() {
- return items.size();
+ return items.size() + (showLibrary ? 1 : 0);
+ }
+
+ int appCount() { return items.size(); }
+
+ boolean isLibraryAt(int position) { return showLibrary && position == items.size(); }
+
+ @Override public int getItemViewType(int position) { return isLibraryAt(position) ? 1 : 0; }
+
+ boolean containsPackage(String pkg) {
+ for (Entry entry : items) if (entry.pkg.equals(pkg)) return true;
+ return false;
}
@Override
public long getItemId(int position) {
- return items.get(position).component.flattenToShortString().hashCode();
+ return isLibraryAt(position) ? Long.MIN_VALUE : items.get(position).component.flattenToShortString().hashCode();
}
/** Stable key for the app at a position (its component), or null. */
diff --git a/launcher/app/src/main/java/com/gathin/tvhome/AppLibraryDialog.java b/launcher/app/src/main/java/com/gathin/tvhome/AppLibraryDialog.java
new file mode 100644
index 000000000..7315213f1
--- /dev/null
+++ b/launcher/app/src/main/java/com/gathin/tvhome/AppLibraryDialog.java
@@ -0,0 +1,517 @@
+package com.gathin.tvhome;
+
+import android.app.Activity;
+import android.content.ActivityNotFoundException;
+import android.content.ComponentName;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.graphics.Color;
+import android.graphics.Rect;
+import android.graphics.drawable.ColorDrawable;
+import android.graphics.drawable.GradientDrawable;
+import android.net.Uri;
+import android.provider.Settings;
+import android.text.TextUtils;
+import android.view.Gravity;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.PopupWindow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.annotation.NonNull;
+import androidx.dynamicanimation.animation.FloatPropertyCompat;
+import androidx.dynamicanimation.animation.SpringAnimation;
+import androidx.dynamicanimation.animation.SpringForce;
+import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
+
+import java.text.Collator;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Predicate;
+
+/** On-demand installed-app picker. Uses the launcher's glass resources; no backdrop capture or blur. */
+final class AppLibraryDialog {
+ private final Activity activity;
+ private final Predicate<String> onHome;
+ private final Runnable changed;
+ private final LinearLayout panel;
+ private final boolean reducedMotion;
+ private final boolean animations;
+ private final boolean rtl;
+ private TextView instructions;
+ private int totalApps;
+ final PopupWindow popup;
+ private final float density;
+ private List<ResolveInfo> apps = new ArrayList<>();
+ private String selectedPackage;
+ private int selectedPosition;
+ private int selectedOffset;
+ private final Map<String, Long> installTimes = new HashMap<>();
+ private final Map<String, String> labels = new HashMap<>();
+ private long catalogTime;
+ private PopupWindow actionPopup;
+ private RecyclerView catalog;
+ private FrameLayout shelf;
+ private GlassView highlight;
+ private SpringAnimation spring;
+ private float scrollOffset;
+ private boolean highlightShown;
+ private final int catalogWidth;
+
+ private void stopHighlight() {
+ if (spring != null) spring.cancel();
+ if (catalog != null) catalog.stopScroll();
+ catalog = null;
+ highlightShown = false;
+ }
+
+ private void highlight(View card, boolean animate) {
+ if (highlight == null || card.getParent() == null) return;
+ Rect rect = new Rect(0, 0, card.getWidth(), card.getHeight());
+ shelf.offsetDescendantRectToMyCoords(card, rect);
+ ViewGroup.LayoutParams lp = highlight.getLayoutParams();
+ lp.width = rect.width() + dp(12);
+ lp.height = rect.height() + dp(12);
+ highlight.setLayoutParams(lp);
+ highlight.setTranslationY(rect.top - dp(6));
+ float x = rect.left - dp(6) + scrollOffset;
+ if (!highlightShown || !animate || !animations) {
+ spring.cancel();
+ highlight.setTranslationX(x - scrollOffset);
+ } else spring.animateToFinalPosition(x);
+ highlightShown = true;
+ highlight.setAlpha(1f);
+ }
+
+ private GradientDrawable surface(int color, int radius) {
+ GradientDrawable bg = new GradientDrawable();
+ bg.setColor(color);
+ bg.setCornerRadius(dp(radius));
+ bg.setStroke(dp(1), 0x18FFFFFF);
+ return bg;
+ }
+
+ private void resize(int width, int height) {
+ popup.setWidth(width);
+ popup.setHeight(height);
+ if (popup.isShowing()) popup.update(width, height);
+ }
+
+ AppLibraryDialog(Activity activity, boolean animations, boolean reducedMotion, Predicate<String> onHome, Runnable changed, Runnable dismissed) {
+ this.activity = activity;
+ this.animations = animations;
+ this.rtl = activity.getResources().getBoolean(R.bool.rtl_app_grid);
+ this.reducedMotion = reducedMotion;
+ this.onHome = onHome;
+ this.changed = changed;
+ density = activity.getResources().getDisplayMetrics().density;
+ panel = new LinearLayout(activity);
+ panel.setLayoutDirection(rtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR);
+ panel.setOrientation(LinearLayout.VERTICAL);
+ panel.setPadding(dp(12), dp(8), dp(12), dp(12));
+ panel.setBackgroundResource(R.drawable.glass_panel);
+ View decor = activity.getWindow().getDecorView();
+ catalogWidth = Math.min(dp(800), Math.max(dp(200), decor.getWidth() - dp(64)));
+ int width = catalogWidth;
+ int height = dp(280);
+ popup = new PopupWindow(panel, width, height, true);
+ popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
+ popup.setOutsideTouchable(true);
+ popup.setAnimationStyle(0);
+ popup.setOnDismissListener(() -> { dismissActions(); stopHighlight(); dismissed.run(); });
+ }
+
+ void close() { dismissActions(); popup.dismiss(); }
+
+ void show() {
+ refresh();
+ popup.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
+ View container = panel.getRootView();
+ if (container.getLayoutParams() instanceof WindowManager.LayoutParams) {
+ WindowManager.LayoutParams params = (WindowManager.LayoutParams) container.getLayoutParams();
+ params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
+ params.dimAmount = 0.55f;
+ activity.getWindowManager().updateViewLayout(container, params);
+ }
+ panel.setAlpha(0f);
+ panel.animate().alpha(1f).setDuration(180).start();
+ }
+
+ /** Called by the activity's existing package receiver; an uninstall cannot leave a stale action. */
+ void refresh() {
+ dismissActions();
+ PackageManager pm = activity.getPackageManager();
+ Map<String, ResolveInfo> unique = new LinkedHashMap<>();
+ // Prefer the TV entry when an app declares both categories.
+ for (String category : new String[]{Intent.CATEGORY_LEANBACK_LAUNCHER, Intent.CATEGORY_LAUNCHER}) {
+ for (ResolveInfo info : pm.queryIntentActivities(new Intent(Intent.ACTION_MAIN).addCategory(category), 0)) {
+ if (info.activityInfo == null || !info.activityInfo.exported) continue;
+ String pkg = info.activityInfo.packageName;
+ if (!pkg.equals(activity.getPackageName()) && !unique.containsKey(pkg)) unique.put(pkg, info);
+ }
+ }
+ totalApps = unique.size();
+ apps = new ArrayList<>(unique.values());
+ installTimes.clear();
+ labels.clear();
+ Map<String, Boolean> home = new HashMap<>();
+ for (ResolveInfo app : apps) {
+ String pkg = app.activityInfo.packageName;
+ home.put(pkg, onHome.test(pkg));
+ label(app);
+ try { installTimes.put(pkg, pm.getPackageInfo(pkg, 0).firstInstallTime); }
+ catch (PackageManager.NameNotFoundException | RuntimeException unavailable) { installTimes.put(pkg, 0L); }
+ }
+ catalogTime = System.currentTimeMillis();
+ Collator collator = Collator.getInstance();
+ apps.sort((a, b) -> {
+ String pa = a.activityInfo.packageName, pb = b.activityInfo.packageName;
+ int priority = LibraryApps.comparePriority(home.get(pa), installTimes.get(pa),
+ home.get(pb), installTimes.get(pb), catalogTime);
+ if (priority != 0) return priority;
+ int byLabel = collator.compare(label(a), label(b));
+ return byLabel != 0 ? byLabel : pa.compareTo(pb);
+ });
+ showCatalog();
+ }
+
+ private String label(ResolveInfo app) {
+ String pkg = app.activityInfo.packageName;
+ String cached = labels.get(pkg);
+ if (cached != null) return cached;
+ String value;
+ try { value = Cards.cleanLabel(String.valueOf(app.loadLabel(activity.getPackageManager())), pkg); }
+ catch (RuntimeException unavailable) { value = pkg; }
+ labels.put(pkg, value);
+ return value;
+ }
+
+ private void heading(String text) {
+ TextView title = text(text, 18, 0xFFFFFFFF);
+ title.setMaxLines(1);
+ title.setEllipsize(TextUtils.TruncateAt.END);
+ title.setPadding(dp(12), dp(10), dp(12), dp(8));
+ panel.addView(title, new LinearLayout.LayoutParams(-1, -2));
+ }
+
+ private void showCatalog() {
+ stopHighlight();
+ resize(catalogWidth, dp(280));
+ panel.removeAllViews();
+ LinearLayout header = new LinearLayout(activity);
+ header.setGravity(Gravity.CENTER_VERTICAL);
+ header.setPadding(dp(12), dp(4), dp(8), dp(4));
+ TextView title = text(activity.getString(R.string.app_library), 22, Color.WHITE);
+ header.addView(title, new LinearLayout.LayoutParams(0, dp(36), 1));
+ title.setGravity(Gravity.CENTER_VERTICAL);
+ title.setSingleLine(true);
+ title.setEllipsize(TextUtils.TruncateAt.END);
+ TextView count = text(activity.getResources().getQuantityString(
+ R.plurals.library_app_count, totalApps, totalApps), 13, 0xA6FFFFFF);
+ count.setSingleLine(true);
+ header.addView(count, new LinearLayout.LayoutParams(-2, -2));
+ panel.addView(header, new LinearLayout.LayoutParams(-1, dp(44)));
+ instructions = text(activity.getString(R.string.library_hint_add), 13, 0xBBFFFFFF);
+ instructions.setSingleLine(true);
+ instructions.setEllipsize(TextUtils.TruncateAt.END);
+ instructions.setPadding(dp(12), 0, dp(12), dp(6));
+ panel.addView(instructions, new LinearLayout.LayoutParams(-1, dp(26)));
+ panel.setFocusableInTouchMode(apps.isEmpty());
+ if (apps.isEmpty()) {
+ instructions.setVisibility(View.GONE);
+ heading(activity.getString(R.string.library_empty));
+ panel.setFocusableInTouchMode(true);
+ panel.requestFocus();
+ return;
+ }
+ shelf = new FrameLayout(activity);
+ // The glass uses physical x coordinates; only the catalogue mirrors its item order.
+ shelf.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
+ shelf.setClipChildren(false);
+ RecyclerView list = new RecyclerView(activity);
+ list.setLayoutDirection(rtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR);
+ catalog = list;
+ list.setLayoutManager(new LinearLayoutManager(activity, RecyclerView.HORIZONTAL, false) {
+ @Override protected boolean isLayoutRTL() { return rtl; }
+ });
+ list.setItemAnimator(null);
+ list.setOverScrollMode(View.OVER_SCROLL_NEVER);
+ list.setClipToPadding(false);
+ list.setPadding(dp(10), dp(8), dp(10), dp(8));
+ list.setAdapter(new Catalog());
+ shelf.addView(list, new FrameLayout.LayoutParams(-1, -1));
+ highlight = new GlassView(activity, null);
+ highlight.setRadius(dp(20));
+ highlight.setAlpha(0f);
+ highlight.setFocusable(false);
+ highlight.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
+ shelf.addView(highlight, new FrameLayout.LayoutParams(dp(144), dp(180)));
+ scrollOffset = 0;
+ spring = new SpringAnimation(highlight, new FloatPropertyCompat<View>("libraryScrollX") {
+ @Override public float getValue(View view) { return view.getTranslationX() + scrollOffset; }
+ @Override public void setValue(View view, float value) { view.setTranslationX(value - scrollOffset); }
+ });
+ spring.setSpring(new SpringForce().setStiffness(reducedMotion ? 1400f : 260f)
+ .setDampingRatio(reducedMotion ? 0.95f : 0.58f));
+ list.addOnScrollListener(new RecyclerView.OnScrollListener() {
+ @Override public void onScrolled(@NonNull RecyclerView rv, int dx, int dy) {
+ scrollOffset += dx;
+ highlight.setTranslationX(highlight.getTranslationX() - dx);
+ }
+ });
+ panel.addView(shelf, new LinearLayout.LayoutParams(-1, 0, 1));
+ int position = Math.min(selectedPosition, apps.size() - 1);
+ for (int i = 0; i < apps.size(); i++) {
+ if (apps.get(i).activityInfo.packageName.equals(selectedPackage)) { position = i; break; }
+ }
+ ((LinearLayoutManager) list.getLayoutManager()).scrollToPositionWithOffset(position, selectedOffset);
+ final int target = position;
+ list.post(() -> {
+ if (catalog != list || !popup.isShowing()) return;
+ RecyclerView.ViewHolder holder = list.findViewHolderForAdapterPosition(target);
+ if (holder != null) holder.itemView.requestFocus();
+ });
+ }
+
+ private void dismissActions() {
+ PopupWindow menu = actionPopup;
+ actionPopup = null;
+ if (menu != null) menu.dismiss();
+ }
+
+ private void restoreCardFocus() {
+ if (catalog == null || !popup.isShowing()) return;
+ catalog.post(() -> {
+ if (catalog == null || !popup.isShowing() || actionPopup != null) return;
+ RecyclerView.ViewHolder holder = catalog.findViewHolderForAdapterPosition(selectedPosition);
+ if (holder != null) holder.itemView.requestFocus();
+ });
+ }
+
+ private void changeHome(ResolveInfo app, boolean add) {
+ if (!LibraryApps.save(activity, app.activityInfo.packageName, add)) {
+ Toast.makeText(activity, R.string.library_save_failed, Toast.LENGTH_LONG).show();
+ return;
+ }
+ selectedOffset = 0;
+ if (add && catalog != null) {
+ RecyclerView.ViewHolder holder = catalog.findViewHolderForAdapterPosition(selectedPosition);
+ if (holder != null) {
+ View card = holder.itemView;
+ RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) card.getLayoutParams();
+ selectedOffset = rtl
+ ? catalog.getWidth() - catalog.getPaddingRight()
+ - catalog.getLayoutManager().getDecoratedRight(card) - params.rightMargin
+ : catalog.getLayoutManager().getDecoratedLeft(card)
+ - params.leftMargin - catalog.getPaddingLeft();
+ }
+ // Advance through missing shortcuts instead of following the newly checked app
+ // into the Home group. Preserve its screen slot when the catalogue is rebuilt.
+ int next = LibraryApps.nextFocus(selectedPosition, apps.size(),
+ index -> !onHome.test(apps.get(index).activityInfo.packageName));
+ if (next >= 0) {
+ selectedPackage = apps.get(next).activityInfo.packageName;
+ selectedPosition = next;
+ }
+ }
+ dismissActions();
+ changed.run();
+ refresh();
+ }
+
+ private void open(ResolveInfo app) {
+ close();
+ Intent intent = new Intent(Intent.ACTION_MAIN).setComponent(
+ new ComponentName(app.activityInfo.packageName, app.activityInfo.name));
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+ try { activity.startActivity(intent); }
+ catch (ActivityNotFoundException | SecurityException e) {
+ Toast.makeText(activity, activity.getString(R.string.cant_open, label(app)), Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ private void showActions(ResolveInfo app, View anchor) {
+ dismissActions();
+ selectedPackage = app.activityInfo.packageName;
+ String pkg = selectedPackage;
+ if (spring != null) spring.cancel();
+ View menuPanel = activity.getLayoutInflater().inflate(R.layout.popup_inputs, panel, false);
+ LinearLayout rows = menuPanel.findViewById(R.id.rows);
+ PopupWindow menu = new PopupWindow(menuPanel, dp(220), ViewGroup.LayoutParams.WRAP_CONTENT, true);
+ actionPopup = menu;
+ menu.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
+ menu.setOutsideTouchable(true);
+ menu.setAnimationStyle(0);
+ menu.setElevation(0f);
+ menu.setOnDismissListener(() -> {
+ if (actionPopup == menu) actionPopup = null;
+ restoreCardFocus();
+ });
+ addAction(rows, R.string.library_open, () -> open(app));
+ boolean home = onHome.test(pkg);
+ addAction(rows, home ? R.string.library_remove_shortcut : R.string.library_add_home,
+ () -> changeHome(app, !home));
+ addAction(rows, R.string.library_app_info, () -> {
+ close();
+ try {
+ activity.startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + pkg)));
+ } catch (ActivityNotFoundException | SecurityException e) {
+ Toast.makeText(activity, activity.getString(R.string.cant_open, label(app)), Toast.LENGTH_SHORT).show();
+ }
+ });
+ int menuWidth = dp(220);
+ for (int i = 0; i < rows.getChildCount(); i++) {
+ TextView title = rows.getChildAt(i).findViewById(R.id.title);
+ menuWidth = Math.max(menuWidth, (int) Math.ceil(title.getPaint().measureText(title.getText().toString())) + dp(58));
+ title.setEllipsize(TextUtils.TruncateAt.END);
+ }
+ menuWidth = Math.min(menuWidth, panel.getWidth() - dp(24));
+ menu.setWidth(menuWidth);
+ menuPanel.measure(View.MeasureSpec.makeMeasureSpec(menuWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.UNSPECIFIED);
+ int[] location = new int[2];
+ anchor.getLocationOnScreen(location);
+ int[] panelLocation = new int[2];
+ panel.getLocationOnScreen(panelLocation);
+ Rect screen = new Rect(panelLocation[0], panelLocation[1],
+ panelLocation[0] + panel.getWidth(), panelLocation[1] + panel.getHeight());
+ int x = Math.max(screen.left + dp(12), Math.min(location[0] + anchor.getWidth() - dp(12), screen.right - menuWidth - dp(12)));
+ int y = Math.max(screen.top + dp(12), Math.min(location[1] + dp(8), screen.bottom - menuPanel.getMeasuredHeight() - dp(12)));
+ menuPanel.setAlpha(0f);
+ menuPanel.setPivotY(0f);
+ menuPanel.setScaleY(0.92f);
+ menuPanel.setTranslationY(-dp(8));
+ menu.showAtLocation(activity.getWindow().getDecorView(), Gravity.TOP | Gravity.START, x, y);
+ menuPanel.animate().alpha(1f).scaleY(1f).translationY(0f).setDuration(220)
+ .setInterpolator(new android.view.animation.DecelerateInterpolator(1.6f)).start();
+ rows.getChildAt(0).requestFocus();
+ }
+
+ private void addAction(LinearLayout rows, int label, Runnable action) {
+ View row = activity.getLayoutInflater().inflate(R.layout.item_input, rows, false);
+ ((TextView) row.findViewById(R.id.title)).setText(label);
+ row.setFocusableInTouchMode(true);
+ row.findViewById(R.id.icon).setVisibility(View.GONE);
+ row.findViewById(R.id.dot).setVisibility(View.GONE);
+ row.findViewById(R.id.status).setVisibility(View.GONE);
+ row.setOnClickListener(v -> action.run());
+ rows.addView(row);
+ row.setOnKeyListener((v, key, event) -> {
+ int index = rows.indexOfChild(v);
+ return event.getAction() == KeyEvent.ACTION_DOWN && (key == KeyEvent.KEYCODE_DPAD_LEFT
+ || key == KeyEvent.KEYCODE_DPAD_RIGHT || key == KeyEvent.KEYCODE_DPAD_UP && index == 0
+ || key == KeyEvent.KEYCODE_DPAD_DOWN && index == rows.getChildCount() - 1);
+ });
+ }
+
+ private TextView text(String value, int size, int color) {
+ TextView view = new TextView(activity);
+ view.setText(value);
+ view.setTextSize(size);
+ view.setTextColor(color);
+ view.setTypeface(activity.getResources().getFont(R.font.outfit));
+ view.setFontVariationSettings("'wght' 500");
+ view.setLetterSpacing(0.01f);
+ view.setIncludeFontPadding(false);
+ return view;
+ }
+
+ private int dp(int value) { return Math.round(value * density); }
+
+ private final class Catalog extends RecyclerView.Adapter<Row> {
+ @NonNull @Override public Row onCreateViewHolder(@NonNull ViewGroup parent, int type) {
+ FrameLayout row = new FrameLayout(activity);
+ RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(dp(132), dp(170));
+ params.setMargins(dp(6), dp(2), dp(6), dp(2));
+ row.setLayoutParams(params);
+ row.setPadding(dp(10), dp(12), dp(10), dp(10));
+ row.setFocusableInTouchMode(true);
+ row.setClickable(true);
+ LinearLayout content = new LinearLayout(activity);
+ content.setOrientation(LinearLayout.VERTICAL);
+ content.setGravity(Gravity.CENTER_HORIZONTAL);
+ row.addView(content, new FrameLayout.LayoutParams(-1, -1));
+ ImageView icon = new ImageView(activity);
+ icon.setId(R.id.icon);
+ icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
+ content.addView(icon, new LinearLayout.LayoutParams(dp(60), dp(60)));
+ TextView name = text("", 15, Color.WHITE);
+ name.setId(R.id.title);
+ name.setGravity(Gravity.CENTER);
+ name.setMaxLines(2);
+ LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(-1, dp(44));
+ nameParams.topMargin = dp(10);
+ content.addView(name, nameParams);
+ TextView status = text("", 11, 0xBBFFFFFF);
+ status.setId(R.id.status);
+ status.setGravity(Gravity.CENTER);
+ status.setMaxLines(2);
+ content.addView(status, new LinearLayout.LayoutParams(-1, -2));
+ View check = new View(activity);
+ check.setId(R.id.dot);
+ FrameLayout.LayoutParams badge = new FrameLayout.LayoutParams(dp(18), dp(18), Gravity.TOP | Gravity.END);
+ badge.setMargins(0, dp(2), dp(2), 0);
+ row.addView(check, badge);
+ return new Row(row);
+ }
+ @Override public void onBindViewHolder(@NonNull Row holder, int position) {
+ ResolveInfo app = apps.get(position);
+ String pkg = app.activityInfo.packageName;
+ ImageView icon = holder.itemView.findViewById(R.id.icon);
+ try { icon.setImageDrawable(app.loadIcon(activity.getPackageManager())); }
+ catch (RuntimeException unavailable) { icon.setImageResource(R.drawable.ic_apps); }
+ TextView name = holder.itemView.findViewById(R.id.title);
+ name.setText(label(app));
+ name.setEllipsize(TextUtils.TruncateAt.END);
+ TextView status = holder.itemView.findViewById(R.id.status);
+ boolean home = onHome.test(pkg);
+ boolean recent = LibraryApps.recent(installTimes.getOrDefault(pkg, 0L), catalogTime);
+ status.setText(home ? R.string.library_on_home : recent ? R.string.library_recent : R.string.library_add_home);
+ status.setVisibility(View.VISIBLE);
+ holder.itemView.setBackground(surface(home ? 0x1475BBA4 : 0x0CFFFFFF, 18));
+ View check = holder.itemView.findViewById(R.id.dot);
+ check.getLayoutParams().width = dp(home ? 18 : 8);
+ check.getLayoutParams().height = dp(home ? 18 : 8);
+ if (home) check.setBackgroundResource(R.drawable.library_check);
+ else check.setBackground(surface(0xFF70D9A0, 8));
+ check.setVisibility(home || recent ? View.VISIBLE : View.GONE);
+ holder.itemView.setOnClickListener(v -> {
+ if (onHome.test(pkg)) open(app);
+ else changeHome(app, true);
+ });
+ holder.itemView.setOnLongClickListener(v -> { showActions(app, v); return true; });
+ holder.itemView.setOnFocusChangeListener((v, focused) -> {
+ if (focused) {
+ selectedPackage = pkg;
+ instructions.setText(onHome.test(pkg)
+ ? R.string.library_hint_open : R.string.library_hint_add);
+ v.post(() -> { if (v.hasFocus() && catalog != null) highlight(v, true); });
+ int index = holder.getBindingAdapterPosition();
+ if (index != RecyclerView.NO_POSITION) selectedPosition = index;
+ }
+ });
+ holder.itemView.setOnKeyListener((v, key, event) -> {
+ int index = holder.getBindingAdapterPosition();
+ return event.getAction() == KeyEvent.ACTION_DOWN && (key == KeyEvent.KEYCODE_DPAD_UP
+ || key == KeyEvent.KEYCODE_DPAD_DOWN
+ || (rtl ? key == KeyEvent.KEYCODE_DPAD_RIGHT : key == KeyEvent.KEYCODE_DPAD_LEFT) && index == 0
+ || (rtl ? key == KeyEvent.KEYCODE_DPAD_LEFT : key == KeyEvent.KEYCODE_DPAD_RIGHT) && index == apps.size() - 1);
+ });
+ }
+ @Override public int getItemCount() { return apps.size(); }
+ }
+
+ private static final class Row extends RecyclerView.ViewHolder {
+ Row(View view) { super(view); }
+ }
+}
diff --git a/launcher/app/src/main/java/com/gathin/tvhome/Cards.java b/launcher/app/src/main/java/com/gathin/tvhome/Cards.java
index a08d231e0..4db7bfefe 100644
--- a/launcher/app/src/main/java/com/gathin/tvhome/Cards.java
+++ b/launcher/app/src/main/java/com/gathin/tvhome/Cards.java
@@ -337,7 +337,7 @@ final class Cards {
/** 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};
+ R.string.live_tv, R.string.home_settings, R.string.app_library, R.string.dream_name};
Set<String> out = new HashSet<>();
for (int id : ids) out.add(fold(res.getString(id)));
return out;
diff --git a/launcher/app/src/main/java/com/gathin/tvhome/Config.java b/launcher/app/src/main/java/com/gathin/tvhome/Config.java
index 96e48018d..1ffc7d33f 100644
--- a/launcher/app/src/main/java/com/gathin/tvhome/Config.java
+++ b/launcher/app/src/main/java/com/gathin/tvhome/Config.java
@@ -54,6 +54,7 @@ final class Config {
final boolean reducedMotion;
final String vpnApp;
final boolean showHomeSettingsShortcut;
+ final boolean appLibrary;
/** Background colour behind everything, #RRGGBB; black unless a theme says otherwise. */
final int backgroundColor;
/** Time-of-day backdrop, 0 to 100 (config.xml, sky_intensity); 0 keeps the plain background. */
@@ -73,7 +74,7 @@ final class Config {
String liveTvAction, String sourcePanelService, String sourcePanelAction, String inputAction,
int columns, int rowsBelowDock, boolean animations, boolean advancedEffects,
boolean shamsiDate, boolean moduleCards, boolean reducedMotion, String vpnApp,
- boolean showHomeSettingsShortcut, int backgroundColor, int skyIntensity,
+ boolean showHomeSettingsShortcut, boolean appLibrary, int backgroundColor, int skyIntensity,
int[] settingsKeycodes, boolean settingsKeyPanel, File wallpaper, boolean overlayApplied,
Festival festival) {
this.dockApps = Collections.unmodifiableList(dockApps);
@@ -93,6 +94,7 @@ final class Config {
this.reducedMotion = reducedMotion;
this.vpnApp = vpnApp;
this.showHomeSettingsShortcut = showHomeSettingsShortcut;
+ this.appLibrary = appLibrary;
this.backgroundColor = backgroundColor;
this.skyIntensity = skyIntensity;
this.settingsKeycodes = settingsKeycodes;
@@ -126,6 +128,7 @@ final class Config {
boolean reducedMotion = res.getBoolean(R.bool.reduced_motion);
String vpn = res.getString(R.string.vpn_app).trim();
boolean homeSettings = res.getBoolean(R.bool.show_home_settings_shortcut);
+ boolean library = res.getBoolean(R.bool.app_library);
int background = 0xFF000000;
int skyIntensity = res.getInteger(R.integer.sky_intensity);
int[] settingsKeycodes = res.getIntArray(R.array.settings_key_keycodes);
@@ -154,6 +157,7 @@ final class Config {
reducedMotion = bool(json, "reduced_motion", reducedMotion);
vpn = string(json, "vpn_app", vpn);
homeSettings = bool(json, "show_home_settings_shortcut", homeSettings);
+ library = bool(json, "app_library", library);
background = color(json, "background_color", background);
skyIntensity = integer(json, "sky_intensity", skyIntensity, 0, 100);
settingsKeycodes = intArray(json, "settings_key_keycodes", settingsKeycodes);
@@ -177,7 +181,7 @@ final class Config {
return new Config(dock, fillDock, hidden, liveTv, liveTvAction, panelService, panelAction, inputAction,
Math.max(1, columns), Math.max(0, rowsBelow), animations, advancedEffects,
- shamsi, moduleCards, reducedMotion, vpn, homeSettings, background,
+ shamsi, moduleCards, reducedMotion, vpn, homeSettings, library, background,
Math.max(0, Math.min(100, skyIntensity)), settingsKeycodes, settingsKeyPanel, wallpaper, applied,
festival);
}
diff --git a/launcher/app/src/main/java/com/gathin/tvhome/LibraryApps.java b/launcher/app/src/main/java/com/gathin/tvhome/LibraryApps.java
new file mode 100644
index 000000000..92d0b15ca
--- /dev/null
+++ b/launcher/app/src/main/java/com/gathin/tvhome/LibraryApps.java
@@ -0,0 +1,177 @@
+package com.gathin.tvhome;
+
+import android.content.Context;
+import android.util.AtomicFile;
+import android.util.Log;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.IntPredicate;
+
+/** Home shortcut choices made from the library, separate from theme defaults and tile ordering. */
+final class LibraryApps {
+ static final int MAX_ADDED = 128;
+ private static final long RECENT_MS = 7L * 24 * 60 * 60 * 1000;
+ private static final int MAX_BYTES = MAX_ADDED * 256;
+
+ private LibraryApps() { }
+
+ private static AtomicFile store(Context context, boolean removed) {
+ return new AtomicFile(new File(context.getFilesDir(), removed ? "library_home_removed.txt" : "library_apps.txt"));
+ }
+
+ static Set<String> load(Context context) {
+ return read(store(context, false));
+ }
+
+ static Set<String> loadRemoved(Context context) { return read(store(context, true)); }
+
+ private static Set<String> read(AtomicFile file) {
+ try { return readStrict(file); }
+ catch (IOException | RuntimeException e) {
+ Log.w("TvHome.Library", "Could not read shortcuts", e);
+ return Collections.emptySet();
+ }
+ }
+
+ private static Set<String> readStrict(AtomicFile file) throws IOException {
+ if (!file.getBaseFile().exists() && !new File(file.getBaseFile() + ".bak").exists())
+ return Collections.emptySet();
+ try (FileInputStream input = file.openRead()) {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ byte[] buffer = new byte[1024];
+ int count;
+ while ((count = input.read(buffer)) != -1) {
+ if (bytes.size() + count > MAX_BYTES) throw new IOException("Shortcut file too large");
+ bytes.write(buffer, 0, count);
+ }
+ return decode(new String(bytes.toByteArray(), StandardCharsets.UTF_8));
+ }
+ }
+
+ static boolean save(Context context, String pkg, boolean onHome) {
+ Set<String> additions, removed;
+ try {
+ additions = readStrict(store(context, false));
+ removed = readStrict(store(context, true));
+ } catch (IOException | RuntimeException e) {
+ // Never replace unreadable owner choices with an empty list on the next edit.
+ Log.w("TvHome.Library", "Keeping unreadable shortcut choices unchanged", e);
+ return false;
+ }
+ if (onHome) {
+ if (!write(store(context, false), additions, pkg, true)) return false;
+ return !removed.contains(pkg) || write(store(context, true), removed, pkg, false);
+ }
+ // The removal takes precedence over theme defaults and any previous explicit addition.
+ if (!write(store(context, true), removed, pkg, true)) return false;
+ if (additions.contains(pkg)) write(store(context, false), additions, pkg, false);
+ return true;
+ }
+
+ private static boolean write(AtomicFile file, Set<String> saved, String pkg, boolean added) {
+ FileOutputStream output = null;
+ try {
+ Set<String> next = change(saved, pkg, added);
+ byte[] bytes = encode(next).getBytes(StandardCharsets.UTF_8);
+ output = file.startWrite();
+ output.write(bytes);
+ file.finishWrite(output);
+ return true;
+ } catch (IOException | RuntimeException e) {
+ if (output != null) file.failWrite(output);
+ Log.w("TvHome.Library", "Could not save shortcut choice", e);
+ return false;
+ }
+ }
+
+ static boolean visible(boolean tvApp, boolean themeHidden, boolean explicitlyAdded) {
+ return visible(tvApp, themeHidden, explicitlyAdded, false);
+ }
+
+ static boolean visible(boolean tvApp, boolean themeHidden, boolean explicitlyAdded, boolean removedFromHome) {
+ return !removedFromHome && (explicitlyAdded || (tvApp && !themeHidden));
+ }
+
+ static boolean recent(long installedAt, long now) {
+ return installedAt > 0 && installedAt <= now && now - installedAt <= RECENT_MS;
+ }
+
+ /** Missing shortcuts first; recent installs lead that group. The caller sorts ties by label. */
+ static int comparePriority(boolean homeA, long installedA, boolean homeB, long installedB, long now) {
+ if (homeA != homeB) return homeA ? 1 : -1;
+ if (homeA) return 0;
+ boolean recentA = recent(installedA, now), recentB = recent(installedB, now);
+ if (recentA != recentB) return recentA ? -1 : 1;
+ return recentA ? Long.compare(installedB, installedA) : 0;
+ }
+
+ /** After adding a shortcut, prefer another missing app; otherwise stay by a neighbour. */
+ static int nextFocus(int current, int count, IntPredicate missing) {
+ if (count <= 0) return -1;
+ current = Math.max(0, Math.min(current, count - 1));
+ for (int step = 1; step < count; step++) {
+ int candidate = (current + step) % count;
+ if (missing.test(candidate)) return candidate;
+ }
+ return current + 1 < count ? current + 1 : Math.max(0, current - 1);
+ }
+
+ static Set<String> change(Set<String> saved, String pkg, boolean added) {
+ if (!validPackage(pkg)) throw new IllegalArgumentException("Invalid package");
+ Set<String> next = new HashSet<>(saved);
+ if (added) next.add(pkg); else next.remove(pkg);
+ if (next.size() > MAX_ADDED) throw new IllegalArgumentException("Too many shortcuts");
+ return next;
+ }
+
+ static String encode(Set<String> added) {
+ if (added.size() > MAX_ADDED) throw new IllegalArgumentException("Too many shortcuts");
+ StringBuilder text = new StringBuilder();
+ for (String pkg : new TreeSet<>(added)) {
+ if (!validPackage(pkg)) throw new IllegalArgumentException("Invalid package");
+ text.append(pkg).append('\n');
+ }
+ return text.toString();
+ }
+
+ static Set<String> decode(String text) {
+ if (text.length() > MAX_BYTES) throw new IllegalArgumentException("Shortcut file too large");
+ Set<String> result = new HashSet<>();
+ int start = 0;
+ for (int i = 0; i <= text.length(); i++) {
+ if (i < text.length() && text.charAt(i) != '\n') continue;
+ if (i == start && i == text.length()) break;
+ String pkg = text.substring(start, i);
+ if (!validPackage(pkg) || !result.add(pkg) || result.size() > MAX_ADDED)
+ throw new IllegalArgumentException("Invalid shortcut file");
+ start = i + 1;
+ }
+ return result;
+ }
+
+ static boolean validPackage(String pkg) {
+ if (pkg == null || pkg.isEmpty() || pkg.length() > 255) return false;
+ boolean first = true;
+ for (int i = 0; i < pkg.length(); i++) {
+ char c = pkg.charAt(i);
+ if (c == '.') {
+ if (first) return false;
+ first = true;
+ } else {
+ boolean letter = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_';
+ if (!letter && (first || c < '0' || c > '9')) return false;
+ first = false;
+ }
+ }
+ return !first;
+ }
+}
diff --git a/launcher/app/src/main/java/com/gathin/tvhome/MainActivity.java b/launcher/app/src/main/java/com/gathin/tvhome/MainActivity.java
index d7c86c17d..46dda6a33 100644
--- a/launcher/app/src/main/java/com/gathin/tvhome/MainActivity.java
+++ b/launcher/app/src/main/java/com/gathin/tvhome/MainActivity.java
@@ -147,6 +147,9 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
private boolean rebuildOnResume = true;
/** The Inputs or Module cards dropdown while one is open, so onPause can close it. */
private PopupWindow openPopup;
+ private AppLibraryDialog appLibrary;
+ private boolean libraryFocusPending;
+ private RecyclerView.OnScrollListener pendingFocusScroll;
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. */
@@ -193,6 +196,7 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
&& intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) return;
reloadApps(false);
+ if (appLibrary != null) appLibrary.refresh();
}
};
private final Runnable minuteTick = new Runnable() {
@@ -287,6 +291,9 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
return true;
}
});
+ ((GridLayoutManager) grid.getLayoutManager()).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
+ @Override public int getSpanSize(int position) { return adapter != null && adapter.isLibraryAt(position) ? COLUMNS : 1; }
+ });
grid.setHasFixedSize(true);
grid.setItemAnimator(null);
grid.addItemDecoration(new DockDecoration(COLUMNS, density));
@@ -309,7 +316,10 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
int itemH = AppAdapter.itemHeightPx(AppAdapter.tileHeightPx(AppAdapter.tileWidthPx(inner, COLUMNS, density)), density);
int dockRow = itemH + (int) ((6 + 12) * density); // item height plus DockDecoration offsets
int gridRows = itemH * rowsBelowDock;
- int want = Math.max(0, h - dockRow - gridRows - (int) (30 * density));
+ // Keep the hero below the header when the library is enabled on a short screen,
+ // even when the theme requests an extra visible row below the dock.
+ int shelfClearance = cfg.appLibrary ? heroName.getMeasuredHeight() + (int) (40 * density) : 0;
+ int want = Math.max(shelfClearance, h - dockRow - gridRows - (int) (30 * density));
if (grid.getPaddingTop() != want) {
grid.setPadding(grid.getPaddingLeft(), want, grid.getPaddingRight(), grid.getPaddingBottom());
}
@@ -525,10 +535,15 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
/** Rebuilds the tiles (and the module cards), then puts focus back where it was. */
private void reloadApps(boolean animate) {
+ cancelPendingFocusScroll();
+ RecyclerView.ViewHolder footer = grid.findViewHolderForAdapterPosition(adapter.appCount());
+ final boolean restoreLibrary = adapter.isLibraryAt(adapter.appCount()) && footer != null
+ && footer.itemView.findViewById(R.id.btnLibrary) != null
+ && footer.itemView.findViewById(R.id.btnLibrary).hasFocus();
// Capture the app before rebinding can move focus and overwrite its key.
final String returnKey = lastFocusedKey;
final int returnSlot = lastFocused;
- final boolean restoreFocus = animate || grid.hasFocus();
+ final boolean restoreFocus = appLibrary == null && (animate || grid.hasFocus());
if (restoreFocus) {
glassShown = false;
glass.setAlpha(0f);
@@ -540,12 +555,13 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
if (animate && animations && !reducedMotion) grid.scheduleLayoutAnimation();
if (restoreFocus) {
- // Follow the same app, or the nearest remaining slot when it was removed.
- restoreFocus();
+ // Keep a focused footer at the end even when the app count changes.
+ if (restoreLibrary) grid.post(this::focusLibrary);
+ else restoreFocus();
} else {
// A package change must not steal focus from a top button or the Inputs popup.
int pos = adapter.positionOf(returnKey);
- lastFocused = Math.max(0, Math.min(pos >= 0 ? pos : returnSlot, adapter.getItemCount() - 1));
+ lastFocused = Math.max(0, Math.min(pos >= 0 ? pos : returnSlot, adapter.appCount() - 1));
lastFocusedKey = adapter.keyAt(lastFocused);
if (pos < 0) hideHero();
// A newly installed app may have brought a card with it.
@@ -575,11 +591,13 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
* reload() the view that holds focus may no longer show the app it had.
*/
private void restoreFocus() {
+ final boolean returnToLibrary = libraryFocusPending;
final String returnKey = lastFocusedKey;
final int returnSlot = lastFocused;
grid.post(() -> {
int pos = adapter.positionOf(returnKey);
- focusTile(pos >= 0 ? pos : returnSlot);
+ if (returnToLibrary || libraryFocusPending) focusLibrary();
+ else focusTile(pos >= 0 ? pos : returnSlot);
tilesReady = true;
showCardPrompt();
});
@@ -593,8 +611,10 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
ambient.animate().cancel();
handler.removeCallbacks(minuteTick);
if (diya != null) diya.stop();
+ cancelPendingFocusScroll();
// Nothing of ours stays on screen over another app; an undecided prompt simply returns next time.
if (cardPrompt != null) cardPrompt.dismiss();
+ if (appLibrary != null) appLibrary.close();
if (openPopup != null) openPopup.dismiss();
}
@@ -608,7 +628,10 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
- if (hasFocus) showCardPrompt();
+ if (hasFocus) {
+ if (libraryFocusPending && appLibrary == null) focusLibrary();
+ showCardPrompt();
+ }
}
@Override
@@ -630,6 +653,23 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
// ---- glass highlight -------------------------------------------------------------------------
+ @Override
+ public void onLibraryRequested() {
+ if (appLibrary != null) appLibrary.close();
+ if (openPopup != null) openPopup.dismiss();
+ libraryFocusPending = false;
+ appLibrary = new AppLibraryDialog(this, animations, reducedMotion, adapter::containsPackage, () -> reloadApps(false), () -> {
+ appLibrary = null;
+ openPopup = null;
+ libraryFocusPending = true;
+ grid.post(() -> {
+ if (libraryFocusPending && appLibrary == null && hasWindowFocus() && !isFinishing()) focusLibrary();
+ });
+ });
+ openPopup = appLibrary.popup;
+ appLibrary.show();
+ }
+
@Override
public void onTileFocused(int position, View card) {
lastFocused = position;
@@ -833,11 +873,16 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
@Override
public boolean onTileVerticalKey(int position, int keyCode) {
- int count = adapter.getItemCount();
+ int count = adapter.appCount();
int target;
// Horizontal: swallow the key at a row's ends so focus never wraps to the next row or
// escapes up into the top bar. Mid-row moves fall through to the default focus search.
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
+ boolean forward = rtlAppGrid ? keyCode == KeyEvent.KEYCODE_DPAD_LEFT : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT;
+ if (forward && position == adapter.focusablePosition(count - 1) && adapter.isLibraryAt(count)) {
+ focusLibrary();
+ return true;
+ }
// In the dock, the last app is the row's end: the empty slots after it take no focus.
int rowCount = position < COLUMNS ? Math.min(count, adapter.dockFilled()) : count;
return GridNavigation.atHorizontalEdge(position, rowCount, COLUMNS,
@@ -848,7 +893,10 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
target = position - COLUMNS;
} else {
int lastRowStart = ((count - 1) / COLUMNS) * COLUMNS;
- if (position >= lastRowStart) return true; // already on the last row: stay put
+ if (position >= lastRowStart) {
+ if (adapter.isLibraryAt(count)) focusLibrary();
+ return true;
+ }
target = Math.min(position + COLUMNS, count - 1);
}
focusTile(target);
@@ -858,12 +906,73 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
return true;
}
+ @Override public void onLibraryFocused() {
+ libraryFocusPending = false;
+ hideGlass();
+ hideHero();
+ }
+
+ @Override public void onLibraryUp() {
+ if (adapter.appCount() == 0) { btnWifi.requestFocus(); return; }
+ int lastRow = ((adapter.appCount() - 1) / COLUMNS) * COLUMNS;
+ focusTile(Math.min(lastRow + lastFocused % COLUMNS, adapter.appCount() - 1));
+ }
+
+ private void focusLibrary() {
+ cancelPendingFocusScroll();
+ int position = adapter.appCount();
+ if (!adapter.isLibraryAt(position)) return;
+ RecyclerView.ViewHolder holder = grid.findViewHolderForAdapterPosition(position);
+ if (holder != null) {
+ View button = holder.itemView.findViewById(R.id.btnLibrary);
+ Rect visible = new Rect();
+ if (button.getGlobalVisibleRect(visible) && visible.height() >= button.getHeight()) {
+ if (button.requestFocus()) libraryFocusPending = false;
+ return;
+ }
+ }
+ if (!animations) {
+ grid.scrollToPosition(position);
+ grid.post(() -> {
+ if (appLibrary != null || !hasWindowFocus()) return;
+ RecyclerView.ViewHolder footer = grid.findViewHolderForAdapterPosition(adapter.appCount());
+ if (footer != null && adapter.isLibraryAt(adapter.appCount())
+ && footer.itemView.findViewById(R.id.btnLibrary).requestFocus()) libraryFocusPending = false;
+ });
+ return;
+ }
+ pendingFocusScroll = new RecyclerView.OnScrollListener() {
+ @Override public void onScrollStateChanged(@NonNull RecyclerView rv, int state) {
+ if (state != RecyclerView.SCROLL_STATE_IDLE) return;
+ rv.removeOnScrollListener(this);
+ if (pendingFocusScroll != this) return;
+ pendingFocusScroll = null;
+ RecyclerView.ViewHolder footer = rv.findViewHolderForAdapterPosition(position);
+ if (footer != null && footer.itemView.findViewById(R.id.btnLibrary).requestFocus())
+ libraryFocusPending = false;
+ }
+ };
+ grid.addOnScrollListener(pendingFocusScroll);
+ grid.smoothScrollToPosition(position);
+ }
+
+ private void cancelPendingFocusScroll() {
+ if (pendingFocusScroll != null) {
+ grid.removeOnScrollListener(pendingFocusScroll);
+ pendingFocusScroll = null;
+ grid.stopScroll();
+ }
+ }
+
private void focusTile(int position) {
- if (adapter.getItemCount() == 0) {
- btnWifi.requestFocus();
+ libraryFocusPending = false;
+ cancelPendingFocusScroll();
+ if (adapter.appCount() == 0) {
+ if (adapter.isLibraryAt(0)) focusLibrary();
+ else btnWifi.requestFocus();
return;
}
- final int pos = adapter.focusablePosition(Math.max(0, Math.min(position, adapter.getItemCount() - 1)));
+ final int pos = adapter.focusablePosition(Math.max(0, Math.min(position, adapter.appCount() - 1)));
RecyclerView.ViewHolder vh = grid.findViewHolderForAdapterPosition(pos);
if (vh != null) {
View card = vh.itemView.findViewById(R.id.card);
@@ -881,16 +990,19 @@ public class MainActivity extends Activity implements AppAdapter.TileListener {
});
return;
}
- grid.addOnScrollListener(new RecyclerView.OnScrollListener() {
+ pendingFocusScroll = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView rv, int newState) {
if (newState != RecyclerView.SCROLL_STATE_IDLE) return;
rv.removeOnScrollListener(this);
+ if (pendingFocusScroll != this) return;
+ pendingFocusScroll = null;
RecyclerView.ViewHolder h = rv.findViewHolderForAdapterPosition(pos);
View target = h != null ? h.itemView.findViewById(R.id.card) : rv.getChildAt(0);
if (target != null) target.requestFocus();
}
- });
+ };
+ grid.addOnScrollListener(pendingFocusScroll);
grid.smoothScrollToPosition(pos);
}
diff --git a/launcher/app/src/main/res/drawable/library_check.xml b/launcher/app/src/main/res/drawable/library_check.xml
new file mode 100644
index 000000000..0cef7eef6
--- /dev/null
+++ b/launcher/app/src/main/res/drawable/library_check.xml
@@ -0,0 +1,8 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp" android:height="18dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:fillColor="#246E58"
+ android:pathData="M12,1a11,11 0,1 0,0 22a11,11 0,1 0,0 -22" />
+ <path android:fillColor="@android:color/transparent" android:strokeColor="#FFFFFFFF"
+ android:strokeWidth="2" android:strokeLineCap="round" android:strokeLineJoin="round"
+ android:pathData="M6.5,12l3.7,3.7L17.5,8.5" />
+</vector>
diff --git a/launcher/app/src/main/res/layout/row_app_library.xml b/launcher/app/src/main/res/layout/row_app_library.xml
new file mode 100644
index 000000000..056c07800
--- /dev/null
+++ b/launcher/app/src/main/res/layout/row_app_library.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent" android:layout_height="84dp">
+ <TextView android:id="@+id/btnLibrary" style="@style/TopButton"
+ android:layout_gravity="center" android:text="@string/app_library"
+ android:drawableStart="@drawable/ic_apps" />
+</FrameLayout>
diff --git a/launcher/app/src/main/res/values-ar/strings.xml b/launcher/app/src/main/res/values-ar/strings.xml
index 78248fc59..c84543f3e 100644
--- a/launcher/app/src/main/res/values-ar/strings.xml
+++ b/launcher/app/src/main/res/values-ar/strings.xml
@@ -58,4 +58,23 @@
<string name="on">تشغيل</string>
<string name="off">إيقاف</string>
<string name="enable">تفعيل</string>
+ <string name="app_library">مكتبة التطبيقات</string>
+ <string name="library_empty">لم يتم العثور على تطبيقات قابلة للتشغيل</string>
+ <string name="library_on_home">على الرئيسية</string>
+ <string name="library_add_home">إضافة إلى الرئيسية</string>
+ <string name="library_remove_shortcut">إزالة من الرئيسية</string>
+ <string name="library_open">فتح</string>
+ <string name="library_app_info">معلومات التطبيق</string>
+ <string name="library_save_failed">تعذر حفظ الاختصار</string>
+ <string name="library_recent">جديد · إضافة إلى الرئيسية</string>
+ <string name="library_hint_add">اضغط للإضافة للرئيسية · اضغط مطولاً للخيارات</string>
+ <string name="library_hint_open">اضغط للفتح · اضغط مطولاً للخيارات</string>
+ <plurals name="library_app_count">
+ <item quantity="zero">%1$d تطبيق</item>
+ <item quantity="one">%1$d تطبيق</item>
+ <item quantity="two">%1$d تطبيقان</item>
+ <item quantity="few">%1$d تطبيقات</item>
+ <item quantity="many">%1$d تطبيقًا</item>
+ <item quantity="other">%1$d تطبيق</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-b+sr+Latn/strings.xml b/launcher/app/src/main/res/values-b+sr+Latn/strings.xml
index 63b877a6e..7d1f178b4 100644
--- a/launcher/app/src/main/res/values-b+sr+Latn/strings.xml
+++ b/launcher/app/src/main/res/values-b+sr+Latn/strings.xml
@@ -39,4 +39,20 @@
<string name="on">Uklj.</string>
<string name="off">Isklj.</string>
<string name="enable">Uključi</string>
+ <string name="app_library">Biblioteka aplikacija</string>
+ <string name="library_empty">Nema aplikacija koje mogu da se pokrenu</string>
+ <string name="library_on_home">Na početnom ekranu</string>
+ <string name="library_add_home">Dodaj na početni ekran</string>
+ <string name="library_remove_shortcut">Ukloni sa početnog ekrana</string>
+ <string name="library_open">Otvori</string>
+ <string name="library_app_info">Informacije o aplikaciji</string>
+ <string name="library_save_failed">Prečica nije sačuvana</string>
+ <string name="library_recent">Novo · Dodaj na početni ekran</string>
+ <string name="library_hint_add">Pritisni za početni ekran · Zadrži za opcije</string>
+ <string name="library_hint_open">Pritisni za otvaranje · Zadrži za opcije</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d aplikacija</item>
+ <item quantity="few">%1$d aplikacije</item>
+ <item quantity="other">%1$d aplikacija</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-ca/strings.xml b/launcher/app/src/main/res/values-ca/strings.xml
index 77d3d13c2..82b7e147f 100644
--- a/launcher/app/src/main/res/values-ca/strings.xml
+++ b/launcher/app/src/main/res/values-ca/strings.xml
@@ -31,4 +31,19 @@
<string name="on">Activat</string>
<string name="off">Desactivat</string>
<string name="enable">Activa</string>
+ <string name="app_library">Biblioteca d’aplicacions</string>
+ <string name="library_empty">No s’ha trobat cap aplicació que es pugui obrir</string>
+ <string name="library_on_home">A l’inici</string>
+ <string name="library_add_home">Afegeix a l’inici</string>
+ <string name="library_remove_shortcut">Elimina de l’inici</string>
+ <string name="library_open">Obre</string>
+ <string name="library_app_info">Informació de l’aplicació</string>
+ <string name="library_save_failed">No s’ha pogut desar la drecera</string>
+ <string name="library_recent">Nova · Afegeix a l’inici</string>
+ <string name="library_hint_add">Prem per afegir a Inici · Mantén per a opcions</string>
+ <string name="library_hint_open">Prem per obrir · Mantén per a opcions</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d aplicació</item>
+ <item quantity="other">%1$d aplicacions</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-de/strings.xml b/launcher/app/src/main/res/values-de/strings.xml
index cd269f5e3..cb56826ae 100644
--- a/launcher/app/src/main/res/values-de/strings.xml
+++ b/launcher/app/src/main/res/values-de/strings.xml
@@ -35,4 +35,19 @@
<string name="on">Ein</string>
<string name="off">Aus</string>
<string name="enable">Aktivieren</string>
+ <string name="app_library">App-Bibliothek</string>
+ <string name="library_empty">Keine startbaren Apps gefunden</string>
+ <string name="library_on_home">Auf dem Startbildschirm</string>
+ <string name="library_add_home">Zum Startbildschirm</string>
+ <string name="library_remove_shortcut">Vom Startbildschirm entfernen</string>
+ <string name="library_open">Öffnen</string>
+ <string name="library_app_info">App-Info</string>
+ <string name="library_save_failed">Verknüpfung konnte nicht gespeichert werden</string>
+ <string name="library_recent">Neu · Zum Startbildschirm</string>
+ <string name="library_hint_add">Drücken: zu Start hinzufügen · Halten: Optionen</string>
+ <string name="library_hint_open">Drücken: öffnen · Halten: Optionen</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d App</item>
+ <item quantity="other">%1$d Apps</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-es/strings.xml b/launcher/app/src/main/res/values-es/strings.xml
index 808ceec24..6e02a07aa 100644
--- a/launcher/app/src/main/res/values-es/strings.xml
+++ b/launcher/app/src/main/res/values-es/strings.xml
@@ -32,4 +32,19 @@
<string name="on">Sí</string>
<string name="off">No</string>
<string name="enable">Activar</string>
+ <string name="app_library">Biblioteca de aplicaciones</string>
+ <string name="library_empty">No hay aplicaciones que se puedan abrir</string>
+ <string name="library_on_home">En Inicio</string>
+ <string name="library_add_home">Añadir a Inicio</string>
+ <string name="library_remove_shortcut">Quitar de Inicio</string>
+ <string name="library_open">Abrir</string>
+ <string name="library_app_info">Información de la aplicación</string>
+ <string name="library_save_failed">No se pudo guardar el acceso directo</string>
+ <string name="library_recent">Nueva · Añadir a Inicio</string>
+ <string name="library_hint_add">Pulsa para añadir a Inicio · Mantén para opciones</string>
+ <string name="library_hint_open">Pulsa para abrir · Mantén para opciones</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d aplicación</item>
+ <item quantity="other">%1$d aplicaciones</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-fr/strings.xml b/launcher/app/src/main/res/values-fr/strings.xml
index f25d6ccb6..a4f5500d3 100644
--- a/launcher/app/src/main/res/values-fr/strings.xml
+++ b/launcher/app/src/main/res/values-fr/strings.xml
@@ -58,4 +58,19 @@
<string name="on">Activé</string>
<string name="off">Désactivé</string>
<string name="enable">Activer</string>
+ <string name="app_library">Bibliothèque d’applications</string>
+ <string name="library_empty">Aucune application à ouvrir</string>
+ <string name="library_on_home">Sur l’accueil</string>
+ <string name="library_add_home">Ajouter à l’accueil</string>
+ <string name="library_remove_shortcut">Retirer de l’accueil</string>
+ <string name="library_open">Ouvrir</string>
+ <string name="library_app_info">Infos sur l’application</string>
+ <string name="library_save_failed">Impossible d’enregistrer le raccourci</string>
+ <string name="library_recent">Nouvelle · Ajouter à l’accueil</string>
+ <string name="library_hint_add">Appuyer : ajouter à Accueil · Maintenir : options</string>
+ <string name="library_hint_open">Appuyer : ouvrir · Maintenir : options</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d application</item>
+ <item quantity="other">%1$d applications</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-iw/strings.xml b/launcher/app/src/main/res/values-iw/strings.xml
index 5f3d99ea9..f759d6826 100644
--- a/launcher/app/src/main/res/values-iw/strings.xml
+++ b/launcher/app/src/main/res/values-iw/strings.xml
@@ -62,4 +62,20 @@
<string name="quick_network">רשת</string>
<string name="quick_apps">אפליקציות</string>
<string name="quick_apps_hint">הפעלה מחדש</string>
+ <string name="app_library">ספריית אפליקציות</string>
+ <string name="library_empty">לא נמצאו אפליקציות שניתן לפתוח</string>
+ <string name="library_on_home">במסך הבית</string>
+ <string name="library_add_home">הוספה למסך הבית</string>
+ <string name="library_remove_shortcut">הסרה ממסך הבית</string>
+ <string name="library_open">פתיחה</string>
+ <string name="library_app_info">פרטי האפליקציה</string>
+ <string name="library_save_failed">לא ניתן לשמור את קיצור הדרך</string>
+ <string name="library_recent">חדשה · הוספה למסך הבית</string>
+ <string name="library_hint_add">לחיצה להוספה למסך הבית · לחיצה ארוכה לאפשרויות</string>
+ <string name="library_hint_open">לחיצה לפתיחה · לחיצה ארוכה לאפשרויות</string>
+ <plurals name="library_app_count">
+ <item quantity="one">אפליקציה אחת</item>
+ <item quantity="two">שתי אפליקציות</item>
+ <item quantity="other">%1$d אפליקציות</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-pl/strings.xml b/launcher/app/src/main/res/values-pl/strings.xml
index 1fa45f537..983fd7edc 100644
--- a/launcher/app/src/main/res/values-pl/strings.xml
+++ b/launcher/app/src/main/res/values-pl/strings.xml
@@ -58,4 +58,21 @@
<string name="on">Wł.</string>
<string name="off">Wył.</string>
<string name="enable">Włącz</string>
+ <string name="app_library">Biblioteka aplikacji</string>
+ <string name="library_empty">Brak aplikacji do uruchomienia</string>
+ <string name="library_on_home">Na ekranie głównym</string>
+ <string name="library_add_home">Dodaj do ekranu głównego</string>
+ <string name="library_remove_shortcut">Usuń z ekranu głównego</string>
+ <string name="library_open">Otwórz</string>
+ <string name="library_app_info">Informacje o aplikacji</string>
+ <string name="library_save_failed">Nie udało się zapisać skrótu</string>
+ <string name="library_recent">Nowa · Dodaj do ekranu głównego</string>
+ <string name="library_hint_add">Naciśnij, aby dodać do ekranu · Przytrzymaj: opcje</string>
+ <string name="library_hint_open">Naciśnij, aby otworzyć · Przytrzymaj: opcje</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d aplikacja</item>
+ <item quantity="few">%1$d aplikacje</item>
+ <item quantity="many">%1$d aplikacji</item>
+ <item quantity="other">%1$d aplikacji</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-pt/strings.xml b/launcher/app/src/main/res/values-pt/strings.xml
index d994915c8..fa236b275 100644
--- a/launcher/app/src/main/res/values-pt/strings.xml
+++ b/launcher/app/src/main/res/values-pt/strings.xml
@@ -46,4 +46,19 @@
<string name="card_state_new">Novo</string>
<string name="card_state_new_key">Nova chave</string>
<string name="card_state_new_label">Novo nome</string>
+ <string name="app_library">Biblioteca de apps</string>
+ <string name="library_empty">Nenhum app disponível para abrir</string>
+ <string name="library_on_home">Na tela inicial</string>
+ <string name="library_add_home">Adicionar à tela inicial</string>
+ <string name="library_remove_shortcut">Remover da tela inicial</string>
+ <string name="library_open">Abrir</string>
+ <string name="library_app_info">Informações do app</string>
+ <string name="library_save_failed">Não foi possível salvar o atalho</string>
+ <string name="library_recent">Novo · Adicionar à tela inicial</string>
+ <string name="library_hint_add">Pressione para adicionar à tela inicial · Segure para ver opções</string>
+ <string name="library_hint_open">Pressione para abrir · Segure para ver opções</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d app</item>
+ <item quantity="other">%1$d apps</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-ru/strings.xml b/launcher/app/src/main/res/values-ru/strings.xml
index f9060ba25..5dc2af37d 100644
--- a/launcher/app/src/main/res/values-ru/strings.xml
+++ b/launcher/app/src/main/res/values-ru/strings.xml
@@ -58,4 +58,21 @@
<string name="on">Вкл.</string>
<string name="off">Выкл.</string>
<string name="enable">Включить</string>
+ <string name="app_library">Библиотека приложений</string>
+ <string name="library_empty">Нет приложений для запуска</string>
+ <string name="library_on_home">На главном экране</string>
+ <string name="library_add_home">Добавить на главный экран</string>
+ <string name="library_remove_shortcut">Убрать с главного экрана</string>
+ <string name="library_open">Открыть</string>
+ <string name="library_app_info">О приложении</string>
+ <string name="library_save_failed">Не удалось сохранить ярлык</string>
+ <string name="library_recent">Новое · Добавить на главный экран</string>
+ <string name="library_hint_add">Нажать: добавить на главный экран · Удержать: опции</string>
+ <string name="library_hint_open">Нажать: открыть · Удержать: опции</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d приложение</item>
+ <item quantity="few">%1$d приложения</item>
+ <item quantity="many">%1$d приложений</item>
+ <item quantity="other">%1$d приложения</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-th/strings.xml b/launcher/app/src/main/res/values-th/strings.xml
index bb66f7f61..e9940d16d 100644
--- a/launcher/app/src/main/res/values-th/strings.xml
+++ b/launcher/app/src/main/res/values-th/strings.xml
@@ -33,4 +33,18 @@
<string name="on">เปิด</string>
<string name="off">ปิด</string>
<string name="enable">เปิดใช้งาน</string>
+ <string name="app_library">คลังแอป</string>
+ <string name="library_empty">ไม่พบแอปที่เปิดได้</string>
+ <string name="library_on_home">อยู่ในหน้าหลัก</string>
+ <string name="library_add_home">เพิ่มในหน้าหลัก</string>
+ <string name="library_remove_shortcut">นำออกจากหน้าหลัก</string>
+ <string name="library_open">เปิด</string>
+ <string name="library_app_info">ข้อมูลแอป</string>
+ <string name="library_save_failed">บันทึกทางลัดไม่สำเร็จ</string>
+ <string name="library_recent">ใหม่ · เพิ่มในหน้าหลัก</string>
+ <string name="library_hint_add">กดเพื่อเพิ่มที่หน้าหลัก · กดค้างเพื่อดูตัวเลือก</string>
+ <string name="library_hint_open">กดเพื่อเปิด · กดค้างเพื่อดูตัวเลือก</string>
+ <plurals name="library_app_count">
+ <item quantity="other">%1$d แอป</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-tr/strings.xml b/launcher/app/src/main/res/values-tr/strings.xml
index 7d71658d6..a839e6f20 100644
--- a/launcher/app/src/main/res/values-tr/strings.xml
+++ b/launcher/app/src/main/res/values-tr/strings.xml
@@ -58,4 +58,19 @@
<string name="on">Açık</string>
<string name="off">Kapalı</string>
<string name="enable">Etkinleştir</string>
+ <string name="app_library">Uygulama kitaplığı</string>
+ <string name="library_empty">Açılabilecek uygulama bulunamadı</string>
+ <string name="library_on_home">Ana ekranda</string>
+ <string name="library_add_home">Ana ekrana ekle</string>
+ <string name="library_remove_shortcut">Ana ekrandan kaldır</string>
+ <string name="library_open">Aç</string>
+ <string name="library_app_info">Uygulama bilgileri</string>
+ <string name="library_save_failed">Kısayol kaydedilemedi</string>
+ <string name="library_recent">Yeni · Ana ekrana ekle</string>
+ <string name="library_hint_add">Ana ekrana eklemek için bas · Seçenekler için basılı tut</string>
+ <string name="library_hint_open">Açmak için bas · Seçenekler için basılı tut</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d uygulama</item>
+ <item quantity="other">%1$d uygulama</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-zh-rCN/strings.xml b/launcher/app/src/main/res/values-zh-rCN/strings.xml
index 220e62447..548a76b49 100644
--- a/launcher/app/src/main/res/values-zh-rCN/strings.xml
+++ b/launcher/app/src/main/res/values-zh-rCN/strings.xml
@@ -34,4 +34,18 @@
<string name="cant_open">无法打开 %1$s</string>
<string name="date_format">M月d日 EEEE</string>
<string name="dream_name">时钟</string>
+ <string name="app_library">应用库</string>
+ <string name="library_empty">未找到可启动的应用</string>
+ <string name="library_on_home">已在主屏幕</string>
+ <string name="library_add_home">添加到主屏幕</string>
+ <string name="library_remove_shortcut">从主屏幕移除</string>
+ <string name="library_open">打开</string>
+ <string name="library_app_info">应用信息</string>
+ <string name="library_save_failed">无法保存快捷方式</string>
+ <string name="library_recent">新安装 · 添加到主屏幕</string>
+ <string name="library_hint_add">按下添加到主屏幕 · 长按查看选项</string>
+ <string name="library_hint_open">按下打开 · 长按查看选项</string>
+ <plurals name="library_app_count">
+ <item quantity="other">%1$d 个应用</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values-zh-rTW/strings.xml b/launcher/app/src/main/res/values-zh-rTW/strings.xml
index 8be29ac81..b8938c043 100644
--- a/launcher/app/src/main/res/values-zh-rTW/strings.xml
+++ b/launcher/app/src/main/res/values-zh-rTW/strings.xml
@@ -58,4 +58,18 @@
<string name="card_state_new">新的</string>
<string name="card_state_new_key">新金鑰</string>
<string name="card_state_new_label">新名稱</string>
+ <string name="app_library">應用程式庫</string>
+ <string name="library_empty">找不到可啟動的應用程式</string>
+ <string name="library_on_home">已在主畫面</string>
+ <string name="library_add_home">新增至主畫面</string>
+ <string name="library_remove_shortcut">從主畫面移除</string>
+ <string name="library_open">開啟</string>
+ <string name="library_app_info">應用程式資訊</string>
+ <string name="library_save_failed">無法儲存捷徑</string>
+ <string name="library_recent">新安裝 · 新增至主畫面</string>
+ <string name="library_hint_add">按下以新增至主畫面 · 長按以顯示選項</string>
+ <string name="library_hint_open">按下以開啟 · 長按以顯示選項</string>
+ <plurals name="library_app_count">
+ <item quantity="other">%1$d 個應用程式</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/main/res/values/config.xml b/launcher/app/src/main/res/values/config.xml
index 959b86d0f..840560339 100644
--- a/launcher/app/src/main/res/values/config.xml
+++ b/launcher/app/src/main/res/values/config.xml
@@ -83,6 +83,9 @@
Off by default because the chooser is also available from launcher settings. -->
<bool name="show_home_settings_shortcut">false</bool>
+ <!-- Installed launchable apps, including ordinary Android apps. Also settable in config.json. -->
+ <bool name="app_library">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>
diff --git a/launcher/app/src/main/res/values/strings.xml b/launcher/app/src/main/res/values/strings.xml
index dd579ee75..bb1a4fb23 100644
--- a/launcher/app/src/main/res/values/strings.xml
+++ b/launcher/app/src/main/res/values/strings.xml
@@ -64,4 +64,19 @@
<string name="card_state_new">New</string>
<string name="card_state_new_key">New key</string>
<string name="card_state_new_label">New name</string>
+ <string name="app_library">App library</string>
+ <string name="library_empty">No launchable apps found</string>
+ <string name="library_on_home">On Home</string>
+ <string name="library_add_home">Add to Home</string>
+ <string name="library_remove_shortcut">Remove from Home</string>
+ <string name="library_open">Open</string>
+ <string name="library_app_info">App info</string>
+ <string name="library_save_failed">Could not save the shortcut</string>
+ <string name="library_recent">New · Add to Home</string>
+ <string name="library_hint_add">Press to add to Home · Hold for options</string>
+ <string name="library_hint_open">Press to open · Hold for options</string>
+ <plurals name="library_app_count">
+ <item quantity="one">%1$d app</item>
+ <item quantity="other">%1$d apps</item>
+ </plurals>
</resources>
diff --git a/launcher/app/src/test/java/com/gathin/tvhome/LibraryAppsTest.java b/launcher/app/src/test/java/com/gathin/tvhome/LibraryAppsTest.java
new file mode 100644
index 000000000..03a6a2b8a
--- /dev/null
+++ b/launcher/app/src/test/java/com/gathin/tvhome/LibraryAppsTest.java
@@ -0,0 +1,102 @@
+package com.gathin.tvhome;
+
+import org.junit.Test;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import static org.junit.Assert.*;
+
+public class LibraryAppsTest {
+ private static final long DAY = 24L * 60 * 60 * 1000;
+
+ @Test public void missingShortcutsComeBeforeHomeAppsEvenWhenTheHomeAppIsNewer() {
+ long now = 100 * DAY;
+ assertTrue(LibraryApps.comparePriority(false, DAY, true, now, now) < 0);
+ assertTrue(LibraryApps.comparePriority(true, now, false, DAY, now) > 0);
+ }
+
+ @Test public void recentMissingAppsComeFirstButOlderAppsAndHomeAppsUseLabelOrder() {
+ long now = 100 * DAY;
+ assertTrue(LibraryApps.comparePriority(false, now, false, now - DAY, now) < 0);
+ assertTrue(LibraryApps.comparePriority(false, now - DAY, false, DAY, now) < 0);
+ assertEquals(0, LibraryApps.comparePriority(false, DAY, false, 2 * DAY, now));
+ assertEquals(0, LibraryApps.comparePriority(true, now, true, DAY, now));
+ }
+
+ @Test public void recentMeansFirstInstalledWithinSevenDaysAndNotAnUnknownOrFutureDate() {
+ long now = 100 * DAY;
+ assertTrue(LibraryApps.recent(now - 7 * DAY, now));
+ assertFalse(LibraryApps.recent(now - 7 * DAY - 1, now));
+ assertFalse(LibraryApps.recent(0, now));
+ assertFalse(LibraryApps.recent(now + 1, now));
+ }
+ @Test public void themeAndTvDefaultsStayInPlaceUntilTheOwnerChoosesAnApp() {
+ assertTrue(LibraryApps.visible(true, false, false));
+ assertFalse(LibraryApps.visible(true, true, false));
+ assertFalse(LibraryApps.visible(false, false, false));
+ assertTrue(LibraryApps.visible(false, false, true));
+ assertTrue(LibraryApps.visible(true, true, true));
+ }
+
+ @Test public void undoingAnAdditionRestoresDefaultVisibilityAndKeepsOtherChoices() {
+ Set<String> original = new HashSet<>();
+ original.add("com.example.phone");
+ original.add("com.example.hidden");
+ Set<String> next = LibraryApps.change(original, "com.example.phone", false);
+ assertFalse(next.contains("com.example.phone"));
+ assertTrue(next.contains("com.example.hidden"));
+ assertTrue(original.contains("com.example.phone"));
+ assertFalse(LibraryApps.visible(false, false, next.contains("com.example.phone")));
+ }
+
+ @Test public void removingAnyHomeAppOverridesThemeDefaultsAndPreviousAdditions() {
+ assertFalse(LibraryApps.visible(true, false, false, true));
+ assertFalse(LibraryApps.visible(true, false, true, true));
+ assertFalse(LibraryApps.visible(false, false, true, true));
+ assertTrue(LibraryApps.visible(false, false, true, false));
+ assertTrue(LibraryApps.visible(true, false, false, false));
+ }
+
+ @Test public void addingAdvancesPastCheckedAppsToTheNextMissingShortcut() {
+ assertEquals(3, LibraryApps.nextFocus(1, 5, index -> index == 3 || index == 4));
+ assertEquals(0, LibraryApps.nextFocus(4, 5, index -> index == 0 || index == 2));
+ }
+
+ @Test public void addingTheLastMissingShortcutKeepsANearbyCardInsteadOfJumpingToTheStart() {
+ assertEquals(3, LibraryApps.nextFocus(2, 5, index -> false));
+ assertEquals(3, LibraryApps.nextFocus(4, 5, index -> false));
+ assertEquals(0, LibraryApps.nextFocus(0, 1, index -> { fail("No other card to inspect"); return true; }));
+ assertEquals(-1, LibraryApps.nextFocus(0, 0, index -> { fail("Empty catalogue"); return true; }));
+ }
+
+ @Test public void staleFocusIsClampedAfterAnAppRemoval() {
+ assertEquals(1, LibraryApps.nextFocus(9, 3, index -> index == 1));
+ assertEquals(1, LibraryApps.nextFocus(-1, 3, index -> index == 1));
+ }
+
+ @Test public void choicesRoundTripInStableOrderIncludingAnEmptyList() {
+ Set<String> apps = new HashSet<>();
+ apps.add("org.z.example"); apps.add("com.a.example");
+ assertEquals("com.a.example\norg.z.example\n", LibraryApps.encode(apps));
+ assertEquals(apps, LibraryApps.decode(LibraryApps.encode(apps)));
+ assertEquals(Collections.emptySet(), LibraryApps.decode(""));
+ }
+
+ @Test public void duplicateAndMalformedRecordsAreRejected() {
+ for (String raw : new String[]{"com.example\ncom.example\n", "com..example\n",
+ "com.example\n\n", "../file\n", "9bad.app\n", "com.example\ninvalid/name\n"}) {
+ try { LibraryApps.decode(raw); fail(raw); }
+ catch (IllegalArgumentException expected) { }
+ }
+ }
+
+ @Test public void aFullListAllowsRemovalAndAnExistingChoiceButNotAnotherApp() {
+ Set<String> apps = new HashSet<>();
+ for (int i = 0; i < LibraryApps.MAX_ADDED; i++) apps.add("com.example.app" + i);
+ assertEquals(apps, LibraryApps.change(apps, "com.example.app0", true));
+ assertEquals(LibraryApps.MAX_ADDED - 1, LibraryApps.change(apps, "com.example.app0", false).size());
+ try { LibraryApps.change(apps, "com.example.extra", true); fail(); }
+ catch (IllegalArgumentException expected) { }
+ assertEquals(LibraryApps.MAX_ADDED, apps.size());
+ }
+}