Skip to content

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

Brightness: the TV's own picture at night on Realtek TVs

מקס חיים0f7971a1f19d
diff --git a/addons/brightness/README.md b/addons/brightness/README.md
index 3c10ae110..1f8cda108 100644
--- a/addons/brightness/README.md
+++ b/addons/brightness/README.md
@@ -17,6 +17,9 @@ Opening it shows one list, worked with the remote alone:
| **Night brightness** | Its own slider, 1 % to 100 %. |
| **Warmth** | Night mode only: an amber tint that takes blue out of the picture, 0 to 100 %. |
| **Night starts**, **Night ends** | The schedule, in 15 minute steps; a night may run past midnight (21:00 to 07:00 is the default). |
+| **TV picture at night** | Realtek-based TVs only: also turns the TV's own backlight, contrast and brightness down for the night, with dynamic backlight on, and puts the day's picture back in the morning. See below. |
+| **Night backlight**, **Night contrast**, **Night TV brightness**, **Night dynamic backlight** | The TV's own picture for the night: backlight 0, contrast 15, brightness 35 and dynamic backlight on by default. Changes reach the TV at once while it is night. |
+| **Use the TV's picture now** | Takes what is set in the TV's own picture menu as the night values. |
Every change shows at once, over the settings screen too, so you see the result as you move the slider. The
settings are kept, and the layer and the schedule come back after a reboot.
@@ -28,6 +31,19 @@ dark to find the way, any of these gives the normal screen back:
- from a computer, `adb shell am broadcast -a io.github.maxhayim.brightness.OFF -n io.github.maxhayim.brightness/.OffReceiver`;
- `adb shell am force-stop io.github.maxhayim.brightness`, or uninstalling it.
+## The TV's own picture
+
+The dimming layer darkens the picture, but the panel's backlight keeps glowing behind it, and that glow is most
+of the light in a dark room. On TVs built on Realtek chips (many Google TVs from TCL, Hisense, MOKA and others)
+the TV's picture menu is made of settings slices, and Brightness drives the same controls the menu does. When
+night begins it notes the TV's current picture, sets the night one, and puts the noted one back when night ends
+or dimming is switched off. If the TV already shows the night picture when night begins (set by hand earlier),
+the day picture is the one noted the night before, or the TVs' Standard default (backlight 100, contrast 50,
+brightness 50, dynamic backlight off).
+
+The TV asks once, "Allow Brightness to show RtkSliceProvider slices?"; the app shows a row that opens the prompt.
+On other TVs these rows don't appear.
+
## How it works
This is software dimming. A full-screen window of one colour sits over everything (`TYPE_APPLICATION_OVERLAY`),
@@ -43,6 +59,9 @@ mode at the scheduled times, and it stops itself when there is nothing to draw a
| Foreground service (`FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SPECIAL_USE`) | One service holds the layer and follows the schedule. It runs only while dimming is on and there is a layer to draw or a schedule to follow. |
| Start at boot (`RECEIVE_BOOT_COMPLETED`) | To put the layer and the schedule back after a reboot or an update, if dimming was on. |
+On Realtek TVs, the system's slice permission for the TV's picture settings, asked once on the TV (see "The TV's
+own picture"). It lets the app read and change the picture menu's settings and nothing else.
+
No internet permission: nothing leaves the TV. No accounts, telemetry, ads or libraries. Settings stay in the
app's own storage (backups are off). The `OffReceiver` is open to any sender on purpose: it can only switch
dimming off.
@@ -65,9 +84,11 @@ with your own key if you hand them out; the launcher pins its Show answer to the
## Limits
-- **It darkens the picture, not the backlight.** Whites get dimmer but blacks don't get blacker, and the TV
- uses as much power as before. For a darker panel, lower the backlight in the TV's own picture settings first,
- then use this for the rest.
+- **The layer darkens the picture, not the backlight.** Whites get dimmer but blacks don't get blacker. On
+ Realtek TVs the TV picture option lowers the backlight itself; elsewhere, lower the backlight in the TV's own
+ picture settings and use the layer for the rest.
+- **The TV picture option uses the TV's settings slices, which aren't public API.** A firmware update could rename
+ them; then the rows still show but the TV no longer follows, and the TV's own menu works as always.
- **Some things are drawn above it.** Android keeps the on-screen keyboard, the volume bar, toasts and the
system's own panels above app overlays, so they show at full brightness.
- **Some screens hide it.** Since Android 12, permission prompts and the app installer can hide overlays while
@@ -88,7 +109,8 @@ with your own key if you hand them out; the launcher pins its Show answer to the
MOKA R8G (Android 14), over ADB, with its own home app: the overlay permission granted by ADB, the layer drawn
over the settings screen and over Home, the scheduled night mode taking over at 21:13 inside a 21:00 to 07:00
window (40 %, then down to 1 %, warm), each slider changing the layer at once, **Dimming** Off and the ADB
-broadcast removing the layer at once and On bringing it back, and the layer back by itself after the app was updated. Memory: about 22 MB with the layer up.
+broadcast removing the layer at once and On bringing it back, the TV picture option asking for and getting
+the slice permission and moving the TV's own backlight to 1 and back to 0 as the slider moved, and the layer back by itself after the app was updated. Memory: about 22 MB with the layer up.
The JVM tests cover the levels, the colour arithmetic, the schedule (past midnight, edges, empty windows), the
1 % floor, the fine steps and the clamping of stored values.
@@ -96,7 +118,8 @@ The JVM tests cover the levels, the colour arithmetic, the schedule (past midnig
Still to check on a TV running this repo's launcher (the test TV's home app has no module cards):
1. The card prompt and **Show card**; the card opens the app.
-2. The switch at the end and start of the night without opening the app.
+2. The switch at the end and start of the night without opening the app, the TV's day picture coming back in
+ the morning, and when dimming is switched off.
3. The layer over a streaming app playing video, Live TV and an HDMI input, with every remote key still
reaching the app below.
4. A reboot with dimming on brings the layer and the schedule back.
diff --git a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/DimService.java b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/DimService.java
index 60b0e94f3..e38b8f9e8 100644
--- a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/DimService.java
+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/DimService.java
@@ -21,11 +21,14 @@ import android.view.View;
import android.view.WindowManager;
import java.util.Calendar;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
/**
* Holds the dimming layer: one full-screen window over every app that never takes focus, keys or touches, so the
* remote keeps controlling what is on screen. Runs only while there is a layer to hold or a schedule to follow,
* and stops itself otherwise. It redraws whenever the settings change and at each start and end of the night.
+ * With the TV picture option on, it also sets the TV's own picture for the night and puts the day's back after.
*/
public class DimService extends Service {
private static final String CHANNEL = "dimming";
@@ -34,6 +37,11 @@ public class DimService extends Service {
private static final long MAX_WAIT_MS = 5 * 60_000L;
private final Handler main = new Handler(Looper.getMainLooper());
+ /** The TV picture's binder calls, one at a time and off the main thread. */
+ private final ExecutorService tvWork = Executors.newSingleThreadExecutor();
+ private TvPicture tv;
+ /** The night picture last sent to the TV, so a slider change sends only what moved. Used on tvWork only. */
+ private Dimming.Picture tvSent;
private WindowManager wm;
private View layer;
/** Kept in a field: SharedPreferences holds its listeners weakly. */
@@ -48,7 +56,10 @@ public class DimService extends Service {
/** Starts the service when the settings need it; harmless when they don't, as it stops itself at once. */
static void start(Context c) {
- if (!Dimming.needsService(Prefs.load(c), minuteNow())) return;
+ Dimming.Settings s = Prefs.load(c);
+ int minute = minuteNow();
+ boolean restoreTv = Prefs.tvAtNight(c) && !Dimming.tvNightNow(s, minute);
+ if (!Dimming.needsService(s, minute) && !restoreTv) return;
try {
c.startForegroundService(new Intent(c, DimService.class));
} catch (RuntimeException e) {
@@ -65,6 +76,7 @@ public class DimService extends Service {
public void onCreate() {
super.onCreate();
wm = getSystemService(WindowManager.class);
+ tv = new TvPicture(this);
NotificationManager nm = getSystemService(NotificationManager.class);
nm.createNotificationChannel(new NotificationChannel(CHANNEL, getString(R.string.channel_name),
NotificationManager.IMPORTANCE_MIN));
@@ -99,6 +111,7 @@ public class DimService extends Service {
Prefs.of(this).unregisterOnSharedPreferenceChangeListener(prefsListener);
unregisterReceiver(clockReceiver);
removeLayer();
+ tvWork.shutdown();
super.onDestroy();
}
@@ -115,10 +128,18 @@ public class DimService extends Service {
Dimming.Level level = Dimming.level(s, minute);
if (level.visible() && canDraw(this)) showLayer(Dimming.color(level));
else removeLayer();
- if (!Dimming.needsService(s, minute)) {
+ boolean stop = !Dimming.needsService(s, minute);
+ boolean tvNight = Dimming.tvNightNow(s, minute);
+ if (tvNight || Prefs.tvAtNight(this)) {
+ // The TV picture first, so a stop waits for the day's picture to be back.
+ tvWork.execute(() -> {
+ syncTv(s, tvNight);
+ if (stop) main.post(this::stopSelf);
+ });
+ } else if (stop) {
stopSelf();
- return;
}
+ if (stop) return;
int next = Dimming.minutesToNextChange(s, minute);
if (next > 0) {
Calendar now = Calendar.getInstance();
@@ -127,6 +148,29 @@ public class DimService extends Service {
}
}
+ /** Runs on tvWork. Night: remember the day's picture, then set the night one. Day: put the day's back. */
+ private void syncTv(Dimming.Settings s, boolean night) {
+ if (!tv.available()) return;
+ boolean atNight = Prefs.tvAtNight(this);
+ if (night && !atNight) {
+ Dimming.Picture now = tv.read();
+ if (now == null) return; // Not allowed yet: the app shows the prompt.
+ Prefs.saveTvDay(this, Dimming.dayPicture(now, s.tvNight, Prefs.tvDay(this)));
+ if (tv.write(s.tvNight, now)) {
+ tvSent = s.tvNight;
+ Prefs.setTvAtNight(this, true);
+ }
+ } else if (night && !s.tvNight.equals(tvSent)) {
+ if (tv.write(s.tvNight, tvSent != null ? tvSent : tv.read())) tvSent = s.tvNight;
+ } else if (!night && atNight) {
+ Dimming.Picture day = Prefs.tvDay(this);
+ if (tv.write(day != null ? day : Dimming.Picture.DAY, tv.read())) {
+ tvSent = null;
+ Prefs.setTvAtNight(this, false);
+ }
+ }
+ }
+
private void showLayer(int color) {
if (layer != null) {
layer.setBackgroundColor(color);
diff --git a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Dimming.java b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Dimming.java
index 306077e00..160093f27 100644
--- a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Dimming.java
+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Dimming.java
@@ -30,6 +30,9 @@ final class Dimming {
/** Minutes after midnight, local time. */
int nightStart = 21 * 60;
int nightEnd = 7 * 60;
+ /** The TV's own picture at night too (Realtek TVs): the values below, and the day's back in the morning. */
+ boolean tvPicture;
+ Picture tvNight = Picture.NIGHT;
/** Every value back in range, whatever the stored copy held. */
Settings clamped() {
@@ -39,10 +42,80 @@ final class Dimming {
nightStart = wrap(snap(nightStart, TIME_STEP));
nightEnd = wrap(snap(nightEnd, TIME_STEP));
if (night == null) night = Night.SCHEDULED;
+ tvNight = tvNight == null ? Picture.NIGHT : tvNight.clamped();
return this;
}
}
+ /** The TV's own picture settings: backlight, contrast and brightness 0 to 100, and dynamic backlight. */
+ static final class Picture {
+ /** The night default: the darkest the panel goes, with contrast and black level down and dynamic backlight on. */
+ static final Picture NIGHT = new Picture(0, 15, 35, true);
+ /** The day default when the day's own values were never seen: the TVs' Standard picture. */
+ static final Picture DAY = new Picture(100, 50, 50, false);
+
+ final int backlight;
+ final int contrast;
+ final int brightness;
+ final boolean dynamicBacklight;
+
+ Picture(int backlight, int contrast, int brightness, boolean dynamicBacklight) {
+ this.backlight = backlight;
+ this.contrast = contrast;
+ this.brightness = brightness;
+ this.dynamicBacklight = dynamicBacklight;
+ }
+
+ Picture clamped() {
+ return new Picture(clamp(backlight, 0, 100), clamp(contrast, 0, 100), clamp(brightness, 0, 100), dynamicBacklight);
+ }
+
+ int[] values() {
+ return new int[]{backlight, contrast, brightness, dynamicBacklight ? 1 : 0};
+ }
+
+ Picture withBacklight(int v) {
+ return new Picture(v, contrast, brightness, dynamicBacklight).clamped();
+ }
+
+ Picture withContrast(int v) {
+ return new Picture(backlight, v, brightness, dynamicBacklight).clamped();
+ }
+
+ Picture withBrightness(int v) {
+ return new Picture(backlight, contrast, v, dynamicBacklight).clamped();
+ }
+
+ Picture withDynamicBacklight(boolean v) {
+ return new Picture(backlight, contrast, brightness, v);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof Picture && java.util.Arrays.equals(values(), ((Picture) o).values());
+ }
+
+ @Override
+ public int hashCode() {
+ return java.util.Arrays.hashCode(values());
+ }
+ }
+
+ /**
+ * The picture to put back in the morning, chosen when night begins from what the TV shows then. If it already
+ * shows the night picture (set by hand before), the day's values are unknown and the remembered or default
+ * day picture stands.
+ */
+ static Picture dayPicture(Picture now, Picture night, Picture remembered) {
+ if (now != null && !now.equals(night)) return now;
+ return remembered != null ? remembered : Picture.DAY;
+ }
+
+ /** True when the TV's picture should be the night one now. */
+ static boolean tvNightNow(Settings s, int minute) {
+ return s.on && s.tvPicture && level(s, minute).night;
+ }
+
/** What the layer shows right now. brightness 100 and warmth 0 means no layer at all. */
static final class Level {
final int brightness;
@@ -133,6 +206,13 @@ final class Dimming {
return clampBrightness(v + direction * (fine ? 1 : BRIGHTNESS_STEP));
}
+ /** One press on a TV picture slider, 0 to 100: 5 steps, 1 steps below FINE_BELOW. */
+ static int stepPercent(int v, int direction) {
+ boolean fine = v < FINE_BELOW || (v == FINE_BELOW && direction < 0);
+ int next = v + direction * (fine ? 1 : BRIGHTNESS_STEP);
+ return clamp(next < FINE_BELOW ? next : snap(next, BRIGHTNESS_STEP), 0, 100);
+ }
+
static int clampBrightness(int v) {
return clamp(v < FINE_BELOW ? v : snap(v, BRIGHTNESS_STEP), MIN_BRIGHTNESS, MAX_BRIGHTNESS);
}
diff --git a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/MainActivity.java b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/MainActivity.java
index dff2c2bb0..d0c494516 100644
--- a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/MainActivity.java
+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/MainActivity.java
@@ -1,6 +1,7 @@
package io.github.maxhayim.brightness;
import android.app.Activity;
+import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
@@ -22,6 +23,11 @@ public class MainActivity extends Activity {
private LinearLayout rows;
private TextView status;
private Row permissionRow, onRow, brightnessRow, nightRow, nightBrightnessRow, warmthRow, startRow, endRow;
+ private TvPicture tv;
+ private boolean tvAvailable;
+ /** The TV's "allow" prompt while this app may not change the picture yet; null once allowed. */
+ private volatile PendingIntent tvAsk;
+ private Row tvRow, tvBacklightRow, tvContrastRow, tvBrightnessRow, tvDynamicRow, tvTakeRow;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -54,6 +60,8 @@ public class MainActivity extends Activity {
hint.setPadding(px(16), px(12), 0, 0);
page.addView(hint);
setContentView(page);
+ tv = new TvPicture(this);
+ tvAvailable = tv.available();
build();
}
@@ -66,6 +74,17 @@ public class MainActivity extends Activity {
if ((permissionRow == null) == !allowed) build();
refresh();
DimService.start(this);
+ if (tvAvailable) {
+ // A binder call into the TV's settings app, which may have to start: off the main thread.
+ new Thread(() -> {
+ PendingIntent ask = tv.permissionRequest();
+ runOnUiThread(() -> {
+ boolean changed = (ask == null) != (tvAsk == null);
+ tvAsk = ask;
+ if (changed && !isFinishing()) build();
+ });
+ }).start();
+ }
}
private void build() {
@@ -115,9 +134,71 @@ public class MainActivity extends Activity {
s.nightEnd += d * Dimming.TIME_STEP;
changed();
}));
+ if (tvAvailable) buildTvRows();
(permissionRow != null ? permissionRow : onRow).requestFocus();
}
+ /** The TV's own picture, on TVs whose picture menu allows it: the light the dimming layer can't take away. */
+ private void buildTvRows() {
+ tvRow = add(new Row(this, "TV picture at night", "Also turns the TV's own backlight, contrast and brightness"
+ + " down for the night, and puts the day's back in the morning.", false, () -> {
+ s.tvPicture = !s.tvPicture;
+ changed();
+ }, d -> {
+ s.tvPicture = d > 0;
+ changed();
+ }));
+ if (tvAsk != null) {
+ Row ask = add(new Row(this, "Allow TV picture control",
+ "The TV asks once whether this app may change its picture settings. OK asks.", false, () -> {
+ try {
+ tvAsk.send();
+ } catch (PendingIntent.CanceledException ignored) {
+ // Asked again on the next open.
+ }
+ }, null));
+ ask.setValue("Not allowed");
+ }
+ tvBacklightRow = add(new Row(this, "Night backlight", "The TV's backlight: the light the panel gives off.",
+ true, null, d -> {
+ s.tvNight = s.tvNight.withBacklight(Dimming.stepPercent(s.tvNight.backlight, d));
+ changed();
+ }));
+ tvContrastRow = add(new Row(this, "Night contrast", "The TV's contrast. Lower dims the whites.", true, null,
+ d -> {
+ s.tvNight = s.tvNight.withContrast(Dimming.stepPercent(s.tvNight.contrast, d));
+ changed();
+ }));
+ tvBrightnessRow = add(new Row(this, "Night TV brightness", "The TV's brightness. Lower darkens the shadows.",
+ true, null, d -> {
+ s.tvNight = s.tvNight.withBrightness(Dimming.stepPercent(s.tvNight.brightness, d));
+ changed();
+ }));
+ tvDynamicRow = add(new Row(this, "Night dynamic backlight", "The TV lowers its backlight further on dark pictures.",
+ false, () -> {
+ s.tvNight = s.tvNight.withDynamicBacklight(!s.tvNight.dynamicBacklight);
+ changed();
+ }, null));
+ tvTakeRow = add(new Row(this, "Use the TV's picture now",
+ "Takes what is set in the TV's own picture menu as the night values.", false, this::takeTvPicture, null));
+ }
+
+ private void takeTvPicture() {
+ tvTakeRow.setValue("Reading…");
+ new Thread(() -> {
+ Dimming.Picture now = tv.read();
+ runOnUiThread(() -> {
+ if (now == null) {
+ tvTakeRow.setValue("Not allowed");
+ return;
+ }
+ s.tvNight = now;
+ changed();
+ tvTakeRow.setValue("Taken");
+ });
+ }).start();
+ }
+
private Row add(Row r) {
rows.addView(r, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
return r;
@@ -150,6 +231,22 @@ public class MainActivity extends Activity {
startRow.setAlpha(scheduled ? 1f : 0.5f);
endRow.setAlpha(scheduled ? 1f : 0.5f);
+ if (tvAvailable && tvRow != null) {
+ tvRow.setValue(s.tvPicture ? "On" : "Off");
+ tvBacklightRow.setValue(s.tvNight.backlight + " %");
+ tvBacklightRow.setBar(s.tvNight.backlight / 100f);
+ tvContrastRow.setValue(s.tvNight.contrast + " %");
+ tvContrastRow.setBar(s.tvNight.contrast / 100f);
+ tvBrightnessRow.setValue(s.tvNight.brightness + " %");
+ tvBrightnessRow.setBar(s.tvNight.brightness / 100f);
+ tvDynamicRow.setValue(s.tvNight.dynamicBacklight ? "On" : "Off");
+ float a = s.tvPicture ? 1f : 0.5f;
+ tvBacklightRow.setAlpha(a);
+ tvContrastRow.setAlpha(a);
+ tvBrightnessRow.setAlpha(a);
+ tvDynamicRow.setAlpha(a);
+ }
+
Dimming.Level l = Dimming.level(s, minute);
String text;
if (!s.on) text = "Off: the screen is normal.";
diff --git a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Prefs.java b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Prefs.java
index 0e5354da5..e004eeff3 100644
--- a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Prefs.java
+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Prefs.java
@@ -24,6 +24,8 @@ final class Prefs {
s.warmth = p.getInt("warmth", s.warmth);
s.nightStart = p.getInt("night_start", s.nightStart);
s.nightEnd = p.getInt("night_end", s.nightEnd);
+ s.tvPicture = p.getBoolean("tv_picture", s.tvPicture);
+ s.tvNight = picture(p, "tv_night_", Dimming.Picture.NIGHT);
try {
s.night = Dimming.Night.valueOf(p.getString("night", s.night.name()));
} catch (IllegalArgumentException e) {
@@ -42,6 +44,41 @@ final class Prefs {
.putInt("night_start", s.nightStart)
.putInt("night_end", s.nightEnd)
.putString("night", s.night.name())
+ .putBoolean("tv_picture", s.tvPicture)
+ .apply();
+ savePicture(c, "tv_night_", s.tvNight);
+ }
+
+ /** The day picture remembered when night last began, or null. */
+ static Dimming.Picture tvDay(Context c) {
+ SharedPreferences p = of(c);
+ return p.contains("tv_day_backlight") ? picture(p, "tv_day_", Dimming.Picture.DAY) : null;
+ }
+
+ static void saveTvDay(Context c, Dimming.Picture day) {
+ savePicture(c, "tv_day_", day);
+ }
+
+ /** "night" while the TV shows the night picture this app set, so the morning knows to put the day's back. */
+ static boolean tvAtNight(Context c) {
+ return of(c).getBoolean("tv_at_night", false);
+ }
+
+ static void setTvAtNight(Context c, boolean atNight) {
+ of(c).edit().putBoolean("tv_at_night", atNight).apply();
+ }
+
+ private static Dimming.Picture picture(SharedPreferences p, String prefix, Dimming.Picture d) {
+ return new Dimming.Picture(p.getInt(prefix + "backlight", d.backlight), p.getInt(prefix + "contrast", d.contrast),
+ p.getInt(prefix + "brightness", d.brightness), p.getBoolean(prefix + "dynamic", d.dynamicBacklight)).clamped();
+ }
+
+ private static void savePicture(Context c, String prefix, Dimming.Picture v) {
+ of(c).edit()
+ .putInt(prefix + "backlight", v.backlight)
+ .putInt(prefix + "contrast", v.contrast)
+ .putInt(prefix + "brightness", v.brightness)
+ .putBoolean(prefix + "dynamic", v.dynamicBacklight)
.apply();
}
diff --git a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/TvPicture.java b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/TvPicture.java
new file mode 100644
index 000000000..a4a413773
--- /dev/null
+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/TvPicture.java
@@ -0,0 +1,175 @@
+package io.github.maxhayim.brightness;
+
+import android.annotation.TargetApi;
+import android.app.PendingIntent;
+import android.app.slice.Slice;
+import android.app.slice.SliceItem;
+import android.app.slice.SliceManager;
+import android.app.slice.SliceSpec;
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Build;
+import android.util.Log;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * The TV's own picture settings on Realtek-based TVs, through the settings slices its picture menu is built from:
+ * the backlight, contrast, brightness and dynamic backlight. These change the light the panel gives off, which
+ * the dimming layer can't. Not public API: other TVs simply don't have the provider, and then this does nothing.
+ * Binder calls: use it off the main thread. Slices need Android 9; before that available() is false.
+ */
+@TargetApi(28)
+final class TvPicture {
+ static final String AUTHORITY = "com.realtek.menuslices";
+ private static final String BASE = "content://" + AUTHORITY + "/";
+ private static final String SEEKBAR = "TYPE_SEEKBAR_CONTROL";
+ private static final String SWITCH = "TYPE_SWITCH_CONTROL";
+ // The extras the TV's own settings fill in when a slider or switch changes.
+ private static final String SLIDER_VALUE = "android.app.slice.extra.SLIDER_VALUE";
+ private static final String TOGGLE_STATE = "android.app.slice.extra.TOGGLE_STATE";
+ private static final String PREFERENCE_KEY = "extra_preference_key";
+
+ /** The four controls, in the order of Dimming.Picture's fields. */
+ private static final Control[] CONTROLS = {
+ new Control(BASE + "MainMenu_Picture/Pic_Backlight", SEEKBAR, "Pic_Backlight_SeekBar"),
+ new Control(BASE + "Pic_Picture_Mode_Item_Personal/Pic_Contrast", SEEKBAR, null),
+ new Control(BASE + "Pic_Picture_Mode_Item_Personal/Pic_Brightness", SEEKBAR, null),
+ new Control(BASE + "MainMenu_Picture/Pic_Backlight", SWITCH, "Pic_Dynamic_Backlight"),
+ };
+
+ private static final class Control {
+ final Uri uri;
+ final String type;
+ final String key;
+
+ Control(String uri, String type, String key) {
+ this.uri = Uri.parse(uri);
+ this.type = type;
+ this.key = key;
+ }
+ }
+
+ /** What a bound slice holds for one control: its value and the action that changes it. */
+ private static final class Found {
+ int value = -1;
+ PendingIntent action;
+ }
+
+ private final Context context;
+ private final SliceManager slices;
+
+ TvPicture(Context context) {
+ this.context = context.getApplicationContext();
+ this.slices = Build.VERSION.SDK_INT >= 28 ? context.getSystemService(SliceManager.class) : null;
+ }
+
+ /** True on a TV whose picture menu offers these slices. */
+ boolean available() {
+ return slices != null && context.getPackageManager().resolveContentProvider(AUTHORITY, 0) != null;
+ }
+
+ /**
+ * The system's "Allow Brightness to show … slices" prompt when this app isn't allowed yet, or null when it is
+ * (or the TV has no such slices). The owner answers it once.
+ */
+ PendingIntent permissionRequest() {
+ if (!available()) return null;
+ Slice s = bind(CONTROLS[0].uri);
+ return s != null && s.getHints().contains("permission_request") ? firstAction(s) : null;
+ }
+
+ /** The TV's picture now, or null when it can't be read. */
+ Dimming.Picture read() {
+ int[] v = new int[CONTROLS.length];
+ for (int i = 0; i < CONTROLS.length; i++) {
+ Found f = find(CONTROLS[i]);
+ if (f == null || f.value < 0) return null;
+ v[i] = f.value;
+ }
+ return new Dimming.Picture(v[0], v[1], v[2], v[3] != 0);
+ }
+
+ /** Sets each control whose value differs from was (all of them when was is null). True when all were sent. */
+ boolean write(Dimming.Picture p, Dimming.Picture was) {
+ int[] want = p.values();
+ int[] had = was == null ? null : was.values();
+ boolean ok = true;
+ for (int i = 0; i < CONTROLS.length; i++) {
+ if (had != null && had[i] == want[i]) continue;
+ ok &= set(CONTROLS[i], want[i]);
+ }
+ return ok;
+ }
+
+ private boolean set(Control c, int value) {
+ Found f = find(c);
+ if (f == null || f.action == null) return false;
+ Intent fill = new Intent();
+ if (SWITCH.equals(c.type)) fill.putExtra(TOGGLE_STATE, value != 0);
+ else fill.putExtra(SLIDER_VALUE, value);
+ if (c.key != null) fill.putExtra(PREFERENCE_KEY, c.key);
+ try {
+ f.action.send(context, 0, fill);
+ return true;
+ } catch (PendingIntent.CanceledException e) {
+ Log.w(Prefs.TAG, "tv picture not set: " + c.uri);
+ return false;
+ }
+ }
+
+ private Found find(Control c) {
+ Slice s = bind(c.uri);
+ if (s == null || s.getHints().contains("permission_request")) return null;
+ for (SliceItem item : s.getItems()) {
+ if (!"slice".equals(item.getFormat()) || !c.type.equals(item.getSubType())) continue;
+ Slice row = item.getSlice();
+ if (c.key != null && !c.key.equals(textOf(row, "keywords"))) continue;
+ Found f = new Found();
+ for (SliceItem i : row.getItems()) {
+ if ("int".equals(i.getFormat()) && "SUBTYPE_SEEKBAR_VALUE".equals(i.getSubType())) {
+ if (SEEKBAR.equals(c.type)) f.value = i.getInt();
+ } else if ("slice".equals(i.getFormat()) && i.getHints().contains("shortcut")) {
+ for (SliceItem a : i.getSlice().getItems()) {
+ if (!"action".equals(a.getFormat())) continue;
+ f.action = a.getAction();
+ if (SWITCH.equals(c.type)) f.value = a.getHints().contains("selected") ? 1 : 0;
+ }
+ }
+ }
+ return f;
+ }
+ return null;
+ }
+
+ private Slice bind(Uri uri) {
+ Set<SliceSpec> specs = new HashSet<>();
+ specs.add(new SliceSpec("androidx.slice.LIST", 1));
+ try {
+ return slices.bindSlice(uri, specs);
+ } catch (RuntimeException e) {
+ Log.w(Prefs.TAG, "tv picture slice not bound: " + e.getMessage());
+ return null;
+ }
+ }
+
+ private static String textOf(Slice s, String hint) {
+ for (SliceItem i : s.getItems()) {
+ if ("text".equals(i.getFormat()) && i.getHints().contains(hint)) return String.valueOf(i.getText());
+ }
+ return null;
+ }
+
+ private static PendingIntent firstAction(Slice s) {
+ for (SliceItem i : s.getItems()) {
+ if ("action".equals(i.getFormat())) return i.getAction();
+ if ("slice".equals(i.getFormat())) {
+ PendingIntent p = firstAction(i.getSlice());
+ if (p != null) return p;
+ }
+ }
+ return null;
+ }
+}
diff --git a/addons/brightness/app/src/test/java/io/github/maxhayim/brightness/DimmingTest.java b/addons/brightness/app/src/test/java/io/github/maxhayim/brightness/DimmingTest.java
index b5c43b900..8555aeadf 100644
--- a/addons/brightness/app/src/test/java/io/github/maxhayim/brightness/DimmingTest.java
+++ b/addons/brightness/app/src/test/java/io/github/maxhayim/brightness/DimmingTest.java
@@ -110,6 +110,49 @@ public class DimmingTest {
assertEquals("fine values survive a reload", 3, s.clamped().nightBrightness);
}
+ @Test
+ public void tvSlidersReachZero() {
+ assertEquals(0, Dimming.stepPercent(1, -1));
+ assertEquals(0, Dimming.stepPercent(0, -1));
+ assertEquals(9, Dimming.stepPercent(10, -1));
+ assertEquals(20, Dimming.stepPercent(15, 1));
+ assertEquals(100, Dimming.stepPercent(100, 1));
+ }
+
+ @Test
+ public void dayPictureIsWhatTheTvShowedBeforeNight() {
+ Dimming.Picture before = new Dimming.Picture(80, 45, 50, false);
+ assertEquals(before, Dimming.dayPicture(before, Dimming.Picture.NIGHT, null));
+ }
+
+ @Test
+ public void nightPictureSetByHandKeepsTheRememberedDay() {
+ Dimming.Picture remembered = new Dimming.Picture(70, 50, 50, false);
+ assertEquals(remembered, Dimming.dayPicture(Dimming.Picture.NIGHT, Dimming.Picture.NIGHT, remembered));
+ assertEquals(Dimming.Picture.DAY, Dimming.dayPicture(Dimming.Picture.NIGHT, Dimming.Picture.NIGHT, null));
+ assertEquals("unreadable: the remembered day", remembered, Dimming.dayPicture(null, Dimming.Picture.NIGHT, remembered));
+ }
+
+ @Test
+ public void tvPictureFollowsNightModeAndTheMasterSwitch() {
+ Dimming.Settings s = on();
+ s.tvPicture = true;
+ assertTrue(Dimming.tvNightNow(s, 23 * 60));
+ assertFalse(Dimming.tvNightNow(s, 12 * 60));
+ s.on = false;
+ assertFalse("off puts the day picture back", Dimming.tvNightNow(s, 23 * 60));
+ s.on = true;
+ s.tvPicture = false;
+ assertFalse(Dimming.tvNightNow(s, 23 * 60));
+ }
+
+ @Test
+ public void picturesClampAndCompare() {
+ Dimming.Picture p = new Dimming.Picture(-5, 150, 35, true).clamped();
+ assertEquals(new Dimming.Picture(0, 100, 35, true), p);
+ assertFalse(p.equals(p.withDynamicBacklight(false)));
+ }
+
@Test
public void windowPastMidnight() {
int start = 21 * 60, end = 7 * 60;