Skip to content

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

addons: News screensaver, headlines from your own RSS and Atom feeds with a QR code to each article

Morten Steensgaard420a221063ef
diff --git a/addons/README.md b/addons/README.md
index c3f00031d..da611147b 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"> |
+| [News screensaver](news-screensaver/) | Headlines from your own RSS and Atom feeds as the TV's screensaver and as a card, one at a time with source, age, a QR code to the article and Left/Right paging; feeds (with names), seconds per headline and idle time are set with `setup.sh` or on the TV | [@modist](https://github.com/modist) | Philips 2021/22 UHD Android TV (Android 11) | `INTERNET` | <img src="news-screensaver/screenshot.jpg" width="240" alt="News screensaver 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 live
here. See the rules below.
diff --git a/addons/news-screensaver/.gitignore b/addons/news-screensaver/.gitignore
new file mode 100644
index 000000000..b7a723e44
--- /dev/null
+++ b/addons/news-screensaver/.gitignore
@@ -0,0 +1,5 @@
+# Local build output and your own feed list stay out of git.
+.gradle/
+build/
+local.properties
+/feeds.txt
diff --git a/addons/news-screensaver/README.md b/addons/news-screensaver/README.md
new file mode 100644
index 000000000..965e26c9c
--- /dev/null
+++ b/addons/news-screensaver/README.md
@@ -0,0 +1,129 @@
+# News screensaver
+
+A system screensaver (Android's "Daydream") for any Android TV or Google TV that shows the news from RSS and Atom
+feeds you choose: one headline at a time, large, with its source, how long ago it was published and a short
+summary, crossfading to the next after 15 seconds (or what you set). Beside it a QR code opens the article on your
+phone, and "3 / 34" under it says where you are. Headlines from several feeds take turns, newest first, and anything
+older than two days is left out. A clock sits in the corner. The layout is fixed: source, headline, summary, count and
+code keep their places from one headline to the next, and a long headline gets smaller type instead of more lines.
+Against burn-in the whole picture drifts together, 6 dp round a small circle, one slow step every two minutes. The
+same story carried word for word by two papers (agency copy) is shown once.
+
+Left and Right on the remote page back and forth through the headlines, at once, and the timer starts again. Any other
+key wakes the TV back to where it was.
+
+Package `com.gathin.newsdream`. You see it as **News** (Danish: **Nyheder**) in the TV's screensaver settings. On
+cleanyourtv's Home it is also a module card, **News**: OK shows the headlines at once, Left and Right page through
+them, and any other key goes back to Home, as in the screensaver.
+
+
+![The news screensaver on a Philips TV: a TV 2 headline with its QR code](screenshot.jpg)
+## What you can set
+
+| Setting | Default | Where |
+|---|---|---|
+| Feeds: up to 10 RSS or Atom addresses, `https://` only | BBC News, World | `feeds.txt` and `setup.sh`, or the settings on the TV |
+| Seconds per headline: 5 to 600 | 15 | `SECONDS_PER_HEADLINE` / `-Seconds`, or the settings on the TV (8 to 120 in steps) |
+| When the screensaver starts: minutes without a key press | the TV's own | `IDLE_MINUTES` / `-IdleMinutes`, or the TV's own screensaver or energy settings |
+
+The settings on the TV are in the screensaver's own entry (TV settings > Screensaver > News > settings). Google TV
+has no settings entry for other screensavers, so there use `setup.sh`. Typing a feed address with the remote works, but `setup.sh` is quicker.
+
+## Install
+
+JDK 17 and Android SDK 34, as for the launcher, and the `tools/venv` from the main README. The small `gradlew`
+scripts reuse the launcher's pinned Gradle wrapper with this folder as the project, so keep this folder inside the
+repository when building.
+
+```sh
+TV_HOST=192.168.1.50 addons/news-screensaver/build-and-install.sh
+```
+
+```powershell
+powershell -ExecutionPolicy Bypass -File addons\news-screensaver\build-and-install.ps1 -TvHost 192.168.1.50
+```
+
+## Choose the feeds and make it the screensaver
+
+Copy `feeds.example.txt` to `feeds.txt` (git ignores it), put one feed address per line (lines starting with `#`
+are skipped) and run it. A name before the address and a bar, `Ekstra Bladet | https://...`, is shown as the source
+instead of the feed's own title, which is sometimes just "Nyheder". The same form works in the settings on the TV.
+
+```sh
+TV_HOST=192.168.1.50 addons/news-screensaver/setup.sh # feeds.txt, or pass another file
+TV_HOST=192.168.1.50 SECONDS_PER_HEADLINE=20 IDLE_MINUTES=10 START=1 addons/news-screensaver/setup.sh
+TV_HOST=192.168.1.50 addons/news-screensaver/setup.sh --default-feeds # back to the built-in feed
+TV_HOST=192.168.1.50 addons/news-screensaver/setup.sh --off # previous screensaver back
+```
+
+```powershell
+addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 [D:\my-feeds.txt] [-Seconds 20] [-IdleMinutes 10] [-Start]
+addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 -DefaultFeeds
+addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 -Off
+```
+
+It makes News the TV's screensaver and changes only what you pass: run it without a feeds file (and with no
+`feeds.txt` here) and the feeds on the TV stay as they are. The feeds and seconds are written through the app's own
+provider, which only the ADB shell may use. The screensaver the TV had before the first run is remembered for
+`--off`; `build-and-install.sh --uninstall` does `--off` and removes the app.
+
+`IDLE_MINUTES` sets `screen_off_timeout`, after which the TV starts its screensaver; on most TVs the same value is
+in TV settings > Screensaver (or Energy saving) as "When to start". Some sets go to standby instead of the
+screensaver at that point: then pick the time in the TV's own settings.
+
+A feed's address is usually linked from the site as "RSS", or found by adding `/rss` or `/feed` to a section's
+address. Some that work:
+
+| Feed | Address |
+|---|---|
+| DR, latest news | `https://www.dr.dk/nyheder/service/feeds/senestenyt` |
+| TV 2 Nyheder | `https://feeds.services.tv2.dk/api/feeds/nyheder/rss` |
+| Ekstra Bladet, Nyheder | `https://ekstrabladet.dk/rssfeed/nyheder/` |
+| B.T., latest | `https://www.bt.dk/bt/seneste/rss` |
+| BBC News, World | `https://feeds.bbci.co.uk/news/world/rss.xml` |
+| The Guardian, World | `https://www.theguardian.com/world/rss` |
+| NPR News | `https://feeds.npr.org/1001/rss.xml` |
+
+`feeds.example.txt` has the first five switched on, with names.
+
+## The QR code
+
+It holds the item's own link (RSS `<link>`, Atom `<link href>`), drawn on the TV by a small built-in encoder (byte
+mode, error correction level M, up to 400 characters), so nothing extra is fetched or sent to make it. An item without
+a link, or with a longer one, shows no code. It is drawn in the screen's navy on a muted blue-grey rather than black on
+white, so it doesn't glare; phones read it from the sofa at about 9:1 contrast.
+
+## How it fetches
+
+The feeds are read when the screensaver or the card starts, then every 15 minutes while it shows, or 2 minutes after
+everything failed. Nothing runs in the background when it is not on screen. The last good list is kept in the app's
+storage, so the screensaver shows headlines at once, and with no network the last ones it had. A feed that fails is
+skipped and the others still show. Each reply is read up to 2 MB and at most 20 items per feed; 60 headlines in all.
+
+## Memory
+
+No pictures and no web view: one screen of text views, a list of at most 60 short headlines, one QR code at a time
+(drawn as rectangles, no bitmap) and one thread for the fetches. The release APK is about 30 KB.
+
+## Permissions
+
+| Permission | Why |
+|---|---|
+| `INTERNET` | To fetch the feeds you set, over HTTPS, while the screensaver or the card is on screen. |
+
+That is all. What goes out is a plain GET for each feed address, with the user agent
+`cleanyourtv-news/1.0`; each news site sees the TV's IP address, as with any visit. No account, no telemetry, no ads,
+no background service, no location. Feeds, seconds and the cached headlines stay in the app's own storage (backups
+are off). The provider that `setup.sh` writes through requires `WRITE_SECURE_SETTINGS`, which the ADB shell has and
+apps don't, so no other app can change the feeds.
+
+## Tested on
+
+Philips 2021/22 UHD Android TV, Android 11: installed with `build-and-install.sh`, feeds and seconds set with
+`setup.sh`, the screensaver started, headlines from DR, TV 2, Ekstra Bladet, B.T. and BBC with Danish letters, the QR codes read back from TV
+screenshots, Left and Right paging, and Up, Down, OK, Back and a digit each waking the TV to Home. The parser, the
+merging and the QR encoder have JVM unit tests (`./gradlew testReleaseUnitTest`).
+
+## Maintainer
+
+[@modist](https://github.com/modist)
diff --git a/addons/news-screensaver/app/build.gradle b/addons/news-screensaver/app/build.gradle
new file mode 100644
index 000000000..7aaae75aa
--- /dev/null
+++ b/addons/news-screensaver/app/build.gradle
@@ -0,0 +1,36 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'com.gathin.newsdream'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'com.gathin.newsdream'
+ // Android 8 and up, as the launcher.
+ minSdk 26
+ targetSdk 34
+ versionCode 1
+ versionName '1.0'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ shrinkResources true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ // Sideloaded over ADB, never published: sign with the debug key so it installs over a debug build.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
+
+dependencies {
+ testImplementation 'junit:junit:4.13.2'
+}
diff --git a/addons/news-screensaver/app/proguard-rules.pro b/addons/news-screensaver/app/proguard-rules.pro
new file mode 100644
index 000000000..7bb3d36ed
--- /dev/null
+++ b/addons/news-screensaver/app/proguard-rules.pro
@@ -0,0 +1,4 @@
+# Shrink and optimise, but keep class and method names: the size win comes from dropping unused
+# AndroidX code, not from renaming, and readable stack traces matter more in a sideloaded app
+# where crash reports arrive as screenshots.
+-dontobfuscate
diff --git a/addons/news-screensaver/app/src/main/AndroidManifest.xml b/addons/news-screensaver/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..d13d210a3
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/AndroidManifest.xml
@@ -0,0 +1,62 @@
+<?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 feeds, fetched over HTTPS while the screensaver or the card shows. Nothing else goes out. -->
+ <uses-permission android:name="android.permission.INTERNET" />
+
+ <application
+ android:allowBackup="false"
+ android:label="@string/app_name"
+ android:icon="@drawable/icon"
+ android:banner="@drawable/banner"
+ android:supportsRtl="true">
+
+ <!-- `settings put secure screensaver_components com.gathin.newsdream/.NewsDream` (setup.sh does it). -->
+ <service
+ android:name=".NewsDream"
+ android:label="@string/dream_name"
+ android:exported="true"
+ android:permission="android.permission.BIND_DREAM_SERVICE">
+ <intent-filter>
+ <action android:name="android.service.dreams.DreamService" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ <meta-data android:name="android.service.dream" android:resource="@xml/dream" />
+ </service>
+
+ <!-- The card on cleanyourtv's Home (docs/modules.md): the headlines at once, Back to leave. -->
+ <activity
+ android:name=".NewsActivity"
+ android:exported="true"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen">
+ <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>
+
+ <!-- Opened by the TV's screensaver settings (xml/dream.xml), which needs it exported. -->
+ <activity
+ android:name=".SettingsActivity"
+ android:exported="true"
+ android:label="@string/settings_title"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
+ android:windowSoftInputMode="adjustPan" />
+
+ <!-- setup.sh writes feeds.txt and seconds.txt through this. WRITE_SECURE_SETTINGS: the adb shell has it,
+ ordinary apps don't, so no other app can change the feeds. -->
+ <provider
+ android:name=".FilesProvider"
+ android:authorities="com.gathin.newsdream.files"
+ android:exported="true"
+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />
+ </application>
+</manifest>
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Config.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Config.java
new file mode 100644
index 000000000..9cdbc1141
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Config.java
@@ -0,0 +1,147 @@
+package com.gathin.newsdream;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * The two settings, each a small text file in the app's files dir: feeds.txt (one HTTPS feed address per line,
+ * optionally after a name and a bar, "Ekstra Bladet | https://...", # for comments) and seconds.txt (how long a headline stays up). setup.sh writes them through FilesProvider,
+ * SettingsActivity on the TV. No feeds.txt yet: the default feed.
+ */
+final class Config {
+ static final String FEEDS = "feeds.txt";
+ static final String SECONDS = "seconds.txt";
+ static final int MAX_FEEDS = 10;
+ static final int DEFAULT_SECONDS = 15;
+ static final int MIN_SECONDS = 5;
+ static final int MAX_SECONDS = 600;
+ static final int MAX_NAME = 40;
+ /** The choices SettingsActivity steps through. */
+ static final int[] SECONDS_CHOICES = {8, 10, 15, 20, 30, 45, 60, 120};
+ static final List<String> DEFAULT_FEEDS =
+ Collections.singletonList("https://feeds.bbci.co.uk/news/world/rss.xml");
+
+ private Config() {}
+
+ /** The file a provider path names: only feeds.txt and seconds.txt, nothing else. */
+ static String path(List<String> segments) {
+ if (segments == null || segments.size() != 1) return null;
+ String name = segments.get(0);
+ return FEEDS.equals(name) || SECONDS.equals(name) ? name : null;
+ }
+
+ /** An absolute https:// address with a host and no spaces. Plain http is refused (Android blocks it too). */
+ static boolean validUrl(String url) {
+ if (url == null || url.length() > 500 || !url.toLowerCase(Locale.ROOT).startsWith("https://")) return false;
+ for (int i = 0; i < url.length(); i++) {
+ if (Character.isWhitespace(url.charAt(i)) || Character.isISOControl(url.charAt(i))) return false;
+ }
+ try {
+ URI uri = new URI(url);
+ return uri.getHost() != null && !uri.getHost().isEmpty();
+ } catch (URISyntaxException e) {
+ return false;
+ }
+ }
+
+ /**
+ * One feed line tidied: "Name | https://..." or just the address; null when the address is not https or the
+ * name too long. The last bar splits them, so a name may hold one ("Kort nyt | DR | https://...").
+ */
+ static String feed(String line) {
+ if (line == null) return null;
+ String text = line.trim();
+ int bar = text.lastIndexOf('|');
+ String name = bar < 0 ? "" : text.substring(0, bar).trim();
+ String url = bar < 0 ? text : text.substring(bar + 1).trim();
+ if (!validUrl(url) || name.length() > MAX_NAME) return null;
+ for (int i = 0; i < name.length(); i++) if (Character.isISOControl(name.charAt(i))) return null;
+ return name.isEmpty() ? url : name + " | " + url;
+ }
+
+ /** The address in a tidied feed line. */
+ static String url(String feed) {
+ return feed.substring(feed.lastIndexOf('|') + 1).trim();
+ }
+
+ /** The name in a tidied feed line, or "" to use the feed's own title. */
+ static String name(String feed) {
+ int bar = feed.lastIndexOf('|');
+ return bar < 0 ? "" : feed.substring(0, bar).trim();
+ }
+
+ /** The feeds in feeds.txt's text, in order, one per address, at most ten; the default when there is no file. */
+ static List<String> feeds(String text) {
+ if (text == null) return DEFAULT_FEEDS;
+ List<String> feeds = new ArrayList<>();
+ Set<String> urls = new HashSet<>();
+ for (String line : text.split("\n")) {
+ if (line.trim().startsWith("#")) continue;
+ String feed = feed(line);
+ if (feed == null || !urls.add(url(feed))) continue;
+ feeds.add(feed);
+ if (feeds.size() == MAX_FEEDS) break;
+ }
+ return feeds;
+ }
+
+ static String feedsText(List<String> feeds) {
+ StringBuilder text = new StringBuilder();
+ for (String feed : feeds) text.append(feed).append('\n');
+ return text.toString();
+ }
+
+ /** seconds.txt's number, 5 to 600; 15 when it is missing or not a number. */
+ static int seconds(String text) {
+ if (text == null) return DEFAULT_SECONDS;
+ try {
+ int s = Integer.parseInt(text.trim());
+ return s < MIN_SECONDS || s > MAX_SECONDS ? DEFAULT_SECONDS : s;
+ } catch (NumberFormatException e) {
+ return DEFAULT_SECONDS;
+ }
+ }
+
+ /** The next choice after {@code seconds}, round to the first. */
+ static int nextSeconds(int seconds) {
+ for (int choice : SECONDS_CHOICES) if (choice > seconds) return choice;
+ return SECONDS_CHOICES[0];
+ }
+
+ static List<String> feeds(File dir) {
+ return feeds(read(new File(dir, FEEDS)));
+ }
+
+ static int seconds(File dir) {
+ return seconds(read(new File(dir, SECONDS)));
+ }
+
+ /** A small text file, or null when it is missing or unreadable. */
+ static String read(File file) {
+ if (!file.isFile() || file.length() > 64 * 1024) return null;
+ try {
+ return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ static void write(File file, String text) {
+ try (FileOutputStream out = new FileOutputStream(file)) {
+ out.write(text.getBytes(StandardCharsets.UTF_8));
+ } catch (IOException ignored) {
+ // The settings screen shows what is on disk again, so a failed write is visible there.
+ }
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/FeedParser.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/FeedParser.java
new file mode 100644
index 000000000..15e112bfe
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/FeedParser.java
@@ -0,0 +1,290 @@
+package com.gathin.newsdream;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.TimeZone;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+/**
+ * RSS 2.0, RSS 1.0 (RDF) and Atom, read as a stream with SAX: the feed's title and its first items. Element names
+ * are matched without their prefix, so dc:date and atom:title count as date and title.
+ */
+final class FeedParser {
+ static final int MAX_ITEMS = 20;
+ private static final int MAX_TITLE = 200;
+ private static final int MAX_SUMMARY = 280;
+ private static final int MAX_SOURCE = 40;
+ private static final int MAX_TEXT = 16 * 1024;
+ private static final int MAX_LINK = 400;
+
+ private FeedParser() {}
+
+ static final class Feed {
+ final String title;
+ final List<Headline> items;
+
+ Feed(String title, List<Headline> items) {
+ this.title = title;
+ this.items = items;
+ }
+ }
+
+ /** Thrown to stop reading once there are enough items. */
+ private static final class Enough extends SAXException {
+ Enough() { super("enough"); }
+ }
+
+ static Feed parse(InputStream in, String fallbackSource) throws IOException {
+ Handler handler = new Handler();
+ try {
+ SAXParserFactory factory = SAXParserFactory.newInstance();
+ // No entities from outside the document. Not every parser knows every feature, so each is optional.
+ for (String feature : new String[]{
+ "http://xml.org/sax/features/external-general-entities",
+ "http://xml.org/sax/features/external-parameter-entities",
+ "http://apache.org/xml/features/nonvalidating/load-external-dtd"}) {
+ try {
+ factory.setFeature(feature, false);
+ } catch (Exception ignored) {
+ // Android's expat parser never loads them anyway.
+ }
+ }
+ SAXParser parser = factory.newSAXParser();
+ parser.parse(new InputSource(in), handler);
+ } catch (Enough enough) {
+ // Read as much as we show.
+ } catch (SAXException | ParserConfigurationException e) {
+ if (handler.items.isEmpty()) throw new IOException("not a feed: " + e.getMessage());
+ }
+ String source = clean(handler.feedTitle, MAX_SOURCE);
+ if (source.isEmpty()) source = fallbackSource;
+ List<Headline> items = new ArrayList<>();
+ for (Item item : handler.items) {
+ String title = clean(item.title, MAX_TITLE);
+ if (title.isEmpty()) continue;
+ String summary = clean(item.summary, MAX_SUMMARY);
+ if (summary.equals(title)) summary = "";
+ items.add(new Headline(source, title, summary, date(item.date), link(item.link)));
+ }
+ return new Feed(source, items);
+ }
+
+ private static final class Item {
+ String title;
+ String summary;
+ String date;
+ String link;
+ }
+
+ private static final class Handler extends DefaultHandler {
+ final List<Item> items = new ArrayList<>();
+ final List<String> path = new ArrayList<>();
+ final StringBuilder text = new StringBuilder();
+ String feedTitle;
+ Item item;
+
+ @Override
+ public void startElement(String uri, String localName, String qName, Attributes attributes) {
+ String name = name(localName, qName);
+ // Atom's type="xhtml" content is markup inside the element: keep its text together.
+ if (insideText()) text.append(' ');
+ else text.setLength(0);
+ path.add(name);
+ if ("item".equals(name) || "entry".equals(name)) item = new Item();
+ // Atom: <link href="..."/>, the alternate one (rel left out means alternate).
+ if ("link".equals(name) && item != null && path.size() >= 2 && "entry".equals(path.get(path.size() - 2))) {
+ String rel = attributes.getValue("rel");
+ String href = attributes.getValue("href");
+ if (href != null && (rel == null || "alternate".equals(rel)) && item.link == null) item.link = href;
+ }
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length) {
+ if (text.length() < MAX_TEXT) text.append(ch, start, Math.min(length, MAX_TEXT - text.length()));
+ }
+
+ @Override
+ public void endElement(String uri, String localName, String qName) throws SAXException {
+ String name = name(localName, qName);
+ if (!path.isEmpty()) path.remove(path.size() - 1);
+ if (insideText()) text.append(' ');
+ String parent = path.isEmpty() ? "" : path.get(path.size() - 1);
+ boolean inItem = item != null && ("item".equals(parent) || "entry".equals(parent));
+ if (inItem) {
+ switch (name) {
+ case "title":
+ item.title = text.toString();
+ break;
+ case "description":
+ case "summary":
+ item.summary = text.toString();
+ break;
+ case "encoded": // content:encoded
+ case "content": // Atom
+ if (item.summary == null || item.summary.trim().isEmpty()) item.summary = text.toString();
+ break;
+ case "pubDate":
+ case "date": // dc:date
+ case "published":
+ item.date = text.toString();
+ break;
+ case "link": // RSS: the address as text
+ if (item.link == null && text.toString().trim().length() > 0) item.link = text.toString();
+ break;
+ case "updated":
+ if (item.date == null) item.date = text.toString();
+ break;
+ default:
+ break;
+ }
+ } else if ("title".equals(name) && feedTitle == null
+ && ("channel".equals(parent) || "feed".equals(parent))) {
+ feedTitle = text.toString();
+ }
+ if (("item".equals(name) || "entry".equals(name)) && item != null) {
+ items.add(item);
+ item = null;
+ if (items.size() >= MAX_ITEMS) throw new Enough();
+ }
+ }
+
+ private boolean insideText() {
+ if (item == null) return false;
+ for (String p : path) {
+ if ("content".equals(p) || "summary".equals(p) || "description".equals(p)) return true;
+ }
+ return false;
+ }
+
+ private static String name(String localName, String qName) {
+ String name = localName != null && !localName.isEmpty() ? localName : qName;
+ if (name == null) return "";
+ int colon = name.indexOf(':');
+ return colon >= 0 ? name.substring(colon + 1) : name;
+ }
+ }
+
+ /** An http(s) address short enough for a QR code a phone reads across the room, or "". */
+ static String link(String text) {
+ if (text == null) return "";
+ String link = text.trim();
+ String lower = link.toLowerCase(Locale.ROOT);
+ if (!(lower.startsWith("https://") || lower.startsWith("http://")) || link.length() > MAX_LINK) return "";
+ for (int i = 0; i < link.length(); i++) if (Character.isWhitespace(link.charAt(i))) return "";
+ return link;
+ }
+
+ private static final Pattern TAG = Pattern.compile("<[^>]*>");
+ private static final Pattern ENTITY = Pattern.compile("&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);");
+ private static final Pattern SPACE = Pattern.compile("\\s+");
+
+ /** Plain text on one line: HTML tags dropped, entities decoded, at most {@code max} characters. */
+ static String clean(String html, int max) {
+ if (html == null) return "";
+ String text = TAG.matcher(html).replaceAll(" ");
+ // Twice: feeds often escape their HTML, so "&amp;amp;" and "&lt;b&gt;" come out of the XML parser.
+ for (int pass = 0; pass < 2 && text.indexOf('&') >= 0; pass++) {
+ text = TAG.matcher(entities(text)).replaceAll(" ");
+ }
+ text = SPACE.matcher(text.replace('\u00A0', ' ')).replaceAll(" ").trim();
+ if (text.length() <= max) return text;
+ int cut = text.lastIndexOf(' ', max - 1);
+ return text.substring(0, cut > max / 2 ? cut : max - 1).trim() + "\u2026";
+ }
+
+ private static String entities(String text) {
+ Matcher m = ENTITY.matcher(text);
+ StringBuilder out = new StringBuilder();
+ int last = 0;
+ while (m.find()) {
+ out.append(text, last, m.start());
+ String e = m.group(1);
+ String decoded;
+ try {
+ if (e.startsWith("#x") || e.startsWith("#X")) decoded = new String(Character.toChars(Integer.parseInt(e.substring(2), 16)));
+ else if (e.startsWith("#")) decoded = new String(Character.toChars(Integer.parseInt(e.substring(1))));
+ else decoded = named(e);
+ } catch (IllegalArgumentException bad) {
+ decoded = null;
+ }
+ out.append(decoded != null ? decoded : m.group());
+ last = m.end();
+ }
+ return out.append(text.substring(last)).toString();
+ }
+
+ private static String named(String name) {
+ switch (name) {
+ case "amp": return "&";
+ case "lt": return "<";
+ case "gt": return ">";
+ case "quot": return "\"";
+ case "apos": return "'";
+ case "nbsp": return " ";
+ case "ndash": return "\u2013";
+ case "mdash": return "\u2014";
+ case "hellip": return "\u2026";
+ case "lsquo": return "\u2018";
+ case "rsquo": return "\u2019";
+ case "ldquo": return "\u201C";
+ case "rdquo": return "\u201D";
+ case "aelig": return "\u00E6";
+ case "AElig": return "\u00C6";
+ case "oslash": return "\u00F8";
+ case "Oslash": return "\u00D8";
+ case "aring": return "\u00E5";
+ case "Aring": return "\u00C5";
+ default: return null;
+ }
+ }
+
+ private static final String[] DATE_FORMATS = {
+ "d MMM yyyy HH:mm:ss Z", // RSS, without its weekday: 25 Oct 2026 14:05:00 +0200
+ "d MMM yyyy HH:mm:ss z", // ... GMT
+ "d MMM yyyy HH:mm Z",
+ "d MMM yyyy HH:mm z",
+ "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", // Atom: 2026-10-25T14:05:00.000+02:00 or ...Z
+ "yyyy-MM-dd'T'HH:mm:ssXXX",
+ "yyyy-MM-dd'T'HH:mmXXX",
+ };
+
+ /** A feed date in ms, or 0 when it is missing or in no format we know. */
+ static long date(String text) {
+ if (text == null) return 0;
+ String s = SPACE.matcher(text.trim()).replaceAll(" ");
+ if (s.isEmpty()) return 0;
+ // The weekday is dropped: feeds get it wrong now and then, and the date says it anyway.
+ s = s.replaceFirst("^[A-Za-z]+,\\s*", "");
+ // Fractions of a second come in any length; keep three digits so one pattern reads them all.
+ s = s.replaceFirst("(T\\d\\d:\\d\\d:\\d\\d)\\.(\\d{1,3})\\d*", "$1.$2")
+ .replaceFirst("(T\\d\\d:\\d\\d:\\d\\d\\.)(\\d)(?!\\d)", "$1$200")
+ .replaceFirst("(T\\d\\d:\\d\\d:\\d\\d\\.)(\\d\\d)(?!\\d)", "$1$20");
+ for (String format : DATE_FORMATS) {
+ SimpleDateFormat f = new SimpleDateFormat(format, Locale.US);
+ f.setTimeZone(TimeZone.getTimeZone("UTC"));
+ f.setLenient(false);
+ try {
+ return f.parse(s).getTime();
+ } catch (ParseException ignored) {
+ // next format
+ }
+ }
+ return 0;
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/FilesProvider.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/FilesProvider.java
new file mode 100644
index 000000000..bb195718e
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/FilesProvider.java
@@ -0,0 +1,57 @@
+package com.gathin.newsdream;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.ParcelFileDescriptor;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+
+/**
+ * Lets setup.sh write the two settings files into the app's own files dir. Only those two names, and only for
+ * callers holding WRITE_SECURE_SETTINGS (the adb shell).
+ *
+ * content write --uri content://com.gathin.newsdream.files/feeds.txt < /data/local/tmp/feeds.txt
+ * content write --uri content://com.gathin.newsdream.files/seconds.txt < /data/local/tmp/seconds.txt
+ * content read --uri content://com.gathin.newsdream.files/feeds.txt
+ * content delete --uri content://com.gathin.newsdream.files/feeds.txt (back to the default feed)
+ */
+public class FilesProvider extends ContentProvider {
+
+ private File file(Uri uri) throws FileNotFoundException {
+ String name = Config.path(uri.getPathSegments());
+ if (getContext() == null || name == null) throw new FileNotFoundException(String.valueOf(uri));
+ return new File(getContext().getFilesDir(), name);
+ }
+
+ @Override
+ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
+ File f = file(uri);
+ if (mode.contains("w")) {
+ // New feeds: the old headlines go, so the next start fetches at once.
+ if (Config.FEEDS.equals(f.getName())) News.clearCache(f.getParentFile());
+ return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_WRITE_ONLY
+ | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
+ }
+ return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
+ }
+
+ @Override
+ public int delete(Uri uri, String selection, String[] selectionArgs) {
+ try {
+ File f = file(uri);
+ if (Config.FEEDS.equals(f.getName())) News.clearCache(f.getParentFile());
+ return f.delete() ? 1 : 0;
+ } catch (FileNotFoundException e) {
+ return 0;
+ }
+ }
+
+ @Override public boolean onCreate() { return true; }
+ @Override public String getType(Uri uri) { return null; }
+ @Override public Cursor query(Uri uri, String[] p, String s, String[] a, String o) { return null; }
+ @Override public Uri insert(Uri uri, ContentValues values) { return null; }
+ @Override public int update(Uri uri, ContentValues v, String s, String[] a) { return 0; }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Headline.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Headline.java
new file mode 100644
index 000000000..0e13db8eb
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Headline.java
@@ -0,0 +1,20 @@
+package com.gathin.newsdream;
+
+/** One item from a feed, cleaned for the screen: plain text, no HTML. */
+final class Headline {
+ final String source;
+ final String title;
+ final String summary;
+ /** When it was published, in ms since 1970; 0 when the feed does not say. */
+ final long time;
+ /** The article's address, for the QR code; empty when the feed has none. */
+ final String link;
+
+ Headline(String source, String title, String summary, long time, String link) {
+ this.source = source;
+ this.title = title;
+ this.summary = summary;
+ this.time = time;
+ this.link = link;
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/News.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/News.java
new file mode 100644
index 000000000..730b25099
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/News.java
@@ -0,0 +1,179 @@
+package com.gathin.newsdream;
+
+import android.util.Log;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * Fetches the feeds and deals their headlines into one list, taking turns between the feeds so a busy one
+ * doesn't crowd out the rest. The last good list is kept in a cache file, so the screensaver has something to
+ * show at once, and with no network.
+ */
+final class News {
+ static final long REFRESH_MS = 15 * 60_000L;
+ static final long MAX_AGE_MS = 48 * 3_600_000L;
+ static final int MAX_HEADLINES = 60;
+ private static final int TIMEOUT_MS = 10_000;
+ private static final int MAX_BYTES = 2 * 1024 * 1024;
+ private static final String CACHE = "cache.bin";
+ private static final int CACHE_VERSION = 2;
+
+ private News() {}
+
+ /**
+ * Every feed's headlines, mixed; blocking, so call it off the main thread. Feeds that fail are skipped. A feed
+ * line with a name ("DR | https://...") shows that name instead of the feed's own title.
+ */
+ static List<Headline> fetch(List<String> feedLines, long now) {
+ List<List<Headline>> feeds = new ArrayList<>();
+ for (String feed : feedLines) {
+ if (Thread.currentThread().isInterrupted()) break;
+ String url = Config.url(feed);
+ String name = Config.name(feed);
+ try {
+ List<Headline> items = fetch(url).items;
+ if (!name.isEmpty()) items = renamed(items, name);
+ feeds.add(items);
+ } catch (IOException | RuntimeException e) {
+ // One feed down, the others still show. `adb logcat -s TvNews` says why.
+ Log.w("TvNews", url + ": " + e);
+ }
+ }
+ return mix(feeds, now);
+ }
+
+ private static List<Headline> renamed(List<Headline> items, String source) {
+ List<Headline> renamed = new ArrayList<>(items.size());
+ for (Headline h : items) renamed.add(new Headline(source, h.title, h.summary, h.time, h.link));
+ return renamed;
+ }
+
+ static FeedParser.Feed fetch(String url) throws IOException {
+ HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
+ connection.setConnectTimeout(TIMEOUT_MS);
+ connection.setReadTimeout(TIMEOUT_MS);
+ connection.setRequestProperty("User-Agent", "cleanyourtv-news/1.0 (Android TV screensaver)");
+ connection.setRequestProperty("Accept", "application/rss+xml, application/atom+xml, application/xml, text/xml");
+ try {
+ int code = connection.getResponseCode();
+ if (code != HttpURLConnection.HTTP_OK) throw new IOException("HTTP " + code);
+ try (InputStream in = new Capped(connection.getInputStream(), MAX_BYTES)) {
+ return FeedParser.parse(in, connection.getURL().getHost());
+ }
+ } finally {
+ connection.disconnect();
+ }
+ }
+
+ /**
+ * One list from many: each feed newest first, older than two days dropped (undated items are kept), then one
+ * from each feed in turn, at most {@link #MAX_HEADLINES}. A headline another feed already gave is left out.
+ */
+ static List<Headline> mix(List<List<Headline>> feeds, long now) {
+ List<List<Headline>> lists = new ArrayList<>();
+ for (List<Headline> feed : feeds) {
+ List<Headline> fresh = new ArrayList<>();
+ for (Headline h : feed) if (h.time == 0 || now - h.time <= MAX_AGE_MS) fresh.add(h);
+ // Stable: undated items keep the feed's own order, after the dated ones.
+ fresh.sort(Comparator.comparingLong((Headline h) -> h.time == 0 ? Long.MIN_VALUE : h.time).reversed());
+ if (!fresh.isEmpty()) lists.add(fresh);
+ }
+ List<Headline> mixed = new ArrayList<>();
+ // The same agency story often runs word for word in several papers: show it once.
+ Set<String> seen = new HashSet<>();
+ for (int i = 0; mixed.size() < MAX_HEADLINES; i++) {
+ boolean any = false;
+ for (List<Headline> list : lists) {
+ if (i < list.size() && mixed.size() < MAX_HEADLINES) {
+ any = true;
+ if (seen.add(list.get(i).title.toLowerCase(Locale.ROOT))) mixed.add(list.get(i));
+ }
+ }
+ if (!any) break;
+ }
+ return mixed;
+ }
+
+ static void save(File dir, List<Headline> headlines) {
+ File tmp = new File(dir, CACHE + ".tmp");
+ try (DataOutputStream out = new DataOutputStream(new FileOutputStream(tmp))) {
+ out.writeInt(CACHE_VERSION);
+ out.writeInt(headlines.size());
+ for (Headline h : headlines) {
+ out.writeUTF(h.source);
+ out.writeUTF(h.title);
+ out.writeUTF(h.summary);
+ out.writeLong(h.time);
+ out.writeUTF(h.link);
+ }
+ } catch (IOException e) {
+ return;
+ }
+ if (!tmp.renameTo(new File(dir, CACHE))) tmp.delete();
+ }
+
+ /** The cached list, or an empty one. */
+ static List<Headline> load(File dir) {
+ File file = new File(dir, CACHE);
+ if (!file.isFile()) return Collections.emptyList();
+ try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
+ if (in.readInt() != CACHE_VERSION) return Collections.emptyList();
+ int n = Math.min(in.readInt(), MAX_HEADLINES);
+ List<Headline> list = new ArrayList<>(Math.max(n, 0));
+ for (int i = 0; i < n; i++) list.add(new Headline(in.readUTF(), in.readUTF(), in.readUTF(), in.readLong(), in.readUTF()));
+ return list;
+ } catch (IOException e) {
+ return Collections.emptyList();
+ }
+ }
+
+ static long cacheTime(File dir) {
+ return new File(dir, CACHE).lastModified();
+ }
+
+ static void clearCache(File dir) {
+ new File(dir, CACHE).delete();
+ }
+
+ /** Stops reading after {@code max} bytes, so a huge or endless reply can't fill the memory. */
+ private static final class Capped extends FilterInputStream {
+ private long left;
+
+ Capped(InputStream in, long max) {
+ super(in);
+ left = max;
+ }
+
+ @Override
+ public int read() throws IOException {
+ if (left <= 0) throw new IOException("feed too large");
+ int b = super.read();
+ if (b >= 0) left--;
+ return b;
+ }
+
+ @Override
+ public int read(byte[] buffer, int off, int len) throws IOException {
+ if (left <= 0) throw new IOException("feed too large");
+ int n = super.read(buffer, off, (int) Math.min(len, left));
+ if (n > 0) left -= n;
+ return n;
+ }
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/NewsActivity.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/NewsActivity.java
new file mode 100644
index 000000000..4e6613ef9
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/NewsActivity.java
@@ -0,0 +1,43 @@
+package com.gathin.newsdream;
+
+import android.app.Activity;
+import android.view.KeyEvent;
+
+/**
+ * The module card on cleanyourtv's Home, and the settings' preview: the same scene as the screensaver, right
+ * away. Left and Right page through the headlines; any other key goes back, to Home (or to the settings it was
+ * opened from), as the screensaver wakes on any other key.
+ */
+public class NewsActivity extends Activity {
+
+ private Scene scene;
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ // Built again on every start, so feeds changed in the settings show at once.
+ scene = new Scene(this);
+ setContentView(scene.root);
+ scene.start();
+ }
+
+ @Override
+ protected void onStop() {
+ if (scene != null) scene.stop();
+ scene = null;
+ super.onStop();
+ }
+
+ @Override
+ public boolean dispatchKeyEvent(KeyEvent event) {
+ int key = event.getKeyCode();
+ if (key == KeyEvent.KEYCODE_DPAD_RIGHT || key == KeyEvent.KEYCODE_DPAD_LEFT) {
+ if (event.getAction() == KeyEvent.ACTION_DOWN && scene != null) {
+ scene.step(key == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : -1);
+ }
+ return true;
+ }
+ if (event.getAction() == KeyEvent.ACTION_DOWN) finish();
+ return true;
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/NewsDream.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/NewsDream.java
new file mode 100644
index 000000000..7e37aaaf9
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/NewsDream.java
@@ -0,0 +1,55 @@
+package com.gathin.newsdream;
+
+import android.service.dreams.DreamService;
+import android.view.KeyEvent;
+
+/**
+ * The system screensaver: the Scene. Left and Right page through the headlines; any other key wakes the TV back
+ * to where it was, as a screensaver that takes no keys would.
+ */
+public class NewsDream extends DreamService {
+
+ private Scene scene;
+
+ @Override
+ public void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ // Interactive so Left and Right reach dispatchKeyEvent; everything else ends the dream there.
+ setInteractive(true);
+ setFullscreen(true);
+ scene = new Scene(this);
+ setContentView(scene.root);
+ }
+
+ @Override
+ public boolean dispatchKeyEvent(KeyEvent event) {
+ int key = event.getKeyCode();
+ if (key == KeyEvent.KEYCODE_DPAD_RIGHT || key == KeyEvent.KEYCODE_DPAD_LEFT) {
+ if (event.getAction() == KeyEvent.ACTION_DOWN && scene != null) {
+ scene.step(key == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : -1);
+ }
+ return true;
+ }
+ // The waking key is used up here, so it doesn't also act on the app below.
+ if (event.getAction() == KeyEvent.ACTION_DOWN) finish();
+ return true;
+ }
+
+ @Override
+ public void onDreamingStarted() {
+ super.onDreamingStarted();
+ if (scene != null) scene.start();
+ }
+
+ @Override
+ public void onDreamingStopped() {
+ if (scene != null) scene.stop();
+ super.onDreamingStopped();
+ }
+
+ @Override
+ public void onDetachedFromWindow() {
+ if (scene != null) scene.stop();
+ super.onDetachedFromWindow();
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Qr.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Qr.java
new file mode 100644
index 000000000..9dedcf511
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Qr.java
@@ -0,0 +1,315 @@
+package com.gathin.newsdream;
+
+import java.nio.charset.StandardCharsets;
+
+/**
+ * A QR code for a short text (the headline's link): byte mode, error correction level M, versions 1 to 15 (up to
+ * about 400 bytes). The smallest version that fits is used, and the mask with the lowest penalty. Follows
+ * ISO/IEC 18004 the way Project Nayuki's MIT-licensed generator lays it out; no library, so no new dependency.
+ */
+final class Qr {
+ static final int MAX_VERSION = 15;
+
+ // Indexed by version; level M.
+ private static final int[] ECC_PER_BLOCK = {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24};
+ private static final int[] BLOCKS = {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10};
+ private static final int FORMAT_M = 0;
+
+ private final int size;
+ private final boolean[][] dark; // [y][x]
+ private final boolean[][] function; // finder, timing, alignment, format and version modules
+
+ private Qr(int version) {
+ size = version * 4 + 17;
+ dark = new boolean[size][size];
+ function = new boolean[size][size];
+ }
+
+ /** The modules, [y][x], true for dark; null when the text is too long for version 15. */
+ static boolean[][] encode(String text) {
+ byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
+ for (int version = 1; version <= MAX_VERSION; version++) {
+ int capacityBits = dataCodewords(version) * 8;
+ int countBits = version < 10 ? 8 : 16;
+ if (4 + countBits + bytes.length * 8 <= capacityBits) {
+ Qr qr = new Qr(version);
+ qr.draw(version, data(bytes, countBits, capacityBits));
+ return qr.dark;
+ }
+ }
+ return null;
+ }
+
+ private static byte[] data(byte[] bytes, int countBits, int capacityBits) {
+ Bits bits = new Bits(capacityBits);
+ bits.add(0b0100, 4); // byte mode
+ bits.add(bytes.length, countBits);
+ for (byte b : bytes) bits.add(b & 0xFF, 8);
+ bits.add(0, Math.min(4, capacityBits - bits.length)); // terminator
+ bits.add(0, (8 - bits.length % 8) % 8);
+ for (int pad = 0xEC; bits.length < capacityBits; pad ^= 0xEC ^ 0x11) bits.add(pad, 8);
+ return bits.bytes;
+ }
+
+ private void draw(int version, byte[] data) {
+ drawFunctionPatterns(version);
+ drawCodewords(withEcc(version, data));
+ int best = 0;
+ long bestPenalty = Long.MAX_VALUE;
+ for (int mask = 0; mask < 8; mask++) {
+ applyMask(mask);
+ drawFormat(mask);
+ long p = penalty();
+ if (p < bestPenalty) {
+ best = mask;
+ bestPenalty = p;
+ }
+ applyMask(mask); // XOR again: undone
+ }
+ applyMask(best);
+ drawFormat(best);
+ }
+
+ // ---- function patterns ----
+
+ private void drawFunctionPatterns(int version) {
+ for (int i = 0; i < size; i++) {
+ set(6, i, i % 2 == 0);
+ set(i, 6, i % 2 == 0);
+ }
+ finder(3, 3);
+ finder(size - 4, 3);
+ finder(3, size - 4);
+ int[] align = alignmentPositions(version);
+ int n = align.length;
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < n; j++) {
+ if (i == 0 && j == 0 || i == 0 && j == n - 1 || i == n - 1 && j == 0) continue;
+ for (int dy = -2; dy <= 2; dy++) {
+ for (int dx = -2; dx <= 2; dx++) {
+ set(align[i] + dx, align[j] + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
+ }
+ }
+ }
+ }
+ drawFormat(0); // reserves the modules; drawn for real once the mask is chosen
+ if (version >= 7) {
+ int rem = version;
+ for (int i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
+ int bits = version << 12 | rem;
+ for (int i = 0; i < 18; i++) {
+ boolean bit = (bits >>> i & 1) != 0;
+ int a = size - 11 + i % 3;
+ int b = i / 3;
+ set(a, b, bit);
+ set(b, a, bit);
+ }
+ }
+ }
+
+ private void finder(int x, int y) {
+ for (int dy = -4; dy <= 4; dy++) {
+ for (int dx = -4; dx <= 4; dx++) {
+ int dist = Math.max(Math.abs(dx), Math.abs(dy));
+ int xx = x + dx;
+ int yy = y + dy;
+ if (xx >= 0 && xx < size && yy >= 0 && yy < size) set(xx, yy, dist != 2 && dist != 4);
+ }
+ }
+ }
+
+ private static int[] alignmentPositions(int version) {
+ if (version == 1) return new int[0];
+ int n = version / 7 + 2;
+ int step = (version * 4 + n * 2 + 1) / (n * 2 - 2) * 2;
+ int[] result = new int[n];
+ result[0] = 6;
+ for (int i = n - 1, pos = version * 4 + 10; i >= 1; i--, pos -= step) result[i] = pos;
+ return result;
+ }
+
+ private void drawFormat(int mask) {
+ int data = FORMAT_M << 3 | mask;
+ int rem = data;
+ for (int i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
+ int bits = (data << 10 | rem) ^ 0x5412;
+ for (int i = 0; i <= 5; i++) set(8, i, bit(bits, i));
+ set(8, 7, bit(bits, 6));
+ set(8, 8, bit(bits, 7));
+ set(7, 8, bit(bits, 8));
+ for (int i = 9; i < 15; i++) set(14 - i, 8, bit(bits, i));
+ for (int i = 0; i < 8; i++) set(size - 1 - i, 8, bit(bits, i));
+ for (int i = 8; i < 15; i++) set(8, size - 15 + i, bit(bits, i));
+ set(8, size - 8, true); // always dark
+ }
+
+ private void set(int x, int y, boolean isDark) {
+ dark[y][x] = isDark;
+ function[y][x] = true;
+ }
+
+ private static boolean bit(int value, int i) {
+ return (value >>> i & 1) != 0;
+ }
+
+ // ---- data ----
+
+ static int rawDataModules(int version) {
+ int result = (16 * version + 128) * version + 64;
+ if (version >= 2) {
+ int n = version / 7 + 2;
+ result -= (25 * n - 10) * n - 55;
+ if (version >= 7) result -= 36;
+ }
+ return result;
+ }
+
+ static int dataCodewords(int version) {
+ return rawDataModules(version) / 8 - ECC_PER_BLOCK[version] * BLOCKS[version];
+ }
+
+ private static byte[] withEcc(int version, byte[] data) {
+ int blocks = BLOCKS[version];
+ int eccLen = ECC_PER_BLOCK[version];
+ int raw = rawDataModules(version) / 8;
+ int shortBlocks = blocks - raw % blocks;
+ int shortLen = raw / blocks;
+ byte[] divisor = rsDivisor(eccLen);
+ byte[][] all = new byte[blocks][];
+ for (int i = 0, k = 0; i < blocks; i++) {
+ int datLen = shortLen - eccLen + (i < shortBlocks ? 0 : 1);
+ byte[] dat = new byte[datLen];
+ System.arraycopy(data, k, dat, 0, datLen);
+ k += datLen;
+ byte[] block = new byte[shortLen + 1];
+ System.arraycopy(dat, 0, block, 0, datLen);
+ byte[] ecc = rsRemainder(dat, divisor);
+ System.arraycopy(ecc, 0, block, block.length - eccLen, eccLen);
+ all[i] = block;
+ }
+ byte[] result = new byte[raw];
+ int n = 0;
+ for (int i = 0; i < shortLen + 1; i++) {
+ for (int j = 0; j < blocks; j++) {
+ // Short blocks have a gap where the long ones carry one more data byte.
+ if (i != shortLen - eccLen || j >= shortBlocks) result[n++] = all[j][i];
+ }
+ }
+ return result;
+ }
+
+ private static byte[] rsDivisor(int degree) {
+ byte[] result = new byte[degree];
+ result[degree - 1] = 1;
+ int root = 1;
+ for (int i = 0; i < degree; i++) {
+ for (int j = 0; j < degree; j++) {
+ result[j] = (byte) mul(result[j] & 0xFF, root);
+ if (j + 1 < degree) result[j] ^= result[j + 1];
+ }
+ root = mul(root, 0x02);
+ }
+ return result;
+ }
+
+ private static byte[] rsRemainder(byte[] data, byte[] divisor) {
+ byte[] result = new byte[divisor.length];
+ for (byte b : data) {
+ int factor = (b ^ result[0]) & 0xFF;
+ System.arraycopy(result, 1, result, 0, result.length - 1);
+ result[result.length - 1] = 0;
+ for (int i = 0; i < result.length; i++) result[i] ^= (byte) mul(divisor[i] & 0xFF, factor);
+ }
+ return result;
+ }
+
+ /** Multiplication in GF(2^8) modulo x^8 + x^4 + x^3 + x^2 + 1. */
+ private static int mul(int x, int y) {
+ int z = 0;
+ for (int i = 7; i >= 0; i--) {
+ z = (z << 1) ^ ((z >>> 7) * 0x11D);
+ z ^= ((y >>> i) & 1) * x;
+ }
+ return z & 0xFF;
+ }
+
+ private void drawCodewords(byte[] data) {
+ int i = 0;
+ for (int right = size - 1; right >= 1; right -= 2) {
+ if (right == 6) right = 5; // skip the vertical timing column
+ for (int vert = 0; vert < size; vert++) {
+ for (int j = 0; j < 2; j++) {
+ int x = right - j;
+ boolean upward = ((right + 1) & 2) == 0;
+ int y = upward ? size - 1 - vert : vert;
+ if (!function[y][x] && i < data.length * 8) {
+ dark[y][x] = ((data[i >>> 3] >>> (7 - (i & 7))) & 1) != 0;
+ i++;
+ }
+ }
+ }
+ }
+ }
+
+ private void applyMask(int mask) {
+ for (int y = 0; y < size; y++) {
+ for (int x = 0; x < size; x++) {
+ boolean invert;
+ switch (mask) {
+ case 0: invert = (x + y) % 2 == 0; break;
+ case 1: invert = y % 2 == 0; break;
+ case 2: invert = x % 3 == 0; break;
+ case 3: invert = (x + y) % 3 == 0; break;
+ case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
+ case 5: invert = x * y % 2 + x * y % 3 == 0; break;
+ case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
+ default: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
+ }
+ if (invert && !function[y][x]) dark[y][x] = !dark[y][x];
+ }
+ }
+ }
+
+ /** The spec's rules 1, 2 and 4: long runs, 2x2 blocks and the dark/light balance. Lower is easier to read. */
+ private long penalty() {
+ long p = 0;
+ for (int a = 0; a < size; a++) {
+ int rowRun = 1;
+ int colRun = 1;
+ for (int b = 1; b < size; b++) {
+ if (dark[a][b] == dark[a][b - 1]) {
+ if (++rowRun == 5) p += 3; else if (rowRun > 5) p++;
+ } else rowRun = 1;
+ if (dark[b][a] == dark[b - 1][a]) {
+ if (++colRun == 5) p += 3; else if (colRun > 5) p++;
+ } else colRun = 1;
+ }
+ }
+ int darkCount = 0;
+ for (int y = 0; y < size; y++) {
+ for (int x = 0; x < size; x++) {
+ if (dark[y][x]) darkCount++;
+ if (x + 1 < size && y + 1 < size && dark[y][x] == dark[y][x + 1]
+ && dark[y][x] == dark[y + 1][x] && dark[y][x] == dark[y + 1][x + 1]) p += 3;
+ }
+ }
+ int total = size * size;
+ int k = (Math.abs(darkCount * 20 - total * 10) + total - 1) / total - 1;
+ return p + Math.max(k, 0) * 10L;
+ }
+
+ private static final class Bits {
+ final byte[] bytes;
+ int length;
+
+ Bits(int capacityBits) {
+ bytes = new byte[capacityBits / 8];
+ }
+
+ void add(int value, int count) {
+ for (int i = count - 1; i >= 0; i--, length++) {
+ if ((value >>> i & 1) != 0) bytes[length >>> 3] |= (byte) (0x80 >>> (length & 7));
+ }
+ }
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/QrView.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/QrView.java
new file mode 100644
index 000000000..a0337e631
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/QrView.java
@@ -0,0 +1,62 @@
+package com.gathin.newsdream;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Outline;
+import android.graphics.Paint;
+import android.view.View;
+import android.view.ViewOutlineProvider;
+
+/**
+ * Draws a QR code with the four-module quiet zone, scaled to whole pixels per module: the screen's navy on a muted
+ * blue-grey, the tone of the summary text, so it sits with the rest instead of glaring white. About 9:1 contrast,
+ * which phones read easily.
+ */
+final class QrView extends View {
+ private static final int QUIET = 4;
+ private static final int LIGHT = 0xFFAEB6C6;
+ private static final int DARK = 0xFF101A30;
+ private final Paint paint = new Paint();
+ private boolean[][] modules;
+
+ QrView(Context context) {
+ super(context);
+ paint.setColor(DARK);
+ paint.setAntiAlias(false);
+ float radius = 10 * context.getResources().getDisplayMetrics().density;
+ setOutlineProvider(new ViewOutlineProvider() {
+ @Override
+ public void getOutline(View view, Outline outline) {
+ outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), radius);
+ }
+ });
+ setClipToOutline(true);
+ }
+
+ /** The address to show; false when there is none or it is too long, and the view should be hidden. */
+ boolean setText(String text) {
+ modules = text == null || text.isEmpty() ? null : Qr.encode(text);
+ invalidate();
+ return modules != null;
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ canvas.drawColor(LIGHT);
+ if (modules == null) return;
+ int n = modules.length + 2 * QUIET;
+ int side = Math.min(getWidth(), getHeight());
+ int scale = Math.max(1, side / n);
+ // Centred, so the rounding leftover becomes extra light border.
+ int left = (getWidth() - scale * n) / 2 + QUIET * scale;
+ int top = (getHeight() - scale * n) / 2 + QUIET * scale;
+ for (int y = 0; y < modules.length; y++) {
+ for (int x = 0; x < modules.length; x++) {
+ if (modules[y][x]) {
+ canvas.drawRect(left + x * scale, top + y * scale,
+ left + (x + 1) * scale, top + (y + 1) * scale, paint);
+ }
+ }
+ }
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Scene.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Scene.java
new file mode 100644
index 000000000..6253fa968
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/Scene.java
@@ -0,0 +1,298 @@
+package com.gathin.newsdream;
+
+import android.content.Context;
+import android.graphics.Color;
+import android.graphics.Typeface;
+import android.graphics.drawable.GradientDrawable;
+import android.os.Handler;
+import android.os.Looper;
+import android.text.TextUtils;
+import android.text.format.DateUtils;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.animation.LinearInterpolator;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.TextClock;
+import android.widget.TextView;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * What the screensaver and the card show: one headline at a time, its source and age above it and a line of
+ * summary below, crossfading to the next after the set seconds. A QR code to the article in the bottom corner,
+ * and "3 / 42" beside the progress line. A clock in the corner. Every part keeps its place from one headline to
+ * the next; only the whole picture drifts a few dp, very slowly, against burn-in. Feeds are fetched on start and every 15 minutes while it shows.
+ */
+final class Scene {
+ private static final int ACCENT = 0xFFFF8A5B;
+ private static final long FADE_MS = 450;
+ private static final long RETRY_MS = 2 * 60_000L;
+ // The fixed layout, in dp.
+ private static final int TOP = 140;
+ private static final int SOURCE = 28;
+ private static final int GAP = 12;
+ private static final int TITLE = 156;
+ private static final int SUMMARY = 96; // three lines of 20sp
+ private static final int QR = 176;
+ // Against burn-in: the whole picture moves together, a few dp round a small circle, one step every two minutes,
+ // sliding there over half a minute. Nothing moves when a headline changes.
+ private static final int SHIFT_DP = 6;
+ private static final int SHIFT_STEPS = 8;
+ private static final long SHIFT_EVERY_MS = 2 * 60_000L;
+ private static final long SHIFT_SLIDE_MS = 30_000L;
+
+ final FrameLayout root;
+ private final Context context;
+ private final File dir;
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private final LinearLayout block;
+ private final TextView source;
+ private final TextView title;
+ private final TextView summary;
+ private final View progress;
+ private final TextView counter;
+ private final QrView qr;
+ private final TextClock clock;
+
+ private List<Headline> headlines = new ArrayList<>();
+ private List<String> feeds;
+ private long secondsMs;
+ private int index = -1;
+ private boolean running;
+ private ExecutorService executor;
+
+ private final FrameLayout stage;
+ private int shiftStep;
+
+ private final Runnable next = this::next;
+ private final Runnable shift = this::shift;
+ private final Runnable refresh = this::refresh;
+
+ Scene(Context context) {
+ this.context = context;
+ this.dir = context.getFilesDir();
+
+ root = new FrameLayout(context);
+ GradientDrawable sky = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
+ new int[]{0xFF14203A, 0xFF070B14});
+ root.setBackground(sky);
+ root.setKeepScreenOn(true);
+ stage = new FrameLayout(context);
+ root.addView(stage, new FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
+
+ clock = new TextClock(context);
+ clock.setTextColor(0xCCFFFFFF);
+ clock.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
+ clock.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
+ FrameLayout.LayoutParams clp = new FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.END);
+ clp.setMargins(dp(64), dp(48), dp(64), 0);
+ stage.addView(clock, clp);
+
+ // A fixed layout: every part has its own place and height, so nothing moves when the headline changes.
+ // On a 1080p TV (540dp high): source at 140dp, the headline box under it, summary, then the count.
+ block = new LinearLayout(context);
+ block.setOrientation(LinearLayout.VERTICAL);
+ FrameLayout.LayoutParams blp = new FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.START);
+ // The end margin leaves room for the QR code.
+ blp.setMargins(dp(112), dp(TOP), dp(112 + QR + 48), 0);
+ stage.addView(block, blp);
+
+ source = text(18, ACCENT, 1);
+ source.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
+ source.setLetterSpacing(0.08f);
+ source.setAllCaps(true);
+ block.addView(source, fixed(dp(SOURCE), 0));
+
+ // Three lines at most; a long headline gets smaller type rather than more room.
+ title = text(44, Color.WHITE, 3);
+ title.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
+ title.setLineSpacing(0, 1.08f);
+ title.setAutoSizeTextTypeUniformWithConfiguration(26, 44, 2, TypedValue.COMPLEX_UNIT_SP);
+ block.addView(title, fixed(dp(TITLE), dp(GAP)));
+
+ summary = text(20, 0xB3FFFFFF, 3);
+ summary.setLineSpacing(0, 1.15f);
+ block.addView(summary, fixed(dp(SUMMARY), dp(16)));
+
+ LinearLayout bottom = new LinearLayout(context);
+ bottom.setOrientation(LinearLayout.HORIZONTAL);
+ bottom.setGravity(Gravity.CENTER_VERTICAL);
+ block.addView(bottom, fixed(dp(24), dp(24)));
+ // "3 / 42" first, in a box of its own width, so the line after it starts in the same place every time.
+ counter = text(16, 0x99FFFFFF, 1);
+ counter.setShadowLayer(0, 0, 0, 0);
+ bottom.addView(counter, new LinearLayout.LayoutParams(dp(80), ViewGroup.LayoutParams.WRAP_CONTENT));
+ progress = new View(context);
+ progress.setBackgroundColor(ACCENT);
+ progress.setAlpha(0.7f);
+ progress.setPivotX(0);
+ bottom.addView(progress, new LinearLayout.LayoutParams(dp(220), dp(3)));
+
+ // Level with the top of the headline.
+ qr = new QrView(context);
+ qr.setVisibility(View.INVISIBLE);
+ qr.setAlpha(0.92f);
+ FrameLayout.LayoutParams qlp = new FrameLayout.LayoutParams(dp(QR), dp(QR), Gravity.TOP | Gravity.END);
+ qlp.setMargins(0, dp(TOP + SOURCE + GAP), dp(112), 0);
+ stage.addView(qr, qlp);
+ }
+
+ void start() {
+ if (running) return;
+ running = true;
+ handler.postDelayed(shift, SHIFT_EVERY_MS);
+ feeds = Config.feeds(dir);
+ secondsMs = Config.seconds(dir) * 1000L;
+ executor = Executors.newSingleThreadExecutor();
+ if (feeds.isEmpty()) {
+ status(R.string.no_feeds_title, R.string.no_feeds_body);
+ return;
+ }
+ headlines = new ArrayList<>(News.load(dir));
+ index = -1;
+ if (headlines.isEmpty()) status(R.string.loading_title, 0);
+ else next();
+ long age = System.currentTimeMillis() - News.cacheTime(dir);
+ if (headlines.isEmpty() || age >= News.REFRESH_MS || age < 0) refresh();
+ else handler.postDelayed(refresh, News.REFRESH_MS - age);
+ }
+
+ void stop() {
+ running = false;
+ handler.removeCallbacksAndMessages(null);
+ progress.animate().cancel();
+ block.animate().cancel();
+ stage.animate().cancel();
+ if (executor != null) executor.shutdownNow();
+ executor = null;
+ }
+
+ private void shift() {
+ if (!running) return;
+ shiftStep = (shiftStep + 1) % SHIFT_STEPS;
+ double angle = 2 * Math.PI * shiftStep / SHIFT_STEPS;
+ stage.animate()
+ .translationX((float) (dp(SHIFT_DP) * Math.cos(angle)))
+ .translationY((float) (dp(SHIFT_DP) * Math.sin(angle)))
+ .setDuration(SHIFT_SLIDE_MS).setInterpolator(new LinearInterpolator()).start();
+ handler.postDelayed(shift, SHIFT_EVERY_MS);
+ }
+
+ /** One headline on (+1, Right on the remote) or back (-1, Left), now; the timer starts again. */
+ void step(int delta) {
+ if (!running || headlines.isEmpty()) return;
+ int n = headlines.size();
+ index = ((index + delta - 1) % n + n) % n; // advance() adds the one back
+ advance(false);
+ }
+
+ private void refresh() {
+ if (!running || executor == null) return;
+ List<String> urls = feeds;
+ executor.execute(() -> {
+ List<Headline> fresh = News.fetch(urls, System.currentTimeMillis());
+ if (!fresh.isEmpty()) News.save(dir, fresh);
+ handler.post(() -> loaded(fresh));
+ });
+ }
+
+ private void loaded(List<Headline> fresh) {
+ if (!running) return;
+ handler.removeCallbacks(refresh);
+ if (fresh.isEmpty()) {
+ // Keep showing the old list; try again sooner.
+ if (headlines.isEmpty()) status(R.string.offline_title, R.string.offline_body);
+ handler.postDelayed(refresh, RETRY_MS);
+ return;
+ }
+ boolean first = headlines.isEmpty();
+ headlines = fresh;
+ if (first) {
+ index = -1;
+ next();
+ } else if (index >= headlines.size()) {
+ index = -1;
+ }
+ handler.postDelayed(refresh, News.REFRESH_MS);
+ }
+
+ private void next() {
+ advance(true);
+ }
+
+ /** The next headline, crossfading on the timer and at once when the remote asks. */
+ private void advance(boolean fade) {
+ if (!running || headlines.isEmpty()) return;
+ index = (index + 1) % headlines.size();
+ Headline h = headlines.get(index);
+ if (!fade || title.getText().length() == 0) {
+ block.animate().cancel();
+ block.setAlpha(1f);
+ show(h);
+ } else {
+ block.animate().alpha(0f).setDuration(FADE_MS).withEndAction(() -> {
+ show(h);
+ block.animate().alpha(1f).setDuration(FADE_MS).start();
+ }).start();
+ }
+ handler.removeCallbacks(next);
+ handler.postDelayed(next, secondsMs);
+ }
+
+ private void show(Headline h) {
+ String age = h.time > 0 ? DateUtils.getRelativeTimeSpanString(Math.min(h.time, System.currentTimeMillis()),
+ System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE).toString() : "";
+ source.setText(age.isEmpty() ? h.source : h.source + " · " + age);
+ title.setText(h.title);
+ summary.setText(h.summary);
+ counter.setText(String.format(Locale.getDefault(), "%d / %d", index + 1, headlines.size()));
+ qr.setVisibility(qr.setText(h.link) ? View.VISIBLE : View.INVISIBLE);
+ progress.setVisibility(View.VISIBLE);
+ progress.animate().cancel();
+ progress.setScaleX(0f);
+ progress.animate().scaleX(1f).setDuration(secondsMs).setInterpolator(new LinearInterpolator()).start();
+ }
+
+ private void status(int titleText, int body) {
+ source.setText(R.string.dream_name);
+ title.setText(titleText);
+ summary.setText(body == 0 ? "" : context.getString(body));
+ progress.animate().cancel();
+ progress.setVisibility(View.INVISIBLE);
+ counter.setText("");
+ qr.setVisibility(View.INVISIBLE);
+ block.setAlpha(1f);
+ }
+
+ private TextView text(int sp, int color, int maxLines) {
+ TextView t = new TextView(context);
+ t.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp);
+ t.setTextColor(color);
+ t.setMaxLines(maxLines);
+ t.setEllipsize(TextUtils.TruncateAt.END);
+ t.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
+ t.setShadowLayer(dp(6), 0, dp(1), 0x66000000);
+ return t;
+ }
+
+ private static LinearLayout.LayoutParams fixed(int height, int top) {
+ LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
+ lp.topMargin = top;
+ return lp;
+ }
+
+ private int dp(int value) {
+ return Math.round(value * context.getResources().getDisplayMetrics().density);
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/SettingsActivity.java b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/SettingsActivity.java
new file mode 100644
index 000000000..dbdb56600
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/java/com/gathin/newsdream/SettingsActivity.java
@@ -0,0 +1,193 @@
+package com.gathin.newsdream;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.Intent;
+import android.os.Bundle;
+import android.text.InputType;
+import android.util.TypedValue;
+import android.view.inputmethod.EditorInfo;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.ScrollView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * The settings, for the remote's D-pad: seconds per headline, and the feeds (OK on one removes it, the field
+ * below adds one). Reached from the TV's screensaver settings.
+ * When the screensaver starts is the TV's own setting (or setup.sh's IDLE_MINUTES).
+ */
+public class SettingsActivity extends Activity {
+
+ private File dir;
+ private Button secondsButton;
+ private LinearLayout feedList;
+ private EditText address;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ dir = getFilesDir();
+ int pad = dp(48);
+ LinearLayout list = new LinearLayout(this);
+ list.setOrientation(LinearLayout.VERTICAL);
+ list.setPadding(pad * 2, pad, pad * 2, pad);
+
+ TextView title = new TextView(this);
+ title.setText(R.string.settings_title);
+ title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
+ title.setPadding(0, 0, 0, dp(16));
+ list.addView(title);
+
+ secondsButton = new Button(this);
+ secondsButton.setOnClickListener(v -> {
+ int next = Config.nextSeconds(Config.seconds(dir));
+ Config.write(new File(dir, Config.SECONDS), String.valueOf(next));
+ updateSeconds();
+ });
+ list.addView(secondsButton, wrap(0));
+ updateSeconds();
+
+ list.addView(heading(R.string.feeds_heading));
+ feedList = new LinearLayout(this);
+ feedList.setOrientation(LinearLayout.VERTICAL);
+ list.addView(feedList);
+
+ address = new EditText(this);
+ address.setHint(R.string.feed_hint);
+ address.setSingleLine(true);
+ address.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
+ address.setImeOptions(EditorInfo.IME_ACTION_DONE);
+ address.setOnEditorActionListener((v, action, event) -> {
+ add();
+ return true;
+ });
+ LinearLayout.LayoutParams alp = new LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
+ alp.topMargin = dp(8);
+ list.addView(address, alp);
+
+ Button add = new Button(this);
+ add.setText(R.string.feed_add);
+ add.setOnClickListener(v -> add());
+ list.addView(add, wrap(0));
+
+ TextView info = new TextView(this);
+ info.setText(R.string.settings_info);
+ info.setPadding(dp(8), dp(24), 0, dp(8));
+ list.addView(info);
+
+ Button preview = new Button(this);
+ preview.setText(R.string.preview);
+ preview.setOnClickListener(v -> startActivity(new Intent(this, NewsActivity.class)));
+ list.addView(preview, wrap(dp(16)));
+
+ ScrollView scroll = new ScrollView(this);
+ scroll.addView(list);
+ setContentView(scroll);
+ secondsButton.requestFocus();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ updateFeeds(); // setup.sh may have changed them meanwhile
+ updateSeconds();
+ }
+
+ private void updateSeconds() {
+ secondsButton.setText(getString(R.string.seconds_per_headline, Config.seconds(dir)));
+ }
+
+ private void updateFeeds() {
+ feedList.removeAllViews();
+ List<String> feeds = Config.feeds(dir);
+ if (feeds.isEmpty()) {
+ TextView none = new TextView(this);
+ none.setText(R.string.no_feeds_body);
+ none.setPadding(dp(8), dp(8), 0, dp(8));
+ feedList.addView(none);
+ }
+ for (String url : feeds) {
+ Button b = new Button(this);
+ b.setText(url);
+ b.setAllCaps(false);
+ b.setSingleLine(true);
+ b.setOnClickListener(v -> new AlertDialog.Builder(this)
+ .setTitle(R.string.feed_remove)
+ .setMessage(url)
+ .setPositiveButton(R.string.feed_remove_yes, (d, w) -> remove(url))
+ .setNegativeButton(android.R.string.cancel, null)
+ .show());
+ feedList.addView(b, wrap(0));
+ }
+ }
+
+ private void add() {
+ String text = address.getText().toString().trim();
+ if (text.isEmpty()) return;
+ // "Name | address" or just the address; https:// is added when it is left out.
+ int bar = text.lastIndexOf('|');
+ String head = bar < 0 ? "" : text.substring(0, bar + 1);
+ String tail = text.substring(bar + 1).trim();
+ if (!tail.contains("://")) tail = "https://" + tail;
+ String feed = Config.feed(head + tail);
+ List<String> feeds = new ArrayList<>(Config.feeds(dir));
+ if (feed == null) {
+ Toast.makeText(this, R.string.feed_invalid, Toast.LENGTH_LONG).show();
+ return;
+ }
+ for (int i = 0; i < feeds.size(); i++) {
+ if (Config.url(feeds.get(i)).equals(Config.url(feed))) {
+ feeds.set(i, feed); // same address again: the new name wins, in the same place
+ save(feeds);
+ address.setText("");
+ return;
+ }
+ }
+ if (feeds.size() >= Config.MAX_FEEDS) {
+ Toast.makeText(this, getString(R.string.feed_too_many, Config.MAX_FEEDS), Toast.LENGTH_LONG).show();
+ return;
+ }
+ feeds.add(feed);
+ save(feeds);
+ address.setText("");
+ }
+
+ private void remove(String url) {
+ List<String> feeds = new ArrayList<>(Config.feeds(dir));
+ feeds.remove(url);
+ save(feeds);
+ }
+
+ private void save(List<String> feeds) {
+ Config.write(new File(dir, Config.FEEDS), Config.feedsText(feeds));
+ News.clearCache(dir);
+ updateFeeds();
+ }
+
+ private TextView heading(int text) {
+ TextView t = new TextView(this);
+ t.setText(text);
+ t.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
+ t.setPadding(dp(8), dp(24), 0, dp(4));
+ return t;
+ }
+
+ private LinearLayout.LayoutParams wrap(int top) {
+ LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
+ lp.topMargin = top;
+ return lp;
+ }
+
+ private int dp(int value) {
+ return Math.round(value * getResources().getDisplayMetrics().density);
+ }
+}
diff --git a/addons/news-screensaver/app/src/main/res/drawable/banner.xml b/addons/news-screensaver/app/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..9ed37cd3d
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/res/drawable/banner.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 320x180, as Android TV banners are: a folded newspaper on a dark blue field. -->
+<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="#FF14203A" android:pathData="M0,0h320v180h-320z" />
+ <path android:fillColor="#FFF2F2F2" android:pathData="M96,36h128v108h-128z" />
+ <path android:fillColor="#FFFF8A5B" android:pathData="M108,48h104v14h-104z" />
+ <path android:fillColor="#FF14203A" android:pathData="M108,72h48v40h-48z" />
+ <path android:fillColor="#FF8A93A6" android:pathData="M164,72h48v6h-48zM164,86h48v6h-48zM164,100h48v6h-48zM108,120h104v6h-104z" />
+</vector>
diff --git a/addons/news-screensaver/app/src/main/res/drawable/icon.xml b/addons/news-screensaver/app/src/main/res/drawable/icon.xml
new file mode 100644
index 000000000..0e560dbd9
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/res/drawable/icon.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A newspaper page with a headline bar. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="48dp"
+ android:height="48dp"
+ android:viewportWidth="48"
+ android:viewportHeight="48">
+ <path android:fillColor="#FF14203A" android:pathData="M0,0h48v48h-48z" />
+ <path android:fillColor="#FFF2F2F2" android:pathData="M9,10h30v28h-30z" />
+ <path android:fillColor="#FFFF8A5B" android:pathData="M12,13h24v4h-24z" />
+ <path android:fillColor="#FF14203A" android:pathData="M12,20h10v9h-10z" />
+ <path android:fillColor="#FF8A93A6" android:pathData="M25,20h11v2h-11zM25,24h11v2h-11zM25,28h11v2h-11zM12,32h24v2h-24z" />
+</vector>
diff --git a/addons/news-screensaver/app/src/main/res/values-da/strings.xml b/addons/news-screensaver/app/src/main/res/values-da/strings.xml
new file mode 100644
index 000000000..1bdc071e9
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/res/values-da/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Nyheds-pauseskærm</string>
+ <string name="dream_name">Nyheder</string>
+ <string name="loading_title">Henter nyheder…</string>
+ <string name="offline_title">Ingen nyheder lige nu</string>
+ <string name="offline_body">Kilderne kunne ikke nås. Tjek tv\'ets netværksforbindelse og kildernes adresser; pauseskærmen prøver igen om et par minutter.</string>
+ <string name="no_feeds_title">Ingen kilder</string>
+ <string name="no_feeds_body">Tilføj et RSS- eller Atom-feed i pauseskærmens indstillinger eller med setup.sh.</string>
+ <string name="settings_title">Nyheds-pauseskærm</string>
+ <string name="seconds_per_headline">Sekunder pr. overskrift: %1$d</string>
+ <string name="feeds_heading">Kilder (OK på en kilde fjerner den)</string>
+ <string name="feed_add">Tilføj kilde</string>
+ <string name="feed_hint">Navn | https://example.com/rss.xml (navnet kan udelades)</string>
+ <string name="feed_invalid">Brug en https://-adresse, gerne efter et navn og en streg: Navn | https://…</string>
+ <string name="feed_too_many">Listen over kilder er fuld (%1$d).</string>
+ <string name="feed_remove">Fjern denne kilde?</string>
+ <string name="feed_remove_yes">Fjern</string>
+ <string name="settings_info">Hvornår pauseskærmen starter, indstilles i tv\'ets egne indstillinger (Pauseskærm eller Energibesparelse) eller med setup.sh. Nyhederne opdateres hvert 15. minut, mens den vises.</string>
+ <string name="preview">Vis eksempel</string>
+</resources>
diff --git a/addons/news-screensaver/app/src/main/res/values/strings.xml b/addons/news-screensaver/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..781c32d73
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/res/values/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">News screensaver</string>
+ <string name="dream_name">News</string>
+ <string name="loading_title">Fetching the news…</string>
+ <string name="offline_title">No news right now</string>
+ <string name="offline_body">The feeds could not be reached. Check the TV\'s network connection and the feed addresses; the screensaver tries again in a couple of minutes.</string>
+ <string name="no_feeds_title">No feeds</string>
+ <string name="no_feeds_body">Add an RSS or Atom feed in the screensaver\'s settings, or with setup.sh.</string>
+ <string name="settings_title">News screensaver</string>
+ <string name="seconds_per_headline">Seconds per headline: %1$d</string>
+ <string name="feeds_heading">Feeds (OK on one removes it)</string>
+ <string name="feed_hint">Name | https://example.com/rss.xml (the name is optional)</string>
+ <string name="feed_add">Add feed</string>
+ <string name="feed_invalid">Use an https:// address, if you like after a name and a bar: Name | https://…</string>
+ <string name="feed_too_many">The feed list is full (%1$d).</string>
+ <string name="feed_remove">Remove this feed?</string>
+ <string name="feed_remove_yes">Remove</string>
+ <string name="settings_info">When the screensaver starts is set in the TV\'s own settings (Screensaver, or Energy saving), or with setup.sh. News is refreshed every 15 minutes while it shows.</string>
+ <string name="preview">Preview</string>
+</resources>
diff --git a/addons/news-screensaver/app/src/main/res/xml/dream.xml b/addons/news-screensaver/app/src/main/res/xml/dream.xml
new file mode 100644
index 000000000..a8d145af6
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/res/xml/dream.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Gives the screensaver a settings entry in the TV's screensaver menu. -->
+<dream xmlns:android="http://schemas.android.com/apk/res/android"
+ android:settingsActivity="com.gathin.newsdream/.SettingsActivity" />
diff --git a/addons/news-screensaver/app/src/main/res/xml/module_card.xml b/addons/news-screensaver/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..2fe5bd47c
--- /dev/null
+++ b/addons/news-screensaver/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="News" caption="Headlines" accent="#FF8A5B" />
diff --git a/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/ConfigTest.java b/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/ConfigTest.java
new file mode 100644
index 000000000..da020d791
--- /dev/null
+++ b/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/ConfigTest.java
@@ -0,0 +1,92 @@
+package com.gathin.newsdream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class ConfigTest {
+
+ @Test public void providerWritesOnlyTheTwoFiles() {
+ assertEquals("feeds.txt", Config.path(Collections.singletonList("feeds.txt")));
+ assertEquals("seconds.txt", Config.path(Collections.singletonList("seconds.txt")));
+ assertNull(Config.path(Collections.singletonList("cache.bin")));
+ assertNull(Config.path(Collections.singletonList("..")));
+ assertNull(Config.path(Arrays.asList("x", "feeds.txt")));
+ assertNull(Config.path(Collections.emptyList()));
+ assertNull(Config.path(null));
+ }
+
+ @Test public void onlyHttpsAddresses() {
+ assertTrue(Config.validUrl("https://feeds.bbci.co.uk/news/world/rss.xml"));
+ assertTrue(Config.validUrl("HTTPS://www.dr.dk/nyheder/service/feeds/senestenyt"));
+ assertFalse(Config.validUrl("http://example.com/rss"));
+ assertFalse(Config.validUrl("https://"));
+ assertFalse(Config.validUrl("https://exa mple.com/rss"));
+ assertFalse(Config.validUrl("file:///sdcard/rss.xml"));
+ assertFalse(Config.validUrl("example.com/rss"));
+ assertFalse(Config.validUrl(null));
+ }
+
+ @Test public void feedsSkipCommentsBadLinesAndDuplicates() {
+ String text = "# my feeds\n"
+ + "https://a.example/rss\n"
+ + "\n"
+ + " https://b.example/atom \r\n"
+ + "http://plain.example/rss\n"
+ + "https://a.example/rss\n";
+ assertEquals(Arrays.asList("https://a.example/rss", "https://b.example/atom"), Config.feeds(text));
+ }
+
+ @Test public void feedsMayHaveANameBeforeABar() {
+ assertEquals("DR | https://www.dr.dk/rss", Config.feed(" DR| https://www.dr.dk/rss "));
+ assertEquals("Kort nyt | DR | https://www.dr.dk/rss", Config.feed("Kort nyt | DR | https://www.dr.dk/rss"));
+ assertEquals("https://www.dr.dk/rss", Config.feed(" | https://www.dr.dk/rss"));
+ assertNull(Config.feed("DR | http://www.dr.dk/rss"));
+ assertNull(Config.feed("A name much longer than forty characters in all | https://x.example/rss"));
+ assertEquals("https://www.dr.dk/rss", Config.url("DR | https://www.dr.dk/rss"));
+ assertEquals("DR", Config.name("DR | https://www.dr.dk/rss"));
+ assertEquals("", Config.name("https://www.dr.dk/rss"));
+ // One line per address: the first one, name and all, wins.
+ assertEquals(Arrays.asList("B.T. | https://www.bt.dk/rss", "https://tv2.example/rss"),
+ Config.feeds("B.T. | https://www.bt.dk/rss\nhttps://www.bt.dk/rss\nhttps://tv2.example/rss\n"));
+ }
+
+ @Test public void noFileMeansTheDefaultFeedAnEmptyFileMeansNone() {
+ assertEquals(Config.DEFAULT_FEEDS, Config.feeds((String) null));
+ assertTrue(Config.feeds("").isEmpty());
+ assertTrue(Config.feeds("# nothing yet\n").isEmpty());
+ }
+
+ @Test public void atMostTenFeeds() {
+ StringBuilder text = new StringBuilder();
+ for (int i = 0; i < 15; i++) text.append("https://f").append(i).append(".example/rss\n");
+ List<String> feeds = Config.feeds(text.toString());
+ assertEquals(Config.MAX_FEEDS, feeds.size());
+ assertEquals("https://f0.example/rss", feeds.get(0));
+ assertEquals(feeds, Config.feeds(Config.feedsText(feeds)));
+ }
+
+ @Test public void secondsDefaultToFifteen() {
+ assertEquals(15, Config.seconds((String) null));
+ assertEquals(15, Config.seconds("abc"));
+ assertEquals(15, Config.seconds("4"));
+ assertEquals(15, Config.seconds("601"));
+ assertEquals(5, Config.seconds("5"));
+ assertEquals(30, Config.seconds(" 30\n"));
+ assertEquals(600, Config.seconds("600"));
+ }
+
+ @Test public void secondsStepRoundTheChoices() {
+ assertEquals(20, Config.nextSeconds(15));
+ assertEquals(8, Config.nextSeconds(120));
+ assertEquals(8, Config.nextSeconds(600));
+ assertEquals(10, Config.nextSeconds(9));
+ }
+}
diff --git a/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/FeedParserTest.java b/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/FeedParserTest.java
new file mode 100644
index 000000000..08bf2819b
--- /dev/null
+++ b/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/FeedParserTest.java
@@ -0,0 +1,159 @@
+package com.gathin.newsdream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class FeedParserTest {
+
+ private static FeedParser.Feed parse(String xml) throws IOException {
+ return FeedParser.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)), "host.example");
+ }
+
+ @Test public void rss2() throws IOException {
+ FeedParser.Feed feed = parse("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ + "<rss version=\"2.0\" xmlns:media=\"http://search.yahoo.com/mrss/\"><channel>"
+ + "<title>DR Nyheder</title><image><title>DR logo</title></image>"
+ + "<link>https://www.dr.dk/</link>"
+ + "<item><title>Første &amp; bedste</title><link> https://www.dr.dk/nyheder/a </link>"
+ + "<description><![CDATA[<p>Et <b>resumé</b>&nbsp;her</p>]]></description>"
+ + "<media:content url=\"https://x/y.jpg\"><media:title>Photo</media:title></media:content>"
+ // 25 October 2026 is a Sunday: a wrong weekday must not lose the date.
+ + "<pubDate>Sat, 25 Oct 2026 14:05:00 +0200</pubDate></item>"
+ + "<item><title>Second</title><pubDate>Sat, 25 Oct 2026 12:00:00 GMT</pubDate></item>"
+ + "</channel></rss>");
+ assertEquals("DR Nyheder", feed.title);
+ assertEquals(2, feed.items.size());
+ Headline first = feed.items.get(0);
+ assertEquals("DR Nyheder", first.source);
+ assertEquals("Første & bedste", first.title);
+ assertEquals("Et resumé her", first.summary);
+ assertEquals(FeedParser.date("2026-10-25T12:05:00Z"), first.time);
+ assertEquals("https://www.dr.dk/nyheder/a", first.link);
+ assertEquals("", feed.items.get(1).summary);
+ assertTrue(feed.items.get(1).time > 0);
+ }
+
+ @Test public void atomWithXhtmlContent() throws IOException {
+ FeedParser.Feed feed = parse("<feed xmlns=\"http://www.w3.org/2005/Atom\">"
+ + "<title type=\"text\">Example Atom</title>"
+ + "<link href=\"https://example.com/\"/>"
+ + "<entry><title>Atom entry</title>"
+ + "<link rel=\"enclosure\" href=\"https://example.com/a.mp3\"/>"
+ + "<link href=\"https://example.com/entry\"/><updated>2026-10-25T10:00:00Z</updated>"
+ + "<published>2026-10-25T09:30:00.123456+02:00</published>"
+ + "<content type=\"xhtml\"><div xmlns=\"http://www.w3.org/1999/xhtml\"><p>One</p><p>two</p></div></content>"
+ + "</entry></feed>");
+ assertEquals("Example Atom", feed.title);
+ Headline h = feed.items.get(0);
+ assertEquals("Atom entry", h.title);
+ assertEquals("One two", h.summary);
+ assertEquals("https://example.com/entry", h.link);
+ assertEquals(FeedParser.date("2026-10-25T07:30:00.123Z"), h.time);
+ }
+
+ @Test public void rdfWithDcDate() throws IOException {
+ FeedParser.Feed feed = parse("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\""
+ + " xmlns=\"http://purl.org/rss/1.0/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
+ + "<channel><title>RDF feed</title></channel>"
+ + "<item><title>RDF item</title><dc:date>2026-10-25T08:00:00+00:00</dc:date></item>"
+ + "</rdf:RDF>");
+ assertEquals("RDF feed", feed.title);
+ assertEquals("RDF item", feed.items.get(0).title);
+ assertEquals(FeedParser.date("2026-10-25T08:00:00Z"), feed.items.get(0).time);
+ }
+
+ @Test public void noFeedTitleUsesTheHostAndUntitledItemsAreSkipped() throws IOException {
+ FeedParser.Feed feed = parse("<rss><channel><item><description>no title</description></item>"
+ + "<item><title> Kept </title></item></channel></rss>");
+ assertEquals("host.example", feed.title);
+ assertEquals(1, feed.items.size());
+ assertEquals("Kept", feed.items.get(0).title);
+ }
+
+ @Test public void stopsAfterTwentyItems() throws IOException {
+ StringBuilder xml = new StringBuilder("<rss><channel><title>Many</title>");
+ for (int i = 0; i < 50; i++) xml.append("<item><title>Item ").append(i).append("</title></item>");
+ xml.append("</channel></rss>");
+ assertEquals(FeedParser.MAX_ITEMS, parse(xml.toString()).items.size());
+ }
+
+ @Test(expected = IOException.class) public void notAFeed() throws IOException {
+ parse("<html><body>Not found</body>");
+ }
+
+ @Test public void linksAreHttpAndShort() {
+ assertEquals("https://a.example/x", FeedParser.link(" https://a.example/x\n"));
+ assertEquals("http://a.example/x", FeedParser.link("http://a.example/x"));
+ assertEquals("", FeedParser.link("javascript:alert(1)"));
+ assertEquals("", FeedParser.link("https://a.example/a b"));
+ assertEquals("", FeedParser.link(null));
+ StringBuilder longLink = new StringBuilder("https://a.example/");
+ while (longLink.length() <= 400) longLink.append('x');
+ assertEquals("", FeedParser.link(longLink.toString()));
+ }
+
+ @Test public void cleanText() {
+ assertEquals("a & b", FeedParser.clean("a &amp;amp; b", 100));
+ assertEquals("bold", FeedParser.clean("&lt;b&gt;bold&lt;/b&gt;", 100));
+ assertEquals("æøå — é", FeedParser.clean("&aelig;&oslash;&aring; &mdash; &#233;", 100));
+ assertEquals("keep &unknown; as is", FeedParser.clean("keep &unknown; as is", 100));
+ assertEquals("one two three…", FeedParser.clean("one two three four five six", 16));
+ assertEquals("", FeedParser.clean(null, 10));
+ }
+
+ @Test public void dates() {
+ long t = FeedParser.date("2026-10-25T12:00:00Z");
+ assertTrue(t > 0);
+ assertEquals(t, FeedParser.date("Sun, 25 Oct 2026 12:00:00 GMT"));
+ assertEquals(t, FeedParser.date("Sun, 25 Oct 2026 14:00:00 +0200"));
+ assertEquals(t, FeedParser.date("25 Oct 2026 12:00:00 +0000"));
+ assertEquals(t, FeedParser.date("2026-10-25T14:00:00+02:00"));
+ assertEquals(t + 500, FeedParser.date("2026-10-25T12:00:00.5Z"));
+ assertEquals(0, FeedParser.date("yesterday"));
+ assertEquals(0, FeedParser.date(""));
+ assertEquals(0, FeedParser.date(null));
+ }
+
+ @Test public void mixTakesTurnsNewestFirstAndDropsOld() {
+ long now = FeedParser.date("2026-10-25T12:00:00Z");
+ long hour = 3_600_000L;
+ List<Headline> a = Arrays.asList(h("A old", now - 3 * hour), h("A new", now - hour), h("A ancient", now - 72 * hour));
+ List<Headline> b = Arrays.asList(h("B undated", 0), h("B new", now - 2 * hour));
+ List<Headline> mixed = News.mix(Arrays.asList(a, b, Collections.emptyList()), now);
+ List<String> titles = new ArrayList<>();
+ for (Headline h : mixed) titles.add(h.title);
+ assertEquals(Arrays.asList("A new", "B new", "A old", "B undated"), titles);
+ }
+
+ @Test public void mixShowsTheSameHeadlineOnce() {
+ List<Headline> eb = Arrays.asList(h("Le Pen lover lov og orden", 0), h("Kun i EB", 0));
+ List<Headline> bt = Arrays.asList(h("le pen lover lov og orden", 0), h("Kun i BT", 0));
+ List<String> titles = new ArrayList<>();
+ for (Headline h : News.mix(Arrays.asList(eb, bt), 0)) titles.add(h.title);
+ assertEquals(Arrays.asList("Le Pen lover lov og orden", "Kun i EB", "Kun i BT"), titles);
+ }
+
+ @Test public void mixStopsAtSixty() {
+ List<List<Headline>> feeds = new ArrayList<>();
+ for (int f = 0; f < 4; f++) {
+ List<Headline> many = new ArrayList<>();
+ for (int i = 0; i < 20; i++) many.add(h("feed " + f + " item " + i, 0));
+ feeds.add(many);
+ }
+ assertEquals(News.MAX_HEADLINES, News.mix(feeds, 0).size());
+ }
+
+ private static Headline h(String title, long time) {
+ return new Headline("s", title, "", time, "");
+ }
+}
diff --git a/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/QrTest.java b/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/QrTest.java
new file mode 100644
index 000000000..b1e22a262
--- /dev/null
+++ b/addons/news-screensaver/app/src/test/java/com/gathin/newsdream/QrTest.java
@@ -0,0 +1,45 @@
+package com.gathin.newsdream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class QrTest {
+
+ @Test public void capacityMatchesTheSpecForLevelM() {
+ // Data codewords per version at level M, ISO/IEC 18004 table 7.
+ int[] expected = {0, 16, 28, 44, 64, 86, 108, 124, 154, 182, 216, 254, 290, 334, 365, 415};
+ for (int v = 1; v <= Qr.MAX_VERSION; v++) assertEquals("version " + v, expected[v], Qr.dataCodewords(v));
+ }
+
+ @Test public void smallestVersionThatFits() {
+ assertEquals(21, Qr.encode("https://dr.dk/").length); // 14 bytes: version 1
+ assertEquals(25, Qr.encode("https://bbc.co.uk").length); // 17 bytes: version 2
+ boolean[][] dr = Qr.encode("https://www.dr.dk/nyheder/seneste/27-000-kalkuner-skal-aflives-paa-lolland");
+ assertNotNull(dr);
+ assertEquals(37, dr.length); // 74 bytes: version 5
+ }
+
+ @Test public void tooLongForVersionFifteen() {
+ StringBuilder s = new StringBuilder();
+ while (s.length() < 420) s.append('x');
+ assertNull(Qr.encode(s.toString()));
+ }
+
+ @Test public void finderPatternsAndTiming() {
+ boolean[][] m = Qr.encode("https://example.com/news/item-123");
+ int n = m.length;
+ for (int[] corner : new int[][]{{0, 0}, {n - 7, 0}, {0, n - 7}}) {
+ for (int i = 0; i < 7; i++) {
+ assertTrue(m[corner[1]][corner[0] + i]); // outer ring, top edge
+ assertTrue(m[corner[1] + 6][corner[0] + i]); // bottom edge
+ }
+ assertTrue(m[corner[1] + 3][corner[0] + 3]); // centre
+ }
+ for (int i = 8; i < n - 8; i++) assertEquals(i % 2 == 0, m[6][i]);
+ assertTrue(m[n - 8][8]); // the always-dark module
+ }
+}
diff --git a/addons/news-screensaver/build-and-install.ps1 b/addons/news-screensaver/build-and-install.ps1
new file mode 100644
index 000000000..5a68e151a
--- /dev/null
+++ b/addons/news-screensaver/build-and-install.ps1
@@ -0,0 +1,38 @@
+# Windows version of build-and-install.sh: build the news screensaver and install it on the TV.
+# Then run setup.ps1 to choose the feeds and make it the TV's screensaver.
+#
+# Usage: addons\news-screensaver\build-and-install.ps1 -TvHost 192.168.1.50
+# addons\news-screensaver\build-and-install.ps1 -TvHost 192.168.1.50 -Uninstall
+param(
+ [string]$TvHost = $env:TV_HOST,
+ [switch]$Uninstall
+)
+$ErrorActionPreference = 'Stop'
+if (-not $TvHost) { throw 'pass -TvHost <tv ip> or set $env:TV_HOST' }
+$env:TV_HOST = $TvHost
+$here = $PSScriptRoot
+$tools = Join-Path (Split-Path (Split-Path $here -Parent) -Parent) 'tools'
+$py = Join-Path $tools 'venv\Scripts\python.exe'
+if (-not (Test-Path $py)) { throw 'run: python -m venv tools\venv; tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt' }
+$pkg = 'com.gathin.newsdream'
+function Tv([string]$cmd) { & $py -I (Join-Path $tools 'tv.py') $cmd; if ($LASTEXITCODE) { throw "tv.py failed: $cmd" } }
+
+if ($Uninstall) {
+ # Put the screensaver from before setup.ps1 back first, then remove the app.
+ & (Join-Path $here 'setup.ps1') -TvHost $TvHost -Off
+ Tv "pm uninstall $pkg"
+ exit 0
+}
+
+Push-Location $here
+try {
+ & .\gradlew.bat assembleRelease -q
+ if ($LASTEXITCODE) { throw 'build failed (JDK 17 and Android SDK 34 needed; see launcher\README)' }
+} finally { Pop-Location }
+$apk = Join-Path $here 'app\build\outputs\apk\release\app-release.apk'
+& $py -I (Join-Path $tools 'b64push.py') $apk /data/local/tmp/newsdream.apk | Out-Null
+if ($LASTEXITCODE) { throw 'sending the APK failed' }
+Tv 'pm install -r /data/local/tmp/newsdream.apk; rm -f /data/local/tmp/newsdream.apk'
+# TCL's TclAppBoot blocks the app's provider until it may auto-start; elsewhere the op doesn't exist.
+Tv "appops set $pkg APP_AUTO_START allow 2>/dev/null; appops write-settings 2>/dev/null; true" | Out-Null
+Write-Host "Installed. Now: addons\news-screensaver\setup.ps1 -TvHost $TvHost"
diff --git a/addons/news-screensaver/build-and-install.sh b/addons/news-screensaver/build-and-install.sh
new file mode 100644
index 000000000..f55b2d359
--- /dev/null
+++ b/addons/news-screensaver/build-and-install.sh
@@ -0,0 +1,31 @@
+#!/usr/bin/env bash
+# Build the news screensaver and install it on the TV. Then run setup.sh to choose the feeds and make it
+# the TV's screensaver.
+#
+# Usage: TV_HOST=192.168.1.50 addons/news-screensaver/build-and-install.sh
+# TV_HOST=192.168.1.50 addons/news-screensaver/build-and-install.sh --uninstall
+set -euo pipefail
+# Git Bash: a Windows path, which the venv's Windows Python can open.
+HERE="$(cd "$(dirname "$0")" && (pwd -W 2>/dev/null || pwd))"
+TOOLS="$HERE/../../tools"
+: "${TV_HOST:?set TV_HOST to the TV IP address, e.g. TV_HOST=192.168.1.50 $0}"
+PY="$TOOLS/venv/bin/python"
+[ -x "$PY" ] || PY="$TOOLS/venv/Scripts/python.exe"
+[ -x "$PY" ] || { echo "run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt" >&2; exit 1; }
+export MSYS_NO_PATHCONV=1
+PKG=com.gathin.newsdream
+tv() { "$PY" -I "$TOOLS/tv.py" "$@"; }
+
+if [ "${1:-}" = --uninstall ]; then
+ # Put the screensaver from before setup.sh back first, then remove the app.
+ "$HERE/setup.sh" --off
+ tv "pm uninstall $PKG"
+ exit 0
+fi
+
+(cd "$HERE" && ./gradlew assembleRelease -q) || { echo "build failed (JDK 17 and Android SDK 34 needed; see launcher/README)" >&2; exit 1; }
+"$PY" -I "$TOOLS/b64push.py" "$HERE/app/build/outputs/apk/release/app-release.apk" /data/local/tmp/newsdream.apk >/dev/null
+tv "pm install -r /data/local/tmp/newsdream.apk; rm -f /data/local/tmp/newsdream.apk"
+# TCL's TclAppBoot blocks the app's provider until it may auto-start; elsewhere the op doesn't exist.
+tv "appops set $PKG APP_AUTO_START allow 2>/dev/null; appops write-settings 2>/dev/null; true" >/dev/null
+echo "Installed. Now: TV_HOST=$TV_HOST addons/news-screensaver/setup.sh"
diff --git a/addons/news-screensaver/build.gradle b/addons/news-screensaver/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/news-screensaver/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/news-screensaver/feeds.example.txt b/addons/news-screensaver/feeds.example.txt
new file mode 100644
index 000000000..157e54658
--- /dev/null
+++ b/addons/news-screensaver/feeds.example.txt
@@ -0,0 +1,10 @@
+# Feeds for the news screensaver: one RSS or Atom address per line, https:// only, at most 10. A name before the
+# address and a bar ("DR | https://...") is shown instead of the feed's own title. Lines starting with # are skipped.
+# Copy this file to feeds.txt (git ignores that one), edit it and run setup.sh.
+DR | https://www.dr.dk/nyheder/service/feeds/senestenyt
+TV 2 | https://feeds.services.tv2.dk/api/feeds/nyheder/rss
+Ekstra Bladet | https://ekstrabladet.dk/rssfeed/nyheder/
+B.T. | https://www.bt.dk/bt/seneste/rss
+BBC News | https://feeds.bbci.co.uk/news/world/rss.xml
+# The Guardian | https://www.theguardian.com/world/rss
+# NPR | https://feeds.npr.org/1001/rss.xml
diff --git a/addons/news-screensaver/gradle.properties b/addons/news-screensaver/gradle.properties
new file mode 100644
index 000000000..18825f968
--- /dev/null
+++ b/addons/news-screensaver/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
diff --git a/addons/news-screensaver/gradlew b/addons/news-screensaver/gradlew
new file mode 100644
index 000000000..fbcfb4bcb
--- /dev/null
+++ b/addons/news-screensaver/gradlew
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Reuse the repository's pinned Gradle distribution, but build this independent project.
+addon_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 1
+exec sh "$addon_dir/../../launcher/gradlew" -p "$addon_dir" "$@"
diff --git a/addons/news-screensaver/gradlew.bat b/addons/news-screensaver/gradlew.bat
new file mode 100644
index 000000000..42f222173
--- /dev/null
+++ b/addons/news-screensaver/gradlew.bat
@@ -0,0 +1,3 @@
+@echo off
+rem Reuse the repository wrapper; this add-on remains its own Gradle project.
+call "%~dp0..\..\launcher\gradlew.bat" -p "%~dp0." %*
diff --git a/addons/news-screensaver/screenshot.jpg b/addons/news-screensaver/screenshot.jpg
new file mode 100644
index 000000000..67edddd33
Binary files /dev/null and b/addons/news-screensaver/screenshot.jpg differ
diff --git a/addons/news-screensaver/settings.gradle b/addons/news-screensaver/settings.gradle
new file mode 100644
index 000000000..77a123fb4
--- /dev/null
+++ b/addons/news-screensaver/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "newsdream"
+include ':app'
diff --git a/addons/news-screensaver/setup.ps1 b/addons/news-screensaver/setup.ps1
new file mode 100644
index 000000000..9bad22865
--- /dev/null
+++ b/addons/news-screensaver/setup.ps1
@@ -0,0 +1,87 @@
+# Windows version of setup.sh: make the news screensaver the TV's screensaver, and set its feeds, its seconds per
+# headline and how long the TV waits before it starts. Only what you pass is changed: without a feeds file and
+# without feeds.txt in this folder the feeds on the TV stay as they are. Install the app first with
+# build-and-install.ps1.
+#
+# Usage: addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 # feeds.txt from this folder
+# addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 D:\my-feeds.txt # any feeds file
+# addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 -Seconds 20 # 20 s per headline
+# addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 -IdleMinutes 10 # start it after 10 idle minutes
+# addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 -Start # and show it now
+# addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 -DefaultFeeds # back to the built-in feed
+# addons\news-screensaver\setup.ps1 -TvHost 192.168.1.50 -Off # previous screensaver back
+param(
+ [Parameter(Position = 0)][string]$Feeds,
+ [int]$Seconds = 0,
+ [int]$IdleMinutes = 0,
+ [switch]$Start,
+ [switch]$DefaultFeeds,
+ [switch]$Off,
+ [string]$TvHost = $env:TV_HOST
+)
+$ErrorActionPreference = 'Stop'
+if (-not $TvHost) { throw 'pass -TvHost <tv ip> or set $env:TV_HOST' }
+$env:TV_HOST = $TvHost
+if (-not $Feeds -and (Test-Path (Join-Path $PSScriptRoot 'feeds.txt'))) { $Feeds = Join-Path $PSScriptRoot 'feeds.txt' }
+if ($Feeds) {
+ if (-not (Test-Path $Feeds -PathType Leaf)) { throw "no feeds file $Feeds (copy feeds.example.txt to feeds.txt and edit it)" }
+ $Feeds = (Resolve-Path $Feeds).Path
+}
+Set-Location (Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) 'tools')
+$py = 'venv\Scripts\python.exe'
+if (-not (Test-Path $py)) { throw 'run: python -m venv tools\venv; tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt' }
+$pkg = 'com.gathin.newsdream'
+$dream = "$pkg/.NewsDream"
+$uri = "content://$pkg.files"
+$tmp = '/data/local/tmp/cyt-news'
+# The screensaver the TV had before the first run, so -Off can put it back.
+$before = '/data/local/tmp/cyt-news-before'
+function Tv([string]$cmd) { & $py -I tv.py $cmd; if ($LASTEXITCODE) { throw "tv.py failed: $cmd" } }
+
+if ($IdleMinutes -lt 0 -or $IdleMinutes -gt 1440) { throw '-IdleMinutes takes 1 to 1440' }
+if ($Seconds -ne 0 -and ($Seconds -lt 5 -or $Seconds -gt 600)) { throw '-Seconds takes 5 to 600' }
+if (-not ((Tv "pm path $pkg; true") -match 'package:')) { throw 'the news screensaver is not on the TV: run addons\news-screensaver\build-and-install.ps1 first' }
+
+if ($Off) {
+ Tv "if [ -f $before ]; then { read c; read e; } < $before; if [ `"`$c`" = null ]; then settings delete secure screensaver_components >/dev/null; else settings put secure screensaver_components `"`$c`"; fi; [ `"`$e`" = null ] || settings put secure screensaver_enabled `"`$e`"; rm -f $before; fi; echo screensaver: `$(settings get secure screensaver_components)"
+ exit 0
+}
+
+if ($DefaultFeeds) {
+ Tv "content delete --uri $uri/feeds.txt" | Out-Null
+ Write-Host 'feeds: the built-in default'
+} elseif ($Feeds) {
+ $list = [System.Collections.Generic.List[string]]::new()
+ $urls = @{}
+ foreach ($line in Get-Content $Feeds -Encoding UTF8) {
+ $line = $line.Trim()
+ if (-not $line -or $line.StartsWith('#')) { continue }
+ # "Name | https://..." or just the address; the last bar splits them.
+ $bar = $line.LastIndexOf('|')
+ $name = if ($bar -ge 0) { $line.Substring(0, $bar).Trim() } else { '' }
+ $url = $line.Substring($bar + 1).Trim()
+ if ($url -notmatch '^(?i)https://[^\s/]+\S*$' -or $url.Length -gt 500) { throw "not an https:// feed address: $line" }
+ if ($name.Length -gt 40) { throw "name over 40 characters: $name" }
+ if ($urls.ContainsKey($url)) { continue }
+ $urls[$url] = $true
+ $list.Add($(if ($name) { "$name | $url" } else { $url }))
+ }
+ if ($list.Count -gt 10) { throw "$($list.Count) feeds; the screensaver takes at most 10" }
+ if ($list.Count -eq 0) { Write-Warning "no feeds in ${Feeds}: the screensaver will say so" }
+ $clean = New-TemporaryFile
+ try {
+ [System.IO.File]::WriteAllText($clean.FullName, (($list | ForEach-Object { "$_`n" }) -join ''))
+ & $py -I b64push.py $clean.FullName "$tmp-feeds.txt" | Out-Null
+ if ($LASTEXITCODE) { throw 'sending the feeds failed' }
+ } finally { Remove-Item $clean -Force }
+ Tv "content write --uri $uri/feeds.txt < $tmp-feeds.txt; rm -f $tmp-feeds.txt" | Out-Null
+ Write-Host "feeds: $($list.Count) from $Feeds"
+}
+
+if ($Seconds) { Tv "printf '%s' $Seconds > $tmp-seconds.txt; content write --uri $uri/seconds.txt < $tmp-seconds.txt; rm -f $tmp-seconds.txt" | Out-Null }
+Tv "[ -f $before ] || { settings get secure screensaver_components; settings get secure screensaver_enabled; } > $before; settings put secure screensaver_components $dream; settings put secure screensaver_enabled 1" | Out-Null
+if ($IdleMinutes) { Tv "settings put system screen_off_timeout $($IdleMinutes * 60000)" | Out-Null }
+Write-Host 'On the TV now:'
+Tv "f=`$(content read --uri $uri/feeds.txt 2>/dev/null); s=`$(content read --uri $uri/seconds.txt 2>/dev/null); echo `"`${f:-(the built-in default feed)}`" | sed 's/^/ feed: /'; echo `" seconds per headline: `${s:-15}`"; echo `" screen_off_timeout: `$(( `$(settings get system screen_off_timeout) / 60000 )) min`""
+Write-Host 'Screensaver: News. Undo with: addons\news-screensaver\setup.ps1 -Off'
+if ($Start) { Tv 'am start -n com.android.systemui/.Somnambulator >/dev/null; sleep 3; dumpsys dreams | grep mCurrentDreamName' }
diff --git a/addons/news-screensaver/setup.sh b/addons/news-screensaver/setup.sh
new file mode 100644
index 000000000..d5d762837
--- /dev/null
+++ b/addons/news-screensaver/setup.sh
@@ -0,0 +1,88 @@
+#!/usr/bin/env bash
+# Make the news screensaver the TV's screensaver, and set its feeds, its seconds per headline and how long the TV
+# waits before it starts. Only what you pass is changed: without a feeds file and without feeds.txt in this folder
+# the feeds on the TV stay as they are. Install the app first with build-and-install.sh.
+#
+# Usage: TV_HOST=192.168.1.50 addons/news-screensaver/setup.sh # feeds.txt from this folder
+# TV_HOST=192.168.1.50 addons/news-screensaver/setup.sh ~/my-feeds.txt # any feeds file
+# TV_HOST=192.168.1.50 SECONDS_PER_HEADLINE=20 addons/news-screensaver/setup.sh # 20 s per headline
+# TV_HOST=192.168.1.50 IDLE_MINUTES=10 addons/news-screensaver/setup.sh # start it after 10 idle minutes
+# TV_HOST=192.168.1.50 START=1 addons/news-screensaver/setup.sh # and show it now
+# TV_HOST=192.168.1.50 addons/news-screensaver/setup.sh --default-feeds # back to the built-in feed
+# TV_HOST=192.168.1.50 addons/news-screensaver/setup.sh --off # previous screensaver back
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && (pwd -W 2>/dev/null || pwd))"
+ARG="${1:-}"
+FEEDS=
+case "$ARG" in
+ --off|--default-feeds) ;;
+ "") [ -f "$HERE/feeds.txt" ] && FEEDS="$HERE/feeds.txt" ;;
+ /*|?:*) FEEDS="$ARG" ;;
+ *) FEEDS="$(pwd -W 2>/dev/null || pwd)/$ARG" ;;
+esac
+cd "$(dirname "$0")/../../tools"
+: "${TV_HOST:?set TV_HOST to the TV IP address, e.g. TV_HOST=192.168.1.50 $0}"
+PY=venv/bin/python
+[ -x "$PY" ] || PY=venv/Scripts/python.exe
+[ -x "$PY" ] || { echo "run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt" >&2; exit 1; }
+export MSYS_NO_PATHCONV=1
+PKG=com.gathin.newsdream
+DREAM=$PKG/.NewsDream
+URI=content://$PKG.files
+TMP=/data/local/tmp/cyt-news
+# The screensaver the TV had before the first run, so --off can put it back.
+BEFORE=/data/local/tmp/cyt-news-before
+IDLE_MINUTES="${IDLE_MINUTES:-0}"
+SECONDS_PER_HEADLINE="${SECONDS_PER_HEADLINE:-}"
+tv() { "$PY" -I tv.py "$@"; }
+
+[[ "$IDLE_MINUTES" =~ ^[0-9]+$ ]] && [ "$IDLE_MINUTES" -le 1440 ] || { echo "IDLE_MINUTES takes 1 to 1440" >&2; exit 1; }
+[ -z "$SECONDS_PER_HEADLINE" ] || { [[ "$SECONDS_PER_HEADLINE" =~ ^[0-9]+$ ]] && [ "$SECONDS_PER_HEADLINE" -ge 5 ] \
+ && [ "$SECONDS_PER_HEADLINE" -le 600 ]; } || { echo "SECONDS_PER_HEADLINE takes 5 to 600" >&2; exit 1; }
+tv "pm path $PKG; true" | grep -q package: \
+ || { echo "the news screensaver is not on the TV: run addons/news-screensaver/build-and-install.sh first" >&2; exit 1; }
+
+if [ "$ARG" = --off ]; then
+ tv "if [ -f $BEFORE ]; then { read c; read e; } < $BEFORE; if [ \"\$c\" = null ]; then settings delete secure screensaver_components >/dev/null; else settings put secure screensaver_components \"\$c\"; fi; [ \"\$e\" = null ] || settings put secure screensaver_enabled \"\$e\"; rm -f $BEFORE; fi; echo screensaver: \$(settings get secure screensaver_components)"
+ exit 0
+fi
+
+if [ "$ARG" = --default-feeds ]; then
+ tv "content delete --uri $URI/feeds.txt" >/dev/null
+ echo "feeds: the built-in default"
+elif [ -n "$FEEDS" ]; then
+ [ -f "$FEEDS" ] || { echo "no feeds file $FEEDS (copy feeds.example.txt to feeds.txt and edit it)" >&2; exit 1; }
+ CLEAN="$(mktemp)"
+ trap 'rm -f "$CLEAN"' EXIT
+ N=0
+ URLS=" "
+ trim() { printf '%s' "$1" | tr -d '\r' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'; }
+ while IFS= read -r LINE || [ -n "$LINE" ]; do
+ LINE="$(trim "$LINE")"
+ case "$LINE" in ''|'#'*) continue ;; esac
+ # "Name | https://..." or just the address; the last bar splits them.
+ NAME=; URL="$LINE"
+ case "$LINE" in *'|'*) NAME="$(trim "${LINE%|*}")"; URL="$(trim "${LINE##*|}")" ;; esac
+ [[ "$URL" =~ ^[Hh][Tt][Tt][Pp][Ss]://[^[:space:]/]+[^[:space:]]*$ ]] && [ "${#URL}" -le 500 ] \
+ || { echo "not an https:// feed address: $LINE" >&2; exit 1; }
+ [ "${#NAME}" -le 40 ] || { echo "name over 40 characters: $NAME" >&2; exit 1; }
+ case "$URLS" in *" $URL "*) continue ;; esac
+ URLS="$URLS$URL "
+ if [ -n "$NAME" ]; then printf '%s | %s\n' "$NAME" "$URL"; else printf '%s\n' "$URL"; fi >> "$CLEAN"
+ N=$((N + 1))
+ done < "$FEEDS"
+ [ "$N" -le 10 ] || { echo "$N feeds; the screensaver takes at most 10" >&2; exit 1; }
+ [ "$N" -gt 0 ] || echo "warning: no feeds in $FEEDS: the screensaver will say so" >&2
+ # Git Bash: the venv's Windows Python needs a Windows path for the temp file.
+ "$PY" -I b64push.py "$(cygpath -w "$CLEAN" 2>/dev/null || printf '%s' "$CLEAN")" "$TMP-feeds.txt" | grep -q md5 || { echo "sending the feeds failed" >&2; exit 1; }
+ tv "content write --uri $URI/feeds.txt < $TMP-feeds.txt; rm -f $TMP-feeds.txt" >/dev/null
+ echo "feeds: $N from $FEEDS"
+fi
+
+[ -z "$SECONDS_PER_HEADLINE" ] || tv "printf '%s' $SECONDS_PER_HEADLINE > $TMP-seconds.txt; content write --uri $URI/seconds.txt < $TMP-seconds.txt; rm -f $TMP-seconds.txt" >/dev/null
+tv "[ -f $BEFORE ] || { settings get secure screensaver_components; settings get secure screensaver_enabled; } > $BEFORE; settings put secure screensaver_components $DREAM; settings put secure screensaver_enabled 1" >/dev/null
+[ "$IDLE_MINUTES" -eq 0 ] || tv "settings put system screen_off_timeout $((IDLE_MINUTES * 60000))" >/dev/null
+echo "On the TV now:"
+tv "f=\$(content read --uri $URI/feeds.txt 2>/dev/null); s=\$(content read --uri $URI/seconds.txt 2>/dev/null); echo \"\${f:-(the built-in default feed)}\" | sed 's/^/ feed: /'; echo \" seconds per headline: \${s:-15}\"; echo \" screen_off_timeout: \$(( \$(settings get system screen_off_timeout) / 60000 )) min\""
+echo "Screensaver: News. Undo with: addons/news-screensaver/setup.sh --off"
+[ -z "${START:-}" ] || tv "am start -n com.android.systemui/.Somnambulator >/dev/null; sleep 3; dumpsys dreams | grep mCurrentDreamName"