Skip to content

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

Add-on: Startup & Branding, a welcome screen of your own

מקס חייםafc171818a97
diff --git a/addons/README.md b/addons/README.md
index 31827a586..46ba662e4 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -26,6 +26,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| [Sources](sources/) | The TV's sources by the names devices give themselves over HDMI-CEC ("PlayStation 5", not "HDMI 2"), with their state, and Live TV; OK switches | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | None | <img src="sources/screenshot.jpg" width="240" alt="Sources on a TV"> |
| [Smart Home](smart-home/) | Home Assistant on the TV: scenes, lights and switches (OK toggles, left and right dim), climate, temperature and humidity, doors and windows, and locks shown but never opened | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | `INTERNET` (your Home Assistant only) | <img src="smart-home/screenshot.jpg" width="240" alt="Smart Home on a TV"> |
| [Ad Blocking](ad-blocking/) | Your Pi-hole (6 or 5) or AdGuard Home on the TV: today's queries and blocked share, and one OK to pause blocking for five minutes | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | `INTERNET` (your blocker only) | <img src="ad-blocking/screenshot.jpg" width="240" alt="Ad Blocking on a TV"> |
+| [Startup & Branding](startup-branding/) | A welcome screen of your own: your picture, a background colour and a line of text, full screen for a few seconds or until Back or OK, with a live preview, Fit/Fill/Stretch/Original scaling and a compatibility check of what the TV allows without root | [@maxhayim](https://github.com/maxhayim) | MOKA M1G (Android TV 11) | None | <img src="startup-branding/screenshot.jpg" width="240" alt="Startup & Branding on a TV"> |
| [World Clock](world-clock/) | One to six offline clocks with dates, UTC offsets and day differences; city search and D-pad controls | [@SaviorOneZero](https://github.com/SaviorOneZero) | Samsung C71KW-200 / AT&T Osprey (Android TV 11) | None | <img src="world-clock/screenshot.jpg" width="240" alt="World Clock on a TV"> |
| [Flock](flock/) | An interactive flocking simulation using separation, alignment and cohesion, controlled with the TV remote | CleanYourTV contributors | TCL 32S5K (Android TV 14) | None | <img src="flock/screenshot.jpg" width="240" alt="Flock on TCL Android TV"> |
diff --git a/addons/startup-branding/.gitignore b/addons/startup-branding/.gitignore
new file mode 100644
index 000000000..a7e04a21b
--- /dev/null
+++ b/addons/startup-branding/.gitignore
@@ -0,0 +1,4 @@
+.gradle/
+build/
+app/build/
+local.properties
diff --git a/addons/startup-branding/README.md b/addons/startup-branding/README.md
new file mode 100644
index 000000000..1c56f9803
--- /dev/null
+++ b/addons/startup-branding/README.md
@@ -0,0 +1,104 @@
+# Startup & Branding
+
+A welcome screen of your own for the TV: your picture (a logo, a family photo, a room name), a background colour
+and a line of text such as "Welcome to the Den", full screen for a few seconds or until Back or OK. Pick the picture,
+how it's scaled (Fit, Fill, Stretch or Original) and where it sits, see it in a live 16:9 preview beside the
+settings, and preview it full screen. A Compatibility screen says plainly what this TV allows without root and what
+it doesn't. For the [Clean Your TV](../../README.md) launcher it declares a [module card](../../docs/modules.md):
+once you answer **Show card** its tile reads "Startup & Branding" with an amber glow. On any other Android TV home it
+is an ordinary app.
+
+![Startup & Branding on a TV: the Custom Image screen with its live preview](screenshot.jpg)
+
+It does **not** change the maker's boot logo or the boot animation, and it does not open by itself after a
+restart: see [Limits](#limits). It never pretends to be part of the TV's startup.
+
+## What's on it
+
+- **Welcome Screen**: Custom (picture, colour, text), Black (a plain black screen) or Off.
+- **Preview**: the welcome screen full screen, exactly as it will look.
+- **Custom Image**: the picture, Scaling, Position, a live preview and the full-screen preview. PNG, JPEG or WebP up
+ to 15 MB; pictures are checked by their first bytes, and big ones are decoded only as large as the screen needs.
+- **Welcome Text** (up to 60 characters, one line), **Text Position** (bottom, center, top), **Background Color**
+ (six), **Display Duration** (3 to 30 s, or until Back or OK).
+- **Device Name**: the TV's real name, as phones and casting see it, and OK opens the TV's own setting to change it.
+ **Nickname** is a second line under the welcome text and lives in this module only; it never renames the TV.
+- **Compatibility**: the TV's maker, model, Android version and screen, and each feature as Works, Not here,
+ Needs launcher, Needs system or Not possible.
+- **Restore Defaults**: turn the welcome screen off (keeping your settings), put every setting back, or delete the
+ pictures. The last two take OK twice.
+
+## Permissions
+
+None. No internet: nothing leaves the TV. No storage permission: pictures live in the app's own folder
+(`Android/data/io.github.maxhayim.startupbranding/files/pictures`). No overlay, accessibility, foreground service,
+start at boot, accounts, telemetry, ads or libraries.
+
+- Package visibility is limited to the file picker and the TV's device-name and device-info settings screens, to
+ offer them only when they exist (many Android TVs have only a stub picker that does nothing).
+- One content provider, guarded by `WRITE_SECURE_SETTINGS`, which the ADB shell has and ordinary apps don't:
+ `push-image.sh` writes pictures through it so the app owns them. It writes and deletes picture names only.
+- `.Welcome` is exported so a remote button or a launcher hook can open the welcome screen (below). It reads nothing
+ from the intent and shows only while the welcome screen is on.
+
+## Build and install
+
+JDK 17 and Android SDK platform 34 with build-tools 34.0.0, as for the launcher. From the repo root, with ADB on:
+
+```bash
+TV_HOST=<tv ip> addons/startup-branding/install.sh
+TV_HOST=<tv ip> addons/startup-branding/push-image.sh logo.png family.jpg # pictures from a computer
+TV_HOST=<tv ip> addons/startup-branding/push-image.sh --delete logo.png
+TV_HOST=<tv ip> addons/startup-branding/install.sh --uninstall # app, settings and pictures gone
+```
+
+Then pick the picture on the TV in Custom Image. Where the TV has a real file picker, Choose a File copies a picture
+in from there instead. To build only: `cd addons/startup-branding && ./gradlew assembleRelease`; the JVM tests run
+with `./gradlew testReleaseUnitTest`.
+
+## Limits
+
+- **The maker's boot logo** is shown by the bootloader before Android starts. Only the maker's firmware changes it.
+- **The boot animation** is a file on a read-only system partition. Replacing it needs root or a firmware change;
+ this module never touches it, and Compatibility only says whether the file is there.
+- **Opening by itself after a restart.** From Android 10, an app can't open a screen from the background, so a boot
+ receiver can't show the welcome screen. The ways around that (drawing over other apps, accessibility, a foreground
+ service) are left out on purpose. Today the welcome screen opens from Preview, or from anything that starts
+ `.Welcome`.
+- **Renaming the TV** needs `WRITE_SECURE_SETTINGS`, so this module opens the TV's own setting rather than setting
+ the name itself.
+- **Pictures.** Animated GIFs, SVG and HEIC are not supported, and pictures over 8192 px on a side are refused.
+ Original size is relative to a 1080p screen.
+
+## Opening after boot: a launcher hook (proposal)
+
+The home app is in front after every boot, so it can do what an add-on can't. A possible opt-in for the launcher,
+**not part of this add-on and off by default**:
+
+- A launcher setting such as "Open after boot", off unless the owner turns it on, naming one activity (for this
+ add-on, `io.github.maxhayim.startupbranding/.Welcome`).
+- Once per boot, when Home first appears, the launcher starts it. If the welcome screen is off, `.Welcome` closes at
+ once, so nothing shows.
+- Nothing else changes: no permissions for the launcher, no change to Home's behaviour while the setting is off.
+
+That needs the maintainer's say-so and its own pull request. Mapping a remote button to `.Welcome` through the
+launcher's app keys works the same way, once those can target an activity.
+
+## Tested on
+
+MOKA M1G (Android TV 11, Realtek RTD2851F, 1920×1080) with the stock Google TV home, over ADB:
+
+- `install.sh` from source, and `push-image.sh` sending a picture through the provider; it showed up in Custom Image
+ and in the live preview.
+- The full-screen preview, closed with OK; Preview still opens while the welcome screen is Off.
+- `.Welcome` opened from outside, as a remote button or launcher hook would: it showed, closed by itself after 5 s and
+ went back to the Google TV home. While Off, it closed at once and Home stayed in front.
+- Compatibility read the TV correctly and found a real file picker on it.
+
+Not tested yet: copying a picture in through Choose a File, Device Name opening the TV's own setting, and Restore
+Defaults. The JVM tests cover the settings and their limits, scaling and placement, picture types, decode size, text
+cleaning, file names and the compatibility answers.
+
+## Maintainer
+
+[@maxhayim](https://github.com/maxhayim)
diff --git a/addons/startup-branding/app/build.gradle b/addons/startup-branding/app/build.gradle
new file mode 100644
index 000000000..5d213ef42
--- /dev/null
+++ b/addons/startup-branding/app/build.gradle
@@ -0,0 +1,36 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'io.github.maxhayim.startupbranding'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'io.github.maxhayim.startupbranding'
+ minSdk 26
+ targetSdk 34
+ versionCode 1
+ versionName '0.1'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ shrinkResources true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ // Sideloaded over ADB, never published: signed with the debug key, like the launcher.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
+
+dependencies {
+ // No libraries in the APK. Test only: plain JVM tests in src/test.
+ testImplementation 'junit:junit:4.13.2'
+}
diff --git a/addons/startup-branding/app/proguard-rules.pro b/addons/startup-branding/app/proguard-rules.pro
new file mode 100644
index 000000000..a4435d69a
--- /dev/null
+++ b/addons/startup-branding/app/proguard-rules.pro
@@ -0,0 +1,2 @@
+# Keep class and method names: readable stack traces matter more than the last few KB in a sideloaded app.
+-dontobfuscate
diff --git a/addons/startup-branding/app/src/main/AndroidManifest.xml b/addons/startup-branding/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..6504c37af
--- /dev/null
+++ b/addons/startup-branding/app/src/main/AndroidManifest.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-feature android:name="android.software.leanback" android:required="false" />
+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
+
+ <!-- No permissions: no network, no storage (pictures live in the app's own folder), no overlay, nothing at boot. -->
+
+ <!-- To know whether this TV has a real file picker and a device-name screen, before offering them. -->
+ <queries>
+ <intent>
+ <action android:name="android.intent.action.OPEN_DOCUMENT" />
+ <data android:mimeType="image/*" />
+ </intent>
+ <intent>
+ <action android:name="android.intent.action.GET_CONTENT" />
+ <data android:mimeType="image/*" />
+ </intent>
+ <intent>
+ <action android:name="android.settings.DEVICE_NAME" />
+ </intent>
+ <intent>
+ <action android:name="android.settings.DEVICE_INFO_SETTINGS" />
+ </intent>
+ </queries>
+
+ <application
+ android:allowBackup="false"
+ android:banner="@drawable/banner"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
+
+ <!-- The tile and card: the settings. -->
+ <activity
+ android:name=".MainActivity"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="com.gathin.tvhome.category.DOCK_CARD" />
+ </intent-filter>
+ <meta-data android:name="com.gathin.tvhome.card" android:resource="@xml/module_card" />
+ </activity>
+
+ <!-- The welcome screen. Preview opens it directly. A task of its own, so closing it goes back to whatever
+ was on screen, not to this app's last screen. -->
+ <activity
+ android:name=".WelcomeActivity"
+ android:exported="false"
+ android:excludeFromRecents="true"
+ android:noHistory="true"
+ android:taskAffinity=""
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen" />
+ <!-- The door for others: a remote button (the launcher's app_keys) or a launcher hook opens .Welcome. It
+ shows only while the welcome screen is on, and reads nothing from the intent. -->
+ <activity-alias
+ android:name=".Welcome"
+ android:exported="true"
+ android:targetActivity=".WelcomeActivity" />
+
+ <activity android:name=".ImageActivity" android:exported="false" />
+ <activity android:name=".CompatActivity" android:exported="false" />
+ <activity android:name=".ResetActivity" android:exported="false" />
+
+ <!-- push-image.sh writes pictures through this, so the app owns them. WRITE_SECURE_SETTINGS: the adb shell
+ has it, ordinary apps don't. -->
+ <provider
+ android:name=".PicturesProvider"
+ android:authorities="io.github.maxhayim.startupbranding.pictures"
+ android:exported="true"
+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />
+ </application>
+</manifest>
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Compat.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Compat.java
new file mode 100644
index 000000000..10265f977
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Compat.java
@@ -0,0 +1,89 @@
+package io.github.maxhayim.startupbranding;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * What can and can't be done about the TV's startup look, from facts about this TV. Plain Java, so the answers
+ * are tested on the computer; {@link DeviceInfo} gathers the facts.
+ */
+final class Compat {
+ enum Status {
+ WORKS("Works", "Works without root"),
+ DEPENDS("Not here", "Depends on the TV"),
+ LAUNCHER("Needs launcher", "Needs the home app's help"),
+ SYSTEM("Needs system", "Needs root or a system app"),
+ NO("Not possible", "Only the maker's firmware");
+
+ final String label, heading;
+
+ Status(String label, String heading) {
+ this.label = label;
+ this.heading = heading;
+ }
+ }
+
+ static final class Item {
+ final String name, detail;
+ final Status status;
+
+ Item(String name, Status status, String detail) {
+ this.name = name;
+ this.status = status;
+ this.detail = detail;
+ }
+ }
+
+ /** Facts about this TV. */
+ static final class Facts {
+ int sdk;
+ boolean picker, nameSettings, bootAnimationFound;
+ }
+
+ private Compat() {
+ }
+
+ static List<Item> items(Facts f) {
+ List<Item> out = new ArrayList<>();
+ out.add(new Item("Welcome screen and preview", Status.WORKS,
+ "Your picture, colour and text, full screen, closed with Back or OK. No root, no permissions."));
+ out.add(new Item("Pictures from a computer", Status.WORKS,
+ "push-image.sh copies them into this module's own folder over ADB."));
+ out.add(new Item("Pictures from the TV's file picker", f.picker ? Status.WORKS : Status.DEPENDS,
+ f.picker ? "This TV has a file picker." : "This TV has none (Android TV often ships only a stub)."));
+ out.add(new Item("Opening by itself after boot", Status.LAUNCHER, f.sdk >= 29
+ ? "Android " + release(f.sdk) + " doesn't let an app open a screen from the background at boot. It needs the home app to open it."
+ : "This module doesn't open itself at boot. It needs the home app to open it."));
+ out.add(new Item("Opening from a remote button", Status.LAUNCHER,
+ "Map a button to .Welcome in the launcher's app_keys, once the launcher supports activity targets."));
+ out.add(new Item("Renaming the TV", f.nameSettings ? Status.WORKS : Status.SYSTEM, f.nameSettings
+ ? "Apps can't set the name themselves; Device Name opens the TV's own setting for it."
+ : "Apps can't set it, and this TV has no settings screen for it."));
+ out.add(new Item("Boot animation", Status.SYSTEM, (f.bootAnimationFound
+ ? "This TV's animation lives on a read-only system partition. "
+ : "")
+ + "Replacing it needs root or a firmware change; this module never touches it."));
+ out.add(new Item("Maker's boot logo", Status.NO,
+ "Shown by the bootloader before Android starts. Only the maker's firmware changes it."));
+ // Grouped by status, in the order above within each group.
+ out.sort((a, b) -> a.status.ordinal() - b.status.ordinal());
+ return out;
+ }
+
+ static String release(int sdk) {
+ switch (sdk) {
+ case 26: return "8.0";
+ case 27: return "8.1";
+ case 28: return "9";
+ case 29: return "10";
+ case 30: return "11";
+ case 31: return "12";
+ case 32: return "12L";
+ case 33: return "13";
+ case 34: return "14";
+ case 35: return "15";
+ case 36: return "16";
+ default: return "API " + sdk;
+ }
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/CompatActivity.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/CompatActivity.java
new file mode 100644
index 000000000..6a5ee43af
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/CompatActivity.java
@@ -0,0 +1,24 @@
+package io.github.maxhayim.startupbranding;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+/**
+ * What works on this TV and what doesn't: from what this module does without root, to what only a system app or
+ * the maker's firmware can change. Rows take focus only so the list scrolls with the D-pad.
+ */
+public class CompatActivity extends Activity {
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ Page page = new Page(this, "Compatibility", false);
+ page.subtitle.setText(DeviceInfo.summary(this));
+ Compat.Status last = null;
+ for (Compat.Item item : Compat.items(DeviceInfo.facts(this))) {
+ if (item.status != last) page.heading(item.status.heading);
+ last = item.status;
+ page.add(item.name, item.detail, () -> { }).setValue(item.status.label);
+ }
+ page.focus(0);
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/DeviceInfo.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/DeviceInfo.java
new file mode 100644
index 000000000..e11e30a41
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/DeviceInfo.java
@@ -0,0 +1,53 @@
+package io.github.maxhayim.startupbranding;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.provider.Settings;
+import android.util.DisplayMetrics;
+
+import java.io.File;
+
+/** Facts about this TV from public APIs only: the build, the screen, features, and which settings screens exist. */
+final class DeviceInfo {
+ private DeviceInfo() {
+ }
+
+ /** The TV's device-name screen, most specific first: Android TV's own, then device info, then settings. */
+ static Intent[] nameSettings() {
+ return new Intent[]{
+ new Intent("android.settings.DEVICE_NAME"),
+ new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS),
+ new Intent(Settings.ACTION_SETTINGS)};
+ }
+
+ static boolean hasNameSettings(Context c) {
+ PackageManager pm = c.getPackageManager();
+ for (int i = 0; i < 2; i++) if (nameSettings()[i].resolveActivity(pm) != null) return true;
+ return false;
+ }
+
+ static Compat.Facts facts(Context c) {
+ Compat.Facts f = new Compat.Facts();
+ f.sdk = Build.VERSION.SDK_INT;
+ f.picker = Images.picker(c) != null;
+ f.nameSettings = hasNameSettings(c);
+ // Only whether the file is there: it is read-only, and this module never opens it.
+ for (String p : new String[]{"/product/media/bootanimation.zip", "/system/media/bootanimation.zip",
+ "/oem/media/bootanimation.zip", "/vendor/media/bootanimation.zip"}) {
+ if (new File(p).exists()) f.bootAnimationFound = true;
+ }
+ return f;
+ }
+
+ /** One line about the TV: maker, model, Android version, screen and TV kind. */
+ static String summary(Context c) {
+ DisplayMetrics m = c.getResources().getDisplayMetrics();
+ PackageManager pm = c.getPackageManager();
+ String kind = pm.hasSystemFeature("com.google.android.feature.GOOGLE_EXPERIENCE") && pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
+ ? "Google TV" : pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ? "Android TV" : "Android";
+ return Build.MANUFACTURER + " " + Build.MODEL + " · " + kind + " · Android " + Build.VERSION.RELEASE
+ + " (API " + Build.VERSION.SDK_INT + ") · " + m.widthPixels + "×" + m.heightPixels;
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Fit.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Fit.java
new file mode 100644
index 000000000..0028c68b9
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Fit.java
@@ -0,0 +1,79 @@
+package io.github.maxhayim.startupbranding;
+
+/** Where things go on the welcome screen, as {left, top, right, bottom}. Plain Java, tested on the computer. */
+final class Fit {
+ private Fit() {
+ }
+
+ /** The largest 16:9 frame centered in a {@code w} by {@code h} screen (black bars on other shapes). */
+ static int[] frame(int w, int h) {
+ if (w <= 0 || h <= 0) return new int[]{0, 0, 0, 0};
+ long fw = w, fh = (long) w * 9 / 16;
+ if (fh > h) {
+ fh = h;
+ fw = (long) h * 16 / 9;
+ }
+ int l = (int) ((w - fw) / 2), t = (int) ((h - fh) / 2);
+ return new int[]{l, t, l + (int) fw, t + (int) fh};
+ }
+
+ /**
+ * The picture's place inside {@code frame}. Fit shows all of it, Fill covers the frame (cropped by the frame),
+ * Stretch ignores its shape, Original keeps its pixel size at {@code density} (shrunk to fit if bigger).
+ */
+ static int[] image(int iw, int ih, int[] frame, Look.Scale scale, Look.Align align, float density) {
+ int fw = frame[2] - frame[0], fh = frame[3] - frame[1];
+ if (iw <= 0 || ih <= 0 || fw <= 0 || fh <= 0) return new int[]{frame[0], frame[1], frame[0], frame[1]};
+ double w, h;
+ switch (scale) {
+ case STRETCH:
+ return frame.clone();
+ case FILL: {
+ double k = Math.max((double) fw / iw, (double) fh / ih);
+ w = iw * k;
+ h = ih * k;
+ break;
+ }
+ case ORIGINAL: {
+ w = iw * (double) density;
+ h = ih * (double) density;
+ double k = Math.min(1, Math.min(fw / w, fh / h));
+ w *= k;
+ h *= k;
+ break;
+ }
+ default: {
+ double k = Math.min((double) fw / iw, (double) fh / ih);
+ w = iw * k;
+ h = ih * k;
+ }
+ }
+ int rw = (int) Math.round(w), rh = (int) Math.round(h);
+ int l = frame[0] + (fw - rw) / 2, t = frame[1] + (fh - rh) / 2;
+ switch (align) {
+ case TOP: t = frame[1]; break;
+ case BOTTOM: t = frame[3] - rh; break;
+ case LEFT: l = frame[0]; break;
+ case RIGHT: l = frame[2] - rw; break;
+ default: break;
+ }
+ return new int[]{l, t, l + rw, t + rh};
+ }
+
+ /** How much to shrink a picture while decoding so it is no bigger than needed (a power of two). */
+ static int sampleSize(int iw, int ih, int maxW, int maxH) {
+ int s = 1;
+ while (iw / (s * 2) >= maxW && ih / (s * 2) >= maxH) s *= 2;
+ return s;
+ }
+
+ /** PNG, JPEG or WebP by the file's first bytes, or null for anything else. */
+ static String kind(byte[] head) {
+ if (head == null) return null;
+ if (head.length >= 8 && (head[0] & 0xFF) == 0x89 && head[1] == 'P' && head[2] == 'N' && head[3] == 'G') return "png";
+ if (head.length >= 3 && (head[0] & 0xFF) == 0xFF && (head[1] & 0xFF) == 0xD8 && (head[2] & 0xFF) == 0xFF) return "jpg";
+ if (head.length >= 12 && head[0] == 'R' && head[1] == 'I' && head[2] == 'F' && head[3] == 'F'
+ && head[8] == 'W' && head[9] == 'E' && head[10] == 'B' && head[11] == 'P') return "webp";
+ return null;
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/ImageActivity.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/ImageActivity.java
new file mode 100644
index 000000000..921b56d3c
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/ImageActivity.java
@@ -0,0 +1,164 @@
+package io.github.maxhayim.startupbranding;
+
+import android.app.Activity;
+import android.content.ActivityNotFoundException;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.view.ViewGroup;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import java.util.List;
+
+/**
+ * The picture: which one, how it's scaled and where it sits, with a live 16:9 preview beside the rows. Pictures
+ * come from the TV's file picker, where it has a real one, or from a computer with push-image.sh.
+ */
+public class ImageActivity extends Activity {
+ private static final int PICK = 1;
+
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private Page page;
+ private WelcomeView preview;
+ private String shownImage;
+ private Bitmap shownBitmap;
+ private int previewW = 640, previewH = 360;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ page = new Page(this, "Custom Image", true);
+ page.subtitle.setText("PNG, JPEG or WebP, up to 15 MB.");
+ TextView label = new TextView(this);
+ label.setText("Preview");
+ label.setTextSize(14);
+ label.setTextColor(0xFF8B949E);
+ label.setPadding(0, 0, 0, page.px(8));
+ page.side.addView(label);
+ FrameLayout box = new FrameLayout(this);
+ preview = new WelcomeView(this);
+ box.addView(preview, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
+ page.side.addView(box, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, page.px(1)));
+ // 16:9 at the side panel's width, once it is known.
+ box.addOnLayoutChangeListener((v, l, t, r, b, ol, ot, or, ob) -> {
+ int w = r - l, h = w * 9 / 16;
+ if (w > 0 && v.getLayoutParams().height != h) {
+ previewW = w;
+ previewH = h;
+ v.getLayoutParams().height = h;
+ v.post(v::requestLayout);
+ }
+ });
+ TextView hint = new TextView(this);
+ hint.setText("From a computer: TV_HOST=<tv ip> addons/startup-branding/push-image.sh picture.png");
+ hint.setTextSize(13);
+ hint.setTextColor(0xFF8B949E);
+ hint.setPadding(0, page.px(14), 0, 0);
+ page.side.addView(hint);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ build(page.focused());
+ }
+
+ private void build(int focus) {
+ page.rows.removeAllViews();
+ Look l = Prefs.load(this);
+ List<String> pictures = Images.list(this);
+ if (!l.image.isEmpty() && !pictures.contains(l.image)) {
+ // The file went away: say None rather than a name that no longer shows.
+ l.image = "";
+ Prefs.save(this, l);
+ }
+
+ page.add("Picture", pictures.isEmpty() ? "None on this TV yet." : "OK picks the next one ("
+ + pictures.size() + (pictures.size() == 1 ? " picture)." : " pictures)."),
+ pictures.isEmpty() ? null : () -> change(x -> {
+ int i = pictures.indexOf(x.image);
+ x.image = i + 1 < pictures.size() ? pictures.get(i + 1) : "";
+ }))
+ .setValue(l.image.isEmpty() ? "None" : l.image);
+ Intent pick = Images.picker(this);
+ page.add("Choose a File", pick != null ? "Opens this TV's file picker; the picture is copied in."
+ : "This TV has no file picker. Use a computer (see right), or a file manager app.",
+ pick == null ? null : () -> {
+ try {
+ startActivityForResult(pick, PICK);
+ } catch (ActivityNotFoundException | SecurityException e) {
+ page.subtitle.setText("The file picker didn't open.");
+ }
+ })
+ .setValue(pick != null ? "" : "Unavailable");
+ page.add("Scaling", scaleDetail(l.scale), () -> change(x -> x.scale = Look.next(Look.Scale.values(), x.scale)))
+ .setValue(MainActivity.cap(l.scale.name()));
+ page.add("Position", "Where the picture sits when it doesn't fill the screen.",
+ () -> change(x -> x.align = Look.next(Look.Align.values(), x.align)))
+ .setValue(MainActivity.cap(l.align.name()));
+ page.add("Full-Screen Preview", "Back or OK closes it.",
+ () -> startActivity(new Intent(this, WelcomeActivity.class).putExtra(WelcomeActivity.EXTRA_PREVIEW, true)));
+ page.focus(focus);
+ showPreview(l);
+ }
+
+ private static String scaleDetail(Look.Scale s) {
+ switch (s) {
+ case FILL: return "Fill: covers the screen, cropping the edges.";
+ case STRETCH: return "Stretch: covers the screen, ignoring the picture's shape.";
+ case ORIGINAL: return "Original: its own size on a 1080p screen, shrunk only if bigger.";
+ default: return "Fit: all of the picture, as big as it fits.";
+ }
+ }
+
+ private void showPreview(Look l) {
+ if (l.image.equals(shownImage)) {
+ preview.show(l, shownBitmap);
+ return;
+ }
+ shownImage = l.image;
+ shownBitmap = null;
+ preview.show(l, null);
+ if (l.image.isEmpty()) return;
+ String name = l.image;
+ int w = previewW, h = previewH;
+ new Thread(() -> {
+ Bitmap b = Images.load(this, name, w * 2, h * 2);
+ main.post(() -> {
+ if (name.equals(shownImage)) {
+ shownBitmap = b;
+ preview.show(Prefs.load(this), b);
+ }
+ });
+ }, "preview-image").start();
+ }
+
+ private interface Change {
+ void apply(Look l);
+ }
+
+ private void change(Change c) {
+ Look l = Prefs.load(this);
+ c.apply(l);
+ Prefs.save(this, l);
+ build(page.focused());
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ Uri uri = data == null ? null : data.getData();
+ if (requestCode != PICK || resultCode != RESULT_OK || uri == null) return;
+ String name = Images.copyIn(this, uri);
+ if (name == null) {
+ page.subtitle.setText("That file isn't a PNG, JPEG or WebP picture under 15 MB.");
+ return;
+ }
+ change(x -> x.image = name);
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Images.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Images.java
new file mode 100644
index 000000000..2b92d5a8d
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Images.java
@@ -0,0 +1,137 @@
+package io.github.maxhayim.startupbranding;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.provider.OpenableColumns;
+import android.database.Cursor;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * The pictures: PNG, JPEG or WebP files in the app's own folder on the TV, put there from a computer
+ * ({@code push-image.sh}) or copied in from the TV's file picker where it has a real one. No storage permission:
+ * the folder is the app's own.
+ */
+final class Images {
+ static final long MAX_BYTES = 15L * 1024 * 1024;
+ /** Bigger pictures are refused rather than decoded: 8192 px a side is beyond any TV. */
+ static final int MAX_SIDE = 8192;
+
+ private Images() {
+ }
+
+ /** /sdcard/Android/data/io.github.maxhayim.startupbranding/files/pictures, which ADB can write to. */
+ static File dir(Context c) {
+ File d = new File(c.getExternalFilesDir(null), "pictures");
+ if (!d.isDirectory()) d.mkdirs();
+ return d;
+ }
+
+ /** Usable pictures by name. */
+ static List<String> list(Context c) {
+ List<String> out = new ArrayList<>();
+ File[] files = dir(c).listFiles();
+ if (files == null) return out;
+ Arrays.sort(files, (a, b) -> a.getName().compareToIgnoreCase(b.getName()));
+ for (File f : files) if (f.isFile() && !Look.fileName(f.getName()).isEmpty() && usable(f)) out.add(f.getName());
+ return out;
+ }
+
+ static boolean usable(File f) {
+ if (f.length() <= 0 || f.length() > MAX_BYTES) return false;
+ byte[] head = new byte[12];
+ try (InputStream in = new FileInputStream(f)) {
+ int n = in.read(head);
+ if (n < 12 || Fit.kind(head) == null) return false;
+ } catch (IOException e) {
+ return false;
+ }
+ BitmapFactory.Options o = new BitmapFactory.Options();
+ o.inJustDecodeBounds = true;
+ BitmapFactory.decodeFile(f.getPath(), o);
+ return o.outWidth > 0 && o.outHeight > 0 && o.outWidth <= MAX_SIDE && o.outHeight <= MAX_SIDE;
+ }
+
+ /** The picture decoded no bigger than {@code maxW} by {@code maxH} needs, or null. */
+ static Bitmap load(Context c, String name, int maxW, int maxH) {
+ if (Look.fileName(name).isEmpty()) return null;
+ File f = new File(dir(c), name);
+ if (!f.isFile() || !usable(f)) return null;
+ BitmapFactory.Options o = new BitmapFactory.Options();
+ o.inJustDecodeBounds = true;
+ BitmapFactory.decodeFile(f.getPath(), o);
+ BitmapFactory.Options d = new BitmapFactory.Options();
+ d.inSampleSize = Fit.sampleSize(o.outWidth, o.outHeight, Math.max(1, maxW), Math.max(1, maxH));
+ try {
+ return BitmapFactory.decodeFile(f.getPath(), d);
+ } catch (OutOfMemoryError e) {
+ return null;
+ }
+ }
+
+ static boolean deleteAll(Context c) {
+ boolean ok = true;
+ File[] files = dir(c).listFiles();
+ if (files != null) for (File f : files) if (f.isFile()) ok &= f.delete();
+ return ok;
+ }
+
+ /** The picker intent, when this TV has a real app for it (Android TV often has only a stub that does nothing). */
+ static Intent picker(Context c) {
+ for (Intent i : new Intent[]{
+ new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("image/*"),
+ new Intent(Intent.ACTION_GET_CONTENT).addCategory(Intent.CATEGORY_OPENABLE).setType("image/*")}) {
+ List<ResolveInfo> found = c.getPackageManager().queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);
+ for (ResolveInfo r : found) {
+ if (!r.activityInfo.packageName.equals("com.android.tv.frameworkpackagestubs")) return i;
+ }
+ }
+ return null;
+ }
+
+ /** Copies a picked picture into the folder; its file name, or null if it isn't a usable picture. */
+ static String copyIn(Context c, Uri uri) {
+ String name = "picked-" + System.currentTimeMillis();
+ try (Cursor q = c.getContentResolver().query(uri, new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null)) {
+ if (q != null && q.moveToFirst()) {
+ String shown = q.getString(0);
+ if (shown != null) name = shown.replaceAll("[^A-Za-z0-9._-]", "_");
+ }
+ } catch (RuntimeException ignored) {
+ // A provider without names: the made-up one will do.
+ }
+ if (Look.fileName(name).isEmpty()) name = "picked-" + System.currentTimeMillis();
+ File out = new File(dir(c), name);
+ long total = 0;
+ try (InputStream in = c.getContentResolver().openInputStream(uri); OutputStream o = new FileOutputStream(out)) {
+ if (in == null) return null;
+ byte[] buf = new byte[64 * 1024];
+ for (int n; (n = in.read(buf)) > 0; ) {
+ total += n;
+ if (total > MAX_BYTES) throw new IOException("too big");
+ o.write(buf, 0, n);
+ }
+ } catch (IOException | SecurityException e) {
+ out.delete();
+ return null;
+ }
+ if (!usable(out)) {
+ out.delete();
+ return null;
+ }
+ return name;
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Look.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Look.java
new file mode 100644
index 000000000..5faaff684
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Look.java
@@ -0,0 +1,133 @@
+package io.github.maxhayim.startupbranding;
+
+/**
+ * What the welcome screen looks like: the settings the owner chose, with their defaults and limits. Plain Java, so
+ * the rules are tested on the computer; {@link Store} is where they are kept.
+ */
+final class Look {
+ /** Off: nothing opens. Custom: background, picture and text. Black: a plain black screen. */
+ enum Mode { OFF, CUSTOM, BLACK }
+
+ /** How the picture fills the 16:9 frame. */
+ enum Scale { FIT, FILL, STRETCH, ORIGINAL }
+
+ /** Where the picture sits when it doesn't fill the frame. */
+ enum Align { CENTER, TOP, BOTTOM, LEFT, RIGHT }
+
+ /** Where the welcome text sits. */
+ enum Place { BOTTOM, CENTER, TOP }
+
+ interface Store {
+ String get(String key);
+
+ void put(String key, String value);
+ }
+
+ static final int MAX_TEXT = 60;
+ static final int MAX_NICKNAME = 32;
+ /** Seconds the screen stays up; 0 is until Back or OK. */
+ static final int[] DURATIONS = {3, 5, 10, 15, 30, 0};
+ static final String[] COLOR_NAMES = {"Black", "Charcoal", "Midnight", "Forest", "Wine", "White"};
+ static final int[] COLORS = {0xFF000000, 0xFF1C1C1E, 0xFF0B1A33, 0xFF0E2A1F, 0xFF2A0E16, 0xFFFFFFFF};
+
+ Mode mode = Mode.CUSTOM;
+ /** A file name in the app's pictures folder, or "" for none. */
+ String image = "";
+ Scale scale = Scale.FIT;
+ Align align = Align.CENTER;
+ String text = "Welcome";
+ Place place = Place.BOTTOM;
+ int color = 0;
+ int seconds = 5;
+ String nickname = "";
+
+ static Look load(Store s) {
+ Look l = new Look();
+ l.mode = pick(Mode.values(), s.get("mode"), l.mode);
+ l.image = fileName(s.get("image"));
+ l.scale = pick(Scale.values(), s.get("scale"), l.scale);
+ l.align = pick(Align.values(), s.get("align"), l.align);
+ String t = s.get("text");
+ if (t != null) l.text = clean(t, MAX_TEXT);
+ l.place = pick(Place.values(), s.get("place"), l.place);
+ l.color = index(s.get("color"), COLORS.length, l.color);
+ int sec = number(s.get("seconds"), l.seconds);
+ for (int d : DURATIONS) if (d == sec) l.seconds = sec;
+ String n = s.get("nickname");
+ if (n != null) l.nickname = clean(n, MAX_NICKNAME);
+ return l;
+ }
+
+ void save(Store s) {
+ s.put("mode", mode.name());
+ s.put("image", image);
+ s.put("scale", scale.name());
+ s.put("align", align.name());
+ s.put("text", text);
+ s.put("place", place.name());
+ s.put("color", Integer.toString(color));
+ s.put("seconds", Integer.toString(seconds));
+ s.put("nickname", nickname);
+ }
+
+ int background() {
+ return COLORS[color];
+ }
+
+ /** White text on dark backgrounds, near-black on light ones. */
+ int textColor() {
+ int c = background();
+ double lum = 0.2126 * ((c >> 16) & 0xFF) + 0.7152 * ((c >> 8) & 0xFF) + 0.0722 * (c & 0xFF);
+ return lum > 140 ? 0xFF111111 : 0xFFFFFFFF;
+ }
+
+ static int nextDuration(int seconds) {
+ for (int i = 0; i < DURATIONS.length; i++) if (DURATIONS[i] == seconds) return DURATIONS[(i + 1) % DURATIONS.length];
+ return DURATIONS[0];
+ }
+
+ static String durationName(int seconds) {
+ return seconds == 0 ? "Until Back or OK" : seconds + " s";
+ }
+
+ static <E extends Enum<E>> E next(E[] all, E e) {
+ return all[(e.ordinal() + 1) % all.length];
+ }
+
+ /** One line of printable text, trimmed and cut to {@code max} characters (never inside a surrogate pair). */
+ static String clean(String s, int max) {
+ if (s == null) return "";
+ StringBuilder b = new StringBuilder();
+ s.codePoints().forEach(cp -> {
+ if (cp == '\n' || cp == '\r' || cp == '\t') b.append(' ');
+ else if (!Character.isISOControl(cp) && Character.getType(cp) != Character.FORMAT) b.appendCodePoint(cp);
+ });
+ String t = b.toString().trim().replaceAll(" {2,}", " ");
+ if (t.codePointCount(0, t.length()) <= max) return t;
+ return t.substring(0, t.offsetByCodePoints(0, max)).trim();
+ }
+
+ /** A bare file name (no folders, no hidden files), or "" when it isn't one. */
+ static String fileName(String s) {
+ if (s == null || s.isEmpty() || s.startsWith(".") || s.contains("/") || s.contains("\\") || s.length() > 100) return "";
+ return s;
+ }
+
+ private static <E extends Enum<E>> E pick(E[] all, String name, E fallback) {
+ if (name != null) for (E e : all) if (e.name().equals(name)) return e;
+ return fallback;
+ }
+
+ private static int number(String s, int fallback) {
+ try {
+ return s == null ? fallback : Integer.parseInt(s);
+ } catch (NumberFormatException e) {
+ return fallback;
+ }
+ }
+
+ private static int index(String s, int size, int fallback) {
+ int i = number(s, fallback);
+ return i >= 0 && i < size ? i : fallback;
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/MainActivity.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/MainActivity.java
new file mode 100644
index 000000000..ee572c729
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/MainActivity.java
@@ -0,0 +1,100 @@
+package io.github.maxhayim.startupbranding;
+
+import android.app.Activity;
+import android.content.ActivityNotFoundException;
+import android.content.Intent;
+import android.os.Bundle;
+import android.provider.Settings;
+
+/**
+ * The tile and the card open this: every setting of the welcome screen, one row each. The picture, the
+ * compatibility list and the reset have their own screens.
+ */
+public class MainActivity extends Activity {
+ private Page page;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ page = new Page(this, getString(R.string.app_name), false);
+ page.subtitle.setText("Your own welcome screen. It never changes the maker's boot logo; see Compatibility.");
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ build(page.focused());
+ }
+
+ private void build(int focus) {
+ page.rows.removeAllViews();
+ Look l = Prefs.load(this);
+
+ page.add("Welcome Screen", "Custom: your picture, colour and text. Black: a plain black screen. Off: nothing.",
+ () -> change(x -> x.mode = Look.next(Look.Mode.values(), x.mode)))
+ .setValue(cap(l.mode.name()));
+ page.add("Preview", "Full screen, as it will look. Back or OK closes it.",
+ () -> startActivity(new Intent(this, WelcomeActivity.class).putExtra(WelcomeActivity.EXTRA_PREVIEW, true)));
+
+ page.heading("Look");
+ page.add("Custom Image", "A picture from this TV's file picker or from a computer, scaled and placed.",
+ () -> startActivity(new Intent(this, ImageActivity.class)))
+ .setValue(l.image.isEmpty() ? "None" : l.image);
+ page.add("Welcome Text", "A line of your own, up to " + Look.MAX_TEXT + " characters.",
+ () -> page.ask("Welcome text", l.text, Look.MAX_TEXT, s -> change(x -> x.text = Look.clean(s, Look.MAX_TEXT))))
+ .setValue(l.text.isEmpty() ? "None" : l.text);
+ page.add("Text Position", "Where the text sits on the screen.",
+ () -> change(x -> x.place = Look.next(Look.Place.values(), x.place)))
+ .setValue(cap(l.place.name()));
+ page.add("Background Color", "Behind the picture, or the whole screen without one.",
+ () -> change(x -> x.color = (x.color + 1) % Look.COLORS.length))
+ .setValue(Look.COLOR_NAMES[l.color]);
+ page.add("Display Duration", "How long it stays up, unless Back or OK closes it sooner.",
+ () -> change(x -> x.seconds = Look.nextDuration(x.seconds)))
+ .setValue(Look.durationName(l.seconds));
+
+ page.heading("Names");
+ String system = Settings.Global.getString(getContentResolver(), Settings.Global.DEVICE_NAME);
+ page.add("Device Name", "The TV's real name, as phones and casting see it. OK opens the TV's own setting.",
+ this::openDeviceName)
+ .setValue(system == null ? "Unknown" : system);
+ page.add("Nickname", "Shown under the welcome text, in this module only. It doesn't rename the TV.",
+ () -> page.ask("Nickname (this module only)", l.nickname, Look.MAX_NICKNAME,
+ s -> change(x -> x.nickname = Look.clean(s, Look.MAX_NICKNAME))))
+ .setValue(l.nickname.isEmpty() ? "None" : l.nickname);
+
+ page.heading("More");
+ page.add("Compatibility", "What works on this TV without root, and what doesn't.",
+ () -> startActivity(new Intent(this, CompatActivity.class)));
+ page.add("Restore Defaults", "Turn the welcome screen off, or clear every custom setting.",
+ () -> startActivity(new Intent(this, ResetActivity.class)));
+ page.focus(focus);
+ }
+
+ private interface Change {
+ void apply(Look l);
+ }
+
+ private void change(Change c) {
+ Look l = Prefs.load(this);
+ c.apply(l);
+ Prefs.save(this, l);
+ build(page.focused());
+ }
+
+ private void openDeviceName() {
+ for (Intent i : DeviceInfo.nameSettings()) {
+ try {
+ startActivity(i);
+ return;
+ } catch (ActivityNotFoundException | SecurityException ignored) {
+ // The next, more general screen.
+ }
+ }
+ page.subtitle.setText("This TV has no settings screen for its name.");
+ }
+
+ static String cap(String s) {
+ return s.charAt(0) + s.substring(1).toLowerCase(java.util.Locale.ROOT);
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Page.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Page.java
new file mode 100644
index 000000000..c6d19631d
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Page.java
@@ -0,0 +1,120 @@
+package io.github.maxhayim.startupbranding;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.text.InputFilter;
+import android.text.InputType;
+import android.view.ViewGroup;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+/**
+ * The layout every screen shares: black, a title and a line under it, then rows worked with the D-pad. {@link #rows}
+ * scrolls; a screen with a side panel (the picture screen) adds it to {@link #side}.
+ */
+final class Page {
+ final LinearLayout root, rows, side;
+ final TextView title, subtitle;
+ private final Activity a;
+
+ Page(Activity a, String titleText, boolean withSide) {
+ this.a = a;
+ root = new LinearLayout(a);
+ root.setOrientation(LinearLayout.HORIZONTAL);
+ root.setBackgroundColor(0xFF000000);
+ root.setPadding(px(56), px(36), px(56), px(28));
+
+ LinearLayout main = new LinearLayout(a);
+ main.setOrientation(LinearLayout.VERTICAL);
+ title = new TextView(a);
+ title.setText(titleText);
+ title.setTextSize(28);
+ title.setTextColor(0xFFFFFFFF);
+ main.addView(title);
+ subtitle = new TextView(a);
+ subtitle.setTextSize(15);
+ subtitle.setTextColor(0xFF8B949E);
+ subtitle.setPadding(0, px(4), 0, px(16));
+ main.addView(subtitle);
+ ScrollView scroll = new ScrollView(a);
+ scroll.setVerticalScrollBarEnabled(false);
+ rows = new LinearLayout(a);
+ rows.setOrientation(LinearLayout.VERTICAL);
+ scroll.addView(rows);
+ main.addView(scroll, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
+ root.addView(main, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f));
+
+ side = new LinearLayout(a);
+ side.setOrientation(LinearLayout.VERTICAL);
+ side.setPadding(px(36), px(56), 0, 0);
+ if (withSide) root.addView(side, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.1f));
+ a.setContentView(root);
+ }
+
+ Row add(String name, String detail, Runnable onClick) {
+ Row r = new Row(a, name, detail, onClick);
+ rows.addView(r, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ return r;
+ }
+
+ /** A small heading between groups of rows. */
+ void heading(String s) {
+ TextView t = new TextView(a);
+ t.setText(s);
+ t.setTextSize(14);
+ t.setTextColor(0xFFF2B84B);
+ t.setPadding(px(16), px(14), 0, px(4));
+ rows.addView(t);
+ }
+
+ /** Keeps focus on the row it was on (by index) after the rows are rebuilt, else the first. */
+ void focus(int index) {
+ int i = 0, n = 0;
+ for (int k = 0; k < rows.getChildCount(); k++) {
+ if (!rows.getChildAt(k).isFocusable()) continue;
+ if (n == index || n == 0) i = k;
+ if (n == index) break;
+ n++;
+ }
+ if (rows.getChildCount() > 0) rows.getChildAt(i).requestFocus();
+ }
+
+ /** The index among focusable rows of the one with focus, or 0. */
+ int focused() {
+ int n = 0;
+ for (int k = 0; k < rows.getChildCount(); k++) {
+ if (!rows.getChildAt(k).isFocusable()) continue;
+ if (rows.getChildAt(k).hasFocus()) return n;
+ n++;
+ }
+ return 0;
+ }
+
+ interface Typed {
+ void typed(String s);
+ }
+
+ /** One line of text, typed with the TV's keyboard. Clear empties it. */
+ void ask(String titleText, String current, int max, Typed done) {
+ EditText field = new EditText(a);
+ field.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
+ field.setSingleLine(true);
+ field.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max)});
+ field.setText(current);
+ field.setSelection(field.getText().length());
+ new AlertDialog.Builder(a, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle(titleText)
+ .setView(field)
+ .setPositiveButton("OK", (d, w) -> done.typed(field.getText().toString()))
+ .setNeutralButton("Clear", (d, w) -> done.typed(""))
+ .setNegativeButton("Cancel", null)
+ .show();
+ field.requestFocus();
+ }
+
+ int px(int dp) {
+ return Math.round(dp * a.getResources().getDisplayMetrics().density);
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/PicturesProvider.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/PicturesProvider.java
new file mode 100644
index 000000000..3b56d918c
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/PicturesProvider.java
@@ -0,0 +1,56 @@
+package io.github.maxhayim.startupbranding;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.ParcelFileDescriptor;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.List;
+
+/**
+ * Lets push-image.sh write pictures into the app's own folder, so the app owns them (a file the shell copies into
+ * Android/data can belong to the shell, and the app then can't read it). Write and delete only, picture names only,
+ * and only for callers holding WRITE_SECURE_SETTINGS: the adb shell has it, ordinary apps don't.
+ *
+ * content write --uri content://io.github.maxhayim.startupbranding.pictures/logo.png < /data/local/tmp/logo.png
+ * content delete --uri content://io.github.maxhayim.startupbranding.pictures/logo.png
+ */
+public class PicturesProvider extends ContentProvider {
+ /** A picture's file name: a bare name with a picture extension. */
+ static boolean pictureName(String name) {
+ if (Look.fileName(name).isEmpty() || !name.matches("[A-Za-z0-9._-]+")) return false;
+ String n = name.toLowerCase(java.util.Locale.ROOT);
+ return n.endsWith(".png") || n.endsWith(".jpg") || n.endsWith(".jpeg") || n.endsWith(".webp");
+ }
+
+ private File file(Uri uri) throws FileNotFoundException {
+ List<String> seg = uri.getPathSegments();
+ if (getContext() == null || seg.size() != 1 || !pictureName(seg.get(0))) throw new FileNotFoundException(String.valueOf(uri));
+ return new File(Images.dir(getContext()), seg.get(0));
+ }
+
+ @Override
+ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
+ if (!mode.contains("w")) throw new FileNotFoundException("write only");
+ return ParcelFileDescriptor.open(file(uri), ParcelFileDescriptor.MODE_WRITE_ONLY
+ | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
+ }
+
+ @Override
+ public int delete(Uri uri, String selection, String[] selectionArgs) {
+ try {
+ return file(uri).delete() ? 1 : 0;
+ } catch (FileNotFoundException e) {
+ return 0;
+ }
+ }
+
+ @Override public boolean onCreate() { return true; }
+ @Override public String getType(Uri uri) { return null; }
+ @Override public Cursor query(Uri uri, String[] p, String s, String[] a, String o) { return null; }
+ @Override public Uri insert(Uri uri, ContentValues values) { return null; }
+ @Override public int update(Uri uri, ContentValues v, String s, String[] a) { return 0; }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Prefs.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Prefs.java
new file mode 100644
index 000000000..bbd779aa4
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Prefs.java
@@ -0,0 +1,38 @@
+package io.github.maxhayim.startupbranding;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+
+/** The welcome screen's settings, kept in the app's private preferences. */
+final class Prefs {
+ private Prefs() {
+ }
+
+ private static Look.Store store(Context c) {
+ SharedPreferences p = c.getApplicationContext().getSharedPreferences("look", Context.MODE_PRIVATE);
+ return new Look.Store() {
+ @Override
+ public String get(String key) {
+ return p.getString(key, null);
+ }
+
+ @Override
+ public void put(String key, String value) {
+ p.edit().putString(key, value).apply();
+ }
+ };
+ }
+
+ static Look load(Context c) {
+ return Look.load(store(c));
+ }
+
+ static void save(Context c, Look l) {
+ l.save(store(c));
+ }
+
+ /** Back to the defaults: everything the owner set is forgotten (pictures stay unless deleted). */
+ static void clear(Context c) {
+ c.getApplicationContext().getSharedPreferences("look", Context.MODE_PRIVATE).edit().clear().apply();
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/ResetActivity.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/ResetActivity.java
new file mode 100644
index 000000000..ebadfbc97
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/ResetActivity.java
@@ -0,0 +1,80 @@
+package io.github.maxhayim.startupbranding;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+
+/**
+ * Undo: turn the welcome screen off, put every setting back to its default, or delete the pictures. The last
+ * two take OK twice, so one stray press doesn't undo an evening's work.
+ */
+public class ResetActivity extends Activity {
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private Page page;
+ /** The row waiting for its second OK, or -1. */
+ private int armed = -1;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ page = new Page(this, "Restore Defaults", false);
+ page.subtitle.setText("Nothing here touches the TV's own settings: only this module's.");
+ build(0);
+ }
+
+ @Override
+ protected void onPause() {
+ main.removeCallbacksAndMessages(null);
+ armed = -1;
+ super.onPause();
+ }
+
+ private void build(int focus) {
+ page.rows.removeAllViews();
+ Look l = Prefs.load(this);
+ int pictures = Images.list(this).size();
+ page.add("Turn Off the Welcome Screen", "Keeps your picture and text for later.", () -> {
+ Look x = Prefs.load(this);
+ x.mode = Look.Mode.OFF;
+ Prefs.save(this, x);
+ done("The welcome screen is off.", 0);
+ }).setValue(l.mode == Look.Mode.OFF ? "Off" : "");
+ page.add("Restore Defaults", "Every setting back as it was installed: text, colour, time, scaling, nickname.",
+ () -> twice(1, () -> {
+ Prefs.clear(this);
+ done("Settings are back to their defaults.", 1);
+ })).setValue(armed == 1 ? "OK again" : "");
+ page.add("Delete Pictures", pictures == 0 ? "No pictures on the TV." : "Removes the " + pictures
+ + (pictures == 1 ? " picture" : " pictures") + " in this module's folder.",
+ pictures == 0 ? null : () -> twice(2, () -> {
+ boolean ok = Images.deleteAll(this);
+ Look x = Prefs.load(this);
+ x.image = "";
+ Prefs.save(this, x);
+ done(ok ? "Pictures deleted." : "Some pictures couldn't be deleted.", 2);
+ })).setValue(armed == 2 ? "OK again" : "");
+ page.focus(focus);
+ }
+
+ private void twice(int row, Runnable action) {
+ if (armed != row) {
+ armed = row;
+ build(row);
+ main.removeCallbacksAndMessages(null);
+ main.postDelayed(() -> {
+ armed = -1;
+ build(page.focused());
+ }, 5000);
+ return;
+ }
+ armed = -1;
+ main.removeCallbacksAndMessages(null);
+ action.run();
+ }
+
+ private void done(String message, int focus) {
+ page.subtitle.setText(message);
+ build(focus);
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Row.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Row.java
new file mode 100644
index 000000000..f0c66505b
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/Row.java
@@ -0,0 +1,58 @@
+package io.github.maxhayim.startupbranding;
+
+import android.content.Context;
+import android.view.Gravity;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+/**
+ * One settings row: a name with a line saying what it does on the left, its value on the right; OK runs it.
+ */
+final class Row extends LinearLayout {
+ private final TextView value;
+ private final TextView desc;
+
+ Row(Context context, String name, String description, Runnable onClick) {
+ super(context);
+ float dp = context.getResources().getDisplayMetrics().density;
+ setOrientation(HORIZONTAL);
+ setGravity(Gravity.CENTER_VERTICAL);
+ int ph = Math.round(16 * dp), pv = Math.round(10 * dp);
+ setPadding(ph, pv, ph, pv);
+ setBackgroundResource(R.drawable.row_background);
+ setFocusable(onClick != null);
+ setClickable(onClick != null);
+ if (onClick != null) setOnClickListener(v -> onClick.run());
+
+ LinearLayout text = new LinearLayout(context);
+ text.setOrientation(VERTICAL);
+ TextView label = new TextView(context);
+ label.setText(name);
+ label.setTextSize(17);
+ label.setTextColor(0xFFFFFFFF);
+ text.addView(label);
+ desc = new TextView(context);
+ desc.setTextSize(12);
+ desc.setTextColor(0xFF8B949E);
+ desc.setPadding(0, Math.round(2 * dp), Math.round(16 * dp), 0);
+ text.addView(desc);
+ setDetail(description);
+ addView(text, new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f));
+
+ value = new TextView(context);
+ value.setTextSize(17);
+ value.setTextColor(0xFFC9D1D9);
+ value.setGravity(Gravity.END);
+ value.setMinWidth(Math.round(90 * dp));
+ addView(value, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+ }
+
+ void setDetail(String d) {
+ desc.setText(d == null ? "" : d);
+ desc.setVisibility(d == null || d.isEmpty() ? GONE : VISIBLE);
+ }
+
+ void setValue(String v) {
+ value.setText(v);
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/WelcomeActivity.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/WelcomeActivity.java
new file mode 100644
index 000000000..ee569e425
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/WelcomeActivity.java
@@ -0,0 +1,91 @@
+package io.github.maxhayim.startupbranding;
+
+import android.app.Activity;
+import android.graphics.Bitmap;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.DisplayMetrics;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.WindowInsets;
+import android.view.WindowInsetsController;
+import android.view.WindowManager;
+
+/**
+ * The welcome screen, full screen with nothing else on it. Back or OK closes it, or it closes by itself after the
+ * chosen time. Opened by Preview, and by others through the exported {@code .Welcome} alias (a remote button mapped
+ * in the launcher, or a launcher hook after boot): then it shows only while the welcome screen is on.
+ */
+public class WelcomeActivity extends Activity {
+ static final String EXTRA_PREVIEW = "preview";
+
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private WelcomeView view;
+ private volatile boolean gone;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ Look look = Prefs.load(this);
+ // Only this app's own Preview may show it while it's off; through the .Welcome alias, the setting decides.
+ boolean outside = getIntent().getComponent() != null && getIntent().getComponent().getClassName().endsWith(".Welcome");
+ boolean preview = !outside && getIntent().getBooleanExtra(EXTRA_PREVIEW, false);
+ if (look.mode == Look.Mode.OFF && !preview) {
+ finish();
+ return;
+ }
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ view = new WelcomeView(this);
+ view.show(look, null);
+ setContentView(view);
+ hideBars();
+ if (look.mode == Look.Mode.CUSTOM && !look.image.isEmpty()) {
+ DisplayMetrics m = getResources().getDisplayMetrics();
+ int w = m.widthPixels, h = m.heightPixels;
+ // Decoded off the main thread; the colour and text show at once, the picture when it's ready.
+ new Thread(() -> {
+ Bitmap b = Images.load(this, look.image, w, h);
+ main.post(() -> {
+ if (!gone && b != null) view.show(look, b);
+ });
+ }, "welcome-image").start();
+ }
+ if (look.seconds > 0) main.postDelayed(this::finish, look.seconds * 1000L);
+ }
+
+ private void hideBars() {
+ if (android.os.Build.VERSION.SDK_INT >= 30) {
+ WindowInsetsController c = getWindow().getInsetsController();
+ if (c != null) {
+ c.hide(WindowInsets.Type.systemBars());
+ c.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
+ }
+ } else {
+ getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
+ }
+ }
+
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ switch (keyCode) {
+ case KeyEvent.KEYCODE_DPAD_CENTER:
+ case KeyEvent.KEYCODE_ENTER:
+ case KeyEvent.KEYCODE_NUMPAD_ENTER:
+ case KeyEvent.KEYCODE_BUTTON_A:
+ finish();
+ return true;
+ default:
+ // Back closes it the usual way; other keys are ignored so a stray press doesn't skip it.
+ return super.onKeyDown(keyCode, event);
+ }
+ }
+
+ @Override
+ protected void onDestroy() {
+ gone = true;
+ main.removeCallbacksAndMessages(null);
+ super.onDestroy();
+ }
+}
diff --git a/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/WelcomeView.java b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/WelcomeView.java
new file mode 100644
index 000000000..9b914994a
--- /dev/null
+++ b/addons/startup-branding/app/src/main/java/io/github/maxhayim/startupbranding/WelcomeView.java
@@ -0,0 +1,82 @@
+package io.github.maxhayim.startupbranding;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.Typeface;
+import android.text.TextPaint;
+import android.text.TextUtils;
+import android.view.View;
+
+/**
+ * Draws the welcome screen at any size: full screen, or small as the live preview. A 16:9 frame holds the
+ * background, the picture and the text; on other screen shapes the bars around it are black.
+ */
+final class WelcomeView extends View {
+ private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
+ private final TextPaint text = new TextPaint(Paint.ANTI_ALIAS_FLAG);
+ private final Rect dest = new Rect();
+ private Look look = new Look();
+ private Bitmap bitmap;
+
+ WelcomeView(Context c) {
+ super(c);
+ text.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
+ text.setTextAlign(Paint.Align.CENTER);
+ }
+
+ void show(Look l, Bitmap b) {
+ look = l;
+ bitmap = b;
+ invalidate();
+ }
+
+ @Override
+ protected void onDraw(Canvas c) {
+ c.drawColor(0xFF000000);
+ int[] f = Fit.frame(getWidth(), getHeight());
+ if (look.mode == Look.Mode.BLACK) return;
+ paint.setColor(look.background());
+ c.drawRect(f[0], f[1], f[2], f[3], paint);
+ if (look.mode == Look.Mode.OFF) return;
+ int fw = f[2] - f[0], fh = f[3] - f[1];
+ c.save();
+ c.clipRect(f[0], f[1], f[2], f[3]);
+ if (bitmap != null) {
+ // Original size is relative to a 1080p screen, so the preview pane shows it to scale.
+ float density = fh / 1080f;
+ int[] r = Fit.image(bitmap.getWidth(), bitmap.getHeight(), f, look.scale, look.align, density);
+ dest.set(r[0], r[1], r[2], r[3]);
+ c.drawBitmap(bitmap, null, dest, paint);
+ }
+ String line1 = look.text, line2 = look.nickname;
+ if (!line1.isEmpty() || !line2.isEmpty()) {
+ float big = fh * 0.075f, small = fh * 0.04f;
+ float block = (line1.isEmpty() ? 0 : big * 1.2f) + (line2.isEmpty() ? 0 : small * 1.4f);
+ float top;
+ switch (look.place) {
+ case TOP: top = f[1] + fh * 0.1f; break;
+ case CENTER: top = f[1] + (fh - block) / 2f; break;
+ default: top = f[3] - fh * 0.1f - block;
+ }
+ text.setColor(look.textColor());
+ // A soft shadow keeps the words readable over a busy picture.
+ text.setShadowLayer(fh * 0.01f, 0, fh * 0.003f, look.textColor() == 0xFFFFFFFF ? 0x99000000 : 0x66FFFFFF);
+ float y = top;
+ if (!line1.isEmpty()) {
+ text.setTextSize(big);
+ y += big;
+ c.drawText(TextUtils.ellipsize(line1, text, fw * 0.9f, TextUtils.TruncateAt.END).toString(), f[0] + fw / 2f, y, text);
+ y += big * 0.2f;
+ }
+ if (!line2.isEmpty()) {
+ text.setTextSize(small);
+ y += small * 1.2f;
+ c.drawText(TextUtils.ellipsize(line2, text, fw * 0.9f, TextUtils.TruncateAt.END).toString(), f[0] + fw / 2f, y, text);
+ }
+ }
+ c.restore();
+ }
+}
diff --git a/addons/startup-branding/app/src/main/res/drawable/banner.xml b/addons/startup-branding/app/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..db05174a5
--- /dev/null
+++ b/addons/startup-branding/app/src/main/res/drawable/banner.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 16:9 banner: the rising sun on a screen, beside a title bar. Own art. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="320dp" android:height="180dp"
+ android:viewportWidth="320" android:viewportHeight="180">
+ <path android:fillColor="#000000" android:pathData="M0,0h320v180h-320z" />
+ <path android:strokeColor="#FFFFFF" android:strokeWidth="4" android:fillColor="#00000000"
+ android:pathData="M48,54h76a6,6 0,0 1,6 6v60a6,6 0,0 1,-6 6h-76a6,6 0,0 1,-6 -6v-60a6,6 0,0 1,6 -6z" />
+ <path android:fillColor="#F2B84B" android:pathData="M66,108a20,20 0,0 1,40 0z" />
+ <path android:fillColor="#FFFFFF" android:pathData="M52,108h68v3h-68z" />
+ <path android:fillColor="#FFFFFF" android:pathData="M156,80h120v9h-120zM156,98h84v7h-84z" />
+</vector>
diff --git a/addons/startup-branding/app/src/main/res/drawable/ic_foreground.xml b/addons/startup-branding/app/src/main/res/drawable/ic_foreground.xml
new file mode 100644
index 000000000..978df7e3f
--- /dev/null
+++ b/addons/startup-branding/app/src/main/res/drawable/ic_foreground.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A screen with a rising sun on its horizon, inside the adaptive icon's safe zone. Own art. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp"
+ android:viewportWidth="108" android:viewportHeight="108">
+ <path android:strokeColor="#FFFFFF" android:strokeWidth="3" android:fillColor="#00000000"
+ android:pathData="M36,38h36a4,4 0,0 1,4 4v22a4,4 0,0 1,-4 4h-36a4,4 0,0 1,-4 -4v-22a4,4 0,0 1,4 -4z" />
+ <path android:fillColor="#F2B84B" android:pathData="M44,60a10,10 0,0 1,20 0z" />
+ <path android:fillColor="#FFFFFF" android:pathData="M38,60h32v2h-32z" />
+</vector>
diff --git a/addons/startup-branding/app/src/main/res/drawable/row_background.xml b/addons/startup-branding/app/src/main/res/drawable/row_background.xml
new file mode 100644
index 000000000..03ccab9f5
--- /dev/null
+++ b/addons/startup-branding/app/src/main/res/drawable/row_background.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A settings row: transparent until focused, then a glass highlight like the launcher's. -->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_focused="true">
+ <shape android:shape="rectangle">
+ <solid android:color="#33FFFFFF" />
+ <stroke android:width="1dp" android:color="#55FFFFFF" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+ <item>
+ <shape android:shape="rectangle">
+ <solid android:color="#00000000" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+</selector>
diff --git a/addons/startup-branding/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/addons/startup-branding/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 000000000..0a99b20b1
--- /dev/null
+++ b/addons/startup-branding/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@android:color/black" />
+ <foreground android:drawable="@drawable/ic_foreground" />
+</adaptive-icon>
diff --git a/addons/startup-branding/app/src/main/res/values/strings.xml b/addons/startup-branding/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..bbfa28319
--- /dev/null
+++ b/addons/startup-branding/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Startup &amp; Branding</string>
+</resources>
diff --git a/addons/startup-branding/app/src/main/res/xml/module_card.xml b/addons/startup-branding/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..fce5b6d8c
--- /dev/null
+++ b/addons/startup-branding/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="Startup &amp; Branding" caption="Welcome screen" accent="#F2B84B" />
diff --git a/addons/startup-branding/app/src/test/java/io/github/maxhayim/startupbranding/StartupBrandingTest.java b/addons/startup-branding/app/src/test/java/io/github/maxhayim/startupbranding/StartupBrandingTest.java
new file mode 100644
index 000000000..24f71de9a
--- /dev/null
+++ b/addons/startup-branding/app/src/test/java/io/github/maxhayim/startupbranding/StartupBrandingTest.java
@@ -0,0 +1,184 @@
+package io.github.maxhayim.startupbranding;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class StartupBrandingTest {
+ private static final class MapStore implements Look.Store {
+ final Map<String, String> m = new HashMap<>();
+
+ @Override
+ public String get(String key) {
+ return m.get(key);
+ }
+
+ @Override
+ public void put(String key, String value) {
+ m.put(key, value);
+ }
+ }
+
+ @Test
+ public void settingsRoundTripAndDefaults() {
+ MapStore s = new MapStore();
+ Look fresh = Look.load(s);
+ assertEquals(Look.Mode.CUSTOM, fresh.mode);
+ assertEquals("Welcome", fresh.text);
+ assertEquals(5, fresh.seconds);
+ Look l = new Look();
+ l.mode = Look.Mode.BLACK;
+ l.image = "logo.png";
+ l.scale = Look.Scale.FILL;
+ l.align = Look.Align.TOP;
+ l.text = "Hello";
+ l.place = Look.Place.CENTER;
+ l.color = 5;
+ l.seconds = 0;
+ l.nickname = "Den";
+ l.save(s);
+ Look back = Look.load(s);
+ assertEquals(Look.Mode.BLACK, back.mode);
+ assertEquals("logo.png", back.image);
+ assertEquals(Look.Scale.FILL, back.scale);
+ assertEquals(Look.Align.TOP, back.align);
+ assertEquals("Hello", back.text);
+ assertEquals(Look.Place.CENTER, back.place);
+ assertEquals(5, back.color);
+ assertEquals(0, back.seconds);
+ assertEquals("Den", back.nickname);
+ }
+
+ @Test
+ public void badStoredValuesFallBack() {
+ MapStore s = new MapStore();
+ s.put("mode", "LOUD");
+ s.put("image", "../../etc/passwd");
+ s.put("color", "99");
+ s.put("seconds", "7");
+ s.put("text", " two\nlines\u0000 ");
+ Look l = Look.load(s);
+ assertEquals(Look.Mode.CUSTOM, l.mode);
+ assertEquals("", l.image);
+ assertEquals(0, l.color);
+ assertEquals(5, l.seconds);
+ assertEquals("two lines", l.text);
+ }
+
+ @Test
+ public void textIsOneLineAndCutWhole() {
+ assertEquals("a b", Look.clean(" a \t\n b ", 10));
+ assertEquals("abc", Look.clean("abcdef", 3));
+ // Never half an emoji.
+ assertEquals("ab😀", Look.clean("ab😀😀", 3));
+ assertEquals("", Look.clean(null, 5));
+ assertEquals("ab", Look.clean("a​b", 5));
+ }
+
+ @Test
+ public void fileNamesStayInTheFolder() {
+ assertEquals("logo.png", Look.fileName("logo.png"));
+ assertEquals("", Look.fileName("a/b.png"));
+ assertEquals("", Look.fileName("..\\x.png"));
+ assertEquals("", Look.fileName(".hidden.png"));
+ assertTrue(PicturesProvider.pictureName("Logo_2.WEBP"));
+ assertFalse(PicturesProvider.pictureName("logo.gif"));
+ assertFalse(PicturesProvider.pictureName("my logo.png"));
+ assertFalse(PicturesProvider.pictureName("../logo.png"));
+ }
+
+ @Test
+ public void cyclesWrapAround() {
+ assertEquals(Look.Mode.OFF, Look.next(Look.Mode.values(), Look.Mode.BLACK));
+ assertEquals(Look.Mode.CUSTOM, Look.next(Look.Mode.values(), Look.Mode.OFF));
+ assertEquals(0, Look.nextDuration(30));
+ assertEquals(3, Look.nextDuration(0));
+ assertEquals(3, Look.nextDuration(42));
+ assertEquals("Until Back or OK", Look.durationName(0));
+ }
+
+ @Test
+ public void textContrastsWithTheBackground() {
+ Look l = new Look();
+ l.color = 0;
+ assertEquals(0xFFFFFFFF, l.textColor());
+ l.color = 5;
+ assertEquals(0xFF111111, l.textColor());
+ }
+
+ @Test
+ public void frameIs16by9() {
+ assertArrayEquals(new int[]{0, 0, 1920, 1080}, Fit.frame(1920, 1080));
+ assertArrayEquals(new int[]{0, 60, 1280, 780}, Fit.frame(1280, 840));
+ assertArrayEquals(new int[]{120, 0, 1800, 945}, Fit.frame(1920, 945));
+ }
+
+ @Test
+ public void picturesFitFillStretchAndKeepTheirSize() {
+ int[] f = {0, 0, 1920, 1080};
+ // A square picture.
+ assertArrayEquals(new int[]{420, 0, 1500, 1080}, Fit.image(500, 500, f, Look.Scale.FIT, Look.Align.CENTER, 1));
+ assertArrayEquals(new int[]{0, 0, 1080, 1080}, Fit.image(500, 500, f, Look.Scale.FIT, Look.Align.LEFT, 1));
+ assertArrayEquals(new int[]{840, 0, 1920, 1080}, Fit.image(500, 500, f, Look.Scale.FIT, Look.Align.RIGHT, 1));
+ assertArrayEquals(new int[]{0, -420, 1920, 1500}, Fit.image(500, 500, f, Look.Scale.FILL, Look.Align.CENTER, 1));
+ assertArrayEquals(f, Fit.image(500, 500, f, Look.Scale.STRETCH, Look.Align.TOP, 1));
+ assertArrayEquals(new int[]{710, 290, 1210, 790}, Fit.image(500, 500, f, Look.Scale.ORIGINAL, Look.Align.CENTER, 1));
+ assertArrayEquals(new int[]{710, 0, 1210, 500}, Fit.image(500, 500, f, Look.Scale.ORIGINAL, Look.Align.TOP, 1));
+ assertArrayEquals(new int[]{710, 580, 1210, 1080}, Fit.image(500, 500, f, Look.Scale.ORIGINAL, Look.Align.BOTTOM, 1));
+ // Bigger than the screen at its own size: shrunk to fit.
+ assertArrayEquals(new int[]{0, 0, 1920, 1080}, Fit.image(3840, 2160, f, Look.Scale.ORIGINAL, Look.Align.CENTER, 1));
+ // Nothing to draw.
+ assertArrayEquals(new int[]{0, 0, 0, 0}, Fit.image(0, 10, f, Look.Scale.FIT, Look.Align.CENTER, 1));
+ }
+
+ @Test
+ public void decodeOnlyAsBigAsNeeded() {
+ assertEquals(1, Fit.sampleSize(1920, 1080, 1920, 1080));
+ assertEquals(2, Fit.sampleSize(3840, 2160, 1920, 1080));
+ assertEquals(4, Fit.sampleSize(8000, 6000, 1280, 720));
+ }
+
+ @Test
+ public void picturesAreKnownByTheirBytes() {
+ assertEquals("png", Fit.kind(new byte[]{(byte) 0x89, 'P', 'N', 'G', 13, 10, 26, 10, 0, 0, 0, 0}));
+ assertEquals("jpg", Fit.kind(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, 0, 0, 0, 0, 0, 0, 0, 0}));
+ assertEquals("webp", Fit.kind("RIFF\0\0\0\0WEBPVP8 ".getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)));
+ assertNull(Fit.kind("GIF89a......".getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)));
+ assertNull(Fit.kind(null));
+ }
+
+ @Test
+ public void compatibilityNeverOverclaims() {
+ Compat.Facts f = new Compat.Facts();
+ f.sdk = 34;
+ List<Compat.Item> items = Compat.items(f);
+ Compat.Status last = Compat.Status.WORKS;
+ for (Compat.Item i : items) {
+ assertTrue("grouped by status", i.status.ordinal() >= last.ordinal());
+ last = i.status;
+ if (i.name.equals("Opening by itself after boot")) {
+ assertEquals(Compat.Status.LAUNCHER, i.status);
+ assertTrue(i.detail.contains("Android 14"));
+ }
+ if (i.name.equals("Maker's boot logo")) assertEquals(Compat.Status.NO, i.status);
+ if (i.name.equals("Boot animation")) assertEquals(Compat.Status.SYSTEM, i.status);
+ if (i.name.equals("Renaming the TV")) assertEquals(Compat.Status.SYSTEM, i.status);
+ if (i.name.equals("Pictures from the TV's file picker")) assertEquals(Compat.Status.DEPENDS, i.status);
+ }
+ f.picker = true;
+ f.nameSettings = true;
+ for (Compat.Item i : Compat.items(f)) {
+ if (i.name.equals("Renaming the TV") || i.name.startsWith("Pictures")) assertEquals(i.name, Compat.Status.WORKS, i.status);
+ }
+ assertEquals("12L", Compat.release(32));
+ assertEquals("API 40", Compat.release(40));
+ }
+}
diff --git a/addons/startup-branding/build.gradle b/addons/startup-branding/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/startup-branding/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/startup-branding/gradle.properties b/addons/startup-branding/gradle.properties
new file mode 100644
index 000000000..18825f968
--- /dev/null
+++ b/addons/startup-branding/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
diff --git a/addons/startup-branding/gradle/wrapper/gradle-wrapper.jar b/addons/startup-branding/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/startup-branding/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/startup-branding/gradle/wrapper/gradle-wrapper.properties b/addons/startup-branding/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..77f5d0ba6
--- /dev/null
+++ b/addons/startup-branding/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,8 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
+distributionSha256Sum=d725d707bfabd4dfdc958c624003b3c80accc03f7037b5122c4b1d0ef15cecab
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/addons/startup-branding/gradlew b/addons/startup-branding/gradlew
new file mode 100755
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/startup-branding/gradlew
@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/addons/startup-branding/gradlew.bat b/addons/startup-branding/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/startup-branding/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/addons/startup-branding/install.sh b/addons/startup-branding/install.sh
new file mode 100755
index 000000000..d174ba931
--- /dev/null
+++ b/addons/startup-branding/install.sh
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+# Build Startup & Branding, install it on the TV and open it. It changes nothing on the TV but its own settings:
+# no permissions, no Home change, nothing at boot.
+# TV_HOST=<tv ip> addons/startup-branding/install.sh
+# TV_HOST=<tv ip> addons/startup-branding/install.sh --uninstall # removes the app, its settings and pictures
+set -euo pipefail
+: "${TV_HOST:?set TV_HOST to the TV IP address}"
+cd "$(dirname "$0")"
+TOOLS="$(cd ../../tools && pwd)"
+PY=$TOOLS/venv/bin/python
+[ -x "$PY" ] || PY=$TOOLS/venv/Scripts/python.exe
+export MSYS_NO_PATHCONV=1
+PKG=io.github.maxhayim.startupbranding
+# Script paths stay relative: with MSYS_NO_PATHCONV, Git Bash would hand Windows Python a /c/... path.
+tv() { "$PY" -I ../../tools/tv.py "$@"; }
+if [ "${1:-}" = "--uninstall" ]; then
+ tv "pm uninstall $PKG"
+ exit 0
+fi
+[ -f local.properties ] || { [ -n "${ANDROID_HOME:-}" ] && echo "sdk.dir=$ANDROID_HOME" > local.properties; } || true
+if [ -n "${JAVA_HOME:-}" ]; then export PATH="$JAVA_HOME/bin:$PATH"; fi
+./gradlew assembleRelease -q --console=plain
+"$PY" -I ../../tools/b64push.py app/build/outputs/apk/release/app-release.apk /data/local/tmp/startup-branding.apk
+OUT=$(tv 'pm install -r /data/local/tmp/startup-branding.apk; rm -f /data/local/tmp/startup-branding.apk')
+echo "$OUT"
+case "$OUT" in *Success*) ;; *) echo "ERROR: pm install failed" >&2; exit 1 ;; esac
+tv "am start -n $PKG/.MainActivity >/dev/null; echo opened"
+echo "Installed. Startup & Branding is open on the TV; on the Clean Your TV launcher, answer Show for its card."
diff --git a/addons/startup-branding/push-image.sh b/addons/startup-branding/push-image.sh
new file mode 100755
index 000000000..dce3400ae
--- /dev/null
+++ b/addons/startup-branding/push-image.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+# Send pictures (PNG, JPEG or WebP, up to 15 MB each) to Startup & Branding on the TV, then pick one in
+# Custom Image. Install the add-on first with install.sh.
+# TV_HOST=<tv ip> addons/startup-branding/push-image.sh logo.png [more.jpg ...]
+# TV_HOST=<tv ip> addons/startup-branding/push-image.sh --delete logo.png
+set -euo pipefail
+: "${TV_HOST:?set TV_HOST to the TV IP address}"
+[ $# -ge 1 ] || { sed -n 2,5p "$0" >&2; exit 1; }
+HERE="$(pwd -W 2>/dev/null || pwd)"
+cd "$(dirname "$0")/../../tools"
+PY=venv/bin/python
+[ -x "$PY" ] || PY=venv/Scripts/python.exe
+[ -x "$PY" ] || { echo "run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt" >&2; exit 1; }
+export MSYS_NO_PATHCONV=1
+PKG=io.github.maxhayim.startupbranding
+URI=content://$PKG.pictures
+TMP=/data/local/tmp/startup-branding-picture
+tv() { "$PY" -I tv.py "$@"; }
+tv "pm path $PKG; true" | grep -q package: \
+ || { echo "Startup & Branding is not on the TV: run addons/startup-branding/install.sh first" >&2; exit 1; }
+
+if [ "$1" = "--delete" ]; then
+ shift
+ for NAME in "$@"; do
+ [[ "$NAME" =~ ^[A-Za-z0-9._-]+\.(png|jpg|jpeg|webp|PNG|JPG|JPEG|WEBP)$ ]] || { echo "not a picture name: $NAME" >&2; exit 1; }
+ tv "content delete --uri $URI/$NAME" >/dev/null && echo "deleted $NAME"
+ done
+ exit 0
+fi
+
+for F in "$@"; do
+ case "$F" in /*|?:*) ;; *) F="$HERE/$F" ;; esac
+ [ -f "$F" ] || { echo "no such file: $F" >&2; exit 1; }
+ NAME=$(basename "$F")
+ # The TV only takes plain names; anything else becomes _.
+ SAFE=$(printf '%s' "$NAME" | tr -c 'A-Za-z0-9._-' '_')
+ [[ "$SAFE" =~ \.(png|jpg|jpeg|webp|PNG|JPG|JPEG|WEBP)$ ]] || { echo "$NAME: PNG, JPEG or WebP only" >&2; exit 1; }
+ SIZE=$(wc -c < "$F" | tr -d ' ')
+ [ "$SIZE" -le 15728640 ] || { echo "$NAME is over 15 MB" >&2; exit 1; }
+ "$PY" -I b64push.py "$F" "$TMP" >/dev/null || { echo "sending $NAME failed" >&2; exit 1; }
+ tv "content write --uri $URI/$SAFE < $TMP; rm -f $TMP" >/dev/null
+ echo "sent $SAFE"
+done
+echo "Pick it on the TV: Startup & Branding, Custom Image, Picture."
diff --git a/addons/startup-branding/screenshot.jpg b/addons/startup-branding/screenshot.jpg
new file mode 100644
index 000000000..fb895aefa
Binary files /dev/null and b/addons/startup-branding/screenshot.jpg differ
diff --git a/addons/startup-branding/settings.gradle b/addons/startup-branding/settings.gradle
new file mode 100644
index 000000000..cda608c62
--- /dev/null
+++ b/addons/startup-branding/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "startup-branding"
+include ':app'