Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
Add-on: Brightness, software dimming with a scheduled warm night mode
מקס חיים144b3b3efe3a
diff --git a/addons/README.md b/addons/README.mdindex 7136a318a..e8e63a589 100644--- a/addons/README.md+++ b/addons/README.md@@ -15,6 +15,7 @@ the core bigger or change how it behaves. You install an add-on only if you want| [Photo Prints](photo-prints/) | Your own photos as a screensaver: dated prints dealt in on a time-of-day sky, and a card that starts the slideshow | [@shivamsingh262](https://github.com/shivamsingh262) | Sony BRAVIA KD-65X82L (Google TV 12) | None || [Photo screensaver](photo-screensaver/) | Your own pictures and MP4 clips as the TV's screensaver and as a card, slowly zooming and crossfading (20 s each by default); optional time, photo dates, prints on a sky and weather | [JorickGU](https://github.com/JorickGU) | TCL 43P69K (Google TV 12) | `INTERNET` and coarse location, only with the weather option on || [Prayer Times](prayer-times/) | Today's prayer times for one city from Aladhan (no key), the next prayer with a countdown, Gregorian and Hijri dates | [@majnioui](https://github.com/majnioui) | Xiaomi TV (MiTV-MOOR2), Google TV 11 | `INTERNET` |+| [Brightness](brightness/) | Dims the picture below the TV's own minimum over every app, with a warm night mode on a schedule and a one-press normal screen | [@maxhayim](https://github.com/maxhayim) | Not yet on a TV | overlay, foreground service, start at boot |A widget, an info tile, a storage or smart-home card: if it can live as its own small app, it can livehere. See the rules below.diff --git a/addons/brightness/.gitignore b/addons/brightness/.gitignorenew file mode 100644index 000000000..a7e04a21b--- /dev/null+++ b/addons/brightness/.gitignore@@ -0,0 +1,4 @@+.gradle/+build/+app/build/+local.propertiesdiff --git a/addons/brightness/README.md b/addons/brightness/README.mdnew file mode 100644index 000000000..a712e818f--- /dev/null+++ b/addons/brightness/README.md@@ -0,0 +1,102 @@+# Brightness++Dims the whole picture below what the TV's own settings allow, and warms it at night, over every app, Live+TV and the home screen. For the [Clean Your TV](../../README.md) launcher it declares a+[module card](../../docs/modules.md): once you answer **Show card** its tile reads "Brightness" with an amber+glow. On any other Android TV home it is an ordinary app.++Opening it shows one list, worked with the remote alone:++| Row | What it does |+|---|---|+| **Dimming** | The master switch, focused first. **Off puts the screen back to normal at once**; the other settings stay for next time. |+| **Brightness** | A slider from 100 % down to 20 % in 5 % steps (◀ ▶), used outside night mode. |+| **Night mode** | Off, On (now, until switched off) or Scheduled (every day between two times). |+| **Night brightness** | Its own slider, 20 % 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). |++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.++The screen never goes below 20 %, so the picture and this app stay readable whatever is set. If it is ever too+dark to find the way, any of these gives the normal screen back:++- open Brightness and press OK on **Dimming**;+- 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.++## How it works++This is software dimming. A full-screen window of one colour sits over everything (`TYPE_APPLICATION_OVERLAY`),+black at the missing brightness with the amber folded in for warmth. It never takes focus, keys or touches, so+the remote keeps controlling whatever is on screen. A foreground service holds the window and switches night+mode at the scheduled times, and it stops itself when there is nothing to draw and no schedule to follow.++## Permissions++| Permission | Why |+|---|---|+| Display over other apps (`SYSTEM_ALERT_WINDOW`) | To draw the dimming layer over other apps. Granted by `install.sh`, since many TVs hide this setting. Without it the app says so and draws nothing. |+| 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. |++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.++## 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/brightness/install.sh+```++It builds the add-on, installs it, allows display over other apps (and TCL's auto-start), and opens it. Press+Home: the launcher asks once whether to show the card. Change the answer later by holding OK on Settings, then+Module cards. To build only: `cd addons/brightness && ./gradlew assembleRelease`; the JVM tests run with+`./gradlew testReleaseUnitTest`.++The release build is signed with the debug key so it installs over ADB like the launcher. Sign your own builds+with your own key if you hand them out; the launcher pins its Show answer to the signing key.++## 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.+- **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+ they are open.+- **Menus drawn by the TV itself** are not Android windows on some sets (picture menus on several TCL and Sony+ models), so they show at full brightness.+- **Video planes vary.** On most TVs video, HDMI inputs and the tuner sit under Android's graphics and are+ dimmed with the rest. Some chips put protected, HDR or tunnelled video on their own plane, which may show+ undimmed or lose the tint. Check on your TV with each source you use.+- **The setting may be hidden.** Some firmware (TCL, some Fire TV builds) has no screen to allow display over+ other apps; `install.sh` allows it over ADB, or the app shows the ADB command.+- **Aggressive memory managers** can stop the service on 1 GB TVs. If they do, the layer goes and the screen+ is brighter, never darker; opening the app starts it again.+- Screenshots and screen recordings include the layer.++## Tested on++Not yet on a TV. The JVM tests cover the levels, the colour arithmetic, the schedule (past midnight, edges,+empty windows), the 20 % floor and the clamping of stored values. These checks need a TV:++1. The card prompt and **Show card**; the card opens the app.+2. Each slider moves the layer at once; the 20 % floor holds.+3. **Dimming** Off removes the layer at once, and so do the ADB broadcast and a force stop.+4. Night mode On, then Scheduled, with a window starting a minute or two ahead: it switches at the start and+ at the end without opening the app.+5. The layer over Home, a streaming app playing video, Live TV and an HDMI input, with every remote key still+ reaching the app below.+6. A reboot with dimming on brings the layer and the schedule back.+7. On a TV that hides the overlay setting, the app's message and `install.sh` grant.+8. Memory with the layer up (`dumpsys meminfo io.github.maxhayim.brightness`).++## Maintainer++[@maxhayim](https://github.com/maxhayim)diff --git a/addons/brightness/app/build.gradle b/addons/brightness/app/build.gradlenew file mode 100644index 000000000..1026d3bee--- /dev/null+++ b/addons/brightness/app/build.gradle@@ -0,0 +1,36 @@+plugins {+ id 'com.android.application'+}++android {+ namespace 'io.github.maxhayim.brightness'+ compileSdk 34++ defaultConfig {+ applicationId 'io.github.maxhayim.brightness'+ 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/brightness/app/proguard-rules.pro b/addons/brightness/app/proguard-rules.pronew file mode 100644index 000000000..a4435d69a--- /dev/null+++ b/addons/brightness/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.+-dontobfuscatediff --git a/addons/brightness/app/src/main/AndroidManifest.xml b/addons/brightness/app/src/main/AndroidManifest.xmlnew file mode 100644index 000000000..e54053643--- /dev/null+++ b/addons/brightness/app/src/main/AndroidManifest.xml@@ -0,0 +1,65 @@+<?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" />++ <!-- The dimming layer is drawn over whatever is on screen. -->+ <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />+ <!-- One foreground service holds the layer and switches night mode on schedule. -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />+ <!-- Put the layer back after a reboot. -->+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />++ <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">++ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:launchMode="singleTask">+ <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>++ <service+ android:name=".DimService"+ android:exported="false"+ android:foregroundServiceType="specialUse">+ <property+ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"+ android:value="Keeps a user-chosen screen dimming layer over other apps" />+ </service>++ <receiver+ android:name=".BootReceiver"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.BOOT_COMPLETED" />+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+ </intent-filter>+ </receiver>++ <!-- Normal screen from ADB: am broadcast -a io.github.maxhayim.brightness.OFF -n io.github.maxhayim.brightness/.OffReceiver+ Open to any sender on purpose: it can only switch dimming off, never on. -->+ <receiver+ android:name=".OffReceiver"+ android:exported="true">+ <intent-filter>+ <action android:name="io.github.maxhayim.brightness.OFF" />+ </intent-filter>+ </receiver>+ </application>+</manifest>diff --git a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/BootReceiver.java b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/BootReceiver.javanew file mode 100644index 000000000..4393f961a--- /dev/null+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/BootReceiver.java@@ -0,0 +1,16 @@+package io.github.maxhayim.brightness;++import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;++/** Puts the layer and the schedule back after a reboot or an update of this app, if dimming was on. */+public class BootReceiver extends BroadcastReceiver {+ @Override+ public void onReceive(Context context, Intent intent) {+ String a = intent.getAction();+ if (Intent.ACTION_BOOT_COMPLETED.equals(a) || Intent.ACTION_MY_PACKAGE_REPLACED.equals(a)) {+ DimService.start(context);+ }+ }+}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.javanew file mode 100644index 000000000..60b0e94f3--- /dev/null+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/DimService.java@@ -0,0 +1,176 @@+package io.github.maxhayim.brightness;++import android.app.Notification;+import android.app.NotificationChannel;+import android.app.NotificationManager;+import android.app.Service;+import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;+import android.content.IntentFilter;+import android.content.SharedPreferences;+import android.content.pm.ServiceInfo;+import android.graphics.PixelFormat;+import android.os.Build;+import android.os.Handler;+import android.os.IBinder;+import android.os.Looper;+import android.provider.Settings;+import android.util.Log;+import android.view.View;+import android.view.WindowManager;++import java.util.Calendar;++/**+ * 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.+ */+public class DimService extends Service {+ private static final String CHANNEL = "dimming";+ private static final int NOTIFICATION_ID = 1;+ /** Checked at least this often while a schedule runs, so a clock change or a TV standby can't leave it stale. */+ private static final long MAX_WAIT_MS = 5 * 60_000L;++ private final Handler main = new Handler(Looper.getMainLooper());+ private WindowManager wm;+ private View layer;+ /** Kept in a field: SharedPreferences holds its listeners weakly. */+ private final SharedPreferences.OnSharedPreferenceChangeListener prefsListener = (p, key) -> apply();+ private final Runnable tick = this::apply;+ private final BroadcastReceiver clockReceiver = new BroadcastReceiver() {+ @Override+ public void onReceive(Context context, Intent intent) {+ apply();+ }+ };++ /** 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;+ try {+ c.startForegroundService(new Intent(c, DimService.class));+ } catch (RuntimeException e) {+ // Android 12+ refuses a foreground start from the background; the next open of the app starts it.+ Log.w(Prefs.TAG, "service not started: " + e.getMessage());+ }+ }++ static boolean canDraw(Context c) {+ return Settings.canDrawOverlays(c);+ }++ @Override+ public void onCreate() {+ super.onCreate();+ wm = getSystemService(WindowManager.class);+ NotificationManager nm = getSystemService(NotificationManager.class);+ nm.createNotificationChannel(new NotificationChannel(CHANNEL, getString(R.string.channel_name),+ NotificationManager.IMPORTANCE_MIN));+ Notification n = new Notification.Builder(this, CHANNEL)+ .setSmallIcon(R.drawable.ic_foreground)+ .setContentTitle(getString(R.string.app_name))+ .setContentText(getString(R.string.notification_text))+ .setOngoing(true)+ .build();+ if (Build.VERSION.SDK_INT >= 34) {+ startForeground(NOTIFICATION_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);+ } else {+ startForeground(NOTIFICATION_ID, n);+ }+ Prefs.of(this).registerOnSharedPreferenceChangeListener(prefsListener);+ IntentFilter f = new IntentFilter();+ f.addAction(Intent.ACTION_TIME_CHANGED);+ f.addAction(Intent.ACTION_TIMEZONE_CHANGED);+ f.addAction(Intent.ACTION_SCREEN_ON);+ registerReceiver(clockReceiver, f);+ }++ @Override+ public int onStartCommand(Intent intent, int flags, int startId) {+ apply();+ return START_STICKY;+ }++ @Override+ public void onDestroy() {+ main.removeCallbacks(tick);+ Prefs.of(this).unregisterOnSharedPreferenceChangeListener(prefsListener);+ unregisterReceiver(clockReceiver);+ removeLayer();+ super.onDestroy();+ }++ @Override+ public IBinder onBind(Intent intent) {+ return null;+ }++ /** Draws what the settings ask for at this minute, plans the next check, or stops when nothing is left to do. */+ private void apply() {+ main.removeCallbacks(tick);+ Dimming.Settings s = Prefs.load(this);+ int minute = minuteNow();+ Dimming.Level level = Dimming.level(s, minute);+ if (level.visible() && canDraw(this)) showLayer(Dimming.color(level));+ else removeLayer();+ if (!Dimming.needsService(s, minute)) {+ stopSelf();+ return;+ }+ int next = Dimming.minutesToNextChange(s, minute);+ if (next > 0) {+ Calendar now = Calendar.getInstance();+ long toBoundary = next * 60_000L - now.get(Calendar.SECOND) * 1000L - now.get(Calendar.MILLISECOND);+ main.postDelayed(tick, Math.max(1000, Math.min(MAX_WAIT_MS, toBoundary)));+ }+ }++ private void showLayer(int color) {+ if (layer != null) {+ layer.setBackgroundColor(color);+ return;+ }+ View v = new View(this);+ v.setBackgroundColor(color);+ try {+ wm.addView(v, params());+ layer = v;+ } catch (RuntimeException e) {+ Log.w(Prefs.TAG, "layer not shown (display over other apps not allowed?): " + e.getMessage());+ }+ }++ private void removeLayer() {+ if (layer == null) return;+ try {+ wm.removeView(layer);+ } catch (RuntimeException ignored) {+ // Already gone with the window manager.+ }+ layer = null;+ }++ private static WindowManager.LayoutParams params() {+ WindowManager.LayoutParams p = new WindowManager.LayoutParams(+ WindowManager.LayoutParams.MATCH_PARENT,+ WindowManager.LayoutParams.MATCH_PARENT,+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE+ | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE+ | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN+ | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,+ PixelFormat.TRANSLUCENT);+ if (Build.VERSION.SDK_INT >= 28) {+ p.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;+ }+ p.setTitle("Brightness");+ return p;+ }++ static int minuteNow() {+ Calendar c = Calendar.getInstance();+ return c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE);+ }+}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.javanew file mode 100644index 000000000..2cdad221e--- /dev/null+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Dimming.java@@ -0,0 +1,139 @@+package io.github.maxhayim.brightness;++/**+ * The settings and the arithmetic, with no Android types, so the JVM tests cover all of it: which level applies+ * at a given minute, the one colour the layer is drawn in, and when the schedule next changes.+ */+final class Dimming {+ /** The darkest the screen goes: 20 % of normal, so menus and this app stay readable whatever is set. */+ static final int MIN_BRIGHTNESS = 20;+ static final int MAX_BRIGHTNESS = 100;+ static final int BRIGHTNESS_STEP = 5;+ static final int WARMTH_STEP = 10;+ static final int TIME_STEP = 15;+ static final int DAY_MINUTES = 24 * 60;+ /** Warmth 100 lays this amber over the picture at MAX_WARM_ALPHA: blue and green drop, red stays. */+ static final int WARM_RGB = 0xFF8A1E;+ static final float MAX_WARM_ALPHA = 0.4f;++ enum Night { OFF, ON, SCHEDULED }++ static final class Settings {+ /** The master switch. Off draws nothing, whatever the rest says. */+ boolean on;+ int brightness = 70;+ Night night = Night.SCHEDULED;+ int nightBrightness = 40;+ int warmth = 50;+ /** Minutes after midnight, local time. */+ int nightStart = 21 * 60;+ int nightEnd = 7 * 60;++ /** Every value back in range, whatever the stored copy held. */+ Settings clamped() {+ brightness = clamp(snap(brightness, BRIGHTNESS_STEP), MIN_BRIGHTNESS, MAX_BRIGHTNESS);+ nightBrightness = clamp(snap(nightBrightness, BRIGHTNESS_STEP), MIN_BRIGHTNESS, MAX_BRIGHTNESS);+ warmth = clamp(snap(warmth, WARMTH_STEP), 0, 100);+ nightStart = wrap(snap(nightStart, TIME_STEP));+ nightEnd = wrap(snap(nightEnd, TIME_STEP));+ if (night == null) night = Night.SCHEDULED;+ return this;+ }+ }++ /** What the layer shows right now. brightness 100 and warmth 0 means no layer at all. */+ static final class Level {+ final int brightness;+ final int warmth;+ final boolean night;++ Level(int brightness, int warmth, boolean night) {+ this.brightness = brightness;+ this.warmth = warmth;+ this.night = night;+ }++ boolean visible() {+ return brightness < MAX_BRIGHTNESS || warmth > 0;+ }+ }++ private Dimming() {+ }++ /** True from start up to, not including, end; a window may run past midnight. start == end is never night. */+ static boolean inWindow(int start, int end, int minute) {+ if (start == end) return false;+ return start < end ? minute >= start && minute < end : minute >= start || minute < end;+ }++ static boolean nightNow(Settings s, int minute) {+ switch (s.night) {+ case ON:+ return true;+ case SCHEDULED:+ return inWindow(s.nightStart, s.nightEnd, minute);+ default:+ return false;+ }+ }++ static Level level(Settings s, int minute) {+ if (!s.on) return new Level(MAX_BRIGHTNESS, 0, false);+ boolean night = nightNow(s, minute);+ return night ? new Level(s.nightBrightness, s.warmth, true) : new Level(s.brightness, 0, false);+ }++ /**+ * The layer's ARGB colour. Drawing it over the picture equals an amber layer at warmth's alpha with black+ * at (1 - brightness) over that, folded into one window: out = (1 - a) * picture + a * colour.+ */+ static int color(Level l) {+ double black = 1 - l.brightness / 100.0;+ double warm = MAX_WARM_ALPHA * l.warmth / 100.0;+ double alpha = 1 - (1 - black) * (1 - warm);+ if (alpha <= 0) return 0;+ double k = (1 - black) * warm / alpha;+ int r = (int) Math.round(((WARM_RGB >> 16) & 0xFF) * k);+ int g = (int) Math.round(((WARM_RGB >> 8) & 0xFF) * k);+ int b = (int) Math.round((WARM_RGB & 0xFF) * k);+ int a = (int) Math.round(alpha * 255);+ return a << 24 | r << 16 | g << 8 | b;+ }++ /**+ * Minutes from minute until the level can next change by itself: the next start or end of the night window.+ * -1 when nothing changes on its own (dimming off, or night mode not scheduled, or an empty window).+ */+ static int minutesToNextChange(Settings s, int minute) {+ if (!s.on || s.night != Night.SCHEDULED || s.nightStart == s.nightEnd) return -1;+ int toStart = wrap(s.nightStart - minute);+ int toEnd = wrap(s.nightEnd - minute);+ if (toStart == 0) toStart = DAY_MINUTES;+ if (toEnd == 0) toEnd = DAY_MINUTES;+ return Math.min(toStart, toEnd);+ }++ /** True when the service has work: a layer to hold, or a schedule to follow. */+ static boolean needsService(Settings s, int minute) {+ return s.on && (level(s, minute).visible() || minutesToNextChange(s, minute) > 0);+ }++ static String clock(int minute, boolean h24) {+ int h = minute / 60, m = minute % 60;+ if (h24) return String.format(java.util.Locale.ROOT, "%02d:%02d", h, m);+ return String.format(java.util.Locale.ROOT, "%d:%02d %s", h % 12 == 0 ? 12 : h % 12, m, h < 12 ? "AM" : "PM");+ }++ static int clamp(int v, int lo, int hi) {+ return Math.max(lo, Math.min(hi, v));+ }++ static int wrap(int minute) {+ return ((minute % DAY_MINUTES) + DAY_MINUTES) % DAY_MINUTES;+ }++ private static int snap(int v, int step) {+ return Math.round(v / (float) step) * step;+ }+}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.javanew file mode 100644index 000000000..7cc0aefb2--- /dev/null+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/MainActivity.java@@ -0,0 +1,181 @@+package io.github.maxhayim.brightness;++import android.app.Activity;+import android.content.ActivityNotFoundException;+import android.content.Intent;+import android.net.Uri;+import android.os.Bundle;+import android.provider.Settings;+import android.text.format.DateFormat;+import android.view.ViewGroup;+import android.widget.LinearLayout;+import android.widget.ScrollView;+import android.widget.TextView;++/**+ * The tile and module card open this: one list, the first row the master switch, so normal screen is a single OK+ * away. Left and Right change a value and the layer follows at once, over this screen too, as a preview.+ * No text fields and nothing to type.+ */+public class MainActivity extends Activity {+ private Dimming.Settings s;+ private LinearLayout rows;+ private TextView status;+ private Row permissionRow, onRow, brightnessRow, nightRow, nightBrightnessRow, warmthRow, startRow, endRow;++ @Override+ protected void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+ LinearLayout page = new LinearLayout(this);+ page.setOrientation(LinearLayout.VERTICAL);+ page.setBackgroundColor(0xFF0D1117);+ page.setPadding(px(48), px(32), px(48), px(24));+ TextView title = new TextView(this);+ title.setText(R.string.app_name);+ title.setTextSize(28);+ title.setTextColor(0xFFFFFFFF);+ status = new TextView(this);+ status.setTextSize(15);+ status.setTextColor(0xFF8B949E);+ status.setPadding(0, 0, 0, px(16));+ page.addView(title);+ page.addView(status);++ ScrollView scroll = new ScrollView(this);+ rows = new LinearLayout(this);+ rows.setOrientation(LinearLayout.VERTICAL);+ scroll.addView(rows);+ page.addView(scroll, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));++ TextView hint = new TextView(this);+ hint.setText("◀ ▶ change OK switch Back closes, settings stay");+ hint.setTextSize(13);+ hint.setTextColor(0xFF8B949E);+ hint.setPadding(px(16), px(12), 0, 0);+ page.addView(hint);+ setContentView(page);+ build();+ }++ @Override+ protected void onResume() {+ super.onResume();+ // The overlay permission may have been granted in Settings or over ADB meanwhile.+ s = Prefs.load(this);+ boolean allowed = DimService.canDraw(this);+ if ((permissionRow == null) == !allowed) build();+ refresh();+ DimService.start(this);+ }++ private void build() {+ s = Prefs.load(this);+ rows.removeAllViews();+ permissionRow = null;+ if (!DimService.canDraw(this)) {+ permissionRow = add(new Row(this, "Allow display over other apps",+ "Needed to dim other apps. OK opens the setting.", false, this::askPermission, null));+ permissionRow.setValue("Not allowed");+ }+ onRow = add(new Row(this, "Dimming", "Off puts the screen back to normal at once. The settings below stay.",+ false, () -> {+ s.on = !s.on;+ changed();+ }, d -> {+ s.on = d > 0;+ changed();+ }));+ brightnessRow = add(new Row(this, "Brightness", "How bright the picture is outside night mode.", true, null,+ d -> {+ s.brightness += d * Dimming.BRIGHTNESS_STEP;+ changed();+ }));+ nightRow = add(new Row(this, "Night mode", null, false, () -> {+ s.night = Dimming.Night.values()[(s.night.ordinal() + 1) % 3];+ changed();+ }, d -> {+ s.night = Dimming.Night.values()[(s.night.ordinal() + d + 3) % 3];+ changed();+ }));+ nightBrightnessRow = add(new Row(this, "Night brightness", "How bright the picture is in night mode.", true,+ null, d -> {+ s.nightBrightness += d * Dimming.BRIGHTNESS_STEP;+ changed();+ }));+ warmthRow = add(new Row(this, "Warmth", "Night mode only: less blue, a warmer picture.", true, null, d -> {+ s.warmth += d * Dimming.WARMTH_STEP;+ changed();+ }));+ startRow = add(new Row(this, "Night starts", "Scheduled night mode begins. ◀ ▶ moves 15 minutes.", false, null,+ d -> {+ s.nightStart += d * Dimming.TIME_STEP;+ changed();+ }));+ endRow = add(new Row(this, "Night ends", "Back to the day brightness.", false, null, d -> {+ s.nightEnd += d * Dimming.TIME_STEP;+ changed();+ }));+ (permissionRow != null ? permissionRow : onRow).requestFocus();+ }++ private Row add(Row r) {+ rows.addView(r, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));+ return r;+ }++ /** Saves, which the running service sees at once; starts it when the new settings need it. */+ private void changed() {+ Prefs.save(this, s);+ refresh();+ DimService.start(this);+ }++ private void refresh() {+ boolean h24 = DateFormat.is24HourFormat(this);+ int minute = DimService.minuteNow();+ onRow.setValue(s.on ? "On" : "Off");+ brightnessRow.setValue(s.brightness + " %");+ brightnessRow.setBar(fraction(s.brightness));+ nightRow.setValue(s.night == Dimming.Night.OFF ? "Off" : s.night == Dimming.Night.ON ? "On" : "Scheduled");+ nightRow.setDetail(s.night == Dimming.Night.SCHEDULED+ ? "Between the times below, every day."+ : s.night == Dimming.Night.ON ? "Now, until switched off here." : "Day brightness all the time.");+ nightBrightnessRow.setValue(s.nightBrightness + " %");+ nightBrightnessRow.setBar(fraction(s.nightBrightness));+ warmthRow.setValue(s.warmth + " %");+ warmthRow.setBar(s.warmth / 100f);+ startRow.setValue(Dimming.clock(s.nightStart, h24));+ endRow.setValue(Dimming.clock(s.nightEnd, h24));+ boolean scheduled = s.night == Dimming.Night.SCHEDULED;+ startRow.setAlpha(scheduled ? 1f : 0.5f);+ endRow.setAlpha(scheduled ? 1f : 0.5f);++ Dimming.Level l = Dimming.level(s, minute);+ String text;+ if (!s.on) text = "Off: the screen is normal.";+ else if (permissionRow != null) text = "On, but nothing is drawn until display over other apps is allowed.";+ else if (l.night) text = "Night mode now: " + l.brightness + " %, warmth " + l.warmth + " %"+ + (scheduled ? ", until " + Dimming.clock(s.nightEnd, h24) : "") + ".";+ else text = "Now: " + l.brightness + " %"+ + (scheduled && s.nightStart != s.nightEnd ? ". Night mode from " + Dimming.clock(s.nightStart, h24) : "") + ".";+ status.setText(text);+ }++ private void askPermission() {+ try {+ startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())));+ } catch (ActivityNotFoundException | SecurityException e) {+ // Many TVs hide this setting; the ADB shell can still grant it.+ permissionRow.setDetail("This TV has no screen for it. From a computer: adb shell appops set "+ + getPackageName() + " SYSTEM_ALERT_WINDOW allow");+ }+ }++ private static float fraction(int brightness) {+ return (brightness - Dimming.MIN_BRIGHTNESS) / (float) (Dimming.MAX_BRIGHTNESS - Dimming.MIN_BRIGHTNESS);+ }++ private int px(int dp) {+ return Math.round(dp * getResources().getDisplayMetrics().density);+ }+}diff --git a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/OffReceiver.java b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/OffReceiver.javanew file mode 100644index 000000000..c4c3e861e--- /dev/null+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/OffReceiver.java@@ -0,0 +1,19 @@+package io.github.maxhayim.brightness;++import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;++/**+ * Normal screen from outside the app, for when the picture is too dark to find the way:+ * am broadcast -a io.github.maxhayim.brightness.OFF -n io.github.maxhayim.brightness/.OffReceiver+ * It only ever switches dimming off; the running service sees the change and removes the layer.+ */+public class OffReceiver extends BroadcastReceiver {+ static final String ACTION = "io.github.maxhayim.brightness.OFF";++ @Override+ public void onReceive(Context context, Intent intent) {+ if (ACTION.equals(intent.getAction())) Prefs.switchOff(context);+ }+}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.javanew file mode 100644index 000000000..0e5354da5--- /dev/null+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Prefs.java@@ -0,0 +1,52 @@+package io.github.maxhayim.brightness;++import android.content.Context;+import android.content.SharedPreferences;++/** The settings in the app's own storage. Writing them is all it takes: the service listens and redraws. */+final class Prefs {+ static final String FILE = "brightness";+ static final String TAG = "Brightness";++ private Prefs() {+ }++ static SharedPreferences of(Context c) {+ return c.getSharedPreferences(FILE, Context.MODE_PRIVATE);+ }++ static Dimming.Settings load(Context c) {+ SharedPreferences p = of(c);+ Dimming.Settings s = new Dimming.Settings();+ s.on = p.getBoolean("on", s.on);+ s.brightness = p.getInt("brightness", s.brightness);+ s.nightBrightness = p.getInt("night_brightness", s.nightBrightness);+ s.warmth = p.getInt("warmth", s.warmth);+ s.nightStart = p.getInt("night_start", s.nightStart);+ s.nightEnd = p.getInt("night_end", s.nightEnd);+ try {+ s.night = Dimming.Night.valueOf(p.getString("night", s.night.name()));+ } catch (IllegalArgumentException e) {+ s.night = Dimming.Night.SCHEDULED;+ }+ return s.clamped();+ }++ static void save(Context c, Dimming.Settings s) {+ s.clamped();+ of(c).edit()+ .putBoolean("on", s.on)+ .putInt("brightness", s.brightness)+ .putInt("night_brightness", s.nightBrightness)+ .putInt("warmth", s.warmth)+ .putInt("night_start", s.nightStart)+ .putInt("night_end", s.nightEnd)+ .putString("night", s.night.name())+ .apply();+ }++ /** Normal screen at once; the other settings stay for next time. */+ static void switchOff(Context c) {+ of(c).edit().putBoolean("on", false).apply();+ }+}diff --git a/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Row.java b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Row.javanew file mode 100644index 000000000..7a4004638--- /dev/null+++ b/addons/brightness/app/src/main/java/io/github/maxhayim/brightness/Row.java@@ -0,0 +1,103 @@+package io.github.maxhayim.brightness;++import android.content.Context;+import android.view.Gravity;+import android.view.KeyEvent;+import android.view.View;+import android.widget.FrameLayout;+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 onClick;+ * Left and Right run onStep with -1 or +1, held keys repeat. A row with a bar draws its value as a slider.+ */+final class Row extends LinearLayout {+ interface Step {+ void step(int direction);+ }++ private final TextView value;+ private final TextView desc;+ private final View fill;+ private final View rest;++ Row(Context context, String name, String description, boolean bar, Runnable onClick, Step onStep) {+ 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);+ boolean active = onClick != null || onStep != null;+ setFocusable(active);+ setClickable(onClick != null);+ if (onClick != null) setOnClickListener(v -> onClick.run());+ if (onStep != null) {+ setOnKeyListener((v, code, e) -> {+ if (code != KeyEvent.KEYCODE_DPAD_LEFT && code != KeyEvent.KEYCODE_DPAD_RIGHT) return false;+ if (e.getAction() == KeyEvent.ACTION_DOWN) onStep.step(code == KeyEvent.KEYCODE_DPAD_LEFT ? -1 : 1);+ return true;+ });+ }++ 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));++ if (bar) {+ LinearLayout track = new LinearLayout(context);+ track.setOrientation(HORIZONTAL);+ track.setBackgroundColor(0x33FFFFFF);+ fill = new View(context);+ fill.setBackgroundColor(0xFFF5A524);+ rest = new View(context);+ track.addView(fill, new LayoutParams(0, LayoutParams.MATCH_PARENT, 0f));+ track.addView(rest, new LayoutParams(0, LayoutParams.MATCH_PARENT, 1f));+ FrameLayout holder = new FrameLayout(context);+ holder.addView(track, new FrameLayout.LayoutParams(Math.round(200 * dp), Math.round(6 * dp), Gravity.CENTER_VERTICAL));+ LayoutParams hp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);+ hp.rightMargin = Math.round(16 * dp);+ addView(holder, hp);+ } else {+ fill = rest = null;+ }++ 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);+ }++ /** The slider's position, 0 to 1. */+ void setBar(float fraction) {+ if (fill == null) return;+ float f = Math.max(0f, Math.min(1f, fraction));+ ((LayoutParams) fill.getLayoutParams()).weight = f;+ ((LayoutParams) rest.getLayoutParams()).weight = 1f - f;+ fill.requestLayout();+ }+}diff --git a/addons/brightness/app/src/main/res/drawable/banner.xml b/addons/brightness/app/src/main/res/drawable/banner.xmlnew file mode 100644index 000000000..7aa5efd5a--- /dev/null+++ b/addons/brightness/app/src/main/res/drawable/banner.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- 16:9 banner: a screen bright on the left, dim and warm on the right, under a half sun. 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="#101418" android:pathData="M0,0h320v180h-320z" />+ <path android:fillColor="#3A4654" android:pathData="M24,24h136v132h-136z" />+ <path android:fillColor="#2A1D10" android:pathData="M160,24h136v132h-136z" />+ <path android:fillColor="#F5A524" android:pathData="M160,62a28,28 0 0 1 0,56z" />+ <path android:fillColor="#FFFFFF" android:pathData="M160,62a28,28 0 0 0 0,56z" />+ <path android:fillColor="#F5A524" android:pathData="M24,146h272v10h-272z" />+ <path android:fillColor="#FFFFFF" android:pathData="M24,146h180v10h-180z" />+</vector>diff --git a/addons/brightness/app/src/main/res/drawable/ic_foreground.xml b/addons/brightness/app/src/main/res/drawable/ic_foreground.xmlnew file mode 100644index 000000000..a21b880e4--- /dev/null+++ b/addons/brightness/app/src/main/res/drawable/ic_foreground.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- A half white, half amber sun 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:fillColor="#FFFFFF" android:pathData="M54,36a18,18 0 0 0 0,36z" />+ <path android:fillColor="#F5A524" android:pathData="M54,36a18,18 0 0 1 0,36z" />+</vector>diff --git a/addons/brightness/app/src/main/res/drawable/row_background.xml b/addons/brightness/app/src/main/res/drawable/row_background.xmlnew file mode 100644index 000000000..03ccab9f5--- /dev/null+++ b/addons/brightness/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/brightness/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/addons/brightness/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmlnew file mode 100644index 000000000..0a99b20b1--- /dev/null+++ b/addons/brightness/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/brightness/app/src/main/res/values/strings.xml b/addons/brightness/app/src/main/res/values/strings.xmlnew file mode 100644index 000000000..ccd9b42d4--- /dev/null+++ b/addons/brightness/app/src/main/res/values/strings.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">Brightness</string>+ <string name="channel_name">Screen dimming</string>+ <string name="notification_text">Dimming the screen. Open Brightness to change or switch off.</string>+</resources>diff --git a/addons/brightness/app/src/main/res/xml/module_card.xml b/addons/brightness/app/src/main/res/xml/module_card.xmlnew file mode 100644index 000000000..1c733f53c--- /dev/null+++ b/addons/brightness/app/src/main/res/xml/module_card.xml@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="utf-8"?>+<card spec="1" label="Brightness" caption="Dim and night mode" accent="#F5A524" />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.javanew file mode 100644index 000000000..25816f722--- /dev/null+++ b/addons/brightness/app/src/test/java/io/github/maxhayim/brightness/DimmingTest.java@@ -0,0 +1,167 @@+package io.github.maxhayim.brightness;++import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertFalse;+import static org.junit.Assert.assertTrue;++import org.junit.Test;++public class DimmingTest {+ private static Dimming.Settings on() {+ Dimming.Settings s = new Dimming.Settings();+ s.on = true;+ return s;+ }++ private static int alpha(int color) {+ return color >>> 24;+ }++ @Test+ public void offDrawsNothingWhateverTheRestSays() {+ Dimming.Settings s = new Dimming.Settings();+ s.night = Dimming.Night.ON;+ s.brightness = s.nightBrightness = 20;+ s.warmth = 100;+ Dimming.Level l = Dimming.level(s, 0);+ assertFalse(l.visible());+ assertEquals(0, Dimming.color(l));+ assertFalse(Dimming.needsService(s, 0));+ }++ @Test+ public void fullBrightnessAndNoWarmthIsNoLayer() {+ Dimming.Settings s = on();+ s.night = Dimming.Night.OFF;+ s.brightness = 100;+ assertFalse(Dimming.level(s, 600).visible());+ assertFalse("no layer and no schedule: the service stops", Dimming.needsService(s, 600));+ }++ @Test+ public void plainDimmingIsBlackAtTheMissingBrightness() {+ int c = Dimming.color(new Dimming.Level(70, 0, false));+ assertEquals(Math.round(0.3 * 255), alpha(c));+ assertEquals(0, c & 0xFFFFFF);+ }++ @Test+ public void warmthIsAmberAndAddsToTheDimming() {+ int dimOnly = Dimming.color(new Dimming.Level(40, 0, true));+ int warm = Dimming.color(new Dimming.Level(40, 50, true));+ assertTrue(alpha(warm) > alpha(dimOnly));+ int r = (warm >> 16) & 0xFF, g = (warm >> 8) & 0xFF, b = warm & 0xFF;+ assertTrue(r > g && g > b);+ // Warmth alone, at full brightness: amber at its full share and nothing else.+ int pure = Dimming.color(new Dimming.Level(100, 100, true));+ assertEquals(Math.round(Dimming.MAX_WARM_ALPHA * 255), alpha(pure));+ assertEquals(Dimming.WARM_RGB, pure & 0xFFFFFF);+ }++ @Test+ public void theColourMatchesTwoLayersDrawnInTurn() {+ // A grey picture under amber at the warm alpha, then black at 1 - brightness: the folded colour must agree.+ double picture = 200, warmA = Dimming.MAX_WARM_ALPHA * 0.6, blackA = 1 - 0.5;+ double red = ((1 - blackA) * ((1 - warmA) * picture + warmA * 0xFF));+ int c = Dimming.color(new Dimming.Level(50, 60, true));+ double a = alpha(c) / 255.0;+ double folded = (1 - a) * picture + a * ((c >> 16) & 0xFF);+ assertEquals(red, folded, 2.0);+ }++ @Test+ public void neverDarkerThanTheFloor() {+ Dimming.Settings s = on();+ s.brightness = 0;+ s.nightBrightness = -50;+ s.warmth = 400;+ s.clamped();+ assertEquals(Dimming.MIN_BRIGHTNESS, s.brightness);+ assertEquals(Dimming.MIN_BRIGHTNESS, s.nightBrightness);+ assertEquals(100, s.warmth);+ int black = alpha(Dimming.color(new Dimming.Level(Dimming.MIN_BRIGHTNESS, 0, false)));+ assertEquals(Math.round(0.8 * 255), black);+ }++ @Test+ public void clampingSnapsToStepsAndWrapsTimes() {+ Dimming.Settings s = on();+ s.brightness = 73;+ s.nightStart = -15;+ s.nightEnd = Dimming.DAY_MINUTES + 30;+ s.night = null;+ s.clamped();+ assertEquals(75, s.brightness);+ assertEquals(23 * 60 + 45, s.nightStart);+ assertEquals(30, s.nightEnd);+ assertEquals(Dimming.Night.SCHEDULED, s.night);+ }++ @Test+ public void windowPastMidnight() {+ int start = 21 * 60, end = 7 * 60;+ assertFalse(Dimming.inWindow(start, end, 20 * 60 + 59));+ assertTrue(Dimming.inWindow(start, end, 21 * 60));+ assertTrue(Dimming.inWindow(start, end, 0));+ assertTrue(Dimming.inWindow(start, end, 6 * 60 + 59));+ assertFalse(Dimming.inWindow(start, end, 7 * 60));+ }++ @Test+ public void windowWithinOneDayAndEmptyWindow() {+ assertTrue(Dimming.inWindow(13 * 60, 15 * 60, 14 * 60));+ assertFalse(Dimming.inWindow(13 * 60, 15 * 60, 15 * 60));+ assertFalse(Dimming.inWindow(13 * 60, 15 * 60, 12 * 60));+ assertFalse(Dimming.inWindow(600, 600, 600));+ }++ @Test+ public void scheduledNightUsesTheNightValues() {+ Dimming.Settings s = on();+ Dimming.Level night = Dimming.level(s, 23 * 60);+ assertTrue(night.night);+ assertEquals(s.nightBrightness, night.brightness);+ assertEquals(s.warmth, night.warmth);+ Dimming.Level day = Dimming.level(s, 12 * 60);+ assertFalse(day.night);+ assertEquals(s.brightness, day.brightness);+ assertEquals("no warmth by day", 0, day.warmth);+ }++ @Test+ public void nightModeOnAndOffIgnoreTheClock() {+ Dimming.Settings s = on();+ s.night = Dimming.Night.ON;+ assertTrue(Dimming.level(s, 12 * 60).night);+ s.night = Dimming.Night.OFF;+ assertFalse(Dimming.level(s, 23 * 60).night);+ assertEquals(-1, Dimming.minutesToNextChange(s, 0));+ }++ @Test+ public void nextChangeIsTheNearerEdgeOfTheWindow() {+ Dimming.Settings s = on();+ assertEquals(60, Dimming.minutesToNextChange(s, 20 * 60));+ assertEquals(8 * 60, Dimming.minutesToNextChange(s, 23 * 60));+ // Exactly on an edge: the next one is the other edge, never zero.+ assertEquals(10 * 60, Dimming.minutesToNextChange(s, 21 * 60));+ assertEquals(14 * 60, Dimming.minutesToNextChange(s, 7 * 60));+ }++ @Test+ public void aScheduleKeepsTheServiceEvenWithNothingToDrawYet() {+ Dimming.Settings s = on();+ s.brightness = 100;+ assertFalse(Dimming.level(s, 12 * 60).visible());+ assertTrue(Dimming.needsService(s, 12 * 60));+ }++ @Test+ public void clockFormats() {+ assertEquals("07:05", Dimming.clock(7 * 60 + 5, true));+ assertEquals("21:00", Dimming.clock(21 * 60, true));+ assertEquals("12:00 AM", Dimming.clock(0, false));+ assertEquals("12:30 PM", Dimming.clock(12 * 60 + 30, false));+ assertEquals("9:00 PM", Dimming.clock(21 * 60, false));+ }+}diff --git a/addons/brightness/build.gradle b/addons/brightness/build.gradlenew file mode 100644index 000000000..48978475f--- /dev/null+++ b/addons/brightness/build.gradle@@ -0,0 +1,3 @@+plugins {+ id 'com.android.application' version '8.5.2' apply false+}diff --git a/addons/brightness/gradle.properties b/addons/brightness/gradle.propertiesnew file mode 100644index 000000000..18825f968--- /dev/null+++ b/addons/brightness/gradle.properties@@ -0,0 +1,3 @@+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8+android.useAndroidX=true+android.nonTransitiveRClass=truediff --git a/addons/brightness/gradle/wrapper/gradle-wrapper.jar b/addons/brightness/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 000000000..2c3521197Binary files /dev/null and b/addons/brightness/gradle/wrapper/gradle-wrapper.jar differdiff --git a/addons/brightness/gradle/wrapper/gradle-wrapper.properties b/addons/brightness/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 000000000..77f5d0ba6--- /dev/null+++ b/addons/brightness/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/distsdiff --git a/addons/brightness/gradlew b/addons/brightness/gradlewnew file mode 100755index 000000000..f5feea6d6--- /dev/null+++ b/addons/brightness/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/brightness/gradlew.bat b/addons/brightness/gradlew.batnew file mode 100644index 000000000..9d21a2183--- /dev/null+++ b/addons/brightness/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++:omegadiff --git a/addons/brightness/install.sh b/addons/brightness/install.shnew file mode 100755index 000000000..81bc1e161--- /dev/null+++ b/addons/brightness/install.sh@@ -0,0 +1,27 @@+#!/usr/bin/env bash+# Build Brightness, install it on the TV and allow it to draw over other apps (many TVs hide that setting).+# TV_HOST=<tv ip> addons/brightness/install.sh+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.brightness+# Script paths stay relative: with MSYS_NO_PATHCONV, Git Bash would hand Windows Python a /c/... path.+tv() { "$PY" -I ../../tools/tv.py "$@"; }++[ -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/brightness.apk+OUT=$(tv 'pm install -r /data/local/tmp/brightness.apk; rm -f /data/local/tmp/brightness.apk')+echo "$OUT"+case "$OUT" in *Success*) ;; *) echo "ERROR: pm install failed" >&2; exit 1 ;; esac++# Display over other apps, and TCL's auto-start so the schedule comes back after a reboot.+tv "appops set $PKG SYSTEM_ALERT_WINDOW allow; cmd appops set $PKG APP_AUTO_START allow 2>/dev/null; echo permissions granted"+tv "am start -n $PKG/.MainActivity >/dev/null; echo opened"+echo "Installed. Brightness is open on the TV; press Home and answer Show card for the card."diff --git a/addons/brightness/settings.gradle b/addons/brightness/settings.gradlenew file mode 100644index 000000000..ed72f22ee--- /dev/null+++ b/addons/brightness/settings.gradle@@ -0,0 +1,16 @@+pluginManagement {+ repositories {+ google()+ mavenCentral()+ gradlePluginPortal()+ }+}+dependencyResolutionManagement {+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)+ repositories {+ google()+ mavenCentral()+ }+}+rootProject.name = "brightness"+include ':app'