KidsTube: landscape 3x3 grid, likes, watch stats, series ordering
Rework the interface against the iPad kids screenshot and make landscape the primary layout, since that is the orientation the child uses. - dark canvas, red play logo + Kids wordmark, category pills (All + folders) - four-tab bar Home / Search / Your stuff / Profile, shield + gear up top - TileView draws the whole tile: rounded 16:9 frame, duration pill, two-line title inside the image, heart when liked; tiles sized from the home grid height so three rows of three fit without scrolling - player offers four more videos as a single row in the lower third, ordered [random, previous of the series, next of the series, random]; a finished video rolls into another one instead of looping - likes (heart in the player) feed "Your stuff"; empty states say so - StatsDb records plays, watched time and per-day sums, mirrors them to stats.json for an outside process; parent gate shows the summary - thumbnails pick the brightest of three offsets, because openings fade from black and left three of ten tiles empty - Series ordering rules covered by unit tests (9 tests, JVM only) Verified locally: assembleDebug, testDebugUnitTest, lintDebug all green. Device verification of the new grid, likes and stats screen is pending: the tablet dropped off the USB bus (adbd crash-loop) before the last two builds.
This commit is contained in:
1 parent
ec3fd61756
commit
d9f7f3dc30
37 files changed
+1660
-353
No files matched your search
@@ -1,106 +1,106 @@
|
||||
# KidsTube
|
||||
|
||||
Android app that reproduces the **iOS** YouTube Kids interface — thumbnail
|
||||
shelves, fullscreen player, bottom bar — while playing video from a **local
|
||||
folder only**. No network, no account, no recommendations. It exists because the
|
||||
son accepts the iOS kids UI and rejects the Android one, so this is a convincing
|
||||
shell around local files. Floor: Android 5.0 / API 21. App name: KidsTube.
|
||||
Android app that reproduces the **iOS** YouTube Kids interface over a **local
|
||||
folder**: 3x3 tile grid, category pills, fullscreen player, four-tab bar. No
|
||||
network, no account, no recommendations. It exists because the son accepts only
|
||||
the iOS kids look, so this is a convincing shell around local files.
|
||||
Floor: Android 5.0 / API 21. App name: KidsTube.
|
||||
|
||||
State 2026-10-28: builds, installs and plays on the target tablet; shelves,
|
||||
search, player and the parent gate were verified on the device.
|
||||
**Primary orientation is landscape** — the child always watches in landscape, so
|
||||
landscape is the layout that must not break. Portrait must still work.
|
||||
|
||||
## Non-negotiables
|
||||
|
||||
- No network. The APK must carry no `INTERNET` permission and no HTTP client:
|
||||
- No network: the APK carries no `INTERNET` permission and no HTTP client.
|
||||
`unzip -p app/build/outputs/apk/debug/app-debug.apk AndroidManifest.xml | strings | grep -ci internet`
|
||||
must print `0`, and
|
||||
prints `0`, and
|
||||
`/home/lotherk/android-sdk/build-tools/35.0.0/aapt2 dump permissions app/build/outputs/apk/debug/app-debug.apk`
|
||||
must list only the two storage permissions.
|
||||
- `minSdk` stays 21. Check any new AAR's `minSdk` before adding it — much of
|
||||
current androidx sits at 23+.
|
||||
lists only the two storage permissions.
|
||||
- `minSdk` stays `21`. Check every new AAR's `minSdk` before adding it.
|
||||
- Grid is always **3 columns**, and exactly **3 rows must fit** the landscape
|
||||
screen without scrolling. The title lives *inside* the tile — a caption row
|
||||
below it costs the height those three rows need.
|
||||
- When the choice is "Material default" vs "the iOS app's proportions", take iOS.
|
||||
|
||||
## Environment (this machine, verified)
|
||||
|
||||
- JDK 21 (`/usr/lib/jvm/java-21-openjdk-amd64`); no JDK 8 or 17 installed.
|
||||
- SDK lives in `/home/lotherk/android-sdk` (user-local). The distro's
|
||||
`/usr/lib/android-sdk` has no `platforms/` or `build-tools/`, and its bundled
|
||||
`sdkmanager`/`apkanalyzer` die on JDK 21 with `NoClassDefFoundError:
|
||||
javax/xml/bind/annotation/XmlSchema` (JAXB removed in JDK 11) — do not use it.
|
||||
- JDK 21 (`/usr/lib/jvm/java-21-openjdk-amd64`); no JDK 8 or 17.
|
||||
- SDK in `/home/lotherk/android-sdk`. The distro's `/usr/lib/android-sdk` has no
|
||||
`platforms/` or `build-tools/`, and its bundled `sdkmanager` dies on JDK 21
|
||||
(`NoClassDefFoundError: javax/xml/bind/...`, JAXB removed in JDK 11).
|
||||
- `gradle` is not on PATH; the standalone distribution is
|
||||
`/home/lotherk/android-tools/gradle-8.13`. The wrapper is pinned to 8.13 and
|
||||
`/home/lotherk/android-tools/gradle-8.13`. Wrapper pinned to 8.13,
|
||||
`local.properties` points at the SDK.
|
||||
- AGP 8.13.2, Kotlin 2.1.20, compileSdk 35, build-tools 35.0.0. AGP 8.13 requires
|
||||
- AGP 8.13.2, Kotlin 2.1.20, compileSdk 35, build-tools 35.0.0. AGP 8.13 needs
|
||||
Gradle >= 8.13, Build-Tools >= 35.0.0, JDK >= 17.
|
||||
|
||||
## Build, install, run
|
||||
## Build, test, run
|
||||
|
||||
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
|
||||
export ANDROID_HOME=/home/lotherk/android-sdk
|
||||
|
||||
./gradlew :app:assembleDebug # apk -> app/build/outputs/apk/debug/
|
||||
./gradlew :app:lintDebug # must stay green; abortOnError = true
|
||||
./gradlew :app:testDebugUnitTest # Series rules, no device needed
|
||||
./gradlew :app:lintDebug # abortOnError = true
|
||||
adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
adb shell pm grant dev.lotherk.kidstube android.permission.READ_EXTERNAL_STORAGE
|
||||
adb shell am start -n dev.lotherk.kidstube/.ui.MainActivity
|
||||
adb exec-out screencap -p > /tmp/kt.png
|
||||
adb logcat -d | grep -E 'kidstube|AndroidRuntime'
|
||||
|
||||
Target device: Huawei AGS2-W09, LineageOS 18.1 (`18.1-20220523-UNOFFICIAL-prague`),
|
||||
Android 11 / API 30, arm64-v8a, 1200x1920 at 480 dpi = 400dp wide. API 21 cannot
|
||||
be exercised here — that needs an emulator image and none is installed.
|
||||
Target device: Huawei AGS2-W09, LineageOS 18.1, API 30, arm64-v8a, 1200x1920 at
|
||||
480 dpi — 640dp wide in landscape. API 21 cannot be exercised here (no emulator
|
||||
image installed).
|
||||
|
||||
## Content
|
||||
|
||||
The library is `Movies/KidsTube` (`/storage/emulated/0/Movies/KidsTube`), scanned
|
||||
through MediaStore; a SAF tree picked from the Profile screen takes precedence.
|
||||
Copy files with
|
||||
Library is `Movies/KidsTube`, scanned via MediaStore; a SAF tree picked behind
|
||||
the parent gate takes precedence. Copying needs a scan:
|
||||
|
||||
adb push video.mp4 /sdcard/Movies/KidsTube/
|
||||
adb shell am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file:///sdcard/Movies/KidsTube/video.mp4
|
||||
|
||||
The broadcast is not optional: a pushed file stays invisible until MediaStore
|
||||
indexes it, and from API 29 scoped storage forbids directory listing (the app uid
|
||||
gets `EACCES`), so there is no fallback route.
|
||||
Mandatory: from API 29 scoped storage forbids directory listing (the app uid gets
|
||||
`EACCES`), and a pushed file stays invisible until MediaStore indexes it.
|
||||
|
||||
## Layout and conventions
|
||||
## Code map
|
||||
|
||||
- `data/` — `Library` (SAF tree, else MediaStore; folder grouping; `MediaItem`
|
||||
carries a sha1 `key`), `MediaItem`.
|
||||
- `media/ThumbCache` — decode via `MediaMetadataRetriever`, write JPEGs to
|
||||
`filesDir/thumbs`, `LruCache` in memory, 3-thread pool, tag-guarded binds.
|
||||
- `ui/` — `MainActivity` (shelves, search grid, parent gate), `SectionAdapter`
|
||||
(vertical shelves, each a horizontal RecyclerView), `VideoAdapter` (modes HERO /
|
||||
CAROUSEL / GRID), `PlayerActivity` (VideoView, immersive, auto-hiding chrome),
|
||||
`ThumbView`.
|
||||
- `ThumbView` owns the two numbers the look depends on — 16:9 and 12dp corner
|
||||
radius — plus the duration pill. Never re-implement them per layout.
|
||||
- Kotlin + Views + AppCompat, single `:app` module, viewBinding, no Compose.
|
||||
Every dimension in dp/sp, designed against 400dp width.
|
||||
- `data/Library` — SAF tree else MediaStore; `MediaItem`; sorted by folder then
|
||||
`Series.naturalOrder` (leading `001`, `002` … numeric, not lexical).
|
||||
- `data/Series` — ordering plus the player's suggestion rule, pure and unit
|
||||
tested: slots are `[random, previous of the series, next of the series, random]`.
|
||||
- `media/ThumbCache` — decode via `MediaMetadataRetriever`, take the brightest of
|
||||
three offsets (openings often fade from black), write JPEGs to
|
||||
`filesDir/thumbs`, `LruCache` in memory, 3 threads, tag-guarded callback.
|
||||
- `ui/TileView` — one view draws the whole tile: rounded 16:9 bitmap, duration
|
||||
pill top-right, two-line title over a bottom scrim, heart when liked.
|
||||
- `ui/MainActivity` — pills, grid, tabs, parent gate. `ui/TileSpacing` centres a
|
||||
tile in its cell. Tiles are sized from the **home grid** height, one value
|
||||
shared by both lists.
|
||||
- `ui/PlayerActivity` — VideoView, immersive, chrome auto-hides; four suggestions,
|
||||
heart to like, and a finished video rolls into a random one.
|
||||
- `stats/StatsDb` — SQLite: `sessions` (plays, watched ms, per day) and `likes`.
|
||||
Mirrored to `getExternalFilesDir()/stats.json` for another process to pull.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- `reload()` must treat "no SAF tree, storage permission granted" as a valid
|
||||
source. Gating on the tree alone silently shows an empty home screen.
|
||||
- `VideoView` swallows touches, so its `OnClickListener` never fires; the player
|
||||
uses a transparent `tap_catcher` view above it to bring the chrome back.
|
||||
- Tint AppCompat widgets with `app:tint`, never `android:tint` — lint fails the
|
||||
build on `UseAppTint`, and the vector drawables are white by default, so a
|
||||
missing tint makes an icon invisible rather than obviously wrong.
|
||||
- The system "Viewing full screen" confirmation appears on first launch and holds
|
||||
focus — dismiss it before trusting any UI dump.
|
||||
- Never size tiles from whichever list is visible: the search tab is shorter
|
||||
(56dp bar) and shrank the tiles for every tab.
|
||||
- `VideoView` swallows touches; the player needs the transparent `tap_catcher`
|
||||
to bring the chrome back.
|
||||
- Tint AppCompat widgets with `app:tint`, never `android:tint` — lint fails on
|
||||
`UseAppTint`, and the vectors are white, so a missing tint hides the icon.
|
||||
- The tablet's adbd crash-loops (`Could not install *smartsocket* listener`) and
|
||||
the device then vanishes from `lsusb`. Re-plugging the cable brings it back; a
|
||||
missing device is the hardware, not the app.
|
||||
- `uiautomator dump` takes seconds here, longer than the 4s chrome timeout, so a
|
||||
dump right after a tap shows stale state. Screenshot instead.
|
||||
- adbd on the device crash-loops (`Could not install *smartsocket* listener`); a
|
||||
dropped `adb` connection is the device, not the app. Reconnect and check
|
||||
`sys.boot_completed`.
|
||||
- The tablet randomly brings up the camera app between commands. Force-stop
|
||||
`com.android.camera2` and restart the activity if the focus looks wrong.
|
||||
- File paths: `/storage/emulated/0` is the real mount; `/sdcard` works for `ls`
|
||||
but not for `df`.
|
||||
- The tablet randomly brings up the camera app. Force-stop `com.android.camera2`
|
||||
and restart the activity if the focus looks wrong.
|
||||
- Rotation is sensor driven; force a test orientation with
|
||||
`adb shell settings put system accelerometer_rotation 0` then
|
||||
`adb shell settings put system user_rotation 0|1`.
|
||||
|
||||
## Repo
|
||||
|
||||
Initialised locally (one commit), no remote yet; Konrad's convention is `origin`
|
||||
= hiddenbox when one is added. Short imperative commit subjects, no
|
||||
conventional-commit prefixes.
|
||||
Initialised locally, no remote yet; Konrad's convention is `origin` = hiddenbox
|
||||
when one is added. Short imperative commit subjects.
|
||||
@@ -45,4 +45,6 @@ dependencies {
|
||||
implementation("androidx.appcompat:appcompat:1.7.0")
|
||||
implementation("androidx.recyclerview:recyclerview:1.3.2")
|
||||
implementation("androidx.documentfile:documentfile:1.0.1")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
@@ -18,14 +18,15 @@
|
||||
|
||||
<activity
|
||||
android:name=".ui.MainActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="orientation|screenSize|keyboardHidden">
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity android:name=".ui.StatsActivity" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.PlayerActivity"
|
||||
android:configChanges="orientation|screenSize|keyboardHidden"
|
||||
|
||||
@@ -62,7 +62,9 @@ object Library {
|
||||
val tree = treeUri(context)
|
||||
Log.d("kidstube", "scan tree=" + (tree != null) + " perm=" + hasReadPermission(context))
|
||||
val items = if (tree != null) scanTree(context, tree) else scanDefaultFolder(context)
|
||||
return items.sortedWith(compareBy({ it.folder.lowercase() }, { it.title.lowercase() }))
|
||||
return items.sortedWith(
|
||||
compareBy<MediaItem> { it.folder.lowercase() }.then(Series.naturalOrder)
|
||||
)
|
||||
}
|
||||
|
||||
fun defaultFolderPath(): String =
|
||||
|
||||
@@ -5,7 +5,7 @@ import android.net.Uri
|
||||
/** One video found under the chosen folder. */
|
||||
data class MediaItem(
|
||||
val uri: Uri,
|
||||
val title: String,
|
||||
val folder: String,
|
||||
val key: String
|
||||
)
|
||||
override val title: String,
|
||||
override val folder: String,
|
||||
override val key: String
|
||||
) : SeriesItem
|
||||
@@ -0,0 +1,68 @@
|
||||
package dev.lotherk.kidstube.data
|
||||
|
||||
/**
|
||||
* Ordering and "what comes next" rules for the player's suggestion strip.
|
||||
*
|
||||
* Videos are named like "001 - ...", "002 - ...", so a folder is a series in
|
||||
* numeric order. Watching one of them must not jump around: the strip is
|
||||
* [random, previous of the series, next of the series, random].
|
||||
*
|
||||
* The rules work on [SeriesItem], not [MediaItem], so they run under a plain
|
||||
* JVM unit test without Android stubs.
|
||||
*/
|
||||
object Series {
|
||||
|
||||
private val LEADING_NUMBER = Regex("^(\\d+)")
|
||||
|
||||
/** Numeric prefix first, then plain title: 2 comes before 10. */
|
||||
val naturalOrder: Comparator<SeriesItem> = Comparator { a, b ->
|
||||
val na = LEADING_NUMBER.find(a.title)?.groupValues?.get(1)?.toLongOrNull()
|
||||
val nb = LEADING_NUMBER.find(b.title)?.groupValues?.get(1)?.toLongOrNull()
|
||||
when {
|
||||
na != null && nb != null -> if (na != nb) na.compareTo(nb) else a.title.compareTo(b.title)
|
||||
na != null -> -1
|
||||
nb != null -> 1
|
||||
else -> a.title.compareTo(b.title, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
|
||||
/** The current video's neighbours inside its own folder. */
|
||||
fun <T : SeriesItem> neighbours(all: List<T>, current: T): Pair<T?, T?> {
|
||||
val series = all.filter { it.folder == current.folder }.sortedWith(naturalOrder)
|
||||
val index = series.indexOfFirst { it.key == current.key }
|
||||
if (index < 0) return null to null
|
||||
val previous = if (index > 0) series[index - 1] else null
|
||||
val next = if (index < series.size - 1) series[index + 1] else null
|
||||
return previous to next
|
||||
}
|
||||
|
||||
fun <T : SeriesItem> suggestionsFor(all: List<T>, current: T, size: Int = 4): List<T> {
|
||||
val (previous, next) = neighbours(all, current)
|
||||
val used = hashSetOf(current.key)
|
||||
previous?.let { used.add(it.key) }
|
||||
next?.let { used.add(it.key) }
|
||||
|
||||
val rest = all.filter { it.key !in used }.shuffled().iterator()
|
||||
val out = ArrayList<T>(size)
|
||||
|
||||
fun takeRandom() {
|
||||
while (rest.hasNext() && out.size < size) {
|
||||
val candidate = rest.next()
|
||||
if (out.none { it.key == candidate.key }) {
|
||||
out.add(candidate)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
takeRandom()
|
||||
previous?.let { if (out.size < size) out.add(it) }
|
||||
next?.let { if (out.size < size) out.add(it) }
|
||||
takeRandom()
|
||||
while (out.size < size && rest.hasNext()) {
|
||||
val candidate = rest.next()
|
||||
if (out.none { it.key == candidate.key }) out.add(candidate)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dev.lotherk.kidstube.data
|
||||
|
||||
/** The parts of a video that ordering and suggestion rules need. */
|
||||
interface SeriesItem {
|
||||
val key: String
|
||||
val title: String
|
||||
val folder: String
|
||||
}
|
||||
@@ -6,10 +6,11 @@ import android.graphics.BitmapFactory
|
||||
import android.media.MediaMetadataRetriever
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.util.LruCache
|
||||
import dev.lotherk.kidstube.data.Library
|
||||
import dev.lotherk.kidstube.data.MediaItem
|
||||
import dev.lotherk.kidstube.ui.ThumbView
|
||||
import android.view.View
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.Executors
|
||||
@@ -35,29 +36,36 @@ object ThumbCache {
|
||||
return if (ms > 0) formatDuration(ms) else null
|
||||
}
|
||||
|
||||
fun load(context: Context, item: MediaItem, view: ThumbView) {
|
||||
fun memory(key: String): Bitmap? = memory.get(key)
|
||||
|
||||
fun load(
|
||||
context: Context,
|
||||
item: MediaItem,
|
||||
view: View,
|
||||
apply: (Bitmap?, String?) -> Unit
|
||||
) {
|
||||
val key = item.key
|
||||
view.tag = key
|
||||
|
||||
memory.get(key)?.let {
|
||||
view.setThumb(it, label(context, item))
|
||||
apply(it, label(context, item))
|
||||
return
|
||||
}
|
||||
|
||||
val fromDisk = readDisk(context, item)
|
||||
if (fromDisk != null) {
|
||||
memory.put(key, fromDisk)
|
||||
view.setThumb(fromDisk, label(context, item))
|
||||
apply(fromDisk, label(context, item))
|
||||
return
|
||||
}
|
||||
|
||||
view.setThumb(null, label(context, item))
|
||||
apply(null, label(context, item))
|
||||
val app = context.applicationContext
|
||||
pool.execute {
|
||||
val data = generateThumb(app, item)
|
||||
main.post {
|
||||
if (data.bitmap != null) memory.put(key, data.bitmap)
|
||||
if (view.tag == key) view.setThumb(data.bitmap, data.label)
|
||||
if (view.tag == key) apply(data.bitmap, data.label)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,17 +84,14 @@ object ThumbCache {
|
||||
val durationMs = retriever
|
||||
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
|
||||
?.toLongOrNull() ?: 0L
|
||||
val frame = retriever.getFrameAtTime(
|
||||
if (durationMs > 3000) 1_000_000L else 0L,
|
||||
MediaMetadataRetriever.OPTION_CLOSEST_SYNC
|
||||
)
|
||||
val scaled = frame?.let { scaleToWidth(it, THUMB_WIDTH) }
|
||||
val scaled = pickFrame(retriever, durationMs)?.let { scaleToWidth(it, THUMB_WIDTH) }
|
||||
if (scaled != null) writeDisk(context, item, scaled)
|
||||
if (durationMs > 0) {
|
||||
Library.prefs(context).edit().putLong("dur_" + item.key, durationMs).apply()
|
||||
}
|
||||
return ThumbData(scaled, if (durationMs > 0) formatDuration(durationMs) else null)
|
||||
} catch (t: Throwable) {
|
||||
Log.w("kidstube", "thumb failed: " + item.title + ": " + t)
|
||||
return ThumbData(null, null)
|
||||
} finally {
|
||||
try {
|
||||
@@ -96,6 +101,57 @@ object ThumbCache {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Videos often open on a fade from black, so the first second is a black
|
||||
* frame. Sample several offsets and keep the brightest one.
|
||||
*/
|
||||
private fun pickFrame(retriever: MediaMetadataRetriever, durationMs: Long): Bitmap? {
|
||||
val offsets = if (durationMs > 5000) {
|
||||
longArrayOf(durationMs / 10, durationMs / 4, durationMs / 2)
|
||||
} else {
|
||||
longArrayOf(0L)
|
||||
}
|
||||
var best: Bitmap? = null
|
||||
var bestScore = -1.0
|
||||
for (offset in offsets) {
|
||||
val frame = try {
|
||||
retriever.getFrameAtTime(offset * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
} ?: continue
|
||||
val score = brightness(frame)
|
||||
if (score > bestScore) {
|
||||
best?.recycle()
|
||||
best = frame
|
||||
bestScore = score
|
||||
} else {
|
||||
frame.recycle()
|
||||
}
|
||||
if (bestScore > 40.0) break
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
private fun brightness(bitmap: Bitmap): Double {
|
||||
var sum = 0.0
|
||||
var count = 0
|
||||
val stepX = (bitmap.width / 16).coerceAtLeast(1)
|
||||
val stepY = (bitmap.height / 16).coerceAtLeast(1)
|
||||
var y = 0
|
||||
while (y < bitmap.height) {
|
||||
var x = 0
|
||||
while (x < bitmap.width) {
|
||||
val c = bitmap.getPixel(x, y)
|
||||
sum += ((c shr 16 and 0xFF) + (c shr 8 and 0xFF) + (c and 0xFF)) / 3.0
|
||||
count++
|
||||
x += stepX
|
||||
}
|
||||
y += stepY
|
||||
}
|
||||
return if (count == 0) 0.0 else sum / count
|
||||
}
|
||||
|
||||
private fun scaleToWidth(source: Bitmap, width: Int): Bitmap {
|
||||
if (source.width <= width) return source
|
||||
val height = (source.height.toFloat() * width / source.width).toInt().coerceAtLeast(1)
|
||||
@@ -103,7 +159,7 @@ object ThumbCache {
|
||||
}
|
||||
|
||||
private fun fileFor(context: Context, item: MediaItem): File =
|
||||
File(File(context.filesDir, "thumbs"), item.key + ".jpg")
|
||||
File(File(context.filesDir, "thumbs"), item.key + "_v2.jpg")
|
||||
|
||||
private fun readDisk(context: Context, item: MediaItem): Bitmap? {
|
||||
val file = fileFor(context, item)
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
package dev.lotherk.kidstube.stats
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import android.database.sqlite.SQLiteOpenHelper
|
||||
import android.net.Uri
|
||||
import dev.lotherk.kidstube.data.MediaItem
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Local watch history. One row per playback session, no network, no account.
|
||||
*
|
||||
* Everything the parent view shows is a query over this table, and the same data
|
||||
* is mirrored to a JSON file under the app's external files dir so another
|
||||
* process can read it with `adb pull`.
|
||||
*/
|
||||
class StatsDb(context: Context) :
|
||||
SQLiteOpenHelper(context.applicationContext, NAME, null, VERSION) {
|
||||
|
||||
private val appContext: Context = context.applicationContext
|
||||
|
||||
companion object {
|
||||
private const val NAME = "stats.db"
|
||||
private const val VERSION = 3
|
||||
private const val MIN_SESSION_MS = 1500L
|
||||
}
|
||||
|
||||
override fun onCreate(db: SQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
video_key TEXT NOT NULL,
|
||||
uri TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
folder TEXT NOT NULL,
|
||||
started_at INTEGER NOT NULL,
|
||||
watched_ms INTEGER NOT NULL,
|
||||
completed INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent()
|
||||
)
|
||||
db.execSQL("CREATE INDEX idx_sessions_started ON sessions(started_at)")
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE likes (
|
||||
video_key TEXT PRIMARY KEY,
|
||||
uri TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
folder TEXT NOT NULL,
|
||||
liked_at INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
|
||||
if (oldVersion < 2) {
|
||||
db.execSQL("ALTER TABLE sessions ADD COLUMN uri TEXT NOT NULL DEFAULT ''")
|
||||
}
|
||||
if (oldVersion < 3) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS likes (
|
||||
video_key TEXT PRIMARY KEY,
|
||||
uri TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
folder TEXT NOT NULL,
|
||||
liked_at INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun record(item: MediaItem, startedAt: Long, watchedMs: Long, completed: Boolean) {
|
||||
if (watchedMs < MIN_SESSION_MS) return
|
||||
val values = ContentValues().apply {
|
||||
put("video_key", item.key)
|
||||
put("uri", item.uri.toString())
|
||||
put("title", item.title)
|
||||
put("folder", item.folder)
|
||||
put("started_at", startedAt)
|
||||
put("watched_ms", watchedMs)
|
||||
put("completed", if (completed) 1 else 0)
|
||||
}
|
||||
writableDatabase.insert("sessions", null, values)
|
||||
exportJson()
|
||||
}
|
||||
|
||||
class VideoStat(val title: String, val plays: Int, val watchedMs: Long)
|
||||
|
||||
fun totals(): LongArray {
|
||||
var plays = 0
|
||||
var watched = 0L
|
||||
readableDatabase.rawQuery(
|
||||
"SELECT COUNT(*), COALESCE(SUM(watched_ms),0) FROM sessions", null
|
||||
).use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
plays = c.getInt(0)
|
||||
watched = c.getLong(1)
|
||||
}
|
||||
}
|
||||
var videos = 0
|
||||
readableDatabase.rawQuery(
|
||||
"SELECT COUNT(DISTINCT video_key) FROM sessions", null
|
||||
).use { c -> if (c.moveToFirst()) videos = c.getInt(0) }
|
||||
return longArrayOf(plays.toLong(), watched, videos.toLong())
|
||||
}
|
||||
|
||||
fun topVideos(limit: Int = 15): List<VideoStat> {
|
||||
val out = ArrayList<VideoStat>()
|
||||
readableDatabase.rawQuery(
|
||||
"""
|
||||
SELECT title, COUNT(*) AS plays, SUM(watched_ms) AS ms
|
||||
FROM sessions GROUP BY video_key ORDER BY ms DESC LIMIT ?
|
||||
""".trimIndent(),
|
||||
arrayOf(limit.toString())
|
||||
).use { c ->
|
||||
while (c.moveToNext()) {
|
||||
out.add(VideoStat(c.getString(0), c.getInt(1), c.getLong(2)))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Plays and watch time per day, newest first. */
|
||||
fun perDay(days: Int = 14): List<Triple<String, Int, Long>> {
|
||||
val out = ArrayList<Triple<String, Int, Long>>()
|
||||
val format = SimpleDateFormat("yyyy-MM-dd", Locale.US)
|
||||
readableDatabase.rawQuery(
|
||||
"""
|
||||
SELECT strftime('%Y-%m-%d', started_at/1000, 'unixepoch', 'localtime') AS day,
|
||||
COUNT(*), SUM(watched_ms)
|
||||
FROM sessions GROUP BY day ORDER BY day DESC LIMIT ?
|
||||
""".trimIndent(),
|
||||
arrayOf(days.toString())
|
||||
).use { c ->
|
||||
while (c.moveToNext()) {
|
||||
out.add(Triple(c.getString(0) ?: format.format(Date()), c.getInt(1), c.getLong(2)))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// --- likes: the only thing "Your stuff" shows -------------------------
|
||||
|
||||
fun isLiked(key: String): Boolean {
|
||||
readableDatabase.rawQuery(
|
||||
"SELECT 1 FROM likes WHERE video_key = ? LIMIT 1", arrayOf(key)
|
||||
).use { c -> return c.moveToFirst() }
|
||||
}
|
||||
|
||||
/** Returns the new state. */
|
||||
fun toggleLike(item: MediaItem): Boolean {
|
||||
return if (isLiked(item.key)) {
|
||||
writableDatabase.delete("likes", "video_key = ?", arrayOf(item.key))
|
||||
false
|
||||
} else {
|
||||
val values = ContentValues().apply {
|
||||
put("video_key", item.key)
|
||||
put("uri", item.uri.toString())
|
||||
put("title", item.title)
|
||||
put("folder", item.folder)
|
||||
put("liked_at", System.currentTimeMillis())
|
||||
}
|
||||
writableDatabase.insertWithOnConflict(
|
||||
"likes", null, values, SQLiteDatabase.CONFLICT_REPLACE
|
||||
)
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fun likedKeys(): Set<String> {
|
||||
val out = HashSet<String>()
|
||||
readableDatabase.rawQuery("SELECT video_key FROM likes", null).use { c ->
|
||||
while (c.moveToNext()) out.add(c.getString(0))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun likedItems(): List<MediaItem> {
|
||||
val out = ArrayList<MediaItem>()
|
||||
readableDatabase.rawQuery(
|
||||
"SELECT video_key, uri, title, folder FROM likes ORDER BY liked_at DESC", null
|
||||
).use { c ->
|
||||
while (c.moveToNext()) {
|
||||
out.add(
|
||||
MediaItem(
|
||||
uri = Uri.parse(c.getString(1)),
|
||||
title = c.getString(2),
|
||||
folder = c.getString(3),
|
||||
key = c.getString(0)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Videos watched before, most recent first. */
|
||||
fun watchedItems(limit: Int = 60): List<MediaItem> {
|
||||
val out = ArrayList<MediaItem>()
|
||||
readableDatabase.rawQuery(
|
||||
"""
|
||||
SELECT video_key, uri, title, folder, MAX(started_at) AS last
|
||||
FROM sessions WHERE uri != ''
|
||||
GROUP BY video_key ORDER BY last DESC LIMIT ?
|
||||
""".trimIndent(),
|
||||
arrayOf(limit.toString())
|
||||
).use { c ->
|
||||
while (c.moveToNext()) {
|
||||
val uri = c.getString(1) ?: continue
|
||||
if (uri.isEmpty()) continue
|
||||
out.add(
|
||||
MediaItem(
|
||||
uri = Uri.parse(uri),
|
||||
title = c.getString(2) ?: "",
|
||||
folder = c.getString(3) ?: "",
|
||||
key = c.getString(0) ?: ""
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Mirrors the history to a file another process can pull. */
|
||||
fun exportJson() {
|
||||
try {
|
||||
val dir = appContext.getExternalFilesDir(null) ?: appContext.filesDir
|
||||
val totals = totals()
|
||||
val root = JSONObject().apply {
|
||||
put("updated_at", System.currentTimeMillis())
|
||||
put("plays", totals[0])
|
||||
put("watched_ms", totals[1])
|
||||
put("videos", totals[2])
|
||||
put("top", JSONArray().apply {
|
||||
for (v in topVideos(50)) {
|
||||
put(
|
||||
JSONObject()
|
||||
.put("title", v.title)
|
||||
.put("plays", v.plays)
|
||||
.put("watched_ms", v.watchedMs)
|
||||
)
|
||||
}
|
||||
})
|
||||
put("days", JSONArray().apply {
|
||||
for ((day, plays, ms) in perDay(60)) {
|
||||
put(JSONObject().put("day", day).put("plays", plays).put("watched_ms", ms))
|
||||
}
|
||||
})
|
||||
}
|
||||
File(dir, "stats.json").writeText(root.toString(2))
|
||||
} catch (t: Throwable) {
|
||||
// Export is a convenience; the SQLite rows stay authoritative.
|
||||
}
|
||||
}
|
||||
|
||||
fun formatMs(ms: Long): String {
|
||||
val totalMinutes = ms / 60000
|
||||
val hours = totalMinutes / 60
|
||||
val minutes = totalMinutes % 60
|
||||
return if (hours > 0) "${hours}h ${minutes}m" else "${minutes}m"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package dev.lotherk.kidstube.ui
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import android.widget.TextView
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import dev.lotherk.kidstube.R
|
||||
import dev.lotherk.kidstube.databinding.ItemChipBinding
|
||||
|
||||
/**
|
||||
* Category pills: "All" plus one per folder. Single selection, white capsule for
|
||||
* the active one and a dark capsule for the rest, as in the iPad app.
|
||||
*/
|
||||
class ChipAdapter(
|
||||
private val labels: List<String>,
|
||||
private val onSelect: (Int) -> Unit
|
||||
) : RecyclerView.Adapter<ChipAdapter.Holder>() {
|
||||
|
||||
private var selected = 0
|
||||
|
||||
fun select(index: Int) {
|
||||
if (index == selected) return
|
||||
val previous = selected
|
||||
selected = index
|
||||
notifyItemChanged(previous)
|
||||
notifyItemChanged(selected)
|
||||
}
|
||||
|
||||
class Holder(val binding: ItemChipBinding) : RecyclerView.ViewHolder(binding.root) {
|
||||
val label: TextView = binding.root
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
|
||||
val binding = ItemChipBinding.inflate(LayoutInflater.from(parent.context), parent, false)
|
||||
return Holder(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: Holder, position: Int) {
|
||||
val context = holder.itemView.context
|
||||
holder.label.text = labels[position]
|
||||
val isSelected = position == selected
|
||||
holder.label.setBackgroundResource(
|
||||
if (isSelected) R.drawable.bg_chip_active else R.drawable.bg_chip
|
||||
)
|
||||
holder.label.setTextColor(
|
||||
ContextCompat.getColor(
|
||||
context,
|
||||
if (isSelected) R.color.kt_chip_text_active else R.color.kt_text
|
||||
)
|
||||
)
|
||||
holder.itemView.setOnClickListener { onSelect(position) }
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int = labels.size
|
||||
}
|
||||
@@ -17,20 +17,27 @@ import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import dev.lotherk.kidstube.R
|
||||
import dev.lotherk.kidstube.data.Library
|
||||
import dev.lotherk.kidstube.data.MediaItem
|
||||
import dev.lotherk.kidstube.stats.StatsDb
|
||||
import dev.lotherk.kidstube.databinding.ActivityMainBinding
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.random.Random
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var binding: ActivityMainBinding
|
||||
private val sectionAdapter = SectionAdapter { openPlayer(it) }
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
|
||||
private lateinit var gridAdapter: VideoAdapter
|
||||
private lateinit var resultsAdapter: VideoAdapter
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private lateinit var stats: StatsDb
|
||||
|
||||
private var all: List<MediaItem> = emptyList()
|
||||
private var folders: List<String> = emptyList()
|
||||
private var selectedFolder: String? = null
|
||||
private var scanning = false
|
||||
private var activeTab = 0
|
||||
private var currentTileWidth = 0
|
||||
|
||||
private val openFolder =
|
||||
registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
|
||||
@@ -47,19 +54,25 @@ class MainActivity : AppCompatActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityMainBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
stats = StatsDb(this)
|
||||
|
||||
binding.rows.layoutManager = LinearLayoutManager(this)
|
||||
binding.rows.adapter = sectionAdapter
|
||||
binding.grid.layoutManager = GridLayoutManager(this, columns())
|
||||
gridAdapter = VideoAdapter { openPlayer(it) }
|
||||
binding.grid.adapter = gridAdapter
|
||||
|
||||
resultsAdapter = VideoAdapter(VideoAdapter.Mode.GRID) { openPlayer(it) }
|
||||
binding.results.layoutManager = GridLayoutManager(this, 2)
|
||||
binding.results.layoutManager = GridLayoutManager(this, columns())
|
||||
resultsAdapter = VideoAdapter { openPlayer(it) }
|
||||
binding.results.adapter = resultsAdapter
|
||||
|
||||
binding.chips.layoutManager =
|
||||
LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
|
||||
|
||||
binding.btnPick.setOnClickListener { pickFolder() }
|
||||
binding.btnTopSearch.setOnClickListener { selectTab(1) }
|
||||
binding.avatar.setOnClickListener { parentGate() }
|
||||
binding.btnShield.setOnClickListener { parentGate() }
|
||||
binding.btnGear.setOnClickListener { pickFolder() }
|
||||
binding.tabHome.setOnClickListener { selectTab(0) }
|
||||
binding.tabSearch.setOnClickListener { selectTab(1) }
|
||||
binding.tabStuff.setOnClickListener { selectTab(2) }
|
||||
binding.tabProfile.setOnClickListener { parentGate() }
|
||||
binding.btnSearchClose.setOnClickListener { selectTab(0) }
|
||||
|
||||
@@ -69,10 +82,46 @@ class MainActivity : AppCompatActivity() {
|
||||
override fun afterTextChanged(s: Editable?) = applyFilter(s?.toString().orEmpty())
|
||||
})
|
||||
|
||||
binding.grid.post { layoutTiles() }
|
||||
|
||||
selectTab(0)
|
||||
start()
|
||||
}
|
||||
|
||||
/** Always three across, so the overview reads as three rows of three. */
|
||||
private fun columns(): Int = 3
|
||||
|
||||
/**
|
||||
* Tiles are sized from the available height so exactly three rows fit; the
|
||||
* leftover width becomes the gaps (see [TileSpacing]).
|
||||
*/
|
||||
private fun layoutTiles() {
|
||||
// Always measure the home grid: the other tabs have a shorter content
|
||||
// area (search bar) and must not shrink the tiles for everybody.
|
||||
val source = binding.grid
|
||||
val width = source.width
|
||||
val height = source.height
|
||||
if (width <= 0 || height <= 0) return
|
||||
val density = resources.displayMetrics.density
|
||||
val rowGap = (8 * density).roundToInt()
|
||||
val cell = width / columns()
|
||||
// Every row carries a bottom gap, including the last, and the list has
|
||||
// its own padding — both must come off before dividing by three, or the
|
||||
// third row ends up under the tab bar.
|
||||
val usable = height - source.paddingTop - source.paddingBottom - 3 * rowGap
|
||||
val byHeight = ((usable / 3.0) * 16.0 / 9.0).toInt()
|
||||
val tile = min(cell, byHeight).coerceAtLeast((120 * density).roundToInt())
|
||||
if (tile <= 0 || tile == currentTileWidth) return
|
||||
currentTileWidth = tile
|
||||
|
||||
for (list in listOf(binding.grid, binding.results)) {
|
||||
while (list.itemDecorationCount > 0) list.removeItemDecorationAt(0)
|
||||
list.addItemDecoration(TileSpacing(columns(), tile, rowGap))
|
||||
}
|
||||
gridAdapter.tileWidth = tile
|
||||
resultsAdapter.tileWidth = tile
|
||||
}
|
||||
|
||||
/** Default folder needs a read permission once; a picked SAF tree does not. */
|
||||
private fun start() {
|
||||
if (Library.treeUri(this) == null && !Library.hasReadPermission(this)) {
|
||||
@@ -92,7 +141,7 @@ class MainActivity : AppCompatActivity() {
|
||||
val hasSource = Library.treeUri(this) != null || Library.hasReadPermission(this)
|
||||
if (!hasSource) {
|
||||
all = emptyList()
|
||||
sectionAdapter.submit(emptyList())
|
||||
gridAdapter.submit(emptyList())
|
||||
refreshEmptyState()
|
||||
return
|
||||
}
|
||||
@@ -102,26 +151,39 @@ class MainActivity : AppCompatActivity() {
|
||||
runOnUiThread {
|
||||
scanning = false
|
||||
all = items
|
||||
buildSections(items)
|
||||
applyFilter(binding.searchInput.text?.toString().orEmpty())
|
||||
buildChips(items)
|
||||
applyFolderFilter()
|
||||
if (activeTab == 1) applyFilter(binding.searchInput.text?.toString().orEmpty())
|
||||
if (activeTab == 2) resultsAdapter.submit(stats.likedItems(), stats.likedKeys())
|
||||
refreshEmptyState()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildSections(items: List<MediaItem>) {
|
||||
if (items.isEmpty()) {
|
||||
sectionAdapter.submit(emptyList())
|
||||
return
|
||||
/** "All" plus one pill per folder, as the reference shows. */
|
||||
private fun buildChips(items: List<MediaItem>) {
|
||||
folders = items.groupBy { it.folder }.keys.toList()
|
||||
if (selectedFolder != null && selectedFolder !in folders) selectedFolder = null
|
||||
|
||||
val labels = ArrayList<String>(folders.size + 1)
|
||||
labels.add(getString(R.string.chip_all))
|
||||
labels.addAll(folders)
|
||||
|
||||
val adapter = ChipAdapter(labels) { index ->
|
||||
selectedFolder = if (index == 0) null else folders.getOrNull(index - 1)
|
||||
binding.chips.adapter?.let { (it as ChipAdapter).select(index) }
|
||||
applyFolderFilter()
|
||||
}
|
||||
val sections = ArrayList<SectionAdapter.Section>()
|
||||
sections.add(SectionAdapter.Section(getString(R.string.shelf_recent), items.take(8), true))
|
||||
for ((folder, list) in items.groupBy { it.folder }) {
|
||||
if (list.size < 2 || sections.size >= 5) continue
|
||||
sections.add(SectionAdapter.Section(folder, list.take(20), false))
|
||||
}
|
||||
sections.add(SectionAdapter.Section(getString(R.string.shelf_all), items.take(30), false))
|
||||
sectionAdapter.submit(sections)
|
||||
binding.chips.adapter = adapter
|
||||
val active = selectedFolder?.let { folders.indexOf(it) + 1 } ?: 0
|
||||
if (active > 0) adapter.select(active)
|
||||
}
|
||||
|
||||
private fun applyFolderFilter() {
|
||||
val folder = selectedFolder
|
||||
val list = if (folder == null) all else all.filter { it.folder == folder }
|
||||
gridAdapter.submit(list, stats.likedKeys())
|
||||
refreshEmptyState()
|
||||
}
|
||||
|
||||
private fun applyFilter(query: String) {
|
||||
@@ -129,35 +191,53 @@ class MainActivity : AppCompatActivity() {
|
||||
val list = if (q.isEmpty()) all else all.filter {
|
||||
it.title.lowercase().contains(q) || it.folder.lowercase().contains(q)
|
||||
}
|
||||
resultsAdapter.submit(list)
|
||||
resultsAdapter.submit(list, stats.likedKeys())
|
||||
}
|
||||
|
||||
private fun selectTab(index: Int) {
|
||||
activeTab = index
|
||||
val active = ContextCompat.getColor(this, R.color.kt_red)
|
||||
val active = ContextCompat.getColor(this, R.color.kt_text)
|
||||
val idle = ContextCompat.getColor(this, R.color.kt_tab_idle)
|
||||
|
||||
binding.tabHomeIcon.imageTintList = ColorStateList.valueOf(if (index == 0) active else idle)
|
||||
binding.tabHomeLabel.setTextColor(if (index == 0) active else idle)
|
||||
binding.tabSearchIcon.imageTintList = ColorStateList.valueOf(if (index == 1) active else idle)
|
||||
binding.tabSearchLabel.setTextColor(if (index == 1) active else idle)
|
||||
binding.tabStuffIcon.imageTintList = ColorStateList.valueOf(if (index == 2) active else idle)
|
||||
binding.tabStuffLabel.setTextColor(if (index == 2) active else idle)
|
||||
binding.tabProfileIcon.imageTintList = ColorStateList.valueOf(idle)
|
||||
binding.tabProfileLabel.setTextColor(idle)
|
||||
|
||||
binding.searchBar.visibility = if (index == 1) View.VISIBLE else View.GONE
|
||||
binding.results.visibility = if (index == 1) View.VISIBLE else View.GONE
|
||||
binding.rows.visibility = if (index == 0) View.VISIBLE else View.GONE
|
||||
binding.results.visibility = if (index in 1..2) View.VISIBLE else View.GONE
|
||||
binding.grid.visibility = if (index == 0) View.VISIBLE else View.GONE
|
||||
binding.chips.visibility = if (index == 0) View.VISIBLE else View.GONE
|
||||
|
||||
if (index == 1) {
|
||||
binding.searchInput.requestFocus()
|
||||
} else {
|
||||
binding.searchInput.setText("")
|
||||
when (index) {
|
||||
1 -> binding.searchInput.requestFocus()
|
||||
2 -> resultsAdapter.submit(stats.likedItems(), stats.likedKeys())
|
||||
else -> binding.searchInput.setText("")
|
||||
}
|
||||
if (index != 1) binding.searchInput.setText("")
|
||||
refreshEmptyState()
|
||||
binding.grid.post { layoutTiles() }
|
||||
}
|
||||
|
||||
private fun refreshEmptyState() {
|
||||
val show = all.isEmpty() && activeTab == 0
|
||||
binding.empty.visibility = if (show) View.VISIBLE else View.GONE
|
||||
val homeEmpty = all.isEmpty() && activeTab == 0
|
||||
binding.empty.visibility = if (homeEmpty) View.VISIBLE else View.GONE
|
||||
|
||||
// Search and "Your stuff" must say something when their list is empty,
|
||||
// otherwise the tab looks broken (grid hidden, nothing drawn).
|
||||
val listEmpty = when (activeTab) {
|
||||
1 -> resultsAdapter.itemCount == 0
|
||||
2 -> resultsAdapter.itemCount == 0
|
||||
else -> false
|
||||
}
|
||||
binding.resultsEmpty.text =
|
||||
getString(if (activeTab == 2) R.string.likes_empty else R.string.search_empty)
|
||||
binding.resultsEmpty.visibility =
|
||||
if (listEmpty && resultsAdapter.itemCount == 0) View.VISIBLE else View.GONE
|
||||
}
|
||||
|
||||
private fun pickFolder() {
|
||||
@@ -203,6 +283,9 @@ class MainActivity : AppCompatActivity() {
|
||||
d.dismiss()
|
||||
pickFolder()
|
||||
}
|
||||
.setNeutralButton(R.string.stats_open) { _, _ ->
|
||||
startActivity(Intent(this, StatsActivity::class.java))
|
||||
}
|
||||
.setNegativeButton(R.string.ok, null)
|
||||
.show()
|
||||
}
|
||||
@@ -212,6 +295,8 @@ class MainActivity : AppCompatActivity() {
|
||||
Intent(this, PlayerActivity::class.java)
|
||||
.putExtra(PlayerActivity.EXTRA_URI, item.uri.toString())
|
||||
.putExtra(PlayerActivity.EXTRA_TITLE, item.title)
|
||||
.putExtra(PlayerActivity.EXTRA_FOLDER, item.folder)
|
||||
.putExtra(PlayerActivity.EXTRA_KEY, item.key)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
import android.view.WindowInsetsController
|
||||
@@ -12,8 +13,14 @@ import android.view.WindowManager
|
||||
import android.widget.SeekBar
|
||||
import android.widget.Toast
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import dev.lotherk.kidstube.R
|
||||
import dev.lotherk.kidstube.data.Library
|
||||
import dev.lotherk.kidstube.data.MediaItem
|
||||
import dev.lotherk.kidstube.data.Series
|
||||
import dev.lotherk.kidstube.stats.StatsDb
|
||||
import dev.lotherk.kidstube.databinding.ActivityPlayerBinding
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/** Fullscreen local playback. No pre-roll, no controls until a tap. */
|
||||
class PlayerActivity : AppCompatActivity() {
|
||||
@@ -21,12 +28,24 @@ class PlayerActivity : AppCompatActivity() {
|
||||
companion object {
|
||||
const val EXTRA_URI = "uri"
|
||||
const val EXTRA_TITLE = "title"
|
||||
const val EXTRA_FOLDER = "folder"
|
||||
const val EXTRA_KEY = "key"
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivityPlayerBinding
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var chromeVisible = true
|
||||
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private lateinit var suggestions: SuggestionAdapter
|
||||
private var pool: List<MediaItem> = emptyList()
|
||||
private lateinit var stats: StatsDb
|
||||
private var item: MediaItem? = null
|
||||
private var segmentStart = 0L
|
||||
private var resumedAt = 0L
|
||||
private var watchedMs = 0L
|
||||
private var prepared = false
|
||||
|
||||
private val hideChrome = Runnable { setChrome(false) }
|
||||
private val ticker = object : Runnable {
|
||||
override fun run() {
|
||||
@@ -46,9 +65,18 @@ class PlayerActivity : AppCompatActivity() {
|
||||
return
|
||||
}
|
||||
|
||||
stats = StatsDb(this)
|
||||
item = MediaItem(
|
||||
uri = Uri.parse(rawUri),
|
||||
title = intent.getStringExtra(EXTRA_TITLE).orEmpty(),
|
||||
folder = intent.getStringExtra(EXTRA_FOLDER).orEmpty(),
|
||||
key = intent.getStringExtra(EXTRA_KEY) ?: rawUri
|
||||
)
|
||||
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
binding.title.text = intent.getStringExtra(EXTRA_TITLE).orEmpty()
|
||||
binding.btnBack.setOnClickListener { finish() }
|
||||
binding.btnLike.setOnClickListener { toggleLike() }
|
||||
binding.tapCatcher.setOnClickListener { setChrome(!chromeVisible) }
|
||||
binding.chrome.setOnClickListener { setChrome(!chromeVisible) }
|
||||
|
||||
@@ -67,20 +95,120 @@ class PlayerActivity : AppCompatActivity() {
|
||||
}
|
||||
})
|
||||
|
||||
binding.video.setVideoURI(Uri.parse(rawUri))
|
||||
suggestions = SuggestionAdapter { play(it) }
|
||||
binding.suggestions.layoutManager =
|
||||
LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
|
||||
binding.suggestions.adapter = suggestions
|
||||
|
||||
binding.video.setOnPreparedListener { player ->
|
||||
binding.spinner.visibility = View.GONE
|
||||
player.isLooping = true
|
||||
prepared = true
|
||||
segmentStart = System.currentTimeMillis()
|
||||
player.isLooping = false
|
||||
binding.seek.max = if (player.duration > 0) player.duration else 1
|
||||
binding.video.start()
|
||||
handler.post(ticker)
|
||||
setChrome(true)
|
||||
}
|
||||
// A finished video rolls into another one, like the iOS app.
|
||||
binding.video.setOnCompletionListener {
|
||||
commitWatch()
|
||||
recordSegment()
|
||||
val next = pool.firstOrNull { it.uri != item?.uri }
|
||||
if (next != null) play(next) else finish()
|
||||
}
|
||||
|
||||
binding.video.setOnErrorListener { _, _, _ ->
|
||||
binding.spinner.visibility = View.GONE
|
||||
Toast.makeText(this, R.string.error_play, Toast.LENGTH_LONG).show()
|
||||
true
|
||||
}
|
||||
|
||||
play(item ?: return)
|
||||
}
|
||||
|
||||
/** Switches the running video and offers four others while chrome is up. */
|
||||
private fun play(next: MediaItem) {
|
||||
if (item != null && prepared) recordSegment()
|
||||
prepared = false
|
||||
item = next
|
||||
binding.title.text = next.title
|
||||
updateLikeIcon(stats.isLiked(next.key))
|
||||
binding.spinner.visibility = View.VISIBLE
|
||||
setChrome(true)
|
||||
binding.video.setVideoURI(next.uri)
|
||||
loadSuggestions(next)
|
||||
}
|
||||
|
||||
/** The heart in the corner; "Your stuff" shows exactly these videos. */
|
||||
private fun toggleLike() {
|
||||
val current = item ?: return
|
||||
val liked = stats.toggleLike(current)
|
||||
updateLikeIcon(liked)
|
||||
}
|
||||
|
||||
private fun updateLikeIcon(liked: Boolean) {
|
||||
binding.btnLike.imageTintList = android.content.res.ColorStateList.valueOf(
|
||||
androidx.core.content.ContextCompat.getColor(
|
||||
this,
|
||||
if (liked) dev.lotherk.kidstube.R.color.kt_red else android.R.color.white
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun loadSuggestions(current: MediaItem) {
|
||||
executor.execute {
|
||||
val scan = Library.scan(this)
|
||||
val others = Series.suggestionsFor(scan, current, 4)
|
||||
pool = others
|
||||
runOnUiThread {
|
||||
suggestions.submit(others)
|
||||
binding.suggestions.visibility = if (others.isEmpty()) View.GONE else View.VISIBLE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
// The activity survives rotation, so the tile widths have to be rebuilt
|
||||
// by hand or the strip keeps the old (wrong) size.
|
||||
val current = item ?: return
|
||||
suggestions = SuggestionAdapter { play(it) }
|
||||
binding.suggestions.adapter = suggestions
|
||||
loadSuggestions(current)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
resumedAt = SystemClock.elapsedRealtime()
|
||||
if (segmentStart == 0L) segmentStart = System.currentTimeMillis()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
commitWatch()
|
||||
recordSegment()
|
||||
}
|
||||
|
||||
/** Watches the clock only while this activity is actually visible. */
|
||||
private fun commitWatch() {
|
||||
if (resumedAt > 0L) {
|
||||
watchedMs += SystemClock.elapsedRealtime() - resumedAt
|
||||
resumedAt = 0L
|
||||
}
|
||||
}
|
||||
|
||||
/** One row per visible segment, so a resumed app counts as a new play. */
|
||||
private fun recordSegment() {
|
||||
val current = item ?: return
|
||||
if (prepared && watchedMs >= 1500L) {
|
||||
val duration = binding.video.duration
|
||||
val position = binding.video.currentPosition
|
||||
val completed = duration > 0 && position >= duration - 3000
|
||||
stats.record(current, segmentStart, watchedMs, completed)
|
||||
}
|
||||
watchedMs = 0L
|
||||
segmentStart = 0L
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
package dev.lotherk.kidstube.ui
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.LinearSnapHelper
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import dev.lotherk.kidstube.data.MediaItem
|
||||
import dev.lotherk.kidstube.databinding.ItemSectionBinding
|
||||
|
||||
/** Vertical list of shelves; each shelf is its own horizontal RecyclerView. */
|
||||
class SectionAdapter(
|
||||
private val onTap: (MediaItem) -> Unit
|
||||
) : RecyclerView.Adapter<SectionAdapter.Holder>() {
|
||||
|
||||
class Section(val title: String, val items: List<MediaItem>, val hero: Boolean)
|
||||
|
||||
private val sections = ArrayList<Section>()
|
||||
|
||||
fun submit(list: List<Section>) {
|
||||
sections.clear()
|
||||
sections.addAll(list)
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
class Holder(val binding: ItemSectionBinding) : RecyclerView.ViewHolder(binding.root) {
|
||||
var snap: LinearSnapHelper? = null
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
|
||||
val binding = ItemSectionBinding.inflate(
|
||||
LayoutInflater.from(parent.context), parent, false
|
||||
)
|
||||
return Holder(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: Holder, position: Int) {
|
||||
val section = sections[position]
|
||||
val binding = holder.binding
|
||||
binding.sectionTitle.text = section.title
|
||||
|
||||
val row = binding.row
|
||||
val context = row.context
|
||||
if (row.layoutManager == null) {
|
||||
row.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
|
||||
}
|
||||
val adapter = VideoAdapter(
|
||||
if (section.hero) VideoAdapter.Mode.HERO else VideoAdapter.Mode.CAROUSEL,
|
||||
onTap
|
||||
)
|
||||
row.adapter = adapter
|
||||
adapter.submit(section.items)
|
||||
|
||||
// The wide top shelf snaps page by page like the iOS carousel; the
|
||||
// smaller shelves scroll freely.
|
||||
if (section.hero && holder.snap == null) {
|
||||
holder.snap = LinearSnapHelper().apply { attachToRecyclerView(row) }
|
||||
} else if (!section.hero && holder.snap != null) {
|
||||
holder.snap?.attachToRecyclerView(null)
|
||||
holder.snap = null
|
||||
}
|
||||
}
|
||||
|
||||
override fun onViewRecycled(holder: Holder) {
|
||||
holder.snap?.attachToRecyclerView(null)
|
||||
holder.snap = null
|
||||
super.onViewRecycled(holder)
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int = sections.size
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package dev.lotherk.kidstube.ui
|
||||
|
||||
import android.os.Bundle
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import dev.lotherk.kidstube.R
|
||||
import dev.lotherk.kidstube.databinding.ActivityStatsBinding
|
||||
import dev.lotherk.kidstube.stats.StatsDb
|
||||
import java.io.File
|
||||
|
||||
/** Parent-facing view over the local watch history. */
|
||||
class StatsActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var binding: ActivityStatsBinding
|
||||
private lateinit var stats: StatsDb
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityStatsBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
stats = StatsDb(this)
|
||||
|
||||
val totals = stats.totals()
|
||||
binding.statPlays.text = totals[0].toString()
|
||||
binding.statTime.text = stats.formatMs(totals[1])
|
||||
binding.statVideos.text = totals[2].toString()
|
||||
|
||||
val dim = ContextCompat.getColor(this, R.color.kt_text_sub)
|
||||
val bright = ContextCompat.getColor(this, R.color.kt_text)
|
||||
|
||||
for (video in stats.topVideos()) {
|
||||
val row = TextView(this).apply {
|
||||
text = "${video.plays}x ${stats.formatMs(video.watchedMs)} ${video.title}"
|
||||
setTextColor(bright)
|
||||
textSize = 13f
|
||||
maxLines = 2
|
||||
setPadding(0, 12, 0, 12)
|
||||
}
|
||||
binding.topList.addView(row)
|
||||
}
|
||||
if (binding.topList.childCount == 0) {
|
||||
binding.topList.addView(note(getString(R.string.stats_empty)))
|
||||
}
|
||||
|
||||
for ((day, plays, ms) in stats.perDay()) {
|
||||
val row = TextView(this).apply {
|
||||
text = "$day ${plays}x ${stats.formatMs(ms)}"
|
||||
setTextColor(dim)
|
||||
textSize = 13f
|
||||
setPadding(0, 8, 0, 8)
|
||||
}
|
||||
binding.dayList.addView(row)
|
||||
}
|
||||
|
||||
val dir: File = getExternalFilesDir(null) ?: filesDir
|
||||
binding.statsPath.text = getString(R.string.stats_export, File(dir, "stats.json").absolutePath)
|
||||
}
|
||||
|
||||
private fun note(text: String): TextView = TextView(this).apply {
|
||||
this.text = text
|
||||
setTextColor(ContextCompat.getColor(this@StatsActivity, R.color.kt_text_sub))
|
||||
textSize = 13f
|
||||
setPadding(0, 8, 0, 8)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package dev.lotherk.kidstube.ui
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.TextView
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import dev.lotherk.kidstube.R
|
||||
import dev.lotherk.kidstube.data.MediaItem
|
||||
import dev.lotherk.kidstube.media.ThumbCache
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** The four "more videos" tiles shown while the player chrome is visible. */
|
||||
class SuggestionAdapter(
|
||||
private val onTap: (MediaItem) -> Unit
|
||||
) : RecyclerView.Adapter<SuggestionAdapter.Holder>() {
|
||||
|
||||
private val items = ArrayList<MediaItem>()
|
||||
|
||||
fun submit(list: List<MediaItem>) {
|
||||
items.clear()
|
||||
items.addAll(list)
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
class Holder(view: View) : RecyclerView.ViewHolder(view) {
|
||||
val thumb: ThumbView = view.findViewById(R.id.thumb)
|
||||
val title: TextView = view.findViewById(R.id.title)
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
|
||||
val view = LayoutInflater.from(parent.context)
|
||||
.inflate(R.layout.item_suggestion, parent, false)
|
||||
// Four tiles side by side, never a 2x2 block: the strip must stay low.
|
||||
val density = parent.resources.displayMetrics.density
|
||||
val margins = (32 * density).roundToInt() + 3 * (8 * density).roundToInt()
|
||||
val params = view.layoutParams as RecyclerView.LayoutParams
|
||||
params.width = ((parent.resources.displayMetrics.widthPixels - margins) / 4)
|
||||
.coerceAtLeast((72 * density).roundToInt())
|
||||
params.marginEnd = (8 * density).roundToInt()
|
||||
view.layoutParams = params
|
||||
return Holder(view)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: Holder, position: Int) {
|
||||
val item = items[position]
|
||||
holder.title.text = item.title
|
||||
ThumbCache.load(holder.itemView.context, item, holder.thumb) { bitmap, label ->
|
||||
holder.thumb.setThumb(bitmap, label)
|
||||
}
|
||||
holder.itemView.setOnClickListener {
|
||||
val current = holder.bindingAdapterPosition
|
||||
if (current != RecyclerView.NO_POSITION && current < items.size) onTap(items[current])
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int = items.size
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dev.lotherk.kidstube.ui
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.view.View
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
|
||||
/**
|
||||
* Centers every tile inside its grid cell and adds the row gap.
|
||||
*
|
||||
* GridLayoutManager gives each child its cell's width, but the tiles are sized
|
||||
* from the available height so three rows fit — they end up narrower than the
|
||||
* cell and must be pulled to the middle.
|
||||
*/
|
||||
class TileSpacing(
|
||||
private val spans: Int,
|
||||
private val tileWidth: Int,
|
||||
private val rowGap: Int
|
||||
) : RecyclerView.ItemDecoration() {
|
||||
|
||||
override fun getItemOffsets(
|
||||
outRect: Rect,
|
||||
view: View,
|
||||
parent: RecyclerView,
|
||||
state: RecyclerView.State
|
||||
) {
|
||||
val cell = parent.width / spans
|
||||
val side = ((cell - tileWidth) / 2).coerceAtLeast(0)
|
||||
outRect.left = side
|
||||
outRect.right = side
|
||||
outRect.bottom = rowGap
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package dev.lotherk.kidstube.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.LinearGradient
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import android.os.Build
|
||||
import android.text.Layout
|
||||
import android.text.StaticLayout
|
||||
import android.text.TextPaint
|
||||
import android.text.TextUtils
|
||||
import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import androidx.core.content.ContextCompat
|
||||
import dev.lotherk.kidstube.R
|
||||
import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* One 16:9 tile with everything inside it: rounded corners, duration pill and a
|
||||
* two-line title over a bottom scrim. Keeping the label inside the bitmap is
|
||||
* what lets three rows fit on a landscape screen.
|
||||
*/
|
||||
class TileView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
defStyle: Int = 0
|
||||
) : View(context, attrs, defStyle) {
|
||||
|
||||
private val density = resources.displayMetrics.density
|
||||
private val radiusPx = 12f * density
|
||||
private val pillMargin = 6f * density
|
||||
private val pillPadH = 5f * density
|
||||
private val pillPadV = 2f * density
|
||||
private val textPad = 8f * density
|
||||
private val scrimHeight = 34f * density
|
||||
|
||||
private val bitmapPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = ContextCompat.getColor(context, R.color.kt_placeholder)
|
||||
}
|
||||
private val pillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = ContextCompat.getColor(context, R.color.kt_pill)
|
||||
}
|
||||
private val pillTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.WHITE
|
||||
textSize = 10f * density
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
}
|
||||
private val titlePaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.WHITE
|
||||
textSize = 12f * density
|
||||
typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
|
||||
}
|
||||
private val heartPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = ContextCompat.getColor(context, R.color.kt_red)
|
||||
}
|
||||
|
||||
private val clip = Path()
|
||||
private val scaleMatrix = Matrix()
|
||||
|
||||
private var thumb: Bitmap? = null
|
||||
private var duration: String? = null
|
||||
private var title: CharSequence? = null
|
||||
private var liked = false
|
||||
|
||||
private val scrimPaint = Paint()
|
||||
private var scrimFor = 0
|
||||
|
||||
private var layout: StaticLayout? = null
|
||||
private var layoutFor: String? = null
|
||||
private var layoutWidth = 0
|
||||
|
||||
fun bind(bitmap: Bitmap?, label: String?, text: CharSequence?, isLiked: Boolean) {
|
||||
thumb = bitmap
|
||||
duration = label
|
||||
title = text
|
||||
liked = isLiked
|
||||
layout = null
|
||||
contentDescription = text
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
val width = MeasureSpec.getSize(widthMeasureSpec)
|
||||
val height = if (width > 0) (width * 9f / 16f).roundToInt() else 0
|
||||
setMeasuredDimension(width, height)
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val w = width.toFloat()
|
||||
val h = height.toFloat()
|
||||
if (w <= 0f || h <= 0f) return
|
||||
|
||||
clip.reset()
|
||||
clip.addRoundRect(0f, 0f, w, h, radiusPx, radiusPx, Path.Direction.CW)
|
||||
canvas.save()
|
||||
canvas.clipPath(clip)
|
||||
|
||||
val bmp = thumb
|
||||
if (bmp == null || bmp.isRecycled) {
|
||||
canvas.drawRect(0f, 0f, w, h, fillPaint)
|
||||
} else {
|
||||
val scale = max(w / bmp.width, h / bmp.height)
|
||||
scaleMatrix.reset()
|
||||
scaleMatrix.setScale(scale, scale)
|
||||
scaleMatrix.postTranslate((w - bmp.width * scale) / 2f, (h - bmp.height * scale) / 2f)
|
||||
canvas.drawBitmap(bmp, scaleMatrix, bitmapPaint)
|
||||
}
|
||||
|
||||
val text = layoutFor(w, title)
|
||||
if (text != null) {
|
||||
val heightKey = height
|
||||
if (scrimFor != heightKey) {
|
||||
scrimPaint.shader = LinearGradient(
|
||||
0f, h - scrimHeight, 0f, h,
|
||||
intArrayOf(0x00000000, 0xB3000000.toInt()),
|
||||
null, Shader.TileMode.CLAMP
|
||||
)
|
||||
scrimFor = heightKey
|
||||
}
|
||||
canvas.drawRect(0f, h - scrimHeight, w, h, scrimPaint)
|
||||
canvas.save()
|
||||
canvas.translate(textPad, h - text.height.toFloat() - textPad * 0.5f)
|
||||
text.draw(canvas)
|
||||
canvas.restore()
|
||||
}
|
||||
canvas.restore()
|
||||
|
||||
duration?.let { drawPill(canvas, it, w) }
|
||||
if (liked) drawHeart(canvas, w)
|
||||
}
|
||||
|
||||
private fun layoutFor(width: Float, text: CharSequence?): StaticLayout? {
|
||||
if (text.isNullOrEmpty()) return null
|
||||
val available = (width - 2 * textPad).roundToInt()
|
||||
if (available <= 0) return null
|
||||
if (layout != null && layoutFor == text.toString() && layoutWidth == available) {
|
||||
return layout
|
||||
}
|
||||
val ellipsized = TextUtils.ellipsize(text, titlePaint, available.toFloat(), TextUtils.TruncateAt.END)
|
||||
?: text
|
||||
val built = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
StaticLayout.Builder.obtain(ellipsized, 0, ellipsized.length, titlePaint, available)
|
||||
.setMaxLines(2)
|
||||
.setEllipsize(TextUtils.TruncateAt.END)
|
||||
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
|
||||
.build()
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
StaticLayout(
|
||||
ellipsized, titlePaint, available, Layout.Alignment.ALIGN_NORMAL,
|
||||
1f, 0f, false
|
||||
)
|
||||
}
|
||||
layout = built
|
||||
layoutFor = text.toString()
|
||||
layoutWidth = available
|
||||
return built
|
||||
}
|
||||
|
||||
private fun drawPill(canvas: Canvas, label: String, w: Float) {
|
||||
val textWidth = pillTextPaint.measureText(label)
|
||||
val pillH = pillTextPaint.textSize + 2 * pillPadV
|
||||
val pillW = textWidth + 2 * pillPadH
|
||||
val left = w - pillMargin - pillW
|
||||
val top = pillMargin
|
||||
val r = pillH / 2f
|
||||
canvas.drawRoundRect(left, top, left + pillW, top + pillH, r, r, pillPaint)
|
||||
val baseline = top + pillH / 2f - (pillTextPaint.descent() + pillTextPaint.ascent()) / 2f
|
||||
canvas.drawText(label, left + pillPadH, baseline, pillTextPaint)
|
||||
}
|
||||
|
||||
/** Small filled heart in the top-left corner marks a liked video. */
|
||||
private val heartPath = Path()
|
||||
|
||||
private fun drawHeart(canvas: Canvas, w: Float) {
|
||||
if (heartPath.isEmpty) {
|
||||
val cx = pillMargin + 7f * density
|
||||
val cy = pillMargin + 7f * density
|
||||
val r = 6f * density
|
||||
heartPath.moveTo(cx, cy + r)
|
||||
heartPath.cubicTo(cx - r * 1.6f, cy - r * 0.2f, cx - r * 0.6f, cy - r * 1.4f, cx, cy - r * 0.5f)
|
||||
heartPath.cubicTo(cx + r * 0.6f, cy - r * 1.4f, cx + r * 1.6f, cy - r * 0.2f, cx, cy + r)
|
||||
}
|
||||
canvas.drawPath(heartPath, heartPaint)
|
||||
}
|
||||
}
|
||||
@@ -3,61 +3,62 @@ package dev.lotherk.kidstube.ui
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.TextView
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import dev.lotherk.kidstube.R
|
||||
import dev.lotherk.kidstube.data.MediaItem
|
||||
import dev.lotherk.kidstube.media.ThumbCache
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* One tile row. HERO is the wide top shelf, CAROUSEL the smaller ones, GRID the
|
||||
* two-column search result list.
|
||||
* The video grid. Tile size comes from the activity: it is derived from the
|
||||
* available height so exactly three rows fit on the landscape screen. The title
|
||||
* lives inside the tile, there is no text row underneath.
|
||||
*/
|
||||
class VideoAdapter(
|
||||
private val mode: Mode,
|
||||
private val onTap: (MediaItem) -> Unit
|
||||
) : RecyclerView.Adapter<VideoAdapter.Holder>() {
|
||||
|
||||
enum class Mode { HERO, CAROUSEL, GRID }
|
||||
|
||||
private val items = ArrayList<MediaItem>()
|
||||
private var likedKeys: Set<String> = emptySet()
|
||||
|
||||
fun submit(list: List<MediaItem>) {
|
||||
var tileWidth: Int = 0
|
||||
set(value) {
|
||||
if (field == value) return
|
||||
field = value
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
fun submit(list: List<MediaItem>, liked: Set<String> = likedKeys) {
|
||||
items.clear()
|
||||
items.addAll(list)
|
||||
likedKeys = liked
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
class Holder(view: View) : RecyclerView.ViewHolder(view) {
|
||||
val thumb: ThumbView = view.findViewById(R.id.thumb)
|
||||
val title: TextView = view.findViewById(R.id.title)
|
||||
val meta: TextView = view.findViewById(R.id.meta)
|
||||
val tile: TileView = view.findViewById(R.id.tile)
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
|
||||
val layout = if (mode == Mode.HERO) R.layout.item_hero else R.layout.item_video
|
||||
val view = LayoutInflater.from(parent.context).inflate(layout, parent, false)
|
||||
val density = parent.resources.displayMetrics.density
|
||||
val view = LayoutInflater.from(parent.context)
|
||||
.inflate(R.layout.item_card, parent, false)
|
||||
val params = view.layoutParams as RecyclerView.LayoutParams
|
||||
when (mode) {
|
||||
Mode.HERO ->
|
||||
params.width = parent.resources.displayMetrics.widthPixels -
|
||||
(56 * density).roundToInt()
|
||||
Mode.CAROUSEL -> params.width = (210 * density).roundToInt()
|
||||
Mode.GRID -> params.width = ViewGroup.LayoutParams.MATCH_PARENT
|
||||
}
|
||||
params.marginEnd = (12 * density).roundToInt()
|
||||
params.bottomMargin = if (mode == Mode.GRID) (16 * density).roundToInt() else 0
|
||||
params.width = if (tileWidth > 0) tileWidth else ViewGroup.LayoutParams.MATCH_PARENT
|
||||
view.layoutParams = params
|
||||
return Holder(view)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: Holder, position: Int) {
|
||||
val item = items[position]
|
||||
holder.title.text = item.title
|
||||
holder.meta.text = item.folder
|
||||
ThumbCache.load(holder.itemView.context, item, holder.thumb)
|
||||
val liked = item.key in likedKeys
|
||||
holder.tile.bind(
|
||||
ThumbCache.memory(item.key),
|
||||
ThumbCache.label(holder.itemView.context, item),
|
||||
item.title,
|
||||
liked
|
||||
)
|
||||
ThumbCache.load(holder.itemView.context, item, holder.tile) { bitmap, label ->
|
||||
holder.tile.bind(bitmap, label, item.title, item.key in likedKeys)
|
||||
}
|
||||
holder.itemView.setOnClickListener {
|
||||
val current = holder.bindingAdapterPosition
|
||||
if (current != RecyclerView.NO_POSITION && current < items.size) onTap(items[current])
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<solid android:color="@color/kt_chip_bg" />
|
||||
<corners android:radius="16dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<solid android:color="@color/kt_chip_active" />
|
||||
<corners android:radius="16dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,9 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M19.14,12.94c0.04,-0.3 0.06,-0.61 0.06,-0.94 0,-0.32 -0.02,-0.64 -0.07,-0.94l2.03,-1.58c0.18,-0.14 0.23,-0.41 0.12,-0.61l-1.92,-3.32c-0.12,-0.22 -0.37,-0.29 -0.59,-0.22l-2.39,0.96c-0.5,-0.38 -1.03,-0.7 -1.62,-0.94L14.4,2.81c-0.04,-0.24 -0.24,-0.41 -0.48,-0.41h-3.84c-0.24,0 -0.43,0.17 -0.47,0.41L9.25,5.35C8.66,5.59 8.12,5.92 7.63,6.29L5.24,5.33c-0.22,-0.08 -0.47,0 -0.59,0.22L2.74,8.87C2.62,9.08 2.66,9.34 2.86,9.48l2.03,1.58C4.84,11.36 4.8,11.69 4.8,12s0.02,0.64 0.07,0.94l-2.03,1.58c-0.18,0.14 -0.23,0.41 -0.12,0.61l1.92,3.32c0.12,0.22 0.37,0.29 0.59,0.22l2.39,-0.96c0.5,0.38 1.03,0.7 1.62,0.94l0.36,2.54c0.05,0.24 0.24,0.41 0.48,0.41h3.84c0.24,0 0.44,-0.17 0.47,-0.41l0.36,-2.54c0.59,-0.24 1.13,-0.56 1.62,-0.94l2.39,0.96c0.22,0.08 0.47,0 0.59,-0.22l1.92,-3.32c0.12,-0.22 0.07,-0.47 -0.12,-0.61l-2.01,-1.58zM12,15.6c-1.98,0 -3.6,-1.62 -3.6,-3.6s1.62,-3.6 3.6,-3.6 3.6,1.62 3.6,3.6 -1.62,3.6 -3.6,3.6z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,9 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,12 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="32dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="32"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FF0000"
|
||||
android:pathData="M4,0 L28,0 A4,4 0 0,1 32,4 L32,20 A4,4 0 0,1 28,24 L4,24 A4,4 0 0,1 0,20 L0,4 A4,4 0 0,1 4,0 Z" />
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M13,7 L22,12 L13,17 Z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,9 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M12,1L3,5v6c0,5.55 3.84,10.74 9,12 5.16,-1.26 9,-6.45 9,-12V5l-9,-4z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,9 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z" />
|
||||
</vector>
|
||||
@@ -10,7 +10,7 @@
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
|
||||
<!-- Top bar: wordmark left, search + avatar right (iOS Kids layout). -->
|
||||
<!-- Top bar: logo left, search + profile right (iPad kids layout). -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="56dp"
|
||||
@@ -19,21 +19,19 @@
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="8dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:fontFamily="sans-serif-medium"
|
||||
android:text="@string/wordmark_1"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="20sp" />
|
||||
<ImageView
|
||||
android:layout_width="32dp"
|
||||
android:layout_height="24dp"
|
||||
android:contentDescription="@string/app_name"
|
||||
android:src="@drawable/ic_kids_logo" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="4dp"
|
||||
android:layout_marginStart="6dp"
|
||||
android:fontFamily="sans-serif-medium"
|
||||
android:text="@string/wordmark_2"
|
||||
android:textColor="@color/kt_red"
|
||||
android:text="@string/wordmark"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="20sp" />
|
||||
|
||||
<Space
|
||||
@@ -42,42 +40,81 @@
|
||||
android:layout_weight="1" />
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/btn_top_search"
|
||||
android:id="@+id/btn_shield"
|
||||
android:layout_width="40dp"
|
||||
android:layout_height="40dp"
|
||||
android:layout_marginStart="2dp"
|
||||
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||
android:contentDescription="@string/parent_gate_title"
|
||||
android:padding="9dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:src="@drawable/ic_shield"
|
||||
app:tint="@color/kt_text" />
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/btn_gear"
|
||||
android:layout_width="40dp"
|
||||
android:layout_height="40dp"
|
||||
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||
android:contentDescription="@string/tab_search"
|
||||
android:padding="8dp"
|
||||
android:contentDescription="@string/folder_label"
|
||||
android:padding="9dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:src="@drawable/ic_search"
|
||||
android:src="@drawable/ic_gear"
|
||||
app:tint="@color/kt_text" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/avatar"
|
||||
android:layout_width="32dp"
|
||||
android:layout_height="32dp"
|
||||
android:layout_marginStart="4dp"
|
||||
android:background="@drawable/bg_avatar"
|
||||
android:contentDescription="@string/tab_profile"
|
||||
android:padding="7dp"
|
||||
android:src="@drawable/ic_person"
|
||||
app:tint="@android:color/white" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Category pills: All plus one per folder, scrollable. -->
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/chips"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:clipToPadding="false"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="2dp"
|
||||
android:paddingEnd="8dp"
|
||||
android:paddingBottom="10dp"
|
||||
android:scrollbars="none" />
|
||||
|
||||
<FrameLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1">
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rows"
|
||||
android:id="@+id/grid"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:clipToPadding="false"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="4dp"
|
||||
android:paddingEnd="4dp"
|
||||
android:paddingBottom="12dp"
|
||||
android:scrollbars="none" />
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/results"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:clipToPadding="false"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="4dp"
|
||||
android:paddingEnd="4dp"
|
||||
android:paddingBottom="12dp"
|
||||
android:scrollbars="none"
|
||||
android:visibility="gone" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/results_empty"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center"
|
||||
android:gravity="center"
|
||||
android:paddingStart="32dp"
|
||||
android:paddingEnd="32dp"
|
||||
android:textColor="@color/kt_text_sub"
|
||||
android:textSize="14sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/empty"
|
||||
android:layout_width="match_parent"
|
||||
@@ -95,6 +132,7 @@
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
@@ -117,30 +155,12 @@
|
||||
android:textColor="@android:color/white"
|
||||
android:textSize="15sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Search results, a 2-column grid like the iOS kids app. -->
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/results"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:clipToPadding="false"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:paddingBottom="12dp"
|
||||
android:scrollbars="none"
|
||||
android:visibility="gone" />
|
||||
</FrameLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/kt_divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/tabbar"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="64dp"
|
||||
android:layout_height="60dp"
|
||||
android:background="@color/kt_bg"
|
||||
android:orientation="horizontal">
|
||||
|
||||
@@ -156,16 +176,16 @@
|
||||
android:layout_height="24dp"
|
||||
android:contentDescription="@string/tab_home"
|
||||
android:src="@drawable/ic_home"
|
||||
app:tint="@color/kt_red" />
|
||||
app:tint="@color/kt_text" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tab_home_label"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="@string/tab_home"
|
||||
android:textColor="@color/kt_red"
|
||||
android:textSize="11sp" />
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="10sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
@@ -186,10 +206,34 @@
|
||||
android:id="@+id/tab_search_label"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="@string/tab_search"
|
||||
android:textColor="@color/kt_tab_idle"
|
||||
android:textSize="11sp" />
|
||||
android:textSize="10sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/tab_stuff"
|
||||
style="@style/KtTab"
|
||||
android:gravity="center"
|
||||
android:orientation="vertical">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/tab_stuff_icon"
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="24dp"
|
||||
android:contentDescription="@string/tab_stuff"
|
||||
android:src="@drawable/ic_star"
|
||||
app:tint="@color/kt_tab_idle" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tab_stuff_label"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="@string/tab_stuff"
|
||||
android:textColor="@color/kt_tab_idle"
|
||||
android:textSize="10sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
@@ -210,15 +254,15 @@
|
||||
android:id="@+id/tab_profile_label"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="@string/tab_profile"
|
||||
android:textColor="@color/kt_tab_idle"
|
||||
android:textSize="11sp" />
|
||||
android:textSize="10sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Search overlay, hidden until the Search tab is tapped. -->
|
||||
<!-- Search overlay, hidden until the Search tab or the magnifier is tapped. -->
|
||||
<LinearLayout
|
||||
android:id="@+id/search_bar"
|
||||
android:layout_width="match_parent"
|
||||
@@ -228,8 +272,7 @@
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="8dp"
|
||||
android:paddingEnd="12dp"
|
||||
android:visibility="gone"
|
||||
android:elevation="4dp">
|
||||
android:visibility="gone">
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/btn_search_close"
|
||||
@@ -237,7 +280,7 @@
|
||||
android:layout_height="40dp"
|
||||
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||
android:contentDescription="@string/cancel"
|
||||
android:padding="8dp"
|
||||
android:padding="9dp"
|
||||
android:src="@drawable/ic_back"
|
||||
app:tint="@color/kt_text" />
|
||||
|
||||
|
||||
@@ -44,6 +44,18 @@
|
||||
android:src="@drawable/ic_back"
|
||||
app:tint="@android:color/white" />
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/btn_like"
|
||||
android:layout_width="44dp"
|
||||
android:layout_height="44dp"
|
||||
android:layout_gravity="top|end"
|
||||
android:layout_margin="12dp"
|
||||
android:background="@drawable/bg_scrim_circle"
|
||||
android:contentDescription="@string/stats_open"
|
||||
android:padding="10dp"
|
||||
android:src="@drawable/ic_heart"
|
||||
app:tint="@android:color/white" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/bottom_panel"
|
||||
android:layout_width="match_parent"
|
||||
@@ -71,6 +83,17 @@
|
||||
android:layout_height="32dp"
|
||||
android:paddingStart="0dp"
|
||||
android:paddingEnd="0dp" />
|
||||
|
||||
<!-- Like the iOS app: tapping the running video offers four more. -->
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/suggestions"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:clipToPadding="false"
|
||||
android:nestedScrollingEnabled="false"
|
||||
android:paddingEnd="0dp"
|
||||
android:scrollbars="none" />
|
||||
</LinearLayout>
|
||||
</FrameLayout>
|
||||
</FrameLayout>
|
||||
@@ -0,0 +1,138 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/kt_bg"
|
||||
android:fillViewport="true">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="20dp"
|
||||
android:paddingTop="16dp"
|
||||
android:paddingEnd="20dp"
|
||||
android:paddingBottom="24dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/stats_title"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="22sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/stat_plays"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="26sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/stats_plays"
|
||||
android:textColor="@color/kt_text_sub"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/stat_time"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="26sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/stats_time"
|
||||
android:textColor="@color/kt_text_sub"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/stat_videos"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="26sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/stats_videos"
|
||||
android:textColor="@color/kt_text_sub"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:text="@string/stats_top"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/top_list"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:orientation="vertical" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:text="@string/stats_days"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/day_list"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:orientation="vertical" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/stats_path"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:textColor="@color/kt_text_sub"
|
||||
android:textSize="11sp" />
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<dev.lotherk.kidstube.ui.TileView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/tile"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" />
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
style="@style/KtChip"
|
||||
android:clickable="true"
|
||||
android:focusable="true" />
|
||||
@@ -1,30 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical">
|
||||
|
||||
<dev.lotherk.kidstube.ui.ThumbView
|
||||
android:id="@+id/thumb"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/title"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="2"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/meta"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="2dp"
|
||||
android:textColor="@color/kt_text_sub"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
@@ -1,28 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/section_title"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:paddingTop="8dp"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/row"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp"
|
||||
android:clipToPadding="false"
|
||||
android:nestedScrollingEnabled="false"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="8dp"
|
||||
android:scrollbars="none" />
|
||||
</LinearLayout>
|
||||
+3
-11
@@ -13,17 +13,9 @@
|
||||
android:id="@+id/title"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:layout_marginTop="6dp"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="2"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/kt_text"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/meta"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="2dp"
|
||||
android:textColor="@color/kt_text_sub"
|
||||
android:textSize="12sp" />
|
||||
android:textSize="11sp" />
|
||||
</LinearLayout>
|
||||
@@ -1,13 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- iOS YouTube Kids metrics: white canvas, near-black text, red accent. -->
|
||||
<color name="kt_bg">#FFFFFFFF</color>
|
||||
<!-- Dark canvas like the iPad kids app: near-black ground, white titles. -->
|
||||
<color name="kt_bg">#FF0F0F0F</color>
|
||||
<color name="kt_red">#FFFF0000</color>
|
||||
<color name="kt_text">#FF212121</color>
|
||||
<color name="kt_text_sub">#FF606060</color>
|
||||
<color name="kt_tab_idle">#FF9E9E9E</color>
|
||||
<color name="kt_divider">#FFE6E6E6</color>
|
||||
<color name="kt_placeholder">#FFE8E8E8</color>
|
||||
<color name="kt_text">#FFFFFFFF</color>
|
||||
<color name="kt_text_sub">#FFAAAAAA</color>
|
||||
<color name="kt_tab_idle">#FF8A8A8A</color>
|
||||
<color name="kt_divider">#FF272727</color>
|
||||
<color name="kt_placeholder">#FF1F1F1F</color>
|
||||
<color name="kt_pill">#B3000000</color>
|
||||
<color name="kt_scrim">#66000000</color>
|
||||
<color name="kt_chip_bg">#FF272727</color>
|
||||
<color name="kt_chip_active">#FFFFFFFF</color>
|
||||
<color name="kt_chip_text_active">#FF000000</color>
|
||||
</resources>
|
||||
@@ -1,12 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">KidsTube</string>
|
||||
<string name="wordmark_1">Kids</string>
|
||||
<string name="wordmark_2">Tube</string>
|
||||
<string name="wordmark">Kids</string>
|
||||
|
||||
<string name="tab_home">Home</string>
|
||||
<string name="tab_search">Search</string>
|
||||
<string name="tab_profile">Profile</string>
|
||||
<string name="tab_stuff">Your stuff</string>
|
||||
<string name="chip_all">All</string>
|
||||
|
||||
<string name="empty_title">No videos yet</string>
|
||||
<string name="empty_body">Put the videos into the folder Movies/KidsTube, or pick another folder. The app only reads that folder and never goes online.</string>
|
||||
@@ -23,5 +24,16 @@
|
||||
<string name="ok">OK</string>
|
||||
<string name="cancel">Cancel</string>
|
||||
<string name="back">Back</string>
|
||||
<string name="stats_title">Statistics</string>
|
||||
<string name="stats_plays">plays</string>
|
||||
<string name="stats_time">watch time</string>
|
||||
<string name="stats_videos">videos</string>
|
||||
<string name="stats_top">Most watched</string>
|
||||
<string name="stats_days">Per day</string>
|
||||
<string name="stats_empty">Nothing watched yet</string>
|
||||
<string name="stats_export">Also written to %1$s</string>
|
||||
<string name="stats_open">Statistics</string>
|
||||
<string name="likes_empty">Nothing liked yet. Tap the heart while a video plays.</string>
|
||||
<string name="search_empty">Nothing found.</string>
|
||||
<string name="error_play">This video cannot be played on this device</string>
|
||||
</resources>
|
||||
@@ -1,11 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.KidsTube" parent="Theme.AppCompat.Light.NoActionBar">
|
||||
<style name="Theme.KidsTube" parent="Theme.AppCompat.NoActionBar">
|
||||
<item name="colorPrimary">@color/kt_red</item>
|
||||
<item name="colorPrimaryDark">@color/kt_red</item>
|
||||
<item name="colorPrimaryDark">@color/kt_bg</item>
|
||||
<item name="colorAccent">@color/kt_red</item>
|
||||
<item name="android:windowBackground">@color/kt_bg</item>
|
||||
<item name="android:statusBarColor">@color/kt_bg</item>
|
||||
<item name="android:navigationBarColor">@color/kt_bg</item>
|
||||
</style>
|
||||
|
||||
<style name="Theme.KidsTube.Player" parent="Theme.AppCompat.NoActionBar">
|
||||
@@ -19,4 +20,18 @@
|
||||
<item name="android:layout_height">match_parent</item>
|
||||
<item name="android:layout_weight">1</item>
|
||||
</style>
|
||||
|
||||
<!-- Category pill: fully rounded capsule, one line high. -->
|
||||
<style name="KtChip">
|
||||
<item name="android:layout_width">wrap_content</item>
|
||||
<item name="android:layout_height">32dp</item>
|
||||
<item name="android:layout_marginEnd">8dp</item>
|
||||
<item name="android:background">@drawable/bg_chip</item>
|
||||
<item name="android:gravity">center</item>
|
||||
<item name="android:paddingStart">14dp</item>
|
||||
<item name="android:paddingEnd">14dp</item>
|
||||
<item name="android:textColor">@color/kt_text</item>
|
||||
<item name="android:textSize">13sp</item>
|
||||
<item name="android:fontFamily">sans-serif-medium</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,110 @@
|
||||
package dev.lotherk.kidstube.data
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SeriesTest {
|
||||
|
||||
/** Deliberately not MediaItem: no Android classes in a JVM unit test. */
|
||||
private data class TestItem(
|
||||
override val key: String,
|
||||
override val title: String,
|
||||
override val folder: String
|
||||
) : SeriesItem
|
||||
|
||||
private fun item(folder: String, title: String) = TestItem("$folder/$title", title, folder)
|
||||
|
||||
private fun series(folder: String, count: Int) =
|
||||
(1..count).map { item(folder, String.format("%03d - Folge %d", it, it)) }
|
||||
|
||||
@Test
|
||||
fun naturalOrder_sortsByNumericPrefix() {
|
||||
val shuffled = listOf(
|
||||
item("A", "010 - zehn"),
|
||||
item("A", "002 - zwei"),
|
||||
item("A", "001 - eins")
|
||||
)
|
||||
val sorted = shuffled.sortedWith(Series.naturalOrder).map { it.title }
|
||||
assertEquals(listOf("001 - eins", "002 - zwei", "010 - zehn"), sorted)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun naturalOrder_putsNumberedBeforePlainTitles() {
|
||||
val sorted = listOf(item("A", "Zebra"), item("A", "007 - Bond"))
|
||||
.sortedWith(Series.naturalOrder).map { it.title }
|
||||
assertEquals(listOf("007 - Bond", "Zebra"), sorted)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun neighbours_middleOfSeries() {
|
||||
val all = series("Sandmann", 10)
|
||||
val (previous, next) = Series.neighbours(all, all[4])
|
||||
assertEquals("004 - Folge 4", previous?.title)
|
||||
assertEquals("006 - Folge 6", next?.title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun neighbours_firstAndLastHaveOneSide() {
|
||||
val all = series("Sandmann", 5)
|
||||
val (firstPrev, firstNext) = Series.neighbours(all, all.first())
|
||||
assertNull(firstPrev)
|
||||
assertEquals("002 - Folge 2", firstNext?.title)
|
||||
|
||||
val (lastPrev, lastNext) = Series.neighbours(all, all.last())
|
||||
assertEquals("004 - Folge 4", lastPrev?.title)
|
||||
assertNull(lastNext)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun suggestions_middleOfSeries_keepsFixedSlotOrder() {
|
||||
val all = series("Sandmann", 10)
|
||||
val current = all[4]
|
||||
val out = Series.suggestionsFor(all, current)
|
||||
assertEquals(4, out.size)
|
||||
// slot 1 random, slot 2 previous, slot 3 next, slot 4 random
|
||||
assertTrue(out[0].key != current.key)
|
||||
assertEquals("004 - Folge 4", out[1].title)
|
||||
assertEquals("006 - Folge 6", out[2].title)
|
||||
assertTrue(out[3].key != current.key)
|
||||
assertEquals(4, out.map { it.key }.distinct().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun suggestions_firstOfSeries_hasNoPrevious() {
|
||||
val all = series("Sandmann", 6)
|
||||
val out = Series.suggestionsFor(all, all.first())
|
||||
assertEquals(4, out.size)
|
||||
assertEquals("002 - Folge 2", out[1].title) // next moves up one slot
|
||||
assertEquals(4, out.map { it.key }.distinct().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun suggestions_prefersNeighboursOverOtherFolders() {
|
||||
val sandmann = series("Sandmann", 4)
|
||||
val other = (1..6).map { item("Tiere", String.format("%03d - Tier %d", it, it)) }
|
||||
val all = (sandmann + other).shuffled()
|
||||
val current = sandmann[1]
|
||||
val out = Series.suggestionsFor(all, current)
|
||||
assertEquals("001 - Folge 1", out[1].title)
|
||||
assertEquals("003 - Folge 3", out[2].title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun suggestions_handlesShortLibrary() {
|
||||
val all = series("Sandmann", 2)
|
||||
val out = Series.suggestionsFor(all, all[0])
|
||||
assertEquals(1, out.size)
|
||||
assertEquals("002 - Folge 2", out[0].title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun suggestions_neverRepeatsTheCurrentVideo() {
|
||||
val all = series("Sandmann", 3)
|
||||
repeat(20) {
|
||||
val out = Series.suggestionsFor(all, all[1])
|
||||
assertTrue(out.none { it.key == all[1].key })
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user