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: Quiet Hours
מקס חיים2e6c9eb413d3
diff --git a/addons/README.md b/addons/README.mdindex c3f00031d..127125f13 100644--- a/addons/README.md+++ b/addons/README.md@@ -20,6 +20,7 @@ the core bigger or change how it behaves. You install an add-on only if you want| [TV Static](tv-static/) | An off-the-air moment each time the screen turns on: the picture opens from a bright line, snow and hiss, colour bars or an old "no signal" screen for 3 to 10 s, then fades into what was on screen; the card sets style, sound and length | [@luyzfernando08](https://github.com/luyzfernando08) | Xiaomi Mi Box S (Android TV 9), Philco by Skyworth (Android TV 14) | foreground service (screen-on watcher), start at boot, display over other apps | <img src="tv-static/screenshot.jpg" width="240" alt="TV Static on a TV"> || [Brightness](brightness/) | Dims the picture below the TV's own minimum over every app (and the picture settings on Realtek TVs), with a warm night mode on a schedule and a one-press normal screen | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | overlay, foreground service, start at boot | <img src="brightness/screenshot.jpg" width="240" alt="Brightness on a TV"> || [Sleep Timer](sleep-timer/) | A sleep timer: 15 to 120 minutes, a one-minute countdown over what is playing with "15 more minutes", then standby; over HDMI-CEC the TV turns off with the box | [@luyzfernando08](https://github.com/luyzfernando08) | Xiaomi Mi Box S (Android TV 9) | accessibility (lock-screen action only), display over other apps, exact alarms | <img src="sleep-timer/screenshot.jpg" width="240" alt="Sleep Timer on a TV"> |+| [Quiet Hours](quiet-hours/) | A volume cap for the night (or all day): the volume is brought back down to the cap whenever it goes above, a muted TV is left alone, headphones can stay uncapped | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | foreground service, start at boot | <img src="quiet-hours/screenshot.jpg" width="240" alt="Quiet Hours on a TV"> |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/quiet-hours/.gitignore b/addons/quiet-hours/.gitignorenew file mode 100644index 000000000..a7e04a21b--- /dev/null+++ b/addons/quiet-hours/.gitignore@@ -0,0 +1,4 @@+.gradle/+build/+app/build/+local.propertiesdiff --git a/addons/quiet-hours/README.md b/addons/quiet-hours/README.mdnew file mode 100644index 000000000..8ed94ad9c--- /dev/null+++ b/addons/quiet-hours/README.md@@ -0,0 +1,65 @@+# Quiet Hours++A volume cap for the night: from 20:00 to 07:00 (or all day, or never) the TV's media volume can't go above the+level you set. A press of Volume Up, an app that starts loud or a loud advert is brought back down to the cap at+once. The cap never raises a quieter volume, and headphones can stay uncapped, since they don't wake the room. For+the [Clean Your TV](../../README.md) launcher it declares a [module card](../../docs/modules.md): once you answer+**Show card** its tile reads "Quiet Hours" with a violet glow. On any other Android TV home it is an ordinary app.++++| Row | What it does |+|---|---|+| **Quiet hours** | Off, Scheduled (every day between the times below) or Always. Focused first. |+| **Volume cap** | The loudest the TV may play, 5 % to 100 % of its volume range in 5 % steps (◀ ▶). The line under it says which volume step that is on this TV. Never 0, so a cap can't look like a broken TV. |+| **Starts**, **Ends** | The schedule, in 15 minute steps; 20:00 to 07:00 by default, and a window may run past midnight. |+| **Headphones** | No cap (the default) or Capped too, for Bluetooth, wired and USB headphones. |++The line at the top shows the volume now and whether the cap applies, and follows the remote's volume keys while+the screen is open. It pairs with [Headphones](../headphones/) (its quiet guard pauses and mutes when headphones+drop) and [Brightness](../brightness/) (a dim, warm night picture).++## Permissions++| Permission | Why |+|---|---|+| Foreground service (`FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SPECIAL_USE`) | One service listens for volume changes and brings the volume back to the cap. It runs while Quiet Hours is on (Scheduled or Always) and stops when it is switched off. |+| Start at boot (`RECEIVE_BOOT_COMPLETED`) | To put the cap back after a reboot or an update. |++Changing the media volume needs no permission. No internet permission: nothing leaves the TV. No accounts,+telemetry, ads or libraries. Settings stay in the app's own storage (backups are 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/quiet-hours/install.sh+```++It builds the add-on, installs it (and allows TCL's auto-start), and opens it. Press Home: the launcher asks once+whether to show the card. To build only: `cd addons/quiet-hours && ./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.++## Limits++- **Fixed volume.** When the TV's sound goes through HDMI ARC or an amplifier, Android reports a fixed volume and+ no app can change it; the screen says so and the cap does nothing. Set the amplifier's own maximum instead.+- **A muted TV is left alone.** On Android, setting a muted stream's volume can unmute it, so the cap waits:+ unmuting is a volume change, and the volume comes down to the cap then.+- **A moment above the cap.** The cap follows the volume change; a very loud start can be heard for a fraction of+ a second before it comes down.+- **One output at a time.** Android keeps a volume per output; the cap applies to the one playing now and to each+ output as it starts playing.+- **Memory managers** on 1 GB TVs can stop the service. The cap then stops until the app is opened or the TV+ restarts.++## Tested on++MOKA R8G (Android 14), over ADB, on a home app that implements the module-card spec: the card prompt and the card, the screen with the volume line, and the service running while Quiet Hours is Scheduled. Testing found that lowering a muted stream's volume can unmute it on Android, so the cap now leaves a muted TV alone (a JVM test covers it). The volume being brought down to the cap was not tried with sound: the test TV stays muted because a baby sleeps nearby. The JVM tests cover the decisions (the window past midnight, the cap as a volume step, never silence, headphones, fixed volume, muted).++## Maintainer++[@maxhayim](https://github.com/maxhayim)diff --git a/addons/quiet-hours/app/build.gradle b/addons/quiet-hours/app/build.gradlenew file mode 100644index 000000000..81bb31d1d--- /dev/null+++ b/addons/quiet-hours/app/build.gradle@@ -0,0 +1,36 @@+plugins {+ id 'com.android.application'+}++android {+ namespace 'io.github.maxhayim.quiethours'+ compileSdk 34++ defaultConfig {+ applicationId 'io.github.maxhayim.quiethours'+ 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/quiet-hours/app/proguard-rules.pro b/addons/quiet-hours/app/proguard-rules.pronew file mode 100644index 000000000..a4435d69a--- /dev/null+++ b/addons/quiet-hours/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/quiet-hours/app/src/main/AndroidManifest.xml b/addons/quiet-hours/app/src/main/AndroidManifest.xmlnew file mode 100644index 000000000..fc9c68cc4--- /dev/null+++ b/addons/quiet-hours/app/src/main/AndroidManifest.xml@@ -0,0 +1,53 @@+<?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" />++ <!-- One foreground service watches the volume while a cap applies or a schedule runs. -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />+ <!-- Put the cap 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=".CapService"+ android:exported="false"+ android:foregroundServiceType="specialUse">+ <property+ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"+ android:value="Keeps the media volume under a user-chosen cap during quiet hours" />+ </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>+ </application>+</manifest>diff --git a/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/BootReceiver.java b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/BootReceiver.javanew file mode 100644index 000000000..fcaf0eda2--- /dev/null+++ b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/BootReceiver.java@@ -0,0 +1,16 @@+package io.github.maxhayim.quiethours;++import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;++/** Puts the cap and the schedule back after a reboot or an update of this app. */+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)) {+ CapService.start(context);+ }+ }+}diff --git a/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/CapService.java b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/CapService.javanew file mode 100644index 000000000..cf06cdcb9--- /dev/null+++ b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/CapService.java@@ -0,0 +1,141 @@+package io.github.maxhayim.quiethours;++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.media.AudioDeviceInfo;+import android.media.AudioManager;+import android.os.Build;+import android.os.Handler;+import android.os.IBinder;+import android.os.Looper;+import android.util.Log;++import java.util.Calendar;++/**+ * Keeps the media volume under the cap: whenever the volume changes (the remote, an app, an ad) or the output+ * changes, it checks and brings the volume back down to the cap if needed. Also checks at each start and end of+ * the quiet hours. Runs while Quiet Hours is on, and stops itself when it is switched off.+ */+public class CapService extends Service {+ private static final String CHANNEL = "cap";+ /** Sent by the system on every volume change; not in the SDK's constants but sent on every Android version. */+ private static final String VOLUME_CHANGED = "android.media.VOLUME_CHANGED_ACTION";+ private static final String DEVICES_CHANGED = "android.media.STREAM_DEVICES_CHANGED_ACTION";+ private static final long MAX_WAIT_MS = 5 * 60_000L;++ private final Handler main = new Handler(Looper.getMainLooper());+ private AudioManager audio;+ /** Kept in a field: SharedPreferences holds its listeners weakly. */+ private final SharedPreferences.OnSharedPreferenceChangeListener prefsListener = (p, key) -> check();+ private final Runnable tick = this::check;+ private final BroadcastReceiver changes = new BroadcastReceiver() {+ @Override+ public void onReceive(Context context, Intent intent) {+ check();+ }+ };++ static void start(Context c) {+ if (!Quiet.needsService(Prefs.load(c))) return;+ try {+ c.startForegroundService(new Intent(c, CapService.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());+ }+ }++ @Override+ public void onCreate() {+ super.onCreate();+ audio = getSystemService(AudioManager.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(1, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);+ else startForeground(1, n);+ Prefs.of(this).registerOnSharedPreferenceChangeListener(prefsListener);+ IntentFilter f = new IntentFilter();+ f.addAction(VOLUME_CHANGED);+ f.addAction(DEVICES_CHANGED);+ f.addAction(Intent.ACTION_TIME_CHANGED);+ f.addAction(Intent.ACTION_TIMEZONE_CHANGED);+ f.addAction(Intent.ACTION_SCREEN_ON);+ registerReceiver(changes, f);+ }++ @Override+ public int onStartCommand(Intent intent, int flags, int startId) {+ check();+ return START_STICKY;+ }++ @Override+ public void onDestroy() {+ main.removeCallbacks(tick);+ Prefs.of(this).unregisterOnSharedPreferenceChangeListener(prefsListener);+ unregisterReceiver(changes);+ super.onDestroy();+ }++ @Override+ public IBinder onBind(Intent intent) {+ return null;+ }++ private void check() {+ main.removeCallbacks(tick);+ Quiet.Settings s = Prefs.load(this);+ if (!Quiet.needsService(s)) {+ stopSelf();+ return;+ }+ int minute = minuteNow();+ int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);+ int volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);+ if (Quiet.mustLower(s, minute, volume, max, onHeadphones(audio), audio.isVolumeFixed(),+ audio.isStreamMute(AudioManager.STREAM_MUSIC))) {+ int cap = Quiet.capIndex(s.cap, max);+ audio.setStreamVolume(AudioManager.STREAM_MUSIC, cap, AudioManager.FLAG_SHOW_UI);+ Log.i(Prefs.TAG, "volume " + volume + " lowered to the cap " + cap + " of " + max);+ }+ int next = Quiet.minutesToNextChange(s, minute);+ long wait = MAX_WAIT_MS;+ if (next > 0) {+ Calendar now = Calendar.getInstance();+ wait = Math.min(wait, next * 60_000L - now.get(Calendar.SECOND) * 1000L - now.get(Calendar.MILLISECOND));+ }+ main.postDelayed(tick, Math.max(1000, wait));+ }++ /** True while headphones (Bluetooth, wired or USB) are connected, which is where Android sends media then. */+ static boolean onHeadphones(AudioManager audio) {+ for (AudioDeviceInfo d : audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {+ int t = d.getType();+ if (t == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP || t == AudioDeviceInfo.TYPE_WIRED_HEADPHONES+ || t == AudioDeviceInfo.TYPE_WIRED_HEADSET || t == AudioDeviceInfo.TYPE_USB_HEADSET) return true;+ if (Build.VERSION.SDK_INT >= 31 && t == AudioDeviceInfo.TYPE_BLE_HEADSET) return true;+ }+ return false;+ }++ static int minuteNow() {+ Calendar c = Calendar.getInstance();+ return c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE);+ }+}diff --git a/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/MainActivity.java b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/MainActivity.javanew file mode 100644index 000000000..42941120e--- /dev/null+++ b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/MainActivity.java@@ -0,0 +1,156 @@+package io.github.maxhayim.quiethours;++import android.app.Activity;+import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;+import android.content.IntentFilter;+import android.media.AudioManager;+import android.os.Bundle;+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 worked with the remote. The first row switches Quiet Hours off,+ * on a schedule, or always; Left and Right change values. No text fields and nothing to type.+ */+public class MainActivity extends Activity {+ private Quiet.Settings s;+ private AudioManager audio;+ private TextView status;+ private Row modeRow, capRow, startRow, endRow, headphonesRow;+ /** The volume line follows the remote's volume keys while this screen is open. */+ private final BroadcastReceiver volume = new BroadcastReceiver() {+ @Override+ public void onReceive(Context context, Intent intent) {+ refresh();+ }+ };++ @Override+ protected void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+ audio = getSystemService(AudioManager.class);+ 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);+ LinearLayout 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);++ s = Prefs.load(this);+ modeRow = add(rows, new Row(this, "Quiet hours", null, false, () -> {+ s.mode = Quiet.Mode.values()[(s.mode.ordinal() + 1) % 3];+ changed();+ }, d -> {+ s.mode = Quiet.Mode.values()[(s.mode.ordinal() + d + 3) % 3];+ changed();+ }));+ capRow = add(rows, new Row(this, "Volume cap", "The loudest the TV may play during quiet hours.", true, null,+ d -> {+ s.cap += d * Quiet.CAP_STEP;+ changed();+ }));+ startRow = add(rows, new Row(this, "Starts", "◀ ▶ moves 15 minutes.", false, null, d -> {+ s.start += d * Quiet.TIME_STEP;+ changed();+ }));+ endRow = add(rows, new Row(this, "Ends", null, false, null, d -> {+ s.end += d * Quiet.TIME_STEP;+ changed();+ }));+ headphonesRow = add(rows, new Row(this, "Headphones", "Headphones don't wake the room, so they can go louder.",+ false, () -> {+ s.headphonesFree = !s.headphonesFree;+ changed();+ }, null));+ modeRow.requestFocus();+ }++ @Override+ protected void onResume() {+ super.onResume();+ s = Prefs.load(this);+ registerReceiver(volume, new IntentFilter("android.media.VOLUME_CHANGED_ACTION"));+ refresh();+ CapService.start(this);+ }++ @Override+ protected void onPause() {+ unregisterReceiver(volume);+ super.onPause();+ }++ private Row add(LinearLayout rows, 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 Quiet Hours is on. */+ private void changed() {+ Prefs.save(this, s);+ refresh();+ CapService.start(this);+ }++ private void refresh() {+ boolean h24 = DateFormat.is24HourFormat(this);+ int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);+ int vol = audio.getStreamVolume(AudioManager.STREAM_MUSIC);+ int cap = Quiet.capIndex(s.cap, max);+ modeRow.setValue(s.mode == Quiet.Mode.OFF ? "Off" : s.mode == Quiet.Mode.ALWAYS ? "Always" : "Scheduled");+ modeRow.setDetail(s.mode == Quiet.Mode.SCHEDULED ? "Every day between the times below."+ : s.mode == Quiet.Mode.ALWAYS ? "The cap applies all day." : "No cap.");+ capRow.setValue(s.cap + " %");+ capRow.setDetail("The loudest the TV may play during quiet hours: step " + cap + " of " + max + ".");+ capRow.setBar(s.cap / 100f);+ startRow.setValue(Quiet.clock(s.start, h24));+ endRow.setValue(Quiet.clock(s.end, h24));+ boolean scheduled = s.mode == Quiet.Mode.SCHEDULED;+ startRow.setAlpha(scheduled ? 1f : 0.5f);+ endRow.setAlpha(scheduled ? 1f : 0.5f);+ headphonesRow.setValue(s.headphonesFree ? "No cap" : "Capped too");++ String now = "Volume " + vol + " of " + max + ". ";+ if (audio.isVolumeFixed()) {+ status.setText("This TV's volume is fixed (HDMI ARC or an amplifier), so Android can't cap it.");+ } else if (s.mode == Quiet.Mode.OFF) {+ status.setText(now + "Quiet hours are off.");+ } else if (Quiet.capNow(s, CapService.minuteNow())) {+ String until = scheduled ? " until " + Quiet.clock(s.end, h24) : "";+ String free = CapService.onHeadphones(audio) && s.headphonesFree ? " Headphones: no cap." : "";+ status.setText(now + "Capped at " + cap + until + "." + free);+ } else {+ status.setText(now + "Quiet hours from " + Quiet.clock(s.start, h24) + ".");+ }+ }++ private int px(int dp) {+ return Math.round(dp * getResources().getDisplayMetrics().density);+ }+}diff --git a/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Prefs.java b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Prefs.javanew file mode 100644index 000000000..ada48ea8e--- /dev/null+++ b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Prefs.java@@ -0,0 +1,42 @@+package io.github.maxhayim.quiethours;++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 checks again. */+final class Prefs {+ static final String TAG = "QuietHours";++ private Prefs() {+ }++ static SharedPreferences of(Context c) {+ return c.getSharedPreferences("quiet", Context.MODE_PRIVATE);+ }++ static Quiet.Settings load(Context c) {+ SharedPreferences p = of(c);+ Quiet.Settings s = new Quiet.Settings();+ try {+ s.mode = Quiet.Mode.valueOf(p.getString("mode", s.mode.name()));+ } catch (IllegalArgumentException e) {+ s.mode = Quiet.Mode.SCHEDULED;+ }+ s.cap = p.getInt("cap", s.cap);+ s.start = p.getInt("start", s.start);+ s.end = p.getInt("end", s.end);+ s.headphonesFree = p.getBoolean("headphones_free", s.headphonesFree);+ return s.clamped();+ }++ static void save(Context c, Quiet.Settings s) {+ s.clamped();+ of(c).edit()+ .putString("mode", s.mode.name())+ .putInt("cap", s.cap)+ .putInt("start", s.start)+ .putInt("end", s.end)+ .putBoolean("headphones_free", s.headphonesFree)+ .apply();+ }+}diff --git a/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Quiet.java b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Quiet.javanew file mode 100644index 000000000..4648e9143--- /dev/null+++ b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Quiet.java@@ -0,0 +1,101 @@+package io.github.maxhayim.quiethours;++import java.util.Locale;++/**+ * The settings and the decisions, with no Android types, so the JVM tests cover all of it: whether the cap applies+ * at a given minute, the cap as a volume step, whether a volume must come down, and when the schedule next changes.+ */+final class Quiet {+ static final int DAY_MINUTES = 24 * 60;+ static final int TIME_STEP = 15;+ static final int CAP_STEP = 5;+ /** The lowest cap: 5 % of the TV's range, never silence, so a cap can't look like a broken TV. */+ static final int MIN_CAP = 5;++ enum Mode { OFF, SCHEDULED, ALWAYS }++ static final class Settings {+ Mode mode = Mode.SCHEDULED;+ /** The highest volume allowed, in percent of the TV's media volume range. */+ int cap = 20;+ int start = 20 * 60;+ int end = 7 * 60;+ /** Headphones don't wake the room: no cap while sound goes to them. */+ boolean headphonesFree = true;++ Settings clamped() {+ if (mode == null) mode = Mode.SCHEDULED;+ cap = clamp(Math.round(cap / (float) CAP_STEP) * CAP_STEP, MIN_CAP, 100);+ start = wrap(Math.round(start / (float) TIME_STEP) * TIME_STEP);+ end = wrap(Math.round(end / (float) TIME_STEP) * TIME_STEP);+ return this;+ }+ }++ private Quiet() {+ }++ /** True from start up to, not including, end; a window may run past midnight. start == end is never. */+ 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 capNow(Settings s, int minute) {+ switch (s.mode) {+ case ALWAYS:+ return true;+ case SCHEDULED:+ return inWindow(s.start, s.end, minute);+ default:+ return false;+ }+ }++ /** The cap as a volume step of a stream that goes 0 to max: at least step 1, so it is never silence. */+ static int capIndex(int capPercent, int max) {+ if (max <= 0) return 0;+ return clamp(Math.round(capPercent * max / 100f), 1, max);+ }++ /**+ * True when the volume must come down to the cap right now. Never while muted: on Android, setting a muted+ * stream's volume can unmute it, so the cap waits for the unmute, which is itself a volume change.+ */+ static boolean mustLower(Settings s, int minute, int volume, int max, boolean onHeadphones, boolean fixedVolume,+ boolean muted) {+ if (fixedVolume || muted || !capNow(s, minute)) return false;+ if (onHeadphones && s.headphonesFree) return false;+ return volume > capIndex(s.cap, max);+ }++ /** Minutes until the cap can start or stop by itself; -1 when it never does on its own. */+ static int minutesToNextChange(Settings s, int minute) {+ if (s.mode != Mode.SCHEDULED || s.start == s.end) return -1;+ int toStart = wrap(s.start - minute);+ int toEnd = wrap(s.end - minute);+ if (toStart == 0) toStart = DAY_MINUTES;+ if (toEnd == 0) toEnd = DAY_MINUTES;+ return Math.min(toStart, toEnd);+ }++ /** The service runs while a cap applies or a schedule waits for its start. */+ static boolean needsService(Settings s) {+ return s.mode != Mode.OFF;+ }++ static String clock(int minute, boolean h24) {+ int h = minute / 60, m = minute % 60;+ if (h24) return String.format(Locale.ROOT, "%02d:%02d", h, m);+ return String.format(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;+ }+}diff --git a/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Row.java b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Row.javanew file mode 100644index 000000000..d61110f3e--- /dev/null+++ b/addons/quiet-hours/app/src/main/java/io/github/maxhayim/quiethours/Row.java@@ -0,0 +1,103 @@+package io.github.maxhayim.quiethours;++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(0xFF8E7CFF);+ 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/quiet-hours/app/src/main/res/drawable/banner.xml b/addons/quiet-hours/app/src/main/res/drawable/banner.xmlnew file mode 100644index 000000000..0c3725880--- /dev/null+++ b/addons/quiet-hours/app/src/main/res/drawable/banner.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- 16:9 banner: a speaker with a volume bar stopped under a line, under a crescent moon. 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="#1E2630" android:pathData="M24,24h272v132h-272z" />+ <path android:fillColor="#8E7CFF" android:pathData="M70,78h18l22,-18v60l-22,-18h-18z" />+ <path android:fillColor="#8E7CFF" android:pathData="M132,110h20v10h-20zM160,100h20v20h-20zM188,90h20v30h-20z" />+ <path android:fillColor="#3A4654" android:pathData="M216,80h20v40h-20zM244,70h20v50h-20z" />+ <path android:strokeColor="#FFFFFF" android:strokeWidth="3" android:fillColor="#00000000" android:pathData="M126,84h146" />+ <path android:fillColor="#FFFFFF" android:pathData="M262,36a14,14 0 1 0 12,22a11,11 0 1 1 -12,-22z" />+</vector>diff --git a/addons/quiet-hours/app/src/main/res/drawable/ic_foreground.xml b/addons/quiet-hours/app/src/main/res/drawable/ic_foreground.xmlnew file mode 100644index 000000000..2b1fb62da--- /dev/null+++ b/addons/quiet-hours/app/src/main/res/drawable/ic_foreground.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- A speaker under a crescent moon 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="#8E7CFF" android:pathData="M36,50h10l12,-10v32l-12,-10h-10z" />+ <path android:fillColor="#FFFFFF" android:pathData="M66,38a8,8 0 1 0 7,13a6,6 0 1 1 -7,-13z" />+</vector>diff --git a/addons/quiet-hours/app/src/main/res/drawable/row_background.xml b/addons/quiet-hours/app/src/main/res/drawable/row_background.xmlnew file mode 100644index 000000000..03ccab9f5--- /dev/null+++ b/addons/quiet-hours/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/quiet-hours/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/addons/quiet-hours/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmlnew file mode 100644index 000000000..0a99b20b1--- /dev/null+++ b/addons/quiet-hours/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/quiet-hours/app/src/main/res/values/strings.xml b/addons/quiet-hours/app/src/main/res/values/strings.xmlnew file mode 100644index 000000000..a05c916b2--- /dev/null+++ b/addons/quiet-hours/app/src/main/res/values/strings.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">Quiet Hours</string>+ <string name="channel_name">Volume cap</string>+ <string name="notification_text">Keeping the volume under the cap. Open Quiet Hours to change it.</string>+</resources>diff --git a/addons/quiet-hours/app/src/main/res/xml/module_card.xml b/addons/quiet-hours/app/src/main/res/xml/module_card.xmlnew file mode 100644index 000000000..1632d3aab--- /dev/null+++ b/addons/quiet-hours/app/src/main/res/xml/module_card.xml@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="utf-8"?>+<card spec="1" label="Quiet Hours" caption="Volume cap" accent="#8E7CFF" />diff --git a/addons/quiet-hours/app/src/test/java/io/github/maxhayim/quiethours/QuietTest.java b/addons/quiet-hours/app/src/test/java/io/github/maxhayim/quiethours/QuietTest.javanew file mode 100644index 000000000..6a3cf1907--- /dev/null+++ b/addons/quiet-hours/app/src/test/java/io/github/maxhayim/quiethours/QuietTest.java@@ -0,0 +1,94 @@+package io.github.maxhayim.quiethours;++import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertFalse;+import static org.junit.Assert.assertTrue;++import org.junit.Test;++public class QuietTest {+ private static final int NIGHT = 23 * 60, DAY = 12 * 60;++ @Test+ public void defaultsCapFromEightToSeven() {+ Quiet.Settings s = new Quiet.Settings();+ assertTrue(Quiet.capNow(s, 20 * 60));+ assertTrue(Quiet.capNow(s, NIGHT));+ assertTrue(Quiet.capNow(s, 6 * 60 + 59));+ assertFalse(Quiet.capNow(s, 7 * 60));+ assertFalse(Quiet.capNow(s, DAY));+ }++ @Test+ public void modes() {+ Quiet.Settings s = new Quiet.Settings();+ s.mode = Quiet.Mode.ALWAYS;+ assertTrue(Quiet.capNow(s, DAY));+ assertEquals(-1, Quiet.minutesToNextChange(s, DAY));+ s.mode = Quiet.Mode.OFF;+ assertFalse(Quiet.capNow(s, NIGHT));+ assertFalse(Quiet.needsService(s));+ }++ @Test+ public void capIsAVolumeStepAndNeverSilence() {+ assertEquals(20, Quiet.capIndex(20, 100));+ assertEquals(3, Quiet.capIndex(20, 15));+ assertEquals(1, Quiet.capIndex(5, 15));+ assertEquals(15, Quiet.capIndex(100, 15));+ assertEquals(0, Quiet.capIndex(20, 0));+ }++ @Test+ public void lowersOnlyAboveTheCapDuringQuietHours() {+ Quiet.Settings s = new Quiet.Settings();+ assertTrue(Quiet.mustLower(s, NIGHT, 21, 100, false, false, false));+ assertFalse(Quiet.mustLower(s, NIGHT, 20, 100, false, false, false));+ assertFalse("never raises a lower volume", Quiet.mustLower(s, NIGHT, 5, 100, false, false, false));+ assertFalse(Quiet.mustLower(s, DAY, 90, 100, false, false, false));+ }++ @Test+ public void headphonesAndFixedVolume() {+ Quiet.Settings s = new Quiet.Settings();+ assertFalse(Quiet.mustLower(s, NIGHT, 80, 100, true, false, false));+ s.headphonesFree = false;+ assertTrue(Quiet.mustLower(s, NIGHT, 80, 100, true, false, false));+ assertFalse("ARC: Android can't change it", Quiet.mustLower(s, NIGHT, 80, 100, false, true, false));+ }++ @Test+ public void neverTouchesAMutedTv() {+ Quiet.Settings s = new Quiet.Settings();+ assertFalse("lowering could unmute it", Quiet.mustLower(s, NIGHT, 80, 100, false, false, true));+ assertTrue("capped as soon as it's unmuted", Quiet.mustLower(s, NIGHT, 80, 100, false, false, false));+ }++ @Test+ public void nextChangeIsTheNearerEdge() {+ Quiet.Settings s = new Quiet.Settings();+ assertEquals(60, Quiet.minutesToNextChange(s, 19 * 60));+ assertEquals(8 * 60, Quiet.minutesToNextChange(s, NIGHT));+ assertEquals(11 * 60, Quiet.minutesToNextChange(s, 20 * 60));+ }++ @Test+ public void storedValuesAreClamped() {+ Quiet.Settings s = new Quiet.Settings();+ s.cap = 0;+ s.start = -15;+ s.end = 24 * 60 + 7;+ s.mode = null;+ s.clamped();+ assertEquals(Quiet.MIN_CAP, s.cap);+ assertEquals(23 * 60 + 45, s.start);+ assertEquals(0, s.end);+ assertEquals(Quiet.Mode.SCHEDULED, s.mode);+ }++ @Test+ public void clock() {+ assertEquals("20:00", Quiet.clock(20 * 60, true));+ assertEquals("8:00 PM", Quiet.clock(20 * 60, false));+ }+}diff --git a/addons/quiet-hours/build.gradle b/addons/quiet-hours/build.gradlenew file mode 100644index 000000000..48978475f--- /dev/null+++ b/addons/quiet-hours/build.gradle@@ -0,0 +1,3 @@+plugins {+ id 'com.android.application' version '8.5.2' apply false+}diff --git a/addons/quiet-hours/gradle.properties b/addons/quiet-hours/gradle.propertiesnew file mode 100644index 000000000..18825f968--- /dev/null+++ b/addons/quiet-hours/gradle.properties@@ -0,0 +1,3 @@+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8+android.useAndroidX=true+android.nonTransitiveRClass=truediff --git a/addons/quiet-hours/gradle/wrapper/gradle-wrapper.jar b/addons/quiet-hours/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 000000000..2c3521197Binary files /dev/null and b/addons/quiet-hours/gradle/wrapper/gradle-wrapper.jar differdiff --git a/addons/quiet-hours/gradle/wrapper/gradle-wrapper.properties b/addons/quiet-hours/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 000000000..77f5d0ba6--- /dev/null+++ b/addons/quiet-hours/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/quiet-hours/gradlew b/addons/quiet-hours/gradlewnew file mode 100755index 000000000..f5feea6d6--- /dev/null+++ b/addons/quiet-hours/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/quiet-hours/gradlew.bat b/addons/quiet-hours/gradlew.batnew file mode 100644index 000000000..9d21a2183--- /dev/null+++ b/addons/quiet-hours/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/quiet-hours/install.sh b/addons/quiet-hours/install.shnew file mode 100755index 000000000..0bf9b0f88--- /dev/null+++ b/addons/quiet-hours/install.sh@@ -0,0 +1,26 @@+#!/usr/bin/env bash+# Build Quiet Hours and install it on the TV; TCL's auto-start lets the cap come back after a reboot.+# TV_HOST=<tv ip> addons/quiet-hours/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.quiethours+# 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/quiet-hours.apk+OUT=$(tv 'pm install -r /data/local/tmp/quiet-hours.apk; rm -f /data/local/tmp/quiet-hours.apk')+echo "$OUT"+case "$OUT" in *Success*) ;; *) echo "ERROR: pm install failed" >&2; exit 1 ;; esac++tv "cmd appops set $PKG APP_AUTO_START allow 2>/dev/null; echo auto-start allowed"+tv "am start -n $PKG/.MainActivity >/dev/null; echo opened"+echo "Installed. Quiet Hours is open on the TV; press Home and answer Show card for the card."diff --git a/addons/quiet-hours/screenshot.jpg b/addons/quiet-hours/screenshot.jpgnew file mode 100644index 000000000..314d278dcBinary files /dev/null and b/addons/quiet-hours/screenshot.jpg differdiff --git a/addons/quiet-hours/settings.gradle b/addons/quiet-hours/settings.gradlenew file mode 100644index 000000000..d44ae489e--- /dev/null+++ b/addons/quiet-hours/settings.gradle@@ -0,0 +1,16 @@+pluginManagement {+ repositories {+ google()+ mavenCentral()+ gradlePluginPortal()+ }+}+dependencyResolutionManagement {+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)+ repositories {+ google()+ mavenCentral()+ }+}+rootProject.name = "quiet-hours"+include ':app'