Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
addons: photo screensaver options and a Home card, with prints and sky from #936
JorickGUb31f29d55361
diff --git a/addons/README.md b/addons/README.mdindex e68a7e631..da628acf5 100644--- a/addons/README.md+++ b/addons/README.md@@ -13,7 +13,7 @@ the core bigger or change how it behaves. You install an add-on only if you want| [Capacity Stats](capacity-stats/) | Available/total and used/total RAM; available/total storage | [lionlev21](https://github.com/lionlev21) | Android TV 12 (model private) | None || [Weather](weather/) | The weather for one city: now, US air quality and the next three days, from Open-Meteo (no key) | [@Sumyabazar1](https://github.com/Sumyabazar1) | Hisense SmartTV 4K FFM (lushan), Google TV 12 | `INTERNET` || [Photo Prints](photo-prints/) | Your own photos as a screensaver: dated prints dealt in on a time-of-day sky, and a card that starts the slideshow | [@shivamsingh262](https://github.com/shivamsingh262) | Sony BRAVIA KD-65X82L (Google TV 12) | None |-| [Photo screensaver](photo-screensaver/) | Your own pictures and MP4 clips as the TV's screensaver, slowly zooming and crossfading (20 s each by default); no module card, it is a system screensaver | [JorickGU](https://github.com/JorickGU) | TCL 43P69K (Google TV 12) | None |+| [Photo screensaver](photo-screensaver/) | Your own pictures and MP4 clips as the TV's screensaver and as a card, slowly zooming and crossfading (20 s each by default); optional time, photo dates, prints on a sky, weather | [JorickGU](https://github.com/JorickGU) | TCL 43P69K (Google TV 12) | `INTERNET` and coarse location, only with the weather option on |A widget, an info tile, a storage or smart-home card: if it can live as its own small app, it can livehere. See the rules below.diff --git a/addons/photo-screensaver/README.md b/addons/photo-screensaver/README.mdindex 2d55e2dd0..16679a2a5 100644--- a/addons/photo-screensaver/README.md+++ b/addons/photo-screensaver/README.md@@ -5,8 +5,26 @@ and MP4 clips, separate from the launcher. Pictures go in filename order, each sand crossfading into the next after 20 seconds (or what you set). A clip plays once, muted and cropped tofill the screen, then the loop moves on; a lone clip loops. Any key wakes the TV back to where it was.-Package `com.gathin.photodream`, about 15 KB. It has no launcher icon: you see it as **Photos** (Dutch:-**Foto's**) in the TV's screensaver settings.+Package `com.gathin.photodream`. You see it as **Photos** (Dutch: **Foto's**) in the TV's screensaver+settings. On cleanyourtv's Home it is also a module card, **Photos**: OK starts the same slideshow at once,+Menu opens the settings, Back leaves.++## Options++All off by default, which is the plain full-screen slideshow above. Switch them on in the screensaver's own+settings (TV settings > screensaver > Photos > settings), or with Menu in the card's slideshow:++| Option | What it does |+|---|---|+| Time and date | A line along the bottom with the time and the date, moved a little every minute against burn-in |+| When a picture was taken | Month and year, from a name ending in the date (`trip-20231202.jpg`) or else the camera's EXIF date |+| Three prints | Three pictures at a time as tilted prints, the whole picture, never cropped; clips are skipped |+| Sky | Behind the prints, a sky that follows the time of day |+| Weather | Temperature and a symbol, from the TV's rough location and Open-Meteo, every 30 minutes |++The weather needs location access (asked when you switch it on) and the TV's location services on; the+settings say when they are off and open the TV's location settings. The prints, the sky and the date on a+picture come from Photo Prints by [@shivamsingh262](https://github.com/shivamsingh262) (#936).## Install@@ -54,8 +72,14 @@ is decoded at screen size. On a TCL 43P69K (1.5 GB) a 1080p clip played with the## Permissions-None. No network, no storage permission, no background service: the pictures stay on the TV in the app's-own folder (`Android/data/com.gathin.photodream/files/pictures`), removed with the app.+No storage permission and no background service: the pictures stay on the TV in the app's own folder+(`Android/data/com.gathin.photodream/files/pictures`), removed with the app.++- **`INTERNET`** and **`ACCESS_COARSE_LOCATION`**: only for the weather option, off by default. With it on,+ the TV's rough location, rounded to two decimals (about 1 km), goes to `api.open-meteo.com` every 30+ minutes while the screensaver runs. Nothing else goes out; with it off, nothing goes over the network.+- **`SlideshowActivity`** (exported) is the module card; **`SettingsActivity`** (exported) is opened by the+ TV's screensaver settings. Both only show the slideshow or change its options.- **`FilesProvider`** (exported) is how `sync.sh` writes the pictures, so the app owns them: on TCL G10 afile the adb shell copies into `Android/data` is unreadable for the app. Only callers holdingdiff --git a/addons/photo-screensaver/app/src/main/AndroidManifest.xml b/addons/photo-screensaver/app/src/main/AndroidManifest.xmlindex 7637d4ad1..5c4a23024 100644--- a/addons/photo-screensaver/app/src/main/AndroidManifest.xml+++ b/addons/photo-screensaver/app/src/main/AndroidManifest.xml@@ -4,10 +4,18 @@<uses-feature android:name="android.software.leanback" android:required="false" /><uses-feature android:name="android.hardware.touchscreen" android:required="false" />- <!-- No permissions: the pictures come in over ADB through FilesProvider and stay on the TV. -->+ <!-- Both only used when the weather option is on (SettingsActivity asks for the location then):+ the TV's rough location, sent rounded to about 1 km to Open-Meteo. -->+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-feature android:name="android.hardware.location" android:required="false" />+ <uses-feature android:name="android.hardware.location.network" android:required="false" />+<applicationandroid: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.photodream/.PhotoDream` (sync.sh does it). -->@@ -20,8 +28,32 @@<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 slideshow at once, Back to leave. -->+ <activity+ android:name=".SlideshowActivity"+ 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" />+<!-- sync.sh writes the pictures through this: on TCL G10 a file the shell copies into Android/databelongs to the shell and the app gets EACCES reading it. WRITE_SECURE_SETTINGS: the adb shell hasit, ordinary apps don't. -->diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Media.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Media.javaindex 4e5fab0f5..f0ad2f5ec 100644--- a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Media.java+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Media.java@@ -5,6 +5,7 @@ import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.List;+import java.util.regex.Matcher;import java.util.regex.Pattern;/** Which files the screensaver shows and FilesProvider accepts, and how big a picture is decoded. */@@ -87,6 +88,16 @@ final class Media {}}+ private static final Pattern NAME_DATE = Pattern.compile("-(\\d{4})(\\d{2})(\\d{2})?\\.[A-Za-z0-9]+$");++ /** {year, month} from a name ending in its date, photo-20231202.jpg or photo-202312.jpg; else null. */+ static int[] dateFromName(String name) {+ Matcher m = name == null ? null : NAME_DATE.matcher(name);+ if (m == null || !m.find()) return null;+ int year = Integer.parseInt(m.group(1)), month = Integer.parseInt(m.group(2));+ return year >= 1900 && month >= 1 && month <= 12 ? new int[]{year, month} : null;+ }+static boolean accepted(int width, int height) {return width > 0 && height > 0 && (long) width * height <= MAX_PIXELS;}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Options.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Options.javanew file mode 100644index 000000000..ca12f3a4b--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Options.java@@ -0,0 +1,35 @@+package com.gathin.photodream;++import android.content.Context;+import android.content.SharedPreferences;++/** The switches in SettingsActivity. All off by default: then it is the plain full-screen slideshow. */+final class Options {+ static final String CLOCK = "clock";+ static final String DATES = "photo_dates";+ static final String SKY = "sky";+ static final String PRINTS = "prints";+ static final String WEATHER = "weather";++ final boolean clock;+ final boolean dates;+ final boolean sky;+ final boolean prints;+ final boolean weather;++ private Options(SharedPreferences p) {+ clock = p.getBoolean(CLOCK, false);+ dates = p.getBoolean(DATES, false);+ sky = p.getBoolean(SKY, false);+ prints = p.getBoolean(PRINTS, false);+ weather = p.getBoolean(WEATHER, false);+ }++ static SharedPreferences preferences(Context context) {+ return context.getSharedPreferences("options", Context.MODE_PRIVATE);+ }++ static Options load(Context context) {+ return new Options(preferences(context));+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PhotoDream.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PhotoDream.javaindex db12a2819..751097d48 100644--- a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PhotoDream.java+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PhotoDream.java@@ -1,343 +1,36 @@package com.gathin.photodream;-import android.animation.AnimatorSet;-import android.animation.ObjectAnimator;-import android.animation.PropertyValuesHolder;-import android.content.Context;-import android.content.SharedPreferences;-import android.graphics.Bitmap;-import android.graphics.BitmapFactory;-import android.graphics.Color;-import android.graphics.Matrix;-import android.graphics.SurfaceTexture;-import android.media.MediaPlayer;-import android.os.Handler;-import android.os.Looper;import android.service.dreams.DreamService;-import android.util.DisplayMetrics;-import android.view.Surface;-import android.view.TextureView;-import android.view.View;-import android.view.ViewGroup;-import android.view.animation.LinearInterpolator;-import android.widget.FrameLayout;-import android.widget.ImageView;-import java.io.File;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.util.ArrayList;-import java.util.List;-import java.util.Random;-import java.util.concurrent.ExecutorService;-import java.util.concurrent.Executors;--/**- * Photo screensaver: loops through the pictures sync.sh put in the app's pictures/ folder, in filename order,- * each slowly zooming and drifting (Ken Burns) and crossfading into the next after seconds.txt (20 s by- * default). Two screen-sized pictures at most, held as GPU bitmaps; no network. MP4 clips play once, muted- * and cropped to fill the screen, on the hardware decoder (one player at a time), then the loop moves on.- */+/** The system screensaver: the Scene, until any key wakes the TV back to where it was. */public class PhotoDream extends DreamService {- private static final long FADE_MS = 1500L;- /** How far a picture zooms in over its time on screen; it drifts at most half the extra width. */- private static final float ZOOM = 1.12f;-- private final Handler handler = new Handler(Looper.getMainLooper());- private final Random random = new Random();- private ExecutorService decoder;- private ImageView front;- private ImageView back;- private TextureView video;- private MediaPlayer player;- private Surface surface;- /** A clip waiting for the TextureView's surface. */- private File pendingClip;- /** Bumped for every clip so callbacks of a released player are ignored. */- private int clipGeneration;- private List<File> images = new ArrayList<>();- private SharedPreferences preferences;- private long interval;- private int width;- private int height;- private boolean running;-- private final Runnable advance = this::showNext;+ private Scene scene;@Overridepublic void onAttachedToWindow() {super.onAttachedToWindow();- setInteractive(false); // any key wakes the TV back to where it was+ setInteractive(false);setFullscreen(true);- FrameLayout root = new FrameLayout(this);- root.setBackgroundColor(Color.BLACK);- video = new TextureView(this);- video.setAlpha(0f);- video.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {- @Override public void onSurfaceTextureAvailable(SurfaceTexture texture, int w, int h) {- surface = new Surface(texture);- File clip = pendingClip;- pendingClip = null;- if (clip != null && running) playVideo(clip);- }- @Override public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int w, int h) {}- @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {- stopVideo();- if (surface != null) surface.release();- surface = null;- return true;- }- @Override public void onSurfaceTextureUpdated(SurfaceTexture texture) {}- });- root.addView(video, new FrameLayout.LayoutParams(- ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));- back = image(root);- front = image(root);- setContentView(root);- DisplayMetrics metrics = getResources().getDisplayMetrics();- width = metrics.widthPixels;- height = metrics.heightPixels;- preferences = getSharedPreferences("photo_dream", Context.MODE_PRIVATE);- File dir = getExternalFilesDir(null);- interval = Media.seconds(read(dir == null ? null : new File(dir, Media.SECONDS))) * 1000L;- images = Media.list(dir == null ? null : new File(dir, Media.PICTURES));- }-- private ImageView image(FrameLayout root) {- ImageView view = new ImageView(this);- view.setScaleType(ImageView.ScaleType.CENTER_CROP);- view.setAlpha(0f);- root.addView(view, new FrameLayout.LayoutParams(- ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));- return view;- }-- private static String read(File file) {- try {- return file != null && file.isFile() && file.length() < 64- ? new String(Files.readAllBytes(file.toPath()), StandardCharsets.US_ASCII) : null;- } catch (Exception e) {- return null;- }- }-- static boolean isVideo(File file) {- return file != null && Media.video(file.getName());+ scene = new Scene(this);+ setContentView(scene.root);}@Overridepublic void onDreamingStarted() {super.onDreamingStarted();- running = true;- decoder = Executors.newSingleThreadExecutor();- showNext();+ if (scene != null) scene.start();}@Overridepublic void onDreamingStopped() {- stopSlides();+ if (scene != null) scene.stop();super.onDreamingStopped();}@Overridepublic void onDetachedFromWindow() {- stopSlides();+ if (scene != null) scene.stop();super.onDetachedFromWindow();}-- private void stopSlides() {- running = false;- handler.removeCallbacksAndMessages(null);- if (decoder != null) decoder.shutdownNow();- decoder = null;- if (front != null) { cancel(front); release(front); }- if (back != null) { cancel(back); release(back); }- pendingClip = null;- stopVideo();- }-- /** Decodes the next picture off the main thread, then fades it in over the current one. */- private void showNext() {- if (!running || images.isEmpty() || decoder == null) return;- decoder.execute(() -> {- Bitmap bitmap = null;- File clip = null;- // Skip unreadable pictures, but stop after one round so a folder of broken files doesn't spin.- for (int tries = 0; tries < images.size() && bitmap == null && clip == null; tries++) {- File file = Media.next(images, preferences.getString("image", ""));- preferences.edit().putString("image", file.getName()).apply();- if (isVideo(file)) clip = file;- else bitmap = decode(file);- }- Bitmap shown = bitmap;- File playing = clip;- handler.post(() -> {- if (!running) {- if (shown != null) shown.recycle();- return;- }- if (playing != null) {- playVideo(playing); // moves on when the clip ends- return;- }- if (shown != null) crossfade(shown);- // A single picture still drifts on: it fades into itself with a new zoom.- handler.postDelayed(advance, interval);- });- });- }-- private void crossfade(Bitmap bitmap) {- ImageView incoming = back;- ImageView outgoing = front;- back = outgoing;- front = incoming;- cancel(incoming);- release(incoming);- incoming.setImageBitmap(bitmap);- incoming.setTag(bitmap);- incoming.bringToFront();- // Start zoomed in or out at random and drift toward a random spot, over the whole slide.- boolean zoomIn = random.nextBoolean();- float from = zoomIn ? 1f : ZOOM;- float to = zoomIn ? ZOOM : 1f;- float dx = (random.nextFloat() - 0.5f) * width * (ZOOM - 1f);- float dy = (random.nextFloat() - 0.5f) * height * (ZOOM - 1f);- incoming.setAlpha(0f);- ObjectAnimator fade = ObjectAnimator.ofFloat(incoming, View.ALPHA, 0f, 1f).setDuration(FADE_MS);- ObjectAnimator drift = ObjectAnimator.ofPropertyValuesHolder(incoming,- PropertyValuesHolder.ofFloat(View.SCALE_X, from, to),- PropertyValuesHolder.ofFloat(View.SCALE_Y, from, to),- PropertyValuesHolder.ofFloat(View.TRANSLATION_X, zoomIn ? 0f : dx, zoomIn ? dx : 0f),- PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, zoomIn ? 0f : dy, zoomIn ? dy : 0f))- .setDuration(interval + 2 * FADE_MS);- drift.setInterpolator(new LinearInterpolator());- AnimatorSet set = new AnimatorSet();- set.playTogether(fade, drift);- incoming.setTag(R.id.animation, set);- set.start();- boolean afterClip = player != null;- handler.postDelayed(() -> {- cancel(outgoing);- outgoing.setAlpha(0f);- release(outgoing);- if (afterClip) stopVideo();- }, FADE_MS + 100);- }-- /** Fades the clip in over whatever shows now and plays it to the end (or loops a lone clip). */- private void playVideo(File clip) {- if (surface == null) {- pendingClip = clip;- return;- }- boolean clipShowing = player != null;- stopVideo();- int generation = ++clipGeneration;- MediaPlayer mp = new MediaPlayer();- player = mp;- try {- mp.setDataSource(clip.getPath());- mp.setSurface(surface);- mp.setVolume(0f, 0f);- mp.setLooping(images.size() == 1);- mp.setOnVideoSizeChangedListener((p, w, h) -> cover(w, h));- mp.setOnPreparedListener(p -> {- if (generation != clipGeneration || !running) return;- p.start();- video.bringToFront();- if (clipShowing) video.setAlpha(1f);- else video.animate().alpha(1f).setDuration(FADE_MS).start();- handler.postDelayed(() -> {- if (generation != clipGeneration) return;- for (ImageView view : new ImageView[] {front, back}) {- cancel(view);- view.setAlpha(0f);- release(view);- }- }, FADE_MS + 100);- });- mp.setOnCompletionListener(p -> {- if (generation == clipGeneration && running) showNext();- });- mp.setOnErrorListener((p, what, extra) -> {- if (generation == clipGeneration && running) {- stopVideo();- handler.postDelayed(advance, 1000);- }- return true;- });- mp.prepareAsync();- } catch (Exception failure) {- stopVideo();- handler.postDelayed(advance, 1000);- }- }-- /** Scales the clip to fill the screen, cropping the overflow evenly (like CENTER_CROP). */- private void cover(int videoWidth, int videoHeight) {- int w = video.getWidth(), h = video.getHeight();- if (videoWidth <= 0 || videoHeight <= 0 || w <= 0 || h <= 0) return;- float scale = Math.max((float) w / videoWidth, (float) h / videoHeight);- Matrix matrix = new Matrix();- matrix.setScale(videoWidth * scale / w, videoHeight * scale / h, w / 2f, h / 2f);- video.setTransform(matrix);- }-- private void stopVideo() {- clipGeneration++;- if (video != null) {- video.animate().cancel();- video.setAlpha(0f);- }- if (player != null) {- try { player.stop(); } catch (IllegalStateException ignored) { }- player.release();- player = null;- }- }-- private static void cancel(ImageView view) {- Object set = view.getTag(R.id.animation);- if (set instanceof AnimatorSet) ((AnimatorSet) set).cancel();- view.setTag(R.id.animation, null);- }-- /** Frees the view's picture now instead of waiting for the garbage collector. */- private static void release(ImageView view) {- Object old = view.getTag();- view.setImageDrawable(null);- view.setTag(null);- if (old instanceof Bitmap) ((Bitmap) old).recycle();- }-- private Bitmap decode(File file) {- try {- BitmapFactory.Options options = new BitmapFactory.Options();- options.inJustDecodeBounds = true;- BitmapFactory.decodeFile(file.getPath(), options);- int w = options.outWidth, h = options.outHeight;- if (w <= 0 || h <= 0) return null;- int sample = Media.sampleSize(w, h, width, height);- if (!Media.accepted(w / sample, h / sample)) return null;- options.inJustDecodeBounds = false;- options.inSampleSize = sample;- int[] scale = Media.coverScale(w / sample, h / sample, width, height);- if (scale != null) {- options.inScaled = true;- options.inDensity = scale[0];- options.inTargetDensity = scale[1];- }- options.inPreferredConfig = Bitmap.Config.RGB_565;- Bitmap decoded = BitmapFactory.decodeFile(file.getPath(), options);- if (decoded == null) return null;- Bitmap gpu = decoded.copy(Bitmap.Config.HARDWARE, false);- if (gpu == null) return decoded;- decoded.recycle();- return gpu;- } catch (Exception | OutOfMemoryError failure) {- return null;- }- }}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Photos.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Photos.javanew file mode 100644index 000000000..61140dbf9--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Photos.java@@ -0,0 +1,96 @@+package com.gathin.photodream;++import android.graphics.Bitmap;+import android.graphics.BitmapFactory;+import android.graphics.Matrix;+import android.media.ExifInterface;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.text.DateFormatSymbols;++/**+ * Reading the pictures: the month and year a picture was taken, its upright size and a decode near a given size.+ * Adapted from Photo Prints by @shivamsingh262 (#936).+ */+final class Photos {++ private Photos() {}++ /** A small text file (seconds.txt), or null. */+ static String read(File file) {+ try {+ return file != null && file.isFile() && file.length() < 64+ ? new String(Files.readAllBytes(file.toPath()), StandardCharsets.US_ASCII) : null;+ } catch (Exception e) {+ return null;+ }+ }++ /** "Dec 2023": from the file name (photo-20231202.jpg), else from the camera's own date; else "". */+ static String dateOf(File file) {+ int[] ym = Media.dateFromName(file.getName());+ if (ym == null) {+ try {+ String taken = new ExifInterface(file.getPath()).getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL);+ if (taken != null && taken.length() >= 7) { // "2023:12:02 09:22:30"+ int year = Integer.parseInt(taken.substring(0, 4));+ int month = Integer.parseInt(taken.substring(5, 7));+ if (year >= 1900 && month >= 1 && month <= 12) ym = new int[]{year, month};+ }+ } catch (Exception ignored) {+ // No date: none is shown.+ }+ }+ if (ym == null) return "";+ return new DateFormatSymbols().getShortMonths()[ym[1] - 1] + " " + ym[0];+ }++ /** The EXIF rotation that turns the photo upright: 0, 90, 180 or 270. */+ private static int rotation(File file) {+ try {+ int o = new ExifInterface(file.getPath()).getAttributeInt(+ ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);+ if (o == ExifInterface.ORIENTATION_ROTATE_90) return 90;+ if (o == ExifInterface.ORIENTATION_ROTATE_180) return 180;+ if (o == ExifInterface.ORIENTATION_ROTATE_270) return 270;+ } catch (Exception ignored) {+ // PNG and WebP carry no EXIF here; show them as they are.+ }+ return 0;+ }++ /** The photo's {width, height} once upright, read from its header only; null if it is not a usable image. */+ static int[] size(File file) {+ BitmapFactory.Options bounds = new BitmapFactory.Options();+ bounds.inJustDecodeBounds = true;+ BitmapFactory.decodeFile(file.getPath(), bounds);+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null;+ return rotation(file) % 180 == 0 ? new int[]{bounds.outWidth, bounds.outHeight}+ : new int[]{bounds.outHeight, bounds.outWidth};+ }++ /** Decodes at the smallest power-of-two size that still covers w x h, upright per EXIF; null on failure. */+ static Bitmap decode(File file, int w, int h) {+ try {+ int rotation = rotation(file);+ int[] size = size(file);+ if (size == null) return null;+ int sample = Media.sampleSize(size[0], size[1], w, h);+ if (!Media.accepted(size[0] / sample, size[1] / sample)) return null;+ BitmapFactory.Options opts = new BitmapFactory.Options();+ opts.inSampleSize = sample;+ opts.inPreferredConfig = Bitmap.Config.RGB_565;+ Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), opts);+ if (bitmap == null || rotation == 0) return bitmap;+ Matrix m = new Matrix();+ m.postRotate(rotation);+ Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);+ if (rotated != bitmap) bitmap.recycle();+ return rotated;+ } catch (OutOfMemoryError | RuntimeException e) {+ return null;+ }+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PrintShadow.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PrintShadow.javanew file mode 100644index 000000000..06f18ea95--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PrintShadow.java@@ -0,0 +1,52 @@+package com.gathin.photodream;++import android.graphics.Canvas;+import android.graphics.ColorFilter;+import android.graphics.Paint;+import android.graphics.PixelFormat;+import android.graphics.Rect;+import android.graphics.RectF;+import android.graphics.drawable.Drawable;++/**+ * The shadow under a print, the same under every print and tilting with it (elevation shadows lean with a light+ * at the top of the screen). From Photo Prints by @shivamsingh262 (#936).+ */+final class PrintShadow extends Drawable {++ private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);+ private final RectF card = new RectF();+ private final float inset, radius;++ PrintShadow(float inset, float radius, float blur, float dy, int color) {+ this.inset = inset;+ this.radius = radius;+ paint.setColor(0xFF101014);+ paint.setShadowLayer(blur, 0f, dy, color);+ }++ @Override+ protected void onBoundsChange(Rect bounds) {+ card.set(bounds.left + inset, bounds.top + inset, bounds.right - inset, bounds.bottom - inset);+ }++ @Override+ public void draw(Canvas canvas) {+ canvas.drawRoundRect(card, radius, radius, paint);+ }++ @Override+ public void setAlpha(int alpha) {+ paint.setAlpha(alpha);+ }++ @Override+ public void setColorFilter(ColorFilter colorFilter) {+ paint.setColorFilter(colorFilter);+ }++ @Override+ public int getOpacity() {+ return PixelFormat.TRANSLUCENT;+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Prints.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Prints.javanew file mode 100644index 000000000..f34b0460c--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Prints.java@@ -0,0 +1,259 @@+package com.gathin.photodream;++import android.content.Context;+import android.graphics.Bitmap;+import android.graphics.drawable.BitmapDrawable;+import android.graphics.drawable.Drawable;+import android.os.Handler;+import android.os.Looper;+import android.view.LayoutInflater;+import android.view.View;+import android.view.ViewGroup;+import android.view.animation.AccelerateInterpolator;+import android.view.animation.DecelerateInterpolator;+import android.widget.FrameLayout;+import android.widget.ImageView;+import android.widget.TextView;++import java.io.File;+import java.util.ArrayList;+import java.util.Collections;+import java.util.HashSet;+import java.util.List;+import java.util.Random;+import java.util.Set;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;++/**+ * Prints mode: three pictures as prints, each the whole picture with rounded corners and a slight tilt. Every+ * interval they slide off to the left one after another and three new ones are dealt in from the right. Clips are+ * left out in this mode. Adapted from Photo Prints by @shivamsingh262 (#936).+ */+final class Prints {++ private static final int PRINTS = 3;+ private static final long OUT_MS = 700L, OUT_STAGGER_MS = 120L;+ private static final long IN_MS = 800L, IN_STAGGER_MS = 180L;+ /** Decode size, in dp: a landscape photo's width, a portrait one's height. */+ private static final int LANDSCAPE_W_DP = 300, PORTRAIT_H_DP = 320;+ /** Each print's resting tilt in degrees; the middle one lies on top. */+ private static final int[] TILT = {-5, 3, -2};+ private static final int SIDE_DP = 48, TOP_DP = 20, COLUMN_GAP_DP = 24, BOTTOM_GAP_DP = 4, BOTTOM_DP = 48;+ private static final int JITTER_DP = 14, JITTER_Y_DP = 6, JITTER_DEG = 2;+ private static final int MAX_TILT_DEG = 7;++ private final Context context;+ private final Handler handler = new Handler(Looper.getMainLooper());+ private final Random random = new Random();+ private final float density;+ private final int screenW;+ private final int screenH;+ private final long interval;+ private final boolean dates;+ /** The clock line, to keep the prints above it; null when it is off. */+ private final View clock;+ private final View empty;+ private final File folder;+ private final View[] cards = new View[PRINTS];+ private final ImageView[] photoViews = new ImageView[PRINTS];+ private final TextView[] dateViews = new TextView[PRINTS];+ private ExecutorService loader;+ /** Loader thread only. */+ private final List<File> queue = new ArrayList<>();+ private boolean dealt;+ /** Bumped on stop, so a decode that finishes afterwards is dropped instead of shown. */+ private int generation;++ private static final class Print {+ Bitmap bitmap;+ String date;+ }++ private final Runnable next = this::loadNext;++ Prints(Context context, FrameLayout stage, View clock, View empty, boolean dates) {+ this.context = context;+ this.clock = clock;+ this.empty = empty;+ this.dates = dates;+ density = context.getResources().getDisplayMetrics().density;+ screenW = context.getResources().getDisplayMetrics().widthPixels;+ screenH = context.getResources().getDisplayMetrics().heightPixels;+ File dir = context.getExternalFilesDir(null);+ folder = dir == null ? null : new File(dir, Media.PICTURES);+ interval = Media.seconds(Photos.read(dir == null ? null : new File(dir, Media.SECONDS))) * 1000L;+ stage.setClipChildren(false);+ LayoutInflater inflater = LayoutInflater.from(context);+ float shadowRoom = context.getResources().getDimensionPixelSize(R.dimen.print_shadow_room);+ for (int i = 0; i < PRINTS; i++) {+ cards[i] = inflater.inflate(R.layout.print, stage, false);+ // Drawn into a layer with a clear margin, the tilted print is filtered as one image: smooth edges.+ cards[i].setLayerType(View.LAYER_TYPE_HARDWARE, null);+ cards[i].setBackground(new PrintShadow(shadowRoom, 16 * density, 22 * density, 4 * density, 0x73000000));+ cards[i].findViewById(R.id.printCard).setClipToOutline(true);+ photoViews[i] = cards[i].findViewById(R.id.printPhoto);+ dateViews[i] = cards[i].findViewById(R.id.printDate);+ cards[i].setTranslationX(screenW * 2f); // off screen until the first deal+ stage.addView(cards[i]);+ }+ cards[1].bringToFront();+ }++ void start() {+ if (loader == null) loader = Executors.newSingleThreadExecutor();+ handler.post(next);+ }++ void stop() {+ generation++;+ handler.removeCallbacksAndMessages(null);+ if (loader != null) loader.shutdownNow();+ loader = null;+ dealt = false;+ for (int i = 0; i < PRINTS; i++) {+ cards[i].animate().cancel();+ cards[i].setTranslationX(screenW * 2f);+ release(photoViews[i]);+ }+ }++ private void loadNext() {+ int gen = generation;+ ExecutorService l = loader;+ if (l == null) return;+ l.execute(() -> {+ Print[] batch = new Print[PRINTS];+ Set<File> used = new HashSet<>();+ for (int i = 0; i < PRINTS; i++) {+ try {+ batch[i] = nextPrint(used);+ } catch (OutOfMemoryError e) {+ batch[i] = null;+ }+ }+ handler.post(() -> {+ if (gen != generation) {+ for (Print p : batch) if (p != null && p.bitmap != null) p.bitmap.recycle();+ return;+ }+ sweep(batch);+ handler.postDelayed(next, interval);+ });+ });+ }++ /** Loader thread only: the next picture in a shuffled round, decoded near its print size. */+ private Print nextPrint(Set<File> used) {+ for (int tries = 0; tries < 4; tries++) {+ if (queue.isEmpty()) {+ for (File f : Media.list(folder)) if (Media.image(f.getName())) queue.add(f);+ queue.removeAll(used);+ Collections.shuffle(queue, random);+ }+ if (queue.isEmpty()) return null;+ File file = queue.remove(0);+ if (!used.add(file)) continue;+ int[] size = Photos.size(file);+ if (size == null) continue;+ int w, h;+ if (size[1] > size[0]) {+ h = Math.round(PORTRAIT_H_DP * density);+ w = h * size[0] / size[1];+ } else {+ w = Math.round(LANDSCAPE_W_DP * density);+ h = w * size[1] / size[0];+ }+ Bitmap bitmap = Photos.decode(file, w, h);+ if (bitmap == null) continue;+ Print p = new Print();+ p.bitmap = bitmap;+ p.date = dates ? Photos.dateOf(file) : "";+ return p;+ }+ return null;+ }++ private void sweep(Print[] batch) {+ boolean none = true;+ for (Print p : batch) none &= p == null;+ empty.setVisibility(none ? View.VISIBLE : View.GONE);+ long dealAt = 0;+ if (dealt) {+ for (int i = 0; i < PRINTS; i++) {+ View card = cards[i];+ card.animate().translationX(-(screenW + card.getWidth() + 200f))+ .rotation(card.getRotation() - 12f)+ .setStartDelay(i * OUT_STAGGER_MS).setDuration(OUT_MS)+ .setInterpolator(new AccelerateInterpolator(1.6f)).start();+ }+ dealAt = OUT_MS + (PRINTS - 1) * OUT_STAGGER_MS + 60;+ }+ dealt = true;+ handler.postDelayed(() -> deal(batch), dealAt);+ }++ /** Where the prints must end: above the clock line, or near the bottom when the clock is off. */+ private float areaBottom() {+ if (clock == null || clock.getHeight() == 0) return screenH - BOTTOM_DP * density;+ return clock.getTop() - BOTTOM_GAP_DP * density - 6 * density;+ }++ /** Three equal columns: each print as large as its column allows, tilted, with a little play. */+ private void deal(Print[] batch) {+ float side = SIDE_DP * density, jitter = JITTER_DP * density, jitterY = JITTER_Y_DP * density;+ float colGap = COLUMN_GAP_DP * density;+ int shadowRoom = context.getResources().getDimensionPixelSize(R.dimen.print_shadow_room);+ float areaTop = TOP_DP * density, areaBottom = areaBottom();+ float colW = (screenW - 2 * side - (PRINTS - 1) * colGap) / PRINTS;+ float boxW = colW - 2 * jitter, boxH = areaBottom - areaTop - 2 * jitterY;+ double rad = Math.toRadians(MAX_TILT_DEG);+ float cos = (float) Math.cos(rad), sin = (float) Math.sin(rad);+ for (int i = 0; i < PRINTS; i++) {+ Print p = batch[i];+ View card = cards[i];+ ImageView photo = photoViews[i];+ release(photo);+ if (p == null) {+ card.setVisibility(View.INVISIBLE);+ continue;+ }+ float a = (float) p.bitmap.getWidth() / p.bitmap.getHeight();+ float h = Math.min(boxW / (a * cos + sin), boxH / (a * sin + cos));+ int ph = Math.max(1, Math.round(h)), pw = Math.max(1, Math.round(h * a));+ float cx = side + colW / 2f + i * (colW + colGap) + (random.nextFloat() * 2 - 1) * jitter;+ float cy = (areaTop + areaBottom) / 2f + (random.nextFloat() * 2 - 1) * jitterY;+ float tilt = TILT[i] + (random.nextFloat() * 2 - 1) * JITTER_DEG;+ card.setVisibility(View.VISIBLE);+ photo.setImageBitmap(p.bitmap);+ ViewGroup.LayoutParams lp = photo.getLayoutParams();+ lp.width = pw;+ lp.height = ph;+ photo.setLayoutParams(lp);+ dateViews[i].setText(p.date);+ dateViews[i].setVisibility(p.date.isEmpty() ? View.GONE : View.VISIBLE);+ ViewGroup.LayoutParams dp = dateViews[i].getLayoutParams();+ dp.width = pw;+ dateViews[i].setLayoutParams(dp);+ FrameLayout.LayoutParams cp = (FrameLayout.LayoutParams) card.getLayoutParams();+ cp.leftMargin = Math.round(cx - pw / 2f) - shadowRoom;+ cp.topMargin = Math.round(cy - ph / 2f) - shadowRoom;+ card.setLayoutParams(cp);+ card.animate().cancel();+ card.setTranslationX(screenW + 200f);+ card.setRotation(tilt + 12f);+ card.animate().translationX(0f).rotation(tilt)+ .setStartDelay(i * IN_STAGGER_MS).setDuration(IN_MS)+ .setInterpolator(new DecelerateInterpolator(2f)).start();+ }+ }++ private static void release(ImageView view) {+ Drawable d = view.getDrawable();+ view.setImageDrawable(null);+ if (d instanceof BitmapDrawable) {+ Bitmap b = ((BitmapDrawable) d).getBitmap();+ if (b != null && !b.isRecycled()) b.recycle();+ }+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Scene.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Scene.javanew file mode 100644index 000000000..08188ae5e--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Scene.java@@ -0,0 +1,164 @@+package com.gathin.photodream;++import android.content.Context;+import android.content.SharedPreferences;+import android.graphics.Color;+import android.os.Handler;+import android.os.Looper;+import android.view.LayoutInflater;+import android.view.View;+import android.view.ViewGroup;+import android.widget.FrameLayout;+import android.widget.TextView;++import java.io.File;+import java.util.Random;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;++/**+ * What the screensaver and the card's slideshow show: the pictures (full screen, or as prints), and on top what+ * the options switch on: the time and date, the weather, the sky behind it all. Both hosts call start and stop.+ */+final class Scene {++ private static final long MINUTE_MS = 60_000L;+ /** How far the bottom line may wander so it does not burn in. */+ private static final int NUDGE_DP = 20, NUDGE_UP_DP = 6;++ final FrameLayout root;+ private final Context context;+ private final Options options;+ private final Handler handler = new Handler(Looper.getMainLooper());+ private final Random random = new Random();+ private final SkyView sky;+ private final View bottomLine;+ private final TextView weather;+ private final Slides slides;+ private final Prints prints;+ private ExecutorService network;+ private boolean running;++ private final Runnable tick = new Runnable() {+ @Override public void run() {+ if (sky != null) sky.update();+ nudge();+ handler.postDelayed(this, MINUTE_MS);+ }+ };+ private final Runnable refreshWeather = this::refreshWeather;++ Scene(Context context) {+ this.context = context;+ options = Options.load(context);+ root = new FrameLayout(context);+ root.setBackgroundColor(Color.BLACK);+ root.setClipChildren(false);+ if (options.sky && options.prints) {+ sky = new SkyView(context);+ root.addView(sky, new FrameLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));+ } else {+ sky = null;+ }+ FrameLayout stage = new FrameLayout(context);+ root.addView(stage, new FrameLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));+ View overlay = LayoutInflater.from(context).inflate(R.layout.overlay, root, false);+ root.addView(overlay);+ bottomLine = overlay.findViewById(R.id.bottomLine);+ weather = overlay.findViewById(R.id.weather);+ TextView caption = overlay.findViewById(R.id.caption);+ View empty = overlay.findViewById(R.id.empty);+ File dir = context.getExternalFilesDir(null);+ ((TextView) overlay.findViewById(R.id.emptyPath)).setText(+ dir == null ? "" : new File(dir, Media.PICTURES).getPath());++ int clockVisibility = options.clock ? View.VISIBLE : View.GONE;+ overlay.findViewById(R.id.time).setVisibility(clockVisibility);+ overlay.findViewById(R.id.ampm).setVisibility(clockVisibility);+ overlay.findViewById(R.id.date).setVisibility(clockVisibility);+ weather.setVisibility(View.GONE);+ bottomLine.setVisibility(options.clock || options.weather ? View.VISIBLE : View.GONE);+ // In full-screen mode the pictures cover everything: a dark fade keeps the bottom line readable.+ overlay.findViewById(R.id.bottomFade).setVisibility(+ !options.prints && (options.clock || options.weather) ? View.VISIBLE : View.GONE);++ if (options.prints) {+ caption.setVisibility(View.GONE);+ prints = new Prints(context, stage, options.clock || options.weather ? bottomLine : null, empty,+ options.dates);+ slides = null;+ } else {+ slides = new Slides(context, stage, options.dates ? caption : null, empty);+ prints = null;+ if (!options.dates) caption.setVisibility(View.GONE);+ }+ bottomLine.bringToFront();+ }++ void start() {+ if (running) return;+ running = true;+ if (slides != null) slides.start();+ if (prints != null) prints.start();+ handler.post(tick);+ if (options.weather) {+ network = Executors.newSingleThreadExecutor();+ handler.post(refreshWeather);+ }+ }++ void stop() {+ running = false;+ handler.removeCallbacksAndMessages(null);+ if (network != null) network.shutdownNow();+ network = null;+ if (slides != null) slides.stop();+ if (prints != null) prints.stop();+ }++ private void nudge() {+ if (bottomLine.getVisibility() != View.VISIBLE) return;+ float d = context.getResources().getDisplayMetrics().density;+ bottomLine.animate().translationX((random.nextFloat() * 2 - 1) * NUDGE_DP * d)+ .translationY(random.nextFloat() * -NUDGE_UP_DP * d).setDuration(1500).start();+ }++ /** The cached reading if it is fresh, else a new one; again every 30 minutes while the scene runs. */+ private void refreshWeather() {+ if (!running) return;+ handler.postDelayed(refreshWeather, Weather.REFRESH_MS);+ SharedPreferences cache = context.getSharedPreferences("weather", Context.MODE_PRIVATE);+ String cached = cache.getString("text", "");+ long age = System.currentTimeMillis() - cache.getLong("at", 0);+ if (!cached.isEmpty() && age >= 0 && age < Weather.REFRESH_MS) {+ showWeather(cached);+ return;+ }+ Weather.locate(context, location -> {+ ExecutorService n = network;+ if (location == null || n == null || !running) return;+ double lat = location.getLatitude(), lon = location.getLongitude();+ try {+ n.execute(() -> {+ String text;+ try {+ text = Weather.now(lat, lon);+ } catch (Exception e) {+ return; // offline: keep what shows, try again in half an hour+ }+ cache.edit().putString("text", text).putLong("at", System.currentTimeMillis()).apply();+ handler.post(() -> { if (running) showWeather(text); });+ });+ } catch (java.util.concurrent.RejectedExecutionException ignored) {+ // Stopped meanwhile.+ }+ });+ }++ private void showWeather(String text) {+ weather.setText(text);+ weather.setVisibility(View.VISIBLE);+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SettingsActivity.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SettingsActivity.javanew file mode 100644index 000000000..8a93dad25--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SettingsActivity.java@@ -0,0 +1,142 @@+package com.gathin.photodream;++import android.Manifest;+import android.app.Activity;+import android.content.ActivityNotFoundException;+import android.content.Intent;+import android.content.SharedPreferences;+import android.content.pm.PackageManager;+import android.os.Bundle;+import android.provider.Settings;+import android.util.TypedValue;+import android.view.View;+import android.widget.Button;+import android.widget.LinearLayout;+import android.widget.ScrollView;+import android.widget.Switch;+import android.widget.TextView;++/**+ * The options, one switch each, for the remote's D-pad. Reached from the TV's screensaver settings (the+ * screensaver's own settings entry) and with Menu in the card's slideshow. All off: the plain slideshow.+ */+public class SettingsActivity extends Activity {++ private static final int ASK_LOCATION = 1;++ private SharedPreferences preferences;+ private Switch weatherSwitch;+ private Switch skySwitch;+ private TextView weatherStatus;+ private Button locationButton;++ @Override+ protected void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+ preferences = Options.preferences(this);+ 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);++ list.addView(toggle(Options.CLOCK, R.string.option_clock, null));+ list.addView(toggle(Options.DATES, R.string.option_dates, null));+ list.addView(toggle(Options.PRINTS, R.string.option_prints, on -> skySwitch.setEnabled(on)));+ skySwitch = toggle(Options.SKY, R.string.option_sky, null);+ skySwitch.setEnabled(preferences.getBoolean(Options.PRINTS, false));+ list.addView(skySwitch);+ weatherSwitch = toggle(Options.WEATHER, R.string.option_weather, this::weatherChanged);+ list.addView(weatherSwitch);++ weatherStatus = new TextView(this);+ weatherStatus.setPadding(dp(8), 0, 0, dp(8));+ list.addView(weatherStatus);+ locationButton = new Button(this);+ locationButton.setText(R.string.open_location_settings);+ locationButton.setOnClickListener(v -> openLocationSettings());+ list.addView(locationButton, new LinearLayout.LayoutParams(+ LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));++ Button preview = new Button(this);+ preview.setText(R.string.preview);+ preview.setOnClickListener(v -> startActivity(new Intent(this, SlideshowActivity.class)));+ LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(+ LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);+ lp.topMargin = dp(24);+ list.addView(preview, lp);++ ScrollView scroll = new ScrollView(this);+ scroll.addView(list);+ setContentView(scroll);+ list.getChildAt(1).requestFocus();+ }++ @Override+ protected void onResume() {+ super.onResume();+ updateWeatherStatus(); // back from the TV's location settings+ }++ private interface Changed {+ void on(boolean value);+ }++ private Switch toggle(String key, int label, Changed changed) {+ Switch s = new Switch(this);+ s.setText(label);+ s.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);+ s.setPadding(dp(8), dp(12), dp(8), dp(12));+ s.setChecked(preferences.getBoolean(key, false));+ s.setOnCheckedChangeListener((button, value) -> {+ preferences.edit().putBoolean(key, value).apply();+ if (changed != null) changed.on(value);+ });+ return s;+ }++ private void weatherChanged(boolean on) {+ if (on && !Weather.permitted(this)) {+ requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, ASK_LOCATION);+ }+ updateWeatherStatus();+ }++ @Override+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) {+ super.onRequestPermissionsResult(requestCode, permissions, results);+ if (requestCode != ASK_LOCATION) return;+ if (results.length == 0 || results[0] != PackageManager.PERMISSION_GRANTED) {+ weatherSwitch.setChecked(false); // no location, no weather+ }+ updateWeatherStatus();+ }++ private void updateWeatherStatus() {+ boolean on = preferences.getBoolean(Options.WEATHER, false);+ boolean locationOff = on && Weather.permitted(this) && !Weather.locationOn(this);+ int status = !on ? R.string.weather_info+ : !Weather.permitted(this) ? R.string.weather_no_permission+ : locationOff ? R.string.weather_location_off+ : R.string.weather_ok;+ weatherStatus.setText(status);+ locationButton.setVisibility(locationOff ? View.VISIBLE : View.GONE);+ }++ private void openLocationSettings() {+ try {+ startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));+ } catch (ActivityNotFoundException e) {+ startActivity(new Intent(Settings.ACTION_SETTINGS));+ }+ }++ private int dp(int value) {+ return Math.round(value * getResources().getDisplayMetrics().density);+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Sky.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Sky.javanew file mode 100644index 000000000..ef7371f0a--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Sky.java@@ -0,0 +1,98 @@+package com.gathin.photodream;++/**+ * Time-of-day sky palette: night blues, a warm horizon at dawn and sunset, a glow where the sun sits. Pure maths,+ * the caller passes minutes since midnight; every colour stays dark enough for white text on top.+ * From Photo Prints by @shivamsingh262 (#936).+ */+final class Sky {++ private static final class Stop {+ final int minute;+ final int top;+ final int mid;+ final int bottom;+ /** Alpha of the sun/moon glow near the horizon, 0 to 255. */+ final int sun;+ /** Horizontal position of the glow, 0 = left edge, 1 = right edge. */+ final float sunX;++ Stop(int minute, int top, int mid, int bottom, int sun, float sunX) {+ this.minute = minute;+ this.top = top;+ this.mid = mid;+ this.bottom = bottom;+ this.sun = sun;+ this.sunX = sunX;+ }+ }++ /** The palette at one instant: the three gradient colours plus the glow. */+ static final class Palette {+ final int top;+ final int mid;+ final int bottom;+ final int sun;+ final float sunX;++ Palette(int top, int mid, int bottom, int sun, float sunX) {+ this.top = top;+ this.mid = mid;+ this.bottom = bottom;+ this.sun = sun;+ this.sunX = sunX;+ }+ }++ private static final int NIGHT_TOP = 0xFF04060E;+ private static final int NIGHT_MID = 0xFF070C1A;+ private static final int NIGHT_BOTTOM = 0xFF0B1326;++ private static final Stop[] STOPS = {+ new Stop(0, NIGHT_TOP, NIGHT_MID, NIGHT_BOTTOM, 0, 0.30f),+ new Stop(320, NIGHT_TOP, NIGHT_MID, NIGHT_BOTTOM, 0, 0.30f),+ new Stop(390, 0xFF160F2E, 0xFF3B2352, 0xFF8A4A6B, 100, 0.24f),+ new Stop(450, 0xFF12203F, 0xFF5C3A63, 0xFFD3674F, 160, 0.30f),+ new Stop(570, 0xFF0E1A33, 0xFF1F3557, 0xFF43648B, 90, 0.38f),+ new Stop(780, 0xFF0B1524, 0xFF17304F, 0xFF31587F, 60, 0.50f),+ new Stop(1020, 0xFF0D1526, 0xFF20395C, 0xFF4C5470, 90, 0.62f),+ new Stop(1140, 0xFF1B1030, 0xFF6C2E52, 0xFFE2704A, 190, 0.76f),+ new Stop(1185, 0xFF140C27, 0xFF4A2049, 0xFFA54A5C, 130, 0.82f),+ new Stop(1260, 0xFF0A0A1C, 0xFF191230, 0xFF3A1F49, 60, 0.86f),+ new Stop(1350, NIGHT_TOP, NIGHT_MID, NIGHT_BOTTOM, 0, 0.30f),+ new Stop(1440, NIGHT_TOP, NIGHT_MID, NIGHT_BOTTOM, 0, 0.30f),+ };++ private Sky() {}++ /** The palette at {@code minuteOfDay}, clamped to a day. */+ static Palette at(int minuteOfDay) {+ int m = Math.max(0, Math.min(1440, minuteOfDay));+ Stop a = STOPS[0];+ Stop b = STOPS[STOPS.length - 1];+ for (int i = 0; i < STOPS.length - 1; i++) {+ if (m >= STOPS[i].minute && m <= STOPS[i + 1].minute) {+ a = STOPS[i];+ b = STOPS[i + 1];+ break;+ }+ }+ float t = b.minute == a.minute ? 0f : (m - a.minute) / (float) (b.minute - a.minute);+ return new Palette(+ lerpColor(a.top, b.top, t),+ lerpColor(a.mid, b.mid, t),+ lerpColor(a.bottom, b.bottom, t),+ Math.round(a.sun + (b.sun - a.sun) * t),+ a.sunX + (b.sunX - a.sunX) * t);+ }++ /** Blends two opaque ARGB colours channel by channel; {@code t} is 0 to 1. */+ static int lerpColor(int from, int to, float t) {+ float f = Math.max(0f, Math.min(1f, t));+ int a = Math.round(((from >>> 24) & 0xFF) + (((to >>> 24) & 0xFF) - ((from >>> 24) & 0xFF)) * f);+ int r = Math.round(((from >> 16) & 0xFF) + (((to >> 16) & 0xFF) - ((from >> 16) & 0xFF)) * f);+ int g = Math.round(((from >> 8) & 0xFF) + (((to >> 8) & 0xFF) - ((from >> 8) & 0xFF)) * f);+ int b = Math.round((from & 0xFF) + ((to & 0xFF) - (from & 0xFF)) * f);+ return (a << 24) | (r << 16) | (g << 8) | b;+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SkyView.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SkyView.javanew file mode 100644index 000000000..3dc5df0b8--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SkyView.java@@ -0,0 +1,73 @@+package com.gathin.photodream;++import android.content.Context;+import android.graphics.Bitmap;+import android.graphics.Canvas;+import android.graphics.LinearGradient;+import android.graphics.Paint;+import android.graphics.PorterDuff;+import android.graphics.RadialGradient;+import android.graphics.Shader;+import android.graphics.drawable.BitmapDrawable;+import android.view.Gravity;+import android.view.View;++import java.util.Calendar;++/**+ * A full-screen gradient that follows the clock (Sky). One small bitmap (480x270) stretched over the screen and+ * redrawn at most once a minute. From Photo Prints by @shivamsingh262 (#936).+ */+final class SkyView extends View {++ private static final int TEX_W = 480, TEX_H = 270;++ private int lastMinute = -1;+ private Bitmap texture;++ SkyView(Context context) {+ super(context);+ setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);+ }++ @Override+ public boolean hasOverlappingRendering() {+ return false;+ }++ /** Picks up a new time of day; cheap and safe to call often. */+ void update() {+ Calendar now = Calendar.getInstance();+ int minute = now.get(Calendar.HOUR_OF_DAY) * 60 + now.get(Calendar.MINUTE);+ if (minute == lastMinute) return;+ lastMinute = minute;++ Sky.Palette sky = Sky.at(minute);+ boolean first = texture == null;+ if (first) texture = Bitmap.createBitmap(TEX_W, TEX_H, Bitmap.Config.ARGB_8888);+ Canvas canvas = new Canvas(texture);+ canvas.drawColor(0, PorterDuff.Mode.CLEAR);++ Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);+ paint.setShader(new LinearGradient(0f, 0f, 0f, TEX_H,+ new int[]{sky.top, sky.mid, sky.bottom},+ new float[]{0f, 0.55f, 1f}, Shader.TileMode.CLAMP));+ canvas.drawRect(0f, 0f, TEX_W, TEX_H, paint);++ if (sky.sun > 0) {+ int warm = Sky.lerpColor(sky.bottom, 0xFFFFD9A0, 0.65f);+ paint.setShader(new RadialGradient(+ sky.sunX * TEX_W, TEX_H * 0.80f, TEX_W * 0.55f,+ new int[]{(sky.sun << 24) | (warm & 0x00FFFFFF), warm & 0x00FFFFFF},+ new float[]{0f, 1f}, Shader.TileMode.CLAMP));+ canvas.drawRect(0f, 0f, TEX_W, TEX_H, paint);+ }++ if (first) {+ BitmapDrawable drawable = new BitmapDrawable(getResources(), texture);+ drawable.setGravity(Gravity.FILL);+ setBackground(drawable);+ }+ invalidate();+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Slides.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Slides.javanew file mode 100644index 000000000..ec97c1748--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Slides.java@@ -0,0 +1,336 @@+package com.gathin.photodream;++import android.animation.AnimatorSet;+import android.animation.ObjectAnimator;+import android.animation.PropertyValuesHolder;+import android.content.Context;+import android.content.SharedPreferences;+import android.graphics.Bitmap;+import android.graphics.BitmapFactory;+import android.graphics.Matrix;+import android.graphics.SurfaceTexture;+import android.media.MediaPlayer;+import android.os.Handler;+import android.os.Looper;+import android.util.DisplayMetrics;+import android.view.Surface;+import android.view.TextureView;+import android.view.View;+import android.view.ViewGroup;+import android.view.animation.LinearInterpolator;+import android.widget.FrameLayout;+import android.widget.ImageView;+import android.widget.TextView;++import java.io.File;+import java.util.ArrayList;+import java.util.List;+import java.util.Random;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;++/**+ * Full-screen mode: loops through the pictures sync.sh put in the app's pictures/ folder, in filename order,+ * each slowly zooming and drifting (Ken Burns) and crossfading into the next after seconds.txt (20 s by+ * default). Two screen-sized pictures at most, held as GPU bitmaps. MP4 clips play once, muted and cropped to+ * fill the screen, on the hardware decoder (one player at a time), then the loop moves on.+ */+final class Slides {++ private static final long FADE_MS = 1500L;+ /** How far a picture zooms in over its time on screen; it drifts at most half the extra width. */+ private static final float ZOOM = 1.12f;++ private final Context context;+ private final Handler handler = new Handler(Looper.getMainLooper());+ private final Random random = new Random();+ /** The month and year of the picture on screen, or null when the option is off. */+ private final TextView caption;+ private final View empty;+ private ExecutorService decoder;+ private ImageView front;+ private ImageView back;+ private final TextureView video;+ private MediaPlayer player;+ private Surface surface;+ /** A clip waiting for the TextureView's surface. */+ private File pendingClip;+ /** Bumped for every clip so callbacks of a released player are ignored. */+ private int clipGeneration;+ private final List<File> images;+ private final SharedPreferences preferences;+ private final long interval;+ private final int width;+ private final int height;+ private boolean running;++ private final Runnable advance = this::showNext;++ Slides(Context context, FrameLayout stage, TextView caption, View empty) {+ this.context = context;+ this.caption = caption;+ this.empty = empty;+ video = new TextureView(context);+ video.setAlpha(0f);+ video.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {+ @Override public void onSurfaceTextureAvailable(SurfaceTexture texture, int w, int h) {+ surface = new Surface(texture);+ File clip = pendingClip;+ pendingClip = null;+ if (clip != null && running) playVideo(clip);+ }+ @Override public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int w, int h) {}+ @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {+ stopVideo();+ if (surface != null) surface.release();+ surface = null;+ return true;+ }+ @Override public void onSurfaceTextureUpdated(SurfaceTexture texture) {}+ });+ stage.addView(video, new FrameLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));+ back = image(stage);+ front = image(stage);+ DisplayMetrics metrics = context.getResources().getDisplayMetrics();+ width = metrics.widthPixels;+ height = metrics.heightPixels;+ preferences = context.getSharedPreferences("photo_dream", Context.MODE_PRIVATE);+ File dir = context.getExternalFilesDir(null);+ interval = Media.seconds(Photos.read(dir == null ? null : new File(dir, Media.SECONDS))) * 1000L;+ images = dir == null ? new ArrayList<>() : Media.list(new File(dir, Media.PICTURES));+ if (caption != null) caption.setAlpha(0f);+ }++ private ImageView image(FrameLayout stage) {+ ImageView view = new ImageView(context);+ view.setScaleType(ImageView.ScaleType.CENTER_CROP);+ view.setAlpha(0f);+ stage.addView(view, new FrameLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));+ return view;+ }++ void start() {+ running = true;+ empty.setVisibility(images.isEmpty() ? View.VISIBLE : View.GONE);+ if (decoder == null) decoder = Executors.newSingleThreadExecutor();+ showNext();+ }++ void stop() {+ running = false;+ handler.removeCallbacksAndMessages(null);+ if (decoder != null) decoder.shutdownNow();+ decoder = null;+ if (front != null) { cancel(front); release(front); }+ if (back != null) { cancel(back); release(back); }+ pendingClip = null;+ stopVideo();+ }++ /** Decodes the next picture off the main thread, then fades it in over the current one. */+ private void showNext() {+ if (!running || images.isEmpty() || decoder == null) return;+ decoder.execute(() -> {+ Bitmap bitmap = null;+ File clip = null;+ String date = "";+ // Skip unreadable pictures, but stop after one round so a folder of broken files doesn't spin.+ for (int tries = 0; tries < images.size() && bitmap == null && clip == null; tries++) {+ File file = Media.next(images, preferences.getString("image", ""));+ preferences.edit().putString("image", file.getName()).apply();+ if (Media.video(file.getName())) {+ clip = file;+ } else {+ bitmap = decode(file);+ if (bitmap != null && caption != null) date = Photos.dateOf(file);+ }+ }+ Bitmap shown = bitmap;+ File playing = clip;+ String shownDate = date;+ handler.post(() -> {+ if (!running) {+ if (shown != null) shown.recycle();+ return;+ }+ if (playing != null) {+ showCaption("");+ playVideo(playing); // moves on when the clip ends+ return;+ }+ if (shown != null) {+ crossfade(shown);+ showCaption(shownDate);+ }+ // A single picture still drifts on: it fades into itself with a new zoom.+ handler.postDelayed(advance, interval);+ });+ });+ }++ private void showCaption(String date) {+ if (caption == null) return;+ caption.animate().cancel();+ if (date.isEmpty()) {+ caption.animate().alpha(0f).setDuration(FADE_MS / 2).start();+ return;+ }+ caption.animate().alpha(0f).setDuration(FADE_MS / 2).withEndAction(() -> {+ caption.setText(date);+ caption.animate().alpha(1f).setDuration(FADE_MS / 2).start();+ }).start();+ }++ private void crossfade(Bitmap bitmap) {+ ImageView incoming = back;+ ImageView outgoing = front;+ back = outgoing;+ front = incoming;+ cancel(incoming);+ release(incoming);+ incoming.setImageBitmap(bitmap);+ incoming.setTag(bitmap);+ incoming.bringToFront();+ // Start zoomed in or out at random and drift toward a random spot, over the whole slide.+ boolean zoomIn = random.nextBoolean();+ float from = zoomIn ? 1f : ZOOM;+ float to = zoomIn ? ZOOM : 1f;+ float dx = (random.nextFloat() - 0.5f) * width * (ZOOM - 1f);+ float dy = (random.nextFloat() - 0.5f) * height * (ZOOM - 1f);+ incoming.setAlpha(0f);+ ObjectAnimator fade = ObjectAnimator.ofFloat(incoming, View.ALPHA, 0f, 1f).setDuration(FADE_MS);+ ObjectAnimator drift = ObjectAnimator.ofPropertyValuesHolder(incoming,+ PropertyValuesHolder.ofFloat(View.SCALE_X, from, to),+ PropertyValuesHolder.ofFloat(View.SCALE_Y, from, to),+ PropertyValuesHolder.ofFloat(View.TRANSLATION_X, zoomIn ? 0f : dx, zoomIn ? dx : 0f),+ PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, zoomIn ? 0f : dy, zoomIn ? dy : 0f))+ .setDuration(interval + 2 * FADE_MS);+ drift.setInterpolator(new LinearInterpolator());+ AnimatorSet set = new AnimatorSet();+ set.playTogether(fade, drift);+ incoming.setTag(R.id.animation, set);+ set.start();+ boolean afterClip = player != null;+ handler.postDelayed(() -> {+ cancel(outgoing);+ outgoing.setAlpha(0f);+ release(outgoing);+ if (afterClip) stopVideo();+ }, FADE_MS + 100);+ }++ /** Fades the clip in over whatever shows now and plays it to the end (or loops a lone clip). */+ private void playVideo(File clip) {+ if (surface == null) {+ pendingClip = clip;+ return;+ }+ boolean clipShowing = player != null;+ stopVideo();+ int generation = ++clipGeneration;+ MediaPlayer mp = new MediaPlayer();+ player = mp;+ try {+ mp.setDataSource(clip.getPath());+ mp.setSurface(surface);+ mp.setVolume(0f, 0f);+ mp.setLooping(images.size() == 1);+ mp.setOnVideoSizeChangedListener((p, w, h) -> cover(w, h));+ mp.setOnPreparedListener(p -> {+ if (generation != clipGeneration || !running) return;+ p.start();+ video.bringToFront();+ if (clipShowing) video.setAlpha(1f);+ else video.animate().alpha(1f).setDuration(FADE_MS).start();+ handler.postDelayed(() -> {+ if (generation != clipGeneration) return;+ for (ImageView view : new ImageView[] {front, back}) {+ cancel(view);+ view.setAlpha(0f);+ release(view);+ }+ }, FADE_MS + 100);+ });+ mp.setOnCompletionListener(p -> {+ if (generation == clipGeneration && running) showNext();+ });+ mp.setOnErrorListener((p, what, extra) -> {+ if (generation == clipGeneration && running) {+ stopVideo();+ handler.postDelayed(advance, 1000);+ }+ return true;+ });+ mp.prepareAsync();+ } catch (Exception failure) {+ stopVideo();+ handler.postDelayed(advance, 1000);+ }+ }++ /** Scales the clip to fill the screen, cropping the overflow evenly (like CENTER_CROP). */+ private void cover(int videoWidth, int videoHeight) {+ int w = video.getWidth(), h = video.getHeight();+ if (videoWidth <= 0 || videoHeight <= 0 || w <= 0 || h <= 0) return;+ float scale = Math.max((float) w / videoWidth, (float) h / videoHeight);+ Matrix matrix = new Matrix();+ matrix.setScale(videoWidth * scale / w, videoHeight * scale / h, w / 2f, h / 2f);+ video.setTransform(matrix);+ }++ private void stopVideo() {+ clipGeneration++;+ video.animate().cancel();+ video.setAlpha(0f);+ if (player != null) {+ try { player.stop(); } catch (IllegalStateException ignored) { }+ player.release();+ player = null;+ }+ }++ private static void cancel(ImageView view) {+ Object set = view.getTag(R.id.animation);+ if (set instanceof AnimatorSet) ((AnimatorSet) set).cancel();+ view.setTag(R.id.animation, null);+ }++ /** Frees the view's picture now instead of waiting for the garbage collector. */+ private static void release(ImageView view) {+ Object old = view.getTag();+ view.setImageDrawable(null);+ view.setTag(null);+ if (old instanceof Bitmap) ((Bitmap) old).recycle();+ }++ private Bitmap decode(File file) {+ try {+ BitmapFactory.Options options = new BitmapFactory.Options();+ options.inJustDecodeBounds = true;+ BitmapFactory.decodeFile(file.getPath(), options);+ int w = options.outWidth, h = options.outHeight;+ if (w <= 0 || h <= 0) return null;+ int sample = Media.sampleSize(w, h, width, height);+ if (!Media.accepted(w / sample, h / sample)) return null;+ options.inJustDecodeBounds = false;+ options.inSampleSize = sample;+ int[] scale = Media.coverScale(w / sample, h / sample, width, height);+ if (scale != null) {+ options.inScaled = true;+ options.inDensity = scale[0];+ options.inTargetDensity = scale[1];+ }+ options.inPreferredConfig = Bitmap.Config.RGB_565;+ Bitmap decoded = BitmapFactory.decodeFile(file.getPath(), options);+ if (decoded == null) return null;+ Bitmap gpu = decoded.copy(Bitmap.Config.HARDWARE, false);+ if (gpu == null) return decoded;+ decoded.recycle();+ return gpu;+ } catch (Exception | OutOfMemoryError failure) {+ return null;+ }+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SlideshowActivity.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SlideshowActivity.javanew file mode 100644index 000000000..9d760ff29--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/SlideshowActivity.java@@ -0,0 +1,47 @@+package com.gathin.photodream;++import android.app.Activity;+import android.content.Intent;+import android.os.Bundle;+import android.view.KeyEvent;+import android.view.WindowManager;++/**+ * The module card on cleanyourtv's Home: the same scene as the screensaver, right away, until Back. Menu opens+ * the settings. The screen stays on while it shows.+ */+public class SlideshowActivity extends Activity {++ private Scene scene;++ @Override+ protected void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);+ }++ @Override+ protected void onStart() {+ super.onStart();+ // Built again on every start, so options 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 onKeyDown(int keyCode, KeyEvent event) {+ if (keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_SETTINGS) {+ startActivity(new Intent(this, SettingsActivity.class));+ return true;+ }+ return super.onKeyDown(keyCode, event);+ }+}diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Weather.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Weather.javanew file mode 100644index 000000000..d79cdb4a6--- /dev/null+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Weather.java@@ -0,0 +1,123 @@+package com.gathin.photodream;++import android.Manifest;+import android.content.Context;+import android.content.pm.PackageManager;+import android.location.Location;+import android.location.LocationListener;+import android.location.LocationManager;+import android.os.Build;+import android.os.Bundle;+import android.os.Looper;++import org.json.JSONException;+import org.json.JSONObject;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.net.HttpURLConnection;+import java.net.URL;+import java.nio.charset.StandardCharsets;+import java.util.Locale;+import java.util.function.Consumer;++/**+ * The weather now, for the weather option: the TV's own location (coarse, rounded to about 1 km before it is+ * sent) and Open-Meteo, which needs no key. Only called while the option is on; nothing else goes out.+ */+final class Weather {+ static final long REFRESH_MS = 30 * 60_000L;+ private static final int TIMEOUT_MS = 8_000;++ private Weather() {}++ static boolean permitted(Context context) {+ return context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)+ == PackageManager.PERMISSION_GRANTED;+ }++ /** Whether the TV's location services are on (Settings > Privacy > Location on Google TV). */+ static boolean locationOn(Context context) {+ LocationManager lm = context.getSystemService(LocationManager.class);+ if (lm == null) return false;+ if (Build.VERSION.SDK_INT >= 28) return lm.isLocationEnabled();+ return !lm.getProviders(true).isEmpty();+ }++ /** The newest location the TV knows, or a fresh one; {@code done} gets null when there is none. */+ @SuppressWarnings("deprecation")+ static void locate(Context context, Consumer<Location> done) {+ LocationManager lm = context.getSystemService(LocationManager.class);+ if (lm == null || !permitted(context) || !locationOn(context)) {+ done.accept(null);+ return;+ }+ try {+ Location best = null;+ for (String provider : lm.getProviders(true)) {+ Location l = lm.getLastKnownLocation(provider);+ if (l != null && (best == null || l.getTime() > best.getTime())) best = l;+ }+ if (best != null) {+ done.accept(best);+ return;+ }+ if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {+ done.accept(null);+ return;+ }+ if (Build.VERSION.SDK_INT >= 30) {+ lm.getCurrentLocation(LocationManager.NETWORK_PROVIDER, null, context.getMainExecutor(),+ done::accept);+ } else {+ // All four methods spelled out: before Android 11 they have no defaults.+ lm.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, new LocationListener() {+ @Override public void onLocationChanged(Location location) { done.accept(location); }+ @Override public void onStatusChanged(String provider, int status, Bundle extras) { }+ @Override public void onProviderEnabled(String provider) { }+ @Override public void onProviderDisabled(String provider) { }+ }, Looper.getMainLooper());+ }+ } catch (SecurityException | IllegalArgumentException e) {+ done.accept(null);+ }+ }++ /** "12° ☁" for the place, blocking: call it off the main thread. */+ static String now(double latitude, double longitude) throws IOException, JSONException {+ // Two decimals is about 1 km: enough for the weather, no more of where the TV is than that.+ String url = String.format(Locale.ROOT, "https://api.open-meteo.com/v1/forecast?latitude=%.2f"+ + "&longitude=%.2f¤t=temperature_2m,weather_code,is_day", latitude, longitude);+ JSONObject current = get(url).getJSONObject("current");+ int temp = (int) Math.round(current.getDouble("temperature_2m"));+ return temp + "° " + symbol(current.getInt("weather_code"), current.optInt("is_day", 1) == 1);+ }++ /** A plain symbol for a WMO weather code, from characters every TV font has. */+ static String symbol(int code, boolean day) {+ if (code == 0 || code == 1) return day ? "\u2600" : "\u263E"; // sun, moon+ if (code == 2) return "\u26C5"; // sun behind cloud+ if (code == 3 || code == 45 || code == 48) return "\u2601"; // cloud (fog too)+ if (code >= 71 && code <= 77 || code == 85 || code == 86) return "\u2744"; // snow+ if (code >= 95) return "\u26A1"; // thunder+ return "\u2602"; // drizzle, rain, showers+ }++ private static JSONObject get(String url) throws IOException, JSONException {+ HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();+ connection.setConnectTimeout(TIMEOUT_MS);+ connection.setReadTimeout(TIMEOUT_MS);+ try (InputStream in = connection.getInputStream()) {+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ byte[] buffer = new byte[4096];+ for (int n; (n = in.read(buffer)) != -1; ) {+ out.write(buffer, 0, n);+ if (out.size() > 64 * 1024) throw new IOException("reply too large");+ }+ return new JSONObject(new String(out.toByteArray(), StandardCharsets.UTF_8));+ } finally {+ connection.disconnect();+ }+ }+}diff --git a/addons/photo-screensaver/app/src/main/res/drawable/banner.xml b/addons/photo-screensaver/app/src/main/res/drawable/banner.xmlnew file mode 100644index 000000000..7ae7324ac--- /dev/null+++ b/addons/photo-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: one framed picture 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="#FF14213D" android:pathData="M0,0h320v180h-320z" />+ <path android:fillColor="#FFF2F2F2" android:pathData="M100,30h120v120h-120z" />+ <path android:fillColor="#FF5B8DEF" android:pathData="M108,38h104v104h-104z" />+ <path android:fillColor="#FFFFC857" android:pathData="M180,70m-12,0a12,12 0,1 1,24 0a12,12 0,1 1,-24 0" />+ <path android:fillColor="#FF2E5E3E" android:pathData="M108,142l34,-44l26,28l18,-16l26,32z" />+</vector>diff --git a/addons/photo-screensaver/app/src/main/res/drawable/bottom_fade.xml b/addons/photo-screensaver/app/src/main/res/drawable/bottom_fade.xmlnew file mode 100644index 000000000..45758f9a0--- /dev/null+++ b/addons/photo-screensaver/app/src/main/res/drawable/bottom_fade.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Under the bottom line in full-screen mode, so the time and weather read on a bright picture. -->+<shape xmlns:android="http://schemas.android.com/apk/res/android">+ <gradient+ android:angle="270"+ android:startColor="#00000000"+ android:endColor="#A6000000" />+</shape>diff --git a/addons/photo-screensaver/app/src/main/res/drawable/icon.xml b/addons/photo-screensaver/app/src/main/res/drawable/icon.xmlnew file mode 100644index 000000000..1da07307b--- /dev/null+++ b/addons/photo-screensaver/app/src/main/res/drawable/icon.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- A picture frame with a hill and a sun. -->+<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="#FF14213D" android:pathData="M0,0h48v48h-48z" />+ <path android:fillColor="#FFF2F2F2" android:pathData="M8,11h32v26h-32z" />+ <path android:fillColor="#FF5B8DEF" android:pathData="M10,13h28v22h-28z" />+ <path android:fillColor="#FFFFC857" android:pathData="M30,20m-3,0a3,3 0,1 1,6 0a3,3 0,1 1,-6 0" />+ <path android:fillColor="#FF2E5E3E" android:pathData="M10,35l9,-11l7,7l5,-4l7,8z" />+</vector>diff --git a/addons/photo-screensaver/app/src/main/res/drawable/print_caption_fade.xml b/addons/photo-screensaver/app/src/main/res/drawable/print_caption_fade.xmlnew file mode 100644index 000000000..25711cf64--- /dev/null+++ b/addons/photo-screensaver/app/src/main/res/drawable/print_caption_fade.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<shape xmlns:android="http://schemas.android.com/apk/res/android">+ <gradient+ android:angle="270"+ android:startColor="#00000000"+ android:endColor="#99000000" />+</shape>diff --git a/addons/photo-screensaver/app/src/main/res/drawable/print_card.xml b/addons/photo-screensaver/app/src/main/res/drawable/print_card.xmlnew file mode 100644index 000000000..d230cb121--- /dev/null+++ b/addons/photo-screensaver/app/src/main/res/drawable/print_card.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<shape xmlns:android="http://schemas.android.com/apk/res/android">+ <solid android:color="#FF101014" />+ <corners android:radius="16dp" />+</shape>diff --git a/addons/photo-screensaver/app/src/main/res/layout/overlay.xml b/addons/photo-screensaver/app/src/main/res/layout/overlay.xmlnew file mode 100644index 000000000..0050e0960--- /dev/null+++ b/addons/photo-screensaver/app/src/main/res/layout/overlay.xml@@ -0,0 +1,130 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- On top of the pictures (Scene): the month and year of the picture, the bottom line with the time, the date+ and the weather, and where to put pictures when there are none. Each part only when its option is on. -->+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:clipChildren="false">++ <View+ android:id="@+id/bottomFade"+ android:layout_width="match_parent"+ android:layout_height="220dp"+ android:layout_gravity="bottom"+ android:background="@drawable/bottom_fade" />++ <TextView+ android:id="@+id/caption"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="top|start"+ android:layout_marginStart="72dp"+ android:layout_marginTop="40dp"+ android:textColor="#F2FFFFFF"+ android:textSize="20sp"+ android:fontFamily="sans-serif-medium"+ android:shadowColor="#CC000000"+ android:shadowRadius="8" />++ <LinearLayout+ android:id="@+id/empty"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="center"+ android:gravity="center_horizontal"+ android:orientation="vertical"+ android:visibility="gone">++ <TextView+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="@string/empty_title"+ android:textColor="#F2FFFFFF"+ android:textSize="28sp" />++ <TextView+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginTop="12dp"+ android:text="@string/empty_body"+ android:textColor="#B3FFFFFF"+ android:textSize="16sp" />++ <TextView+ android:id="@+id/emptyPath"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginTop="6dp"+ android:textColor="#B3FFFFFF"+ android:textSize="16sp"+ android:fontFamily="monospace" />+ </LinearLayout>++ <!-- Moved a little every minute so it does not burn in. -->+ <LinearLayout+ android:id="@+id/bottomLine"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_gravity="bottom"+ android:layout_marginStart="72dp"+ android:layout_marginEnd="72dp"+ android:layout_marginBottom="40dp"+ android:baselineAligned="true"+ android:orientation="horizontal">++ <TextClock+ android:id="@+id/time"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:format12Hour="h:mm"+ android:format24Hour="HH:mm"+ android:textColor="#F2FFFFFF"+ android:textSize="56sp"+ android:fontFamily="sans-serif-light"+ android:includeFontPadding="false"+ android:shadowColor="#99000000"+ android:shadowRadius="6" />++ <TextClock+ android:id="@+id/ampm"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp"+ android:format12Hour="a"+ android:format24Hour=""+ android:textAllCaps="true"+ android:textColor="#B3FFFFFF"+ android:textSize="16sp"+ android:shadowColor="#99000000"+ android:shadowRadius="6" />++ <TextClock+ android:id="@+id/date"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="22dp"+ android:format12Hour="@string/date_format"+ android:format24Hour="@string/date_format"+ android:letterSpacing="0.14"+ android:textAllCaps="true"+ android:textColor="#B3FFFFFF"+ android:textSize="16sp"+ android:shadowColor="#99000000"+ android:shadowRadius="6" />++ <Space+ android:layout_width="0dp"+ android:layout_height="1dp"+ android:layout_weight="1" />++ <TextView+ android:id="@+id/weather"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:textColor="#F2FFFFFF"+ android:textSize="32sp"+ android:fontFamily="sans-serif-light"+ android:shadowColor="#99000000"+ android:shadowRadius="6" />+ </LinearLayout>+</FrameLayout>diff --git a/addons/photo-screensaver/app/src/main/res/layout/print.xml b/addons/photo-screensaver/app/src/main/res/layout/print.xmlnew file mode 100644index 000000000..213dc3547--- /dev/null+++ b/addons/photo-screensaver/app/src/main/res/layout/print.xml@@ -0,0 +1,43 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- One print (Prints): the whole picture with rounded corners and its month and year over a fade along its+ foot. The outer frame is a clear margin for the shadow (PrintShadow), drawn as one layer with the picture so+ the tilted edges come out smooth. From Photo Prints by @shivamsingh262 (#936). -->+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:padding="@dimen/print_shadow_room"+ android:clipToPadding="false"+ android:clipChildren="false">++ <FrameLayout+ android:id="@+id/printCard"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:background="@drawable/print_card">++ <ImageView+ android:id="@+id/printPhoto"+ android:layout_width="0dp"+ android:layout_height="0dp"+ android:scaleType="fitXY"+ android:importantForAccessibility="no" />++ <TextView+ android:id="@+id/printDate"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_gravity="bottom"+ android:background="@drawable/print_caption_fade"+ android:gravity="start|bottom"+ android:paddingStart="16dp"+ android:paddingEnd="16dp"+ android:paddingTop="32dp"+ android:paddingBottom="12dp"+ android:singleLine="true"+ android:textColor="#F2FFFFFF"+ android:textSize="16sp"+ android:fontFamily="sans-serif-medium"+ android:shadowColor="#80000000"+ android:shadowRadius="4" />+ </FrameLayout>+</FrameLayout>diff --git a/addons/photo-screensaver/app/src/main/res/values-nl/strings.xml b/addons/photo-screensaver/app/src/main/res/values-nl/strings.xmlindex 7c144d4fe..47f85ccf5 100644--- a/addons/photo-screensaver/app/src/main/res/values-nl/strings.xml+++ b/addons/photo-screensaver/app/src/main/res/values-nl/strings.xml@@ -2,4 +2,19 @@<resources><string name="app_name">Foto-screensaver</string><string name="dream_name">Foto\'s</string>+ <string name="date_format">EEEE d MMMM</string>+ <string name="empty_title">Nog geen foto\'s</string>+ <string name="empty_body">Zet foto\'s in deze map op de TV met sync.sh of sync.ps1:</string>+ <string name="settings_title">Foto-screensaver</string>+ <string name="option_clock">Tijd en datum tonen</string>+ <string name="option_dates">Tonen wanneer een foto is gemaakt (maand en jaar)</string>+ <string name="option_prints">Drie afdrukken in plaats van schermvullend (geen clips)</string>+ <string name="option_sky">Lucht die meekleurt met het tijdstip achter de afdrukken</string>+ <string name="option_weather">Het weer tonen (heeft de locatie van de TV nodig)</string>+ <string name="weather_info">Gebruikt de globale locatie van de TV en Open-Meteo. Uit: er gaat niets over het netwerk.</string>+ <string name="weather_no_permission">Sta locatietoegang toe voor het weer.</string>+ <string name="weather_location_off">Locatieservices staan uit op deze TV: zet ze aan voor het weer.</string>+ <string name="weather_ok">Locatie staat aan. Het weer wordt elke 30 minuten bijgewerkt.</string>+ <string name="open_location_settings">Locatie-instellingen openen</string>+ <string name="preview">Voorbeeld</string></resources>diff --git a/addons/photo-screensaver/app/src/main/res/values/dimens.xml b/addons/photo-screensaver/app/src/main/res/values/dimens.xmlnew file mode 100644index 000000000..66fbedcee--- /dev/null+++ b/addons/photo-screensaver/app/src/main/res/values/dimens.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!-- The clear margin around each print that its shadow is drawn into (print.xml). -->+ <dimen name="print_shadow_room">56dp</dimen>+</resources>diff --git a/addons/photo-screensaver/app/src/main/res/values/strings.xml b/addons/photo-screensaver/app/src/main/res/values/strings.xmlindex 1fcbaa5e2..4bacbcfc5 100644--- a/addons/photo-screensaver/app/src/main/res/values/strings.xml+++ b/addons/photo-screensaver/app/src/main/res/values/strings.xml@@ -2,4 +2,19 @@<resources><string name="app_name">Photo screensaver</string><string name="dream_name">Photos</string>+ <string name="date_format">EEEE d MMMM</string>+ <string name="empty_title">No pictures yet</string>+ <string name="empty_body">Put pictures in this folder on the TV with sync.sh or sync.ps1:</string>+ <string name="settings_title">Photo screensaver</string>+ <string name="option_clock">Show the time and date</string>+ <string name="option_dates">Show when a picture was taken (month and year)</string>+ <string name="option_prints">Three prints instead of full screen (no clips)</string>+ <string name="option_sky">Sky that follows the time of day behind the prints</string>+ <string name="option_weather">Show the weather (needs the TV\'s location)</string>+ <string name="weather_info">Uses the TV\'s rough location and Open-Meteo. Off: nothing goes over the network.</string>+ <string name="weather_no_permission">Allow location access for the weather.</string>+ <string name="weather_location_off">Location services are off on this TV: turn them on for the weather.</string>+ <string name="weather_ok">Location is on. The weather is updated every 30 minutes.</string>+ <string name="open_location_settings">Open location settings</string>+ <string name="preview">Preview</string></resources>diff --git a/addons/photo-screensaver/app/src/main/res/xml/dream.xml b/addons/photo-screensaver/app/src/main/res/xml/dream.xmlnew file mode 100644index 000000000..5105fbf14--- /dev/null+++ b/addons/photo-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.photodream/.SettingsActivity" />diff --git a/addons/photo-screensaver/app/src/main/res/xml/module_card.xml b/addons/photo-screensaver/app/src/main/res/xml/module_card.xmlnew file mode 100644index 000000000..6ad2bd873--- /dev/null+++ b/addons/photo-screensaver/app/src/main/res/xml/module_card.xml@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="utf-8"?>+<card spec="1" label="Photos" caption="Slideshow" accent="#5B8DEF" />diff --git a/addons/photo-screensaver/app/src/test/java/com/gathin/photodream/MediaTest.java b/addons/photo-screensaver/app/src/test/java/com/gathin/photodream/MediaTest.javaindex 392d4d6a4..4b635872d 100644--- a/addons/photo-screensaver/app/src/test/java/com/gathin/photodream/MediaTest.java+++ b/addons/photo-screensaver/app/src/test/java/com/gathin/photodream/MediaTest.java@@ -67,6 +67,14 @@ public class MediaTest {assertNull(Media.coverScale(1920, 1080, 1920, 1080));}+ @Test public void readsTheDateFromTheName() {+ assertArrayEquals(new int[]{2023, 12}, Media.dateFromName("photo-0007-20231202.jpg"));+ assertArrayEquals(new int[]{2023, 12}, Media.dateFromName("photo-202312.jpg"));+ assertNull(Media.dateFromName("photo-20231302.jpg"));+ assertNull(Media.dateFromName("holiday.jpg"));+ assertNull(Media.dateFromName(null));+ }+private static void write(File file, int bytes) throws Exception {try (FileOutputStream out = new FileOutputStream(file)) {out.write(new byte[bytes]);