Compare commits

...

16 commits
v0.2.1 ... main

Author SHA1 Message Date
34f54bcc29 Release Kaleido 0.8.1 fixing Down from a title page's buttons
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m32s
- A row below the header (Seasons, Cast, search results) attached its
  entry focus target to its first card. Once the row was scrolled away,
  e.g. a show page's restored Seasons scroll, that card was not composed,
  so Down from the actions failed and focus stayed in the header.
- Enter at the preferred card while it is in view, otherwise at the first
  fully visible card (rowEntryIndex, with JVM tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:11:26 -07:00
3e020bd7fa Release Kaleido 0.8.0 with a single-countdown Up Next screen
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m33s
- Credits and episode endings open Up Next: the video keeps playing in a
  top-left mini-player beside the next episode, season and related shows.
  Play next episode carries the only countdown; any remote press stops it.
  Left then OK on the video, or Back, returns to the credits.
- Wait for the player's final timeline report before reloading Home, so
  Continue Watching reflects the episode just watched.
- Remove the source label above Home's featured title.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 21:48:11 -07:00
8533347b51 Release Kaleido 0.7.0 with previous episode, timed auto-skip and cross-device refresh
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m36s
- Player: Previous episode (also through a shuffle) and a redesigned bar,
  with times at the timeline ends and a centred transport cluster.
- Settings > Playback: skip intros/credits automatically after 3-15 s or
  show the button only. A pending skip reads "Skipping intro" with a
  filling background; any remote press cancels it, OK skips now.
- Continue Watching changes from other devices are picked up by the
  15-second foreground poll (5%-step fingerprint) and within a second of
  returning to Kaleido.
- Keep Continue Watching focus when a refresh replaces the restored card.
- AGENTS.md: tiered testing so small changes don't run every device suite.
- New scripts/verify_player_features.py device checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:41:47 -07:00
bdc37db05d Fix playback lifecycle, server-change and navigation bugs from review
Playback
- A preparation finishing after Home no longer starts playing in the
  background; the post-play countdown only runs while Kaleido is on screen.
- Closing or backgrounding during preparation keeps the requested resume
  position instead of reporting the player's unprepared 0.
- Progress, scrobble and transcode-stop reports stay pinned to the server
  the title came from, even after a server change.

Networking
- Cancelling a request now cancels its OkHttp call, so timeouts such as the
  3-second server-stop check actually return on time.
- Connection discovery accepts the most preferred answering address without
  waiting for slower, less preferred probes.

State and navigation
- Server/account changes clear episode queues, shuffle, version choices,
  episode selections and search.
- Leaving Search cancels its pending request.
- Version selection updates the format badges and technical line.
- Down from the Home tab enters the rows when there is no featured title.
- Back (or a new Cancel button) closes Settings > Choose server.
- One unavailable show no longer discards the whole New Seasons row.

Release
- package_release.py and CI check the APK's own versionName/versionCode
  (and that it is not debuggable) via scripts/verify_distribution.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:52:52 -07:00
4780bdcdb2 Remove volume boost, honour server-stopped streams, drop the Library genre filter
Work already pending in the tree before the bug-fix pass, committed on its own:
- Remove Volume boost (it degraded audio) and its setting; keep passthrough.
- Leave playback with the server's reason when Plex stops a session
  (timeline terminationCode/terminationText); never fall back or reconnect after.
- Genre filtering lives in Categories; the Library grid lists the whole section.
- Update UI verification scripts and AGENTS.md accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:52:52 -07:00
0ee43ffa76 Release Kaleido 0.6.2 with a kaleidoscope startup animation
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m26s
The cold-start iris is replaced with Kaleido Desktop's kaleidoscope: a
mirrored field of shards gathers into the mark, then the camera flies
through its centre as before. A still, faint field holds until startup is
ready, keeping cold-start hitches out of the motion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 19:47:07 -07:00
30e0f30bca Release Kaleido 0.6.1 with smoother browsing
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m24s
Home, Movies and TV stay composed once shown and are revealed instead of
rebuilt; hidden screens are unplaced, have no semantics and take no focus.
The hero stays composed as a zero-alpha layer. Lazy-list prefetch runs on
FramePrefetch, which uses only spare frame time (unlimited only when truly
idle) instead of Compose's scheduler, which gave late frames unlimited time
and composed whole rows mid-scroll. CacheWindows keeps Compose's cache-window
strategy on that scheduler and premeasures nested cards.

With any accessibility service enabled, Compose walked and sorted every
composed node every 100 ms while browsing; rows and cards outside the
viewport now carry no semantics. Cards use a lighter artwork path, lay out
both title weights up front, and models are @Immutable. Preview and hero copy
compose over the transparent start of their fade. Library sync applies its
snapshot after 2 s without input, and moveToRow retries focus so a refreshed
card is never left unfocused.

profile_transitions.py now counts frames actually dropped on the display.
On the onn the 42 measured transitions dropped 24-38 frames, versus 55 for
0.6.0; details are in docs/runtime-verification.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:24:07 -07:00
ca5f0e20e5 Refresh README screenshots for Kaleido 0.6.0
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m36s
Retake every screenshot on Android TV and add Home rows, a season page
and Categories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 19:28:32 -07:00
24042bebbc Release Kaleido 0.6.0 with Silo-style browsing and details
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m35s
Movie, show, season and episode pages now share the browse previews'
design: the same top-right artwork and optional colour wash, title art, a
facts line with rating and format badges, and a three-line synopsis.
Season and episode pages follow the focused episode's still and details,
and the player's controls show title art and the rating badge. The
details tests step past the library filter row and read title art from
its content description.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:48:00 -07:00
7471f7cac2 Redesign browse previews after Silo, with an optional artwork colour wash
Home's hero now compacts into a preview of the focused card instead of
scrolling away, and Movies and TV share the same preview: large title
art, facts, a three-line synopsis, cast and format badges, with the card's
own image scaled whole into the top-right. Artwork crossfades and copy
fades and lifts between titles, driven from graphics layers so no
composition or layout runs per frame. An Interface setting tints the page
with the artwork's colour, baked into the cached backdrop frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:23:28 -07:00
dedf62a19e Release Kaleido 0.5.0 with source bitrate, audio selection and show shuffle
All checks were successful
Validate and publish Kaleido / android (push) Successful in 3m4s
2026-10-28 11:19:25 -07:00
eeebc9af38 Release Kaleido 0.4.1 with genre-led cards and unique category artwork
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m41s
2026-10-28 10:45:19 -07:00
a2c72704f5 Release Kaleido 0.4.0 with artwork categories, TV framing and compact skip cues
All checks were successful
Validate and publish Kaleido / android (push) Successful in 3m9s
2026-10-28 10:16:23 -07:00
be47bd550c Correct episode regression script Home cleanup [skip ci] 2026-10-27 21:01:14 -07:00
7843775064 Release Kaleido 0.3.1 fixing episode row focus on reentry
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m26s
2026-10-27 21:00:22 -07:00
0c62d7414e Release Kaleido 0.3.0 with categories, alphabet jumps and audio preferences
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m24s
2026-10-27 20:33:20 -07:00
78 changed files with 3673 additions and 695 deletions

View file

@ -35,6 +35,11 @@ jobs:
if test -f distribution/Kaleido.apk; then if test -f distribution/Kaleido.apk; then
(cd distribution && sha256sum -c Kaleido.apk.sha256) (cd distribution && sha256sum -c Kaleido.apk.sha256)
.tools/sdk/build-tools/35.0.0/apksigner verify --verbose --print-certs distribution/Kaleido.apk .tools/sdk/build-tools/35.0.0/apksigner verify --verbose --print-certs distribution/Kaleido.apk
# The APK's own manifest must carry the advertised version (and, for a tag, version.properties').
case "${{ github.ref }}" in
refs/tags/v*) python3 scripts/verify_distribution.py --release ;;
*) python3 scripts/verify_distribution.py ;;
esac
fi fi
- name: Publish signed tag release - name: Publish signed tag release
if: startsWith(github.ref, 'refs/tags/v') if: startsWith(github.ref, 'refs/tags/v')

View file

@ -4,14 +4,14 @@
- Ask clarifying questions before proceeding when more information is needed. Otherwise make reasonable decisions and complete the authorized work. - Ask clarifying questions before proceeding when more information is needed. Otherwise make reasonable decisions and complete the authorized work.
- This is a real native Android TV Plex client: Kotlin, Jetpack Compose, Media3/ExoPlayer. Preserve working Plex functionality; do not substitute mock content or prototype playback. - This is a real native Android TV Plex client: Kotlin, Jetpack Compose, Media3/ExoPlayer. Preserve working Plex functionality; do not substitute mock content or prototype playback.
- The primary test device is the onn at **192.168.50.195:5555**, package **tv.kaleido.app**, activity **.MainActivity**. The user also authorized two weaker devices for performance testing: a Fire TV Stick 4K (Fire OS 8, 32-bit) at **192.168.50.146:5555** and a TCL Smart TV Pro (MT5896, slowest GPU) at **192.168.50.200:5555**. Scripts target the onn unless `KALEIDO_DEVICE` names another serial. Always specify the ADB serial. Do not modify any device's launcher, accessibility services (the onn runs two, which add per-frame semantics work), settings, or other apps. The TCL's network ADB link drops intermittently; `device.py` reconnects and retries. - The primary test device is the onn at **192.168.50.195:5555**, package **tv.kaleido.app**, activity **.MainActivity**. The user also authorized two weaker devices for performance testing: a Fire TV Stick 4K (Fire OS 8, 32-bit) at **192.168.50.146:5555** and a TCL Smart TV Pro (MT5896, slowest GPU) at **192.168.50.200:5555**. Scripts target the onn unless `KALEIDO_DEVICE` names another serial. Always specify the ADB serial. Do not modify any device's launcher, accessibility services (the onn runs Luma's Home-button service; Button Mapper was removed at the user's request on 2026-10-29; any service makes Compose do semantics work), settings, or other apps. The TCL's network ADB link drops intermittently; `device.py` reconnects and retries.
- `.env` contains `PLEX_SERVER_URL` and `PLEX_TOKEN` for local testing. Never print, commit, or embed credentials in source, resources, APKs, or logs. Keep `.env`, signing keys, toolchains, and private evidence ignored. - `.env` contains `PLEX_SERVER_URL` and `PLEX_TOKEN` for local testing. Never print, commit, or embed credentials in source, resources, APKs, or logs. Keep `.env`, signing keys, toolchains, and private evidence ignored.
- Use the existing encrypted session. `scripts/device.py seed` provisions an installed **debug** build only when needed; the app encrypts and deletes its bootstrap file. Never clear app data or sign out just to reset a test. - Use the existing encrypted session. `scripts/device.py seed` provisions an installed **debug** build only when needed; the app encrypts and deletes its bootstrap file. Never clear app data or sign out just to reset a test.
## UI and architecture ## UI and architecture
- **Home:** large cinematic hero with playback/information actions and integrated landscape Continue Watching. Do not replace it with the compact section preview. - **Home:** large cinematic hero with playback/information actions and integrated landscape Continue Watching. Entering the rows compacts it into a Silo-style preview of the focused card (its own image, top-right); Up/Back restores the hero.
- **Movies:** compact preview/backdrop follows focused posters; recent releases and movie recommendations lead. **TV:** episode-first layout with wider next-episode thumbnails, new seasons and new episodes. Keep these destinations visibly distinct. - **Movies:** the same Silo-style preview follows focused posters; recent releases and movie recommendations lead. **TV:** episode-first layout with wider next-episode thumbnails, new seasons and new episodes. Keep these destinations' rows visibly distinct. The optional artwork colour wash is baked into the preview backdrop bitmap.
- Both sections retain a dedicated, filtered/sorted **A–Z poster grid**. Primary tabs activate on focus. Use neutral near-black chrome, artwork-led color, restrained controls and stable card bounds. Inspect actual TV screenshots and D-pad behavior after UI changes. - Both sections retain a dedicated, filtered/sorted **A–Z poster grid**. Primary tabs activate on focus. Use neutral near-black chrome, artwork-led color, restrained controls and stable card bounds. Inspect actual TV screenshots and D-pad behavior after UI changes.
- `KaleidoViewModel.kt`: navigation, async loading and section caches. `PlexApi.kt` / `Models.kt`: Plex transport and parsing. `FocusedBrowse.kt`, `BrowseBackdrop.kt`, `BrowseScreens.kt`, `Theme.kt`: browsing/focus/design. `Playback.kt`: controller, negotiation and progress. `PlayerControls.kt` / `PlaybackExtras.kt`: controls, options and post-play. `SecureSession.kt`: Android Keystore persistence. `AppUpdater.kt`: repository updates. - `KaleidoViewModel.kt`: navigation, async loading and section caches. `PlexApi.kt` / `Models.kt`: Plex transport and parsing. `FocusedBrowse.kt`, `BrowseBackdrop.kt`, `BrowseScreens.kt`, `Theme.kt`: browsing/focus/design. `Playback.kt`: controller, negotiation and progress. `PlayerControls.kt` / `PlaybackExtras.kt`: controls, options and post-play. `SecureSession.kt`: Android Keystore persistence. `AppUpdater.kt`: repository updates.
@ -35,7 +35,17 @@ Install `app/build/outputs/apk/release/app-release.apk` instead for performance/
## Testing suite ## Testing suite
Use `& $KaleidoPython` before the Python commands below. Run only checks relevant to the change; **never run competing device/UI tests in parallel**. Live playback tests change real Plex progress and can change playback preferences. Restore a useful final state, normally the release build on Home. After a functional debug batch, restore the signed release and its ART profile before returning the device to normal use; never judge performance from an unoptimized debug build. Use `& $KaleidoPython` before the Python commands below. **Never run competing device/UI tests in parallel.**
**Test in tiers; don't run every suite for every change.** Each device script cold-starts Kaleido, waits for playback and real timers, and dumps the UI per check, so a full pass takes 30+ minutes.
1. **Every change:** `.\Build.ps1 -Test` (compile, JVM unit tests, lint; about a minute). Put pure logic (ordering, parsing, fingerprints, countdown rules) in unit-testable functions with JVM tests instead of proving it on the TV.
2. **UI or device behaviour changed:** run only the one or two scripts for the area touched (map below), plus a screenshot of the changed screen. One script is usually 1–4 minutes.
3. **Before a release, or after broad navigation/playback/startup changes:** the full set: `verify_ui.py browse` and `player`, `repro_runtime.py controls episode postplay credits sections`, `verify_player_features.py`, `verify_settings.py`, then the release build with `repro_runtime.py browse` for frame pacing.
Area → checks: Home/Movies/TV rows, focus, details Back → `verify_ui.py browse` · player bar, menus, scrubbing → `verify_ui.py player` · previous/next episode, auto-skip, server picker, cross-device refresh → `verify_player_features.py <phase>` · post-play/autoplay/credits → `repro_runtime.py postplay` or `credits` · Settings rows/dialogs → `verify_settings.py` · details/cast → `verify_details_layout.py` / `verify_movie_details.py` · library A–Z/search → `verify_library_jump.py` · startup/tab loading → `repro_runtime.py sections` · scrolling smoothness → release + `repro_runtime.py browse`. Skip suites for untouched areas and say which were skipped.
Run only checks relevant to the change. Live playback tests change real Plex progress and can change playback preferences. Restore a useful final state, normally the release build on Home. After a functional debug batch, restore the signed release and its ART profile before returning the device to normal use; never judge performance from an unoptimized debug build.
| Command | Purpose / required build | | Command | Purpose / required build |
| --- | --- | | --- | --- |
@ -45,8 +55,8 @@ Use `& $KaleidoPython` before the Python commands below. Run only checks relevan
| `scripts/repro_runtime.py browse` | Horizontal bounds and frame pacing; **optimized release with profile compilation** | | `scripts/repro_runtime.py browse` | Horizontal bounds and frame pacing; **optimized release with profile compilation** |
| `scripts/repro_runtime.py controls` | One-press Back, OK reveal, timed hide and exit; **debug** | | `scripts/repro_runtime.py controls` | One-press Back, OK reveal, timed hide and exit; **debug** |
| `scripts/repro_runtime.py episode` | Next-episode replacement/crash regression; **debug** | | `scripts/repro_runtime.py episode` | Next-episode replacement/crash regression; **debug** |
| `scripts/repro_runtime.py postplay` | Natural ending → five-second countdown → next episode READY; **debug** | | `scripts/repro_runtime.py postplay` | Natural ending → Up Next countdown → next episode READY; **debug** |
| `scripts/repro_runtime.py credits` | Visible Skip credits, season/related rows and cancellable countdown; **debug** | | `scripts/repro_runtime.py credits` | Credits → Up Next (mini-player), season/related rows, any-press cancel, Back to video; **debug** |
| `scripts/device.py screenshot <name>` | Capture to ignored `evidence/private/`; also supports `hierarchy`, `logs`, `launch`, `key` | | `scripts/device.py screenshot <name>` | Capture to ignored `evidence/private/`; also supports `hierarchy`, `logs`, `launch`, `key` |
| `scripts/profile_browse.py` | Targeted atrace investigation when navigation performance regresses | | `scripts/profile_browse.py` | Targeted atrace investigation when navigation performance regresses |
| `scripts/profile_transitions.py <label>` | Skipped frames per D-pad transition (tabs, hero, rows, Movies) from framestats; first cycle is the first pass after launch; profiled **release**; raw frames kept for `resummarize` | | `scripts/profile_transitions.py <label>` | Skipped frames per D-pad transition (tabs, hero, rows, Movies) from framestats; first cycle is the first pass after launch; profiled **release**; raw frames kept for `resummarize` |
@ -57,6 +67,9 @@ Use `& $KaleidoPython` before the Python commands below. Run only checks relevan
| `scripts/verify_details_layout.py` | Fresh TV show header bounds and Seasons before Cast; debug or release | | `scripts/verify_details_layout.py` | Fresh TV show header bounds and Seasons before Cast; debug or release |
| `scripts/verify_movie_details.py` | Movie safe header, related movies and Back focus restoration; debug or release | | `scripts/verify_movie_details.py` | Movie safe header, related movies and Back focus restoration; debug or release |
| `scripts/verify_settings.py` | Category navigation, preference-dialog cancellation and live update check; expects Original quality / 80% test preferences | | `scripts/verify_settings.py` | Category navigation, preference-dialog cancellation and live update check; expects Original quality / 80% test preferences |
| `scripts/verify_library_jump.py` | Scoped Movie/TV categories, A–Z jumps beyond the first page, details/Back focus and exact Silo search |
| `scripts/verify_player_features.py [phase…]` | Phases `previous_episode`, `auto_skip` (Skipping intro fill, Down/Back cancel), `server_picker` (Back/Cancel), `refresh` (resume and open-app Continue Watching sync; moves and restores Silo 1×1 progress); **debug**; restores skip preferences |
| `scripts/verify_audio_preferences.py` | Theme persistence and actual playback audio; **debug**; restores prior audio preferences |
Live Android integration tests (currently six) cover secure persistence, library APIs, episodes, PIN, preview JPEGs/new seasons and supported HEVC remux negotiation: Live Android integration tests (currently six) cover secure persistence, library APIs, episodes, PIN, preview JPEGs/new seasons and supported HEVC remux negotiation:
@ -73,14 +86,17 @@ These require the private test session. Playback test intents (`testTitleId`, `t
## Important regression traps ## Important regression traps
- Keep initialization independent of cancellable tab requests and apply section results atomically. Cancelling initialization during a startup tab switch previously left Movies/TV blank. - Keep initialization independent of cancellable tab requests and apply section results atomically. Cancelling initialization during a startup tab switch previously left Movies/TV blank.
- Foreground library sync polls revisions every 15 seconds with a 60-second refresh fallback; pause it for playback/background and stage updates before applying them. Preserve stable hub/card focus IDs and current library filters/range. `LibrarySyncIntegrationTest` tests the real timer against an in-memory HTTP fixture without changing Plex or the encrypted session. - Foreground library sync polls revisions every 15 seconds with a 60-second refresh fallback, and checks within a second of returning to the foreground. The revision includes a Continue Watching fingerprint (membership, order, watch count, progress in 5% steps) so watching on another device shows up without refreshing Home on every poll; pause it for playback/background and stage updates before applying them. Preserve stable hub/card focus IDs and current library filters/range. `LibrarySyncIntegrationTest` tests the real timer against an in-memory HTTP fixture without changing Plex or the encrypted session.
- Home, Movies and TV stay composed once shown; hidden ones are unplaced, have no semantics and must never request focus (gate effects on `active`). Catalog and rails prefetch through `FramePrefetch`/`CacheWindows`, which must remain a `CacheWindowLogic` or rows stop being kept around. With any accessibility service enabled, Compose walks every composed node after each layout change: keep offscreen rows and cards without semantics (`semanticsOnScreen`). See `docs/runtime-verification.md` (frame pacing).
- Preserve explicit D-pad row/column targets and fixed card geometry. Avoid expensive beyond-bounds focus searches, per-focus catalog recomposition and full-screen gradient overdraw. Contrast is baked into cached backdrop bitmaps off the main thread. - Preserve explicit D-pad row/column targets and fixed card geometry. Avoid expensive beyond-bounds focus searches, per-focus catalog recomposition and full-screen gradient overdraw. Contrast is baked into cached backdrop bitmaps off the main thread.
- Give every Media3 session a unique ID: next-episode creation can overlap the old controller's disposal. Plex HLS position is absolute; **do not add the requested resume offset again**. - Give every Media3 session a unique ID: next-episode creation can overlap the old controller's disposal. Plex HLS position is absolute; **do not add the requested resume offset again**.
- Handle remote Back explicitly before default focus handling. Wait for menu focus restoration in tests instead of sending blind rapid button sequences. - Handle remote Back explicitly before default focus handling. Wait for menu focus restoration in tests instead of sending blind rapid button sequences.
- A text field keeps the D-pad: route Down/IME actions out of Search's field explicitly. Give every `focusRestorer()` a fallback, or it overrides explicit focus targets. Per-card modifiers on browse rows must be `Modifier.Node`s, not `composed {}`, and must not animate per card. - A text field keeps the D-pad: route Down/IME actions out of Search's field explicitly. Give every `focusRestorer()` a fallback, or it overrides explicit focus targets. Per-card modifiers on browse rows must be `Modifier.Node`s, not `composed {}`, and must not animate per card.
- Playback has one quality preference (`StreamQuality`): **Original quality** (the default) tries the original file, then Plex HLS, then a 1080p conversion if needed; 4K/1080p/720p/480p ask Plex to convert. A nonempty audio-only track list for a declared video must trigger fallback. Earlier preferences migrate on first read. Debug `testMode` still forces a delivery mode. Augment Plex's existing HEVC target; competing targets previously forced unnecessary conversion. A server copy decision does not prove rendering. Preserve the selected Plex tracks and check actual delivered formats. - Playback has one quality preference (`StreamQuality`): **Original quality** (the default) tries the original file, then Plex HLS, then a 1080p conversion if needed; 4K/1080p/720p/480p ask Plex to convert. A nonempty audio-only track list for a declared video must trigger fallback. Earlier preferences migrate on first read. Debug `testMode` still forces a delivery mode. Augment Plex's existing HEVC target; competing targets previously forced unnecessary conversion. A server copy decision does not prove rendering. Preserve the selected Plex tracks and check actual delivered formats.
- **ADB screenshots can omit HEVC video on this onn while the actual TV displays it. The user confirmed this.** Do not force transcoding based solely on a blank capture. `scripts/check_video.py` has a pixel assertion that can falsely fail for this reason; use playback logs/rendered-frame evidence and physical TV confirmation as appropriate. Never infer universal HDR/codec support from one test. - **ADB screenshots can omit HEVC video on this onn while the actual TV displays it. The user confirmed this.** Do not force transcoding based solely on a blank capture. `scripts/check_video.py` has a pixel assertion that can falsely fail for this reason; use playback logs/rendered-frame evidence and physical TV confirmation as appropriate. Never infer universal HDR/codec support from one test.
- Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them. - Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them. Automatic skips (Settings › Playback, 0 = button only) show "Skipping intro/credits" with a filling background rather than a number, count down only while playing, and are cancelled by any remote press (OK on the button skips now; Back only cancels).
- Theme tracks come from Plex metadata and inherit from the show for seasons/episodes. Stop music on video playback/background. Volume boost was removed because it degraded audio; keep passthrough and the normal audio path.
- A server-stopped session (Plex dashboard Stop) arrives as `terminationCode`/`terminationText` on the timeline response. Leave the player with the reason and never fall back or reconnect afterwards; timelines keep reporting `buffering` while a stream stalls so the stop is still noticed.
### Performance testing ### Performance testing
@ -96,6 +112,8 @@ The harness requires horizontal Y drift ≤3 px and frame-time p95 <40 ms. On 20
## Releases and further detail ## Releases and further detail
Use Semantic Versioning (`major.minor.patch`) for release names.
Updates come from `https://git.elijahkuntz.com/Elijah/Kaleido`. Keep the private `.tools/kaleido-signing.jks`; replacing it breaks in-place updates. `version.properties` is the version source. Before a requested release, increment version name/code, update `CHANGELOG.md`, build/test, and use `scripts/package_release.py`; the Forgejo workflow publishes matching version tags. Do not claim publication or updater installation was tested without verifying it. Updates come from `https://git.elijahkuntz.com/Elijah/Kaleido`. Keep the private `.tools/kaleido-signing.jks`; replacing it breaks in-place updates. `version.properties` is the version source. Before a requested release, increment version name/code, update `CHANGELOG.md`, build/test, and use `scripts/package_release.py`; the Forgejo workflow publishes matching version tags. Do not claim publication or updater installation was tested without verifying it.
See `docs/design-system.md` for the visual system and `docs/runtime-verification.md` for device evidence and limitations. Keep this file concise; put detailed investigation history there. See `docs/design-system.md` for the visual system and `docs/runtime-verification.md` for device evidence and limitations. Keep this file concise; put detailed investigation history there.

View file

@ -1,5 +1,79 @@
# Kaleido releases # Kaleido releases
## 0.8.1
- Fix a title page where Down from the buttons did nothing, leaving you stuck at the top. This happened when the Seasons, Cast or another row below had been scrolled away from its first card, for example by reopening a show from Continue Watching. Down now moves to a card in view.
## 0.8.0
- Replace the two countdowns at the end of an episode with one Up Next screen. When the credits start, the video shrinks into the top-left corner and keeps playing, beside the next episode's artwork, details, rating and synopsis, with the rest of the season and related shows below. Play next episode fills as it counts down, and pressing any button on the remote stops the countdown. Press Left and select the video, or press Back, to return to the credits.
- Update Continue Watching as soon as you leave the player, including an episode you have just started.
- Remove the label above the featured title on Home ("Recently released", "Suggested for you" and similar), as in Kaleido Desktop.
## 0.7.0
- Add a Previous episode button to the player, and redesign its controls: elapsed and remaining time at the ends of the timeline, previous episode, back 10 seconds, play, forward 30 seconds and next episode grouped in the centre, and the finish time beside Exit. Previous episode also steps back through a shuffle.
- Skip intros and credits automatically after a delay you choose in Settings › Playback (3, 5, 10 or 15 seconds, or show the button only). A pending skip reads "Skipping intro" with a filling background; pressing any button on the remote cancels it, and OK skips straight away. The earlier "Automatically" setting becomes a 5-second skip.
- Show what you watch on other devices promptly: Kaleido checks Continue Watching every 15 seconds while open and as soon as you return to it.
- Keep playback paused when you leave Kaleido while a stream is still starting, and only count down to the next episode while Kaleido is on screen.
- Keep the resume point when leaving a title before its stream has started, and keep progress reports on the server the title came from.
- Close Settings › Choose server with Back or the new Cancel button, and enter Home's rows from the Home tab when there is no featured title.
- Cancel slow network requests when they are no longer needed, and connect to the best server address as soon as it answers.
- Update a title's format badges when you pick another version, keep New Seasons when one show can't be loaded, and keep focus on Continue Watching when a card is replaced while a title page is open.
- Remove Volume boost, which degraded audio, and leave the player with the server's reason when a stream is stopped from the Plex dashboard.
## 0.6.2
- New startup animation, the same as Kaleido Desktop's: a kaleidoscope of shards turns and gathers into the Kaleido mark, then the view flies through its centre into Home.
## 0.6.1
- Make browsing noticeably smoother on Android TV hardware. Switching between Home, Movies and TV no longer rebuilds each section, returning to the hero or from a title page no longer redraws Home, and moving between rows prepares the next cards ahead of time instead of mid-scroll.
- Reduce the work done for accessibility services while browsing, which was the largest cost on devices running one (for example a Home-button remapper or TalkBack).
- Apply background library updates only after the remote has been still for a moment, so they no longer interrupt a move, and keep focus on a card when an update replaces it.
## 0.6.0
- Redesign Home after Silo. Moving into the rows compacts the hero into a preview of the focused card instead of scrolling it away: large title art, a rating badge, year, genre and runtime or time left, ratings, three lines of synopsis, cast and 4K/HDR/Atmos badges. Up or Back restores the hero.
- Show the focused card's own image in the top-right, scaled whole and fading into the page. Episodes show their own still instead of the show's artwork.
- Give Movies and TV the same preview above their rows.
- Fade between artwork, and fade and lift titles and descriptions between cards, instead of popping in. The hero's featured titles use the same transitions.
- Add Settings › Interface › Artwork colour wash (on by default), which tints the page with the focused artwork's colour.
- Redesign movie, show, season and episode pages to match: the same artwork and colour wash, title art, a facts line with rating and format badges, and a three-line synopsis. Season and episode pages follow the focused episode's still and details.
- Show title art, the rating badge and episode details in the player's controls.
## 0.5.0
- Show the selected version's source bitrate beside Original quality in the playback quality menu.
- Add a named Audio entry to Playback options alongside the speaker button. Preserve position, pause state and selected tracks when switching audio or rebuilding a Plex stream.
- Add Shuffle on TV show pages. Play episodes from all seasons in repeating shuffled cycles, starting each episode from the beginning and continuing even when ordinary autoplay is off. Seasons keep their usual Play action.
- Record sparse audio underrun and sink-error diagnostics for investigating intermittent dropouts. A short Infinity War check did not reproduce the reported stutter; a fix for that symptom is not yet confirmed.
## 0.4.1
- Make Categories about the genre: large centered labels over dim artwork with subdued natural color, a compact four-column grid and a restrained focus outline. Remove title captions and FILM/SERIES badges from category cards.
- Give every movie and TV category a distinct artwork source. Match overlapping genres together, preserve scarce choices, and fetch more candidates when needed instead of reusing a background.
## 0.4.0
- Frame TV show, season and episode background artwork against the full page, preserving the top of the scene instead of cropping it into a short season header, with no gap above the artwork.
- Redesign Movie and TV Categories with large artwork cards drawn from titles in each Plex genre, with clear remote focus and category return navigation.
- Show a brief animated direction and seconds cue when tapping Left or Right during playback. Repeated taps accumulate and holding still opens the timeline.
- Remove the broken in-app voice search button. Android TV keyboard voice input remains available. Add a Clear button that empties the query and results and returns focus to the search field.
## 0.3.1
- Fix episode pages getting stuck on Resume after scrolling the season row away from the original episode, returning Home, and reopening it from Continue Watching.
## 0.3.0
- Add Categories alongside Discover and Library in Movies and TV Shows. Browse the genres from the selected Plex library, with movies and shows kept separate.
- Add a light grey A–Z jump bar on the right of libraries and category results. Jump to letters with the remote, including titles beyond the first loaded page, and press Left to enter the titles.
- Put exact title matches first in Search, including the Silo series ahead of unrelated movie matches. Order result rows by relevance instead of always placing movies first.
- Add optional Plex theme music on movie, series, season and episode pages, with a separate volume setting. Music stops for playback and when Kaleido leaves the foreground; titles without theme tracks stay silent.
- Add an optional app-wide volume boost from +3 to +12 dB for all video playback. Boost uses decoded audio instead of compressed passthrough; Off preserves the original audio path.
- Remove repeated category headings in Settings and restore focus to preference controls after closing their dialogs.
## 0.2.1 ## 0.2.1
- Season and episode pages are one horizontal layout again. Moving along the season row shows that episode at the top, and selecting it or Play plays it, instead of opening another page with the same information. Back from playback returns to the episode you played. - Season and episode pages are one horizontal layout again. Moving along the season row shows that episode at the top, and selecting it or Play plays it, instead of opening another page with the same information. Back from playback returns to the episode you played.

View file

@ -10,7 +10,7 @@ A Plex client for Android TV, designed for browsing from the couch. Kaleido puts
- **Home** brings together featured titles, Plex recommendations and Continue Watching. Resume a movie or get back to your current series without digging through your library. - **Home** brings together featured titles, Plex recommendations and Continue Watching. Resume a movie or get back to your current series without digging through your library.
- **Movies** starts with recent releases and recommendations. **TV Shows** leads with your next episodes, new seasons and newly added episodes. - **Movies** starts with recent releases and recommendations. **TV Shows** leads with your next episodes, new seasons and newly added episodes.
- **Library** gives you an A–Z poster grid with genre, watched-status and sorting controls. If you have more than one movie or TV library, choose which one each section shows. - **Library** gives you an A–Z poster grid with watched-status and sorting controls; **Categories** browses by genre. If you have more than one movie or TV library, choose which one each section shows.
- **Search** finds movies, shows, episodes and people across your libraries. Type with the remote or search by voice. - **Search** finds movies, shows, episodes and people across your libraries. Type with the remote or search by voice.
- **Title pages** include ratings, a synopsis, trailers and extras, and cast portraits with character names. Select an actor to see their available movies and shows. Series pages put seasons first. Season and episode pages show the episode you move to in the season row; select it, or Play, to watch. - **Title pages** include ratings, a synopsis, trailers and extras, and cast portraits with character names. Select an actor to see their available movies and shows. Series pages put seasons first. Season and episode pages show the episode you move to in the season row; select it, or Play, to watch.
- **Quick actions**: hold OK (or press Menu) on any title to play, start over, mark it watched, remove it from Continue Watching, or jump to its season or show. - **Quick actions**: hold OK (or press Menu) on any title to play, start over, mark it watched, remove it from Continue Watching, or jump to its season or show.
@ -37,27 +37,35 @@ A manual server URL and token connection is also available. For future updates,
## Screenshots ## Screenshots
Captured from Kaleido **0.1.8** running on Android TV with a live Plex library. Select a screenshot to view it at full resolution. Captured from Kaleido **0.6.0** running on Android TV with a live Plex library. Select a screenshot to view it at full resolution.
**Home** — a cinematic feature with playback actions and integrated Continue Watching. **Home** — a cinematic feature with playback actions and integrated Continue Watching.
[![Kaleido Home with cinematic featured artwork and a Continue Watching row](docs/screenshots/home.webp)](docs/screenshots/home.webp) [![Kaleido Home with a cinematic featured title, playback actions and Continue Watching](docs/screenshots/home.webp)](docs/screenshots/home.webp)
Moving into the rows compacts the feature into a preview of the focused card, with its artwork, ratings, cast and formats.
[![Home rows with a compact preview of the focused Continue Watching card](docs/screenshots/home-rows.webp)](docs/screenshots/home-rows.webp)
| Movie discovery | TV discovery | | Movie discovery | TV discovery |
| --- | --- | | --- | --- |
| [![Movies with focused backdrop artwork, audience ratings, and recently released posters](docs/screenshots/movies.webp)](docs/screenshots/movies.webp) | [![TV shows with next-episode thumbnails and newly added seasons](docs/screenshots/tv.webp)](docs/screenshots/tv.webp) | | [![Movies with a preview of the focused poster, format badges and recently released titles](docs/screenshots/movies.webp)](docs/screenshots/movies.webp) | [![TV shows with a next-episode preview and wide episode thumbnails](docs/screenshots/tv.webp)](docs/screenshots/tv.webp) |
| Movie information and cast | TV show information and seasons | | Movie information and cast | TV show information and seasons |
| --- | --- | | --- | --- |
| [![Movie information with synopsis, ratings, watched controls and actor portraits](docs/screenshots/details.webp)](docs/screenshots/details.webp) | [![TV show information with a fitted poster, readable synopsis and Seasons first](docs/screenshots/show.webp)](docs/screenshots/show.webp) | | [![Movie information with title art, ratings, format badges, actions and cast](docs/screenshots/details.webp)](docs/screenshots/details.webp) | [![TV show information with Watch next, Shuffle episodes and seven seasons](docs/screenshots/show.webp)](docs/screenshots/show.webp) |
| Season episodes | Cast and related shows |
| --- | --- |
| [![Season page previewing the focused episode above the episode row](docs/screenshots/season.webp)](docs/screenshots/season.webp) | [![Show information with actor portraits and related series from Plex](docs/screenshots/related.webp)](docs/screenshots/related.webp) |
| A–Z library | Categories |
| --- | --- |
| [![Movie library with a six-column poster grid, genre filters, sorting and alphabet jumps](docs/screenshots/library.webp)](docs/screenshots/library.webp) | [![TV categories shown as artwork tiles for each genre](docs/screenshots/categories.webp)](docs/screenshots/categories.webp) |
| Actor filmography | Settings | | Actor filmography | Settings |
| --- | --- | | --- | --- |
| [![Actor page showing available movies and television series across Plex libraries](docs/screenshots/actors.webp)](docs/screenshots/actors.webp) | [![Settings category rail with playback quality and watched preferences](docs/screenshots/settings.webp)](docs/screenshots/settings.webp) | | [![Actor page showing available movies across Plex libraries](docs/screenshots/actors.webp)](docs/screenshots/actors.webp) | [![Interface settings with navigation sounds, theme music and the artwork colour wash](docs/screenshots/settings.webp)](docs/screenshots/settings.webp) |
| A–Z library | Cast and related shows |
| --- | --- |
| [![Movie library with a six-column poster grid, genre filters, and sorting](docs/screenshots/library.webp)](docs/screenshots/library.webp) | [![Show information with actor portraits and related series from Plex](docs/screenshots/related.webp)](docs/screenshots/related.webp) |
## Build from source ## Build from source

View file

@ -0,0 +1,62 @@
package tv.kaleido.app
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/** Read-only checks against the private server, including the same filters used by category jumps. */
@RunWith(AndroidJUnit4::class)
class BrowseAudioIntegrationTest {
private val app get()=InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as KaleidoApplication
private val api get()=app.api.apply { session=app.secure.load() }
@Test fun exactShowRanksAheadOfMetadataMovieMatch()=runBlocking {
val results=api.search("Silo")
assertEquals("Silo",searchGroups(results.titles,"Silo").first().second.first().title)
assertEquals("show",searchGroups(results.titles,"Silo").first().second.first().type)
}
@Test fun plexThemesAreInheritedAndPlayable()=runBlocking {
val show=api.details("6115")
val episode=api.details("7599")
assertTrue(show.theme.startsWith("/library/"))
assertEquals(show.theme,episode.theme)
val season=api.details(episode.parentId)
val inherited=season.theme.ifBlank { api.details(season.parentId).theme }
assertEquals(show.theme,inherited)
val request=okhttp3.Request.Builder().url(api.url(show.theme)).apply {
api.headers().filterKeys { it!="Accept" }.forEach { (k,v)->header(k,v) }
header("Range","bytes=0-1023")
}.build()
api.http.newCall(request).execute().use { response->
assertTrue(response.isSuccessful)
assertTrue(response.body!!.source().readByteArray(32).isNotEmpty())
}
val movie=Title.parse(JSONObject().put("type","movie").put("theme","/library/metadata/1/theme/2"))
assertEquals("/library/metadata/1/theme/2",movie.theme)
}
@Test fun letterCountsRespectCategoriesAndMediaType()=runBlocking {
for(section in api.sections().filter { it.type in listOf("movie","show") }) {
val type=plexLibraryType(section.type)
val genres=api.genres(section.id)
val genre=genres.firstOrNull { it.second=="Animation" } ?: genres.first()
for(unwatched in listOf(false,true)) {
val page=api.library(section.id,genre=genre.first,unwatched=unwatched,type=type)
val characters=api.firstCharacters(section.id,genre.first,unwatched,type)
assertEquals(page.total,characters.sumOf { it.size })
assertTrue(page.items.all { it.type==section.type })
val offsets=libraryCharacterOffsets(characters)
assertTrue(offsets.values.all { it in 0 until page.total })
val last=characters.lastOrNull { it.size>0 } ?: continue
val offset=offsets[last.title] ?: continue
val tail=api.library(section.id,start=offset,genre=genre.first,unwatched=unwatched,type=type)
assertEquals(last.size,tail.items.size)
}
}
}
}

View file

@ -30,6 +30,14 @@ class BrowsePolicyTest {
assertEquals(listOf("unknown1","unknown2","s1"),result.take(3).map{it.id}) assertEquals(listOf("unknown1","unknown2","s1"),result.take(3).map{it.id})
assertTrue(groupRecentSeasons(emptyList()){error("Empty row")}.isEmpty()) assertTrue(groupRecentSeasons(emptyList()){error("Empty row")}.isEmpty())
} }
@Test fun recentSeasonsSurviveOneUnavailableShow()=runBlocking {
val newest=title("s4","season").copy(parentId="gone",parentTitle="Missing",title="Season 4")
val older=title("s3","season").copy(parentId="gone",parentTitle="Missing",title="Season 3")
val other=title("s9","season").copy(parentId="show-c",parentTitle="Other",title="Season 9")
val result=groupRecentSeasons(listOf(newest,older,other)){throw PlexException("This item is no longer available.",404)}
assertEquals(listOf("s4","s9"),result.map{it.id})
assertEquals("Missing · Season 4",result.first().title)
}
@Test fun partiallyWatchedShowUsesEpisodeCountsEvenWithViewCount() { @Test fun partiallyWatchedShowUsesEpisodeCountsEvenWithViewCount() {
val show=Title.parse(JSONObject("""{"type":"show","viewCount":12,"leafCount":30,"viewedLeafCount":10}""")) val show=Title.parse(JSONObject("""{"type":"show","viewCount":12,"leafCount":30,"viewedLeafCount":10}"""))

View file

@ -0,0 +1,56 @@
package tv.kaleido.app
import android.content.Intent
import android.media.session.MediaSessionManager
import android.media.session.PlaybackState
import android.os.SystemClock
import androidx.lifecycle.ViewModelProvider
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.runBlocking
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
/** Opt-in real episode endings and Compose autoplay; validation mode never writes Plex progress. */
class PlaybackChangesIntegrationTest {
@Test fun shuffleContinuesAfterTwoNaturalEndingsWithNormalAutoplayOff()=runBlocking {
assumeTrue(InstrumentationRegistry.getArguments().getString("playbackChanges")=="true")
val instrumentation=InstrumentationRegistry.getInstrumentation()
val app=instrumentation.targetContext.applicationContext as KaleidoApplication
val show=app.api.details("6115")
val episodes=app.api.allEpisodes(show.id)
assertTrue(episodes.map{it.parentId}.distinct().size>1)
val activity=instrumentation.startActivitySync(Intent(app,MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
lateinit var vm:KaleidoViewModel
instrumentation.runOnMainSync{vm=ViewModelProvider(activity)[KaleidoViewModel::class.java]}
val oldCountdown=vm.autoplaySeconds
instrumentation.uiAutomation.adoptShellPermissionIdentity("android.permission.MEDIA_CONTENT_CONTROL")
try {
instrumentation.runOnMainSync{vm.chooseAutoplaySeconds(0);vm.playShuffled(show,validation=true)}
await{vm.playing!=null&&vm.shuffling}
val played=mutableSetOf<String>()
val manager=app.getSystemService(MediaSessionManager::class.java)
repeat(2) {
val current=vm.playing!!
assertTrue(episodes.any{it.id==current.id})
assertTrue("No repeat before exhausting the show",played.add(current.id))
assertTrue(vm.startFromZero)
await{manager.getActiveSessions(null).any{it.packageName==app.packageName&&it.playbackState?.state==PlaybackState.STATE_PLAYING}}
val controller=manager.getActiveSessions(null).first{it.packageName==app.packageName&&it.playbackState?.state==PlaybackState.STATE_PLAYING}
val duration=controller.metadata!!.getLong(android.media.MediaMetadata.METADATA_KEY_DURATION)
assertTrue(duration>5000)
controller.transportControls.seekTo(duration-4000)
await{vm.playing?.id!=current.id}
assertTrue(vm.shuffling)
}
assertFalse(played.contains(vm.playing!!.id))
} finally {
instrumentation.runOnMainSync{vm.chooseAutoplaySeconds(oldCountdown);vm.stopPlayback()}
instrumentation.uiAutomation.dropShellPermissionIdentity()
}
}
private fun await(check:()->Boolean) {
val deadline=SystemClock.elapsedRealtime()+60000
while(!check()){assertTrue("Playback transition timed out",SystemClock.elapsedRealtime()<deadline);SystemClock.sleep(200)}
}
}

View file

@ -8,8 +8,12 @@ HPLtv/kaleido/app/NavigationSoundsKt**->**(**)**
HPLtv/kaleido/app/NavigationSoundController;->**(**)** HPLtv/kaleido/app/NavigationSoundController;->**(**)**
HPLtv/kaleido/app/TitleDetailsKt**->**(**)** HPLtv/kaleido/app/TitleDetailsKt**->**(**)**
HPLtv/kaleido/app/SettingsScreenKt**->**(**)** HPLtv/kaleido/app/SettingsScreenKt**->**(**)**
HPLtv/kaleido/app/LibraryNavigationKt**->**(**)**
HPLtv/kaleido/app/ScreensKt**->**(**)** HPLtv/kaleido/app/ScreensKt**->**(**)**
HPLtv/kaleido/app/TitleActionsNode;->**(**)** HPLtv/kaleido/app/TitleActionsNode;->**(**)**
HPLtv/kaleido/app/TitleActionsElement;->**(**)** HPLtv/kaleido/app/TitleActionsElement;->**(**)**
HPLtv/kaleido/app/Title;->**(**)** HPLtv/kaleido/app/Title;->**(**)**
HPLtv/kaleido/app/Media;->**(**)** HPLtv/kaleido/app/Media;->**(**)**
HPLtv/kaleido/app/FramePrefetch;->**(**)**
HPLtv/kaleido/app/FramePrefetchKt;->**(**)**
HPLtv/kaleido/app/CacheWindows;->**(**)**

View file

@ -4,15 +4,24 @@ import android.graphics.Bitmap
import android.graphics.Canvas import android.graphics.Canvas
import android.graphics.LinearGradient import android.graphics.LinearGradient
import android.graphics.Paint import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Shader import android.graphics.Shader
import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.BitmapDrawable
import android.content.Context import android.content.Context
import androidx.compose.animation.Crossfade import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.animation.core.tween import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.* import androidx.compose.runtime.*
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
@ -24,10 +33,16 @@ import coil.request.ImageRequest
import coil.size.Size import coil.size.Size
import coil.transform.Transformation import coil.transform.Transformation
/** Bake contrast into the cached bitmap on Coil's worker thread, not two screen-sized GPU passes per frame. */ /**
private class BrowseContrast(val cinematic:Boolean):Transformation { * Bake contrast into the cached bitmap on Coil's worker thread, not two screen-sized GPU passes per frame.
override val cacheKey="kaleido-browse-contrast-v2-$cinematic" * [header] artwork is scaled whole into the top-right of a screen-sized frame and fades into the page
* toward its left and bottom edges, so the frame still crossfades like any other backdrop. With [wash],
* the page beneath carries the artwork's own colour, as Silo does, at no per-frame cost.
*/
private class BrowseContrast(val cinematic:Boolean,val header:Boolean,val wash:Boolean):Transformation {
override val cacheKey="kaleido-browse-contrast-v2-$cinematic"+if(header)"-header-corner4-$wash"else ""
override suspend fun transform(input:Bitmap,size:Size):Bitmap { override suspend fun transform(input:Bitmap,size:Size):Bitmap {
if(header)return headerFrame(input)
val output=input.copy(Bitmap.Config.ARGB_8888,true) val output=input.copy(Bitmap.Config.ARGB_8888,true)
val canvas=Canvas(output) val canvas=Canvas(output)
val paint=Paint(Paint.ANTI_ALIAS_FLAG) val paint=Paint(Paint.ANTI_ALIAS_FLAG)
@ -37,26 +52,96 @@ private class BrowseContrast(val cinematic:Boolean):Transformation {
canvas.drawRect(0f,0f,output.width.toFloat(),output.height.toFloat(),paint) canvas.drawRect(0f,0f,output.width.toFloat(),output.height.toFloat(),paint)
return output return output
} }
private fun headerFrame(input:Bitmap):Bitmap {
val output=Bitmap.createBitmap(960,540,Bitmap.Config.ARGB_8888)
val canvas=Canvas(output)
val width=output.width.toFloat();val height=output.height.toFloat()
canvas.drawColor(0xFF090909.toInt())
if(wash) {
// Richest behind the art (top-right), carried dimmer toward the rows (bottom-left).
val tint=ambientTint(input) and 0xFFFFFF
val paint=Paint()
paint.shader=LinearGradient(width,0f,0f,height,intArrayOf(0xFF shl 24 or tint,0x80 shl 24 or tint,0x2E shl 24 or tint),floatArrayOf(0f,.45f,1f),Shader.TileMode.CLAMP)
canvas.drawRect(0f,0f,width,height,paint)
}
// Whole pixels: a fractional edge left a faint seam beside the fade.
val art=RectF((width*(1f-HeaderArtWidth)).toInt().toFloat(),0f,width,(height*HeaderArtHeight).toInt().toFloat())
// The art gets its own layer, so its fading edges reveal the page (or wash) beneath.
val layer=canvas.saveLayer(art,null)
// Centre-crop only the small difference between the image's and the box's proportions.
val scale=maxOf(art.width()/input.width,art.height()/input.height)
val cropWidth=art.width()/scale;val cropHeight=art.height()/scale
val left=((input.width-cropWidth)/2f).toInt();val top=((input.height-cropHeight)/2f).toInt()
canvas.drawBitmap(input,Rect(left,top,left+cropWidth.toInt(),top+cropHeight.toInt()),art,Paint(Paint.FILTER_BITMAP_FLAG))
val mask=Paint().apply{xfermode=PorterDuffXfermode(PorterDuff.Mode.DST_IN)}
mask.shader=LinearGradient(art.left,0f,art.right,0f,intArrayOf(0,0x4D000000,0xFF000000.toInt()),floatArrayOf(0f,.2f,.5f),Shader.TileMode.CLAMP)
canvas.drawRect(art,mask)
mask.shader=LinearGradient(0f,art.top,0f,art.bottom,intArrayOf(0xFF000000.toInt(),0xFF000000.toInt(),0x4D000000,0),floatArrayOf(0f,.45f,.8f,1f),Shader.TileMode.CLAMP)
canvas.drawRect(art,mask)
canvas.restoreToCount(layer)
return output
}
} }
internal fun browseBackdropRequest(context:Context,api:PlexApi,path:String,cinematic:Boolean):ImageRequest? = /**
* The artwork's average colour at a fixed, low luminance (as Silo and tvOS do): bright art is dimmed
* and dark art lifted, giving a subtle, consistent tint over the near-black page.
*/
private fun ambientTint(input:Bitmap):Int {
val sample=Bitmap.createScaledBitmap(input,32,18,true)
val pixels=IntArray(sample.width*sample.height).also{sample.getPixels(it,0,sample.width,0,0,sample.width,sample.height)}
if(sample!==input)sample.recycle()
var r=0.0;var g=0.0;var b=0.0
for(pixel in pixels){r+=(pixel shr 16 and 0xFF);g+=(pixel shr 8 and 0xFF);b+=(pixel and 0xFF)}
r/=pixels.size*255.0;g/=pixels.size*255.0;b/=pixels.size*255.0
val luminance=.2126*r+.7152*g+.0722*b
val scale=when{luminance<=.001->0.0;luminance>.22->.22/luminance;else->maxOf(1.0,.22/maxOf(luminance,.05))}
fun channel(value:Double)=(value*scale*255).toInt().coerceIn(0,255)
return android.graphics.Color.rgb(channel(r),channel(g),channel(b))
}
/** The preview artwork box (Home, Movies, TV), as fractions of the screen; close to 16:9, so stills and art show whole. */
private const val HeaderArtWidth=.72f
private const val HeaderArtHeight=.78f
/** Old and new artwork overlap briefly instead of the new one popping in. */
internal const val ArtworkFadeMillis=320
internal fun browseBackdropRequest(context:Context,api:PlexApi,path:String,cinematic:Boolean,header:Boolean=false,wash:Boolean=false):ImageRequest? =
api.image(path,if(cinematic)1280 else 960,if(cinematic)720 else 540)?.let{url-> api.image(path,if(cinematic)1280 else 960,if(cinematic)720 else 540)?.let{url->
ImageRequest.Builder(context).data(url).apply{api.headers().forEach{(k,v)->addHeader(k,v)}} ImageRequest.Builder(context).data(url).apply{api.headers().forEach{(k,v)->addHeader(k,v)}}
.size(if(cinematic)1280 else 960,if(cinematic)720 else 540).allowHardware(false) .size(if(cinematic)1280 else 960,if(cinematic)720 else 540).allowHardware(false)
.transformations(BrowseContrast(cinematic)).crossfade(false).build() .transformations(BrowseContrast(cinematic,header&&!cinematic,wash)).crossfade(false).build()
} }
@Composable internal fun BrowseBackdrop(api:PlexApi,path:String,modifier:Modifier,cinematic:Boolean=false,animate:Boolean=false) { /** The new artwork fades in over the old one; only its layer alpha changes per frame. */
@Composable private fun FadingArtwork(bitmap:Bitmap?,modifier:Modifier,contentScale:ContentScale,alignment:Alignment) {
val progress=remember{Animatable(1f)}
var shown by remember{mutableStateOf<Bitmap?>(null)}
var under by remember{mutableStateOf<Bitmap?>(null)}
LaunchedEffect(bitmap) {
if(bitmap==null||bitmap===shown)return@LaunchedEffect
under=shown;shown=bitmap
progress.snapTo(0f);progress.animateTo(1f,tween(ArtworkFadeMillis,easing=FastOutSlowInEasing))
under=null
}
Box(modifier) {
under?.let{Image(remember(it){it.asImageBitmap()},null,contentScale=contentScale,alignment=alignment,modifier=Modifier.fillMaxSize())}
shown?.let{Image(remember(it){it.asImageBitmap()},null,contentScale=contentScale,alignment=alignment,modifier=Modifier.fillMaxSize().graphicsLayer{
compositingStrategy=CompositingStrategy.ModulateAlpha;alpha=progress.value
})}
}
}
@Composable internal fun BrowseBackdrop(api:PlexApi,path:String,modifier:Modifier,cinematic:Boolean=false,header:Boolean=false,wash:Boolean=false,animate:Boolean=false,alignment:Alignment=Alignment.Center,contentScale:ContentScale=ContentScale.Crop) {
val context=LocalContext.current val context=LocalContext.current
var previous by remember{mutableStateOf<MemoryCache.Key?>(null)} var previous by remember{mutableStateOf<MemoryCache.Key?>(null)}
val request=remember(path,api.session?.server,cinematic,animate){browseBackdropRequest(context,api,path,cinematic)?.newBuilder()?.placeholderMemoryCacheKey(previous)?.build()} val request=remember(path,api.session?.server,cinematic,header,wash,animate){browseBackdropRequest(context,api,path,cinematic,header,wash)?.newBuilder()?.placeholderMemoryCacheKey(previous)?.build()}
if(animate) { if(animate) {
// Animate cache hits too; Coil intentionally skips its own crossfade for memory-cache results. // Animate cache hits too; Coil intentionally skips its own crossfade for memory-cache results.
val bitmap by produceState<Bitmap?>(null,request){ val bitmap by produceState<Bitmap?>(null,request){
if(request!=null){val result=context.imageLoader.execute(request);if(result is SuccessResult){previous=result.memoryCacheKey;value=(result.drawable as? BitmapDrawable)?.bitmap}} if(request!=null){val result=context.imageLoader.execute(request);if(result is SuccessResult){previous=result.memoryCacheKey;value=(result.drawable as? BitmapDrawable)?.bitmap}}
} }
Crossfade(bitmap,modifier=modifier,animationSpec=tween(220),label="heroArtwork"){loaded-> FadingArtwork(bitmap,modifier,contentScale,alignment)
loaded?.let{Image(it.asImageBitmap(),null,contentScale=ContentScale.Crop,modifier=Modifier.fillMaxSize())} }else AsyncImage(request,contentDescription=null,modifier=modifier,contentScale=contentScale,alignment=alignment,onSuccess={previous=it.result.memoryCacheKey})
}
}else AsyncImage(request,contentDescription=null,modifier=modifier,contentScale=ContentScale.Crop,onSuccess={previous=it.result.memoryCacheKey})
} }

View file

@ -26,6 +26,8 @@ import androidx.compose.ui.geometry.Size
import androidx.compose.ui.focus.* import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.* import androidx.compose.ui.input.key.*
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
@ -33,8 +35,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import androidx.activity.compose.rememberLauncherForActivityResult import kotlinx.coroutines.flow.first
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
@ -77,10 +78,10 @@ import androidx.compose.ui.text.input.TextFieldValue
if(navigation!=null&&it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){ if(navigation!=null&&it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
pendingTab[0]?.cancel() pendingTab[0]?.cancel()
val target=focusedTab[0] val target=focusedTab[0]
if(vm.page.kind!=target){navigation.pendingEntry=target;vm.tab(target);vm.focusId=if(target=="home")"home-feature"else "discovery-entry"}else navigation.enter?.invoke() if(vm.page.kind!=target){navigation.pendingEntry=target;vm.tab(target);vm.focusId=if(target=="home")"home-feature"else "discovery-entry"}else navigation.of(target).enter?.invoke()
true true
}else false }else false
}.focusProperties{if(navigation!=null)down=navigation.entry},horizontalArrangement=Arrangement.spacedBy(16.dp),verticalAlignment=Alignment.CenterVertically) { }.focusProperties{if(navigation!=null)down=navigation.of(vm.page.kind).entry},horizontalArrangement=Arrangement.spacedBy(16.dp),verticalAlignment=Alignment.CenterVertically) {
listOf("home" to "Home","movies" to "Movies","tv" to "TV Shows").forEach{(kind,label)-> listOf("home" to "Home","movies" to "Movies","tv" to "TV Shows").forEach{(kind,label)->
NavigationLabel(label,vm.page.kind==kind,modifier=if(navigation!=null&&vm.page.kind==kind)Modifier.focusRequester(navigation.top)else Modifier,initialFocus=vm.page.kind==kind&&initialFocus,onFocused={ NavigationLabel(label,vm.page.kind==kind,modifier=if(navigation!=null&&vm.page.kind==kind)Modifier.focusRequester(navigation.top)else Modifier,initialFocus=vm.page.kind==kind&&initialFocus,onFocused={
focusedTab[0]=kind focusedTab[0]=kind
@ -107,14 +108,32 @@ import androidx.compose.ui.text.input.TextFieldValue
val initial=remember(rowId){items.indexOfFirst{it.id==initialItem}.coerceAtLeast(0)} val initial=remember(rowId){items.indexOfFirst{it.id==initialItem}.coerceAtLeast(0)}
val entry=items.indexOfFirst{it.id==selectedItem}.takeIf{it>=0} ?: initial val entry=items.indexOfFirst{it.id==selectedItem}.takeIf{it>=0} ?: initial
val row=rememberLazyListState(initialFirstVisibleItemIndex=(initial-1).coerceAtLeast(0)) val row=rememberLazyListState(initialFirstVisibleItemIndex=(initial-1).coerceAtLeast(0))
// A reopened episode page resets its selection, but its saved scroll can still
// point elsewhere. Compose the entry card before the header sends focus Down.
LaunchedEffect(rowId){if(initialItem!=null)row.scrollToItem((initial-1).coerceAtLeast(0))}
val entryIndex=if(entryFocus!=null)rememberRowEntry(row,entry).value else -1
Column { Column {
Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading(title,subtitle)} Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading(title,subtitle)}
LazyRow(state=row,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=5.dp,bottom=5.dp),horizontalArrangement=Arrangement.spacedBy(if(landscape)13.dp else 12.dp),modifier=Modifier.focusRestorer(fallback=entryFocus ?: FocusRequester.Default)) { LazyRow(state=row,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=5.dp,bottom=5.dp),horizontalArrangement=Arrangement.spacedBy(if(landscape)13.dp else 12.dp),modifier=Modifier.focusRestorer(fallback=entryFocus ?: FocusRequester.Default)) {
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,modifier=(if(index==entry&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier).then(if(up!=null)Modifier.focusProperties{this.up=up}else Modifier),onMove={anticipateTileMove(vm,items,index,it,0)},episodeTitle=episodeTitles,current=item.id==selectedItem,onFocused=onFocused,onClick=onClick)} itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,modifier=(if(index==entryIndex&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier).then(if(up!=null)Modifier.focusProperties{this.up=up}else Modifier),onMove={anticipateTileMove(vm,items,index,it,0)},episodeTitle=episodeTitles,current=item.id==selectedItem,onFocused=onFocused,onClick=onClick)}
} }
} }
} }
/**
* The card a row is entered at from above: [preferred] while it is in view, otherwise the first
* card fully in view. A card scrolled out of a lazy row (e.g. a restored or scrolled Seasons row)
* is not composed, so an explicit focus move to its requester fails and strands focus above.
*/
internal fun rowEntryIndex(preferred:Int,visible:List<LazyListItemInfo>,viewportStart:Int):Int {
if(visible.isEmpty()||visible.any{it.index==preferred})return preferred
return (visible.firstOrNull{it.offset>=viewportStart} ?: visible.first()).index
}
/** [rowEntryIndex], updated only when a card enters or leaves the row's view. */
@Composable internal fun rememberRowEntry(row:LazyListState,preferred:Int):State<Int> =
remember(row,preferred){derivedStateOf{row.layoutInfo.let{rowEntryIndex(preferred,it.visibleItemsInfo,it.viewportStartOffset)}}}
internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) { internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
val target=when(direction){ val target=when(direction){
Key.DirectionLeft->if(columns==0||index%columns>0)index-1 else -1 Key.DirectionLeft->if(columns==0||index%columns>0)index-1 else -1
@ -149,71 +168,118 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
} }
@Composable fun LibraryScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation) { @Composable fun LibraryScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation) {
if(!vm.allTitles){DiscoveryScreen(vm,home=false,navigation=navigation);return} // Discover is a retained DiscoveryScreen (see KaleidoApp); this is only the A–Z library.
if(!vm.allTitles)return
val name=if(vm.page.kind=="movies")"Movies"else "TV Shows" val name=if(vm.page.kind=="movies")"Movies"else "TV Shows"
LaunchedEffect(vm.categories,vm.section?.id,vm.genres){vm.loadCategoryArtworks()}
var sortMenu by remember{mutableStateOf(false)} var sortMenu by remember{mutableStateOf(false)}
var genreMenu by remember{mutableStateOf(false)}
var sectionMenu by remember{mutableStateOf(false)} var sectionMenu by remember{mutableStateOf(false)}
// Without explicit links, Right from Library searches upward and lands on (and opens) Home. val discoverFocus=remember{FocusRequester()};val libraryFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()}
val libraryFocus=remember{FocusRequester()};val filterFocus=remember{FocusRequester()} val filterFocus=remember{FocusRequester()};val categoryEntryFocus=remember{FocusRequester()};val railFocus=remember{FocusRequester()};val sectionFocus=remember{FocusRequester()}
val filters=vm.section!=null||vm.busy val filters=vm.section!=null||vm.busy
Column(Modifier.fillMaxSize()) { Column(Modifier.fillMaxSize()) {
Row(Modifier.fillMaxWidth().height(64.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) { Row(Modifier.fillMaxWidth().height(64.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) {
Text(name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp) Text(name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)
Spacer(Modifier.width(21.dp)) Spacer(Modifier.width(21.dp))
NavigationLabel("Discover",!vm.allTitles){vm.setAll(false)} NavigationLabel("Discover",!vm.allTitles,modifier=Modifier.focusRequester(discoverFocus).focusProperties{right=libraryFocus},onClick={vm.setAll(false)})
NavigationLabel("Library",vm.allTitles,modifier=Modifier.focusRequester(libraryFocus).focusProperties{right=if(filters)filterFocus else FocusRequester.Cancel},initialFocus=vm.focusId=="library-entry"){vm.setAll(true)} NavigationLabel("Library",!vm.categories,modifier=Modifier.focusRequester(libraryFocus).focusProperties{right=categoriesFocus;down=if(filters)filterFocus else FocusRequester.Cancel},initialFocus=vm.focusId=="library-entry"){vm.setAll(true)}
NavigationLabel("Categories",vm.categories,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{right=if(vm.sections.count{it.type==vm.section?.type}>1)sectionFocus else FocusRequester.Cancel;down=if(vm.categories&&vm.genre.isBlank())categoryEntryFocus else if(filters)filterFocus else FocusRequester.Cancel}){vm.openCategories()}
Spacer(Modifier.weight(1f)) Spacer(Modifier.weight(1f))
if(vm.sections.count{it.type==vm.section?.type}>1)TvButton(vm.section?.title ?: "Library"){sectionMenu=true} if(vm.sections.count{it.type==vm.section?.type}>1)TvButton(vm.section?.title ?: "Library",Modifier.focusRequester(sectionFocus).focusProperties{left=categoriesFocus}){sectionMenu=true}
else if(!vm.allTitles)Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp)
} }
if(!filters)EmptyState("No $name library","This server has no matching library.") if(vm.categories&&vm.genre.isBlank()) {
if(vm.section==null)EmptyState("No $name library","This server has no matching library.")
else if(vm.genres.isEmpty()&&vm.busy)Text("Loading categories…",color=Muted,fontSize=13.sp,modifier=Modifier.padding(start=Cinema.gutter,top=24.dp))
else if(vm.genres.isEmpty())EmptyState("No categories available","This Plex library has no genre categories.")
else {
val categoryRequesters=remember(vm.section?.id,vm.genres,categoryEntryFocus){vm.genres.mapIndexed{i,entry->entry.first to if(i==0)categoryEntryFocus else FocusRequester()}.toMap()}
val categoryColor=remember{ColorFilter.colorMatrix(ColorMatrix().apply{setToSaturation(.65f)})}
LazyVerticalGrid(GridCells.Fixed(4),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=18.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(13.dp),modifier=Modifier.fillMaxSize()) {
itemsIndexed(vm.genres,key={_,it->it.first}){index,entry->
val requester=categoryRequesters.getValue(entry.first)
val sample=vm.categoryArtwork[entry.first]
val artworkPath=sample?.let{it.art.ifBlank{it.thumb}}.orEmpty()
var focused by remember(entry.first,vm.section?.id){mutableStateOf(false)}
val shape=RoundedCornerShape(Cinema.radius)
Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).focusRequester(requester).focusProperties {
left=if(index%4==0)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index-1].first)
right=if(index%4==3||index==vm.genres.lastIndex)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+1].first)
up=if(index<4)categoriesFocus else categoryRequesters.getValue(vm.genres[index-4].first)
down=if(index+4>=vm.genres.size)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+4].first)
}.onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId="category:${entry.first}"}.navigationSound().clip(shape).background(Color(0xFF171717)).border(if(focused)2.dp else 1.dp,Color.White.copy(alpha=if(focused).9f else .1f),shape).clickable{vm.selectCategory(entry.first)}) {
if(artworkPath.isNotBlank())Artwork(vm.api,artworkPath,Modifier.fillMaxSize(),540,304,colorFilter=categoryColor)
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha=if(focused).48f else .62f)))
Text(entry.second,color=Color.White,fontSize=22.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,maxLines=2,overflow=TextOverflow.Ellipsis,textAlign=androidx.compose.ui.text.style.TextAlign.Center,
style=LocalTextStyle.current.copy(shadow=androidx.compose.ui.graphics.Shadow(Color.Black,androidx.compose.ui.geometry.Offset(0f,1f),5f)),modifier=Modifier.align(Alignment.Center).fillMaxWidth().padding(horizontal=16.dp))
}
LaunchedEffect(vm.focusId,index){if((vm.focusId=="categories-entry"&&index==0)||vm.focusId=="category:${entry.first}"){withFrameNanos{};runCatching{requester.requestFocus()}}}
}
}
}
} else if(!filters)EmptyState("No $name library","This server has no matching library.")
else { else {
Row(Modifier.fillMaxWidth().height(43.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(8.dp)) { Row(Modifier.fillMaxWidth().height(43.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(8.dp)) {
Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp) Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp)
Spacer(Modifier.weight(1f)) Spacer(Modifier.weight(1f))
TvButton((if(vm.genre.isBlank())"All genres"else vm.genres.firstOrNull{it.first==vm.genre}?.second ?: "Genre")+" ⌄",Modifier.focusRequester(filterFocus).focusProperties{left=libraryFocus}){genreMenu=true} TvButton(if(vm.unwatched)"Unwatched ✓"else "Unwatched",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus},selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)}
TvButton(if(vm.unwatched)"Unwatched ✓"else "Unwatched",selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)}
TvButton((sortLabels.firstOrNull{it.first==vm.sort}?.second ?: "Title: A–Z")+" ⌄",Modifier.focusProperties{right=FocusRequester.Cancel}){sortMenu=true} TvButton((sortLabels.firstOrNull{it.first==vm.sort}?.second ?: "Title: A–Z")+" ⌄",Modifier.focusProperties{right=FocusRequester.Cancel}){sortMenu=true}
} }
val grid=rememberLazyGridState() val grid=rememberLazyGridState()
val tileRequesters=remember{mutableMapOf<String,FocusRequester>()}
val scope=rememberCoroutineScope()
val enabledLetters=remember{LibraryJumpLetters.toSet()}
LaunchedEffect(grid,vm.library.size,vm.total){snapshotFlow{grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0}.collect{if(it>=vm.library.size-18&&vm.library.isNotEmpty())vm.more()}} LaunchedEffect(grid,vm.library.size,vm.total){snapshotFlow{grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0}.collect{if(it>=vm.library.size-18&&vm.library.isNotEmpty())vm.more()}}
LazyVerticalGrid(GridCells.Fixed(6),state=grid,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=10.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) { LaunchedEffect(vm.libraryJumpRequest){
itemsIndexed(vm.library,key={_,it->it.id}){index,item->MediaTile(vm,item,"library:${item.id}",fillWidth=true,onMove={anticipateTileMove(vm,vm.library,index,it,6)})} val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size} ?: return@LaunchedEffect
if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another genre or watch filter.")} grid.scrollToItem(index)
}
LaunchedEffect(vm.libraryFocusRequest){
val itemId=vm.focusId.removePrefix("library:").takeIf{vm.focusId.startsWith("library:")}
val index=itemId?.let{id->vm.library.indexOfFirst{it.id==id}}?.takeIf{it>=0}
?: if(vm.focusId=="category-grid"&&!vm.busy&&vm.library.isNotEmpty())0 else -1
if(index>=0){
grid.scrollToItem(index)
snapshotFlow{grid.layoutInfo.visibleItemsInfo.any{it.index==index}}.first{it}
withFrameNanos{}
tileRequesters[vm.library[index].id]?.requestFocus()
}
}
suspend fun returnFocusToGrid(){
val itemId=vm.focusId.removePrefix("library:").takeIf{vm.focusId.startsWith("library:")}
val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size}
?: itemId?.let{id->vm.library.indexOfFirst{it.id==id}}?.takeIf{it>=0} ?: 0
if(vm.library.isNotEmpty()){
grid.scrollToItem(index)
snapshotFlow{grid.layoutInfo.visibleItemsInfo.any{it.index==index}}.first{it}
withFrameNanos{}
tileRequesters[vm.library[index].id]?.requestFocus()
}
}
Row(Modifier.fillMaxWidth().weight(1f),horizontalArrangement=Arrangement.spacedBy(7.dp),verticalAlignment=Alignment.Top) {
LazyVerticalGrid(GridCells.Fixed(6),state=grid,contentPadding=PaddingValues(start=Cinema.gutter,end=5.dp,top=10.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.weight(1f)) {
itemsIndexed(vm.library,key={_,it->it.id}){index,item->
val requester=tileRequesters.getOrPut(item.id){FocusRequester()}
val lastColumn=index%6==5||index==vm.library.lastIndex
MediaTile(vm,item,"library:${item.id}",fillWidth=true,modifier=Modifier.focusRequester(requester).then(if(lastColumn)Modifier.focusProperties{right=railFocus}else Modifier),onMove={anticipateTileMove(vm,vm.library,index,it,6)},onFocused={vm.onLibraryGridFocused()})
}
if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another category or watch filter.")}
if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}} if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}}
} }
LibraryJumpRail(enabledLetters,vm.libraryJumpLetter,railFocus,{scope.launch{runCatching{ returnFocusToGrid() }}},{vm.jumpToLibraryLetter(it)})
}
} }
} }
if(sortMenu)ChoiceDialog("Sort by",sortLabels.map{it.second},sortLabels.indexOfFirst{it.first==vm.sort},{sortMenu=false}){vm.filter(sortValue=sortLabels[it].first);sortMenu=false} if(sortMenu)ChoiceDialog("Sort by",sortLabels.map{it.second},sortLabels.indexOfFirst{it.first==vm.sort},{sortMenu=false}){vm.filter(sortValue=sortLabels[it].first);sortMenu=false}
if(genreMenu)ChoiceDialog("Genres",listOf("All genres")+vm.genres.map{it.second},vm.genres.indexOfFirst{it.first==vm.genre}+1,{genreMenu=false}){vm.filter(genreValue=if(it==0)""else vm.genres[it-1].first);genreMenu=false}
if(sectionMenu){val options=vm.sections.filter{it.type==vm.section?.type};ChoiceDialog("Libraries",options.map{it.title},options.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(options[it]);sectionMenu=false}} if(sectionMenu){val options=vm.sections.filter{it.type==vm.section?.type};ChoiceDialog("Libraries",options.map{it.title},options.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(options[it]);sectionMenu=false}}
} }
@Composable fun SearchScreen(vm:KaleidoViewModel) { @Composable fun SearchScreen(vm:KaleidoViewModel) {
val field=remember{FocusRequester()};val resultsFocus=remember{FocusRequester()};val micFocus=remember{FocusRequester()} val field=remember{FocusRequester()};val resultsFocus=remember{FocusRequester()};val clearFocus=remember{FocusRequester()}
val keyboard=LocalSoftwareKeyboardController.current val keyboard=LocalSoftwareKeyboardController.current
val context=LocalContext.current
var value by remember{mutableStateOf(TextFieldValue(vm.query,TextRange(vm.query.length)))} var value by remember{mutableStateOf(TextFieldValue(vm.query,TextRange(vm.query.length)))}
fun query(text:String){value=TextFieldValue(text,TextRange(text.length));vm.search(text)} fun query(text:String){value=TextFieldValue(text,TextRange(text.length));vm.search(text)}
val voiceIntent=remember{android.content.Intent(android.speech.RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
.putExtra(android.speech.RecognizerIntent.EXTRA_LANGUAGE_MODEL,android.speech.RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
.putExtra(android.speech.RecognizerIntent.EXTRA_PROMPT,"Search your Plex libraries")}
// Fire TV and some TVs have no speech recognizer for apps; hide the microphone there. Google TV
// offers its TV voice input and a speech service: prefer the TV one rather than show a chooser.
val canSpeak=remember{
val recognizers=context.packageManager.queryIntentActivities(voiceIntent,0).map{it.activityInfo.packageName}.distinct()
(listOf("com.google.android.katniss","com.google.android.googlequicksearchbox").firstOrNull{it in recognizers} ?: recognizers.firstOrNull().takeIf{recognizers.size==1})
?.let{voiceIntent.setPackage(it)}
recognizers.isNotEmpty()
}
val voice=rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()){result->
result.data?.getStringArrayListExtra(android.speech.RecognizerIntent.EXTRA_RESULTS)?.firstOrNull()?.takeIf{it.isNotBlank()}?.let{query(it);runCatching{field.requestFocus()}}
}
fun listen(){keyboard?.hide();runCatching{voice.launch(voiceIntent)}}
LaunchedEffect(vm.voicePending){if(vm.voicePending){vm.voiceStarted();if(canSpeak)listen()}}
LaunchedEffect(vm.query){if(vm.query!=value.text)value=TextFieldValue(vm.query,TextRange(vm.query.length))} LaunchedEffect(vm.query){if(vm.query!=value.text)value=TextFieldValue(vm.query,TextRange(vm.query.length))}
val groups=remember(vm.searchResults){searchGroups(vm.searchResults.titles)} val groups=remember(vm.searchResults,vm.query){searchGroups(vm.searchResults.titles,vm.query)}
val people=vm.searchResults.people val people=vm.searchResults.people
val hasResults=groups.isNotEmpty()||people.isNotEmpty() val hasResults=groups.isNotEmpty()||people.isNotEmpty()
fun enterResults(){keyboard?.hide();runCatching{resultsFocus.requestFocus()}} fun enterResults(){keyboard?.hide();runCatching{resultsFocus.requestFocus()}}
@ -224,18 +290,20 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
LaunchedEffect(Unit){if(!vm.focusId.startsWith("search-")){delay(150);runCatching{field.requestFocus()}}} LaunchedEffect(Unit){if(!vm.focusId.startsWith("search-")){delay(150);runCatching{field.requestFocus()}}}
OutlinedTextField(value,{value=it;if(it.text!=vm.query)vm.search(it.text)},placeholder={Text("Movies, shows, episodes, people",fontSize=12.sp)},leadingIcon={Icon(Icons.Outlined.Search,null,Modifier.size(19.dp))},singleLine=true, OutlinedTextField(value,{value=it;if(it.text!=vm.query)vm.search(it.text)},placeholder={Text("Movies, shows, episodes, people",fontSize=12.sp)},leadingIcon={Icon(Icons.Outlined.Search,null,Modifier.size(19.dp))},singleLine=true,
keyboardOptions=KeyboardOptions(imeAction=ImeAction.Search),keyboardActions=KeyboardActions(onSearch={if(hasResults)enterResults()else keyboard?.hide()}), keyboardOptions=KeyboardOptions(imeAction=ImeAction.Search),keyboardActions=KeyboardActions(onSearch={if(hasResults)enterResults()else keyboard?.hide()}),
// A text field keeps the D-pad for its cursor: Down enters the results, Right at the end reaches the microphone. // Down enters results; Right at the end reaches Clear without deleting character by character.
modifier=Modifier.weight(1f).height(49.dp).focusRequester(field).onPreviewKeyEvent{ modifier=Modifier.weight(1f).height(49.dp).focusRequester(field).onPreviewKeyEvent{
if(it.type!=KeyEventType.KeyDown)false if(it.type!=KeyEventType.KeyDown)false
else if(it.key==Key.DirectionDown){if(hasResults)enterResults()else if(canSpeak)runCatching{micFocus.requestFocus()};true} else if(it.key==Key.DirectionDown){if(hasResults)enterResults()else if(value.text.isNotEmpty()){keyboard?.hide();runCatching{clearFocus.requestFocus()}};true}
else if(it.key==Key.DirectionRight&&canSpeak&&value.selection.collapsed&&value.selection.end==value.text.length){runCatching{micFocus.requestFocus()};true} else if(it.key==Key.DirectionRight&&value.text.isNotEmpty()&&value.selection.collapsed&&value.selection.end==value.text.length){keyboard?.hide();runCatching{clearFocus.requestFocus()};true}
else false else false
},shape=RoundedCornerShape(6.dp),textStyle=androidx.compose.ui.text.TextStyle(fontSize=13.sp),colors=OutlinedTextFieldDefaults.colors(unfocusedBorderColor=Color.White.copy(alpha=.15f),focusedBorderColor=Accent)) },shape=RoundedCornerShape(6.dp),textStyle=androidx.compose.ui.text.TextStyle(fontSize=13.sp),colors=OutlinedTextFieldDefaults.colors(unfocusedBorderColor=Color.White.copy(alpha=.15f),focusedBorderColor=Accent))
if(canSpeak)IconControl(Icons.Outlined.Mic,"Voice search",requester=micFocus,modifier=Modifier.focusProperties{left=field;if(hasResults)down=resultsFocus}){listen()} if(value.text.isNotEmpty())ActionButton("Clear",Icons.Outlined.Close,modifier=Modifier.focusRequester(clearFocus).focusProperties{left=field;if(hasResults)down=resultsFocus}){
Text(if(vm.query.isBlank())"Your collection"else (vm.searchResults.titles.size+people.size).let{if(it==1)"1 result" else "$it results"},color=Muted,fontSize=11.sp) // Move focus before removing this button from the composition.
runCatching{field.requestFocus()};query("")
} }
if(vm.query.isBlank())Text(if(canSpeak)"Type, or select the microphone to search by voice."else "Find something worth watching.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(start=Cinema.gutter,top=8.dp)) if(vm.query.isNotBlank())Text((vm.searchResults.titles.size+people.size).let{if(it==1)"1 result" else "$it results"},color=Muted,fontSize=11.sp)
else if(!hasResults&&!vm.busy)Text("No matches for “${vm.query}”.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(start=Cinema.gutter,top=8.dp)) }
if(vm.query.isNotBlank()&&!hasResults&&!vm.busy)Text("No matches for “${vm.query}”.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(start=Cinema.gutter,top=8.dp))
// Grouped rows, like Home: Movies, TV shows, collections, episodes, then people. // Grouped rows, like Home: Movies, TV shows, collections, episodes, then people.
LazyColumn(Modifier.fillMaxSize(),contentPadding=PaddingValues(top=4.dp,bottom=30.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) { LazyColumn(Modifier.fillMaxSize(),contentPadding=PaddingValues(top=4.dp,bottom=30.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) {
groups.forEachIndexed{index,group-> groups.forEachIndexed{index,group->
@ -246,9 +314,9 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
} }
} }
internal fun searchGroups(titles:List<Title>):List<Pair<String,List<Title>>> = internal fun searchGroups(titles:List<Title>,query:String=""):List<Pair<String,List<Title>>> = rankSearchGroups(
listOf("movie" to "Movies","show" to "TV shows","season" to "Seasons","collection" to "Collections","episode" to "Episodes") titles,query,Title::type
.map{(type,label)->label to titles.filter{it.type==type}}.filter{it.second.isNotEmpty()} ){title->listOf(title.title,title.parentTitle,title.grandparentTitle)}
@Composable private fun PeopleRow(vm:KaleidoViewModel,people:List<CastMember>,entryFocus:FocusRequester?) { @Composable private fun PeopleRow(vm:KaleidoViewModel,people:List<CastMember>,entryFocus:FocusRequester?) {
Column { Column {

View file

@ -0,0 +1,58 @@
package tv.kaleido.app;
import androidx.annotation.NonNull;
import androidx.annotation.OptIn;
import androidx.compose.foundation.ExperimentalFoundationApi;
import androidx.compose.foundation.lazy.LazyListCacheWindowScope;
import androidx.compose.foundation.lazy.LazyListLayoutInfo;
import androidx.compose.foundation.lazy.LazyListPrefetchScope;
import androidx.compose.foundation.lazy.LazyListPrefetchStrategy;
import androidx.compose.foundation.lazy.layout.CacheWindowLogic;
import androidx.compose.foundation.lazy.layout.LazyLayoutCacheWindow;
import androidx.compose.foundation.lazy.layout.NestedPrefetchScope;
import androidx.compose.foundation.lazy.layout.PrefetchScheduler;
/**
* Compose's cache-window strategy for lazy lists (LazyListCacheWindowStrategy, Compose 1.10),
* prefetching on {@link FramePrefetch} instead of Compose's scheduler. It must itself be a
* CacheWindowLogic: the list's measure policy only keeps items in the window composed after they
* scroll out when its strategy is one, so a delegating wrapper disposed every row leaving view.
* These classes are Kotlin-internal but public in bytecode; a Compose update that changes them
* fails this build instead of changing behaviour silently.
*/
@OptIn(markerClass = ExperimentalFoundationApi.class)
@SuppressWarnings("deprecation") // Compose marks parts of the prefetch API deprecated for Java callers.
final class CacheWindows extends CacheWindowLogic implements LazyListPrefetchStrategy {
private final LazyListCacheWindowScope scope = new LazyListCacheWindowScope();
CacheWindows(LazyLayoutCacheWindow window) {
super(window, true);
}
@NonNull
@Override
public PrefetchScheduler getPrefetchScheduler() {
return FramePrefetch.INSTANCE;
}
@Override
public void onScroll(@NonNull LazyListPrefetchScope prefetch, float delta, @NonNull LazyListLayoutInfo layoutInfo) {
scope.setLayoutInfo(layoutInfo);
scope.setPrefetchScope(prefetch);
onScroll(scope, delta);
}
@Override
public void onVisibleItemsUpdated(@NonNull LazyListPrefetchScope prefetch, @NonNull LazyListLayoutInfo layoutInfo) {
scope.setLayoutInfo(layoutInfo);
scope.setPrefetchScope(prefetch);
onVisibleItemsUpdated(scope);
}
@Override
public void onNestedPrefetch(@NonNull NestedPrefetchScope nested, int firstVisibleItemIndex) {
// Every card the row showed when last measured (Compose: precompose two); see premeasure.
int count = nested.getNestedPrefetchItemCount() == -1 ? 2 : nested.getNestedPrefetchItemCount();
for (int i = 0; i < count; i++) FramePrefetchKt.premeasure(nested, firstVisibleItemIndex + i);
}
}

View file

@ -0,0 +1,29 @@
package tv.kaleido.app
/** Match genres to distinct artwork sources, moving an earlier choice when a later genre needs it. */
internal fun <T> selectCategoryArtwork(candidates:Map<String,List<T>>,identity:(T)->String):Map<String,T> {
val options=candidates.mapValues{(_,items)->items.filter{identity(it).isNotBlank()}.distinctBy(identity)}
val owners=mutableMapOf<String,String>()
val selected=mutableMapOf<String,T>()
fun assign(genre:String,visited:MutableSet<String>):Boolean {
// Keep preferred choices where possible; try free sources before moving another genre.
val choices=options.getValue(genre)
choices.firstOrNull{identity(it) !in owners&&identity(it) !in visited}?.let {
owners[identity(it)]=genre;selected[genre]=it;return true
}
for(item in choices) {
val key=identity(item)
if(!visited.add(key))continue
val previous=owners[key] ?: continue
if(assign(previous,visited)){owners[key]=genre;selected[genre]=item;return true}
}
return false
}
// Give narrow genres first choice, so a broad category cannot exhaust their only source.
options.keys.sortedBy{options.getValue(it).size}.forEach{assign(it,mutableSetOf())}
return candidates.keys.mapNotNull{genre->selected[genre]?.let{genre to it}}.toMap()
}
/** Plex timestamps/query strings do not make a refreshed image a different artwork source. */
private val artworkVersion=Regex("(/(?:art|thumb))/[0-9]+$")
internal fun categoryArtworkIdentity(path:String):String = path.substringBefore('?').replace(artworkVersion,"\$1")

View file

@ -40,11 +40,16 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
class DiscoveryNavigation { class DiscoveryNavigation {
val entry=FocusRequester()
val section=FocusRequester()
val top=FocusRequester() val top=FocusRequester()
var scrolled by mutableStateOf(false) var scrolled by mutableStateOf(false)
var pendingEntry by mutableStateOf<String?>(null) var pendingEntry by mutableStateOf<String?>(null)
private val destinations=mutableMapOf<String,DestinationNavigation>()
/** Home, Movies and TV stay composed while hidden, so each needs its own targets: a hidden one must never take focus. */
fun of(destination:String)=destinations.getOrPut(destination){DestinationNavigation()}
}
class DestinationNavigation {
val entry=FocusRequester()
val section=FocusRequester()
var enter:(()->Unit)?=null var enter:(()->Unit)?=null
} }
/** Preserve server-supplied recommendations, but give each destination an editorial purpose. */ /** Preserve server-supplied recommendations, but give each destination an editorial purpose. */

View file

@ -4,15 +4,22 @@ package tv.kaleido.app
import androidx.compose.foundation.* import androidx.compose.foundation.*
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.* import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.lazy.layout.LazyLayoutCacheWindow
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.gestures.BringIntoViewSpec import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.DpSize
import coil.imageLoader
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.withTimeoutOrNull
import androidx.compose.material3.* import androidx.compose.material3.*
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.PlayArrow
@ -29,6 +36,11 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.* import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.* import androidx.compose.ui.semantics.*
import androidx.compose.ui.node.invalidateSemantics
import androidx.compose.ui.node.observeReads
import androidx.compose.ui.node.ObserverModifierNode
import androidx.compose.ui.node.SemanticsModifierNode
import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@ -45,7 +57,10 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.Shadow
import androidx.compose.material.icons.outlined.GridView import androidx.compose.material.icons.outlined.GridView
@Composable fun HomeScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation)=DiscoveryScreen(vm,true,navigation) /** Movies, TV and Home's second row show posters; the rest landscape cards (wider TV episodes). */
private fun posterRow(hub:Hub,row:Int,destination:String)=hub.items.firstOrNull()?.type in listOf("movie","show","season")&&!hub.title.contains("Continue",true)&&(destination=="movies"||destination=="tv"||row==1)
/** A card's width plus the rail's spacing. */
private fun railPitch(poster:Boolean,tv:Boolean)=if(poster)130.dp else if(tv)274.dp else 224.dp
/** Column id of a row's trailing "View all" card. */ /** Column id of a row's trailing "View all" card. */
internal const val VIEW_ALL="view-all" internal const val VIEW_ALL="view-all"
@ -62,38 +77,46 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(visible!=null)animateScrollBy(visible.offset.toFloat(),tween(220))else animateScrollToItem(index) if(visible!=null)animateScrollBy(visible.offset.toFloat(),tween(220))else animateScrollToItem(index)
} }
/** The preview never scrolls. Only the bounded catalog below it moves. */ /**
@Composable fun DiscoveryScreen(vm:KaleidoViewModel,home:Boolean,navigation:DiscoveryNavigation) { * The preview never scrolls. Only the bounded catalog below it moves.
val destination=if(home)"home"else vm.page.kind *
val source=if(home)vm.homeHubs else vm.discoverHubs * Home, Movies and TV stay composed once shown: while [active] is false the screen is neither placed
* nor drawn (see KaleidoApp), and must not take focus. Switching tabs or returning from details then
* shows it again instead of disposing and composing whole sections (a 50–80 ms frame on the onn).
*/
@Composable fun DiscoveryScreen(vm:KaleidoViewModel,destination:String,navigation:DiscoveryNavigation,active:()->Boolean) {
val home=destination=="home"
val local=remember(destination){navigation.of(destination)}
val source=vm.discoveryHubs(destination)
val hubs=remember(source,destination){editorialHubs(source,destination)} val hubs=remember(source,destination){editorialHubs(source,destination)}
var previousHubs by remember(destination){mutableStateOf(hubs)} var previousHubs by remember(destination){mutableStateOf(hubs)}
val restore=remember(hubs){ val restore=remember(hubs){
val focused=Snapshot.withoutReadObservation{vm.focusId} val focused=Snapshot.withoutReadObservation{vm.focusId}
hubs.withIndex().firstNotNullOfOrNull{(row,h)->val column=if(focused=="${h.id}:$VIEW_ALL")h.items.size else h.items.indexOfFirst{"${h.id}:${it.id}"==focused};if(column>=0)Triple(h.id,row,column)else null} hubs.withIndex().firstNotNullOfOrNull{(row,h)->val column=if(focused=="${h.id}:$VIEW_ALL")h.items.size else h.items.indexOfFirst{"${h.id}:${it.id}"==focused};if(column>=0)Triple(h.id,row,column)else null}
} }
val initialRow=restore?.let{it.second+if(home)1 else 0} ?: 0 val initialRow=restore?.second ?: 0
// Keep the hero/preview and adjacent rows prepared across vertical moves. // Keep the hero/preview and two rows either side prepared across vertical moves (about two
// Without a behind window, every return discards and recomposes those cards. // viewports). Prefetch only uses spare or idle frame time (FramePrefetch), so a wider window
val list=rememberLazyListState(initialFirstVisibleItemIndex=initialRow, // costs no frames; a one-viewport window composed rows mid-scroll when moving back up.
cacheWindow=remember{LazyLayoutCacheWindow(aheadFraction=1f,behindFraction=1f)}) val list=rememberLazyListState(initialFirstVisibleItemIndex=initialRow,prefetchStrategy=remember{budgetedCacheWindow(ahead=2f,behind=2f)})
// The window only fills ahead after the list has scrolled, so the first move down after // The window only fills after the list has scrolled, and a change of rows resets it, so the
// a section appeared composed the next rows mid-animation (a ~200 ms stall on the onn). // next move composed rows mid-animation (a ~200 ms stall on the onn). Once the screen settles,
// Once the screen settles, nudge it so those rows compose in idle frames, then undo it. // nudge it so those rows compose in idle frames, then undo it.
LaunchedEffect(list,hubs.isNotEmpty()){ LaunchedEffect(list,hubs){
if(hubs.isEmpty()||list.firstVisibleItemIndex!=0||list.firstVisibleItemScrollOffset!=0)return@LaunchedEffect if(hubs.isEmpty())return@LaunchedEffect
snapshotFlow{active()}.first{it}
awaitSteadyFrames(4) awaitSteadyFrames(4)
if(list.isScrollInProgress||list.firstVisibleItemScrollOffset!=0)return@LaunchedEffect if(list.isScrollInProgress)return@LaunchedEffect
list.scrollBy(1f) val moved=list.scrollBy(1f)
val at=list.firstVisibleItemIndex to list.firstVisibleItemScrollOffset
repeat(45){withFrameNanos{}} repeat(45){withFrameNanos{}}
if(!list.isScrollInProgress&&list.firstVisibleItemIndex==0&&list.firstVisibleItemScrollOffset==1)list.scrollBy(-1f) if(moved!=0f&&!list.isScrollInProgress&&(list.firstVisibleItemIndex to list.firstVisibleItemScrollOffset)==at)list.scrollBy(-moved)
} }
// Hub order and membership can change during a live refresh. Keep each rail's scroll // Hub order and membership can change during a live refresh. Keep each rail's scroll
// state and each card's requester by stable Plex IDs so surviving rows/cards retain them. // state and each card's requester by stable Plex IDs so surviving rows/cards retain them.
val rowStateByHub=remember(destination){mutableMapOf<String,LazyListState>()} val rowStateByHub=remember(destination){mutableMapOf<String,LazyListState>()}
val rowStates=remember(hubs){hubs.associate{hub->hub.id to rowStateByHub.getOrPut(hub.id){LazyListState( val rowStates=remember(hubs){hubs.associate{hub->hub.id to rowStateByHub.getOrPut(hub.id){LazyListState(
cacheWindow=LazyLayoutCacheWindow(aheadFraction=1f,behindFraction=.5f), firstVisibleItemIndex=if(restore?.first==hub.id)restore.third else 0,prefetchStrategy=budgetedCacheWindow(ahead=1f,behind=.5f))}}}
firstVisibleItemIndex=if(restore?.first==hub.id)restore.third else 0)}}}
val requesters=remember(destination){mutableMapOf<String,FocusRequester>()} val requesters=remember(destination){mutableMapOf<String,FocusRequester>()}
val columns=remember(destination){mutableMapOf<String,String>()} val columns=remember(destination){mutableMapOf<String,String>()}
val pendingColumns=remember(destination){mutableMapOf<String,String>()} val pendingColumns=remember(destination){mutableMapOf<String,String>()}
@ -102,29 +125,39 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val scope=rememberCoroutineScope() val scope=rememberCoroutineScope()
val density=LocalDensity.current val density=LocalDensity.current
val hovered=remember{mutableStateOf<Title?>(null)} val hovered=remember{mutableStateOf<Title?>(null)}
val sectionEntry by remember{derivedStateOf{vm.focusId=="discovery-entry"}} val sectionEntry by remember{derivedStateOf{vm.focusId=="discovery-entry"&&active()}}
val features=vm.homeFeatures val features=vm.homeFeatures
var featureIndex by rememberSaveable{mutableIntStateOf(0)} var featureIndex by rememberSaveable{mutableIntStateOf(0)}
val nextFeature=features.getOrNull(featureIndex % features.size.coerceAtLeast(1)) val nextFeature=features.getOrNull(featureIndex % features.size.coerceAtLeast(1))
var selectedFeature by remember{mutableStateOf(nextFeature)} var selectedFeature by remember{mutableStateOf(nextFeature)}
val heroFade=remember{Animatable(1f)} val context=LocalContext.current
LaunchedEffect(nextFeature){ LaunchedEffect(nextFeature){
if(home)nextFeature?.item?.let{vm.anticipate(it,cinematic=true)} val next=nextFeature?.item
if(home&&selectedFeature!=null&&nextFeature!=null&&selectedFeature?.item?.id!=nextFeature.item.id)heroFade.animateTo(0f,tween(100)) if(home&&next!=null)vm.anticipate(next,cinematic=true)
// Hold the copy briefly until the new artwork is decoded, so both fade together.
if(home&&next!=null&&selectedFeature!=null&&selectedFeature?.item?.id!=next.id)
browseBackdropRequest(context,vm.api,next.art.ifBlank{next.thumb},true)?.let{withTimeoutOrNull(700){context.imageLoader.execute(it)}}
selectedFeature=nextFeature selectedFeature=nextFeature
heroFade.animateTo(1f,tween(180))
} }
val feature=selectedFeature?.item val feature=selectedFeature?.item
val activeFeature=rememberUpdatedState(feature) val activeFeature=rememberUpdatedState(feature)
var heroActive by remember{mutableStateOf(restore==null)} // Home only: the large hero while it holds focus; a compact preview of the focused card otherwise.
// Read only inside effects, callbacks and layers: switching modes must not recompose the catalog.
val heroMode=remember{mutableStateOf(restore==null)}
var heroActive by heroMode
val compact=remember{Animatable(if(home&&restore==null)0f else 1f)}
LaunchedEffect(compact,home){snapshotFlow{home&&heroMode.value}.collectLatest{compact.animateTo(if(it)0f else 1f,tween(HeaderMillis,easing=FastOutSlowInEasing))}}
val firstCard=rememberUpdatedState(hubs.firstOrNull()?.items?.firstOrNull())
val preview=restingPreview(hovered,{firstCard.value}){!home||!heroMode.value}
fun anticipateCard(item:Title)=vm.anticipate(item,path=previewArt(item),header=true)
var rotating by remember{mutableStateOf(true)} var rotating by remember{mutableStateOf(true)}
LaunchedEffect(home,features,heroActive,rotating,featureIndex){ LaunchedEffect(home,features,rotating,featureIndex){
if(home&&heroActive&&rotating&&features.size>1){delay(12000);featureIndex=(featureIndex+1)%features.size} snapshotFlow{heroMode.value&&active()}.collectLatest{if(home&&it&&rotating&&features.size>1){delay(12000);featureIndex=(featureIndex+1)%features.size}}
} }
val heroFocus=remember{FocusRequester()} val heroFocus=remember{FocusRequester()}
val staging=remember{CardStaging()} val staging=remember{CardStaging()}
LaunchedEffect(staging){delay(1000);staging.entering=false} LaunchedEffect(staging){delay(1000);staging.entering=false}
val rowOffset=if(home)1 else 0 suspend fun focusHero(){repeat(4){withFrameNanos{};if(runCatching{heroFocus.requestFocus()}.getOrDefault(false))return}}
suspend fun moveToRow(hubId:String,titleId:String)=coroutineScope { suspend fun moveToRow(hubId:String,titleId:String)=coroutineScope {
val row=hubs.indexOfFirst{it.id==hubId} val row=hubs.indexOfFirst{it.id==hubId}
val hub=hubs.getOrNull(row) ?: return@coroutineScope val hub=hubs.getOrNull(row) ?: return@coroutineScope
@ -132,22 +165,27 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(column<0)return@coroutineScope if(column<0)return@coroutineScope
val state=rowStates[hub.id] ?: return@coroutineScope val state=rowStates[hub.id] ?: return@coroutineScope
val focusKey="$hubId:$titleId" val focusKey="$hubId:$titleId"
val visible=list.layoutInfo.visibleItemsInfo.any{it.index==row+rowOffset}&&state.layoutInfo.visibleItemsInfo.any{it.index==column} val visible=list.layoutInfo.visibleItemsInfo.any{it.index==row}&&state.layoutInfo.visibleItemsInfo.any{it.index==column}
val focused=visible&&runCatching{requesters[focusKey]?.requestFocus()==true}.getOrDefault(false) val focused=visible&&runCatching{requesters[focusKey]?.requestFocus()==true}.getOrDefault(false)
val scrolling=launch{list.animateBrowseTo(row+rowOffset)} val scrolling=launch{list.animateBrowseTo(row)}
if(!state.layoutInfo.visibleItemsInfo.any{it.index==column})state.requestScrollToItem(column) if(!state.layoutInfo.visibleItemsInfo.any{it.index==column})state.requestScrollToItem(column)
if(!focused) { if(!focused) {
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==row+rowOffset}&&state.layoutInfo.visibleItemsInfo.any{it.index==column}}.first{it} snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==row}&&state.layoutInfo.visibleItemsInfo.any{it.index==column}}.first{it}
withFrameNanos{} // A card that replaced another (a live refresh) may compose a frame or two later; until it
runCatching{requesters.getOrPut(focusKey){FocusRequester()}.requestFocus()} // does, its requester is unattached and the request fails, which left nothing focused.
for(attempt in 0 until 8){withFrameNanos{};if(runCatching{requesters.getOrPut(focusKey){FocusRequester()}.requestFocus()}.getOrDefault(false))break}
} }
scrolling.join() scrolling.join()
} }
/** The first card of the first row: where Down goes when Home has no hero to hold focus. */
suspend fun enterFirstRow(){hubs.firstOrNull{it.items.isNotEmpty()}?.let{hub->val item=hub.items.first();anticipateCard(item);moveToRow(hub.id,item.id)}}
suspend fun moveToHero()=coroutineScope { suspend fun moveToHero()=coroutineScope {
heroActive=true
val scrolling=launch{list.animateBrowseTo(0)} val scrolling=launch{list.animateBrowseTo(0)}
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==0}}.first{it} focusHero();scrolling.join()
withFrameNanos{};runCatching{heroFocus.requestFocus()};scrolling.join()
} }
/** Whether focus is inside this screen; a card key in [KaleidoViewModel.focusId] alone doesn't mean it is. */
val screenFocus=remember{booleanArrayOf(false)}
LaunchedEffect(hubs) { LaunchedEffect(hubs) {
val old=previousHubs val old=previousHubs
if(old==hubs)return@LaunchedEffect if(old==hubs)return@LaunchedEffect
@ -170,6 +208,21 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(pendingColumns[hub.id]?.let{id->hub.items.any{it.id==id}}!=true)hub.items.firstOrNull()?.let{pendingColumns[hub.id]=it.id} ?: pendingColumns.remove(hub.id) if(pendingColumns[hub.id]?.let{id->hub.items.any{it.id==id}}!=true)hub.items.firstOrNull()?.let{pendingColumns[hub.id]=it.id} ?: pendingColumns.remove(hub.id)
} }
previousHubs=hubs previousHubs=hubs
// A hidden screen moves no focus; it finds its card again when shown.
if(!active())return@LaunchedEffect
if(oldHub==null) {
// The card being restored (e.g. after details) was already gone from the previous rows,
// and this refresh cancelled that restoration. Finish it here instead of leaving focus
// on the top bar: the card itself if it is back, else the first card of its row.
val key=focus
val row=hubs.firstOrNull{key.startsWith("${it.id}:")&&it.items.isNotEmpty()}
if(row!=null&&!screenFocus[0]) {
val item=row.items.firstOrNull{"${row.id}:${it.id}"==key} ?: row.items.first()
columns[row.id]=item.id;pendingColumns[row.id]=item.id
navigationJob[0]=scope.launch{withFrameNanos{};moveToRow(row.id,item.id)}
}
return@LaunchedEffect
}
if(oldHub!=null&&oldTitle!=null) { if(oldHub!=null&&oldTitle!=null) {
val sameHub=hubs.firstOrNull{it.id==oldHub.id} val sameHub=hubs.firstOrNull{it.id==oldHub.id}
@ -189,10 +242,10 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
hovered.value=null hovered.value=null
if(home&&feature!=null) { if(home&&feature!=null) {
vm.focusId="home-feature";heroActive=true vm.focusId="home-feature";heroActive=true
navigationJob[0]=scope.launch{list.scrollToItem(0);withFrameNanos{};runCatching{heroFocus.requestFocus()}} navigationJob[0]=scope.launch{list.scrollToItem(0);focusHero()}
}else if(!home) { }else if(!home) {
vm.focusId="discovery-entry" vm.focusId="discovery-entry"
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{navigation.section.requestFocus()}} navigationJob[0]=scope.launch{withFrameNanos{};runCatching{local.section.requestFocus()}}
}else { }else {
vm.focusId="" vm.focusId=""
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{navigation.top.requestFocus()}} navigationJob[0]=scope.launch{withFrameNanos{};runCatching{navigation.top.requestFocus()}}
@ -200,25 +253,29 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
} }
} }
} }
LaunchedEffect(home,features.isNotEmpty()){if(home&&vm.focusId=="home-feature"){list.scrollToItem(0);withFrameNanos{};runCatching{heroFocus.requestFocus()}}} LaunchedEffect(home,features.isNotEmpty()){if(home&&active()&&vm.focusId=="home-feature"){heroActive=true;list.scrollToItem(0);focusHero()}}
DisposableEffect(navigation,list,hubs){ DisposableEffect(local,list,hubs){
navigation.scrolled=false navigation.scrolled=false
navigation.enter={ local.enter={
navigationJob[0]?.cancel() navigationJob[0]?.cancel()
// Discover is fixed above the catalog. Enter it immediately, without resetting // Discover is fixed above the catalog. Enter it immediately, without resetting
// or waiting for two lazy lists to lay out. The next Down explicitly enters row 0. // or waiting for two lazy lists to lay out. The next Down explicitly enters row 0.
if(!home)runCatching{navigation.section.requestFocus()} if(!home)runCatching{local.section.requestFocus()}
// Continue Watching and other rows can exist without an eligible featured title.
else if(activeFeature.value==null)navigationJob[0]=scope.launch{enterFirstRow()}
else { else {
val visible=list.layoutInfo.visibleItemsInfo.any{it.index==0} if(heroActive)runCatching{heroFocus.requestFocus()}
if(visible)runCatching{heroFocus.requestFocus()} navigationJob[0]=scope.launch{moveToHero()}
navigationJob[0]=scope.launch{if(visible)list.animateBrowseTo(0)else moveToHero()}
activeFeature.value?.let{vm.anticipate(it,cinematic=true)} activeFeature.value?.let{vm.anticipate(it,cinematic=true)}
} }
} }
onDispose{navigation.enter=null} onDispose{local.enter=null}
} }
LaunchedEffect(navigation.pendingEntry,destination) { LaunchedEffect(navigation.pendingEntry,destination) {
if(navigation.pendingEntry==destination){navigation.pendingEntry=null;navigation.enter?.invoke()} if(navigation.pendingEntry!=destination)return@LaunchedEffect
// A retained screen is shown by the same change; enter it once it is placed again.
if(!active()){snapshotFlow{active()}.first{it};withFrameNanos{}}
navigation.pendingEntry=null;local.enter?.invoke()
} }
// Back from the catalog first returns to the hero (Home) or Discover; only then leaves. // Back from the catalog first returns to the hero (Home) or Discover; only then leaves.
var catalogFocus by remember{mutableStateOf(false)} var catalogFocus by remember{mutableStateOf(false)}
@ -227,68 +284,68 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
navigationJob[0]?.cancel() navigationJob[0]?.cancel()
if(home&&feature!=null){vm.anticipate(feature,cinematic=true);navigationJob[0]=scope.launch{moveToHero()}} if(home&&feature!=null){vm.anticipate(feature,cinematic=true);navigationJob[0]=scope.launch{moveToHero()}}
// Move focus out of the rows before they scroll away, or the removed card clears it. // Move focus out of the rows before they scroll away, or the removed card clears it.
else navigationJob[0]=scope.launch{runCatching{(if(home)navigation.top else navigation.section).requestFocus()};withFrameNanos{};list.scrollToItem(0)} else navigationJob[0]=scope.launch{runCatching{(if(home)navigation.top else local.section).requestFocus()};withFrameNanos{};list.scrollToItem(0)}
} }
// Focus the hero or card that started playback once the player closes. // Focus the hero or card that started playback once the player closes.
val seenReturn=remember{intArrayOf(vm.playbackReturn)} val seenReturn=remember{intArrayOf(vm.playbackReturn)}
LaunchedEffect(vm.playbackReturn) { LaunchedEffect(vm.playbackReturn) {
if(vm.playbackReturn==seenReturn[0])return@LaunchedEffect if(vm.playbackReturn==seenReturn[0])return@LaunchedEffect
seenReturn[0]=vm.playbackReturn seenReturn[0]=vm.playbackReturn
if(!active())return@LaunchedEffect
withFrameNanos{} withFrameNanos{}
val key=vm.focusId val key=vm.focusId
runCatching{if(key=="home-feature")heroFocus.requestFocus()else requesters[key]?.requestFocus()} runCatching{if(key=="home-feature")heroFocus.requestFocus()else requesters[key]?.requestFocus()}
} }
// Hidden, the screen keeps its state but gives up focus: an unplaced card must not take key
// events. Shown again, it focuses what a freshly composed screen would.
val focusManager=LocalFocusManager.current
suspend fun reveal() {
withFrameNanos{}
val key=vm.focusId
if(key.isBlank()||key.startsWith("tab:")||key=="discovery-entry") {
// Entered from the top bar or Library: the screen opens at its start, as when first shown.
hovered.value=null;if(home)heroActive=true
if(list.firstVisibleItemIndex!=0||list.firstVisibleItemScrollOffset!=0)list.scrollToItem(0)
if(key=="discovery-entry"&&!home)runCatching{local.section.requestFocus()}
return
}
if(key=="home-feature"){if(home&&feature!=null)moveToHero()else if(home)enterFirstRow();return}
val card=hubs.firstNotNullOfOrNull{hub->hub.items.firstOrNull{"${hub.id}:${it.id}"==key}?.let{hub to it}}
if(card!=null){moveToRow(card.first.id,card.second.id);return}
if(requesters[key]?.let{runCatching{it.requestFocus()}.getOrDefault(false)}==true)return
// Its card left while hidden (e.g. finished from Continue Watching): that row's first card.
val row=hubs.firstOrNull{key.startsWith("${it.id}:")&&it.items.isNotEmpty()}
if(row!=null)moveToRow(row.id,row.items.first().id)
else if(home&&feature!=null)moveToHero()
else runCatching{(if(home)navigation.top else local.section).requestFocus()}
}
LaunchedEffect(Unit) {
var shown=active()
snapshotFlow{active()}.collect{now->
if(now==shown)return@collect
shown=now
navigationJob[0]?.cancel();navigationJob[0]=null
if(!now){if(screenFocus[0])focusManager.clearFocus(force=true)}
else if(navigation.pendingEntry!=destination)navigationJob[0]=scope.launch{reveal()}
}
}
var sectionMenu by remember{mutableStateOf(false)} var sectionMenu by remember{mutableStateOf(false)}
val sectionChoices=vm.sections.filter{it.type==vm.section?.type} val sectionChoices=vm.sections.filter{it.type==vm.section?.type}
val sectionFocus=remember{FocusRequester()} val sectionFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()}
val title=when(destination){"movies"->"Movies";"tv"->"TV Shows";else->"Home"} val title=when(destination){"movies"->"Movies";"tv"->"TV Shows";else->"Home"}
BoxWithConstraints(Modifier.fillMaxSize()) { BoxWithConstraints(Modifier.fillMaxSize().onFocusChanged{screenFocus[0]=it.hasFocus}) {
val heroHeight=maxHeight*.80f-62.dp val heroHeight=maxHeight*.80f-62.dp
if(home)HomeBackdrop(vm.api,hovered,feature,heroActive) if(home)HomeBackdrop(vm.api,preview,feature,heroMode,vm.colourWash)
else FocusedPreviewCanvas(vm,hovered,hubs.firstOrNull()?.items?.firstOrNull(),destination) else FocusedPreviewCanvas(vm,preview,hubs.firstOrNull()?.items?.firstOrNull(),vm.colourWash)
Column(Modifier.fillMaxSize().padding(top=62.dp)) { if(home) {
if(!home) { val lift=with(density){HeaderLift.toPx()}
Row(Modifier.fillMaxWidth().height(39.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) { // Leaving for the rows, the hero lifts away as the preview rises in; the reverse settles it back.
Text(title,color=Accent,fontSize=19.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(end=20.dp)) HeaderLayer({compact.value},{heroMode.value},true,lift,Modifier.padding(top=62.dp).fillMaxWidth().height(heroHeight)) {
if(!home) { feature?.let{item->Box(Modifier.fillMaxSize()) {
NavigationLabel("Discover",true,modifier=Modifier.focusRequester(navigation.section).focusProperties{up=navigation.top;down=navigation.entry}.onPreviewKeyEvent {
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
hubs.firstOrNull()?.items?.firstOrNull()?.let{item->vm.anticipate(item)}
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
},initialFocus=sectionEntry){}
// Nothing sits right of Library; an unbounded search would open Home from the top bar.
NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry;right=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}){vm.setAll(true)}
Spacer(Modifier.weight(1f))
// A second movie or TV library (e.g. 4K, Kids) is chosen here and remembered.
if(sectionChoices.size>1)TvButton((vm.section?.title ?: title)+" ⌄",Modifier.focusRequester(sectionFocus).focusProperties{up=navigation.top;right=FocusRequester.Cancel}.onPreviewKeyEvent{
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
}){sectionMenu=true}
}
}
Spacer(Modifier.fillMaxWidth().height(if(destination=="movies")137.dp else 119.dp))
}
CompositionLocalProvider(LocalBringIntoViewSpec provides BrowseScroll) {
LazyColumn(state=list,modifier=Modifier.fillMaxWidth().weight(1f).onFocusChanged{catalogFocus=it.hasFocus},verticalArrangement=Arrangement.spacedBy(15.dp),contentPadding=PaddingValues(bottom=22.dp)) {
if(home)item(key="home-feature") {
Box(Modifier.fillMaxWidth().height(heroHeight)) {
feature?.let{item->
val metadata by produceState(item,item.id){value=item;value=vm.previewDetails(item)}
Column(Modifier.align(Alignment.BottomStart).padding(start=Cinema.gutter,bottom=35.dp).width(350.dp)) { Column(Modifier.align(Alignment.BottomStart).padding(start=Cinema.gutter,bottom=35.dp).width(350.dp)) {
Column(Modifier.graphicsLayer{alpha=heroFade.value}) { FadingCopy(selectedFeature,{it.item.id},lift,contentAlignment=Alignment.BottomStart){HeroCopy(vm,it)}
Eyebrow(selectedFeature?.reason.orEmpty())
Spacer(Modifier.height(9.dp))
TitleIdentity(vm.api,item,Modifier.width(264.dp).height(80.dp))
Row(Modifier.fillMaxWidth().padding(top=8.dp,bottom=8.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.year,item.genres.firstOrNull().orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=10.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(metadata,Modifier.padding(start=10.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis)
}
Row(Modifier.padding(top=16.dp).onPreviewKeyEvent{event-> Row(Modifier.padding(top=16.dp).onPreviewKeyEvent{event->
if(event.type==KeyEventType.KeyDown&&event.key==Key.DirectionDown){hubs.firstOrNull()?.items?.firstOrNull()?.let{vm.anticipate(it,cinematic=true)};navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true}else false if(event.type==KeyEventType.KeyDown&&event.key==Key.DirectionDown){hubs.firstOrNull()?.items?.firstOrNull()?.let{anticipateCard(it)};navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true}else false
}.onFocusChanged{if(it.hasFocus){heroActive=true;hovered.value=null}},horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) { }.onFocusChanged{if(it.hasFocus){heroActive=true;hovered.value=null}},horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) {
ActionButton(if(item.offset>0)"Resume"else "Play",Icons.Filled.PlayArrow,primary=true,modifier=Modifier.focusRequester(heroFocus).focusProperties{up=navigation.top}.onFocusChanged{if(it.isFocused){vm.focusId="home-feature";rotating=true}}){vm.play(item)} ActionButton(if(item.offset>0)"Resume"else "Play",Icons.Filled.PlayArrow,primary=true,modifier=Modifier.focusRequester(heroFocus).focusProperties{up=navigation.top}.onFocusChanged{if(it.isFocused){vm.focusId="home-feature";rotating=true}}){vm.play(item)}
IconControl(Icons.Outlined.Info,"More info",modifier=Modifier.focusProperties{up=navigation.top},onFocused={rotating=false}){vm.open(item)} IconControl(Icons.Outlined.Info,"More info",modifier=Modifier.focusProperties{up=navigation.top},onFocused={rotating=false}){vm.open(item)}
@ -298,11 +355,48 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
Row(Modifier.align(Alignment.BottomCenter).padding(bottom=8.dp),horizontalArrangement=Arrangement.spacedBy(5.dp)) { Row(Modifier.align(Alignment.BottomCenter).padding(bottom=8.dp),horizontalArrangement=Arrangement.spacedBy(5.dp)) {
features.forEachIndexed{i,_->Box(Modifier.size(if(i==featureIndex)12.dp else 3.dp,3.dp).background(Accent.copy(alpha=if(i==featureIndex).9f else .35f),RoundedCornerShape(2.dp)))} features.forEachIndexed{i,_->Box(Modifier.size(if(i==featureIndex)12.dp else 3.dp,3.dp).background(Accent.copy(alpha=if(i==featureIndex).9f else .35f),RoundedCornerShape(2.dp)))}
} }
}}
}
HeaderLayer({compact.value},{heroMode.value},false,lift,Modifier.padding(start=Cinema.gutter,top=78.dp).height(200.dp)) {
HomePreview(vm,preview)
} }
} }
Column(Modifier.fillMaxSize().padding(top=62.dp)) {
if(!home) {
Row(Modifier.fillMaxWidth().height(39.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) {
Text(title,color=Accent,fontSize=19.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(end=20.dp))
if(!home) {
NavigationLabel("Discover",true,modifier=Modifier.focusRequester(local.section).focusProperties{up=navigation.top;down=local.entry}.onPreviewKeyEvent {
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
hubs.firstOrNull()?.items?.firstOrNull()?.let{item->anticipateCard(item)}
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
},initialFocus=sectionEntry){}
NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=local.entry;right=categoriesFocus}){vm.setAll(true)}
NavigationLabel("Categories",false,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{up=navigation.top;down=local.entry;right=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}.onPreviewKeyEvent{
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
}){vm.openCategories()}
Spacer(Modifier.weight(1f))
// A second movie or TV library (e.g. 4K, Kids) is chosen here and remembered.
if(sectionChoices.size>1)TvButton((vm.section?.title ?: title)+" ⌄",Modifier.focusRequester(sectionFocus).focusProperties{up=navigation.top;right=FocusRequester.Cancel}.onPreviewKeyEvent{
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
}){sectionMenu=true}
} }
}
Spacer(Modifier.fillMaxWidth().height(SectionPreviewSpace))
}
else Spacer(Modifier.fillMaxWidth().height(HomePreviewHeight))
// The rows sit below the hero, then slide up beneath the compact preview. A layer
// offset rather than a resized list: the catalog never re-measures during the move.
val heroDrop=with(density){(heroHeight+15.dp-HomePreviewHeight).toPx()}
CompositionLocalProvider(LocalBringIntoViewSpec provides BrowseScroll) {
LazyColumn(state=list,modifier=Modifier.fillMaxWidth().weight(1f).then(if(home)Modifier.graphicsLayer{translationY=heroDrop*(1f-compact.value)}else Modifier).onFocusChanged{catalogFocus=it.hasFocus},verticalArrangement=Arrangement.spacedBy(15.dp),contentPadding=PaddingValues(bottom=22.dp)) {
itemsIndexed(hubs,key={_,h->h.id},contentType={_,h->if(h.items.firstOrNull()?.type=="episode")"episodes"else "titles"}) {row,hub-> itemsIndexed(hubs,key={_,h->h.id},contentType={_,h->if(h.items.firstOrNull()?.type=="episode")"episodes"else "titles"}) {row,hub->
val poster=hub.items.firstOrNull()?.type in listOf("movie","show","season")&&!hub.title.contains("Continue",true)&&(destination=="movies"||destination=="tv"||row==1) val poster=posterRow(hub,row,destination)
val wideEpisode=destination=="tv"&&!poster val wideEpisode=destination=="tv"&&!poster
val continuing=isContinueHub(hub) val continuing=isContinueHub(hub)
// A row with more titles than Plex returned ends with a "View all" card. // A row with more titles than Plex returned ends with a "View all" card.
@ -327,12 +421,12 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
// catalog layout between those events. Bursts keep the latest // catalog layout between those events. Bursts keep the latest
// logical column instead of dropping a move while awaiting layout. // logical column instead of dropping a move while awaiting layout.
withFrameNanos{} withFrameNanos{}
if(!rapid)hub.items.getOrNull(target)?.let{vm.anticipate(it,cinematic=home)} if(!rapid)hub.items.getOrNull(target)?.let{anticipateCard(it)}
val visible=state.layoutInfo.visibleItemsInfo.any{it.index==target} val visible=state.layoutInfo.visibleItemsInfo.any{it.index==target}
val anchor=(target-1).coerceAtLeast(0) val anchor=(target-1).coerceAtLeast(0)
if(visible&&!rapid) { if(visible&&!rapid) {
runCatching{requesters.getOrPut("${hub.id}:${idAt(target)}"){FocusRequester()}.requestFocus()} runCatching{requesters.getOrPut("${hub.id}:${idAt(target)}"){FocusRequester()}.requestFocus()}
val pitch=with(density){(if(poster)130.dp else if(wideEpisode)274.dp else 224.dp).toPx()} val pitch=with(density){railPitch(poster,wideEpisode).toPx()}
val delta=(anchor-state.firstVisibleItemIndex)*pitch-state.firstVisibleItemScrollOffset val delta=(anchor-state.firstVisibleItemIndex)*pitch-state.firstVisibleItemScrollOffset
if(kotlin.math.abs(delta)>1)state.animateScrollBy(delta,tween(140)) if(kotlin.math.abs(delta)>1)state.animateScrollBy(delta,tween(140))
}else{ }else{
@ -345,7 +439,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
// A held direction snaps to the latest anchor. Repeatedly // A held direction snaps to the latest anchor. Repeatedly
// cancelling pixel animations and decoding transient backdrops // cancelling pixel animations and decoding transient backdrops
// costs more than the focus move; predict only after it settles. // costs more than the focus move; predict only after it settles.
if(rapid){delay(70);hub.items.getOrNull(target)?.let{vm.anticipate(it,cinematic=home)}} if(rapid){delay(70);hub.items.getOrNull(target)?.let{anticipateCard(it)}}
} }
} }
true true
@ -353,7 +447,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(event.key==Key.DirectionUp&&row==0) { if(event.key==Key.DirectionUp&&row==0) {
if(home)feature?.let{vm.anticipate(it,cinematic=true)} if(home)feature?.let{vm.anticipate(it,cinematic=true)}
navigationJob[0]?.cancel() navigationJob[0]?.cancel()
navigationJob[0]=scope.launch{if(home)moveToHero()else{withFrameNanos{};runCatching{navigation.section.requestFocus()}}} navigationJob[0]=scope.launch{if(home&&feature!=null)moveToHero()else{withFrameNanos{};runCatching{(if(home)navigation.top else local.section).requestFocus()}}}
} }
else { else {
navigationJob[0]?.cancel() navigationJob[0]?.cancel()
@ -362,21 +456,22 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val targetHub=hubs[target] val targetHub=hubs[target]
val selectedId=columns[targetHub.id] val selectedId=columns[targetHub.id]
val col=targetHub.items.indexOfFirst{it.id==selectedId}.takeIf{it>=0} ?: 0 val col=targetHub.items.indexOfFirst{it.id==selectedId}.takeIf{it>=0} ?: 0
vm.anticipate(hubs[target].items[col],cinematic=home) anticipateCard(hubs[target].items[col])
navigationJob[0]=scope.launch{moveToRow(targetHub.id,targetHub.items[col].id)} navigationJob[0]=scope.launch{moveToRow(targetHub.id,targetHub.items[col].id)}
} }
} }
true true
}else false }else false
} }
Column { Column(Modifier.semanticsOnScreen{list.layoutInfo.visibleItemsInfo.any{it.index==row}}) {
Text(hub.title,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,style=LocalTextStyle.current.copy(shadow=CaptionShadow),modifier=Modifier.padding(start=Cinema.gutter,bottom=5.dp)) Text(hub.title,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,style=LocalTextStyle.current.copy(shadow=CaptionShadow),modifier=Modifier.padding(start=Cinema.gutter,bottom=5.dp))
LazyRow(state=rowStates[hub.id]!!,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=3.dp,bottom=3.dp),horizontalArrangement=Arrangement.spacedBy(10.dp)) { LazyRow(state=rowStates[hub.id]!!,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=3.dp,bottom=3.dp),horizontalArrangement=Arrangement.spacedBy(10.dp)) {
itemsIndexed(hub.items,key={_,t->t.id},contentType={_,_->poster}) {column,item-> itemsIndexed(hub.items,key={_,t->t.id},contentType={_,_->poster}) {column,item->
val focusKey="${hub.id}:${item.id}" val focusKey="${hub.id}:${item.id}"
val requester=requesters.getOrPut(focusKey){FocusRequester()} val requester=requesters.getOrPut(focusKey){FocusRequester()}
BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)navigation.entry else null,requester,staging,continuing, val rail=rowStates[hub.id]!!
rowKeys(column),onHovered={columns[hub.id]=item.id;pendingColumns[hub.id]=item.id;hovered.value=it;heroActive=false}) BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)local.entry else null,requester,staging,continuing,
rowKeys(column).semanticsOnScreen{rail.layoutInfo.visibleItemsInfo.any{it.index==column}},onHovered={columns[hub.id]=item.id;pendingColumns[hub.id]=item.id;hovered.value=it;heroActive=false})
} }
if(viewAll)item(key=VIEW_ALL,contentType="viewAll") { if(viewAll)item(key=VIEW_ALL,contentType="viewAll") {
val focusKey="${hub.id}:$VIEW_ALL" val focusKey="${hub.id}:$VIEW_ALL"
@ -397,45 +492,195 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(sectionMenu)ChoiceDialog("Libraries",sectionChoices.map{it.title},sectionChoices.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(sectionChoices[it]);sectionMenu=false} if(sectionMenu)ChoiceDialog("Libraries",sectionChoices.map{it.title},sectionChoices.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(sectionChoices[it]);sectionMenu=false}
} }
/** Focus changes invalidate this small preview scope, never the catalog hierarchy. */ /** Home's compact header: the preview block Movies and TV show above their rows. */
@Composable private fun HomeBackdrop(api:PlexApi,hovered:State<Title?>,feature:Title?,heroActive:Boolean) { /** Home's compact header (after Silo's): its height below the top bar, and its title art. */
var displayed by remember{mutableStateOf<Title?>(null)} private val HomePreviewHeight=228.dp
val current=if(heroActive)feature else hovered.value ?: feature private val HomeLogo=DpSize(300.dp,64.dp)
LaunchedEffect(current){if(!heroActive)delay(90);displayed=current} /** Movies and TV use the same preview below their Discover/Library/Categories line, slightly smaller. */
(displayed ?: feature)?.let{BrowseBackdrop(api,it.art.ifBlank{it.thumb},Modifier.fillMaxSize(),cinematic=true,animate=heroActive)} private val SectionPreviewSpace=199.dp
private val SectionPreviewHeight=190.dp
private val SectionLogo=DpSize(280.dp,56.dp)
private const val HeaderMillis=380
private const val CopyMillis=380
internal val HeaderLift=12.dp
/** Focus must rest this long before the preview follows it, so a held direction doesn't replay fades. */
private const val PreviewRestMillis=110L
/** Previews show a card's own image: an episode's still, not its show's artwork. */
internal fun previewArt(item:Title)=if(item.type=="episode")item.still.ifBlank{item.thumb}.ifBlank{item.art}else item.art.ifBlank{item.thumb}
/**
* The card the preview shows: [hovered] once focus rests on it. The first card after the
* preview reappears shows at once. Inactive, it holds [idle] (the card Down enters), already
* composed under the hero, so entering the rows is only a fade.
*/
@Composable private fun restingPreview(hovered:State<Title?>,idle:()->Title?,active:()->Boolean):State<Title?> {
val rested=remember{mutableStateOf<Title?>(null)}
LaunchedEffect(hovered) {
snapshotFlow{if(active())hovered.value else idle()}.collectLatest{
if(it!=null&&rested.value!=null)delay(PreviewRestMillis)
rested.value=it
}
}
return rested
} }
@Composable private fun FocusedPreviewCanvas(vm:KaleidoViewModel,hovered:State<Title?>,fallback:Title?,destination:String) { /**
var displayed by remember{mutableStateOf<Title?>(null)} * The hero ([hero]) or the compact preview, faded and lifted by [progress] in its own layer: one
val current=hovered.value * animation, no per-frame composition or layout. Both stay composed: the hidden one is a zero-alpha
LaunchedEffect(current){delay(120);displayed=current} * layer, which the renderer skips, without semantics. Composing the hero again on every return to it
val feature=displayed ?: fallback * cost a frame there.
val metadata by produceState(feature,feature){value=feature;feature?.let{value=vm.previewDetails(it)}} */
@Composable private fun HeaderLayer(progress:()->Float,heroShown:()->Boolean,hero:Boolean,lift:Float,modifier:Modifier,content:@Composable ()->Unit) {
val shown by remember{derivedStateOf{!hero||heroShown()||progress()<1f}}
Box(modifier.then(if(shown)Modifier else Modifier.clearAndSetSemantics{}).graphicsLayer{
val c=progress()
compositingStrategy=CompositingStrategy.ModulateAlpha
if(hero){alpha=(1f-c*1.6f).coerceIn(0f,1f);translationY=-lift*c}
else{alpha=((c-.3f)/.7f).coerceIn(0f,1f);translationY=lift*(1f-c)}
}){content()}
}
/**
* Swaps [item] Silo-style: the outgoing copy lifts slightly as it fades; the next rises into
* place as it fades in. Two keyed layers driven by one animation, read only while drawing.
*/
@Composable internal fun <T:Any> FadingCopy(item:T?,id:(T)->String,lift:Float,modifier:Modifier=Modifier,contentAlignment:Alignment=Alignment.TopStart,content:@Composable (T)->Unit) {
val progress=remember{Animatable(1f)}
var shown by remember{mutableStateOf(item)}
var leaving by remember{mutableStateOf<T?>(null)}
LaunchedEffect(item?.let(id)) {
val previous=shown
shown=item
if(previous==null||item==null){leaving=null;progress.snapTo(1f);return@LaunchedEffect}
if(id(previous)==id(item))return@LaunchedEffect
leaving=previous
progress.snapTo(0f)
progress.animateTo(1f,tween(CopyMillis,easing=FastOutSlowInEasing))
leaving=null
}
// The same title with fresher details updates in place.
val current=if(item!=null&&shown?.let(id)==id(item))item else shown
Box(modifier,contentAlignment=contentAlignment) {
listOfNotNull(leaving,current).forEach{entry->
val outgoing=entry===leaving
key(id(entry)) {
Box(Modifier.graphicsLayer{
val t=progress.value
compositingStrategy=CompositingStrategy.ModulateAlpha
if(outgoing){alpha=(1f-t*2.5f).coerceAtLeast(0f);translationY=-lift*.66f*t}
else{alpha=((t-.2f)/.8f).coerceIn(0f,1f);translationY=lift*(1f-t)}
}){CompositionLocalProvider(LocalStagedCopy provides(!outgoing&&leaving!=null)){content(entry)}}
}
}
}
}
/** True for a [FadingCopy] entry that is fading in: it stays transparent for its first five or so frames. */
private val LocalStagedCopy=staticCompositionLocalOf{false}
/**
* How many of a copy's [total] parts to compose. An incoming copy adds one per frame while it is
* still transparent: composing and measuring all of a preview's text at once took 12 ms on the onn.
*/
@Composable private fun copyParts(total:Int):Int {
val staged=LocalStagedCopy.current
var parts by remember{mutableIntStateOf(if(staged)1 else total)}
if(parts<total)LaunchedEffect(Unit){while(parts<total){withFrameNanos{};parts++}}
return parts
}
/** Focus changes invalidate this small preview scope, never the catalog hierarchy. */
@Composable private fun HomeBackdrop(api:PlexApi,preview:State<Title?>,feature:Title?,heroMode:State<Boolean>,wash:Boolean) {
val target=if(heroMode.value)feature?.let{it.art.ifBlank{it.thumb} to true}else preview.value?.let{previewArt(it) to false}
// Keep the last artwork while the preview waits for its first resting card.
val last=remember{arrayOfNulls<Pair<String,Boolean>>(1)}
val shown=target ?: last[0] ?: feature?.let{it.art.ifBlank{it.thumb} to true}
last[0]=shown
shown?.let{(path,cinematic)->BrowseBackdrop(api,path,Modifier.fillMaxSize(),cinematic=cinematic,header=true,wash=wash,animate=true)}
}
@Composable private fun FocusedPreviewCanvas(vm:KaleidoViewModel,preview:State<Title?>,fallback:Title?,wash:Boolean) {
val feature=preview.value ?: fallback
Box(Modifier.fillMaxSize()) { Box(Modifier.fillMaxSize()) {
feature?.let{item-> feature?.let{BrowseBackdrop(vm.api,previewArt(it),Modifier.fillMaxSize(),header=true,wash=wash,animate=true)}
BrowseBackdrop(vm.api,item.art,Modifier.fillMaxSize()) Box(Modifier.padding(start=Cinema.gutter,top=104.dp).height(SectionPreviewHeight)) {
Column(Modifier.padding(start=Cinema.gutter,top=106.dp).width(350.dp).clearAndSetSemantics{contentDescription=listOf(item.displayTitle,metadata?.rating.orEmpty(),item.summary).filter{it.isNotBlank()}.joinToString(". ")}) { PreviewBlock(vm,feature,SectionLogo)
TitleIdentity(vm.api,item,Modifier.width(if(destination=="tv")230.dp else 260.dp).height(if(destination=="tv")43.dp else 53.dp))
Row(Modifier.fillMaxWidth().padding(top=7.dp,bottom=5.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else item.year,item.genres.firstOrNull().orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),fontSize=10.sp,lineHeight=14.sp,color=Cinema.secondary,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(metadata ?: item,Modifier.padding(start=10.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=11.5.sp,lineHeight=16.sp,maxLines=2,overflow=TextOverflow.Ellipsis)
} }
} }
}
@Composable private fun HomePreview(vm:KaleidoViewModel,preview:State<Title?>)=PreviewBlock(vm,preview.value,HomeLogo)
/** Bottom-anchored like Silo's: a shorter synopsis leaves room above the title, not a gap above the rows. */
@Composable private fun PreviewBlock(vm:KaleidoViewModel,item:Title?,logo:DpSize) {
FadingCopy(item,{it.id},with(LocalDensity.current){HeaderLift.toPx()},Modifier.fillMaxHeight(),Alignment.BottomStart){PreviewText(vm,it,logo)}
}
/** The focused card: large title art, the facts, three lines of synopsis, then cast and format. */
@Composable private fun PreviewText(vm:KaleidoViewModel,item:Title,logo:DpSize) {
var loaded by remember{mutableStateOf(false)}
val metadata by produceState(item,item){value=vm.previewDetails(item);loaded=true}
// Cast and formats need the full details. Their rows are reserved, and fade in when they arrive.
val details=remember{Animatable(0f)}
LaunchedEffect(loaded){if(loaded)details.animateTo(1f,tween(220))}
val formats=formatLabels(metadata.media.firstOrNull())
val runtime=when{item.duration<=0->"";item.offset>0->runtimeLabel(item.duration-item.offset)+" left";else->runtimeLabel(item.duration)}
Column(Modifier.width(420.dp).clearAndSetSemantics{contentDescription=listOf(item.displayTitle,metadata.rating,item.summary).filter{it.isNotBlank()}.joinToString(". ")}) {
val parts=copyParts(4)
TitleIdentity(vm.api,item,Modifier.size(logo))
if(parts>=2)Row(Modifier.fillMaxWidth().padding(top=10.dp,bottom=7.dp).height(17.dp),verticalAlignment=Alignment.CenterVertically) {
if(item.contentRating.isNotBlank())FormatBadge(item.contentRating,Modifier.padding(end=8.dp))
Text(listOf(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else item.year,item.genres.firstOrNull().orEmpty(),runtime).filter{it.isNotBlank()}.joinToString(" · "),fontSize=11.sp,lineHeight=15.sp,color=Cinema.secondary,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(metadata,Modifier.padding(start=10.dp))
}
if(parts>=3)Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=17.5.sp,maxLines=3,overflow=TextOverflow.Ellipsis)
if(parts>=4)Column(Modifier.graphicsLayer{alpha=details.value}) {
Text(metadata.cast.take(3).joinToString(", "),color=Muted,fontSize=10.5.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=6.dp).height(14.dp))
Row(Modifier.padding(top=8.dp).height(16.dp),horizontalArrangement=Arrangement.spacedBy(6.dp),verticalAlignment=Alignment.CenterVertically) {
formats.forEach{FormatBadge(it)}
}
}
}
}
/** Resolution, dynamic range and the best audio format, e.g. 4K · Dolby Vision · Atmos. */
internal fun formatLabels(media:Media?)=listOfNotNull(media?.resolutionLabel?.ifBlank{null},media?.dynamicRange?.ifBlank{null},media?.let{if(it.atmos)"Atmos"else it.channelLabel.ifBlank{null}})
/** A small outlined label: a content rating or a video/audio format. */
@Composable internal fun FormatBadge(label:String,modifier:Modifier=Modifier) {
Text(label.uppercase(),color=Color.White.copy(alpha=.9f),fontSize=8.5.sp,lineHeight=11.sp,fontWeight=FontWeight.SemiBold,letterSpacing=.5.sp,maxLines=1,
modifier=modifier.border(.5.dp,Color.White.copy(alpha=.3f),RoundedCornerShape(3.dp)).background(Color.White.copy(alpha=.06f),RoundedCornerShape(3.dp)).padding(horizontal=5.dp,vertical=1.5.dp))
}
internal fun runtimeLabel(ms:Long):String {val minutes=(ms/60000).coerceAtLeast(1);return if(minutes>=60)"${minutes/60}h ${minutes%60}m"else "${minutes}m"}
@Composable private fun HeroCopy(vm:KaleidoViewModel,feature:HomeFeature) {
val item=feature.item
val metadata by produceState(item,item.id){value=item;value=vm.previewDetails(item)}
Column {
val parts=copyParts(3)
TitleIdentity(vm.api,item,Modifier.width(264.dp).height(80.dp))
if(parts>=2)Row(Modifier.fillMaxWidth().padding(top=8.dp,bottom=8.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.year,item.genres.firstOrNull().orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=10.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(metadata,Modifier.padding(start=10.dp))
}
if(parts>=3)Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis)
} }
} }
/** /**
* A newly shown section composed every visible card in one 100–200 ms frame. While it is * A newly shown section composed every visible card in one 100–200 ms frame. While it is
* entering, each card first lays out at its fixed size and fills in its artwork and titles a * entering, each card first lays out at its fixed size and fills in its artwork and titles a
* few cards per frame, under the page's fade-in. Later offscreen cards spread their * few cards per frame, under the page's fade-in. Later cards are composed whole: they come from
* artwork/text work over three frames too, keeping lazy-layout work short during input. * the lazy lists' cache windows, which compose and measure them in idle time. Deferring their
* content instead moved that text layout into the next frames' synchronous layout, in the middle
* of the row scroll (about 1 ms per title on the onn).
*/ */
private class CardStaging { private class CardStaging {
var entering=true var entering=true
private var count=0 private var count=0
fun frames()=if(entering)count++/3 else count++%3 fun frames()=if(entering)count++/3 else -1
} }
@Composable private fun BrowseCard(vm:KaleidoViewModel,item:Title,focusKey:String,poster:Boolean,wideEpisode:Boolean,entry:FocusRequester?,requester:FocusRequester,staging:CardStaging,continuing:Boolean,modifier:Modifier,onHovered:(Title)->Unit) { @Composable private fun BrowseCard(vm:KaleidoViewModel,item:Title,focusKey:String,poster:Boolean,wideEpisode:Boolean,entry:FocusRequester?,requester:FocusRequester,staging:CardStaging,continuing:Boolean,modifier:Modifier,onHovered:(Title)->Unit) {
@ -459,7 +704,7 @@ private class CardStaging {
}) { }) {
Box(Modifier.fillMaxWidth().aspectRatio(if(poster)2f/3f else 16f/9f).clip(RoundedCornerShape(4.dp))) { Box(Modifier.fillMaxWidth().aspectRatio(if(poster)2f/3f else 16f/9f).clip(RoundedCornerShape(4.dp))) {
if(filled) { if(filled) {
Artwork(vm.api,image,Modifier.fillMaxSize(),if(poster)300 else 480,if(poster)450 else 270,animate=false) CardArtwork(vm.api,image,Modifier.fillMaxSize(),if(poster)300 else 480,if(poster)450 else 270)
if(item.offset>0)Box(Modifier.align(Alignment.BottomCenter).padding(6.dp).fillMaxWidth().height(2.dp).background(Color.Black.copy(alpha=.65f))) { if(item.offset>0)Box(Modifier.align(Alignment.BottomCenter).padding(6.dp).fillMaxWidth().height(2.dp).background(Color.Black.copy(alpha=.65f))) {
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.01f)).fillMaxHeight().background(Accent)) Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.01f)).fillMaxHeight().background(Accent))
} }
@ -471,7 +716,13 @@ private class CardStaging {
// Placeholder height matches the titles' fixed heights, so card bounds never change. // Placeholder height matches the titles' fixed heights, so card bounds never change.
if(!filled)Spacer(Modifier.height(if(poster)21.dp else 35.dp)) if(!filled)Spacer(Modifier.height(if(poster)21.dp else 35.dp))
else { else {
Text(item.displayTitle,color=if(focused)Accent else Cinema.secondary,fontSize=10.5.sp,lineHeight=14.sp,fontWeight=if(focused)FontWeight.SemiBold else FontWeight.Normal,maxLines=1,overflow=TextOverflow.Ellipsis,style=LocalTextStyle.current.copy(shadow=CaptionShadow),modifier=Modifier.padding(top=5.dp).height(16.dp)) // Both weights are laid out with the card (in prefetch); focus only swaps their layers.
// Changing the weight re-measured two titles in the first frame of every move.
Box(Modifier.padding(top=5.dp).height(16.dp)) {
val title=LocalTextStyle.current.copy(shadow=CaptionShadow)
Text(item.displayTitle,color=Cinema.secondary,fontSize=10.5.sp,lineHeight=14.sp,fontWeight=FontWeight.Normal,maxLines=1,overflow=TextOverflow.Ellipsis,style=title,modifier=Modifier.graphicsLayer{alpha=if(focused)0f else 1f})
Text(item.displayTitle,color=Accent,fontSize=10.5.sp,lineHeight=14.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,style=title,modifier=Modifier.graphicsLayer{alpha=if(focused)1f else 0f})
}
if(!poster)Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else if(item.type=="season")item.subtitle else if(item.offset>0)"${((item.duration-item.offset)/60000).coerceAtLeast(0)} min left"else item.year,color=Cinema.secondary.copy(alpha=.85f),fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,style=LocalTextStyle.current.copy(shadow=CaptionShadow),modifier=Modifier.height(14.dp)) if(!poster)Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else if(item.type=="season")item.subtitle else if(item.offset>0)"${((item.duration-item.offset)/60000).coerceAtLeast(0)} min left"else item.year,color=Cinema.secondary.copy(alpha=.85f),fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,style=LocalTextStyle.current.copy(shadow=CaptionShadow),modifier=Modifier.height(14.dp))
} }
} }
@ -496,3 +747,32 @@ private class CardStaging {
Spacer(Modifier.height(if(poster)21.dp else 35.dp)) Spacer(Modifier.height(if(poster)21.dp else 35.dp))
} }
} }
/**
* Semantics only while [onScreen]. With any accessibility service enabled, Compose walks and
* geometry-sorts every composed node, placed or not, after each layout change (every 100 ms while
* rows scroll): the rows and cards the lazy lists keep composed off screen made that the largest
* main-thread cost on the onn. Observed in the node, so entering or leaving view never recomposes.
*/
internal fun Modifier.semanticsOnScreen(onScreen:()->Boolean):Modifier=this then OnScreenSemanticsElement(onScreen)
private class OnScreenSemanticsElement(val onScreen:()->Boolean):ModifierNodeElement<OnScreenSemanticsNode>() {
override fun create()=OnScreenSemanticsNode(onScreen)
override fun update(node:OnScreenSemanticsNode){node.onScreen=onScreen;node.check()}
override fun equals(other:Any?)=other is OnScreenSemanticsElement&&other.onScreen===onScreen
override fun hashCode()=System.identityHashCode(onScreen)
}
private class OnScreenSemanticsNode(var onScreen:()->Boolean):Modifier.Node(),SemanticsModifierNode,ObserverModifierNode {
private var shown=true
override val shouldClearDescendantSemantics get()=!shown
override fun SemanticsPropertyReceiver.applySemantics(){}
override fun onAttach()=check()
override fun onObservedReadsChanged()=check()
fun check() {
if(!isAttached)return
var now=true
observeReads{now=onScreen()}
if(now!=shown){shown=now;invalidateSemantics()}
}
}

View file

@ -0,0 +1,77 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import android.os.Handler
import android.os.Looper
import android.view.Choreographer
import androidx.compose.foundation.lazy.LazyListPrefetchStrategy
import androidx.compose.foundation.lazy.layout.LazyLayoutCacheWindow
import androidx.compose.foundation.lazy.layout.NestedPrefetchScope
import androidx.compose.ui.unit.Constraints
import androidx.compose.foundation.lazy.layout.PrefetchRequest
import androidx.compose.foundation.lazy.layout.PrefetchRequestScope
import androidx.compose.foundation.lazy.layout.PrefetchScheduler
/**
* Runs lazy-list prefetch in what is left of each frame. Compose's scheduler treats a frame that
* follows a late one as idle and gives its request unlimited time: on the onn it then composed a
* whole row of cards (35–45 ms) in the middle of the row scroll, dropping the frames it meant to
* save. Here a request that needs more than the frame has left waits for the next; only when
* nothing has been drawn for two frames (truly idle) may it take as long as it needs, since a
* whole row is more than one frame's work and must be ready before the next move.
*/
internal object FramePrefetch:PrefetchScheduler,Choreographer.FrameCallback,Runnable,PrefetchRequestScope {
/** The display's frame interval; MainActivity sets it from the actual refresh rate. */
var frameNanos=16_666_667L
/** Left for input and the frame's own late work. */
private const val MarginNanos=2_000_000L
private val requests=ArrayDeque<PrefetchRequest>()
private val handler=Handler(Looper.getMainLooper())
private var scheduled=false
private var deadline=0L
private var lastDraw=0L
private val stalls=java.util.IdentityHashMap<PrefetchRequest,Int>()
/** About two seconds of frames without progress before a request is dropped. */
private const val StallFrames=120
/** Called for every window draw (MainActivity's draw listener). */
fun drew(){lastDraw=System.nanoTime()}
override fun schedulePrefetch(prefetchRequest:PrefetchRequest) {
requests.addLast(prefetchRequest)
if(!scheduled){scheduled=true;Choreographer.getInstance().postFrameCallback(this)}
}
// Posted from the frame callback, this runs once the frame's layout and draw are done.
override fun doFrame(frameTimeNanos:Long) {
deadline=if(frameTimeNanos-lastDraw>2*frameNanos)Long.MAX_VALUE else frameTimeNanos+frameNanos-MarginNanos
handler.post(this)
}
override fun availableTimeNanos()=(deadline-System.nanoTime()).coerceAtLeast(0L)
override fun run() {
var skipped=0
while(requests.isNotEmpty()&&skipped<requests.size&&availableTimeNanos()>0) {
val request=requests.removeFirst()
val start=System.nanoTime()
// True means it has more work, but not enough time for its next step in this frame.
val more=with(request){execute()}
val worked=System.nanoTime()-start>200_000L
if(!more){stalls.remove(request);skipped=0;continue}
if(worked){stalls.remove(request);requests.addFirst(request);break}
// No progress: let the rest go first. A request for a list nobody lays out (a hidden
// screen's) never progresses, and must not hold up the visible screen's rows.
val misses=(stalls[request] ?: 0)+1
if(misses>=StallFrames)stalls.remove(request)else{stalls[request]=misses;requests.addLast(request)}
skipped++
}
if(requests.isNotEmpty())Choreographer.getInstance().postFrameCallback(this)else scheduled=false
}
}
/** Compose's cache window ([ahead] and [behind] in viewports), prefetching on [FramePrefetch]. */
internal fun budgetedCacheWindow(ahead:Float,behind:Float):LazyListPrefetchStrategy=
CacheWindows(LazyLayoutCacheWindow(aheadFraction=ahead,behindFraction=behind))
/**
* For [CacheWindows]: compose and measure a rail's card while the catalog prefetches its row.
* Only composing it left its text layout to the row's first frame on screen, mid-scroll.
*/
internal fun NestedPrefetchScope.premeasure(index:Int)=schedulePrecompositionAndPremeasure(index,Constraints())

View file

@ -1,6 +1,6 @@
package tv.kaleido.app package tv.kaleido.app
data class HomeFeature(val item:Title,val reason:String) data class HomeFeature(val item:Title)
/** Interleave discovery categories; Continue Watching has its own rail. */ /** Interleave discovery categories; Continue Watching has its own rail. */
internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,continuing:List<Title>,random:kotlin.random.Random=kotlin.random.Random.Default):List<HomeFeature> { internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,continuing:List<Title>,random:kotlin.random.Random=kotlin.random.Random.Default):List<HomeFeature> {
@ -9,10 +9,10 @@ internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,co
item.id !in excluded&&!item.fullyWatched&&item.offset==0L item.id !in excluded&&!item.fullyWatched&&item.offset==0L
// Shuffle movies and shows together rather than always leading with the same movie section. // Shuffle movies and shows together rather than always leading with the same movie section.
val buckets=listOf( val buckets=listOf(
recent.filter{eligible(it)&&it.releaseDate.isNotBlank()}.sortedByDescending{it.releaseDate}.take(18).shuffled(random).map{HomeFeature(it,"Recently released")}, recent.filter{eligible(it)&&it.releaseDate.isNotBlank()}.sortedByDescending{it.releaseDate}.take(18).shuffled(random).map{HomeFeature(it)},
rated.filter{eligible(it)&&it.viewedLeafCount==0}.shuffled(random).map{HomeFeature(it,"Highly rated · Unwatched")}, rated.filter{eligible(it)&&it.viewedLeafCount==0}.shuffled(random).map{HomeFeature(it)},
hubs.filterNot{h->listOf("continue","ondeck","inprogress","recentlyviewed","recentlyadded","recentlyaired","recent").any{h.id.contains(it,true)}} hubs.filterNot{h->listOf("continue","ondeck","inprogress","recentlyviewed","recentlyadded","recentlyaired","recent").any{h.id.contains(it,true)}}
.flatMap{it.items}.filter(::eligible).distinctBy{it.id}.shuffled(random).map{HomeFeature(it,"Suggested for you")} .flatMap{it.items}.filter(::eligible).distinctBy{it.id}.shuffled(random).map{HomeFeature(it)}
) )
val seen=mutableSetOf<String>() val seen=mutableSetOf<String>()
return buildList { return buildList {

View file

@ -22,10 +22,24 @@ import coil.request.Disposable
import java.util.concurrent.Executors import java.util.concurrent.Executors
import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="",val actor:CastMember?=null) data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="",val actor:CastMember?=null)
private data class SectionContent(val hubs:List<Hub>,val genres:List<Pair<String,String>>,val library:LibraryPage) private data class SectionContent(val hubs:List<Hub>,val genres:List<Pair<String,String>>,val library:LibraryPage)
private data class HomeContent(val hubs:List<Hub>,val features:List<HomeFeature>) private data class HomeContent(val hubs:List<Hub>,val features:List<HomeFeature>)
private fun Title.artworkPath():String=art.ifBlank{thumb}
private fun categoryArtworkHint(section:Section,genre:String):String?=when {
section.type=="show"&&genre.equals("Animation",ignoreCase=true)->"Hazbin"
section.type=="movie"&&genre.equals("Action",ignoreCase=true)->"Batman"
else->null
}
private const val SyncQuietMillis=2000L
/** The countdown an earlier "Automatically" skip setting becomes. */
internal const val AutoSkipDefaultSeconds=5
/** Returning to Kaleido checks the server almost at once, so watching elsewhere shows up promptly. */
private const val ResumeSyncDelayMillis=750L
private const val PlaybackReportWaitMillis=4_000L
class KaleidoViewModel(app: Application): AndroidViewModel(app) { class KaleidoViewModel(app: Application): AndroidViewModel(app) {
val application = app as KaleidoApplication val application = app as KaleidoApplication
val api = application.api val api = application.api
@ -39,23 +53,47 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var sections by mutableStateOf(emptyList<Section>()); private set var sections by mutableStateOf(emptyList<Section>()); private set
var homeHubs by mutableStateOf(emptyList<Hub>()); private set var homeHubs by mutableStateOf(emptyList<Hub>()); private set
var homeFeatures by mutableStateOf(emptyList<HomeFeature>()); private set var homeFeatures by mutableStateOf(emptyList<HomeFeature>()); private set
var discoverHubs by mutableStateOf(emptyList<Hub>()); private set private var discoverHubsState by mutableStateOf(emptyList<Hub>())
var discoverHubs:List<Hub>
get()=discoverHubsState
private set(value){discoverHubsState=value;publishDiscovery(value)}
/**
* Rows per destination, for the Movies and TV screens that stay composed while hidden. A reload of
* the same library keeps its previous rows until the fresh ones arrive (equal rows keep their
* instances), so a retained screen neither empties nor recomposes its cards.
*/
var movieHubs by mutableStateOf(emptyList<Hub>()); private set
var showHubs by mutableStateOf(emptyList<Hub>()); private set
private val discoverySections=mutableMapOf<String,String?>()
fun discoveryHubs(destination:String)=when(destination){"home"->homeHubs;"movies"->movieHubs;else->showHubs}
private fun publishDiscovery(hubs:List<Hub>) {
val destination=when(section?.type){"movie"->"movies";"show"->"tv";else->pages.first().kind.takeIf{it in listOf("movies","tv")}} ?: return
val sectionId=section?.id
if(hubs.isEmpty()&&sectionId!=null&&discoverySections[destination]==sectionId)return
discoverySections[destination]=sectionId
if(destination=="movies")movieHubs=hubs else showHubs=hubs
}
private fun clearDiscovery(){discoverySections.clear();movieHubs=emptyList();showHubs=emptyList()}
var library by mutableStateOf(emptyList<Title>()); private set var library by mutableStateOf(emptyList<Title>()); private set
var total by mutableStateOf(0); private set var total by mutableStateOf(0); private set
var genres by mutableStateOf(emptyList<Pair<String,String>>()); private set var genres by mutableStateOf(emptyList<Pair<String,String>>()); private set
var categoryArtwork by mutableStateOf<Map<String,Title>>(emptyMap()); private set
var section by mutableStateOf<Section?>(null); private set var section by mutableStateOf<Section?>(null); private set
var sort by mutableStateOf("titleSort:asc"); private set var sort by mutableStateOf("titleSort:asc"); private set
var genre by mutableStateOf(""); private set var genre by mutableStateOf(""); private set
var unwatched by mutableStateOf(false); private set var unwatched by mutableStateOf(false); private set
var allTitles by mutableStateOf(false); private set var allTitles by mutableStateOf(false); private set
var categories by mutableStateOf(false); private set
var libraryJumpIndex by mutableIntStateOf(-1); private set
var libraryJumpRequest by mutableIntStateOf(0); private set
var libraryFocusRequest by mutableIntStateOf(0); private set
var libraryJumpLetter by mutableStateOf<String?>(null); private set
var detail by mutableStateOf<Title?>(null); private set var detail by mutableStateOf<Title?>(null); private set
var children by mutableStateOf(emptyList<Title>()); private set var children by mutableStateOf(emptyList<Title>()); private set
var detailRelated by mutableStateOf(emptyList<Title>()); private set var detailRelated by mutableStateOf(emptyList<Title>()); private set
var actorTitles by mutableStateOf(emptyList<Title>()); private set var actorTitles by mutableStateOf(emptyList<Title>()); private set
var markingId by mutableStateOf<String?>(null); private set var markingId by mutableStateOf<String?>(null); private set
var searchResults by mutableStateOf(SearchResults()); private set var searchResults by mutableStateOf(SearchResults()); private set
/** A voice search should start when Search opens, e.g. from the remote's search key. */
var voicePending by mutableStateOf(false); private set
/** The long-press/Menu actions sheet, and the row it came from (for Remove from Continue Watching). */ /** The long-press/Menu actions sheet, and the row it came from (for Remove from Continue Watching). */
var contextItem by mutableStateOf<Title?>(null); private set var contextItem by mutableStateOf<Title?>(null); private set
var contextFromContinue by mutableStateOf(false); private set var contextFromContinue by mutableStateOf(false); private set
@ -64,7 +102,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var playbackReturn by mutableIntStateOf(0); private set var playbackReturn by mutableIntStateOf(0); private set
private var retryAction:(()->Unit)?=null private var retryAction:(()->Unit)?=null
private var previousTab="home" private var previousTab="home"
private val mediaChoices=mutableMapOf<String,Int>() /** Observable, so the version button, format badges and technical line all follow a new choice. */
private val mediaChoices=androidx.compose.runtime.mutableStateMapOf<String,Int>()
/** The episode a season or episode page shows, by page id. Focus in its season row chooses it. */ /** The episode a season or episode page shows, by page id. Focus in its season row chooses it. */
val episodeSelections=androidx.compose.runtime.mutableStateMapOf<String,String>() val episodeSelections=androidx.compose.runtime.mutableStateMapOf<String,String>()
var query by mutableStateOf(""); private set var query by mutableStateOf(""); private set
@ -73,6 +112,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var linkingAccount by mutableStateOf(false);private set var linkingAccount by mutableStateOf(false);private set
var accountToken = session?.accountToken.orEmpty() var accountToken = session?.accountToken.orEmpty()
var playing by mutableStateOf<Title?>(null); private set var playing by mutableStateOf<Title?>(null); private set
var playbackInstance by mutableIntStateOf(0);private set
var startFromZero by mutableStateOf(false); private set var startFromZero by mutableStateOf(false); private set
var focusId by mutableStateOf("") var focusId by mutableStateOf("")
var update by mutableStateOf<Release?>(null); private set var update by mutableStateOf<Release?>(null); private set
@ -86,8 +126,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var remoteQuality by mutableStateOf(preferences.getString("remoteQuality",null)?.let{n->StreamQuality.entries.firstOrNull{it.name==n}} ?: StreamQuality.FullHD); private set var remoteQuality by mutableStateOf(preferences.getString("remoteQuality",null)?.let{n->StreamQuality.entries.firstOrNull{it.name==n}} ?: StreamQuality.FullHD); private set
/** Seconds before the next episode starts; 0 turns autoplay off. */ /** Seconds before the next episode starts; 0 turns autoplay off. */
var autoplaySeconds by mutableIntStateOf(preferences.getInt("autoplaySeconds",5)); private set var autoplaySeconds by mutableIntStateOf(preferences.getInt("autoplaySeconds",5)); private set
var autoSkipIntro by mutableStateOf(preferences.getBoolean("autoSkipIntro",false)); private set /** Seconds the Skip intro/credits button counts down before skipping by itself; 0 only shows the button. */
var autoSkipCredits by mutableStateOf(preferences.getBoolean("autoSkipCredits",false)); private set var autoSkipIntroSeconds by mutableIntStateOf(autoSkipSeconds("autoSkipIntro")); private set
var autoSkipCreditsSeconds by mutableIntStateOf(autoSkipSeconds("autoSkipCredits")); private set
var subtitleSize by mutableStateOf(preferences.getString("subtitleSize",null)?.let{n->SubtitleSize.entries.firstOrNull{it.name==n}} ?: SubtitleSize.Normal); private set var subtitleSize by mutableStateOf(preferences.getString("subtitleSize",null)?.let{n->SubtitleSize.entries.firstOrNull{it.name==n}} ?: SubtitleSize.Normal); private set
var subtitleStyle by mutableStateOf(preferences.getString("subtitleStyle",null)?.let{n->SubtitleStyle.entries.firstOrNull{it.name==n}} ?: SubtitleStyle.Box); private set var subtitleStyle by mutableStateOf(preferences.getString("subtitleStyle",null)?.let{n->SubtitleStyle.entries.firstOrNull{it.name==n}} ?: SubtitleStyle.Box); private set
/** Debug test intents force a delivery mode (0 file, 1 direct stream, 2 convert); never set in release. */ /** Debug test intents force a delivery mode (0 file, 1 direct stream, 2 convert); never set in release. */
@ -96,20 +137,34 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var debugValidationFile:File?=null; private set var debugValidationFile:File?=null; private set
var watchedPercent by mutableStateOf(preferences.getInt("watchedPercent",80).coerceIn(50,100)); private set var watchedPercent by mutableStateOf(preferences.getInt("watchedPercent",80).coerceIn(50,100)); private set
var navigationSounds by mutableStateOf(preferences.getBoolean("navigationSounds",true)); private set var navigationSounds by mutableStateOf(preferences.getBoolean("navigationSounds",true)); private set
/** Tint the page behind browse previews with the focused artwork's colour. */
var colourWash by mutableStateOf(preferences.getBoolean("colourWash",true)); private set
var themeMusic by mutableStateOf(preferences.getBoolean("themeMusic",false)); private set
var themeVolume by mutableIntStateOf(preferences.getInt("themeVolume",30).coerceIn(10,100)); private set
var episodeQueue by mutableStateOf(emptyList<Title>());private set var episodeQueue by mutableStateOf(emptyList<Title>());private set
var relatedShows by mutableStateOf(emptyList<Title>());private set var relatedShows by mutableStateOf(emptyList<Title>());private set
var transitioningEpisode by mutableStateOf(false);private set var transitioningEpisode by mutableStateOf(false);private set
private var shuffleEpisodes by mutableStateOf<ShuffleEpisodes<Title>?>(null)
val shuffling get()=shuffleEpisodes!=null
private var episodeContextJob:Job?=null private var episodeContextJob:Job?=null
private var episodeTransitionJob:Job?=null private var episodeTransitionJob:Job?=null
private var loadJob: Job? = null private var loadJob: Job? = null
private var initializeJob:Job?=null private var initializeJob:Job?=null
private var librarySyncJob:Job?=null private var librarySyncJob:Job?=null
/** Uptime of the latest remote key, from the UI; library sync applies its snapshot only after a quiet spell. */
var lastInteraction=0L
private var foreground=false private var foreground=false
private var loadGeneration=0 private var loadGeneration=0
private var authJob: Job? = null private var authJob: Job? = null
private var searchJob: Job? = null private var searchJob: Job? = null
private var categoryArtworkJob: Job? = null
private var categoryArtworkSectionId = ""
private var categoryArtworkGeneration = 0
private var categoryArtworkGenres=emptyList<Pair<String,String>>()
private var categoryArtworkComplete=false
private val detailsCache = mutableMapOf<String,Title>() private val detailsCache = mutableMapOf<String,Title>()
private val sectionCache=mutableMapOf<String,SectionContent>() private val sectionCache=mutableMapOf<String,SectionContent>()
private val characterOffsetCache=mutableMapOf<LibraryCharacterQuery,Map<String,Int>>()
private var sectionStale=false private var sectionStale=false
private val featureSeed=kotlin.random.Random.nextInt() private val featureSeed=kotlin.random.Random.nextInt()
private val previews=PreviewMetadata(viewModelScope){api.details(it.id)} private val previews=PreviewMetadata(viewModelScope){api.details(it.id)}
@ -119,6 +174,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
Thread({android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);task.run()},"KaleidoArtworkPrefetch").apply{isDaemon=true} Thread({android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);task.run()},"KaleidoArtworkPrefetch").apply{isDaemon=true}
}.asCoroutineDispatcher() }.asCoroutineDispatcher()
init { init {
// Volume boost was removed; drop its stored level.
if(preferences.contains("volumeBoostDb"))preferences.edit().remove("volumeBoostDb").apply()
// Development provisioning is private app data, never an APK resource or build constant. // Development provisioning is private app data, never an APK resource or build constant.
if(BuildConfig.DEBUG) { if(BuildConfig.DEBUG) {
val seed=File(app.filesDir,"bootstrap.json") val seed=File(app.filesDir,"bootstrap.json")
@ -186,24 +243,29 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
librarySyncJob?.cancel();librarySyncJob=null librarySyncJob?.cancel();librarySyncJob=null
if(!value)return if(!value)return
librarySyncJob=viewModelScope.launch { librarySyncJob=viewModelScope.launch {
var observedSession=session // Kept across background spells: returning compares against what was last applied,
var sync=newLibrarySync() // so Continue Watching changes made on another device show up within a second.
var interval=LibrarySync.POLL_MS var interval=ResumeSyncDelayMillis
var backoff=LibrarySync.POLL_MS
while(isActive) { while(isActive) {
delay(interval) delay(interval);interval=backoff
if(session!=observedSession){observedSession=session;sync=newLibrarySync()} val sync=librarySync?.takeIf{librarySyncSession==session} ?: newLibrarySync().also{librarySync=it;librarySyncSession=session}
if(session==null||playing!=null||busy||markingId!=null||initializeJob?.isActive==true)continue if(session==null||playing!=null||busy||markingId!=null||initializeJob?.isActive==true)continue
try{sync.check();interval=LibrarySync.POLL_MS} try{sync.check();backoff=LibrarySync.POLL_MS}
catch(e:CancellationException){throw e} catch(e:CancellationException){throw e}
catch(_:Exception){interval=(interval*2).coerceAtMost(LibrarySync.FALLBACK_MS)} catch(_:Exception){backoff=(backoff*2).coerceAtMost(LibrarySync.FALLBACK_MS)}
interval=backoff
} }
} }
} }
private fun newLibrarySync()=LibrarySync(api::libraryRevision,::syncLibrary,android.os.SystemClock::elapsedRealtime) private var librarySyncSession:Session?=null
private var librarySync:LibrarySync?=null
/** Library contents plus Continue Watching progress, which changes when anything is watched elsewhere. */
private fun newLibrarySync()=LibrarySync({api.libraryRevision()+"#"+api.continueWatchingRevision()},::syncLibrary,android.os.SystemClock::elapsedRealtime)
private suspend fun syncLibrary():Boolean { private suspend fun syncLibrary():Boolean {
val expectedSession=session ?: return false val expectedSession=session ?: return false
val expectedPage=page;val generation=loadGeneration val expectedPage=page;val generation=loadGeneration
val expectedSection=section;val expectedSort=sort;val expectedGenre=genre;val expectedUnwatched=unwatched val expectedSection=section;val expectedSort=sort;val expectedGenre=genre;val expectedUnwatched=unwatched;val expectedCategories=categories;val expectedAllTitles=allTitles
val freshSections=api.sections() val freshSections=api.sections()
val freshHome=fetchHome(freshSections) val freshHome=fetchHome(freshSections)
val sectionPage=expectedPage.kind in listOf("movies","tv") val sectionPage=expectedPage.kind in listOf("movies","tv")
@ -215,7 +277,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
// Preserve the loaded range and selected filters, instead of resetting the A-Z grid. // Preserve the loaded range and selected filters, instead of resetting the A-Z grid.
val freshSection=active?.let{s-> val freshSection=active?.let{s->
val raw=api.hubs(s.id);val newGenres=api.genres(s.id) val raw=api.hubs(s.id);val newGenres=api.genres(s.id)
val p=api.library(s.id,sort=expectedSort,genre=expectedGenre,unwatched=expectedUnwatched,size=library.size.coerceAtLeast(100)) val p=api.library(s.id,sort=expectedSort,genre=expectedGenre,unwatched=expectedUnwatched,size=library.size.coerceAtLeast(100),type=plexLibraryType(s.type))
val seasons=if(s.type=="show")api.recentSeasons(s.id)else emptyList() val seasons=if(s.type=="show")api.recentSeasons(s.id)else emptyList()
val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+ val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+
if(seasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",seasons))else emptyList() if(seasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",seasons))else emptyList()
@ -223,12 +285,16 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
val detailSnapshot=detail?.takeIf{expectedPage.kind in listOf("details","group")&&it.type in listOf("show","season","collection")} val detailSnapshot=detail?.takeIf{expectedPage.kind in listOf("details","group")&&it.type in listOf("show","season","collection")}
val freshChildren=detailSnapshot?.let{api.children(it.id)} val freshChildren=detailSnapshot?.let{api.children(it.id)}
// Applying rebuilds every changed row (Plex varies some hubs on each request), which dropped
// frames when it landed mid-move. Wait until the remote has been quiet, then validate.
while(android.os.SystemClock.uptimeMillis()-lastInteraction<SyncQuietMillis)delay(250)
// All loads above are staged. A tab/filter/session change must win over this snapshot. // All loads above are staged. A tab/filter/session change must win over this snapshot.
if(!foreground||session!=expectedSession||page!=expectedPage||generation!=loadGeneration|| if(!foreground||session!=expectedSession||page!=expectedPage||generation!=loadGeneration||
section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched|| section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched||categories!=expectedCategories||allTitles!=expectedAllTitles||
playing!=null||busy||markingId!=null)return false playing!=null||busy||markingId!=null)return false
sections=freshSections;homeHubs=freshHome.hubs;homeFeatures=freshHome.features sections=freshSections;homeHubs=freshHome.hubs;homeFeatures=freshHome.features
sectionCache.clear();detailsCache.clear();previews.clear() android.util.Log.i("KaleidoSync","APPLIED continue=${freshHome.hubs.firstOrNull{it.id=="continue"}?.items?.size ?: 0}")
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear()
sectionStale=freshSection==null sectionStale=freshSection==null
if(freshSection!=null){section=active;discoverHubs=freshSection.hubs;genres=freshSection.genres;library=freshSection.library.items;total=freshSection.library.total} if(freshSection!=null){section=active;discoverHubs=freshSection.hubs;genres=freshSection.genres;library=freshSection.library.items;total=freshSection.library.total}
else if(sectionPage){section=null;discoverHubs=emptyList();genres=emptyList();library=emptyList();total=0} else if(sectionPage){section=null;discoverHubs=emptyList();genres=emptyList();library=emptyList();total=0}
@ -238,16 +304,23 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
suspend fun previewDetails(item:Title):Title { suspend fun previewDetails(item:Title):Title {
return try{previews.details(item)}catch(e:CancellationException){throw e}catch(_:Exception){item} return try{previews.details(item)}catch(e:CancellationException){throw e}catch(_:Exception){item}
} }
fun anticipate(item:Title,cinematic:Boolean=false,backdrop:Boolean=true) { fun anticipate(item:Title,cinematic:Boolean=false,backdrop:Boolean=true,path:String=item.art.ifBlank{item.thumb},header:Boolean=false) {
previews.anticipate(item) previews.anticipate(item)
val path=item.art.ifBlank{item.thumb} val wash=header&&colourWash
val key=if(backdrop)"$cinematic:$path"else "" val key=if(backdrop)"$cinematic:$header:$wash:$path"else ""
if(key!=predictedArtworkKey){ if(key!=predictedArtworkKey){
predictedArtwork?.dispose();predictedArtwork=null;predictedArtworkKey=key predictedArtwork?.dispose();predictedArtwork=null;predictedArtworkKey=key
if(backdrop)browseBackdropRequest(application,api,path,cinematic)?.let{predictedArtwork=application.imageLoader.enqueue(it.newBuilder().dispatcher(artworkPrefetchDispatcher).build())} if(backdrop)browseBackdropRequest(application,api,path,cinematic,header,wash)?.let{predictedArtwork=application.imageLoader.enqueue(it.newBuilder().dispatcher(artworkPrefetchDispatcher).build())}
} }
} }
private fun cancelAnticipation(){previews.cancelPrediction();predictedArtwork?.dispose();predictedArtwork=null;predictedArtworkKey=""} private fun cancelAnticipation(){previews.cancelPrediction();predictedArtwork?.dispose();predictedArtwork=null;predictedArtworkKey=""}
private fun resetCategoryArtwork(sectionId:String?) {
categoryArtworkGeneration++
categoryArtworkJob?.cancel();categoryArtworkJob=null
categoryArtworkSectionId=sectionId.orEmpty()
categoryArtwork=emptyMap()
categoryArtworkGenres=emptyList();categoryArtworkComplete=false
}
override fun onCleared(){cancelAnticipation();artworkPrefetchDispatcher.close();super.onCleared()} override fun onCleared(){cancelAnticipation();artworkPrefetchDispatcher.close();super.onCleared()}
fun linkAccount() { fun linkAccount() {
authJob?.cancel();error=null;pin=null authJob?.cancel();error=null;pin=null
@ -265,24 +338,37 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
fun beginAccountLink(){linkingAccount=true;linkAccount()} fun beginAccountLink(){linkingAccount=true;linkAccount()}
fun cancelAccountLink(){authJob?.cancel();pin=null;servers=emptyList();accountToken=session?.accountToken.orEmpty();linkingAccount=false} fun cancelAccountLink(){authJob?.cancel();pin=null;servers=emptyList();accountToken=session?.accountToken.orEmpty();linkingAccount=false}
/** Rating keys are only unique per server: drop per-title state when the server or account changes. */
private fun clearServerState(){
searchJob?.cancel();searchJob=null;query="";searchResults=SearchResults()
episodeContextJob?.cancel();episodeContextJob=null;episodeTransitionJob?.cancel();episodeTransitionJob=null
episodeQueue=emptyList();relatedShows=emptyList();shuffleEpisodes=null;transitioningEpisode=false
mediaChoices.clear();episodeSelections.clear()
}
fun chooseServer(server: Server) = launchLoad { fun chooseServer(server: Server) = launchLoad {
sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery();clearServerState()
val s=api.connect(server,accountToken); application.secure.save(s);api.session=s;session=s;servers=emptyList();linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome() val s=api.connect(server,accountToken); application.secure.save(s);api.session=s;session=s;servers=emptyList();linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
} }
fun manualConnect(address: String, token: String) = launchLoad { fun manualConnect(address: String, token: String) = launchLoad {
sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery();clearServerState()
require(address.startsWith("https://")||address.startsWith("http://")){"Enter a complete http:// or https:// server address."} require(address.startsWith("https://")||address.startsWith("http://")){"Enter a complete http:// or https:// server address."}
require(token.isNotBlank()){ "Enter an access token." } require(token.isNotBlank()){ "Enter an access token." }
val s=api.validate(Session("",token.trim(),address.trim().trimEnd('/'),"Plex","")) val s=api.validate(Session("",token.trim(),address.trim().trimEnd('/'),"Plex",""))
authJob?.cancel();application.secure.save(s);api.session=s;session=s;linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome() authJob?.cancel();application.secure.save(s);api.session=s;session=s;linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
} }
fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();sections=emptyList();library=emptyList();sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()} fun signOut(){loadJob?.cancel();initializeJob?.cancel();clearServerState();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();clearDiscovery();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()}
/** Back or Cancel from the server picker: keep the current server, or start over with a new sign-in code. */
fun dismissServerPicker(){
loadJob?.cancel();busy=false
if(session==null){servers=emptyList();linkAccount()}else cancelAccountLink()
}
fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) } fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) }
fun tab(kind: String){ fun tab(kind: String){
if(pages.size==1&&page.kind==kind)return if(pages.size==1&&page.kind==kind)return
// Search and Settings return to the browsing tab they were opened from. // Search and Settings return to the browsing tab they were opened from.
if(kind in listOf("search","settings")&&pages.first().kind in listOf("home","movies","tv"))previousTab=pages.first().kind if(kind in listOf("search","settings")&&pages.first().kind in listOf("home","movies","tv"))previousTab=pages.first().kind
cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv"))allTitles=false;pages=listOf(Page(kind));loadPage(true) if(kind!="search"){searchJob?.cancel();searchJob=null}
cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv")){allTitles=false;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null};pages=listOf(Page(kind));loadPage(true)
} }
fun open(item: Title){detailsCache[item.id]=item;episodeSelections.remove(item.id);pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()} fun open(item: Title){detailsCache[item.id]=item;episodeSelections.remove(item.id);pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()}
/** Opens an episode's show, or a season's show. */ /** Opens an episode's show, or a season's show. */
@ -291,26 +377,37 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
/** "View all" for a Plex hub row. */ /** "View all" for a Plex hub row. */
fun openHub(hub:Hub){if(hub.key.isBlank())return;pages=pages+Page("hub",hub.key,hub.title,focusId);focusId="";loadPage()} fun openHub(hub:Hub){if(hub.key.isBlank())return;pages=pages+Page("hub",hub.key,hub.title,focusId);focusId="";loadPage()}
fun openSearch(text:String=""){if(page.kind!="search")tab("search");if(text.isNotBlank())search(text)} fun openSearch(text:String=""){if(page.kind!="search")tab("search");if(text.isNotBlank())search(text)}
fun requestVoiceSearch(){openSearch();voicePending=true}
fun voiceStarted(){voicePending=false}
fun showActions(item:Title,fromContinue:Boolean=false){contextItem=item;contextFromContinue=fromContinue} fun showActions(item:Title,fromContinue:Boolean=false){contextItem=item;contextFromContinue=fromContinue}
fun dismissActions(){contextItem=null;contextFromContinue=false} fun dismissActions(){contextItem=null;contextFromContinue=false}
fun removeFromContinueWatching(item:Title){ fun removeFromContinueWatching(item:Title){
viewModelScope.launch { viewModelScope.launch {
try{api.removeFromContinueWatching(item);homeHubs=loadHome();sectionCache.clear()} try{api.removeFromContinueWatching(item);homeHubs=loadHome();sectionCache.clear();characterOffsetCache.clear()}
catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update Continue Watching."){removeFromContinueWatching(item)}} catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update Continue Watching."){removeFromContinueWatching(item)}}
} }
} }
/** The version (Plex Media) chosen for this title in this session; the first version by default. */ /** The version (Plex Media) chosen for this title in this session; the first version by default. */
fun mediaIndex(item:Title)=(mediaChoices[item.id] ?: 0).coerceIn(0,(item.media.size-1).coerceAtLeast(0)) fun mediaIndex(item:Title)=(mediaChoices[item.id] ?: 0).coerceIn(0,(item.media.size-1).coerceAtLeast(0))
fun chooseMedia(item:Title,index:Int){mediaChoices[item.id]=index;detail=detail?.let{if(it.id==item.id)it.copy()else it}} fun chooseMedia(item:Title,index:Int){mediaChoices[item.id]=index}
fun openActor(actor:CastMember){ fun openActor(actor:CastMember){
if(actor.id.isBlank())return if(actor.id.isBlank())return
pages=pages+Page("actor",actor.id,actor.name,focusId,actor);focusId="";loadPage() pages=pages+Page("actor",actor.id,actor.name,focusId,actor);focusId="";loadPage()
} }
fun back(): Boolean { fun back(): Boolean {
if(playing!=null){stopPlayback();return true} if(playing!=null){stopPlayback();return true}
if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);loadPage();return true} if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);if(pages.last().kind in listOf("movies","tv")&&focusId.startsWith("library:"))libraryFocusRequest++;loadPage();return true}
if(page.kind in listOf("movies","tv")&&allTitles){
if(categories&&genre.isNotBlank()){
val selected=genre
genre=""
focusId="category:$selected"
libraryJumpIndex=-1;libraryJumpLetter=null
refreshLibrary()
return true
}
if(categories){categories=false;allTitles=false;genre="";focusId="discovery-entry";libraryJumpIndex=-1;libraryJumpLetter=null;return true}
setAll(false)
return true
}
if(page.kind in listOf("search","settings")){tab(previousTab);return true} if(page.kind in listOf("search","settings")){tab(previousTab);return true}
if(page.kind!="home"){tab("home");return true} if(page.kind!="home"){tab("home");return true}
return false return false
@ -358,30 +455,167 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
/** Shows [s] in its destination, from cache when possible, with default filters. */ /** Shows [s] in its destination, from cache when possible, with default filters. */
private fun loadSection(s:Section?) { private fun loadSection(s:Section?) {
loadJob?.cancel();section=s;sort="titleSort:asc";genre="";unwatched=false loadJob?.cancel();resetCategoryArtwork(s?.id);section=s;sort="titleSort:asc";genre="";unwatched=false
categories=false;libraryJumpIndex=-1;libraryJumpLetter=null
if(s==null){discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList();return} if(s==null){discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList();return}
val cached=sectionCache[s.id] val cached=sectionCache[s.id]
if(cached!=null){discoverHubs=cached.hubs;genres=cached.genres;library=cached.library.items;total=cached.library.total;busy=false;return} if(cached!=null){discoverHubs=cached.hubs;genres=cached.genres;library=cached.library.items;total=cached.library.total;busy=false;return}
discoverHubs=emptyList();library=emptyList();total=0 discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList()
launchLoad({loadSection(s)}) {coroutineScope { launchLoad({loadSection(s)}) {
val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id)} val content=loadSectionContent(s).also{sectionCache[s.id]=it}
if(section?.id==s.id){discoverHubs=content.hubs;genres=content.genres;library=content.library.items;total=content.library.total}
}
}
private suspend fun loadSectionContent(s:Section):SectionContent=coroutineScope {
val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id,type=plexLibraryType(s.type))}
val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(s.type=="show")async{runCatching{api.recentSeasons(s.id)}.getOrDefault(emptyList())}else null val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(s.type=="show")async{runCatching{api.recentSeasons(s.id)}.getOrDefault(emptyList())}else null
val raw=h.await();val genreList=g.await();val p=l.await();val newSeasons=seasons?.await().orEmpty() val raw=h.await();val genreList=g.await();val p=l.await();val newSeasons=seasons?.await().orEmpty()
val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+if(newSeasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",newSeasons))else emptyList() val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+if(newSeasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",newSeasons))else emptyList()
sectionCache[s.id]=SectionContent(rows,genreList,p) SectionContent(rows,genreList,p)
if(section?.id==s.id){discoverHubs=rows;genres=genreList;library=p.items;total=p.total}
}}
} }
fun chooseSection(s: Section){ fun chooseSection(s: Section){
if(s.id==section?.id)return if(s.id==section?.id)return
val keepCategories=categories
preferences.edit().putString("section.${s.type}",s.id).apply() preferences.edit().putString("section.${s.type}",s.id).apply()
cancelAnticipation();focusId=if(allTitles)"library-entry"else "discovery-entry";loadSection(s) cancelAnticipation();focusId=if(allTitles)"library-entry"else "discovery-entry";loadSection(s)
if(keepCategories){allTitles=true;categories=true;focusId="categories-entry"}
} }
fun setAll(value: Boolean){focusId=if(value)"library-entry"else "discovery-entry";allTitles=value} fun setAll(value: Boolean){
fun filter(sortValue: String=sort,genreValue: String=genre,unwatchedValue: Boolean=unwatched){sort=sortValue;genre=genreValue;unwatched=unwatchedValue;refreshLibrary()} // Genre filtering belongs to Categories; the Library grid always lists the whole section.
private fun refreshLibrary()=launchLoad { val p=api.library(section?.id ?: return@launchLoad,0,sort,genre,unwatched);library=p.items;total=p.total } val hadGenre=genre.isNotBlank();focusId=if(value)"library-entry"else "discovery-entry";allTitles=value;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null
fun more(){if(busy||library.size>=total)return;launchLoad {val p=api.library(section?.id ?: return@launchLoad,library.size,sort,genre,unwatched);library=(library+p.items).distinctBy {it.id};total=p.total}} if(hadGenre)refreshLibrary()
fun search(text: String){query=text;searchJob?.cancel();searchJob=viewModelScope.launch {delay(350);if(text.isBlank()){searchResults=SearchResults();return@launch};busy=true;error=null;try{searchResults=api.search(text)}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Search is unavailable."){search(text)}}finally{busy=false}}} }
fun openCategories(){val hadGenre=genre.isNotBlank();allTitles=true;categories=true;genre="";focusId="categories-entry";libraryJumpIndex=-1;libraryJumpLetter=null;if(hadGenre)refreshLibrary()}
fun loadCategoryArtworks() {
val selectedSection=section ?: return
if(!categories||genre.isNotBlank()||genres.isEmpty())return
if(categoryArtworkSectionId!=selectedSection.id||categoryArtworkGenres!=genres)resetCategoryArtwork(selectedSection.id)
categoryArtworkGenres=genres.toList()
if(categoryArtworkComplete||categoryArtworkJob?.isActive==true)return
val sectionId=selectedSection.id
val sectionType=selectedSection.type
val generation=categoryArtworkGeneration
val entries=genres.toList()
fun ordered(entry:Pair<String,String>,items:List<Title>):List<Title> {
val hint=categoryArtworkHint(selectedSection,entry.second)
return items.filter{it.type==sectionType&&it.artworkPath().isNotBlank()}.distinctBy{it.id}
.sortedBy{if(hint!=null&&it.title.contains(hint,ignoreCase=true))0 else 1}
}
val candidates=entries.associate{entry->entry.first to ordered(entry,library.filter{item->item.genres.any{it.equals(entry.second,ignoreCase=true)}})}.toMutableMap()
fun choose()=selectCategoryArtwork(candidates){categoryArtworkIdentity(it.artworkPath())}
// The initial cached samples follow the same uniqueness rule as network results.
if(categoryArtwork.isEmpty())categoryArtwork=choose()
categoryArtworkJob=viewModelScope.launch {
val requestGate=Semaphore(3)
val offsets=mutableMapOf<String,Int>()
val totals=mutableMapOf<String,Int>()
var failed=false
fun current()=generation==categoryArtworkGeneration&&categoryArtworkSectionId==sectionId&&section?.id==sectionId
suspend fun fetch(batch:List<Pair<String,String>>,first:Boolean=false) {
val pages=coroutineScope {batch.map{entry->async {
requestGate.withPermit {
val hint=categoryArtworkHint(selectedSection,entry.second)
entry to try {
api.library(sectionId,start=offsets[entry.first] ?: 0,sort="titleSort:asc",genre=entry.first,size=if(first&&hint!=null)80 else 32,type=plexLibraryType(sectionType))
}catch(e:CancellationException){throw e}catch(_:Exception){null}
}
}}.awaitAll()}
for((entry,page) in pages) {
if(page==null){failed=true;totals[entry.first]=offsets[entry.first] ?: 0;continue}
offsets[entry.first]=(offsets[entry.first] ?: 0)+page.items.size
totals[entry.first]=if(page.items.isEmpty())offsets.getValue(entry.first)else page.total
candidates[entry.first]=ordered(entry,candidates[entry.first].orEmpty()+page.items)
}
}
fetch(entries,first=true)
if(!current())return@launch
var chosen=choose()
categoryArtwork=chosen
// Expand only overlapping candidate groups that could free a missing genre.
while(chosen.size<entries.size) {
val needed=(entries.map{it.first}-chosen.keys).toMutableSet()
var expanded=true
while(expanded) {
val count=needed.size
val sources=needed.flatMap{candidates[it].orEmpty()}.map{categoryArtworkIdentity(it.artworkPath())}.toSet()
candidates.forEach{(genre,items)->if(items.any{categoryArtworkIdentity(it.artworkPath()) in sources})needed+=genre}
expanded=needed.size>count
}
val more=entries.filter{it.first in needed&&(offsets[it.first] ?: 0)<(totals[it.first] ?: 0)}
if(more.isEmpty())break
fetch(more)
if(!current())return@launch
chosen=choose();categoryArtwork=chosen
}
if(chosen.size<entries.size) {
// Some Plex genres are aliases with only one shared title. Preserve the
// distinct-title assignment and give remaining genres different landscape art.
val remaining=entries.filter{it.first !in chosen}
val used=chosen.values.map{categoryArtworkIdentity(it.artworkPath())}.toSet()
val alternatives=coroutineScope {remaining.map{entry->async {
val variants=mutableListOf<Title>()
for(item in candidates[entry.first].orEmpty()) {
val paths=try {requestGate.withPermit{api.categoryArtAlternatives(item.id)}}
catch(e:CancellationException){throw e}catch(_:Exception){failed=true;emptyList()}
variants+=paths.filter{categoryArtworkIdentity(it) !in used}.map{item.copy(art=it)}
if(variants.size>=remaining.size)break
}
entry.first to variants
}}.awaitAll().toMap()}
if(!current())return@launch
chosen=chosen+selectCategoryArtwork(alternatives){categoryArtworkIdentity(it.artworkPath())}
categoryArtwork=chosen
}
categoryArtworkComplete=!failed
}
}
fun selectCategory(value:String){if(value.isBlank())return;categories=true;allTitles=true;genre=value;sort="titleSort:asc";focusId="category-grid";libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()}
fun filter(sortValue: String=sort,unwatchedValue: Boolean=unwatched){sort=sortValue;unwatched=unwatchedValue;libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()}
private fun refreshLibrary() {
val selectedSection=section ?: return
val requestedSort=sort;val requestedGenre=genre;val requestedUnwatched=unwatched
launchLoad {
val p=api.library(selectedSection.id,0,requestedSort,requestedGenre,requestedUnwatched,type=plexLibraryType(selectedSection.type))
if(section?.id!=selectedSection.id||sort!=requestedSort||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad
library=p.items;total=p.total
if(categories&&requestedGenre.isNotBlank()){
focusId=p.items.firstOrNull()?.let{"library:${it.id}"} ?: "category-grid"
libraryFocusRequest++
}
}
}
fun more(){
if(busy||library.size>=total)return
val selectedSection=section ?: return;val start=library.size
val requestedSort=sort;val requestedGenre=genre;val requestedUnwatched=unwatched
launchLoad {
val p=api.library(selectedSection.id,start,requestedSort,requestedGenre,requestedUnwatched,type=plexLibraryType(selectedSection.type))
if(section?.id!=selectedSection.id||sort!=requestedSort||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad
library=(library+p.items).distinctBy{it.id};total=p.total
}
}
fun jumpToLibraryLetter(letter:String){
if(busy||letter !in LibraryJumpLetters)return
val selectedSection=section ?: return
val requestedGenre=genre;val requestedUnwatched=unwatched;val requestedSort=sort;val requestedType=plexLibraryType(selectedSection.type)
val cacheKey=LibraryCharacterQuery(selectedSection.id,requestedGenre,requestedUnwatched,requestedType)
launchLoad({jumpToLibraryLetter(letter)}) {
val offsets=characterOffsetCache[cacheKey] ?: libraryCharacterOffsets(api.firstCharacters(selectedSection.id,requestedGenre,requestedUnwatched,requestedType)).also{characterOffsetCache[cacheKey]=it}
val offset=offsets[letter] ?: return@launchLoad
val loaded=if(requestedSort=="titleSort:asc"&&library.size>offset)null else api.library(
selectedSection.id,0,"titleSort:asc",requestedGenre,requestedUnwatched,
size=(offset+100).coerceAtLeast(100),type=requestedType,
)
if(section?.id!=selectedSection.id||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad
if(loaded!=null){library=loaded.items;total=loaded.total}
sort="titleSort:asc"
if(offset !in library.indices)return@launchLoad
focusId="library-rail"
libraryJumpIndex=offset;libraryJumpLetter=letter;libraryJumpRequest++
}
}
fun onLibraryGridFocused(){libraryJumpIndex=-1}
fun search(text: String){query=text;searchJob?.cancel();if(text.isBlank()){searchResults=SearchResults();busy=false;return};searchJob=viewModelScope.launch {delay(350);busy=true;error=null;try{searchResults=api.search(text)}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Search is unavailable."){search(text)}}finally{busy=false}}}
fun mark(item: Title) { fun mark(item: Title) {
if(markingId!=null)return if(markingId!=null)return
markingId=item.id markingId=item.id
@ -393,7 +627,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update this title."){mark(item)}}finally{markingId=null} }catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update this title."){mark(item)}}finally{markingId=null}
} }
} }
fun refreshWatched(item:Title){viewModelScope.launch{try{refreshWatchedItems(item)}catch(e:CancellationException){throw e}catch(_:Exception){sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()}}} fun refreshWatched(item:Title){viewModelScope.launch{try{refreshWatchedItems(item)}catch(e:CancellationException){throw e}catch(_:Exception){sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()}}}
private suspend fun refreshWatchedItems(item:Title) { private suspend fun refreshWatchedItems(item:Title) {
val d=api.details(item.id) val d=api.details(item.id)
val updated=mutableMapOf(d.id to d) val updated=mutableMapOf(d.id to d)
@ -421,15 +655,29 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
hubTitles=hubTitles.map(::refreshedTitle) hubTitles=hubTitles.map(::refreshedTitle)
actorTitles=actorTitles.map(::refreshedTitle);detailRelated=detailRelated.map(::refreshedTitle) actorTitles=actorTitles.map(::refreshedTitle);detailRelated=detailRelated.map(::refreshedTitle)
homeFeatures=homeFeatures.map{it.copy(item=refreshedTitle(it.item))}.filterNot{it.item.fullyWatched} homeFeatures=homeFeatures.map{it.copy(item=refreshedTitle(it.item))}.filterNot{it.item.fullyWatched}
sectionCache.clear() sectionCache.clear();characterOffsetCache.clear()
} }
fun play(item: Title,fromStart: Boolean=false):Unit=launchLoad({play(item,fromStart)}) { fun play(item: Title,fromStart: Boolean=false):Unit=launchLoad({play(item,fromStart)}) {
shuffleEpisodes=null
debugMode=null;debugValidation=false;debugValidationFile=null debugMode=null;debugValidation=false;debugValidationFile=null
val playable=if(item.type=="show" || item.type=="season") { val playable=if(item.type=="show" || item.type=="season") {
val episodes=api.allEpisodes(item.id);episodes.firstOrNull {it.offset>0&&!it.watched} ?: episodes.firstOrNull {!it.watched} ?: episodes.firstOrNull() ?: throw PlexException("No playable episodes are available.") val episodes=api.allEpisodes(item.id);episodes.firstOrNull {it.offset>0&&!it.watched} ?: episodes.firstOrNull {!it.watched} ?: episodes.firstOrNull() ?: throw PlexException("No playable episodes are available.")
} else item } else item
val d=api.details(playable.id);require(d.media.firstOrNull()?.parts?.isNotEmpty()==true){"No playable media file is available."};startFromZero=fromStart;playing=d val d=api.details(playable.id);require(d.media.firstOrNull()?.parts?.isNotEmpty()==true){"No playable media file is available."};startFromZero=fromStart;playing=d
} }
/** Starts a show-wide shuffle bag. Watched state and resume offsets do not affect eligibility. */
fun playShuffled(show:Title,validation:Boolean=false):Unit=launchLoad({playShuffled(show,validation)}) {
require(show.type=="show") { "Shuffle is available from a TV show page." }
debugMode=null;debugValidation=BuildConfig.DEBUG&&validation;debugValidationFile=null
val episodes=api.allEpisodes(show.id).filter{it.type=="episode"}.distinctBy{it.id}
val order=ShuffleEpisodes(episodes,Title::id)
val first=order.first ?: throw PlexException("No playable episodes are available.")
val metadata=api.details(first.id)
require(metadata.media.firstOrNull()?.parts?.isNotEmpty()==true){"No playable media file is available."}
shuffleEpisodes=order
startFromZero=true
playing=metadata
}
fun loadEpisodeContext(item:Title) { fun loadEpisodeContext(item:Title) {
if(item.type!="episode")return if(item.type!="episode")return
if(episodeQueue.any{it.id==item.id})return if(episodeQueue.any{it.id==item.id})return
@ -443,25 +691,71 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
} }
} }
fun followingEpisode(item:Title):Title? {val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>=0)episodeQueue.getOrNull(i+1)else null} /** The episode before [item]: the previous one in the show, or the previous shuffle pick. */
fun precedingEpisode(item:Title):Title? {
val shuffle=shuffleEpisodes
if(shuffle!=null)return shuffle.preceding(item.id)
val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>0)episodeQueue[i-1]else null
}
/** False only once the episode list has loaded and [item] is the show's first episode (or the shuffle's first pick). */
fun mayHavePrecedingEpisode(item:Title):Boolean {
val shuffle=shuffleEpisodes
if(shuffle!=null)return shuffle.preceding(item.id)!=null
val i=episodeQueue.indexOfFirst{it.id==item.id};return i!=0
}
fun followingEpisode(item:Title):Title? {
val shuffle=shuffleEpisodes
if(shuffle!=null)return shuffle.following(item.id)
val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>=0)episodeQueue.getOrNull(i+1)else null
}
fun previousEpisode(item: Title) {
if(episodeTransitionJob?.isActive==true)return
episodeTransitionJob=viewModelScope.launch {
transitioningEpisode=true
try {
val shuffle=shuffleEpisodes
val previous=if(shuffle!=null)shuffle.preceding(item.id) else {
val episodes=if(episodeQueue.any{it.id==item.id})episodeQueue else api.allEpisodes(item.grandparentId).sortedWith(compareBy<Title>{it.parentIndex}.thenBy{it.index})
val i=episodes.indexOfFirst{it.id==item.id};if(i>0)episodes[i-1]else null
} ?: return@launch
val metadata=api.details(previous.id)
if(playing?.id==item.id){if(shuffle!=null)shuffle.retreat(item.id,previous.id);startFromZero=true;playbackInstance++;playing=metadata}
}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "The previous episode could not be loaded."){previousEpisode(item)}}finally{transitioningEpisode=false}
}
}
fun nextEpisode(item: Title) { fun nextEpisode(item: Title) {
if(episodeTransitionJob?.isActive==true)return if(episodeTransitionJob?.isActive==true)return
episodeTransitionJob=viewModelScope.launch { episodeTransitionJob=viewModelScope.launch {
transitioningEpisode=true transitioningEpisode=true
try { try {
val shuffle=shuffleEpisodes
val next=if(shuffle!=null)shuffle.following(item.id) else {
val episodes=if(episodeQueue.any{it.id==item.id})episodeQueue else api.allEpisodes(item.grandparentId).sortedWith(compareBy<Title>{it.parentIndex}.thenBy{it.index}) val episodes=if(episodeQueue.any{it.id==item.id})episodeQueue else api.allEpisodes(item.grandparentId).sortedWith(compareBy<Title>{it.parentIndex}.thenBy{it.index})
val i=episodes.indexOfFirst{it.id==item.id};val next=if(i>=0)episodes.getOrNull(i+1)else null val i=episodes.indexOfFirst{it.id==item.id};if(i>=0)episodes.getOrNull(i+1)else null
if(next!=null){val metadata=api.details(next.id);if(playing?.id==item.id){startFromZero=true;playing=metadata}} }
if(next!=null){val metadata=api.details(next.id);if(playing?.id==item.id){if(shuffle!=null)shuffle.advance(item.id,next.id);startFromZero=true;playbackInstance++;playing=metadata}}
else if(playing?.id==item.id)stopPlayback() else if(playing?.id==item.id)stopPlayback()
}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "The next episode could not be loaded."){nextEpisode(item)}}finally{transitioningEpisode=false} }catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "The next episode could not be loaded."){nextEpisode(item)}}finally{transitioningEpisode=false}
} }
} }
/** The server ended this session: leave the player and explain, offering to resume from the saved position. */
fun playbackStoppedByServer(item:Title,message:String){
if(playing?.id!=item.id)return
stopPlayback();fail(message){play(item)}
}
/** Each player's timeline reporter, until it has sent its final position. */
private val playbackReports=java.util.concurrent.CopyOnWriteArraySet<Job>()
internal fun trackPlaybackReports(job:Job){playbackReports+=job;job.invokeOnCompletion{playbackReports-=job}}
fun stopPlayback(){ fun stopPlayback(){
val finished=playing val finished=playing
if(finished!=null)playbackReturn++;playing=null;sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() shuffleEpisodes=null
if(finished!=null)playbackReturn++;playing=null;sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
// A season or episode page shows the last episode played, with fresh progress in its row. // A season or episode page shows the last episode played, with fresh progress in its row.
detail?.let{if(finished?.type=="episode"&&it.type in listOf("season","episode"))episodeSelections[it.id]=finished.id} detail?.let{if(finished?.type=="episode"&&it.type in listOf("season","episode"))episodeSelections[it.id]=finished.id}
launchLoad { launchLoad {
// The player closes after this frame and only then reports where it stopped. Reloading
// before Plex has that report showed the previous Continue Watching.
kotlinx.coroutines.withTimeoutOrNull(PlaybackReportWaitMillis){playbackReports.toList().forEach{it.join()}}
homeHubs=loadHome() homeHubs=loadHome()
detail?.let { detail?.let {
if(it.type in listOf("movie","episode"))detail=api.details(it.id) if(it.type in listOf("movie","episode"))detail=api.details(it.id)
@ -470,6 +764,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
} }
} }
// Earlier versions stored an on/off switch that skipped at once; on becomes a short, cancellable countdown.
private fun autoSkipSeconds(name:String)=preferences.getInt("${name}Seconds",if(preferences.getBoolean(name,false))AutoSkipDefaultSeconds else 0).coerceIn(0,60)
// Earlier versions stored a mode (Original/Direct stream/Transcode) and a separate transcode quality. // Earlier versions stored a mode (Original/Direct stream/Transcode) and a separate transcode quality.
private fun savedStreamQuality()=preferences.getString("streamQuality",null)?.let{name->StreamQuality.entries.firstOrNull{it.name==name}} private fun savedStreamQuality()=preferences.getString("streamQuality",null)?.let{name->StreamQuality.entries.firstOrNull{it.name==name}}
?: if(preferences.getInt("playbackModeV2",1)==2)(if(preferences.getInt("quality",20000)>20000)StreamQuality.UltraHD else StreamQuality.FullHD)else StreamQuality.Original ?: if(preferences.getInt("playbackModeV2",1)==2)(if(preferences.getInt("quality",20000)>20000)StreamQuality.UltraHD else StreamQuality.FullHD)else StreamQuality.Original
@ -478,12 +774,15 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
/** The player's quality menu changes the preference for the connection in use. */ /** The player's quality menu changes the preference for the connection in use. */
fun chooseActiveQuality(value: StreamQuality)=if(localConnection)chooseStreamQuality(value)else chooseRemoteQuality(value) fun chooseActiveQuality(value: StreamQuality)=if(localConnection)chooseStreamQuality(value)else chooseRemoteQuality(value)
fun chooseAutoplaySeconds(value:Int){autoplaySeconds=value.coerceAtLeast(0);preferences.edit().putInt("autoplaySeconds",autoplaySeconds).apply()} fun chooseAutoplaySeconds(value:Int){autoplaySeconds=value.coerceAtLeast(0);preferences.edit().putInt("autoplaySeconds",autoplaySeconds).apply()}
fun chooseAutoSkipIntro(value:Boolean){autoSkipIntro=value;preferences.edit().putBoolean("autoSkipIntro",value).apply()} fun chooseAutoSkipIntro(seconds:Int){autoSkipIntroSeconds=seconds.coerceIn(0,60);preferences.edit().putInt("autoSkipIntroSeconds",autoSkipIntroSeconds).remove("autoSkipIntro").apply()}
fun chooseAutoSkipCredits(value:Boolean){autoSkipCredits=value;preferences.edit().putBoolean("autoSkipCredits",value).apply()} fun chooseAutoSkipCredits(seconds:Int){autoSkipCreditsSeconds=seconds.coerceIn(0,60);preferences.edit().putInt("autoSkipCreditsSeconds",autoSkipCreditsSeconds).remove("autoSkipCredits").apply()}
fun chooseSubtitleSize(value:SubtitleSize){subtitleSize=value;preferences.edit().putString("subtitleSize",value.name).apply()} fun chooseSubtitleSize(value:SubtitleSize){subtitleSize=value;preferences.edit().putString("subtitleSize",value.name).apply()}
fun chooseSubtitleStyle(value:SubtitleStyle){subtitleStyle=value;preferences.edit().putString("subtitleStyle",value.name).apply()} fun chooseSubtitleStyle(value:SubtitleStyle){subtitleStyle=value;preferences.edit().putString("subtitleStyle",value.name).apply()}
fun chooseWatchedPercent(value:Int){watchedPercent=value.coerceIn(50,100);preferences.edit().putInt("watchedPercent",watchedPercent).apply()} fun chooseWatchedPercent(value:Int){watchedPercent=value.coerceIn(50,100);preferences.edit().putInt("watchedPercent",watchedPercent).apply()}
fun chooseNavigationSounds(value:Boolean){navigationSounds=value;preferences.edit().putBoolean("navigationSounds",value).apply()} fun chooseNavigationSounds(value:Boolean){navigationSounds=value;preferences.edit().putBoolean("navigationSounds",value).apply()}
fun chooseColourWash(value:Boolean){colourWash=value;preferences.edit().putBoolean("colourWash",value).apply()}
fun chooseThemeMusic(value:Boolean){themeMusic=value;preferences.edit().putBoolean("themeMusic",value).apply()}
fun chooseThemeVolume(value:Int){themeVolume=value.coerceIn(10,100);preferences.edit().putInt("themeVolume",themeVolume).apply()}
fun checkUpdate(manual: Boolean=true){viewModelScope.launch { fun checkUpdate(manual: Boolean=true){viewModelScope.launch {
if(downloading||!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch if(downloading||!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch
updateStatus="Checking for updates…" updateStatus="Checking for updates…"

View file

@ -0,0 +1,134 @@
package tv.kaleido.app
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.unit.DpSize
import androidx.compose.material3.Text
internal data class PlexCharacterCount(val key: String, val title: String, val size: Int)
internal data class LibraryCharacterQuery(val section: String, val genre: String, val unwatched: Boolean, val type: String)
internal fun libraryFilterParameters(genre: String, unwatched: Boolean, type: String): Map<String, String> = buildMap {
if (genre.isNotBlank()) put("genre", genre)
if (unwatched) put("unwatched", "1")
if (type.isNotBlank()) put("type", type)
}
internal val LibraryJumpLetters = listOf("#") + ('A'..'Z').map(Char::toString)
/** Plex returns one ordered Directory per initial; summing its sizes yields each absolute grid index. */
internal fun libraryCharacterOffsets(characters: List<PlexCharacterCount>): Map<String, Int> {
val offsets = linkedMapOf<String, Int>()
var index = 0
characters.forEach { character ->
val label = when {
character.key.equals("%23", ignoreCase = true) || character.key == "#" || character.title == "#" -> "#"
else -> character.title.firstOrNull()?.uppercaseChar()?.toString()
?: character.key.firstOrNull()?.uppercaseChar()?.toString()
}
if (character.size > 0 && label != null && label in LibraryJumpLetters) offsets.putIfAbsent(label, index)
index += character.size.coerceAtLeast(0)
}
return offsets
}
internal fun plexLibraryType(type: String): String = when (type) {
"movie" -> "1"
"show" -> "2"
else -> ""
}
@Composable
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
internal fun LibraryJumpRail(
enabledLetters: Set<String>,
selectedLetter: String?,
entryFocus: FocusRequester,
returnToGrid: () -> Unit,
onLetter: (String) -> Unit,
) {
// This remote-operated alphabet is denser than touch controls. Expanded touch targets
// overlap adjacent letters and hide their accessibility labels on Android TV.
val configuration=LocalViewConfiguration.current
val compactTargets=remember(configuration){object:ViewConfiguration by configuration {
override val minimumTouchTargetSize=DpSize.Zero
}}
CompositionLocalProvider(LocalViewConfiguration provides compactTargets) {
Column(modifier = Modifier.width(34.dp).height(350.dp)) {
LibraryJumpLetters.forEach { letter ->
var focused by remember { mutableStateOf(false) }
val active = letter in enabledLetters
val selected = letter == selectedLetter
Box(
Modifier
.weight(1f)
.width(34.dp)
.semantics { contentDescription = letter }
.then(if (letter == "#") Modifier.focusRequester(entryFocus) else Modifier)
.focusProperties { right = FocusRequester.Cancel }
.onPreviewKeyEvent {
if (it.type == KeyEventType.KeyDown && it.key == Key.DirectionLeft) {
returnToGrid()
true
} else false
}
.onFocusChanged { focused = it.isFocused }
.navigationSound()
.background(
when {
focused -> Accent
selected -> Color.White.copy(alpha = .14f)
else -> Color.Transparent
},
RoundedCornerShape(3.dp),
)
.clickable { if (active) onLetter(letter) },
contentAlignment = Alignment.Center,
) {
Text(
letter,
color = when {
focused -> Ink
selected -> Color(0xFFBBBBBB)
active -> Color(0xFF999999)
else -> Muted.copy(alpha = .46f)
},
fontSize = 10.sp,
lineHeight = 12.sp,
fontWeight = if (focused || selected) FontWeight.SemiBold else FontWeight.Normal,
)
}
}
}
}
}

View file

@ -36,7 +36,10 @@ class MainActivity: ComponentActivity() {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window,false) WindowCompat.setDecorFitsSystemWindows(window,false)
WindowInsetsControllerCompat(window,window.decorView).apply{hide(WindowInsetsCompat.Type.systemBars());systemBarsBehavior=WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE} WindowInsetsControllerCompat(window,window.decorView).apply{hide(WindowInsetsCompat.Type.systemBars());systemBarsBehavior=WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE}
@Suppress("DEPRECATION")
FramePrefetch.frameNanos=(1_000_000_000/windowManager.defaultDisplay.refreshRate.coerceAtLeast(24f)).toLong()
setContent { KaleidoApp(model,::installApk) } setContent { KaleidoApp(model,::installApk) }
window.decorView.viewTreeObserver.addOnDrawListener{FramePrefetch.drew()}
// Compose paints Ink over the whole window; the theme background only covers launch. // Compose paints Ink over the whole window; the theme background only covers launch.
window.setBackgroundDrawable(null) window.setBackgroundDrawable(null)
debugPlayback(intent) debugPlayback(intent)
@ -49,14 +52,14 @@ class MainActivity: ComponentActivity() {
val query=intent.getStringExtra(android.app.SearchManager.QUERY).orEmpty().trim() val query=intent.getStringExtra(android.app.SearchManager.QUERY).orEmpty().trim()
if(model.session!=null)model.openSearch(query) if(model.session!=null)model.openSearch(query)
} }
/** The remote's search key (and the system's search request) starts a voice search inside Kaleido. */ /** Open the native text field; voice input belongs to the Android TV keyboard. */
override fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean { override fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean {
if(keyCode==android.view.KeyEvent.KEYCODE_SEARCH&&model.session!=null&&model.playing==null){if(event.repeatCount==0)model.requestVoiceSearch();return true} if(keyCode==android.view.KeyEvent.KEYCODE_SEARCH&&model.session!=null&&model.playing==null){if(event.repeatCount==0)model.openSearch();return true}
return super.onKeyDown(keyCode,event) return super.onKeyDown(keyCode,event)
} }
override fun onSearchRequested(): Boolean { override fun onSearchRequested(): Boolean {
if(model.session==null||model.playing!=null)return false if(model.session==null||model.playing!=null)return false
model.requestVoiceSearch();return true model.openSearch();return true
} }
private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG){ private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG){
intent.getStringExtra("testFixture")?.let{model.debugPlayFixture(it);return} intent.getStringExtra("testFixture")?.let{model.debugPlayFixture(it);return}

View file

@ -1,13 +1,14 @@
package tv.kaleido.app package tv.kaleido.app
import androidx.compose.runtime.Immutable
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
fun JSONArray?.objects(): List<JSONObject> = if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) } fun JSONArray?.objects(): List<JSONObject> = if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) }
data class Section(val id: String, val title: String, val type: String) data class Section(val id: String, val title: String, val type: String)
data class Stream(val id: String, val type: Int, val codec: String, val language: String, val title: String, val selected: Boolean, val key: String, val channels: Int, val index: Int) @Immutable data class Stream(val id: String, val type: Int, val codec: String, val language: String, val title: String, val selected: Boolean, val key: String, val channels: Int, val index: Int)
data class Part(val id: String, val key: String, val streams: List<Stream>,val indexes:String="",val duration:Long=0,val size:Long=0) @Immutable data class Part(val id: String, val key: String, val streams: List<Stream>,val indexes:String="",val duration:Long=0,val size:Long=0)
data class Media(val id: String, val container: String, val videoCodec: String, val audioCodec: String, val resolution: String, val width: Int, val height: Int, val bitrate: Int, val parts: List<Part>, @Immutable data class Media(val id: String, val container: String, val videoCodec: String, val audioCodec: String, val resolution: String, val width: Int, val height: Int, val bitrate: Int, val parts: List<Part>,
val dynamicRange:String="",val audioChannels:Int=0) { val dynamicRange:String="",val audioChannels:Int=0) {
val resolutionLabel get()=when(resolution.lowercase()){"4k"->"4K";"sd"->"SD";""->"";else->if(resolution.all(Char::isDigit))"${resolution}p"else resolution.uppercase()} val resolutionLabel get()=when(resolution.lowercase()){"4k"->"4K";"sd"->"SD";""->"";else->if(resolution.all(Char::isDigit))"${resolution}p"else resolution.uppercase()}
val channelLabel get()=when(audioChannels){0->"";1->"Mono";2->"Stereo";6->"5.1";8->"7.1";else->"$audioChannels ch"} val channelLabel get()=when(audioChannels){0->"";1->"Mono";2->"Stereo";6->"5.1";8->"7.1";else->"$audioChannels ch"}
@ -18,16 +19,19 @@ data class Media(val id: String, val container: String, val videoCodec: String,
listOf(audioCodec.uppercase(),channelLabel,if(atmos)"Atmos"else "").filter{it.isNotBlank()}.joinToString(" "), listOf(audioCodec.uppercase(),channelLabel,if(atmos)"Atmos"else "").filter{it.isNotBlank()}.joinToString(" "),
if(bitrate>0)"${(bitrate+500)/1000} Mbps"else "",if(includeSize&&size>0)fileSize(size)else "",if(parts.size>1)"${parts.size} parts"else "") if(bitrate>0)"${(bitrate+500)/1000} Mbps"else "",if(includeSize&&size>0)fileSize(size)else "",if(parts.size>1)"${parts.size} parts"else "")
.filter{it.isNotBlank()}.joinToString(" · ") .filter{it.isNotBlank()}.joinToString(" · ")
/** What the format badges leave out: codecs, audio layout and bitrate, e.g. "AV1 · EAC3 5.1 · 10 Mbps". */
val technical get()=listOf(videoCodec.uppercase(),listOf(audioCodec.uppercase(),channelLabel).filter{it.isNotBlank()}.joinToString(" "),
if(bitrate>0)"${(bitrate+500)/1000} Mbps"else "",if(parts.size>1)"${parts.size} parts"else "").filter{it.isNotBlank()}.joinToString(" · ")
} }
internal fun fileSize(bytes:Long):String = if(bytes>=1_000_000_000L)String.format(java.util.Locale.US,"%.1f GB",bytes/1e9)else "${bytes/1_000_000} MB" internal fun fileSize(bytes:Long):String = if(bytes>=1_000_000_000L)String.format(java.util.Locale.US,"%.1f GB",bytes/1e9)else "${bytes/1_000_000} MB"
data class Marker(val type: String, val start: Long, val end: Long) @Immutable data class Marker(val type: String, val start: Long, val end: Long)
data class Chapter(val index:Int,val title:String,val start:Long,val end:Long,val thumb:String) @Immutable data class Chapter(val index:Int,val title:String,val start:Long,val end:Long,val thumb:String)
data class CastMember(val id:String,val name:String,val role:String,val thumb:String) { @Immutable data class CastMember(val id:String,val name:String,val role:String,val thumb:String) {
companion object { companion object {
fun parse(j:JSONObject)=CastMember(j.optString("id").ifBlank{j.optString("filter").removePrefix("actor=")}.takeIf{it.all(Char::isDigit)}.orEmpty(),j.optString("tag"),j.optString("role"),j.optString("thumb")) fun parse(j:JSONObject)=CastMember(j.optString("id").ifBlank{j.optString("filter").removePrefix("actor=")}.takeIf{it.all(Char::isDigit)}.orEmpty(),j.optString("tag"),j.optString("role"),j.optString("thumb"))
} }
} }
data class Title( @Immutable data class Title(
val id: String, val key: String, val type: String, val title: String, val summary: String, val id: String, val key: String, val type: String, val title: String, val summary: String,
val thumb: String, val art: String, val year: String, val duration: Long, val offset: Long, val thumb: String, val art: String, val year: String, val duration: Long, val offset: Long,
val watched: Boolean, val rating: String, val contentRating: String, val parentTitle: String, val watched: Boolean, val rating: String, val contentRating: String, val parentTitle: String,
@ -36,7 +40,8 @@ data class Title(
val genres: List<String>, val cast: List<String>, val media: List<Media>, val markers: List<Marker>, val genres: List<String>, val cast: List<String>, val media: List<Media>, val markers: List<Marker>,
val logo: String = "", val poster: String = "", val still: String = "",val chapters:List<Chapter> = emptyList(), val logo: String = "", val poster: String = "", val still: String = "",val chapters:List<Chapter> = emptyList(),
val audienceScore: AudienceScore? = null, val releaseDate: String = "",val audienceScores:List<AudienceScore> = emptyList(), val audienceScore: AudienceScore? = null, val releaseDate: String = "",val audienceScores:List<AudienceScore> = emptyList(),
val castMembers:List<CastMember> = emptyList(),val subtype:String="",val extras:List<Title> = emptyList() val castMembers:List<CastMember> = emptyList(),val subtype:String="",val extras:List<Title> = emptyList(),
val theme:String=""
) { ) {
val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0) val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0)
val fullyWatched get() = isWatched() val fullyWatched get() = isWatched()
@ -77,7 +82,8 @@ data class Title(
j.optJSONArray("Chapter").objects().mapIndexed{position,c->Chapter(c.optInt("index"),chapterTitle(c.optString("title"),position),c.optLong("startTimeOffset"),c.optLong("endTimeOffset"),c.optString("thumb"))}, j.optJSONArray("Chapter").objects().mapIndexed{position,c->Chapter(c.optInt("index"),chapterTitle(c.optString("title"),position),c.optLong("startTimeOffset"),c.optLong("endTimeOffset"),c.optString("thumb"))},
AudienceScore.parse(j),j.optString("originallyAvailableAt"),AudienceScore.parseAll(j), AudienceScore.parse(j),j.optString("originallyAvailableAt"),AudienceScore.parseAll(j),
j.optJSONArray("Role").objects().map(CastMember::parse).filter{it.name.isNotBlank()}.distinctBy{it.id.ifBlank{it.name}}, j.optJSONArray("Role").objects().map(CastMember::parse).filter{it.name.isNotBlank()}.distinctBy{it.id.ifBlank{it.name}},
j.optString("subtype"),j.optJSONObject("Extras")?.optJSONArray("Metadata").objects().map(::parse) j.optString("subtype"),j.optJSONObject("Extras")?.optJSONArray("Metadata").objects().map(::parse),
j.optString("theme").ifBlank{j.optString("parentTheme")}.ifBlank{j.optString("grandparentTheme")}
) )
private fun parseMedia(m:JSONObject):Media { private fun parseMedia(m:JSONObject):Media {
val parts=m.optJSONArray("Part").objects().map { p -> Part(p.optString("id"),p.optString("key"),p.optJSONArray("Stream").objects().map { s -> Stream(s.optString("id"),s.optInt("streamType"),s.optString("codec"),s.optString("language",s.optString("languageCode","Unknown")),s.optString("displayTitle",s.optString("title",s.optString("language","Unknown"))),s.optBoolean("selected"),s.optString("key"),s.optInt("channels"),s.optInt("index",-1)) },p.optString("indexes"),p.optLong("duration"),p.optLong("size")) } val parts=m.optJSONArray("Part").objects().map { p -> Part(p.optString("id"),p.optString("key"),p.optJSONArray("Stream").objects().map { s -> Stream(s.optString("id"),s.optInt("streamType"),s.optString("codec"),s.optString("language",s.optString("languageCode","Unknown")),s.optString("displayTitle",s.optString("title",s.optString("language","Unknown"))),s.optBoolean("selected"),s.optString("key"),s.optInt("channels"),s.optInt("index",-1)) },p.optString("indexes"),p.optLong("duration"),p.optLong("size")) }
@ -97,7 +103,7 @@ data class Title(
} }
/** Plex normalizes external ratings to 0–10. Never substitute the critic `rating` field. */ /** Plex normalizes external ratings to 0–10. Never substitute the critic `rating` field. */
data class AudienceScore(val source:String,val value:Double) { @Immutable data class AudienceScore(val source:String,val value:Double) {
val displayValue get() = if(source=="Rotten Tomatoes")"${kotlin.math.round(value*10).toInt()}%"else "${String.format(java.util.Locale.US,"%.1f",value)}/10" val displayValue get() = if(source=="Rotten Tomatoes")"${kotlin.math.round(value*10).toInt()}%"else "${String.format(java.util.Locale.US,"%.1f",value)}/10"
val label get() = "$source ${if(source=="Rotten Tomatoes")"audience "else ""}$displayValue" val label get() = "$source ${if(source=="Rotten Tomatoes")"audience "else ""}$displayValue"
companion object { companion object {
@ -124,9 +130,9 @@ data class AudienceScore(val source:String,val value:Double) {
internal fun reachedWatchedThreshold(position:Long,duration:Long,percent:Int):Boolean = internal fun reachedWatchedThreshold(position:Long,duration:Long,percent:Int):Boolean =
duration>0&&position.toDouble()/duration>=percent.coerceIn(50,100)/100.0 duration>0&&position.toDouble()/duration>=percent.coerceIn(50,100)/100.0
/** [key] and [more] come from Plex: a row with more titles than shown can open its full list. */ /** [key] and [more] come from Plex: a row with more titles than shown can open its full list. */
data class Hub(val id: String, val title: String, val items: List<Title>,val key:String="",val more:Boolean=false) @Immutable data class Hub(val id: String, val title: String, val items: List<Title>,val key:String="",val more:Boolean=false)
data class LibraryPage(val items: List<Title>,val total: Int) @Immutable data class LibraryPage(val items: List<Title>,val total: Int)
data class SearchResults(val titles:List<Title> = emptyList(),val people:List<CastMember> = emptyList()) @Immutable data class SearchResults(val titles:List<Title> = emptyList(),val people:List<CastMember> = emptyList())
data class Server(val id: String, val name: String, val token: String, val connections: List<String>) data class Server(val id: String, val name: String, val token: String, val connections: List<String>)
data class Session(val accountToken: String, val serverToken: String, val server: String, val serverName: String, val machineId: String) data class Session(val accountToken: String, val serverToken: String, val server: String, val serverName: String, val machineId: String)
data class Pin(val id: String,val code: String) data class Pin(val id: String,val code: String)

View file

@ -48,6 +48,8 @@ data class TimelineReport(val position: Long,val state: String,val duration: Lon
class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
private val app=vm.application private val app=vm.application
val api=vm.api val api=vm.api
/** The server this title belongs to. Progress reports finish after close and must not follow a server change. */
private val server=api.session
val scope=CoroutineScope(SupervisorJob()+Dispatchers.Main.immediate) val scope=CoroutineScope(SupervisorJob()+Dispatchers.Main.immediate)
val selector=DefaultTrackSelector(app) val selector=DefaultTrackSelector(app)
private val sourceFactory=DefaultMediaSourceFactory(DefaultDataSource.Factory(app,OkHttpDataSource.Factory(api.http).setDefaultRequestProperties(api.headers().filterKeys{it!="Accept"}))) private val sourceFactory=DefaultMediaSourceFactory(DefaultDataSource.Factory(app,OkHttpDataSource.Factory(api.http).setDefaultRequestProperties(api.headers().filterKeys{it!="Accept"})))
@ -80,8 +82,9 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
mode==2->"Converting · "+quality.conversion.label mode==2->"Converting · "+quality.conversion.label
serverConverting->if(serverAudioConverting)"Converted video and audio"else "Converted video" serverConverting->if(serverAudioConverting)"Converted video and audio"else "Converted video"
serverAudioConverting->"Original video · Converted audio" serverAudioConverting->"Original video · Converted audio"
else->StreamQuality.Original.label else->qualityOptionLabel(StreamQuality.Original)
} }
fun qualityOptionLabel(value:StreamQuality)=value.forMedia(media)
var loading by mutableStateOf(true);private set var loading by mutableStateOf(true);private set
var error by mutableStateOf<String?>(null);private set var error by mutableStateOf<String?>(null);private set
var position by mutableLongStateOf(if(vm.startFromZero)0 else item.offset);private set var position by mutableLongStateOf(if(vm.startFromZero)0 else item.offset);private set
@ -97,30 +100,46 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
val part get()=parts[partIndex.coerceIn(0,parts.lastIndex)] val part get()=parts[partIndex.coerceIn(0,parts.lastIndex)]
private val partOffset get()=partStart(parts,partIndex) private val partOffset get()=partStart(parts,partIndex)
var activeSubtitle by mutableStateOf(parts.first().streams.firstOrNull{it.type==3&&it.selected}?.id ?: "0");private set var activeSubtitle by mutableStateOf(parts.first().streams.firstOrNull{it.type==3&&it.selected}?.id ?: "0");private set
var activeAudio by mutableStateOf(parts.first().streams.firstOrNull{it.type==2&&it.selected}?.id.orEmpty());private set var activeAudio by mutableStateOf((parts.first().streams.firstOrNull{it.type==2&&it.selected} ?: parts.first().streams.firstOrNull{it.type==2})?.id.orEmpty());private set
private var streamSession=UUID.randomUUID().toString() private var streamSession=UUID.randomUUID().toString()
private var streamStart=0L private var streamStart=0L
private var preparing=false private var preparing=false
private var closed=false private var closed=false
/** False while the app is stopped (Home, another app): a pending preparation must not start playing. */
private var foreground=true
private val prepareMutex=Mutex() private val prepareMutex=Mutex()
private val streamSelectionMutex=Mutex()
private var fallbackPending=false private var fallbackPending=false
private var nativeSelectionApplied=false private var nativeSelectionApplied=false
private val reports=Channel<TimelineReport>(Channel.UNLIMITED) private val reports=Channel<TimelineReport>(Channel.UNLIMITED)
private val reportJob=app.scope.launch {
val watched=WatchedProgress{api.watched(item,true);withContext(Dispatchers.Main){vm.refreshWatched(item)}}
// Trailers and other extras are not library progress. // Trailers and other extras are not library progress.
val synced=!validation&&item.type!="clip" private val synced=!validation&&item.type!="clip"
/** Set once the server ends this session (dashboard Stop); nothing may reconnect or fall back after it. */
private var serverStopped=false
private val reportJob=app.scope.launch {
val watched=WatchedProgress{api.watched(item,true,server);withContext(Dispatchers.Main){if(api.session==server)vm.refreshWatched(item)}}
for(r in reports) { for(r in reports) {
if(synced) { if(synced) {
runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")} runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession,server)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")}
.getOrNull()?.let{if(!r.final)withContext(Dispatchers.Main){stoppedByServer(it)}}
runCatching{watched.report(r.position,r.duration,vm.watchedPercent)} runCatching{watched.report(r.position,r.duration,vm.watchedPercent)}
.onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")} .onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")}
} }
if(r.final){if(mode>0)runCatching{api.stopTranscode(streamSession)};break} if(r.final){if(mode>0)runCatching{api.stopTranscode(streamSession,server)};break}
} }
} }
init { init {
vm.trackPlaybackReports(reportJob)
audit?.let{player.addAnalyticsListener(it)} audit?.let{player.addAnalyticsListener(it)}
// Sparse diagnostics also survive in release logcat when an intermittent dropout occurs.
player.addAnalyticsListener(object:androidx.media3.exoplayer.analytics.AnalyticsListener {
override fun onAudioUnderrun(t:androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,size:Int,duration:Long,elapsed:Long) {
Log.w("KaleidoAudio","UNDERRUN item=${item.id} position=${t.eventPlaybackPositionMs} bufferMs=$duration sinceFeedMs=$elapsed mode=$mode")
}
override fun onAudioSinkError(t:androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,e:Exception) {
Log.w("KaleidoAudio","SINK_ERROR item=${item.id} position=${t.eventPlaybackPositionMs} kind=${e.javaClass.simpleName}")
}
})
player.addListener(object: Player.Listener { player.addListener(object: Player.Listener {
override fun onPlaybackStateChanged(state: Int) { override fun onPlaybackStateChanged(state: Int) {
loading=state==Player.STATE_BUFFERING loading=state==Player.STATE_BUFFERING
@ -137,6 +156,9 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
override fun onIsPlayingChanged(value: Boolean){isPlaying=value;if(!preparing&&!closed)report(if(value)"playing"else "paused")} override fun onIsPlayingChanged(value: Boolean){isPlaying=value;if(!preparing&&!closed)report(if(value)"playing"else "paused")}
override fun onTracksChanged(value: Tracks){ override fun onTracksChanged(value: Tracks){
tracks=value tracks=value
audit?.event("selectedTracks",org.json.JSONObject().put("audio",org.json.JSONArray(value.groups.filter{it.type==C.TRACK_TYPE_AUDIO}.flatMap{g->
(0 until g.length).filter{g.isTrackSelected(it)}.map{index->g.getTrackFormat(index).let{f->org.json.JSONObject().put("id",f.id).put("mime",f.sampleMimeType).put("channels",f.channelCount)}}
})))
Log.i("KaleidoPlayback","TRACKS audio=${value.groups.count{it.type==C.TRACK_TYPE_AUDIO}} text=${value.groups.count{it.type==C.TRACK_TYPE_TEXT}}") Log.i("KaleidoPlayback","TRACKS audio=${value.groups.count{it.type==C.TRACK_TYPE_AUDIO}} text=${value.groups.count{it.type==C.TRACK_TYPE_TEXT}}")
// Some extractors expose only audio for an unsupported video codec (e.g. VC-1). // Some extractors expose only audio for an unsupported video codec (e.g. VC-1).
if(value.groups.isNotEmpty()&&media.videoCodec.isNotBlank()&& if(value.groups.isNotEmpty()&&media.videoCodec.isNotBlank()&&
@ -151,23 +173,39 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
} }
override fun onPlayerError(e: PlaybackException) { override fun onPlayerError(e: PlaybackException) {
Log.w("KaleidoPlayback","ERROR code=${e.errorCodeName} mode=$mode") Log.w("KaleidoPlayback","ERROR code=${e.errorCodeName} mode=$mode")
if(mode<2&&localValidationFile==null)fallback(e.errorCodeName)else{loading=false;error="Playback failed (${e.errorCodeName}). Check the server transcoder, network connection, and media availability."} if(serverStopped)return
if(mode<2&&localValidationFile==null)fallback(e.errorCodeName)
else scope.launch{if(!checkServerStopped(position)){loading=false;error="Playback failed (${e.errorCodeName}). Check the server transcoder, network connection, and media availability."}}
} }
}) })
scope.launch {prepare(mode,position)} scope.launch {prepare(mode,position)}
if(audit!=null)scope.launch{while(isActive){delay(1000);audit.sample(mode)}} if(audit!=null)scope.launch{while(isActive){delay(1000);audit.sample(mode)}}
scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=(partOffset+player.bufferedPosition).coerceIn(0,duration);val d=player.duration;if(d>0&&parts.size==1)duration=if(mode>0)item.duration else d};if(++ticks%40==0&&!preparing&&!ended)report(if(isPlaying)"playing"else "paused")}} scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=(partOffset+player.bufferedPosition).coerceIn(0,duration);val d=player.duration;if(d>0&&parts.size==1)duration=if(mode>0)item.duration else d};if(++ticks%40==0&&!ended)report(if(preparing||loading)"buffering"else if(isPlaying)"playing"else "paused")}}
} }
/** Position on the title's timeline, across parts. */ /** Position on the title's timeline, across parts. */
private fun currentPosition() = (partOffset+player.currentPosition).coerceIn(0,duration.coerceAtLeast(0)) private fun currentPosition() = (partOffset+player.currentPosition).coerceIn(0,duration.coerceAtLeast(0))
private fun report(state: String,final: Boolean=false){reports.trySend(TimelineReport(position,state,duration,final))} private fun report(state: String,final: Boolean=false){reports.trySend(TimelineReport(position,state,duration,final))}
private fun stoppedByServer(termination:PlaybackTermination) {
if(closed||serverStopped)return
serverStopped=true
Log.i("KaleidoPlayback","TERMINATED item=${item.id} code=${termination.code} mode=$mode")
seekJob?.cancel();player.stop();loading=false
vm.playbackStoppedByServer(item,termination.message)
}
/** A failed stream may be one the server stopped: ask Plex before reconnecting, so a stopped session stays stopped. */
private suspend fun checkServerStopped(offset:Long):Boolean {
if(serverStopped)return true
if(!synced)return false
val termination=withTimeoutOrNull(3000){runCatching{api.timeline(item,offset,"buffering",duration,streamSession,server)}.getOrNull()} ?: return false
stoppedByServer(termination);return true
}
private fun fallback(reason:String) { private fun fallback(reason:String) {
if(closed||mode>=2||localValidationFile!=null||fallbackPending)return if(closed||serverStopped||mode>=2||localValidationFile!=null||fallbackPending)return
fallbackPending=true fallbackPending=true
val session=streamSession;val offset=if(preparing)position else currentPosition();val resume=player.playWhenReady val session=streamSession;val offset=if(preparing)position else currentPosition();val resume=player.playWhenReady
scope.launch { scope.launch {
try {prepareMutex.withLock { try {prepareMutex.withLock {
if(!closed&&session==streamSession) { if(!closed&&session==streamSession&&!checkServerStopped(offset)) {
audit?.event("fallback",org.json.JSONObject().put("reason",reason).put("fromMode",mode).put("offset",offset)) audit?.event("fallback",org.json.JSONObject().put("reason",reason).put("fromMode",mode).put("offset",offset))
prepareInternal(mode+1,offset,resume) prepareInternal(mode+1,offset,resume)
} }
@ -176,13 +214,14 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
} }
suspend fun prepare(newMode: Int,offset: Long,resume:Boolean=true) = prepareMutex.withLock{prepareInternal(newMode,offset,resume)} suspend fun prepare(newMode: Int,offset: Long,resume:Boolean=true) = prepareMutex.withLock{prepareInternal(newMode,offset,resume)}
private suspend fun prepareInternal(newMode: Int,offset: Long,resume:Boolean) { private suspend fun prepareInternal(newMode: Int,offset: Long,resume:Boolean) {
if(closed)return if(closed||serverStopped)return
preparing=true;loading=true;error=null;ended=false;nativeSelectionApplied=false preparing=true;loading=true;error=null;ended=false;nativeSelectionApplied=false
serverConverting=false;serverAudioConverting=false serverConverting=false;serverAudioConverting=false
// Empty track events from stop must not be mistaken for a missing video track. // Empty track events from stop must not be mistaken for a missing video track.
player.stop() player.stop()
selector.parameters=selector.buildUponParameters().clearOverrides().build()
try { try {
if(mode>0)runCatching{api.stopTranscode(streamSession)} if(mode>0)runCatching{api.stopTranscode(streamSession,server)}
mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=offset mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=offset
partIndex=partFor(parts,offset) partIndex=partFor(parts,offset)
val partOffsetMs=(offset-partOffset).coerceAtLeast(0) val partOffsetMs=(offset-partOffset).coerceAtLeast(0)
@ -196,7 +235,10 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
MediaItem.SubtitleConfiguration.Builder(android.net.Uri.parse(api.url(s.key))).setId(s.id).setLabel(s.title).setLanguage(s.language).setMimeType(when(s.codec){"srt"->MimeTypes.APPLICATION_SUBRIP;"ass","ssa"->MimeTypes.TEXT_SSA;else->MimeTypes.TEXT_VTT}).setSelectionFlags(if(s.id==currentStream(activeSubtitle)?.id)C.SELECTION_FLAG_DEFAULT else 0).build() MediaItem.SubtitleConfiguration.Builder(android.net.Uri.parse(api.url(s.key))).setId(s.id).setLabel(s.title).setLanguage(s.language).setMimeType(when(s.codec){"srt"->MimeTypes.APPLICATION_SUBRIP;"ass","ssa"->MimeTypes.TEXT_SSA;else->MimeTypes.TEXT_VTT}).setSelectionFlags(if(s.id==currentStream(activeSubtitle)?.id)C.SELECTION_FLAG_DEFAULT else 0).build()
}) })
} else { } else {
val p=api.transcodeParams(item,streamSession,mode,partOffsetMs,quality.conversion,mediaIndex,partIndex,local,vm.subtitleSize.plexPercent) val p=api.transcodeParams(item,streamSession,mode,partOffsetMs,quality.conversion,mediaIndex,partIndex,local,vm.subtitleSize.plexPercent).toMutableMap().apply {
currentStream(activeAudio)?.let{put("audioStreamID",it.id)}
put("subtitleStreamID",currentStream(activeSubtitle)?.id ?: "0")
}
val decision=api.container("/video/:/transcode/universal/decision",p) val decision=api.container("/video/:/transcode/universal/decision",p)
val streams=decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()} val streams=decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()}
.flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()} .flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}
@ -213,7 +255,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
} }
// Plex HLS exposes the part's original timeline, including a seek-start offset: // Plex HLS exposes the part's original timeline, including a seek-start offset:
// never add the requested offset again. // never add the requested offset again.
player.setMediaItem(builder.build(),partOffsetMs);player.prepare();player.playWhenReady=resume;player.setPlaybackSpeed(playbackRate) player.setMediaItem(builder.build(),partOffsetMs);player.prepare();player.playWhenReady=resume&&foreground;player.setPlaybackSpeed(playbackRate)
Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset part=${partIndex+1}/${parts.size} media=${mediaIndex+1}/${item.media.size} local=$local") Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset part=${partIndex+1}/${parts.size} media=${mediaIndex+1}/${item.media.size} local=$local")
}catch(e:CancellationException){throw e}catch(e:Exception){ }catch(e:CancellationException){throw e}catch(e:Exception){
audit?.event("prepareFailure",org.json.JSONObject().put("mode",newMode).put("kind",e.javaClass.simpleName).put("httpStatus",(e as? PlexException)?.status)) audit?.event("prepareFailure",org.json.JSONObject().put("mode",newMode).put("kind",e.javaClass.simpleName).put("httpStatus",(e as? PlexException)?.status))
@ -234,7 +276,10 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
/** Moves the pending seek target; repeated presses accumulate into one seek after [settle] ms. */ /** Moves the pending seek target; repeated presses accumulate into one seek after [settle] ms. */
fun scrubBy(delta:Long,settle:Long=650){scrubPosition=((scrubPosition ?: position)+delta).coerceIn(0,duration);seekJob?.cancel();seekJob=scope.launch{delay(settle);commitScrub()}} fun scrubBy(delta:Long,settle:Long=650){scrubPosition=((scrubPosition ?: position)+delta).coerceIn(0,duration);seekJob?.cancel();seekJob=scope.launch{delay(settle);commitScrub()}}
fun commitScrub(){val target=scrubPosition ?: return;scrubPosition=null;seekTo(target)} fun commitScrub(){val target=scrubPosition ?: return;scrubPosition=null;seekTo(target)}
fun pause(){player.pause();position=currentPosition();report("paused")} fun pause(){player.pause();if(!preparing)position=currentPosition();report("paused")}
/** The app left the foreground: pause, and keep any preparation still in flight paused. */
fun enterBackground(){foreground=false;pause()}
fun enterForeground(){foreground=true}
fun select(type:Int,groupIndex:Int,trackIndex:Int) { fun select(type:Int,groupIndex:Int,trackIndex:Int) {
val group=tracks.groups[groupIndex];selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,false).setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup,listOf(trackIndex))).build() val group=tracks.groups[groupIndex];selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,false).setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup,listOf(trackIndex))).build()
} }
@ -266,18 +311,27 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
} }
fun selectServerStream(stream:Stream?,type:Int) { fun selectServerStream(stream:Stream?,type:Int) {
scope.launch { scope.launch {
try { streamSelectionMutex.withLock {
try {prepareMutex.withLock selection@{
if(closed)return@selection
val part=part val part=part
if(type==C.TRACK_TYPE_TEXT){activeSubtitle=stream?.id ?: "0";api.selectStreams(part,subtitle=activeSubtitle)}else{activeAudio=stream?.id.orEmpty();api.selectStreams(part,audio=activeAudio)} val selected=stream?.let{currentStream(it.id)}
if(mode>0){prepare(mode,position,player.playWhenReady);return@launch} val id=selected?.id ?: "0"
if(type==C.TRACK_TYPE_AUDIO&&selected==null)return@selection
if(type==C.TRACK_TYPE_TEXT){api.selectStreams(part,subtitle=id);activeSubtitle=id}
else{api.selectStreams(part,audio=id);activeAudio=id}
val offset=currentPosition();val resume=player.playWhenReady
audit?.event("streamSelected",org.json.JSONObject().put("type",type).put("streamId",id).put("offset",offset).put("resume",resume))
if(mode>0){prepareInternal(mode,offset,resume);return@selection}
if(stream==null){selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return@launch} if(stream==null){selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return@launch}
val match=nativeTrack(type,stream) val match=selected?.let{nativeTrack(type,it)}
if(match!=null&&tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second) if(match!=null&&tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second)
else prepare(2,position) // Image subtitles and unsupported embedded tracks are burned by Plex. else prepareInternal(if(type==C.TRACK_TYPE_AUDIO)1 else 2,offset,resume)
}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message ?: "Could not change the selected track."} }}catch(e:CancellationException){throw e}catch(e:Exception){error="Could not change the selected track. Please try again."}
} }
} }
fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()} }
fun close(){if(closed)return;if(!preparing)position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()}
} }
/** The single playback quality preference: the original stream, then conversions from highest to lowest resolution. */ /** The single playback quality preference: the original stream, then conversions from highest to lowest resolution. */
enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:Int) { enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:Int) {
@ -288,6 +342,8 @@ enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:
SD("480p · 3 Mbps",720,480,3000); SD("480p · 3 Mbps",720,480,3000);
/** Target used when Plex must convert; Original falls back to 1080p if direct streaming fails. */ /** Target used when Plex must convert; Original falls back to 1080p if direct streaming fails. */
val conversion get()=if(this==Original)FullHD else this val conversion get()=if(this==Original)FullHD else this
fun forMedia(media:Media):String = if(this!=Original)label else "$label · "+
if(media.bitrate>0)String.format(java.util.Locale.US,"%.1f Mbps",media.bitrate/1000.0)else "Bitrate unavailable"
} }
fun clockTime(ms:Long):String {val s=(ms.coerceAtLeast(0)/1000);return if(s>=3600)"%d:%02d:%02d".format(s/3600,s/60%60,s%60)else "%d:%02d".format(s/60,s%60)} fun clockTime(ms:Long):String {val s=(ms.coerceAtLeast(0)/1000);return if(s>=3600)"%d:%02d:%02d".format(s/3600,s/60%60,s%60)else "%d:%02d".format(s/60,s%60)}
/** Subtitle text size; [plexPercent] sizes subtitles Plex burns into converted video. */ /** Subtitle text size; [plexPercent] sizes subtitles Plex burns into converted video. */

View file

@ -19,71 +19,178 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import androidx.compose.material3.Icon
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
@Composable internal fun PlaybackOptions(vm:KaleidoViewModel,controller:PlaybackController,item:Title,menu:Int,open:(Int)->Unit,close:()->Unit) { @Composable internal fun PlaybackOptions(vm:KaleidoViewModel,controller:PlaybackController,item:Title,menu:Int,open:(Int)->Unit,close:()->Unit) {
val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f) val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f)
// Audio and Subtitles have their own buttons; this menu holds the remaining options. // Audio is also named here so it is discoverable without recognizing the speaker icon.
val entries=listOfNotNull(4 to "Quality · ${vm.activeQuality.label}"+if(vm.localConnection)""else " (remote)",5 to "Speed · ${speedLabel(controller.playbackRate)}", val entries=listOfNotNull(10 to "Audio · ${controller.currentStream(controller.activeAudio)?.title ?: "Choose track"}",
4 to "Quality · ${controller.qualityOptionLabel(vm.activeQuality)}"+if(vm.localConnection)""else " (remote)",5 to "Speed · ${speedLabel(controller.playbackRate)}",
if(item.chapters.isNotEmpty())7 to "Chapters" else null,8 to "Subtitle size · ${vm.subtitleSize.label}",9 to "Subtitle style · ${vm.subtitleStyle.label}") if(item.chapters.isNotEmpty())7 to "Chapters" else null,8 to "Subtitle size · ${vm.subtitleSize.label}",9 to "Subtitle style · ${vm.subtitleStyle.label}")
// A submenu returns focus to the option that opened it. // A submenu returns focus to the option that opened it.
var returnTo by remember{mutableIntStateOf(0)} var returnTo by remember{mutableIntStateOf(0)}
val dismiss={if(menu==3)close()else open(3)} val dismiss={if(menu==3)close()else open(3)}
when(menu) { when(menu) {
3->TrackPanel("Playback options",entries.map{it.second},-1,dismiss,focusIndex=entries.indexOfFirst{it.first==returnTo}.coerceAtLeast(0)){index->returnTo=entries[index].first;open(entries[index].first)} 3->TrackPanel("Playback options",entries.map{it.second},-1,dismiss,focusIndex=entries.indexOfFirst{it.first==returnTo}.coerceAtLeast(0)){index->returnTo=entries[index].first;open(entries[index].first)}
4->TrackPanel(if(vm.localConnection)"Playback quality"else "Remote playback quality",StreamQuality.entries.map{it.label},vm.activeQuality.ordinal,dismiss){controller.changeQuality(StreamQuality.entries[it]);close()} 4->TrackPanel(if(vm.localConnection)"Playback quality"else "Remote playback quality",StreamQuality.entries.map(controller::qualityOptionLabel),vm.activeQuality.ordinal,dismiss){controller.changeQuality(StreamQuality.entries[it]);close()}
5->TrackPanel("Playback speed",speeds.map(::speedLabel),speeds.indexOf(controller.playbackRate),dismiss){controller.changeSpeed(speeds[it]);close()} 5->TrackPanel("Playback speed",speeds.map(::speedLabel),speeds.indexOf(controller.playbackRate),dismiss){controller.changeSpeed(speeds[it]);close()}
7->TrackPanel("Chapters",item.chapters.map{"${it.title} · ${clockTime(it.start)}"},item.chapters.indexOfLast{it.start<=controller.position},dismiss){controller.seekTo(item.chapters[it].start);close()} 7->TrackPanel("Chapters",item.chapters.map{"${it.title} · ${clockTime(it.start)}"},item.chapters.indexOfLast{it.start<=controller.position},dismiss){controller.seekTo(item.chapters[it].start);close()}
8->TrackPanel("Subtitle size",SubtitleSize.entries.map{it.label},vm.subtitleSize.ordinal,dismiss){vm.chooseSubtitleSize(SubtitleSize.entries[it]);close()} 8->TrackPanel("Subtitle size",SubtitleSize.entries.map{it.label},vm.subtitleSize.ordinal,dismiss){vm.chooseSubtitleSize(SubtitleSize.entries[it]);close()}
9->TrackPanel("Subtitle style",SubtitleStyle.entries.map{it.label},vm.subtitleStyle.ordinal,dismiss){vm.chooseSubtitleStyle(SubtitleStyle.entries[it]);close()} 9->TrackPanel("Subtitle style",SubtitleStyle.entries.map{it.label},vm.subtitleStyle.ordinal,dismiss){vm.chooseSubtitleStyle(SubtitleStyle.entries[it]);close()}
10->AudioTrackPanel(controller,dismiss,close)
} }
} }
internal fun speedLabel(speed:Float)=if(speed==1f)"Normal" else "${speed.toString().removeSuffix(".0")}×" internal fun speedLabel(speed:Float)=if(speed==1f)"Normal" else "${speed.toString().removeSuffix(".0")}×"
@Composable internal fun PostPlayScreen(vm:KaleidoViewModel,item:Title,dismiss:()->Unit,next:()->Unit) { /** Where the playing video shrinks to while Up Next is open, on the 960 × 540 dp canvas. */
internal object UpNextFrame {
val x=44.dp;val y=34.dp;val width=352.dp;val height=198.dp
}
/**
* Up Next's page beneath the player's surface: the next episode's artwork, top-right, fading into
* the page, and a black frame under the mini-player for letterboxed video. Drawn before the
* PlayerView, whose SurfaceView shows through only where nothing is drawn above it.
*/
@Composable internal fun UpNextBackdrop(vm:KaleidoViewModel,item:Title,modifier:Modifier) {
val upcoming=vm.followingEpisode(item) val upcoming=vm.followingEpisode(item)
// Settings › Playback sets the countdown; 0 turns autoplay off. val path=upcoming?.let{it.still.ifBlank{it.thumb}.ifBlank{it.art}} ?: item.art.ifBlank{item.thumb}
val countdown=vm.autoplaySeconds Box(modifier.fillMaxSize().background(Ink)) {
var autoplay by remember{mutableStateOf(countdown>0)} Box(Modifier.align(Alignment.TopEnd).width(640.dp).aspectRatio(16f/9f)) {
var seconds by remember{mutableIntStateOf(countdown)} if(path.isNotBlank())Artwork(vm.api,path,Modifier.fillMaxSize(),960,540,animate=false)
LaunchedEffect(autoplay,upcoming?.id) { Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(0f to Ink,.42f to Ink.copy(alpha=.72f),1f to Color.Transparent)))
if(autoplay&&upcoming!=null&&countdown>0){seconds=countdown;android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}");repeat(countdown){delay(1000);seconds--};android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()} Box(Modifier.fillMaxSize().background(Brush.verticalGradient(.35f to Color.Transparent,1f to Ink)))
} }
val season=vm.episodeQueue.filter{it.parentId==item.parentId} Box(Modifier.offset(UpNextFrame.x,UpNextFrame.y).size(UpNextFrame.width,UpNextFrame.height).background(Color.Black))
LazyColumn(Modifier.fillMaxSize().background(Color.Black.copy(alpha=.93f)),contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=29.dp),verticalArrangement=Arrangement.spacedBy(15.dp)) {
item {
Text(if(upcoming!=null)"Up next"else "More to watch",color=Accent,fontSize=25.sp,fontWeight=FontWeight.SemiBold)
Row(Modifier.padding(top=13.dp),horizontalArrangement=Arrangement.spacedBy(20.dp),verticalAlignment=Alignment.CenterVertically) {
if(upcoming!=null)Artwork(vm.api,upcoming.still.ifBlank{upcoming.thumb},Modifier.width(205.dp).aspectRatio(16f/9f).clip(RoundedCornerShape(5.dp)),480,270,animate=false)
Column(Modifier.weight(1f)) {
Text(upcoming?.displayTitle ?: item.displayTitle,color=Accent,fontSize=21.sp,fontWeight=FontWeight.SemiBold)
Text(upcoming?.let{"S${it.parentIndex} · E${it.index} ${it.title}"} ?: "You've reached the end of this series.",color=Cinema.secondary,fontSize=12.sp,modifier=Modifier.padding(top=5.dp,bottom=15.dp))
Row(horizontalArrangement=Arrangement.spacedBy(10.dp),verticalAlignment=Alignment.CenterVertically) {
if(upcoming!=null)ActionButton(if(vm.transitioningEpisode)"Loading…"else if(autoplay)"Play in $seconds"else "Play now",Icons.Filled.PlayArrow,modifier=Modifier.onFocusChanged{if(it.isFocused&&BuildConfig.DEBUG)android.util.Log.i("KaleidoPlayback","POSTPLAY focus=play")},primary=true,initialFocus=true){autoplay=false;next()}
if(upcoming!=null&&countdown>0)TvButton(if(autoplay)"Cancel autoplay"else "Autoplay off"){autoplay=!autoplay;android.util.Log.i("KaleidoPlayback","AUTOPLAY ${if(autoplay)"enabled"else "cancelled"} item=${item.id}")}
TvButton("Back to video"){autoplay=false;dismiss()}
}
}
}
}
if(season.isNotEmpty())item {PostPlayRail(vm,"Episodes in this season",season){autoplay=false;vm.play(it,true)}}
if(vm.relatedShows.isNotEmpty())item {PostPlayRail(vm,"Related shows",vm.relatedShows){autoplay=false;vm.stopPlayback();vm.open(it)}}
} }
} }
@Composable private fun PostPlayRail(vm:KaleidoViewModel,label:String,titles:List<Title>,choose:(Title)->Unit) { /**
* Up Next, over the shrunken player: the next episode with one countdown, the season and related shows.
* Any remote press stops the countdown. Left from Play next (or Back) returns to the playing video.
*/
@Composable internal fun PostPlayScreen(vm:KaleidoViewModel,item:Title,controller:PlaybackController,watchVideo:()->Unit,next:()->Unit) {
val upcoming=vm.followingEpisode(item)
// Settings › Playback sets the countdown; 0 turns autoplay off.
val countdown=if(vm.shuffling&&vm.autoplaySeconds==0)5 else vm.autoplaySeconds
var cancelled by remember{mutableStateOf(false)}
val counting=upcoming!=null&&countdown>0&&!cancelled
var elapsed by remember{mutableLongStateOf(0)}
// The countdown runs only while Kaleido is on screen; leaving it restarts on return.
val lifecycle by LocalLifecycleOwner.current.lifecycle.currentStateAsState()
val onScreen=lifecycle.isAtLeast(Lifecycle.State.STARTED)
LaunchedEffect(counting,upcoming?.id,onScreen) {
if(!counting||!onScreen||upcoming==null)return@LaunchedEffect
val total=countdown*1000L;elapsed=0
android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}")
while(elapsed<total){delay(50);elapsed+=50}
android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()
}
val playFocus=remember{FocusRequester()}
val videoFocus=remember{FocusRequester()}
LaunchedEffect(Unit){withFrameNanos{};runCatching{(if(upcoming!=null)playFocus else videoFocus).requestFocus()}}
val season=vm.episodeQueue.filter{it.parentId==item.parentId}
Box(Modifier.fillMaxSize().onPreviewKeyEvent{
if(it.type==KeyEventType.KeyDown&&counting){cancelled=true;android.util.Log.i("KaleidoPlayback","AUTOPLAY cancelled item=${item.id}")}
false
}) {
// The video itself is the PlayerView beneath; this is its focus target and outline.
var videoFocused by remember{mutableStateOf(false)}
Box(Modifier.offset(UpNextFrame.x-4.dp,UpNextFrame.y-4.dp).size(UpNextFrame.width+8.dp,UpNextFrame.height+8.dp)
.focusRequester(videoFocus).focusProperties{right=if(upcoming!=null)playFocus else FocusRequester.Default}
.navigationSound().onFocusChanged{videoFocused=it.isFocused}
.border(if(videoFocused)2.dp else 1.dp,Color.White.copy(alpha=if(videoFocused)1f else .16f),RoundedCornerShape(8.dp))
.semantics{contentDescription="Return to "+item.displayTitle}.clickable(onClick=watchVideo))
NowPlaying(item,controller,videoFocused,Modifier.offset(UpNextFrame.x,UpNextFrame.y+UpNextFrame.height+10.dp).width(UpNextFrame.width))
Column(Modifier.padding(start=UpNextFrame.x+UpNextFrame.width+36.dp,top=36.dp,end=Cinema.gutter)) {
Eyebrow(if(upcoming==null)"More to watch"else if(vm.shuffling)"Up next · Shuffle"else "Up next")
Spacer(Modifier.height(8.dp))
// The playing episode carries its show's title art; listed episodes may not.
TitleIdentity(vm.api,item,Modifier.size(240.dp,44.dp))
if(upcoming!=null) {
val metadata by produceState(upcoming,upcoming.id){value=upcoming;value=vm.previewDetails(upcoming)}
Text(upcoming.title,color=Accent,fontSize=21.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=6.dp))
Row(Modifier.padding(top=6.dp).height(17.dp),verticalAlignment=Alignment.CenterVertically) {
if(metadata.contentRating.isNotBlank())FormatBadge(metadata.contentRating,Modifier.padding(end=8.dp))
Text(listOf("S${upcoming.parentIndex} · E${upcoming.index}",if(upcoming.duration>0)runtimeLabel(upcoming.duration)else "").filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=11.sp,lineHeight=15.sp,maxLines=1)
AudienceRatings(metadata,Modifier.padding(start=10.dp))
}
if(metadata.summary.isNotBlank())Text(metadata.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=8.dp))
UpNextButton(if(vm.transitioningEpisode)"Loading…"else "Play next episode",if(counting)({(elapsed.toFloat()/(countdown*1000)).coerceIn(0f,1f)})else null,
Modifier.padding(top=14.dp).focusRequester(playFocus).focusProperties{left=videoFocus}.onFocusChanged{if(it.isFocused&&BuildConfig.DEBUG)android.util.Log.i("KaleidoPlayback","POSTPLAY focus=play")}) {
cancelled=true;next()
}
}
else Text("You've reached the end of this series.",color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=8.dp))
}
LazyColumn(Modifier.fillMaxWidth().padding(top=292.dp),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,bottom=24.dp),verticalArrangement=Arrangement.spacedBy(14.dp)) {
val up=if(upcoming!=null)playFocus else videoFocus
if(season.isNotEmpty())item {
val current=season.indexOfFirst{it.id==item.id}
PostPlayRail(vm,if(item.parentIndex>0)"Season ${item.parentIndex}"else "Episodes",season,up,(current-1).coerceAtLeast(0),{when(it.id){item.id->"Now playing";upcoming?.id->"Up next";else->if(it.duration>0)runtimeLabel(it.duration)else ""}}){vm.play(it,true)}
}
if(vm.relatedShows.isNotEmpty())item {PostPlayRail(vm,"Related shows",vm.relatedShows,if(season.isEmpty())up else null,0,{it.year}){vm.stopPlayback();vm.open(it)}}
}
}
}
/** Where the playing episode is, under the mini-player. Its own scope: position ticks recompose only this. */
@Composable private fun NowPlaying(item:Title,controller:PlaybackController,focused:Boolean,modifier:Modifier) {
Column(modifier) {
Row(verticalAlignment=Alignment.CenterVertically) {
Text((if(item.type=="episode")"S${item.parentIndex} · E${item.index} "else "")+item.title,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f))
Text("−"+clockTime(controller.duration-controller.position),color=Cinema.quiet,fontSize=10.sp,lineHeight=14.sp,maxLines=1,modifier=Modifier.padding(start=10.dp))
}
val progress=if(controller.duration>0)(controller.position.toFloat()/controller.duration).coerceIn(0f,1f)else 0f
Box(Modifier.padding(top=6.dp).fillMaxWidth().height(3.dp).clip(RoundedCornerShape(2.dp)).background(Color.White.copy(alpha=.22f))) {
Box(Modifier.fillMaxHeight().fillMaxWidth(progress).background(Accent))
}
}
}
/** Play next episode. While autoplay counts down ([progress] non-null) a lighter fill sweeps across it, without numbers. */
@Composable private fun UpNextButton(label:String,progress:(()->Float)?,modifier:Modifier,onClick:()->Unit) {
var focused by remember{mutableStateOf(false)}
val shape=RoundedCornerShape(5.dp)
val foreground=if(focused)Ink else Accent
Row(modifier.height(34.dp).navigationSound().onFocusChanged{focused=it.isFocused}.clip(shape)
.drawBehind{
val fill=progress?.invoke()
drawRect(if(focused)(if(fill!=null)Color(0xFFBDBDBD)else Accent)else Color.White.copy(alpha=.16f))
if(fill!=null)drawRect(if(focused)Accent else Color.White.copy(alpha=.18f),size=androidx.compose.ui.geometry.Size(size.width*fill,size.height))
}
.semantics{contentDescription=label}.clickable(onClick=onClick).padding(horizontal=14.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
Icon(Icons.Filled.PlayArrow,null,tint=foreground,modifier=Modifier.size(17.dp))
Text(label,color=foreground,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.SemiBold)
}
}
@Composable private fun PostPlayRail(vm:KaleidoViewModel,label:String,titles:List<Title>,up:FocusRequester?,start:Int,caption:(Title)->String,choose:(Title)->Unit) {
Column { Column {
Text(label,color=Accent,fontSize=16.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=8.dp)) Text(label,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=8.dp))
LazyRow(horizontalArrangement=Arrangement.spacedBy(12.dp)) { LazyRow(state=rememberLazyListState(start),horizontalArrangement=Arrangement.spacedBy(12.dp)) {
items(titles,key={it.id}){title-> items(titles,key={it.id}){title->
var focused by remember{mutableStateOf(false)} var focused by remember{mutableStateOf(false)}
Column(Modifier.width(167.dp).navigationSound().onFocusChanged{focused=it.isFocused}.semantics{contentDescription=title.displayTitle+" "+title.subtitle}.clickable{choose(title)}) { Column(Modifier.width(188.dp).then(if(up!=null)Modifier.focusProperties{this.up=up}else Modifier).navigationSound().onFocusChanged{focused=it.isFocused}.semantics{contentDescription=title.displayTitle+" "+title.subtitle}.clickable{choose(title)}) {
Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).clip(RoundedCornerShape(4.dp))) { Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).clip(RoundedCornerShape(6.dp))) {
Artwork(vm.api,if(title.type=="episode")title.still.ifBlank{title.thumb}else title.art.ifBlank{title.thumb},Modifier.fillMaxSize(),384,216,animate=false) Artwork(vm.api,if(title.type=="episode")title.still.ifBlank{title.thumb}else title.art.ifBlank{title.thumb},Modifier.fillMaxSize(),384,216,animate=false)
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(4.dp))) if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(6.dp)))
} }
Text(if(title.type=="episode")"${title.index}. ${title.title}"else title.title,color=if(focused)Accent else Cinema.secondary,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=4.dp)) Text(if(title.type=="episode")"${title.index}. ${title.title}"else title.title,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=5.dp))
Text(caption(title),color=Cinema.quiet,fontSize=10.sp,lineHeight=14.sp,maxLines=1)
} }
} }
} }

View file

@ -5,6 +5,8 @@ import androidx.activity.compose.LocalActivity
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.core.tween import androidx.compose.animation.core.tween
@ -26,10 +28,14 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.focus.* import androidx.compose.ui.focus.*
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.layout
import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.input.key.* import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
@ -64,6 +70,18 @@ import kotlinx.coroutines.delay
// Set once the timeline takes focus for this reveal, so Play's initial focus can't take it back. // Set once the timeline takes focus for this reveal, so Play's initial focus can't take it back.
var timelineReveal by remember{mutableStateOf(false)} var timelineReveal by remember{mutableStateOf(false)}
var restoreMenuFocus by remember{mutableIntStateOf(0)} var restoreMenuFocus by remember{mutableIntStateOf(0)}
var skipSeconds by remember(item.id){mutableIntStateOf(0)}
var skipPulse by remember(item.id){mutableIntStateOf(0)}
var skipForward by remember(item.id){mutableStateOf(true)}
LaunchedEffect(skipPulse){if(skipPulse>0){delay(1000);skipSeconds=0}}
fun quickSkip(delta:Long){
val before=controller.scrubPosition ?: controller.position
controller.scrubBy(delta,settle=350)
val actual=((controller.scrubPosition ?: before)-before).toInt()/1000
skipSeconds=if(skipSeconds*actual>0)skipSeconds+actual else actual
skipForward=delta>0
skipPulse++
}
val rootFocus=remember{FocusRequester()} val rootFocus=remember{FocusRequester()}
val timelineFocus=remember{FocusRequester()} val timelineFocus=remember{FocusRequester()}
val playFocus=remember{FocusRequester()} val playFocus=remember{FocusRequester()}
@ -82,32 +100,61 @@ import kotlinx.coroutines.delay
// Derived: the player only recomposes when a marker starts or ends, not on every position tick. // Derived: the player only recomposes when a marker starts or ends, not on every position tick.
val marker by remember{derivedStateOf{item.markers.firstOrNull{controller.position>=it.start&&controller.position<it.end&&it.type in listOf("intro","credits")}}} val marker by remember{derivedStateOf{item.markers.firstOrNull{controller.position>=it.start&&controller.position<it.end&&it.type in listOf("intro","credits")}}}
fun skip(marker:Marker){ fun skip(marker:Marker){
if(marker.type=="credits"&&item.type=="episode"){controller.pause();android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=skip-credits");postPlay=true} // Episodes go to Up Next, where the credits keep playing in the corner.
if(marker.type=="credits"&&item.type=="episode"){android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=skip-credits");postPlay=true}
else controller.seekTo(marker.end) else controller.seekTo(marker.end)
} }
// Each marker is skipped automatically once, so seeking back into it plays it. // Each marker counts down to an automatic skip once, so seeking back into it plays it.
// The countdown runs only while playing; any remote press cancels it (OK on the button skips now).
val autoSkipped=remember{mutableSetOf<Marker>()} val autoSkipped=remember{mutableSetOf<Marker>()}
LaunchedEffect(marker,controller.loading) { var autoSkip by remember{mutableStateOf<Marker?>(null)}
val m=marker ?: return@LaunchedEffect var autoSkipTotal by remember{mutableLongStateOf(0)}
if(controller.loading||postPlay||m in autoSkipped)return@LaunchedEffect var autoSkipRemaining by remember{mutableLongStateOf(0)}
if(m.type=="intro"&&vm.autoSkipIntro||m.type=="credits"&&vm.autoSkipCredits){autoSkipped+=m;android.util.Log.i("KaleidoPlayback","AUTOSKIP ${m.type} item=${item.id}");skip(m)} fun cancelAutoSkip(){val m=autoSkip ?: return;autoSkipped+=m;autoSkip=null;android.util.Log.i("KaleidoPlayback","AUTOSKIP cancelled ${m.type} item=${item.id}")}
LaunchedEffect(marker,controller.loading,postPlay) {
val m=marker
if(m==null||controller.loading||postPlay||m in autoSkipped){if(m==null||postPlay)autoSkip=null;return@LaunchedEffect}
val seconds=when(m.type){"intro"->vm.autoSkipIntroSeconds;"credits"->vm.autoSkipCreditsSeconds;else->0}
if(seconds<=0)return@LaunchedEffect
// Up Next has the one countdown (to the next episode), so automatic credits open it at once.
if(m.type=="credits"&&item.type=="episode"){autoSkipped+=m;android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=credits");postPlay=true;return@LaunchedEffect}
if(autoSkip!=m){autoSkip=m;autoSkipTotal=seconds*1000L;autoSkipRemaining=autoSkipTotal;android.util.Log.i("KaleidoPlayback","AUTOSKIP countdown ${m.type} seconds=$seconds item=${item.id}")}
while(autoSkipRemaining>0){delay(50);if(autoSkip!=m)return@LaunchedEffect;if(controller.isPlaying)autoSkipRemaining-=50}
if(autoSkip!=m)return@LaunchedEffect
autoSkipped+=m;autoSkip=null;android.util.Log.i("KaleidoPlayback","AUTOSKIP ${m.type} item=${item.id}");skip(m)
} }
DisposableEffect(controller) { DisposableEffect(controller) {
activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
val observer=LifecycleEventObserver{_,event->if(event==Lifecycle.Event.ON_STOP)controller.pause()} val observer=LifecycleEventObserver{_,event->when(event){Lifecycle.Event.ON_STOP->controller.enterBackground();Lifecycle.Event.ON_START->controller.enterForeground();else->{}}}
owner.lifecycle.addObserver(observer) owner.lifecycle.addObserver(observer)
// Created while already stopped (e.g. a next episode loading behind Home): start paused.
if(!owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))controller.enterBackground()
onDispose{owner.lifecycle.removeObserver(observer);activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);controller.close()} onDispose{owner.lifecycle.removeObserver(observer);activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);controller.close()}
} }
LaunchedEffect(controls,interaction,controller.isPlaying,trackMenu) { // Up Next owns focus while open: hiding the controls behind it must not take focus back.
if(controls&&controller.isPlaying&&trackMenu==0){delay(5000);controls=false} LaunchedEffect(controls,interaction,controller.isPlaying,trackMenu,postPlay) {
if(controls&&controller.isPlaying&&trackMenu==0&&!postPlay){delay(5000);controls=false}
} }
LaunchedEffect(controls) {if(!controls){timelineReveal=false;delay(210);runCatching{rootFocus.requestFocus()}}} LaunchedEffect(controls) {if(!controls&&!postPlay){timelineReveal=false;delay(210);if(!postPlay)runCatching{rootFocus.requestFocus()}}}
LaunchedEffect(seekFocus,controls) {if(seekFocus&&controls){delay(220);runCatching{timelineFocus.requestFocus()};timelineReveal=true;seekFocus=false}} LaunchedEffect(seekFocus,controls) {if(seekFocus&&controls){delay(220);runCatching{timelineFocus.requestFocus()};timelineReveal=true;seekFocus=false}}
LaunchedEffect(restoreMenuFocus,trackMenu) {if(restoreMenuFocus!=0&&trackMenu==0){delay(16);runCatching{(when(restoreMenuFocus){1->audioFocus;2->subtitleFocus;else->optionsFocus}).requestFocus()};restoreMenuFocus=0}} LaunchedEffect(restoreMenuFocus,trackMenu) {if(restoreMenuFocus!=0&&trackMenu==0){delay(16);runCatching{(when(restoreMenuFocus){1->audioFocus;2->subtitleFocus;else->optionsFocus}).requestFocus()};restoreMenuFocus=0}}
fun goBack(){if(postPlay)postPlay=false else if(trackMenu!=0)closeTracks()else if(controls)controls=false else vm.stopPlayback()} // Leaving Up Next returns to the full-screen video without revealing the controls.
var refocusRoot by remember{mutableIntStateOf(0)}
LaunchedEffect(refocusRoot){if(refocusRoot>0){withFrameNanos{};runCatching{rootFocus.requestFocus()}}}
fun leaveUpNext(){postPlay=false;controls=false;refocusRoot++;android.util.Log.i("KaleidoPlayback","POSTPLAY closed item=${item.id}")}
// The video shrinks into Up Next's corner and grows back; only its layout reads the animation.
val upNext=androidx.compose.animation.core.animateFloatAsState(if(postPlay)1f else 0f,tween(320),label="upNext")
fun goBack(){if(postPlay)leaveUpNext() else if(trackMenu!=0)closeTracks()else if(controls)controls=false else vm.stopPlayback()}
BackHandler(onBack=::goBack) BackHandler(onBack=::goBack)
val visible=controls&&!postPlay val visible=controls&&!postPlay
Box(Modifier.fillMaxSize().background(Color.Black).focusRequester(rootFocus).onPreviewKeyEvent{event-> Box(Modifier.fillMaxSize().background(Color.Black).focusRequester(rootFocus).onPreviewKeyEvent{event->
// A pending automatic skip yields to the remote. Back only cancels it; OK on a hidden
// player still takes the Skip button, which skips now.
val okHidden=!visible&&event.nativeKeyEvent.keyCode in listOf(android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER)
if(autoSkip!=null&&event.type==KeyEventType.KeyDown&&!okHidden&&!postPlay){
cancelAutoSkip()
if(event.key==Key.Back)return@onPreviewKeyEvent true
}
if(event.key==Key.Back){if(event.type==KeyEventType.KeyDown)goBack();true} if(event.key==Key.Back){if(event.type==KeyEventType.KeyDown)goBack();true}
else if(event.type!=KeyEventType.KeyDown||postPlay)false else { else if(event.type!=KeyEventType.KeyDown||postPlay)false else {
interacted() interacted()
@ -118,12 +165,12 @@ import kotlinx.coroutines.delay
android.view.KeyEvent.KEYCODE_MEDIA_FAST_FORWARD->{controller.seekTo(controller.position+30000);controls=true;seekFocus=true;true} android.view.KeyEvent.KEYCODE_MEDIA_FAST_FORWARD->{controller.seekTo(controller.position+30000);controls=true;seekFocus=true;true}
android.view.KeyEvent.KEYCODE_MEDIA_REWIND->{controller.seekTo(controller.position-10000);controls=true;seekFocus=true;true} android.view.KeyEvent.KEYCODE_MEDIA_REWIND->{controller.seekTo(controller.position-10000);controls=true;seekFocus=true;true}
// With the controls hidden, OK takes a visible Skip intro/credits; otherwise it reveals them. // With the controls hidden, OK takes a visible Skip intro/credits; otherwise it reveals them.
android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER->{if(!visible){marker?.let(::skip) ?: run{controls=true};true}else false} android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER->{if(!visible){marker?.let{autoSkip=null;autoSkipped+=it;skip(it)} ?: run{controls=true};true}else false}
android.view.KeyEvent.KEYCODE_DPAD_LEFT,android.view.KeyEvent.KEYCODE_DPAD_RIGHT->{ android.view.KeyEvent.KEYCODE_DPAD_LEFT,android.view.KeyEvent.KEYCODE_DPAD_RIGHT->{
val delta=if(event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_LEFT)-10000L else 10000L val delta=if(event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_LEFT)-10000L else 10000L
when { when {
// A tap skips without revealing anything; quick taps add up into one seek. // Quick taps accumulate a seek and show a brief directional cue.
!visible&&event.nativeKeyEvent.repeatCount==0->{controller.scrubBy(delta,settle=350);true} !visible&&event.nativeKeyEvent.repeatCount==0->{quickSkip(delta);true}
// Holding reveals the timeline and keeps scrubbing until it takes focus. // Holding reveals the timeline and keeps scrubbing until it takes focus.
!visible||seekFocus->{controller.scrubBy(delta);controls=true;seekFocus=true;true} !visible||seekFocus->{controller.scrubBy(delta);controls=true;seekFocus=true;true}
else->false else->false
@ -134,6 +181,7 @@ import kotlinx.coroutines.delay
} }
} }
}.focusable()) { }.focusable()) {
if(postPlay)UpNextBackdrop(vm,item,Modifier.graphicsLayer{alpha=upNext.value})
AndroidView(factory={context->PlayerView(context).apply { AndroidView(factory={context->PlayerView(context).apply {
setEnableComposeSurfaceSyncWorkaround(true) setEnableComposeSurfaceSyncWorkaround(true)
player=controller.player player=controller.player
@ -142,42 +190,71 @@ import kotlinx.coroutines.delay
descendantFocusability=ViewGroup.FOCUS_BLOCK_DESCENDANTS descendantFocusability=ViewGroup.FOCUS_BLOCK_DESCENDANTS
setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER) setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER)
setKeepContentOnPlayerReset(true) setKeepContentOnPlayerReset(true)
}},update={view->view.subtitleView?.let{applySubtitleStyle(it,vm.subtitleSize,vm.subtitleStyle)}},modifier=Modifier.fillMaxSize(),onRelease={it.player=null}) }},update={view->view.subtitleView?.let{applySubtitleStyle(it,vm.subtitleSize,vm.subtitleStyle)}},modifier=Modifier.fillMaxSize().layout{measurable,constraints->
if(controller.loading)CircularProgressIndicator(color=Accent,strokeWidth=2.dp,modifier=Modifier.align(Alignment.Center).size(30.dp)) val f=upNext.value
fun lerp(a:Int,b:Int)=(a+(b-a)*f).toInt()
val width=lerp(constraints.maxWidth,UpNextFrame.width.roundToPx());val height=lerp(constraints.maxHeight,UpNextFrame.height.roundToPx())
val placeable=measurable.measure(androidx.compose.ui.unit.Constraints.fixed(width,height))
layout(constraints.maxWidth,constraints.maxHeight){placeable.place(lerp(0,UpNextFrame.x.roundToPx()),lerp(0,UpNextFrame.y.roundToPx()))}
},onRelease={it.player=null})
if(controller.loading&&!postPlay)CircularProgressIndicator(color=Accent,strokeWidth=2.dp,modifier=Modifier.align(Alignment.Center).size(30.dp))
QuickSkipFeedback(skipSeconds,skipPulse,!visible&&!postPlay,Modifier.align(if(skipForward)Alignment.CenterEnd else Alignment.CenterStart).padding(horizontal=32.dp))
AnimatedVisibility(visible=visible,enter=fadeIn(tween(190))+slideInVertically(tween(190)){it/8},exit=fadeOut(tween(190))+slideOutVertically(tween(190)){it/10},modifier=Modifier.align(Alignment.BottomCenter)) { AnimatedVisibility(visible=visible,enter=fadeIn(tween(190))+slideInVertically(tween(190)){it/8},exit=fadeOut(tween(190))+slideOutVertically(tween(190)){it/10},modifier=Modifier.align(Alignment.BottomCenter)) {
Column(Modifier.fillMaxWidth().background(Brush.verticalGradient(0f to Color.Transparent,.42f to Color.Black.copy(alpha=.46f),1f to Color.Black.copy(alpha=.79f))).padding(start=Cinema.gutter,end=Cinema.gutter,top=31.dp,bottom=16.dp)) { Column(Modifier.fillMaxWidth().background(Brush.verticalGradient(0f to Color.Transparent,.35f to Color.Black.copy(alpha=.5f),1f to Color.Black.copy(alpha=.85f))).padding(start=Cinema.gutter,end=Cinema.gutter,top=48.dp,bottom=16.dp)) {
Row(Modifier.fillMaxWidth().padding(bottom=7.dp),verticalAlignment=Alignment.Bottom) { // The title art and facts the browse previews and details use, at playback scale.
Text(item.displayTitle,color=Accent,fontSize=18.sp,lineHeight=23.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f)) Row(Modifier.fillMaxWidth().padding(bottom=10.dp),verticalAlignment=Alignment.Bottom) {
Column(Modifier.weight(1f)) {
TitleIdentity(vm.api,item,Modifier.size(240.dp,44.dp))
Row(Modifier.padding(top=8.dp).height(17.dp),verticalAlignment=Alignment.CenterVertically) {
if(item.contentRating.isNotBlank())FormatBadge(item.contentRating,Modifier.padding(end=8.dp))
Text((if(item.type=="episode")listOf("S${item.parentIndex} · E${item.index}",item.title)else listOf(item.year,item.genres.firstOrNull().orEmpty())).filter{it.isNotBlank()}.joinToString(" · "),
color=Cinema.secondary,fontSize=11.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis)
}
}
Spacer(Modifier.width(18.dp)) Spacer(Modifier.width(18.dp))
Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else controller.qualityLabel,color=Color.White.copy(alpha=.72f),fontSize=12.sp,lineHeight=16.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=420.dp)) Text(controller.qualityLabel,color=Color.White.copy(alpha=.6f),fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=360.dp))
} }
SeekTimeline(controller,item,Modifier.fillMaxWidth().focusRequester(timelineFocus).focusProperties{down=playFocus},::interacted) // Elapsed and remaining time sit at the timeline's ends and follow a pending scrub.
Box(Modifier.fillMaxWidth().height(40.dp)) { val shownPosition=controller.scrubPosition ?: controller.position
Row(Modifier.align(Alignment.CenterStart),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) { Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) {
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Exit playback",size=30.dp,iconSize=18.dp,onFocused=::interacted){vm.stopPlayback()} Text(clockTime(shownPosition),color=Color.White.copy(alpha=.82f),fontSize=10.sp,lineHeight=14.sp,maxLines=1,modifier=Modifier.width(58.dp))
Text(clockTime(controller.position),color=Color.White.copy(alpha=.78f),fontSize=10.sp,lineHeight=14.sp) SeekTimeline(controller,item,Modifier.weight(1f).focusRequester(timelineFocus).focusProperties{down=playFocus},::interacted)
Text("−"+clockTime(controller.duration-shownPosition),color=Color.White.copy(alpha=.62f),fontSize=10.sp,lineHeight=14.sp,maxLines=1,textAlign=TextAlign.End,modifier=Modifier.width(58.dp))
} }
Row(Modifier.align(Alignment.Center),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(16.dp)) { Box(Modifier.fillMaxWidth().padding(top=6.dp).height(48.dp)) {
IconControl(Icons.Outlined.Replay10,"Back 10 seconds",size=32.dp,iconSize=22.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.seekTo(controller.position-10000);interacted()} Row(Modifier.align(Alignment.CenterStart),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) {
IconControl(if(controller.isPlaying)Icons.Filled.Pause else Icons.Filled.PlayArrow,if(controller.isPlaying)"Pause"else "Play",size=38.dp,iconSize=28.dp,requester=playFocus,initialFocus=controls&&!seekFocus&&!timelineReveal,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.toggle();controls=true;interacted()} IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Exit playback",size=32.dp,iconSize=19.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){vm.stopPlayback()}
IconControl(Icons.Outlined.Forward30,"Forward 30 seconds",size=32.dp,iconSize=22.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.seekTo(controller.position+30000);interacted()} Text("Ends "+endsAt(controller),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,maxLines=1)
}
// Transport: episodes step between neighbours around the seek and play controls.
// An absent previous episode keeps its space, so Play stays centred.
Row(Modifier.align(Alignment.Center),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(14.dp)) {
val up=Modifier.focusProperties{up=timelineFocus}
if(item.type=="episode") {
if(vm.mayHavePrecedingEpisode(item))IconControl(Icons.Outlined.SkipPrevious,"Previous episode",size=34.dp,iconSize=22.dp,modifier=up,onFocused=::interacted){vm.previousEpisode(item);interacted()}
else Spacer(Modifier.size(34.dp))
}
IconControl(Icons.Outlined.Replay10,"Back 10 seconds",size=34.dp,iconSize=22.dp,modifier=up,onFocused=::interacted){controller.seekTo(controller.position-10000);interacted()}
IconControl(if(controller.isPlaying)Icons.Filled.Pause else Icons.Filled.PlayArrow,if(controller.isPlaying)"Pause"else "Play",size=46.dp,iconSize=30.dp,requester=playFocus,selected=true,initialFocus=controls&&!seekFocus&&!timelineReveal,modifier=up,onFocused=::interacted){controller.toggle();controls=true;interacted()}
IconControl(Icons.Outlined.Forward30,"Forward 30 seconds",size=34.dp,iconSize=22.dp,modifier=up,onFocused=::interacted){controller.seekTo(controller.position+30000);interacted()}
if(item.type=="episode")IconControl(Icons.Outlined.SkipNext,"Next episode",size=34.dp,iconSize=22.dp,modifier=up,onFocused=::interacted){vm.nextEpisode(item);interacted()}
} }
Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) { Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) {
Text("−"+clockTime(controller.duration-controller.position)+" · Ends "+endsAt(controller),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,modifier=Modifier.padding(end=8.dp)) IconControl(Icons.AutoMirrored.Outlined.VolumeUp,"Audio tracks",size=32.dp,iconSize=20.dp,requester=audioFocus,selected=trackMenu==1,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=1;interacted()}
if(item.type=="episode")IconControl(Icons.Outlined.SkipNext,"Next episode",size=30.dp,iconSize=21.dp,onFocused=::interacted){vm.nextEpisode(item)} IconControl(Icons.Outlined.Subtitles,"Subtitles",size=32.dp,iconSize=20.dp,requester=subtitleFocus,selected=trackMenu==2,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=2;interacted()}
IconControl(Icons.AutoMirrored.Outlined.VolumeUp,"Audio tracks",size=30.dp,iconSize=21.dp,requester=audioFocus,selected=trackMenu==1,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=1;interacted()} IconControl(Icons.Outlined.Settings,"Playback options",size=32.dp,iconSize=20.dp,requester=optionsFocus,selected=trackMenu>=3,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=3;interacted()}
IconControl(Icons.Outlined.Subtitles,"Subtitles",size=30.dp,iconSize=21.dp,requester=subtitleFocus,selected=trackMenu==2,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=2;interacted()}
IconControl(Icons.Outlined.Settings,"Playback options",size=30.dp,iconSize=21.dp,requester=optionsFocus,selected=trackMenu>=3,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=3;interacted()}
} }
} }
} }
} }
marker?.let{marker->if(!postPlay)Box(Modifier.align(Alignment.BottomEnd).padding(end=Cinema.gutter,bottom=if(visible)130.dp else 45.dp)) { marker?.let{marker->if(!postPlay)Box(Modifier.align(Alignment.BottomEnd).padding(end=Cinema.gutter,bottom=if(visible)146.dp else 45.dp)) {
ActionButton(if(marker.type=="intro")"Skip intro"else "Skip credits",Icons.Outlined.ChevronRight,modifier=Modifier.background(Color.Black.copy(alpha=.9f),RoundedCornerShape(5.dp)).border(1.dp,Color.White.copy(alpha=.75f),RoundedCornerShape(5.dp))){skip(marker);interacted()} val counting=autoSkip==marker&&autoSkipTotal>0
SkipMarkerButton(marker.type=="intro",if(counting)1f-(autoSkipRemaining.toFloat()/autoSkipTotal).coerceIn(0f,1f)else null){autoSkip=null;autoSkipped+=marker;skip(marker);interacted()}
}} }}
if(postPlay)PostPlayScreen(vm,item,{postPlay=false;controls=true},{vm.nextEpisode(item)}) if(postPlay)PostPlayScreen(vm,item,controller,::leaveUpNext){vm.nextEpisode(item)}
controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})} controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})}
if(trackMenu in 1..2) { if(trackMenu==1)AudioTrackPanel(controller,::closeTracks,::closeTracks)
if(trackMenu==2) {
val type=if(trackMenu==1)C.TRACK_TYPE_AUDIO else C.TRACK_TYPE_TEXT val type=if(trackMenu==1)C.TRACK_TYPE_AUDIO else C.TRACK_TYPE_TEXT
val streams=controller.part.streams.filter{it.type==(if(trackMenu==1)2 else 3)} val streams=controller.part.streams.filter{it.type==(if(trackMenu==1)2 else 3)}
val options=(if(trackMenu==2)listOf("Off")else emptyList())+streams.map{it.title} val options=(if(trackMenu==2)listOf("Off")else emptyList())+streams.map{it.title}
@ -193,6 +270,57 @@ import kotlinx.coroutines.delay
} }
} }
/**
* Skip intro/credits. While an automatic skip is pending ([progress] non-null) it reads
* "Skipping intro" and a lighter fill sweeps across it until the skip happens, without numbers.
*/
@Composable private fun SkipMarkerButton(intro:Boolean,progress:Float?,onClick:()->Unit) {
var focused by remember{mutableStateOf(false)}
val shape=RoundedCornerShape(6.dp)
val label=if(progress!=null)(if(intro)"Skipping intro"else "Skipping credits")else if(intro)"Skip intro"else "Skip credits"
val foreground=if(focused)Ink else Accent
Row(Modifier.height(36.dp).navigationSound().onFocusChanged{focused=it.isFocused}.clip(shape)
.drawBehind{
drawRect(if(focused)Accent else Color(0xE6181818))
if(progress!=null&&!focused)drawRect(Color.White.copy(alpha=.2f),size=androidx.compose.ui.geometry.Size(size.width*progress,size.height))
}
.border(1.dp,Color.White.copy(alpha=if(focused)0f else .55f),shape).semantics{contentDescription=label}
.clickable(onClick=onClick).padding(horizontal=16.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) {
Text(label,color=foreground,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.SemiBold)
Icon(Icons.Filled.SkipNext,null,tint=foreground,modifier=Modifier.size(17.dp))
}
}
/** The same track selector is reachable from the speaker and from Playback options. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable internal fun AudioTrackPanel(controller:PlaybackController,dismiss:()->Unit,close:()->Unit) {
val streams=controller.part.streams.filter{it.type==2}
val active=controller.currentStream(controller.activeAudio)
TrackPanel("Audio tracks",streams.map{it.title},streams.indexOfFirst{it.id==active?.id},dismiss){index->
streams.getOrNull(index)?.let{controller.selectServerStream(it,C.TRACK_TYPE_AUDIO)}
close()
}
}
/** A short, non-focusable cue leaves the picture and remote focus undisturbed. */
@Composable private fun QuickSkipFeedback(seconds:Int,pulse:Int,allowed:Boolean,modifier:Modifier) {
// Keep the final label while the cue fades out.
var last by remember{mutableIntStateOf(10)}
if(seconds!=0)last=seconds
AnimatedVisibility(visible=seconds!=0&&allowed,enter=fadeIn(tween(100))+scaleIn(tween(150),initialScale=.88f),exit=fadeOut(tween(180))+scaleOut(tween(180),targetScale=.96f),modifier=modifier) {
Column(Modifier.size(width=56.dp,height=64.dp).background(Brush.radialGradient(listOf(Color.Black.copy(alpha=.4f),Color.Transparent)))
.semantics(mergeDescendants=true){contentDescription=if(last<0)"Back ${-last} seconds"else "Forward $last seconds"},horizontalAlignment=Alignment.CenterHorizontally) {
Spacer(Modifier.height(9.dp))
key(pulse){
val opacity=remember{androidx.compose.animation.core.Animatable(.6f)}
LaunchedEffect(Unit){opacity.animateTo(1f,tween(180))}
Icon(if(last<0)Icons.Filled.FastRewind else Icons.Filled.FastForward,null,tint=Color.White,modifier=Modifier.size(22.dp).graphicsLayer{alpha=opacity.value})
}
Text((if(last>0)"+"else "−")+kotlin.math.abs(last)+" s",color=Color.White,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,style=LocalTextStyle.current.copy(shadow=androidx.compose.ui.graphics.Shadow(Color.Black,Offset(0f,1f),4f)),modifier=Modifier.padding(top=3.dp))
}
}
}
/** Wall-clock time the title finishes at the current speed, in the TV's 12/24-hour format. */ /** Wall-clock time the title finishes at the current speed, in the TV's 12/24-hour format. */
@Composable private fun endsAt(controller:PlaybackController):String { @Composable private fun endsAt(controller:PlaybackController):String {
val format=android.text.format.DateFormat.getTimeFormat(LocalContext.current) val format=android.text.format.DateFormat.getTimeFormat(LocalContext.current)

View file

@ -1,10 +1,13 @@
package tv.kaleido.app package tv.kaleido.app
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import okhttp3.FormBody import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
@ -15,6 +18,10 @@ import java.io.IOException
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
class PlexException(message: String, val status: Int = 0): IOException(message) class PlexException(message: String, val status: Int = 0): IOException(message)
/** Plex's timeline answer after the server ends a playback session. */
data class PlaybackTermination(val code: Int, val reason: String) {
val message get() = listOf("The server stopped this stream.", reason.trim()).filter { it.isNotBlank() }.joinToString("\n\n")
}
class PlexApi(val clientId: String) { class PlexApi(val clientId: String) {
val http = OkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).readTimeout(30,TimeUnit.SECONDS).addNetworkInterceptor { chain -> val http = OkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).readTimeout(30,TimeUnit.SECONDS).addNetworkInterceptor { chain ->
val original=chain.call().request().url;val current=chain.request().url val original=chain.call().request().url;val current=chain.request().url
@ -27,16 +34,24 @@ class PlexApi(val clientId: String) {
put("X-Plex-Client-Identifier",clientId);put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV");put("X-Plex-Device-Name","Kaleido TV") put("X-Plex-Client-Identifier",clientId);put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV");put("X-Plex-Device-Name","Kaleido TV")
if(!token.isNullOrBlank()) put("X-Plex-Token",token) if(!token.isNullOrBlank()) put("X-Plex-Token",token)
} }
suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map<String,String> = emptyMap()): String = withContext(Dispatchers.IO) { suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map<String,String> = emptyMap()): String = coroutineScope {
val req=Request.Builder().url(url).apply { headers(token).forEach { (k,v) -> header(k,v) }; if(method!="GET") method(method,FormBody.Builder().apply { form.forEach { (k,v)->add(k,v) } }.build()) }.build() val req=Request.Builder().url(url).apply { headers(token).forEach { (k,v) -> header(k,v) }; if(method!="GET") method(method,FormBody.Builder().apply { form.forEach { (k,v)->add(k,v) } }.build()) }.build()
http.newCall(req).execute().use { r -> if(!r.isSuccessful) throw PlexException(when(r.code){401,403->"Plex rejected this session. Sign in again or check server access.";404->"This item is no longer available.";else->"Plex could not complete the request (${r.code})."},r.code); r.body?.string() ?: "{}" } val call=http.newCall(req)
// execute() blocks until the server answers; a cancelled caller (a timeout, a replaced load) aborts the call.
val abort=launch(start=CoroutineStart.UNDISPATCHED){try{awaitCancellation()}finally{call.cancel()}}
try {
withContext(Dispatchers.IO) {
call.execute().use { r -> if(!r.isSuccessful) throw PlexException(when(r.code){401,403->"Plex rejected this session. Sign in again or check server access.";404->"This item is no longer available.";else->"Plex could not complete the request (${r.code})."},r.code); r.body?.string() ?: "{}" }
} }
fun url(path: String, params: Map<String,String> = emptyMap()): String { } finally { abort.cancel() }
val s=session ?: throw PlexException("Choose a Plex server first.") }
/** [server] pins a request to one server; by default it follows the current session. */
fun url(path: String, params: Map<String,String> = emptyMap(), server: Session? = session): String {
val s=server ?: throw PlexException("Choose a Plex server first.")
require(!path.startsWith("http")) { "Expected a server-relative Plex path" } require(!path.startsWith("http")) { "Expected a server-relative Plex path" }
return (s.server.trimEnd('/')+"/"+path.trimStart('/')).toHttpUrl().newBuilder().apply { params.forEach { (k,v)->addQueryParameter(k,v) } }.build().toString() return (s.server.trimEnd('/')+"/"+path.trimStart('/')).toHttpUrl().newBuilder().apply { params.forEach { (k,v)->addQueryParameter(k,v) } }.build().toString()
} }
suspend fun container(path: String, params: Map<String,String> = emptyMap()): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params)).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()} suspend fun container(path: String, params: Map<String,String> = emptyMap(), server: Session? = session): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params,server),server?.serverToken).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()}
suspend fun validate(s: Session): Session { suspend fun validate(s: Session): Session {
val j=JSONObject(request(s.server.trimEnd('/')+"/",s.serverToken)).getJSONObject("MediaContainer") val j=JSONObject(request(s.server.trimEnd('/')+"/",s.serverToken)).getJSONObject("MediaContainer")
if(j.optString("machineIdentifier").isBlank()) throw PlexException("This address is not a Plex Media Server.") if(j.optString("machineIdentifier").isBlank()) throw PlexException("This address is not a Plex Media Server.")
@ -55,9 +70,12 @@ class PlexApi(val clientId: String) {
// Try TLS connections first; local HTTP remains available for servers without TLS. // Try TLS connections first; local HTTP remains available for servers without TLS.
var last: Throwable? = null var last: Throwable? = null
for (group in server.connections.partition { it.startsWith("https://") }.toList()) { for (group in server.connections.partition { it.startsWith("https://") }.toList()) {
val results=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } }.awaitAll() // Probe together, but accept in preference order (local first, relay last): the best
results.firstOrNull { it.isSuccess }?.getOrNull()?.let { return@coroutineScope it } // answering address wins without waiting for slower, less preferred probes to time out.
last=results.lastOrNull()?.exceptionOrNull() ?: last val attempts=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } }
try {
for (attempt in attempts) attempt.await().onSuccess { return@coroutineScope it }.onFailure { last=it }
} finally { attempts.forEach { it.cancel() } }
} }
throw PlexException("Cannot reach ${server.name}. Check that the server is online and reachable from this TV.") throw PlexException("Cannot reach ${server.name}. Check that the server is online and reachable from this TV.")
} }
@ -69,19 +87,34 @@ class PlexApi(val clientId: String) {
suspend fun hubs(section: String? = null): List<Hub> = withContext(Dispatchers.Default){container(if(section==null) "/hubs" else "/hubs/sections/$section", mapOf("count" to "18","includeExternalMetadata" to "1")).optJSONArray("Hub").objects().map { Hub(it.optString("hubIdentifier",it.optString("key",it.optString("title"))),it.optString("title"),it.optJSONArray("Metadata").objects().map(Title::parse),it.optString("key"),it.opt("more").let{v->v==true||v==1||v=="1"||v=="true"}) }.filter { it.items.isNotEmpty() && it.items.first().type in listOf("movie","show","episode","season","collection") }} suspend fun hubs(section: String? = null): List<Hub> = withContext(Dispatchers.Default){container(if(section==null) "/hubs" else "/hubs/sections/$section", mapOf("count" to "18","includeExternalMetadata" to "1")).optJSONArray("Hub").objects().map { Hub(it.optString("hubIdentifier",it.optString("key",it.optString("title"))),it.optString("title"),it.optJSONArray("Metadata").objects().map(Title::parse),it.optString("key"),it.opt("more").let{v->v==true||v==1||v=="1"||v=="true"}) }.filter { it.items.isNotEmpty() && it.items.first().type in listOf("movie","show","episode","season","collection") }}
/** A hub's complete list, for "View all". Plex keys may already carry query parameters. */ /** A hub's complete list, for "View all". Plex keys may already carry query parameters. */
suspend fun hubItems(key:String):List<Title> = withContext(Dispatchers.Default){container(key,mapOf("X-Plex-Container-Start" to "0","X-Plex-Container-Size" to "500","includeExternalMetadata" to "1")).optJSONArray("Metadata").objects().map(Title::parse)} suspend fun hubItems(key:String):List<Title> = withContext(Dispatchers.Default){container(key,mapOf("X-Plex-Container-Start" to "0","X-Plex-Container-Size" to "500","includeExternalMetadata" to "1")).optJSONArray("Metadata").objects().map(Title::parse)}
/**
* Continue Watching as a fingerprint. Watching on another device changes it without changing the
* library revision above: new, finished or reordered titles at once, progress in 5% steps (so
* a title playing elsewhere doesn't rebuild Home on every poll).
*/
suspend fun continueWatchingRevision():String = continueWatchingFingerprint(container("/library/onDeck",mapOf("X-Plex-Container-Size" to "30")).optJSONArray("Metadata").objects())
suspend fun onDeck(): List<Title> = container("/library/onDeck",mapOf("X-Plex-Container-Size" to "30")).optJSONArray("Metadata").objects().map(Title::parse) suspend fun onDeck(): List<Title> = container("/library/onDeck",mapOf("X-Plex-Container-Size" to "30")).optJSONArray("Metadata").objects().map(Title::parse)
suspend fun recentSeasons(section:String):List<Title> = withContext(Dispatchers.Default){ suspend fun recentSeasons(section:String):List<Title> = withContext(Dispatchers.Default){
// Fetch beyond the display limit so one large series import doesn't fill the row. // Fetch beyond the display limit so one large series import doesn't fill the row.
val seasons=container("/library/sections/$section/all",mapOf("type" to "3","sort" to "addedAt:desc","X-Plex-Container-Size" to "100")).optJSONArray("Metadata").objects().map(Title::parse) val seasons=container("/library/sections/$section/all",mapOf("type" to "3","sort" to "addedAt:desc","X-Plex-Container-Size" to "100")).optJSONArray("Metadata").objects().map(Title::parse)
groupRecentSeasons(seasons,::details) groupRecentSeasons(seasons,::details)
} }
suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false, size:Int=100): LibraryPage = withContext(Dispatchers.Default){ /** Alternative landscape art, used when two narrow genres only contain the same title. */
suspend fun categoryArtAlternatives(id:String):List<String> = container("/library/metadata/$id/arts")
.optJSONArray("Metadata").objects().filterNot{it.optBoolean("selected")}
.map{it.optString("key")}.filter{it.startsWith('/')||it.startsWith("https://")}.distinct()
suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false, size:Int=100, type:String=""): LibraryPage = withContext(Dispatchers.Default){
val p=mutableMapOf("X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to size.coerceAtLeast(1).toString(),"sort" to sort) val p=mutableMapOf("X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to size.coerceAtLeast(1).toString(),"sort" to sort)
if(genre.isNotBlank())p["genre"]=genre p.putAll(libraryFilterParameters(genre,unwatched,type))
if(unwatched)p["unwatched"]="1"
val d=container("/library/sections/$section/all",p) val d=container("/library/sections/$section/all",p)
LibraryPage(d.optJSONArray("Metadata").objects().map(Title::parse),d.optInt("totalSize",d.optInt("size"))) LibraryPage(d.optJSONArray("Metadata").objects().map(Title::parse),d.optInt("totalSize",d.optInt("size")))
} }
internal suspend fun firstCharacters(section:String,genre:String="",unwatched:Boolean=false,type:String=""):List<PlexCharacterCount> = withContext(Dispatchers.Default){
container("/library/sections/$section/firstCharacter",libraryFilterParameters(genre,unwatched,type)).optJSONArray("Directory").objects().map {
PlexCharacterCount(it.optString("key"),it.optString("title"),it.optInt("size"))
}
}
suspend fun genres(section: String): List<Pair<String,String>> = container("/library/sections/$section/genre").optJSONArray("Directory").objects().map { it.optString("key") to it.optString("title") } suspend fun genres(section: String): List<Pair<String,String>> = container("/library/sections/$section/genre").optJSONArray("Directory").objects().map { it.optString("key") to it.optString("title") }
suspend fun details(id: String): Title = withContext(Dispatchers.Default){container("/library/metadata/$id",mapOf("includeMarkers" to "1","includeChapters" to "1","includeExtras" to "1")).optJSONArray("Metadata").objects().firstOrNull()?.let(Title::parse) ?: throw PlexException("This title is unavailable.")} suspend fun details(id: String): Title = withContext(Dispatchers.Default){container("/library/metadata/$id",mapOf("includeMarkers" to "1","includeChapters" to "1","includeExtras" to "1")).optJSONArray("Metadata").objects().firstOrNull()?.let(Title::parse) ?: throw PlexException("This title is unavailable.")}
suspend fun relatedShows(id:String):List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="show"}.distinctBy{it.id}} suspend fun relatedShows(id:String):List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="show"}.distinctBy{it.id}}
@ -118,9 +151,11 @@ class PlexApi(val clientId: String) {
} }
/** Removes an in-progress title from Continue Watching without changing its watched state. */ /** Removes an in-progress title from Continue Watching without changing its watched state. */
suspend fun removeFromContinueWatching(item:Title){request(url("/actions/removeFromContinueWatching",mapOf("ratingKey" to item.id)),method="PUT")} suspend fun removeFromContinueWatching(item:Title){request(url("/actions/removeFromContinueWatching",mapOf("ratingKey" to item.id)),method="PUT")}
suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) } suspend fun watched(item: Title, watched: Boolean, server: Session? = session) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library"),server) }
suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String) { /** Reports progress; a stream the server stopped (Plex dashboard "Stop", or shutdown) comes back as a termination. */
container("/:/timeline",mapOf("ratingKey" to item.id,"key" to item.key,"state" to state,"time" to position.coerceAtLeast(0).toString(),"duration" to duration.coerceAtLeast(0).toString(),"identifier" to "com.plexapp.plugins.library","session" to sessionId)) suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String, server: Session? = session): PlaybackTermination? {
val c=container("/:/timeline",mapOf("ratingKey" to item.id,"key" to item.key,"state" to state,"time" to position.coerceAtLeast(0).toString(),"duration" to duration.coerceAtLeast(0).toString(),"identifier" to "com.plexapp.plugins.library","session" to sessionId),server)
return if(c.has("terminationCode"))PlaybackTermination(c.optInt("terminationCode",-1),c.optString("terminationText"))else null
} }
suspend fun selectStreams(part: Part, audio: String? = null, subtitle: String? = null) { suspend fun selectStreams(part: Part, audio: String? = null, subtitle: String? = null) {
request(url("/library/parts/${part.id}",buildMap { put("allParts","1");audio?.let {put("audioStreamID",it)};subtitle?.let {put("subtitleStreamID",it)} }),method="PUT") request(url("/library/parts/${part.id}",buildMap { put("allParts","1");audio?.let {put("audioStreamID",it)};subtitle?.let {put("subtitleStreamID",it)} }),method="PUT")
@ -138,7 +173,7 @@ class PlexApi(val clientId: String) {
val hevcAvailable=android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS).codecInfos.any{!it.isEncoder&&it.supportedTypes.any{type->type.equals("video/hevc",true)}} val hevcAvailable=android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS).codecInfos.any{!it.isEncoder&&it.supportedTypes.any{type->type.equals("video/hevc",true)}}
put("X-Plex-Client-Profile-Extra",if(mode==1&&hevcAvailable)"append-transcode-target-codec(type=videoProfile&context=streaming&protocol=hls&videoCodec=hevc)"else "") put("X-Plex-Client-Profile-Extra",if(mode==1&&hevcAvailable)"append-transcode-target-codec(type=videoProfile&context=streaming&protocol=hls&videoCodec=hevc)"else "")
} }
suspend fun stopTranscode(sessionId: String) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId)) } suspend fun stopTranscode(sessionId: String, server: Session? = session) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId),server) }
} }
/** Index of the part containing [time] on the title's combined timeline. */ /** Index of the part containing [time] on the title's combined timeline. */
@ -148,3 +183,8 @@ internal fun partFor(parts:List<Part>,time:Long):Int {
return 0 return 0
} }
internal fun partStart(parts:List<Part>,index:Int):Long = parts.take(index.coerceAtLeast(0)).sumOf{it.duration.coerceAtLeast(0)} internal fun partStart(parts:List<Part>,index:Int):Long = parts.take(index.coerceAtLeast(0)).sumOf{it.duration.coerceAtLeast(0)}
internal fun continueWatchingFingerprint(items:List<JSONObject>):String = items.joinToString("|"){j->
val duration=j.optLong("duration");val offset=j.optLong("viewOffset")
val step=if(duration>0)(offset*20/duration).toString()else (offset/120_000).toString()
"${j.optString("ratingKey")}:${j.optString("viewCount")}:$step"
}

View file

@ -1,14 +1,19 @@
package tv.kaleido.app package tv.kaleido.app
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
/** Preserve newest-first order. A multi-season addition opens the real show's season list. */ /**
* Preserve newest-first order. A multi-season addition opens the real show's season list; if that
* show can't be loaded, its newest season stands in rather than discarding the whole row.
*/
internal suspend fun groupRecentSeasons(seasons:List<Title>,loadShow:suspend (String)->Title):List<Title> = coroutineScope { internal suspend fun groupRecentSeasons(seasons:List<Title>,loadShow:suspend (String)->Title):List<Title> = coroutineScope {
seasons.distinctBy{it.id}.groupBy{it.parentId.ifBlank{"season:${it.id}"}}.values.take(18).map { group->async { seasons.distinctBy{it.id}.groupBy{it.parentId.ifBlank{"season:${it.id}"}}.values.take(18).map { group->async {
val season=group.first() val season=group.first()
if(group.size>1&&season.parentId.isNotBlank())loadShow(season.parentId) val single=season.copy(title=listOf(season.parentTitle,season.title).filter{it.isNotBlank()}.joinToString(" · "))
else season.copy(title=listOf(season.parentTitle,season.title).filter{it.isNotBlank()}.joinToString(" · ")) if(group.size>1&&season.parentId.isNotBlank())try{loadShow(season.parentId)}catch(e:CancellationException){throw e}catch(_:Exception){single}
else single
}}.awaitAll() }}.awaitAll()
} }

View file

@ -26,6 +26,8 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
@ -34,6 +36,13 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage import coil.compose.AsyncImage
import coil.imageLoader
import android.graphics.drawable.BitmapDrawable
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import coil.request.ImageRequest import coil.request.ImageRequest
import coil.size.Precision import coil.size.Precision
import androidx.compose.foundation.gestures.BringIntoViewSpec import androidx.compose.foundation.gestures.BringIntoViewSpec
@ -49,19 +58,42 @@ import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import java.io.File import java.io.File
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true,contentScale:ContentScale=ContentScale.Crop) { @Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true,contentScale:ContentScale=ContentScale.Crop,colorFilter:androidx.compose.ui.graphics.ColorFilter?=null) {
val context=LocalContext.current val context=LocalContext.current
// The server already scales to width × height. Stating that size lets Coil resolve cache // The server already scales to width × height. Stating that size lets Coil resolve cache
// hits while composing, instead of each painter waiting for layout to measure it. // hits while composing, instead of each painter waiting for layout to measure it.
val model=remember(path,api.session?.server,width,height,animate){api.image(path,width,height)?.let {u -> ImageRequest.Builder(context).data(u).apply {api.headers().forEach{(k,v)->addHeader(k,v)}}.size(width,height).precision(Precision.INEXACT).crossfade(if(animate)180 else 0).build()}} val model=remember(path,api.session?.server,width,height,animate){api.image(path,width,height)?.let {u -> ImageRequest.Builder(context).data(u).apply {api.headers().forEach{(k,v)->addHeader(k,v)}}.size(width,height).precision(Precision.INEXACT).crossfade(if(animate)180 else 0).build()}}
AsyncImage(model=model,contentDescription=null,contentScale=contentScale,modifier=modifier.background(Panel)) AsyncImage(model=model,contentDescription=null,contentScale=contentScale,colorFilter=colorFilter,modifier=modifier.background(Panel))
}
/**
* A browse card's artwork, without Coil's painter machinery (a painter, a snapshot flow and a
* request run per card cost about 2.5 ms of each card's composition on the onn). A memory-cache
* hit is drawn straight away; otherwise the image loads, then draws without recomposing. Like
* [Artwork] with ContentScale.Crop and no crossfade.
*/
@Composable fun CardArtwork(api:PlexApi,path:String,modifier:Modifier,width:Int,height:Int) {
val context=LocalContext.current
val loader=context.imageLoader
val request=remember(path,api.session?.server,width,height){api.image(path,width,height)?.let{u->ImageRequest.Builder(context).data(u).memoryCacheKey("card:$u")
.apply{api.headers().forEach{(k,v)->addHeader(k,v)}}.size(width,height).precision(Precision.INEXACT).build()}}
val image=remember(request){mutableStateOf(request?.memoryCacheKey?.let{loader.memoryCache?.get(it)?.bitmap?.asImageBitmap()})}
if(image.value==null&&request!=null)LaunchedEffect(request){(loader.execute(request).drawable as? BitmapDrawable)?.bitmap?.let{image.value=it.asImageBitmap()}}
Box(modifier.background(Panel).drawBehind{
val bitmap=image.value ?: return@drawBehind
// Centre crop: scale to cover the card, trim the overflow.
val scale=maxOf(size.width/bitmap.width,size.height/bitmap.height)
val srcWidth=(size.width/scale).toInt().coerceIn(1,bitmap.width);val srcHeight=(size.height/scale).toInt().coerceIn(1,bitmap.height)
drawImage(bitmap,IntOffset((bitmap.width-srcWidth)/2,(bitmap.height-srcHeight)/2),IntSize(srcWidth,srcHeight),dstSize=IntSize(size.width.toInt(),size.height.toInt()),filterQuality=FilterQuality.Low)
})
} }
@Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) { @Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) {
KaleidoTheme { KaleidoTheme {
ThemeMusic(vm)
val stateHolder=rememberSaveableStateHolder() val stateHolder=rememberSaveableStateHolder()
val discoveryFocus=remember{DiscoveryNavigation()} val discoveryFocus=remember{DiscoveryNavigation()}
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles) val immersive=isDiscovery(vm)
val screenKey=vm.page.kind+":"+vm.page.id+if(vm.page.kind in listOf("movies","tv")) ":${vm.allTitles}"else "" val discoveries=remember{LinkedHashSet<String>()}
val screenKey=vm.page.kind+":"+vm.page.id+if(vm.page.kind in listOf("movies","tv")) ":${vm.allTitles}:${vm.categories}:${vm.genre}"else ""
val entrance=remember{Animatable(1f)} val entrance=remember{Animatable(1f)}
val density=LocalDensity.current val density=LocalDensity.current
var previousDestination by remember{mutableStateOf(vm.page.kind)} var previousDestination by remember{mutableStateOf(vm.page.kind)}
@ -86,11 +118,12 @@ import java.io.File
splashExit.animateTo(1f,tween(StartupExitMillis,easing=LinearEasing));startup=false splashExit.animateTo(1f,tween(StartupExitMillis,easing=LinearEasing));startup=false
} }
} }
BackHandler(enabled=vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){ // The server picker covers every page, so Back closes it before navigating underneath.
if(vm.linkingAccount)vm.cancelAccountLink()else if(vm.playing==null&&vm.pages.size==1&&vm.page.kind in listOf("movies","tv")&&vm.allTitles)vm.setAll(false)else vm.back() BackHandler(enabled=vm.servers.isNotEmpty()||vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){
if(vm.servers.isNotEmpty())vm.dismissServerPicker()else if(vm.linkingAccount)vm.cancelAccountLink()else vm.back()
} }
NavigationSounds(vm.navigationSounds&&!startup) { NavigationSounds(vm.navigationSounds&&!startup) {
Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{startup}) { Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{vm.lastInteraction=android.os.SystemClock.uptimeMillis();startup}) {
// The app settles into place behind the splash as its aperture opens. // The app settles into place behind the splash as its aperture opens.
Box(Modifier.fillMaxSize().then(if(startup)Modifier.graphicsLayer{val s=startupArrivalScale(splashExit.value);scaleX=s;scaleY=s}else Modifier)) { Box(Modifier.fillMaxSize().then(if(startup)Modifier.graphicsLayer{val s=startupArrivalScale(splashExit.value);scaleX=s;scaleY=s}else Modifier)) {
if(vm.servers.isNotEmpty()) ServerPicker(vm) else if(vm.session==null||vm.linkingAccount) SignIn(vm) else { if(vm.servers.isNotEmpty()) ServerPicker(vm) else if(vm.session==null||vm.linkingAccount) SignIn(vm) else {
@ -101,9 +134,24 @@ import java.io.File
translationX=with(density){28.dp.toPx()}*direction*(1f-entrance.value) translationX=with(density){28.dp.toPx()}*direction*(1f-entrance.value)
}) { }) {
if(!immersive&&vm.page.kind !in listOf("details","group","actor","hub")) TopBar(vm) if(!immersive&&vm.page.kind !in listOf("details","group","actor","hub")) TopBar(vm)
stateHolder.SaveableStateProvider(screenKey) { // Home, Movies and TV stay composed once shown; only the one on screen is measured,
// placed and drawn. Unplaced, the others take no focus and draw nothing, and
// showing one again costs no composition. Other pages compose as before.
if(immersive)discoveries+=vm.page.kind
val shown=if(immersive)discoveries.indexOf(vm.page.kind)else -1
Layout({
discoveries.forEach{destination->key(destination){
// Unplaced screens are still walked whenever accessibility rebuilds its tree
// (every 100 ms while anything moves, with the onn's services); clearing
// their semantics stops that walk at the root.
Box(if(isDiscovery(vm)&&vm.page.kind==destination)Modifier else Modifier.clearAndSetSemantics{}) {
stateHolder.SaveableStateProvider("discovery:$destination") {
DiscoveryScreen(vm,destination,discoveryFocus){isDiscovery(vm)&&vm.page.kind==destination}
}
}
}}
if(!immersive)Box{stateHolder.SaveableStateProvider(screenKey) {
when(vm.page.kind){ when(vm.page.kind){
"home"->HomeScreen(vm,discoveryFocus)
"movies","tv"->LibraryScreen(vm,discoveryFocus) "movies","tv"->LibraryScreen(vm,discoveryFocus)
"details","group"->DetailsScreen(vm) "details","group"->DetailsScreen(vm)
"actor"->ActorScreen(vm) "actor"->ActorScreen(vm)
@ -111,6 +159,10 @@ import java.io.File
"search"->SearchScreen(vm) "search"->SearchScreen(vm)
"settings"->CohesiveSettingsScreen(vm,install) "settings"->CohesiveSettingsScreen(vm,install)
} }
}}
},Modifier.fillMaxSize()){measurables,constraints->
val page=(if(shown>=0)measurables.getOrNull(shown)else measurables.lastOrNull())?.measure(constraints)
layout(constraints.maxWidth,constraints.maxHeight){page?.place(0,0)}
} }
} }
if(immersive)TopBar(vm,discoveryFocus) if(immersive)TopBar(vm,discoveryFocus)
@ -119,12 +171,14 @@ import java.io.File
if(vm.busy) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopCenter),color=Accent,trackColor=Color.Transparent) if(vm.busy) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopCenter),color=Accent,trackColor=Color.Transparent)
if(vm.error!=null) ErrorDialog(vm.error!!,{vm.dismissError()},{vm.retry()}) if(vm.error!=null) ErrorDialog(vm.error!!,{vm.dismissError()},{vm.retry()})
vm.contextItem?.let{item->if(vm.playing==null)TitleActions(vm,item)} vm.contextItem?.let{item->if(vm.playing==null)TitleActions(vm,item)}
vm.playing?.let {item-> androidx.compose.runtime.key(item.id) {PlaybackScreen(vm,item)} } vm.playing?.let {item-> androidx.compose.runtime.key(item.id,vm.playbackInstance) {PlaybackScreen(vm,item)} }
if(startup)StartupSplash({splashExit.value},{!vm.busy}){brandReady=true} if(startup)StartupSplash({splashExit.value},{!vm.busy}){brandReady=true}
} }
} }
} }
} }
/** Home, or Movies/TV showing Discover rather than the A–Z library: the full-screen browse destinations. */
internal fun isDiscovery(vm:KaleidoViewModel)=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Title: Z–A","addedAt:desc" to "Recently added","year:desc" to "Newest release","year:asc" to "Oldest release","audienceRating:desc" to "Audience rating","duration:asc" to "Shortest first") val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Title: Z–A","addedAt:desc" to "Recently added","year:desc" to "Newest release","year:asc" to "Oldest release","audienceRating:desc" to "Audience rating","duration:asc" to "Shortest first")
@Composable fun SignIn(vm: KaleidoViewModel) { @Composable fun SignIn(vm: KaleidoViewModel) {
var manual by rememberSaveable{mutableStateOf(false)} var manual by rememberSaveable{mutableStateOf(false)}
@ -144,7 +198,7 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit
Spacer(Modifier.height(14.dp));OutlinedTextField(address,{address=it},label={Text("Server URL")},singleLine=true,modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(10.dp));OutlinedTextField(token,{token=it},label={Text("Access token")},singleLine=true,visualTransformation=PasswordVisualTransformation(),modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(18.dp));TvButton("Connect",primary=true,onClick={vm.manualConnect(address,token)});Spacer(Modifier.height(10.dp));TvButton("Use Plex account",onClick=back) Spacer(Modifier.height(14.dp));OutlinedTextField(address,{address=it},label={Text("Server URL")},singleLine=true,modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(10.dp));OutlinedTextField(token,{token=it},label={Text("Access token")},singleLine=true,visualTransformation=PasswordVisualTransformation(),modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(18.dp));TvButton("Connect",primary=true,onClick={vm.manualConnect(address,token)});Spacer(Modifier.height(10.dp));TvButton("Use Plex account",onClick=back)
} }
@Composable fun ServerPicker(vm: KaleidoViewModel) { @Composable fun ServerPicker(vm: KaleidoViewModel) {
Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})}} Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})};if(vm.session!=null){Spacer(Modifier.height(6.dp));TvButton("Cancel",onClick={vm.dismissServerPicker()})}}
} }
@Composable fun EmptyState(title: String,message: String){Column(Modifier.padding(52.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){Text(title,color=Color.White,fontSize=26.sp,fontWeight=FontWeight.Bold);Text(message,color=Muted,fontSize=14.sp)}} @Composable fun EmptyState(title: String,message: String){Column(Modifier.padding(52.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){Text(title,color=Color.White,fontSize=26.sp,fontWeight=FontWeight.Bold);Text(message,color=Muted,fontSize=14.sp)}}
@Composable fun ErrorDialog(message: String,dismiss: ()->Unit,retry: ()->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(23.dp)){Text("Something needs attention",color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold);Text(message,color=Muted,fontSize=12.sp,lineHeight=19.sp,modifier=Modifier.padding(vertical=17.dp));Row(horizontalArrangement=Arrangement.spacedBy(9.dp)){TvButton("Try again",primary=true,initialFocus=true,onClick=retry);TvButton("Dismiss",onClick=dismiss)}}}} @Composable fun ErrorDialog(message: String,dismiss: ()->Unit,retry: ()->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(23.dp)){Text("Something needs attention",color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold);Text(message,color=Muted,fontSize=12.sp,lineHeight=19.sp,modifier=Modifier.padding(vertical=17.dp));Row(horizontalArrangement=Arrangement.spacedBy(9.dp)){TvButton("Try again",primary=true,initialFocus=true,onClick=retry);TvButton("Dismiss",onClick=dismiss)}}}}

View file

@ -0,0 +1,82 @@
package tv.kaleido.app
import java.text.Normalizer
import java.util.Locale
private val searchGroupSpecs = listOf(
"movie" to "Movies",
"show" to "TV shows",
"season" to "Seasons",
"collection" to "Collections",
"episode" to "Episodes"
)
private val combiningMarks = Regex("\\p{M}+")
private val nonLettersOrDigits = Regex("[^\\p{L}\\p{N}]+")
private val whitespace = Regex("\\s+")
private data class RankedSearchResult<T>(val value: T, val index: Int, val score: Int)
private data class RankedSearchGroup<T>(
val label: String,
val results: List<T>,
val bestScore: Int,
val firstBestResult: Int
)
internal fun <T> rankSearchGroups(
titles: List<T>,
query: String,
typeOf: (T) -> String,
searchableTitles: (T) -> List<String>
): List<Pair<String, List<T>>> {
val normalizedQuery = normalizeSearchText(query)
if (normalizedQuery.isBlank()) {
return searchGroupSpecs
.map { (type, label) -> label to titles.filter { typeOf(it) == type } }
.filter { it.second.isNotEmpty() }
}
val ranked = titles.mapIndexed { index, title ->
RankedSearchResult(title, index, titleRelevance(normalizedQuery, searchableTitles(title)))
}
return searchGroupSpecs.mapNotNull { (type, label) ->
val matching = ranked.filter { typeOf(it.value) == type }
if (matching.isEmpty()) return@mapNotNull null
val bestScore = matching.maxOf { it.score }
val ordered = matching.sortedWith(compareByDescending<RankedSearchResult<T>> { it.score }.thenBy { it.index })
RankedSearchGroup(
label = label,
results = ordered.map { it.value },
bestScore = bestScore,
firstBestResult = matching.first { it.score == bestScore }.index
)
}
.sortedWith(compareByDescending<RankedSearchGroup<T>> { it.bestScore }.thenBy { it.firstBestResult })
.map { it.label to it.results }
}
private fun titleRelevance(query: String, titles: List<String>): Int {
if (query.isBlank()) return 0
val queryTokens = query.split(' ')
return titles.mapIndexedNotNull { index, title ->
val candidate = normalizeSearchText(title)
val matchScore = when {
candidate.isBlank() -> 0
candidate == query -> 4
candidate.startsWith(query) -> 3
candidate.split(' ').windowed(queryTokens.size).any { it == queryTokens } -> 2
candidate.contains(query) -> 1
else -> 0
}
if (matchScore == 0) null else matchScore * 10 - index
}.maxOrNull() ?: 0
}
private fun normalizeSearchText(value: String): String = Normalizer.normalize(value, Normalizer.Form.NFKD)
.replace(combiningMarks, "")
.lowercase(Locale.ROOT)
.replace(nonLettersOrDigits, " ")
.replace(whitespace, " ")
.trim()

View file

@ -44,13 +44,19 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
var watchedDialog by remember { mutableStateOf(false) } var watchedDialog by remember { mutableStateOf(false) }
var remoteDialog by remember { mutableStateOf(false) } var remoteDialog by remember { mutableStateOf(false) }
var autoplayDialog by remember { mutableStateOf(false) } var autoplayDialog by remember { mutableStateOf(false) }
var introDialog by remember { mutableStateOf(false) }
var creditsDialog by remember { mutableStateOf(false) }
var subtitleSizeDialog by remember { mutableStateOf(false) } var subtitleSizeDialog by remember { mutableStateOf(false) }
var subtitleStyleDialog by remember { mutableStateOf(false) } var subtitleStyleDialog by remember { mutableStateOf(false) }
var themeVolumeDialog by remember { mutableStateOf(false) }
val remoteFocus = remember { FocusRequester() } val remoteFocus = remember { FocusRequester() }
val autoplayFocus = remember { FocusRequester() } val autoplayFocus = remember { FocusRequester() }
val introFocus = remember { FocusRequester() } val introFocus = remember { FocusRequester() }
val creditsFocus = remember { FocusRequester() } val creditsFocus = remember { FocusRequester() }
val subtitleStyleFocus = remember { FocusRequester() } val subtitleStyleFocus = remember { FocusRequester() }
val themeMusicFocus = remember { FocusRequester() }
val colourWashFocus = remember { FocusRequester() }
val themeVolumeFocus = remember { FocusRequester() }
val categoryFocus = remember { List(categories.size) { FocusRequester() } } val categoryFocus = remember { List(categories.size) { FocusRequester() } }
val entryFocus = remember { List(categories.size) { FocusRequester() } } val entryFocus = remember { List(categories.size) { FocusRequester() } }
@ -59,6 +65,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
val signOutActionFocus = remember { FocusRequester() } val signOutActionFocus = remember { FocusRequester() }
val updateFocus = remember { FocusRequester() } val updateFocus = remember { FocusRequester() }
val updateDownloadFocus = remember { FocusRequester() } val updateDownloadFocus = remember { FocusRequester() }
var dialogRestoreFocus by remember { mutableStateOf<FocusRequester?>(null) }
var settingsFocused by remember { mutableStateOf(false) } var settingsFocused by remember { mutableStateOf(false) }
val paused = remember { booleanArrayOf(false) } val paused = remember { booleanArrayOf(false) }
@ -67,6 +74,16 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
delay(140) delay(140)
runCatching { entryFocus[selectedCategory].requestFocus() } runCatching { entryFocus[selectedCategory].requestFocus() }
} }
val anyDialogOpen = confirmSignOut || qualityDialog || watchedDialog || remoteDialog || autoplayDialog || introDialog || creditsDialog ||
subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog
LaunchedEffect(anyDialogOpen, dialogRestoreFocus) {
if (!anyDialogOpen) {
dialogRestoreFocus?.let { requester ->
runCatching { requester.requestFocus() }
dialogRestoreFocus = null
}
}
}
LifecycleResumeEffect(Unit) { LifecycleResumeEffect(Unit) {
if (paused[0]) { if (paused[0]) {
vm.installerReturned() vm.installerReturned()
@ -99,7 +116,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
modifier = Modifier.padding(top = 3.dp) modifier = Modifier.padding(top = 3.dp)
) )
} }
Eyebrow(categories[selectedCategory])
} }
Spacer(Modifier.height(25.dp)) Spacer(Modifier.height(25.dp))
@ -135,7 +151,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
) { ) {
when (selectedCategory) { when (selectedCategory) {
0 -> { 0 -> {
SettingsSectionTitle("Plex account", "Manage the server and account used by Kaleido.") SettingsSectionDescription("Manage the server and account used by Kaleido.")
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) { Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text( Text(
vm.session?.serverName.orEmpty().ifBlank { "Plex connection" }, vm.session?.serverName.orEmpty().ifBlank { "Plex connection" },
@ -187,20 +203,20 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
"Sign out", "Sign out",
requester = signOutActionFocus, requester = signOutActionFocus,
leftTarget = categoryFocus[0], leftTarget = categoryFocus[0],
onClick = { confirmSignOut = true } onClick = { dialogRestoreFocus = signOutActionFocus; confirmSignOut = true }
) )
} }
} }
1 -> { 1 -> {
SettingsSectionTitle("Playback", "Choose how Plex delivers video and when a title counts as watched.") SettingsSectionDescription("Choose how Plex delivers video and when a title counts as watched.")
SettingsValueRow( SettingsValueRow(
title = "Playback quality", title = "Playback quality",
description = "On your home network. Original plays the source; a resolution asks Plex to convert.", description = "On your home network. Original plays the source; a resolution asks Plex to convert.",
value = vm.streamQuality.label, value = vm.streamQuality.label,
requester = entryFocus[1], requester = entryFocus[1],
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { qualityDialog = true } onClick = { dialogRestoreFocus = entryFocus[1]; qualityDialog = true }
) )
SettingsValueRow( SettingsValueRow(
title = "Remote quality", title = "Remote quality",
@ -208,7 +224,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
value = vm.remoteQuality.label, value = vm.remoteQuality.label,
requester = remoteFocus, requester = remoteFocus,
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { remoteDialog = true } onClick = { dialogRestoreFocus = remoteFocus; remoteDialog = true }
) )
SettingsValueRow( SettingsValueRow(
title = "Watched status", title = "Watched status",
@ -216,31 +232,31 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
value = "${vm.watchedPercent}%", value = "${vm.watchedPercent}%",
requester = watchedFocus, requester = watchedFocus,
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { watchedDialog = true } onClick = { dialogRestoreFocus = watchedFocus; watchedDialog = true }
) )
SettingsValueRow( SettingsValueRow(
title = "Autoplay next episode", title = "Autoplay next episode",
description = "Count down to the next episode when one ends.", description = "Up Next counts down to the next episode. Any remote press stops it.",
value = autoplayLabel(vm.autoplaySeconds), value = autoplayLabel(vm.autoplaySeconds),
requester = autoplayFocus, requester = autoplayFocus,
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { autoplayDialog = true } onClick = { dialogRestoreFocus = autoplayFocus; autoplayDialog = true }
) )
SettingsValueRow( SettingsValueRow(
title = "Skip intros", title = "Skip intros",
description = "Uses intro markers from your Plex server.", description = "Uses intro markers from your Plex server. Any remote press cancels an automatic skip.",
value = if (vm.autoSkipIntro) "Automatically" else "Show button", value = autoSkipLabel(vm.autoSkipIntroSeconds),
requester = introFocus, requester = introFocus,
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { vm.chooseAutoSkipIntro(!vm.autoSkipIntro) } onClick = { dialogRestoreFocus = introFocus; introDialog = true }
) )
SettingsValueRow( SettingsValueRow(
title = "Skip credits", title = "Skip credits",
description = "Episodes go straight to Up Next; movies skip past the credits.", description = "Automatic: episodes open Up Next as the credits start; movies skip past them after the delay.",
value = if (vm.autoSkipCredits) "Automatically" else "Show button", value = autoSkipLabel(vm.autoSkipCreditsSeconds),
requester = creditsFocus, requester = creditsFocus,
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { vm.chooseAutoSkipCredits(!vm.autoSkipCredits) } onClick = { dialogRestoreFocus = creditsFocus; creditsDialog = true }
) )
Text( Text(
"Completed titles keep their Plex watched status.", "Completed titles keep their Plex watched status.",
@ -252,14 +268,14 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
} }
2 -> { 2 -> {
SettingsSectionTitle("Subtitles", "Choose how text subtitles look. Image subtitles keep their own style.") SettingsSectionDescription("Choose how text subtitles look. Image subtitles keep their own style.")
SettingsValueRow( SettingsValueRow(
title = "Size", title = "Size",
description = "Also sizes subtitles Plex adds to converted video.", description = "Also sizes subtitles Plex adds to converted video.",
value = vm.subtitleSize.label, value = vm.subtitleSize.label,
requester = entryFocus[2], requester = entryFocus[2],
leftTarget = categoryFocus[2], leftTarget = categoryFocus[2],
onClick = { subtitleSizeDialog = true } onClick = { dialogRestoreFocus = entryFocus[2]; subtitleSizeDialog = true }
) )
SettingsValueRow( SettingsValueRow(
title = "Style", title = "Style",
@ -267,13 +283,13 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
value = vm.subtitleStyle.label, value = vm.subtitleStyle.label,
requester = subtitleStyleFocus, requester = subtitleStyleFocus,
leftTarget = categoryFocus[2], leftTarget = categoryFocus[2],
onClick = { subtitleStyleDialog = true } onClick = { dialogRestoreFocus = subtitleStyleFocus; subtitleStyleDialog = true }
) )
SubtitlePreview(vm.subtitleSize, vm.subtitleStyle) SubtitlePreview(vm.subtitleSize, vm.subtitleStyle)
} }
3 -> { 3 -> {
SettingsSectionTitle("Interface", "Control the small cues Kaleido plays as you browse.") SettingsSectionDescription("Choose how Kaleido looks and sounds while you browse.")
SettingsValueRow( SettingsValueRow(
title = "Navigation sounds", title = "Navigation sounds",
description = "Play the TV's system tap when focus moves. Follows the TV sound-effects setting.", description = "Play the TV's system tap when focus moves. Follows the TV sound-effects setting.",
@ -282,10 +298,34 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
leftTarget = categoryFocus[3], leftTarget = categoryFocus[3],
onClick = { vm.chooseNavigationSounds(!vm.navigationSounds) } onClick = { vm.chooseNavigationSounds(!vm.navigationSounds) }
) )
SettingsValueRow(
title = "Theme music",
description = "Play Plex theme tracks on movie, series, season and episode pages when available.",
value = if (vm.themeMusic) "On" else "Off",
requester = themeMusicFocus,
leftTarget = categoryFocus[3],
onClick = { vm.chooseThemeMusic(!vm.themeMusic) }
)
SettingsValueRow(
title = "Theme music volume",
description = "Set the browsing music volume.",
value = "${vm.themeVolume}%",
requester = themeVolumeFocus,
leftTarget = categoryFocus[3],
onClick = { dialogRestoreFocus = themeVolumeFocus; themeVolumeDialog = true }
)
SettingsValueRow(
title = "Artwork colour wash",
description = "Tint the page behind Home, Movies and TV previews with the focused artwork's colour.",
value = if (vm.colourWash) "On" else "Off",
requester = colourWashFocus,
leftTarget = categoryFocus[3],
onClick = { vm.chooseColourWash(!vm.colourWash) }
)
} }
else -> { else -> {
SettingsSectionTitle("Software updates", "Install the latest updates published for Kaleido.") SettingsSectionDescription("Install the latest updates published for Kaleido.")
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text("Kaleido ${BuildConfig.VERSION_NAME}", color = Accent, fontSize = 18.sp, lineHeight = 23.sp, fontWeight = FontWeight.SemiBold) Text("Kaleido ${BuildConfig.VERSION_NAME}", color = Accent, fontSize = 18.sp, lineHeight = 23.sp, fontWeight = FontWeight.SemiBold)
Text(vm.updateStatus, color = Muted, fontSize = 11.sp, lineHeight = 16.sp) Text(vm.updateStatus, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
@ -367,6 +407,18 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
remoteDialog = false remoteDialog = false
} }
} }
if (introDialog) {
ChoiceDialog("Skip intros", AutoSkipChoices.map(::autoSkipLabel), AutoSkipChoices.indexOf(vm.autoSkipIntroSeconds).coerceAtLeast(0), { introDialog = false }) {
vm.chooseAutoSkipIntro(AutoSkipChoices[it])
introDialog = false
}
}
if (creditsDialog) {
ChoiceDialog("Skip credits", AutoSkipChoices.map(::autoSkipLabel), AutoSkipChoices.indexOf(vm.autoSkipCreditsSeconds).coerceAtLeast(0), { creditsDialog = false }) {
vm.chooseAutoSkipCredits(AutoSkipChoices[it])
creditsDialog = false
}
}
if (autoplayDialog) { if (autoplayDialog) {
val choices = listOf(0, 5, 10, 15, 30) val choices = listOf(0, 5, 10, 15, 30)
ChoiceDialog("Autoplay next episode", choices.map(::autoplayLabel), choices.indexOf(vm.autoplaySeconds), { autoplayDialog = false }) { ChoiceDialog("Autoplay next episode", choices.map(::autoplayLabel), choices.indexOf(vm.autoplaySeconds), { autoplayDialog = false }) {
@ -392,9 +444,19 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
qualityDialog = false qualityDialog = false
} }
} }
if (themeVolumeDialog) {
val choices = (10..100 step 10).toList()
ChoiceDialog("Theme music volume", choices.map { "$it%" }, choices.indexOf(vm.themeVolume).coerceAtLeast(0), { themeVolumeDialog = false }) {
vm.chooseThemeVolume(choices[it])
themeVolumeDialog = false
}
}
} }
private fun autoplayLabel(seconds: Int) = if (seconds <= 0) "Off" else "After $seconds seconds" private fun autoplayLabel(seconds: Int) = if (seconds <= 0) "Off" else "After $seconds seconds"
/** 0 only shows the Skip button; otherwise the button counts down this long before skipping. */
private val AutoSkipChoices = listOf(0, 3, 5, 10, 15)
private fun autoSkipLabel(seconds: Int) = if (seconds <= 0) "Show button" else "Automatically after $seconds s"
/** A sample line in the chosen subtitle look, rendered by the player's own subtitle view. */ /** A sample line in the chosen subtitle look, rendered by the player's own subtitle view. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@ -426,11 +488,8 @@ private object SettingsScroll:BringIntoViewSpec {
} }
@Composable @Composable
private fun SettingsSectionTitle(title: String, subtitle: String) { private fun SettingsSectionDescription(description: String) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(description, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
Text(title, color = Accent, fontSize = 21.sp, lineHeight = 27.sp, fontWeight = FontWeight.SemiBold, letterSpacing = (-.3).sp)
Text(subtitle, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
}
} }
@Composable @Composable

View file

@ -0,0 +1,62 @@
package tv.kaleido.app
import kotlin.random.Random
/** A repeating shuffle bag that never repeats the previous episode at a cycle boundary. */
internal class ShuffleEpisodes<T>(
episodes: List<T>,
private val id: (T) -> String,
private val random: Random = Random.Default,
) {
private val episodes = episodes.distinctBy(id)
private var order = this.episodes.shuffled(random)
private var currentIndex = 0
private var nextCycle: List<T>? = null
val first: T? get() = order.firstOrNull()
/** Returns the item after [currentId], preparing the next bag when needed. */
fun following(currentId: String): T? {
if (order.getOrNull(currentIndex)?.let(id) != currentId) return null
if (currentIndex < order.lastIndex) return order[currentIndex + 1]
return nextCycle?.firstOrNull() ?: makeNextCycle(order[currentIndex]).also { nextCycle = it }.firstOrNull()
}
/** The item played before [currentId] in this bag, or null at the bag's start. */
fun preceding(currentId: String): T? {
if (order.getOrNull(currentIndex)?.let(id) != currentId) return null
return order.getOrNull(currentIndex - 1)
}
/** Steps back only when [previousId] is the item returned by [preceding]. */
fun retreat(currentId: String, previousId: String): Boolean {
if (preceding(currentId)?.let(id) != previousId) return false
currentIndex--
return true
}
/** Advances only when [nextId] is the next item returned by [following]. */
fun advance(currentId: String, nextId: String): Boolean {
if (following(currentId)?.let(id) != nextId) return false
if (currentIndex == order.lastIndex) {
order = nextCycle ?: makeNextCycle(order[currentIndex])
nextCycle = null
currentIndex = 0
} else {
currentIndex++
}
return order.getOrNull(currentIndex)?.let(id) == nextId
}
private fun makeNextCycle(previous: T): List<T> {
val shuffled = episodes.shuffled(random)
if (shuffled.size < 2 || id(shuffled.first()) != id(previous)) return shuffled
val firstDifferent = shuffled.indexOfFirst { id(it) != id(previous) }
if (firstDifferent < 1) return shuffled
return shuffled.toMutableList().also { bag ->
val first = bag[0]
bag[0] = bag[firstDifferent]
bag[firstDifferent] = first
}
}
}

View file

@ -16,30 +16,24 @@ import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
import kotlin.math.PI import kotlin.math.PI
import kotlin.math.cos import kotlin.math.cos
import kotlin.math.exp import kotlin.math.exp
import kotlin.math.ln import kotlin.math.ln
import kotlin.math.max
import kotlin.math.sin import kotlin.math.sin
private class ApertureFacet(val points:List<Offset>,val color:Color,val normal:Offset) private class KaleidoFacet(val points:List<Offset>,val centroid:Offset,val color:Color,val angle:Float)
// Exact geometry and colors from brand_mark.xml, centered on its 64-unit viewport. // Exact geometry and colors from brand_mark.xml, centered on its 64-unit viewport.
// Each facet carries the outward normal of its hexagon edge for the iris motion. // Each facet carries its centroid and the angle of its hexagon edge's outward normal.
private val apertureFacets=listOf( private val kaleidoFacets=listOf(
floatArrayOf(33f,4f,55.5f,17f,42.5f,24.5f,33f,19f) to 0xFFC3E8D3, floatArrayOf(33f,4f,55.5f,17f,42.5f,24.5f,33f,19f) to 0xFFC3E8D3,
floatArrayOf(56.5f,19f,56.5f,45f,43.5f,37.5f,43.5f,26.5f) to 0xFF71B9B0, floatArrayOf(56.5f,19f,56.5f,45f,43.5f,37.5f,43.5f,26.5f) to 0xFF71B9B0,
floatArrayOf(55.5f,47f,33f,60f,33f,45f,42.5f,39.5f) to 0xFF3D7C7B, floatArrayOf(55.5f,47f,33f,60f,33f,45f,42.5f,39.5f) to 0xFF3D7C7B,
@ -47,52 +41,65 @@ private val apertureFacets=listOf(
floatArrayOf(7.5f,45f,7.5f,19f,20.5f,26.5f,20.5f,37.5f) to 0xFFE9D8AE, floatArrayOf(7.5f,45f,7.5f,19f,20.5f,26.5f,20.5f,37.5f) to 0xFFE9D8AE,
floatArrayOf(8.5f,17f,31f,4f,31f,19f,21.5f,24.5f) to 0xFFEEF2DD floatArrayOf(8.5f,17f,31f,4f,31f,19f,21.5f,24.5f) to 0xFFEEF2DD
).mapIndexed { index,(points,color) -> ).mapIndexed { index,(points,color) ->
val angle=(-60.0+60*index)*PI/180 val corners=points.toList().chunked(2){Offset(it[0]-32f,it[1]-32f)}
ApertureFacet(points.toList().chunked(2){Offset(it[0]-32f,it[1]-32f)},Color(color),Offset(cos(angle).toFloat(),sin(angle).toFloat())) val centroid=Offset(corners.sumOf{it.x.toDouble()}.toFloat()/4,corners.sumOf{it.y.toDouble()}.toFloat()/4)
KaleidoFacet(corners,centroid,Color(color),rad(-60f+60*index))
} }
// Loose shards around each facet: angle from the facet's normal (degrees), starting radius (dp),
// size, palette offset and how far they tumble on the way in.
private class Shard(val angle:Float,val radius:Float,val scale:Float,val color:Int,val spin:Float)
private val shards=listOf(
Shard(20f,170f,.42f,2,1.2f),Shard(-20f,170f,.42f,4,-1.2f),
Shard(36f,320f,.3f,3,2.1f),Shard(-36f,320f,.3f,1,-2.1f),
Shard(8f,420f,.2f,5,3f),Shard(-8f,420f,.2f,5,-3f)
)
// Inner hexagon traced by the facets' inner edges: the aperture the exit flies through. // Inner hexagon traced by the facets' inner edges: the aperture the exit flies through.
private const val InnerRadius=13.6f private const val InnerRadius=13.6f
private const val InnerApothem=11.8f private const val MarkBox=140f
private const val IntroBox=132f // Timeline in ms. The shard field fades in, still, until GatherEnd and holds there until startup is ready; the
// The settled lockup is the header Brand() scaled up, so it reads as the same mark. // gather then plays in motion time (timeline minus GatherEnd). Completion is reported at IntroEnd; the timeline
private const val LockScale=2.75f // keeps running to TimelineEnd only so the mark stays alive while the exit plays or startup loads.
private const val LockBox=29f*LockScale
private const val LockGap=7f*LockScale
// Opening timeline in ms, paused at GatherEnd until startup is ready. Completion is reported at IntroEnd; the timeline keeps
// running to TimelineEnd only for the slow settle while the exit plays or startup loads.
private const val GatherEnd=260f private const val GatherEnd=260f
private const val IntroEnd=2260f private const val IntroEnd=GatherEnd+1700f
private const val TimelineEnd=2900f private const val TimelineEnd=GatherEnd+8000f
const val StartupExitMillis=640 const val StartupExitMillis=640
// The mark is larger than the old lockup, so it zooms less to end the flight at the same size.
private const val FlightZoom=30f
private val Emphasized=CubicBezierEasing(.2f,0f,0f,1f) private val Emphasized=CubicBezierEasing(.2f,0f,0f,1f)
private val EmphasizedDecelerate=CubicBezierEasing(.05f,.7f,.1f,1f) private val EmphasizedDecelerate=CubicBezierEasing(.05f,.7f,.1f,1f)
private val Standard=CubicBezierEasing(.4f,0f,.2f,1f) private val Standard=CubicBezierEasing(.4f,0f,.2f,1f)
private val InOut=CubicBezierEasing(.45f,0f,.55f,1f) private val InOut=CubicBezierEasing(.45f,0f,.55f,1f)
// A mechanical iris: the blades gather, snap open, and overshoot slightly as they lock.
private val IrisOpen=CubicBezierEasing(.55f,0f,.15f,1f)
private val IrisTwist=CubicBezierEasing(.5f,0f,.18f,1.1f)
// Applied in log space: a brief pull back, then an accelerating flight. // Applied in log space: a brief pull back, then an accelerating flight.
private val Flight=CubicBezierEasing(.55f,-.06f,.8f,.36f) private val Flight=CubicBezierEasing(.55f,-.06f,.8f,.36f)
private val SeaGlass=Color(0xFF71B9B0) private val SeaGlass=Color(0xFF71B9B0)
private val Light=Color(0xFFEEF2DD)
private fun rad(degrees:Float)=degrees*PI.toFloat()/180
private fun phase(time:Float,start:Float,end:Float)=((time-start)/(end-start)).coerceIn(0f,1f) private fun phase(time:Float,start:Float,end:Float)=((time-start)/(end-start)).coerceIn(0f,1f)
private fun mix(from:Float,to:Float,amount:Float)=from+(to-from)*amount private fun mix(from:Float,to:Float,amount:Float)=from+(to-from)*amount
private class Iris(val inward:Float,val theta:Float,val grow:Float) /** A facet turned [rotation] about the mark center, shrunk and spun about its own centroid, then offset. */
private fun irisAt(time:Float):Iris { private fun Path.facet(facet:KaleidoFacet,center:Offset,unit:Float,rotation:Float=0f,scale:Float=1f,spin:Float=0f,offset:Offset=Offset.Zero) {
val progress=phase(time,140f,1180f) val cr=cos(rotation);val sr=sin(rotation);val cs=cos(spin);val ss=sin(spin)
return Iris(InnerApothem*(1f-IrisOpen.transform(progress)),(-44f*(1f-IrisTwist.transform(progress))*PI/180).toFloat(), facet.points.forEachIndexed { index,point ->
mix(.64f,1f,Emphasized.transform(progress))) val rx=point.x-facet.centroid.x;val ry=point.y-facet.centroid.y
val x=facet.centroid.x+(rx*cs-ry*ss)*scale;val y=facet.centroid.y+(rx*ss+ry*cs)*scale
val px=center.x+(x*cr-y*sr)*unit+offset.x;val py=center.y+(x*sr+y*cr)*unit+offset.y
if(index==0)moveTo(px,py)else lineTo(px,py)
}
close()
} }
private fun Path.facet(facet:ApertureFacet,iris:Iris,unit:Float,center:Offset) { /** A loose facet shape with its centroid at [position]. */
val c=cos(iris.theta);val s=sin(iris.theta);val k=unit*iris.grow private fun Path.shard(facet:KaleidoFacet,position:Offset,size:Float,angle:Float) {
val c=cos(angle);val s=sin(angle)
facet.points.forEachIndexed { index,point -> facet.points.forEachIndexed { index,point ->
val x=point.x-facet.normal.x*iris.inward;val y=point.y-facet.normal.y*iris.inward val x=point.x-facet.centroid.x;val y=point.y-facet.centroid.y
val px=center.x+(x*c-y*s)*k;val py=center.y+(x*s+y*c)*k val px=position.x+(x*c-y*s)*size;val py=position.y+(x*s+y*c)*size
if(index==0)moveTo(px,py)else lineTo(px,py) if(index==0)moveTo(px,py)else lineTo(px,py)
} }
close() close()
@ -111,21 +118,21 @@ private fun Path.hexagon(center:Offset,radius:Float) {
fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(phase(exit,.25f,1f))) fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(phase(exit,.25f,1f)))
/** /**
* The cold-start brand sequence: a closed iris lit from behind twists open once [ready], light catches * The cold-start brand sequence, the same as Kaleido Desktop: a kaleidoscope. A mirrored field of shards turns
* the facets, and the wordmark slides out of the mark. [exit] (0–1, linear) then flies * and gathers into the mark's six facets once [ready]; small shards circle the mark if startup runs on. [exit]
* the camera through the aperture's dark center, revealing the app drawn beneath. * (0–1, linear) then flies the camera through the mark's open center, revealing the app drawn beneath.
*/ */
@Composable fun StartupSplash(exit:()->Float,ready:()->Boolean,onComplete:()->Unit) { @Composable fun StartupSplash(exit:()->Float,ready:()->Boolean,onComplete:()->Unit) {
val timeline=remember{Animatable(0f)} val timeline=remember{Animatable(0f)}
val complete by rememberUpdatedState(onComplete) val complete by rememberUpdatedState(onComplete)
LaunchedEffect(Unit){ LaunchedEffect(Unit){
// Animatable honors Android's animation duration scale, including animations off. // Animatable honors Android's animation duration scale, including animations off.
// Light gathers on the closed iris straight away. It is nearly still, so the first // The field fades in faint and still straight away, so the first cold-start frames
// cold-start frames can hitch there without being noticed. // can hitch there without being noticed.
timeline.animateTo(GatherEnd,tween(GatherEnd.toInt(),easing=LinearEasing)) timeline.animateTo(GatherEnd,tween(GatherEnd.toInt(),easing=LinearEasing))
// Startup data arriving composes the app beneath the splash in one long frame. Hold // Startup data arriving composes the app beneath the splash in one long frame. Hold
// until that has happened and frames arrive steadily again (at most 700 ms), so // until that has happened and frames arrive steadily again (at most 700 ms), so
// the iris never opens through it. // the gather, fastest at its start, never runs through it.
withTimeoutOrNull(700){ withTimeoutOrNull(700){
snapshotFlow{ready()}.first{it} snapshotFlow{ready()}.first{it}
awaitSteadyFrames(4) awaitSteadyFrames(4)
@ -136,42 +143,23 @@ fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(
snapshotFlow{timeline.value>=IntroEnd}.first{it} snapshotFlow{timeline.value>=IntroEnd}.first{it}
complete() complete()
} }
val measurer=rememberTextMeasurer()
val density=LocalDensity.current
val style=TextStyle(color=Accent,fontSize=(19f*LockScale).sp,fontWeight=FontWeight.Bold)
val letters=remember(measurer,density){"KALEIDO".map{measurer.measure(it.toString(),style)}}
val letterX=remember(letters,density){
val tracking=with(density){(1.4f*LockScale).sp.toPx()}
letters.runningFold(0f){x,letter->x+letter.size.width+tracking}
}
val textWidth=letterX.last()-with(density){(1.4f*LockScale).sp.toPx()}
val capHeight=with(density){style.fontSize.toPx()}*.711f
val paths=remember{List(4){Path()}} val paths=remember{List(4){Path()}}
Canvas(Modifier.fillMaxSize().clearAndSetSemantics{contentDescription="Kaleido starting"}) { Canvas(Modifier.fillMaxSize().clearAndSetSemantics{contentDescription="Kaleido starting"}) {
val time=timeline.value val time=timeline.value
val motion=time-GatherEnd
val prelude=EmphasizedDecelerate.transform(phase(time,0f,GatherEnd))
val q=exit() val q=exit()
val dp=density.density val dp=density
val lockup=Emphasized.transform(phase(time,1250f,2000f)) val zoom=if(q>0f)exp(ln(FlightZoom)*Flight.transform(q))else 1f
val lockWidth=(LockBox+LockGap)*dp+textWidth val unit=MarkBox*dp/64f*zoom
var box=mix(IntroBox,LockBox,lockup)*dp val origin=center
// A slow push-in keeps the settled frame alive. val gather=Emphasized.transform(phase(motion,0f,1450f))
val drift=1f+.025f*InOut.transform(phase(time,1900f,2900f)) // The whole field turns a little less than half a revolution as it gathers.
var cx=mix(center.x,center.x-lockWidth/2+LockBox*dp/2,lockup) val field=rad(-150f)*(1f-Emphasized.transform(phase(motion,0f,1550f)))
var cy=center.y val (surface,aperture,shape,ring)=paths
var zoom=1f;var textAlpha=1f;var textShift=0f;var hole=0f
if(q>0f) {
zoom=exp(ln(52f)*Flight.transform(q))
val recenter=Standard.transform((q/.75f).coerceAtMost(1f))
cx=mix(cx,center.x,recenter);cy=mix(cy,center.y,recenter)
textAlpha=1f-Standard.transform(phase(q,0f,.4f))
textShift=-14f*dp*Standard.transform(phase(q,0f,.4f))
hole=InOut.transform(phase(q,.12f,.5f))
}
val unit=box/64f*drift*zoom
val origin=Offset(cx,cy)
val (surface,aperture,facets,ray)=paths
// Splash surface: Ink everywhere, with the aperture's center cut away on exit. // Splash surface: Ink everywhere, with the aperture's center cut away on exit.
val hole=InOut.transform(phase(q,.12f,.5f))
if(hole<=0f)drawRect(Ink) if(hole<=0f)drawRect(Ink)
else { else {
surface.rewind();surface.fillType=PathFillType.EvenOdd surface.rewind();surface.fillType=PathFillType.EvenOdd
@ -180,58 +168,66 @@ fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(
if(hole<1f){aperture.rewind();aperture.hexagon(origin,InnerRadius*unit);drawPath(aperture,Ink,alpha=1f-hole)} if(hole<1f){aperture.rewind();aperture.hexagon(origin,InnerRadius*unit);drawPath(aperture,Ink,alpha=1f-hole)}
} }
val iris=irisAt(time) // The kaleidoscope's mirror lines, turning with the field.
val lightUp=EmphasizedDecelerate.transform(phase(time,0f,620f)) val lines=max(.5f*prelude,InOut.transform(phase(motion,0f,450f)))*(1f-Standard.transform(phase(motion,1100f,1700f)))
val light=lightUp*(1f-Standard.transform(phase(time,620f,1250f))) if(lines>0f) for(index in 0 until 6) {
val ambient=.03f*InOut.transform(phase(time,300f,900f))*(1f-Standard.transform(phase(time,1500f,2300f))) val angle=field+rad(-90f+60*index)
// Light behind the blades: a soft bloom, a hot core, and rays leaking through val end=origin+Offset(cos(angle),sin(angle))*(640f*dp)
// the six gaps while the iris turns. drawLine(Brush.linearGradient(0f to Light.copy(alpha=.2f*lines),1f to Color.Transparent,start=origin,end=end),origin,end,dp)
if(light>.001f||ambient>.001f) { }
val bloom=250f*dp
drawCircle(Brush.radialGradient(0f to SeaGlass.copy(alpha=.16f*light+ambient),.45f to SeaGlass.copy(alpha=.04f*light+ambient*.3f), val bloom=.09f*InOut.transform(phase(motion,200f,1000f))*(1f-Standard.transform(phase(motion,1500f,2600f)))
1f to Color.Transparent,center=origin,radius=bloom),bloom,origin,blendMode=BlendMode.Plus) if(bloom>.001f) {
val core=26f*unit/2.0625f*mix(.6f,1f,light) val radius=300f*dp
if(light>.001f) { drawCircle(Brush.radialGradient(0f to SeaGlass.copy(alpha=bloom),.45f to SeaGlass.copy(alpha=bloom*.3f),1f to Color.Transparent,
drawCircle(Brush.radialGradient(0f to Color(1f,.98f,.925f,.95f*light),.35f to Color(0xFFEEF2DD).copy(alpha=.55f*light), center=origin,radius=radius),radius,origin,blendMode=BlendMode.Plus)
1f to Color.Transparent,center=origin,radius=core),core,origin,blendMode=BlendMode.Plus) }
val rays=light*(IrisOpen.transform(phase(time,140f,1180f))*2.5f).coerceAtMost(1f)
for(index in 0 until 6) { // Shards spiral inward, faster than the field turns, and vanish into the center.
val angle=((-90.0+60*index)*PI/180).toFloat()+iris.theta val inward=Emphasized.transform(phase(motion,0f,1350f))
val length=mix(40f,250f,lightUp)*(.75f+.25f*sin(index*2.1f+1f))*dp kaleidoFacets.forEachIndexed { s,facet ->
ray.rewind();ray.moveTo(origin.x,origin.y) shards.forEachIndexed { j,shard ->
ray.lineTo(origin.x+cos(angle-.014f)*length,origin.y+sin(angle-.014f)*length) val appear=max(.3f*prelude,Standard.transform(phase(motion,j*50f+s*25,j*50f+s*25+420)))
ray.lineTo(origin.x+cos(angle+.014f)*length,origin.y+sin(angle+.014f)*length);ray.close() val vanish=Standard.transform(phase(motion,750f+j*45,1350f+j*45))
drawPath(ray,Brush.linearGradient(0f to Color(1f,.973f,.902f,.42f*rays),.25f to Color(0xFFD6ECE2).copy(alpha=.12f*rays), if(appear>0f&&vanish<1f) {
1f to Color.Transparent,start=origin,end=Offset(origin.x+cos(angle)*length,origin.y+sin(angle)*length)),blendMode=BlendMode.Plus) val angle=facet.angle+rad(shard.angle)+field*1.5f
val radius=shard.radius*dp*(1f-.88f*inward)
shape.rewind()
shape.shard(facet,origin+Offset(cos(angle),sin(angle))*radius,unit*shard.scale*(1f-.6f*vanish),field*2+shard.spin*(1f-gather))
drawPath(shape,kaleidoFacets[(s+shard.color)%6].color,alpha=appear*(1f-vanish)*.9f,blendMode=BlendMode.Screen)
} }
} }
} }
// Facets. Short echoes of earlier frames act as motion blur while the blades // The six facets ride in from the field and lock into the mark.
// turn; they disappear beneath the facets once the iris is still. kaleidoFacets.forEachIndexed { s,facet ->
fun facetAlpha(index:Int)=EmphasizedDecelerate.transform(phase(time,40f+index*34,380f+index*34)) val radius=240f*dp*(1f-gather);val angle=facet.angle+field
if(time<1400f) for((delay,alpha) in listOf(84f to .07f,56f to .12f,28f to .2f)) { shape.rewind()
val echo=irisAt(time-delay) shape.facet(facet,origin,unit,field,mix(.55f,1f,gather),rad(-60f)*(1f-gather),Offset(cos(angle),sin(angle))*radius)
apertureFacets.forEachIndexed { index,facet -> drawPath(shape,facet.color,alpha=max(.3f*prelude,Standard.transform(phase(motion,s*25f,s*25f+420))))
facets.rewind();facets.facet(facet,echo,unit,origin);drawPath(facets,facet.color,alpha=alpha*facetAlpha(index))
}
}
apertureFacets.forEachIndexed { index,facet ->
facets.rewind();facets.facet(facet,iris,unit,origin);drawPath(facets,facet.color,alpha=facetAlpha(index))
} }
val sheen=phase(time,980f,1560f) // A ring pulses out as the facets lock.
if(light>.01f||(sheen>0f&&sheen<1f)) { val pulse=phase(motion,1380f,2050f)
facets.rewind();apertureFacets.forEach{facets.facet(it,iris,unit,origin)} if(pulse>0f&&pulse<1f) {
clipPath(facets) { ring.rewind();ring.hexagon(origin,(30f+24f*EmphasizedDecelerate.transform(pulse))*unit)
// Backlight tints the blades while the core is hot, so they read as glass. drawPath(ring,SeaGlass,alpha=.45f*(1f-pulse),style=Stroke(1.5f*dp))
if(light>.01f) {
val radius=36f*unit/2.0625f
drawCircle(Brush.radialGradient(0f to Color(1f,.988f,.94f,.26f*light),1f to Color.Transparent,center=origin,radius=radius),radius,origin)
} }
// One diagonal band of light crosses the settled mark.
if(sheen>0f&&sheen<1f) { // Still starting: small shards keep circling the mark.
val reach=34f*unit;val angle=36f*PI.toFloat()/180;val direction=Offset(cos(angle),sin(angle)) val idle=Standard.transform(phase(motion,2300f,2900f))*(1f-phase(q,0f,.25f))
if(idle>0f) for(s in 0 until 6) for(side in intArrayOf(-1,1)) {
val angle=rad(-60f+60*s)+side*rad(11f)+(motion-2300f)*.00032f
shape.rewind();shape.shard(kaleidoFacets[s],origin+Offset(cos(angle),sin(angle))*(50f*unit),unit*.16f,angle*2)
drawPath(shape,kaleidoFacets[(s+if(side>0)2 else 4)%6].color,alpha=.4f*idle,blendMode=BlendMode.Screen)
}
// A band of light crosses the settled mark, then again every few seconds while it waits.
val sheen=if(motion<1500f)0f else ((motion-1500f)%3600f)/900f
if(q==0f&&sheen>0f&&sheen<1f) {
shape.rewind();kaleidoFacets.forEach{shape.facet(it,origin,unit)}
clipPath(shape) {
val reach=40f*unit;val angle=rad(36f);val direction=Offset(cos(angle),sin(angle))
val position=mix(-1.25f,1.25f,InOut.transform(sheen))*reach;val width=10f*unit val position=mix(-1.25f,1.25f,InOut.transform(sheen))*reach;val width=10f*unit
val peak=.42f*sin((sheen*1.1f).coerceAtMost(1f)*PI.toFloat()) val peak=.42f*sin((sheen*1.1f).coerceAtMost(1f)*PI.toFloat())
drawRect(Brush.linearGradient(0f to Color.Transparent,.5f to Color.White.copy(alpha=peak),1f to Color.Transparent, drawRect(Brush.linearGradient(0f to Color.Transparent,.5f to Color.White.copy(alpha=peak),1f to Color.Transparent,
@ -239,23 +235,4 @@ fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(
} }
} }
} }
// The wordmark slides out from behind the mark as it moves into the lockup.
if(time>=1400f&&textAlpha>0f) {
val scale=box/(LockBox*dp)*drift
val textLeft=cx-box*drift/2+(LockBox+LockGap)*dp*scale
val slide=EmphasizedDecelerate.transform(phase(time,1400f,2050f))
val baseline=cy+capHeight/2*scale
clipRect(left=cx+24.5f*unit+2f*dp*scale) {
letters.forEachIndexed { index,letter ->
val start=1460f+index*45
val reveal=Standard.transform(phase(time,start,start+320f))
if(reveal>0f) withTransform({
translate(textLeft+(letterX[index]-(1f-slide)*textWidth*.42f)*scale+textShift,baseline-letter.firstBaseline*scale)
scale(scale,scale,pivot=Offset.Zero)
}) {drawText(letter,alpha=reveal*textAlpha)}
}
}
}
}
} }

View file

@ -0,0 +1,81 @@
package tv.kaleido.app
import androidx.compose.runtime.*
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.okhttp.OkHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import kotlinx.coroutines.CancellationException
/** Themes belong to title pages, never the foreground video or a background Activity. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable internal fun ThemeMusic(vm:KaleidoViewModel) {
val lifecycle=LocalLifecycleOwner.current.lifecycle
var resumed by remember { mutableStateOf(false) }
LifecycleResumeEffect(Unit) {
resumed=true
onPauseOrDispose { resumed=false }
}
val title=vm.detail?.takeIf { it.id==vm.page.id && vm.page.kind in listOf("details","group") }
val eligible=resumed && vm.themeMusic && vm.playing==null && !vm.linkingAccount && vm.servers.isEmpty() && vm.session!=null
val server=vm.session?.server
val parents=remember(server) { mutableMapOf<String,String>() }
val path by produceState("",eligible,title?.id,title?.theme,server) {
value=""
if(!eligible || title==null)return@produceState
val direct=title.theme
if(direct.isNotBlank()) { value=safeThemePath(direct);return@produceState }
val parent=when(title.type) { "season"->title.parentId; "episode"->title.grandparentId; else->"" }
if(parent.isBlank())return@produceState
try {
val theme=parents[parent] ?: vm.api.details(parent).theme.also { parents[parent]=it }
value=safeThemePath(theme)
} catch(e:CancellationException) { throw e } catch(_:Exception) { /* Missing themes stay silent. */ }
}
val source=path.takeIf { eligible && it.isNotBlank() }
val player=remember(source,server) {
source?.let {
val data=OkHttpDataSource.Factory(vm.api.http).setDefaultRequestProperties(vm.api.headers().filterKeys { key->key!="Accept" })
ExoPlayer.Builder(vm.application).setMediaSourceFactory(DefaultMediaSourceFactory(DefaultDataSource.Factory(vm.application,data))).build().apply {
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(),true)
setHandleAudioBecomingNoisy(true)
repeatMode=Player.REPEAT_MODE_ONE
volume=vm.themeVolume/100f
addListener(object:Player.Listener {
override fun onPlaybackStateChanged(state:Int) {
if(state==Player.STATE_READY)android.util.Log.i("KaleidoTheme","READY volume=${vm.themeVolume}%")
}
override fun onIsPlayingChanged(isPlaying:Boolean) {
if(isPlaying)android.util.Log.i("KaleidoTheme","PLAYING")
}
})
setMediaItem(MediaItem.fromUri(vm.api.url(it)))
prepare();playWhenReady=true
}
}
}
SideEffect { player?.volume=vm.themeVolume/100f }
DisposableEffect(player,lifecycle) {
// Pause synchronously: backgrounding must not depend on a later Compose frame.
val observer=LifecycleEventObserver { _,event->
if(event==Lifecycle.Event.ON_PAUSE)player?.pause()
else if(event==Lifecycle.Event.ON_RESUME && vm.themeMusic && vm.playing==null &&
vm.page.id==title?.id && vm.page.kind in listOf("details","group") && !vm.linkingAccount)player?.play()
}
lifecycle.addObserver(observer)
onDispose {
lifecycle.removeObserver(observer)
if(player!=null){player.release();android.util.Log.i("KaleidoTheme","STOP")}
}
}
}
internal fun safeThemePath(path:String):String = path.takeIf { it.startsWith('/') && !it.startsWith("//") }.orEmpty()

View file

@ -81,36 +81,16 @@ import kotlinx.coroutines.launch
// An episode started from the season row gets focus back itself, once the rebuilt row composes. // An episode started from the season row gets focus back itself, once the rebuilt row composes.
LaunchedEffect(vm.playbackReturn){if(vm.playbackReturn!=seenReturn[0]){seenReturn[0]=vm.playbackReturn;if(vm.focusId.startsWith("children:${item.id}:"))return@LaunchedEffect;withFrameNanos{};list.scrollToItem(0);withFrameNanos{};runCatching{actionFocus.requestFocus()}}} LaunchedEffect(vm.playbackReturn){if(vm.playbackReturn!=seenReturn[0]){seenReturn[0]=vm.playbackReturn;if(vm.focusId.startsWith("children:${item.id}:"))return@LaunchedEffect;withFrameNanos{};list.scrollToItem(0);withFrameNanos{};runCatching{actionFocus.requestFocus()}}}
Box(Modifier.fillMaxSize().background(Ink)) { Box(Modifier.fillMaxSize().background(Ink)) {
val usesPosterHeader=item.type in listOf("show","movie") // The browse previews' framing, so opening a title keeps its artwork in place; a season's
if(usesPosterHeader) { // artwork follows the episode it shows. Scroll is read in the layer, never in composition.
BrowseBackdrop(vm.api,item.art.ifBlank{item.thumb},Modifier.fillMaxSize().graphicsLayer { BrowseBackdrop(vm.api,if(episodic)previewArt(shown)else item.art.ifBlank{item.thumb},Modifier.fillMaxSize().graphicsLayer {
alpha=if(list.firstVisibleItemIndex>0)0f else (1f-list.firstVisibleItemScrollOffset/backdropFadeDistance).coerceIn(0f,1f) alpha=if(list.firstVisibleItemIndex>0)0f else (1f-list.firstVisibleItemScrollOffset/backdropFadeDistance).coerceIn(0f,1f)
},cinematic=true) },header=true,wash=vm.colourWash,animate=true)
// Keep the scene in the header; rows and captions sit on near-black. Read scroll
// in the layer so scrolling doesn't recompose the details and cast hierarchy.
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Ink.copy(alpha=.4f),.35f to Ink.copy(alpha=.5f),.62f to Ink.copy(alpha=.96f),.8f to Ink)))
}
// Actions lead to the first row below them: seasons/episodes, otherwise the first cast member. // Actions lead to the first row below them: seasons/episodes, otherwise the first cast member.
val below=if(vm.children.isNotEmpty())childFocus else if(item.castMembers.isNotEmpty())castFocus else null val below=if(vm.children.isNotEmpty())childFocus else if(item.castMembers.isNotEmpty())castFocus else null
CompositionLocalProvider(LocalBringIntoViewSpec provides DetailsScroll) { CompositionLocalProvider(LocalBringIntoViewSpec provides DetailsScroll) {
LazyColumn(state=list,contentPadding=PaddingValues(bottom=30.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) { LazyColumn(state=list,contentPadding=PaddingValues(bottom=30.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) {
item(key="details-${item.id}") { item(key="details-${item.id}"){DetailHeader(vm,shown,item,actionFocus,below,!restoreRow)}
// A fixed episode header, so moving along the season row never shifts the page.
Box(Modifier.fillMaxWidth().then(if(usesPosterHeader)Modifier.heightIn(min=248.dp)else if(episodic)Modifier.height(322.dp)else Modifier.heightIn(min=286.dp))) {
if(!usesPosterHeader) {
Artwork(vm.api,item.art,Modifier.matchParentSize(),1920,1080)
Box(Modifier.matchParentSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.8f),Color.Transparent))))
Box(Modifier.matchParentSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha=.12f),Color.Transparent,Ink))))
}
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=14.dp)){vm.back()}
if(usesPosterHeader) {
Row(Modifier.fillMaxWidth().padding(start=Cinema.gutter,end=Cinema.gutter,top=56.dp),horizontalArrangement=Arrangement.spacedBy(24.dp),verticalAlignment=Alignment.Top) {
Artwork(vm.api,item.poster.ifBlank{item.thumb},Modifier.width(128.dp).height(192.dp).clip(androidx.compose.foundation.shape.RoundedCornerShape(6.dp)),384,576,animate=false,contentScale=ContentScale.Fit)
TitleInformation(vm,item,item,actionFocus,below,!restoreRow,Modifier.weight(1f))
}
}else TitleInformation(vm,shown,item,actionFocus,below,!restoreRow,Modifier.align(Alignment.CenterStart).padding(start=Cinema.gutter,end=Cinema.gutter,top=64.dp,bottom=24.dp).fillMaxWidth())
}
}
// Rebuilt after playback so the row scrolls to the episode last played. // Rebuilt after playback so the row scrolls to the episode last played.
if(vm.children.isNotEmpty())item(key="children-${item.id}-${if(episodic)vm.playbackReturn else 0}") { if(vm.children.isNotEmpty())item(key="children-${item.id}-${if(episodic)vm.playbackReturn else 0}") {
if(episodic)MediaRow(vm,if(item.type=="season")item.title else "Season ${item.parentIndex}",vm.children,"children:${item.id}",landscape=true,entryFocus=childFocus,episodeTitles=true, if(episodic)MediaRow(vm,if(item.type=="season")item.title else "Season ${item.parentIndex}",vm.children,"children:${item.id}",landscape=true,entryFocus=childFocus,episodeTitles=true,
@ -134,29 +114,66 @@ private object DetailsScroll:BringIntoViewSpec {
} }
} }
/** [page] is the open title; on a season or episode page, [item] is the episode it shows. */ /**
@Composable private fun TitleInformation(vm:KaleidoViewModel,item:Title,page:Title,actionFocus:FocusRequester,below:FocusRequester?,initialFocus:Boolean,modifier:Modifier) { * The header, after the browse previews: title art, facts and format, synopsis, then actions.
val actionNavigation=Modifier.focusProperties{if(below!=null)down=below} * [page] is the open title; on a season or episode page, [item] is the episode it shows, and
* moving along the season row fades its copy like the previews. Fixed heights keep the rows
* below in place, and leave a show's season captions on screen.
*/
@Composable private fun DetailHeader(vm:KaleidoViewModel,item:Title,page:Title,actionFocus:FocusRequester,below:FocusRequester?,initialFocus:Boolean) {
var summaryOverflow by remember(item.id){mutableStateOf(false)} var summaryOverflow by remember(item.id){mutableStateOf(false)}
val episodic=page.type in listOf("season","episode")
val technical=item.type in listOf("movie","episode")
val height=when{episodic->296.dp;technical->276.dp;else->250.dp}
Box(Modifier.fillMaxWidth().height(height)) {
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=14.dp)){vm.back()}
Column(Modifier.align(Alignment.BottomStart).padding(start=Cinema.gutter,end=Cinema.gutter,bottom=4.dp)) {
CompositionLocalProvider(LocalTextStyle provides LocalTextStyle.current.copy(shadow=CaptionShadow)) {
FadingCopy(item,{it.id},with(LocalDensity.current){HeaderLift.toPx()},Modifier.height(if(episodic)166.dp else 150.dp),Alignment.BottomStart) {shown->
DetailCopy(vm,shown,page){if(shown.id==item.id)summaryOverflow=it}
}
}
DetailActions(vm,item,page,actionFocus,below,initialFocus,summaryOverflow)
if(technical)item.media.getOrNull(vm.mediaIndex(item))?.let{Text(it.technical,color=Cinema.quiet,fontSize=9.5.sp,lineHeight=13.sp,maxLines=1,modifier=Modifier.padding(top=10.dp))}
}
}
}
@Composable private fun DetailCopy(vm:KaleidoViewModel,item:Title,page:Title,onOverflow:(Boolean)->Unit) {
val runtime=when{item.duration<=0->"";item.offset>0->runtimeLabel(item.duration-item.offset)+" left";else->runtimeLabel(item.duration)}
val seasons=vm.children.size.takeIf{page.id==item.id&&item.type=="show"&&it>0}?.let{if(it==1)"1 season"else "$it seasons"}.orEmpty()
val facts=when(item.type) {
"episode"->listOf("S${item.parentIndex} · E${item.index}",airDate(item.releaseDate),runtime)
"season"->listOf(item.subtitle)
"show"->listOf(item.year,item.genres.take(2).joinToString(" / "),seasons,if(item.leafCount>0)"${item.leafCount} episodes"else "")
else->listOf(item.year,item.genres.take(2).joinToString(" / "),runtime)
}
Column(Modifier.width(560.dp)) {
// Episodes name their show with its title art, then the episode itself.
if(item.type=="episode") {
TitleIdentity(vm.api,item,Modifier.size(280.dp,48.dp))
Text(item.title,color=Accent,fontSize=19.sp,lineHeight=24.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=8.dp))
}else TitleIdentity(vm.api,item,Modifier.size(340.dp,64.dp))
Row(Modifier.padding(top=9.dp,bottom=7.dp).height(17.dp),verticalAlignment=Alignment.CenterVertically) {
if(item.contentRating.isNotBlank())FormatBadge(item.contentRating,Modifier.padding(end=8.dp))
Text(facts.filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=11.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(item,Modifier.padding(start=10.dp))
formatLabels(item.media.getOrNull(vm.mediaIndex(item))).forEachIndexed{index,label->FormatBadge(label,Modifier.padding(start=if(index==0)14.dp else 6.dp))}
}
Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=17.5.sp,maxLines=3,overflow=TextOverflow.Ellipsis,onTextLayout={onOverflow(it.hasVisualOverflow)})
}
}
@Composable private fun DetailActions(vm:KaleidoViewModel,item:Title,page:Title,actionFocus:FocusRequester,below:FocusRequester?,initialFocus:Boolean,summaryOverflow:Boolean) {
val actionNavigation=Modifier.focusProperties{if(below!=null)down=below}
var showSynopsis by remember(item.id){mutableStateOf(false)} var showSynopsis by remember(item.id){mutableStateOf(false)}
var showVersions by remember(item.id){mutableStateOf(false)} var showVersions by remember(item.id){mutableStateOf(false)}
val media=item.media.getOrNull(vm.mediaIndex(item)) val media=item.media.getOrNull(vm.mediaIndex(item))
Column(modifier) { // Scrolls sideways only if a title has more actions than fit the page.
CompositionLocalProvider(LocalTextStyle provides LocalTextStyle.current.copy(shadow=Shadow(Color.Black.copy(alpha=.95f),Offset(0f,2f),6f))) { if(item.type!="collection")Row(Modifier.padding(top=9.dp).horizontalScroll(rememberScrollState()).padding(vertical=3.dp),horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) {
// Seasons and episodes name their show above the title.
val show=when(page.type){"episode"->page.grandparentTitle;"season"->page.parentTitle;else->""}.ifBlank{item.grandparentTitle.takeIf{item.type=="episode"}.orEmpty()}
if(show.isNotBlank())Text(show,color=Cinema.secondary,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium)
Text(item.title,color=Accent,fontSize=32.sp,lineHeight=36.sp,fontWeight=FontWeight.Bold,maxLines=if(page.type in listOf("season","episode"))1 else 2,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=560.dp))
Row(Modifier.widthIn(max=620.dp).padding(top=9.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.subtitle,airDate(item.releaseDate).takeIf{item.type=="episode"}.orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Muted,fontSize=10.5.sp,lineHeight=16.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(item,Modifier.padding(start=12.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis,onTextLayout={summaryOverflow=it.hasVisualOverflow},modifier=Modifier.widthIn(max=560.dp).padding(top=10.dp,bottom=17.dp))
}
// Scrolls sideways only if a title has more actions than fit beside its poster.
if(item.type!="collection")Row(Modifier.horizontalScroll(rememberScrollState()).padding(vertical=3.dp),horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) {
ActionButton(if(item.offset>0)"Resume from ${clockTime(item.offset)}"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,modifier=actionNavigation.focusRequester(actionFocus),primary=true,initialFocus=initialFocus){played(vm,page);vm.play(item)} ActionButton(if(item.offset>0)"Resume from ${clockTime(item.offset)}"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,modifier=actionNavigation.focusRequester(actionFocus),primary=true,initialFocus=initialFocus){played(vm,page);vm.play(item)}
if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay,modifier=actionNavigation){played(vm,page);vm.play(item,true)} if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay,modifier=actionNavigation){played(vm,page);vm.play(item,true)}
if(page.type=="show"&&item.type=="show")ActionButton("Shuffle episodes",Icons.Outlined.Shuffle,modifier=actionNavigation){played(vm,page);vm.playShuffled(item)}
if(item.type in listOf("movie","show","season","episode")) { if(item.type in listOf("movie","show","season","episode")) {
val watched=item.isWatched(vm.watchedPercent) val watched=item.isWatched(vm.watchedPercent)
ActionButton(if(vm.markingId==item.id)"Updating…"else if(watched)"Mark unwatched"else "Mark watched",if(watched)Icons.Outlined.CheckCircle else Icons.Outlined.Check,modifier=actionNavigation){vm.mark(item)} ActionButton(if(vm.markingId==item.id)"Updating…"else if(watched)"Mark unwatched"else "Mark watched",if(watched)Icons.Outlined.CheckCircle else Icons.Outlined.Check,modifier=actionNavigation){vm.mark(item)}
@ -167,8 +184,6 @@ private object DetailsScroll:BringIntoViewSpec {
else "Version ${vm.mediaIndex(item)+1} of ${item.media.size}",Icons.Outlined.Layers,modifier=actionNavigation){showVersions=true} else "Version ${vm.mediaIndex(item)+1} of ${item.media.size}",Icons.Outlined.Layers,modifier=actionNavigation){showVersions=true}
if(item.type in listOf("show","movie")&&summaryOverflow)ActionButton("Synopsis",Icons.Outlined.Description,modifier=actionNavigation){showSynopsis=true} if(item.type in listOf("show","movie")&&summaryOverflow)ActionButton("Synopsis",Icons.Outlined.Description,modifier=actionNavigation){showSynopsis=true}
} }
if(item.type !in listOf("show","season"))media?.let{Text(it.description(),color=Cinema.quiet,fontSize=9.5.sp,modifier=Modifier.padding(top=12.dp))}
}
if(showSynopsis)SynopsisDialog(vm.api,item){showSynopsis=false} if(showSynopsis)SynopsisDialog(vm.api,item){showSynopsis=false}
if(showVersions)ChoiceDialog("Versions",item.media.map{it.description(includeSize=true)},vm.mediaIndex(item),{showVersions=false}){vm.chooseMedia(item,it);showVersions=false} if(showVersions)ChoiceDialog("Versions",item.media.map{it.description(includeSize=true)},vm.mediaIndex(item),{showVersions=false}){vm.chooseMedia(item,it);showVersions=false}
} }
@ -218,6 +233,7 @@ internal fun nextUp(episodes:List<Title>,watchedPercent:Int)=episodes.firstOrNul
@Composable private fun CastRail(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester,entry:FocusRequester) { @Composable private fun CastRail(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester,entry:FocusRequester) {
val initial=remember(item.id){item.castMembers.indexOfFirst{"cast:${item.id}:${it.id.ifBlank{it.name}}"==vm.focusId}.coerceAtLeast(0)} val initial=remember(item.id){item.castMembers.indexOfFirst{"cast:${item.id}:${it.id.ifBlank{it.name}}"==vm.focusId}.coerceAtLeast(0)}
val row=rememberLazyListState(initialFirstVisibleItemIndex=initial) val row=rememberLazyListState(initialFirstVisibleItemIndex=initial)
val entryIndex by rememberRowEntry(row,0)
Column { Column {
Text("Cast",color=Accent,fontSize=17.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=10.dp)) Text("Cast",color=Accent,fontSize=17.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=10.dp))
LazyRow(state=row,contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer(fallback=entry)) { LazyRow(state=row,contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer(fallback=entry)) {
@ -226,7 +242,7 @@ internal fun nextUp(episodes:List<Title>,watchedPercent:Int)=episodes.firstOrNul
var focused by remember{mutableStateOf(false)} var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()} val requester=remember{FocusRequester()}
LaunchedEffect(Unit){if(vm.focusId==key){withFrameNanos{};runCatching{requester.requestFocus()}}} LaunchedEffect(Unit){if(vm.focusId==key){withFrameNanos{};runCatching{requester.requestFocus()}}}
Column(Modifier.width(108.dp).then(if(index==0)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).focusProperties{if(item.type!="collection"&&vm.children.isEmpty())up=actionFocus}.navigationSound().onFocusChanged{ Column(Modifier.width(108.dp).then(if(index==entryIndex)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).focusProperties{if(item.type!="collection"&&vm.children.isEmpty())up=actionFocus}.navigationSound().onFocusChanged{
focused=it.isFocused;if(it.isFocused)vm.focusId=key focused=it.isFocused;if(it.isFocused)vm.focusId=key
}.clickable(enabled=actor.id.isNotBlank()){vm.openActor(actor)}.clearAndSetSemantics{ }.clickable(enabled=actor.id.isNotBlank()){vm.openActor(actor)}.clearAndSetSemantics{
contentDescription=listOf(actor.name,actor.role).filter{it.isNotBlank()}.joinToString(". ") contentDescription=listOf(actor.name,actor.role).filter{it.isNotBlank()}.joinToString(". ")

View file

@ -0,0 +1,13 @@
package tv.kaleido.app
import org.junit.Assert.*
import org.junit.Test
class AudioPreferencesTest {
@Test fun themesUseOnlyServerRelativePaths() {
assertEquals("/library/metadata/6115/theme/1",safeThemePath("/library/metadata/6115/theme/1"))
assertEquals("",safeThemePath("https://elsewhere.example/theme.mp3"))
assertEquals("",safeThemePath("//elsewhere.example/theme.mp3"))
assertEquals("",safeThemePath(""))
}
}

View file

@ -0,0 +1,55 @@
package tv.kaleido.app
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
class CategoryArtworkTest {
@Test fun overlappingGenresUseDifferentShows() {
val chosen=selectCategoryArtwork(linkedMapOf("Adventure" to listOf("Adventure Time","Silo"),"Children" to listOf("Adventure Time","Bluey"))){it}
assertEquals(2,chosen.values.toSet().size)
assertEquals("Adventure Time",chosen["Adventure"])
assertEquals("Bluey",chosen["Children"])
}
@Test fun narrowGenresKeepTheirOnlySource() {
val chosen=selectCategoryArtwork(linkedMapOf("Action" to listOf("Shared","Action only"),"Children" to listOf("Shared"))){it}
assertEquals(mapOf("Action" to "Action only","Children" to "Shared"),chosen)
}
@Test fun unavailableUniqueSourcesNeverProduceDuplicates() {
val chosen=selectCategoryArtwork(mapOf("A" to listOf("Same","Same"),"B" to listOf("Same"),"Empty" to listOf(""))){it}
assertEquals(1,chosen.size)
assertEquals(1,chosen.values.toSet().size)
assertFalse(chosen.containsKey("Empty"))
assertEquals("/library/metadata/12/art",categoryArtworkIdentity("/library/metadata/12/art/123?cache=1"))
}
@Test fun matchingFindsEveryAvailableAssignmentInSmallOverlappingCatalogs() {
// Exhaust all 512 three-genre/three-source graphs against a brute-force reference.
for(mask in 0 until 512) {
val candidates=(0..2).associate{i->i.toString() to (0..2).filter{j->mask and (1 shl (i*3+j))!=0}.map(Int::toString)}
fun maximum(index:Int,used:Set<String>):Int = if(index==3)0 else maxOf(
maximum(index+1,used),candidates.getValue(index.toString()).filter{it !in used}.maxOfOrNull{1+maximum(index+1,used+it)} ?: 0)
val selected=selectCategoryArtwork(candidates){it}
assertEquals("catalog $mask",maximum(0,emptySet()),selected.size)
assertEquals(selected.size,selected.values.toSet().size)
}
}
@Test fun realPlexCategoryCandidatesHaveCompleteUniqueAssignments() {
val path=System.getenv("KALEIDO_CATEGORY_FIXTURE")
assumeTrue("Optional private, read-only Plex fixture",!path.isNullOrBlank())
val rows=File(path!!).readLines().map{it.split('\t',limit=5)}
for((kind,section) in rows.groupBy{it[0]}) {
val candidates=section.groupBy{it[1]}.mapValues{(_,items)->items}
val selected=selectCategoryArtwork(candidates){categoryArtworkIdentity(it[3])}
assertEquals("Every $kind category needs artwork",candidates.size,selected.size)
val distinctTitles=selectCategoryArtwork(candidates){it[2]}.size
assertEquals("Use as many distinct titles as the library allows",distinctTitles,selected.values.map{it[2]}.toSet().size)
assertEquals(selected.size,selected.values.map{categoryArtworkIdentity(it[3])}.toSet().size)
println("PASS $kind: ${selected.size} distinct backgrounds from $distinctTitles different titles")
}
}
}

View file

@ -0,0 +1,33 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
class LibraryNavigationTest {
@Test fun firstCharacterCountsProduceAbsoluteTitleOffsets() {
val counts = listOf(
PlexCharacterCount("%23", "#", 3),
PlexCharacterCount("A", "A", 12),
PlexCharacterCount("B", "B", 0),
PlexCharacterCount("C", "C", 4),
)
assertEquals(mapOf("#" to 0, "A" to 3, "C" to 15), libraryCharacterOffsets(counts))
assertEquals(false, libraryCharacterOffsets(counts).containsKey("B"))
}
@Test fun genreUnwatchedAndMediaTypeArePartOfTheCharacterQuery() {
val all = LibraryCharacterQuery("1", "", false, plexLibraryType("movie"))
val action = LibraryCharacterQuery("1", "12", false, plexLibraryType("movie"))
val unwatched = LibraryCharacterQuery("1", "12", true, plexLibraryType("movie"))
val shows = LibraryCharacterQuery("2", "12", true, plexLibraryType("show"))
assertNotEquals(all, action)
assertNotEquals(action, unwatched)
assertNotEquals(unwatched, shows)
assertEquals(mapOf("genre" to "12", "unwatched" to "1", "type" to "2"), libraryFilterParameters("12", true, "2"))
assertEquals("1", plexLibraryType("movie"))
assertEquals("2", plexLibraryType("show"))
}
}

View file

@ -38,7 +38,7 @@ class PlaybackModelTest {
} }
@Test fun searchGroupsFollowBrowsingOrder() { @Test fun searchGroupsFollowBrowsingOrder() {
val groups=searchGroups(listOf(title("episode","e"),title("show","s"),title("movie","m"))) val groups=searchGroups(listOf(title("episode","e"),title("show","s"),title("movie","m")),query="")
assertEquals(listOf("Movies","TV shows","Episodes"),groups.map{it.first}) assertEquals(listOf("Movies","TV shows","Episodes"),groups.map{it.first})
} }
@ -51,6 +51,13 @@ class PlaybackModelTest {
@Test fun speedLabels() { @Test fun speedLabels() {
assertEquals("Normal",speedLabel(1f));assertEquals("1.25×",speedLabel(1.25f));assertEquals("2×",speedLabel(2f)) assertEquals("Normal",speedLabel(1f));assertEquals("1.25×",speedLabel(1.25f));assertEquals("2×",speedLabel(2f))
} }
@Test fun originalQualityUsesTheSelectedVersionsBitrate() {
val media=Media("1","mkv","hevc","eac3","4k",3840,2160,19094,emptyList())
assertEquals("Original quality · 19.1 Mbps",StreamQuality.Original.forMedia(media))
assertEquals("Original quality · 0.8 Mbps",StreamQuality.Original.forMedia(media.copy(bitrate=768)))
assertEquals("Original quality · Bitrate unavailable",StreamQuality.Original.forMedia(media.copy(bitrate=0)))
assertEquals(StreamQuality.FullHD.label,StreamQuality.FullHD.forMedia(media))
}
@Test fun seasonPagesShowTheNextEpisode() { @Test fun seasonPagesShowTheNextEpisode() {
val watched=title("episode","1").copy(watched=true) val watched=title("episode","1").copy(watched=true)
val unwatched=title("episode","2");val started=title("episode","3").copy(duration=60_000,offset=10_000) val unwatched=title("episode","2");val started=title("episode","3").copy(duration=60_000,offset=10_000)

View file

@ -0,0 +1,13 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Test
class PlaybackTerminationTest {
@Test fun serverReasonFollowsTheExplanation() {
assertEquals("The server stopped this stream.\n\nMaintenance tonight",PlaybackTermination(2006," Maintenance tonight ").message)
}
@Test fun blankReasonLeavesOnlyTheExplanation() {
assertEquals("The server stopped this stream.",PlaybackTermination(2006,"").message)
}
}

View file

@ -0,0 +1,32 @@
package tv.kaleido.app
import androidx.compose.foundation.lazy.LazyListItemInfo
import org.junit.Assert.assertEquals
import org.junit.Test
class RowEntryTest {
private fun card(index:Int,offset:Int)=object:LazyListItemInfo {
override val index=index
override val key:Any=index
override val offset=offset
override val size=264
}
// A 264 px card plus 24 px spacing; the row's start padding is 88 px (viewportStart -88).
private fun row(first:Int,firstOffset:Int,count:Int)=List(count){card(first+it,firstOffset+it*288)}
@Test fun keepsThePreferredCardWhileItIsInView() {
assertEquals(0,rowEntryIndex(0,row(0,0,7),-88))
assertEquals(3,rowEntryIndex(3,row(1,-100,7),-88))
}
@Test fun scrolledAwayRowEntersAtTheFirstFullyVisibleCard() {
// Seasons row restored to its end: Season 6 (index 5) is clipped, Season 7 is the first whole card.
assertEquals(6,rowEntryIndex(0,row(5,-167,7),-88))
// A card resting in the start padding is still wholly on screen.
assertEquals(4,rowEntryIndex(0,row(4,-60,7),-88))
}
@Test fun emptyLayoutKeepsThePreferredCard() {
assertEquals(2,rowEntryIndex(2,emptyList(),-88))
}
}

View file

@ -0,0 +1,70 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Test
class SearchRankingTest {
private data class Result(val type: String, val title: String, val inheritedTitles: List<String> = emptyList())
@Test fun exactShowRanksAheadOfLooseMovieResult() {
val groups = rankSearchGroups(listOf(
Result("movie", "The SpongeBob Movie: Sponge on the Run"),
Result("show", "Silo")
), "Silo", { it.type }) { listOf(it.title) }
assertEquals("TV shows", groups.first().first)
}
@Test fun exactMovieRanksAheadOfLooselyMatchingShow() {
val groups = rankSearchGroups(
listOf(Result("show", "The Silo Series"), Result("movie", "Silo")),
"Silo",
{ it.type }
) { listOf(it.title) }
assertEquals("Movies", groups.first().first)
}
@Test fun titlePrefixRanksAheadOfLaterTokenMatch() {
val groups = rankSearchGroups(
listOf(Result("show", "The Silo Series"), Result("movie", "Silo: Lost in Space")),
"Silo",
{ it.type }
) { listOf(it.title) }
assertEquals("Movies", groups.first().first)
}
@Test fun normalizedExactTitleOutranksPrefix() {
val groups = rankSearchGroups(
listOf(Result("movie", "Silo: The Movie"), Result("show", "Sílo")),
"Silo",
{ it.type }
) { listOf(it.title) }
assertEquals("TV shows", groups.first().first)
}
@Test fun ownExactTitleOutranksAnInheritedShowTitle() {
val groups = rankSearchGroups(
listOf(
Result("episode", "The Long Day", listOf("Silo")),
Result("show", "Silo")
),
"Silo",
{ it.type }
) { listOf(it.title) + it.inheritedTitles }
assertEquals("TV shows", groups.first().first)
}
@Test fun tiedGroupsKeepPlexResultOrder() {
val groups = rankSearchGroups(
listOf(Result("show", "Silo"), Result("movie", "Silo")),
"Silo",
{ it.type }
) { listOf(it.title) }
assertEquals(listOf("TV shows", "Movies"), groups.map { it.first })
}
}

View file

@ -0,0 +1,76 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.random.Random
class ShuffleEpisodesTest {
@Test fun previousEpisodeReturnsToTheEarlierPickOnly() {
val shuffle=ShuffleEpisodes(listOf("e1","e2","e3","e4"),{it},Random(7))
val first=shuffle.first!!
assertNull(shuffle.preceding(first))
val second=shuffle.following(first)!!
assertTrue(shuffle.advance(first,second))
assertEquals(first,shuffle.preceding(second))
assertTrue(!shuffle.retreat(second,"not-played"))
assertTrue(shuffle.retreat(second,first))
// Stepping back keeps the bag: the same episode follows again.
assertEquals(second,shuffle.following(first))
assertNull(shuffle.preceding(second))
}
@Test fun eachBagContainsEveryEpisodeOnceAndBoundaryDoesNotRepeat() {
val episodes=listOf("e1","e2","e3","e4","e5")
val shuffle=ShuffleEpisodes(episodes,{it},Random(42))
var current=shuffle.first
assertNotNull(current)
val firstBag=mutableListOf(current!!)
repeat(episodes.size-1) {
val next=shuffle.following(current!!)
assertNotNull(next)
assertTrue(shuffle.advance(current!!,next!!))
current=next
firstBag+=current!!
}
assertEquals(episodes.size,firstBag.distinct().size)
assertEquals(episodes.toSet(),firstBag.toSet())
val previous=current!!
val next=shuffle.following(previous)
assertNotNull(next)
assertNotEquals(previous,next)
assertTrue(shuffle.advance(previous,next!!))
current=next
val secondBag=mutableListOf(current!!)
repeat(episodes.size-1) {
val upcoming=shuffle.following(current!!)
assertNotNull(upcoming)
assertTrue(shuffle.advance(current!!,upcoming!!))
current=upcoming
secondBag+=current!!
}
assertEquals(episodes.size,secondBag.distinct().size)
assertEquals(episodes.toSet(),secondBag.toSet())
}
@Test fun onlyEpisodeRepeatsWhenItIsTheWholeShow() {
val shuffle=ShuffleEpisodes(listOf("only"),{it},Random(42))
assertEquals("only",shuffle.first)
assertEquals("only",shuffle.following("only"))
assertTrue(shuffle.advance("only","only"))
assertEquals("only",shuffle.following("only"))
}
@Test fun rejectsUnknownCurrentAndUnexpectedAdvance() {
val shuffle=ShuffleEpisodes(listOf("e1","e2","e3"),{it},Random(42))
assertNull(shuffle.following("missing"))
val current=shuffle.first!!
assertEquals(false,shuffle.advance(current,"missing"))
assertNotNull(shuffle.following(current))
}
}

Binary file not shown.

View file

@ -1 +1 @@
aaf650185f6854837afae9f69aee40e64060e5b22d8783aa1850a31196bf075a Kaleido.apk 2fd832eb90633d1519c15abccc122970a3c5ef51933da35634b8a5b1429d5bc3 Kaleido.apk

View file

@ -1,7 +1,7 @@
{ {
"version": "0.2.1", "version": "0.8.1",
"versionCode": 14, "versionCode": 25,
"url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.2.1/distribution/Kaleido.apk", "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.8.1/distribution/Kaleido.apk",
"checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.2.1/distribution/Kaleido.apk.sha256", "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.8.1/distribution/Kaleido.apk.sha256",
"notes": "- Season and episode pages are one horizontal layout again. Moving along the season row shows that episode at the top, and selecting it or Play plays it, instead of opening another page with the same information. Back from playback returns to the episode you played.\n- Remove the Go to show button from season and episode pages; Back returns to the show, and quick actions still offer Go to show.\n- Play buttons are solid white only when focused, so an unfocused Play no longer looks selected." "notes": "- Fix a title page where Down from the buttons did nothing, leaving you stuck at the top. This happened when the Seasons, Cast or another row below had been scrolled away from its first card, for example by reopening a show from Continue Watching. Down now moves to a card in view."
} }

View file

@ -5,16 +5,16 @@ The interface gives artwork priority. App chrome uses neutral near-black, charco
## Layout and typography ## Layout and typography
- Horizontal safe gutter: 44 dp. Navigation: 62 dp, with centered text destinations and independent search/settings icons. - Horizontal safe gutter: 44 dp. Navigation: 62 dp, with centered text destinations and independent search/settings icons.
- Home retains a large cinematic feature: an 80 percent stage with original title artwork, synopsis, playback and information actions. The scene continues beneath Continue Watching; entering the rail scrolls the feature away and the backdrop follows focused titles. Features interleave recently released, highly rated unwatched, and Plex-suggested movies/shows, excluding Continue Watching. They shuffle per refresh and rotate every 12 seconds while the hero is active, pausing during row browsing. - Home retains a large cinematic feature: an 80 percent stage with original title artwork, synopsis, playback and information actions, with Continue Watching peeking below. Entering the rows compacts it into a Silo-style preview of the focused card instead of scrolling it away: the hero lifts and fades as the rows slide up beneath a bottom-anchored block (64 dp title art, content-rating badge, year/episode, genre, runtime or time left, ratings, three synopsis lines, three cast names and 4K/HDR/Atmos format badges). The card's own image (an episode's still, not its show's art) is scaled whole into a top-right box of 72 × 78 percent of the screen, baked off-thread to fade into the page toward its left and bottom edges. Movies and TV use the same preview (56 dp title art) beneath their Discover/Library/Categories line, with rows starting 300 dp down; their row content stays distinct. With Settings › Interface › Artwork colour wash (default On), the page beneath carries the artwork's average colour normalized to 0.22 luminance, diagonally from the top-right (full) to the bottom-left (18 percent), as Silo does. It is baked into the same cached 960 × 540 frame, so it costs nothing per frame and changes through the artwork crossfade. A 1280 × 720 frame was tried for sharper art and raised Movies' horizontal p95 from about 31 to 36 ms through larger texture uploads, so it was not kept. The preview stays composed, invisible, under the hero with the first row's first card, so entering the rows is only a fade. Up from the first row or Back restores the hero. Features interleave recently released, highly rated unwatched, and Plex-suggested movies/shows, excluding Continue Watching, without a label naming the source. They shuffle per refresh and rotate every 12 seconds while the hero is active, pausing during row browsing.
- Movies uses a compact fixed preview above poster rows, with the backdrop and synopsis following focused titles. Recently released films and movie recommendations lead. TV uses a shorter preview, larger episode thumbnails, next episodes, newly added seasons, and then new episodes and show recommendations. Redundant TV hubs are omitted when their episode lists match exactly. These are deliberately different compositions. - Movies uses a compact fixed preview above poster rows, with the backdrop and synopsis following focused titles. Recently released films and movie recommendations lead. TV uses a shorter preview, larger episode thumbnails, next episodes, newly added seasons, and then new episodes and show recommendations. Redundant TV hubs are omitted when their episode lists match exactly. These are deliberately different compositions.
- Library: title and discovery/full-library navigation share a 64 dp header. A 43 dp filter row sits immediately above the six-column poster grid. - Library: title and discovery/full-library navigation share a 64 dp header. A 43 dp filter row sits immediately above the six-column poster grid.
- Browsing card widths: landscape 214 dp, TV episodes 264 dp, posters 120 dp. Landscape artwork uses 16:9; posters use 2:3. The full grid scales six columns to available width. Captions reserve a fixed height. - Browsing card widths: landscape 214 dp, TV episodes 264 dp, posters 120 dp. Landscape artwork uses 16:9; posters use 2:3. The full grid scales six columns to available width. Captions reserve a fixed height.
- Search uses three columns of landscape results. Episodes use their actual stills, preserving their native proportions instead of cropping them into posters. - Search uses three columns of landscape results. Episodes use their actual stills, preserving their native proportions instead of cropping them into posters.
- Movie and episode information pages place a horizontal Cast row beneath the description and actions, using Plex portraits, names and character roles. TV show pages place Seasons first, then Cast, then server-provided Related shows; season pages likewise keep Episodes ahead of Cast. Missing portraits use a neutral person placeholder. Actor cards open a six-column filmography of available movies and shows across the connected server's libraries, using Plex actor identifiers and pagination. - Movie and episode information pages place a horizontal Cast row beneath the description and actions, using Plex portraits, names and character roles. TV show pages place Seasons first, then Cast, then server-provided Related shows; season pages likewise keep Episodes ahead of Cast. Missing portraits use a neutral person placeholder. Actor cards open a six-column filmography of available movies and shows across the connected server's libraries, using Plex actor identifiers and pagination.
- TV show information uses a full-screen backdrop behind a fitted 128 × 192 dp poster and a top-aligned text block capped at 560 dp, matching movie details. The three-line summary offers a Synopsis action when truncated, opening the full text with D-pad scrolling. Its 248 dp minimum header keeps season artwork and captions on the initial screen at the standard TV density; longer titles can grow the header. The Back control stays in the safe area; focus only scrolls controls that are out of view. Artwork fades to near-black before the lower rows and disappears over the first 180 dp of scrolling. Soft text shadows preserve header contrast. - Movie, show, season and episode pages share the browse previews' language: the same top-right artwork frame and optional colour wash (so opening a title keeps its artwork in place), original title art (340 × 64 dp; episodes show their show's art at 280 × 48 dp above the episode name), a facts line with the content-rating badge, ratings and 4K/HDR/Atmos badges, and a three-line synopsis capped at 560 dp. A truncated movie or show synopsis offers a Synopsis action. Codec, audio layout and bitrate sit quietly beneath the actions. Season and episode pages follow the focused episode: its still crossfades and its copy fades and lifts as on the browse pages, while the actions stay in place. Fixed header heights (250 dp shows, 276 dp movies, 296 dp seasons/episodes) keep the rows still and a show's season captions on the initial screen. The Back control stays in the safe area; artwork disappears over the first 180 dp of scrolling. Soft text shadows preserve contrast.
- Movie, episode, show and season information pages expose labelled Mark watched / Mark unwatched actions. Changes are sent to Plex and reflected in the title, descendant episodes/seasons, library cards, actor results and recommendations. An in-flight write survives navigation and prevents duplicate submissions. Partial episode-list records update watch fields without replacing full cast/detail metadata. - Movie, episode, show and season information pages expose labelled Mark watched / Mark unwatched actions. Changes are sent to Plex and reflected in the title, descendant episodes/seasons, library cards, actor results and recommendations. An in-flight write survives navigation and prevents duplicate submissions. Partial episode-list records update watch fields without replacing full cast/detail metadata.
- Settings uses a fixed category rail (Connection, Playback, Interface, Updates) beside compact value/action rows. Focus selects categories; Right enters their controls and Left returns to the rail. Neutral surfaces, white focus, existing typography and restrained motion match the browsing destinations. Existing account, quality, watched-threshold, navigation-sound and updater preferences keep their behavior. - Settings uses a fixed category rail (Connection, Playback, Interface, Updates) beside compact value/action rows. Focus selects categories; Right enters their controls and Left returns to the rail. Neutral surfaces, white focus, existing typography and restrained motion match the browsing destinations. Existing account, quality, watched-threshold, navigation-sound and updater preferences keep their behavior.
- Features use original Plex clear-logo artwork within 264 × 80 dp, falling back to title text. Detail title: 32/36 sp. Library title: 29/34 sp. Discovery rail heading: 17/22 sp. Supporting information: 10/14 sp. - Features use original Plex clear-logo artwork within 264 × 80 dp, falling back to title text. Library title: 29/34 sp. Discovery rail heading: 17/22 sp. Supporting information: 10/14 sp.
- Poster and thumbnail corners: 6 dp. Compact action corners: 5 dp. Cards have no idle border; a compact bottom-right check marks watched titles, or a number shows remaining episodes for a show/season when Plex provides counts. Unwatched movies have no badge. Resumed movies/episodes only show a check after the configured playback threshold (80 percent by default), even if Plex retains a historical watched flag. Completed titles with no resume position retain Plex's watched state. Progress uses a two-dp inset line. - Poster and thumbnail corners: 6 dp. Compact action corners: 5 dp. Cards have no idle border; a compact bottom-right check marks watched titles, or a number shows remaining episodes for a show/season when Plex provides counts. Unwatched movies have no badge. Resumed movies/episodes only show a check after the configured playback threshold (80 percent by default), even if Plex retains a historical watched flag. Completed titles with no resume position retain Plex's watched state. Progress uses a two-dp inset line.
- The abstract six-facet aperture mark is shared by the header, sign-in, app icon, TV banner, and the cold-start aperture sequence. It uses muted sea-glass and warm ivory facets around a dark center, with no letterform or sparkle. The launcher banner and app icon place it on a diagonal light, deep sea-glass at the top right through near-black to a warm tan glow at the bottom left, with a soft vignette and nothing over the aperture; `scripts/generate_brand_tiles.py` regenerates both from `brand_mark.xml`. - The abstract six-facet aperture mark is shared by the header, sign-in, app icon, TV banner, and the cold-start aperture sequence. It uses muted sea-glass and warm ivory facets around a dark center, with no letterform or sparkle. The launcher banner and app icon place it on a diagonal light, deep sea-glass at the top right through near-black to a warm tan glow at the bottom left, with a soft vignette and nothing over the aperture; `scripts/generate_brand_tiles.py` regenerates both from `brand_mark.xml`.
- Audience ratings display Rotten Tomatoes as a percentage beside its official Popcornmeter artwork, and IMDb on its native ten-point scale beside the gold IMDb logo. Both appear when Plex exposes both; TVDB is retained as a fallback when neither is available. Critic scores and unsupported providers are omitted. Stable preview focus hydrates detail metadata, where Plex exposes the full provider list. The official red Hot mark appears at 60 percent or above and the green Stale mark below 60 percent; each fits a stable, font-scaled square without recoloring or distortion. Verified Hot is not inferred from a percentage. Asset provenance is in [brand-assets.md](brand-assets.md). The IMDb vector uses the official gold primary mark and supplied clear space from the [IMDb brand toolkit](https://brand.imdb.com/imdb). - Audience ratings display Rotten Tomatoes as a percentage beside its official Popcornmeter artwork, and IMDb on its native ten-point scale beside the gold IMDb logo. Both appear when Plex exposes both; TVDB is retained as a fallback when neither is available. Critic scores and unsupported providers are omitted. Stable preview focus hydrates detail metadata, where Plex exposes the full provider list. The official red Hot mark appears at 60 percent or above and the green Stale mark below 60 percent; each fits a stable, font-scaled square without recoloring or distortion. Verified Hot is not inferred from a percentage. Asset provenance is in [brand-assets.md](brand-assets.md). The IMDb vector uses the official gold primary mark and supplied clear space from the [IMDb brand toolkit](https://brand.imdb.com/imdb).
@ -27,7 +27,7 @@ The interface gives artwork priority. App chrome uses neutral near-black, charco
- Navigation contrast comes from a gradient extending past the controls and fading to transparent. Home/Movies/TV activate on focus. Explicit row and column links prevent beyond-bounds focus searches when holding a remote direction. - Navigation contrast comes from a gradient extending past the controls and fading to transparent. Home/Movies/TV activate on focus. Explicit row and column links prevent beyond-bounds focus searches when holding a remote direction.
- A spaced D-pad move predicts the actual row/column destination before starting its scroll or focus change. The target backdrop is fetched and contrast-processed through the same Coil request/cache as the visible scene. Speculative artwork uses one low-priority worker so it cannot flood normal decode workers during a burst of input. Metadata starts in parallel; the visible preview and details page share that in-flight request. Rapid horizontal input settles to the latest target before starting speculative work. Full metadata uses a 64-item LRU with a 30-second lifetime, cleared on account/server changes and refreshed after watched updates. Neutral library/search grids prefetch metadata without fetching an unused full-screen backdrop. - A spaced D-pad move predicts the actual row/column destination before starting its scroll or focus change. The target backdrop is fetched and contrast-processed through the same Coil request/cache as the visible scene. Speculative artwork uses one low-priority worker so it cannot flood normal decode workers during a burst of input. Metadata starts in parallel; the visible preview and details page share that in-flight request. Rapid horizontal input settles to the latest target before starting speculative work. Full metadata uses a 64-item LRU with a 30-second lifetime, cleared on account/server changes and refreshed after watched updates. Neutral library/search grids prefetch metadata without fetching an unused full-screen backdrop.
- Home's vertical list prepares content within one viewport ahead and retains one viewport behind, using Compose's bounded lazy-layout cache window. This keeps the hero and nearby rows ready when moving between them, rather than repeatedly composing and measuring the exposed image cards during the animation. Movies/TV use the same window. The window only fills ahead after the list has scrolled, so once a section settles it is nudged 1 px and back, letting the next rows compose in idle frames instead of during the first move down. Card sizes, row targets and the large cinematic Home layout are unchanged. - Home's vertical list prepares content within one viewport ahead and retains one viewport behind, using Compose's bounded lazy-layout cache window. This keeps the hero and nearby rows ready when moving between them, rather than repeatedly composing and measuring the exposed image cards during the animation. Movies/TV use the same window. The window only fills ahead after the list has scrolled, so once a section settles it is nudged 1 px and back, letting the next rows compose in idle frames instead of during the first move down. Card sizes, row targets and the large cinematic Home layout are unchanged.
- Section previews settle for 120 ms (Home artwork for 90 ms), overlapping the navigation animation, and retain previous artwork until replacement data is ready. Contrast gradients are baked into a cached bitmap on a worker thread, reducing GPU overdraw. Hero recommendation changes crossfade the artwork over 220 ms, including cache hits, and fade the title/summary out for 100 ms and back in over 180 ms. Rotation pauses on the information/next controls and preserves their focus. Vertical row changes animate to explicit row/column targets; page entrances fade and slide 28 dp over 280 ms, using per-draw alpha rather than an offscreen layer, and start once the new section's composition frames have passed (at most 300 ms). While a section enters, its cards lay out at their fixed size first and fill in artwork and titles three per frame under the fade, so the section's first frame stays short. Focusing a top tab lets its highlight draw before the section switches. The cold-start sequence lasts 2.9 seconds. The six exact facets begin as a closed, overlapping iris lit from behind; it holds there (at most 700 ms) until startup data has arrived and frames are steady, so cold-start hitches never interrupt the motion. The iris then twists 44° open and locks with a slight overshoot while light leaks through the six gaps, a single sheen crosses the settled mark, and the mark shrinks into a lockup scaled from the header brand as KALEIDO slides out from behind it. Once loading finishes (up to 600 ms extra) the camera flies through the aperture's dark center over 640 ms, revealing the app beneath as it settles from 114 percent scale. The completed mark itself is never redesigned. Android animation duration scale is honored, including animations off. It does not replay when returning from background. - Home, Movies and TV previews follow focus once it rests for 110 ms and retain previous artwork until replacement data is ready. New artwork fades in over the old for 320 ms, including cache hits; the outgoing title and synopsis lift slightly as they fade while the new ones rise 12 dp into place (380 ms). Hero recommendation changes use the same artwork and copy transitions, holding the copy up to 700 ms for the new artwork to decode. These fades, and the hero/preview exchange, are single animations read only in graphics layers, so they add no per-frame composition or layout. Contrast gradients are baked into a cached bitmap on a worker thread, reducing GPU overdraw. Rotation pauses on the information/next controls and preserves their focus. Vertical row changes animate to explicit row/column targets; page entrances fade and slide 28 dp over 280 ms, using per-draw alpha rather than an offscreen layer, and start once the new section's composition frames have passed (at most 300 ms). While a section enters, its cards lay out at their fixed size first and fill in artwork and titles three per frame under the fade, so the section's first frame stays short. Focusing a top tab lets its highlight draw before the section switches. The cold-start sequence is a kaleidoscope, the same as Kaleido Desktop's, and lasts about 2.6 seconds. A faint mirrored field of shards fades in, still, for 260 ms and holds there (at most 700 ms) until startup data has arrived and frames are steady, so cold-start hitches never interrupt the motion. The field then turns 150° while the shards spiral inward and vanish and the six exact facets ride in from it and lock into the mark (1.7 s), a hexagonal ring pulses out and a sheen crosses the settled mark. Once loading finishes (up to 600 ms extra; small shards begin circling the mark if it runs long) the camera flies through the mark's open center over 640 ms, revealing the app beneath as it settles from 114 percent scale. The completed mark itself is never redesigned. Android animation duration scale is honored, including animations off. It does not replay when returning from background.
- Returning from details restores the library's mode, scroll position, and previously focused title. - Returning from details restores the library's mode, scroll position, and previously focused title.
- Entering Movies/TV from the top bar focuses the fixed Discover control immediately. Down from Discover explicitly reveals the first catalog card; focus on already-visible targets changes before scrolling. A quick tab/Down sequence queues entry for the new destination, and focused tabs never repeat their delayed initial-focus request. - Entering Movies/TV from the top bar focuses the fixed Discover control immediately. Down from Discover explicitly reveals the first catalog card; focus on already-visible targets changes before scrolling. A quick tab/Down sequence queues entry for the new destination, and focused tabs never repeat their delayed initial-focus request.
- Offscreen card navigation requests the next lazy layout instead of forcing synchronous composition between key events. Up at the top bar is consumed because there is no destination above it; it must not start a lazy-list focus search. - Offscreen card navigation requests the next lazy layout instead of forcing synchronous composition between key events. Up at the top bar is consumed because there is no destination above it; it must not start a lazy-list focus search.
@ -37,11 +37,11 @@ The interface gives artwork priority. App chrome uses neutral near-black, charco
## Player ## Player
Controls occupy a shallow bottom gradient. A compact title, slim timeline, small time labels, central transport icons, and right-aligned track icons replace the rectangular button grid. The timeline is a true D-pad focus target: Up from transport reaches it, Left/Right seek, and Down returns to Play/Pause. Holding a direction increases the seek step. Dedicated media keys remain supported. Controls occupy a bottom gradient. The title uses the same original title art (240 × 44 dp) and rating badge/facts line as the browse and details pages, with the delivery quality quietly at the right; a slim timeline, small time labels, central transport icons, and right-aligned track icons replace the rectangular button grid. The timeline is a true D-pad focus target: Up from transport reaches it, Left/Right seek, and Down returns to Play/Pause. Holding a direction increases the seek step. Dedicated media keys remain supported.
The controls fade and slide away after five seconds during playback. While they are hidden, a Left/Right tap skips 10 seconds without revealing anything (quick taps add up into one seek), and holding Left/Right reveals the focused timeline for scrubbing. OK and Down reveal them; Back hides them before exiting. Audio and subtitle panels open above their icons and restore focus when dismissed. A gear exposes quality, audio, subtitles, speed, and chapters. Quality is one list shared with Settings: Original quality (the default, direct stream of the source video), then 4K, 1080p, 720p and 480p conversions. The timeline includes buffered progress and server-generated video/chapter previews. Skip actions have opaque contrast surfaces. The controls fade and slide away after five seconds during playback. While they are hidden, a Left/Right tap skips 10 seconds without revealing anything (quick taps add up into one seek), and holding Left/Right reveals the focused timeline for scrubbing. OK and Down reveal them; Back hides them before exiting. Audio and subtitle panels open above their icons and restore focus when dismissed. A gear exposes quality, audio, subtitles, speed, and chapters. Quality is one list shared with Settings: Original quality (the default, direct stream of the source video), then 4K, 1080p, 720p and 480p conversions. The timeline includes buffered progress and server-generated video/chapter previews. Skip actions have opaque contrast surfaces.
Episode endings and Skip credits open a five-second, cancellable next-episode countdown with season episodes and related shows. Each player session has a unique Media3 session ID so overlapping Compose disposal and next-episode creation cannot collide. Credits (automatically, or through Skip credits) and episode endings open Up Next: the playing video shrinks to a 352 × 198 dp frame at the top left and keeps playing, beside the next episode's still (top right, fading into the page), title art, episode title, facts line and three-line synopsis, with the season and related shows below. The page is drawn beneath the PlayerView so its SurfaceView shows through. Play next episode carries the only countdown (Settings › Autoplay next episode) as a sweeping fill; any remote press stops it. Left from Play next focuses the video; selecting it, or Back, returns to the full-screen credits. Each player session has a unique Media3 session ID so overlapping Compose disposal and next-episode creation cannot collide.
Settings includes a persistent watched percentage. Timeline reporting scrobbles the item in Plex once the selected percentage is reached, retries a failed write, and avoids repeated scrobbles within the same player session. This preference belongs to Kaleido and does not change the Plex server's global settings. Explicit watched changes refresh the title and parent episode counts across browsing caches. Settings includes a persistent watched percentage. Timeline reporting scrobbles the item in Plex once the selected percentage is reached, retries a failed write, and avoids repeated scrobbles within the same player session. This preference belongs to Kaleido and does not change the Plex server's global settings. Explicit watched changes refresh the title and parent episode counts across browsing caches.

View file

@ -22,7 +22,7 @@ Open Kaleido and enter its code at [plex.tv/link](https://plex.tv/link). Setting
D-pad moves focus, OK activates, and Back returns through details and seasons. In the player, OK shows controls; Left/Right while controls are hidden seeks; dedicated media keys control playback. The on-screen controls provide pause, seeking, audio, subtitles, next episode, and exit. Back first hides controls, then exits playback. Stopping or leaving the app reports the latest position to Plex. D-pad moves focus, OK activates, and Back returns through details and seasons. In the player, OK shows controls; Left/Right while controls are hidden seeks; dedicated media keys control playback. The on-screen controls provide pause, seeking, audio, subtitles, next episode, and exit. Back first hides controls, then exits playback. Stopping or leaving the app reports the latest position to Plex.
Original quality is the default, requesting the source video and remuxing where supported, with a 1080p conversion fallback. The player gear exposes the same quality preference as Settings, along with audio, subtitles, speed and chapters. Media3's SurfaceView preserves supported HDR. Actual HDR, Dolby Vision, codecs, and audio passthrough depend on the device, connected display/receiver, source profile, and server. Plex owns transcoding capability and any account entitlements. Unsupported subtitle formats use server conversion. Intro and credit buttons appear when the server supplies markers. Scrubbing displays server-generated video previews or chapter thumbnails when available; the timeline also shows buffered progress. Episode endings and Skip credits show a cancellable five-second next-episode countdown, season episodes, and related shows. Original quality is the default, requesting the source video and remuxing where supported, with a 1080p conversion fallback. The player gear exposes the same quality preference as Settings, along with audio, subtitles, speed and chapters. Media3's SurfaceView preserves supported HDR. Actual HDR, Dolby Vision, codecs, and audio passthrough depend on the device, connected display/receiver, source profile, and server. Plex owns transcoding capability and any account entitlements. Unsupported subtitle formats use server conversion. Intro and credit buttons appear when the server supplies markers. Scrubbing displays server-generated video previews or chapter thumbnails when available; the timeline also shows buffered progress. Credits and episode endings open Up Next: the video keeps playing in a corner beside the next episode, its single countdown, the season and related shows.
## Updates and releases ## Updates and releases

View file

@ -0,0 +1,37 @@
# Navigation performance comparison - 2026-10-27
The onn shows measurable navigation hitches in all three releases. This comparison does not establish a broad regression from the 0.2.1 bugfixes: optimized horizontal browse p95 was 32 ms in both 0.1.11 and 0.2.1, and 34 ms in 0.3.0. Some first-entry transitions are slower in the newer releases, while warm results overlap. No individual change or author can be identified as the cause from these measurements.
## Method
- Same onn 4K Plus Streaming at 192.168.50.195:5555, Android 14, armeabi-v7a; existing 1920x1080 display override and density 320 retained. Launcher, accessibility services and system settings were unchanged.
- Original signed 0.1.11/code 12 and 0.2.1/code 14 APKs were extracted from their tags and checksum-verified. The final signed 0.3.0/code 15 APK was tested. In-place installs retained the encrypted session and app preferences. Theme music and boost were Off.
- Each fresh install began in ART status=verify. Ran the horizontal browse harness, installed the bundled baseline profile, forced speed-profile compilation, confirmed ART status=speed-profile, then ran three cycles of all 14 Home/Movies transitions and another horizontal browse check. Thermal status was 0 throughout the version-start snapshots; corresponding reported sensor temperatures were essentially unchanged.
- Commands: scripts/repro_runtime.py browse and scripts/profile_transitions.py <label> --cycles 3. No competing device/UI tests ran. Raw framestats, compilation states and thermal snapshots remain in ignored evidence/private/.
## Results
| Release | Fresh-install browse median / p95 | Profiled browse median / p95 | Missed intervals across 42 transitions |
| --- | --- | --- | --- |
| 0.1.11 | 27 / 48 ms | 14 / 32 ms | 47 |
| 0.2.1 | 30 / 61 ms | 16 / 32 ms | 50 |
| 0.3.0 | 30 / 53 ms | 16 / 34 ms | 54 |
Fresh-install browse exceeded the 40 ms harness threshold in every release. All profiled browse runs passed, with stable horizontal Y geometry and zero gfxinfo Missed Vsync in that specific horizontal sample. That does not mean every frame met the 16.7 ms budget or every navigation transition was smooth.
Missed intervals below are inferred display stalls from adjacent framestats, not a count of dropped video frames. Each array is cycles 1, 2 and 3; the first cycle is the first pass after launch.
| Transition | 0.1.11 | 0.2.1 | 0.3.0 |
| --- | --- | --- | --- |
| home: hero -> row | 1 / 0 / 0 | 2 / 0 / 0 | 1 / 0 / 0 |
| home: hero <- row | 0 / 0 / 0 | 1 / 1 / 0 | 1 / 2 / 1 |
| tabs: home -> movies | 7 / 6 / 7 | 10 / 6 / 5 | 8 / 6 / 5 |
| tabs: home <- movies | 6 / 4 / 3 | 6 / 3 / 3 | 4 / 6 / 4 |
| movies: row -> row | 2 / 1 / 0 | 2 / 1 / 1 | 1 / 2 / 1 |
| movies: row <- row | 2 / 2 / 2 | 2 / 2 / 2 | 2 / 2 / 2 |
First Home hero-to-row p95 was 28.4 / 42.0 / 43.0 ms respectively; later cycles were 26.5-27.6 / 25.9 / 23.9-27.5 ms. First-pass work is a visible source of occasional stutter. Repeated tab switches also missed display intervals in every version.
This is a small on-device comparison, not a statistical attribution study. It cannot reconstruct the original compilation state when the user noticed the issue. Fresh-install optimization has a large effect here, but it is not proven to explain that earlier observation. The final 0.3.0 release was reinstalled, baseline-profile compiled and returned to Home afterward.

View file

@ -4,6 +4,72 @@ For the 2026-10-26 codec/HDR sweep and its native-versus-converted playback find
Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`. Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`.
## 2026-10-28/29 browse frame pacing toward 60 fps (0.6.1)
Measured on the onn with signed release builds, each freshly installed, profile-broadcast and `speed-profile` compiled (the same preparation for 0.6.0 and every candidate; a long-lived `bg-dexopt` install measures faster and is not comparable). `profile_transitions.py` now reports `dropped`: refreshes that repeated a frame, from `DisplayPresentTime`. A gap longer than about six frames counts only when the frame before it ran long enough to cause it. Frame latency alone misleads: the render thread usually waits 8–12 ms in `dequeueBuffer` because the pipeline is full, and buffer stuffing hides many 20–30 ms UI frames. The metric still cannot tell a deliberate pause from a stall, and run-to-run variance is large (the same code measured 24–38 drops), so compare totals across several runs.
Causes found with atrace, temporary measure sections and `simpleperf` (a temporarily `profileable` release):
- **Tab switches** disposed one section (~31 ms of `onForgotten`) and composed the next (50–100 ms frames). Home, Movies and TV now stay composed once shown; hidden ones are neither measured, placed nor drawn, carry `clearAndSetSemantics{}`, and take no focus. A hidden screen gives up focus and moves none; shown again it focuses what a new screen would. Movies and TV rows are kept per destination and keep their previous rows while the same library reloads. A retained switch is now one ~25 ms frame (placing and redrawing the screen).
- **The hero** was composed again on every return; it stays composed as a zero-alpha layer without semantics.
- **Prefetch**: Compose's scheduler treats a frame after a late one as idle and gives its request unlimited time; it composed whole rows (35–45 ms) mid-scroll. `FramePrefetch` uses only what is left of each frame, unlimited only when nothing has drawn for two frames, and rotates past a request that cannot progress (a hidden screen's list) instead of letting it block the queue. `CacheWindows` keeps Compose's cache-window strategy on that scheduler; it must subclass `CacheWindowLogic`, because the list measure policy only keeps scrolled-out items when the strategy is one. Nested prefetch composes and measures each card a row will show (Compose precomposes two). The catalog window is two viewports each way, refilled after row changes.
- **Accessibility** was the largest single cost. With any accessibility service enabled (the onn runs Luma's; Button Mapper was removed at the user's request), Compose rebuilds and geometry-sorts its whole semantics tree, placed or not, after every layout change, at most every 100 ms: about 40% of main-thread time while browsing. Rows and cards outside the viewport now carry no semantics (`semanticsOnScreen`, a `Modifier.Node` that observes the list and never recomposes). With accessibility temporarily disabled (restored afterwards), all 42 transitions dropped 16 frames; with Luma's service the best runs dropped 24–33.
- **Cards**: `CardArtwork` draws a memory-cache hit directly and otherwise loads then draws without recomposing, instead of Coil's painter (~2.5 ms per card). Staging applies only while a section first enters. Both title weights are laid out with the card and focus swaps their layers, so a move no longer re-measures two titles. Models are `@Immutable`, so equal rows and cards skip recomposition after a refresh.
- **The preview and hero copy** compose their parts over the first frames of their fade while still transparent (12 ms in one frame before).
- **Library sync** refreshes every 60 s, and Plex varies some Movies hubs on each request, so each refresh rebuilt rows; landing mid-move it caused a recurring 80–150 ms frame. The staged snapshot now waits for 2 s without a key before it is validated and applied. That exposed a latent bug: after a refresh replaced the focused card, the replacement could compose a frame after focus was requested, leaving nothing focused. `moveToRow` now retries for a few frames.
Dropped frames across three cycles of all 14 transitions (cycle 1 is the first pass after launch), 0.6.0 versus this build, Luma's service enabled:
| Transition | 0.6.0 | this build |
| --- | --- | --- |
| home: tab -> hero | 5 / 0 / 0 | 5 / 0 / 0 |
| home: row -> row | 4 / 0 / 2 | 4 / 1 / 1 |
| home: hero <- row | 1 / 1 / 1 | 0 / 0 / 0 |
| tabs: home -> movies | 7 / 4 / 5 | 6 / 2 / 1 (the first composes Movies) |
| movies: row -> row | 1 / 2 / 0 | 1 / 0 / 1 |
| tabs: home <- movies | 2 / 7 / 6 | 2 / 1 / 2 |
| all 42 transitions | 55 | 33 (24–38 across runs) |
On the TCL (two cycles, 28 transitions) 0.6.0 dropped 39 and this build 31; Movies → Home frames fell from 118 ms to 30 ms of UI time. The TCL is GPU-bound: the preview crossfade takes 17–18 ms of GPU time per frame (two full-screen backdrop layers), against 7 ms at rest. Its ADB reset sometimes failed and its later frames arrived every 25 ms, so treat those numbers as indicative.
Tried and reverted: delaying tab activation until the highlight settles (not measurably better, adds latency); a graphics layer per retained screen (the redraw was not avoided); preloading Movies/TV after startup and composing them unseen (first visit 7 → 2 drops, but it added post-startup load and coincided with an accessibility-dump anomaly); capping idle prefetch to one frame (rows were unprepared for quick moves). Silo's Android source was reviewed: standard Compose for TV with default prefetch, per-card spring focus animations, Coil 3 and a Macrobenchmark baseline profile; its settled-focus prefetch matches Kaleido's `anticipate`. JIT was ruled out here (about 16 compilations in a 6 s trace). On Google TV the default-Home preference is ignored (`launcherx` keeps resolving), and disabling `launcherx` would hand Home to Google's setup recovery activity, so Luma still needs its service.
Checks: `Build.ps1 -Release -Test` passed; `repro_runtime.py browse` passed (stable geometry, GPU p95 6 ms); `verify_ui.py browse` (8), `repro_runtime.py sections`, `verify_movie_details.py` and `verify_library_jump.py` passed. `verify_library_jump.py` now reads the first of a rail entry's labels (`# #`); it failed identically on 0.6.0. Since Button Mapper's removal, `verify_details_layout.py` fails at the synopsis dialog on 0.6.0 and this build alike: uiautomator dumps the window behind the dialog, while the dialog is shown with Close focused. The goal of no dropped frames is not met: tab switches still have one long frame, row moves sometimes drop one or two, the first Movies visit composes the section, and the Fire TV was not measured. Playback suites were not run; playback code did not change.
## 2026-10-28 playback quality, audio selection and show shuffle (0.5.0)
- Original quality now uses the selected media version's source bitrate; Infinity War shows `19.1 Mbps`. No source bitrate is invented when Plex omits it. The quality menu and audio-track popup were checked in actual device screenshots.
- `scripts/verify_playback_changes.py audio` passed real Infinity War track switches in Original mode and Plex conversion. Selected stereo audio was actually delivered as AC3 two-channel audio and AAC two-channel audio respectively; the paused state and timeline position survived both switches. The script restored the prior Plex audio selection and local preferences. Validation playback suppresses timeline/scrobble writes.
- Twelve focused unit checks passed (`PlaybackModelTest`, `ShuffleEpisodesTest`), along with lint and signed debug/release builds. The opt-in `PlaybackChangesIntegrationTest` passed two natural episode endings through the real player/Compose post-play path with ordinary autoplay set to Off; shuffle continued to different episodes. The test restored the original autoplay preference. Shuffle bags cover every eligible episode from all seasons before reshuffling and avoid repeating the previous episode at a bag boundary; a one-episode show explicitly recreates playback for its next cycle.
- The reported intermittent Infinity War audio stutter remains unresolved. A 45-second steady baseline near one hour played its original Dolby Vision video and EAC3 eight-channel audio without player errors or audio underruns; the user reports that rewinding does not repeat the symptom and that it also happens with boost disabled. No codec, output routing or buffer change was made without a reproduction. Release logcat now records sparse `KaleidoAudio` underrun/sink-error events with position and audio path, and the debug validation harness can fail on audio underruns with `--fail-on-audio-underrun`.
- The signed release passed the focused show/season UI check: Shuffle is remote-focusable on Silo's show page and absent on its season page. Reinstalled the release, installed its baseline profile and compiled only Kaleido with `speed-profile`, then returned the onn to Home. The user authorized publication after these local checks.
## 2026-10-28 genre-led category revision (0.4.1)
- The user requested a genre-led page instead of title-led cards: four columns, centered 22 sp genre labels, no title captions or FILM/SERIES badges, and dim artwork in the background. Natural artwork color is retained at 65% saturation after a monochrome preview was rejected. There are no added genre color tints.
- Release build/lint and the focused Movie/TV category navigation, selection and Back-restoration checks passed. The final build was installed/profile-compiled on the onn; final screenshots are `evidence/private/041-movies-unique.png`, `041-tv-unique.png` and `041-tv-lower-unique.png`. Verified different Adventure/Children shows and distinct Talk/Talk Show landscape images on the actual TV UI, traversed lower rows, and returned the signed release to Home.
- After reviewing the color preview, the user authorized publication once duplicate backgrounds were fixed. Artwork candidates are now matched across the whole selected library so categories cannot reuse a source; narrow genres get priority and overlapping groups can fetch additional pages. Selection is deterministic and applied atomically after the candidate requests, with the existing section/generation guards. The earlier 0.4.0 public APK/checksum were also verified.
- Five focused `CategoryArtworkTest` checks passed, including every three-genre/three-source overlap graph and a private read-only Plex fixture: 31 movie backgrounds from 31 titles, and 37 TV backgrounds from 36 titles. Talk and Talk Show each contain only The Grand Tour, so the remaining tile uses a different landscape from Plex's artwork list. Both images were downloaded through Plex and their SHA-256 values differ. Initial independent selection reproduced six repeated movie sources and fourteen repeated TV sources. No Plex metadata or artwork selection was changed.
## 2026-10-28 artwork, category cards, quick skips and search (0.4.0)
- Started from the latest published 0.3.1 history, retaining its episode-row reentry fix and regression script.
- Reproduced the Hazbin Hotel season artwork cutting off the character's head. Season/episode artwork now uses the full-page background rather than a cropped 322 dp header. A temporary top inset was removed after visual review: TV art fills the top edge like movies. Compared final signed-release screenshots of the show, season and 2 Fast 2 Furious; retained episode selection and season Back focus.
- Movie and TV category cards display real Plex artwork from matching genres. Both pages passed horizontal/vertical navigation, scoped-category entry and selected-card restoration on Back; TV navigation also traversed six lower rows. Screenshots include The Batman for movie Action and Hazbin Hotel for TV Animation.
- Verified actual hidden-controls skips of +10 s, -10 s and repeated +20 s on real playback. The final compact cue sits near either edge, with a centered arrow above its time, a short fade and no bordered panel. Screenshots cover both directions and accumulation; normal controls/timeline still work. Debug validation suppressed timeline/scrobble writes, and the harness confirmed the Plex fixture's progress and watched state stayed unchanged.
- Verified Clear empties the query/results and returns typing focus for a new search. The Android TV keyboard must be closed before D-pad navigation to app controls. The in-app microphone is absent; final signed-release empty Search has neither "Your collection" nor "Find something worth watching."
- `scripts/verify_040.py` contains focused feature checks. Debug/release builds and lint passed; the broad device suites were not run. Restored the signed release, installed its ART profile, compiled only Kaleido with `speed-profile`, and returned to Home.
## 2026-10-27 categories, search, themes and volume boost (0.3.0)
- Removed repeated Settings category headings. Exact normalized title matches now lead search rows instead of fixed Movies-first ordering; own-title matches outrank inherited episode/show names. The Silo case was reproduced by a failing grouping regression and verified against the live server and remote UI.
- Added scoped Plex genre categories and a light grey A–Z rail to movie/show libraries and category results. Plex first-character counts use the same media type, genre and watched filters as the grid; a jump loads the required prefix without fetching its artwork. Movie S reached absolute index 772 and TV S index 200. Both Animation categories, details Back, selected-category Back and grid focus restoration passed. Dense rail controls require compact touch targets, otherwise Android TV accessibility hides overlapping letters despite correct visual focus.
- Theme music defaults Off, with independent 10–100% volume. Plex themes inherit from show metadata on season/episode pages. Real Silo theme playback, season/episode pages, background stop and video stop were checked. The server currently supplies no movie theme fixtures; movie theme parsing is tested and uses the same playback path. Returning through a launcher can reopen Home, where music correctly remains silent; reopening a supported title starts its theme.
- Boost defaults Off and supports +3/+6/+9/+12 dB. It processes decoded 16-bit PCM across all channels and disables encoded passthrough/offload only while enabled; Off preserves the normal audio path. Unit tests cover gain, clipping without integer wrap and unchanged samples at zero gain. Real +6 dB playback of HEVC/EAC3 episode 7599 and converted movie 9776 confirmed PCM processing, advancing audio and rendered video. No acoustic loudness measurement was made. Validation mode avoided Plex progress changes.
- Checks: 26 unit tests, debug/release compilation and lint, three new live integration tests, existing Settings remote/dialog tests, the scoped library/jump checks and `verify_audio_preferences.py --playback-only`. The full audio UI batch separately verified setting changes, dialog focus and cold-start persistence; its fixture assertions now accept labels such as `Resume from 2:01`. Prior audio preferences were restored exactly. Private screenshots and audio/video validation logs remain ignored.
See [the navigation comparison](performance-2026-10-27.md) for matched release/profile benchmarks against 0.1.11 and 0.2.1. The final 0.3.0 release was restored on Home with ART speed-profile compilation. Publication and ADB installation do not constitute an in-app updater installation test.
## 2026-10-27 one season layout (0.2.1) ## 2026-10-27 one season layout (0.2.1)
- 0.2.0 gave seasons a vertical episode list whose items opened an episode page with a horizontal season row, so the same season appeared in two layouts and selecting an episode never played it. Season and episode pages now share the episode header and horizontal season row: focusing a card shows that episode (summary row data at once, full metadata after 250 ms, keeping the row's progress), and OK on the card or Play plays it. The header has a fixed height so moving along the row never shifts the page. Up from the row returns to Play; Down from Play enters the shown episode. - 0.2.0 gave seasons a vertical episode list whose items opened an episode page with a horizontal season row, so the same season appeared in two layouts and selecting an episode never played it. Season and episode pages now share the episode header and horizontal season row: focusing a card shows that episode (summary row data at once, full metadata after 250 ms, keeping the row's progress), and OK on the card or Play plays it. The header has a fixed height so moving along the row never shifts the page. Up from the row returns to Play; Down from Play enters the shown episode.
@ -189,3 +255,13 @@ The user reported severe lag while the devices still had temporary debug APKs in
The signed 0.1.10 APK uses the existing production certificate, version code 11. APK checks found neither private session data nor debug playback intent strings. Raw comparison records remain in ignored `evidence/private/release-comparison/`. The new benchmark scripts reject debuggable APKs and require `speed-profile`, so functional debug results cannot be mistaken for release performance evidence. The user explicitly authorized leaving Dolby Vision/HDR10 enabled; cleanup must not restore the earlier disabled list. The signed 0.1.10 APK uses the existing production certificate, version code 11. APK checks found neither private session data nor debug playback intent strings. Raw comparison records remain in ignored `evidence/private/release-comparison/`. The new benchmark scripts reject debuggable APKs and require `speed-profile`, so functional debug results cannot be mistaken for release performance evidence. The user explicitly authorized leaving Dolby Vision/HDR10 enabled; cleanup must not restore the earlier disabled list.
The actual non-debuggable release was also opened through Search and title details and played the 4K HEVC fixture from the beginning. Playback reached PLAYING/READY in 2.565 seconds; the recorded 30-second steady sample had zero BUFFERING transitions and one READY event. A preceding one-minute session also completed without a second READY event, but its harness incorrectly expected Home instead of the originating details page, so it is not counted as a fully completed benchmark. The corrected run returned normally and restored the exact previous resume point with the watched count unchanged. This checks real release playback, rather than ignored debug test intents. The actual non-debuggable release was also opened through Search and title details and played the 4K HEVC fixture from the beginning. Playback reached PLAYING/READY in 2.565 seconds; the recorded 30-second steady sample had zero BUFFERING transitions and one READY event. A preceding one-minute session also completed without a second READY event, but its harness incorrectly expected Home instead of the originating details page, so it is not counted as a fully completed benchmark. The corrected run returned normally and restored the exact previous resume point with the watched count unchanged. This checks real release playback, rather than ignored debug test intents.
## Silo-style browse and details redesign - 2026-10-28
Verified on the onn with the profiled release (baseline profile installed, `speed-profile` compiled). The first Home version used AnimatedVisibility/AnimatedContent and read the hero mode in the catalog's composition; `profile_home.py` failed at p95 39.9 ms, and atrace showed recomposition and layout on nearly every frame plus one 44 ms frame on entry. Driving the header, copy and artwork fades from single animations read only in graphics layers, and keeping the invisible preview composed under the hero, brought five hero → Continue Watching transitions to median 16.9 ms, p95 25.1 ms and none above 33.34 ms (the pre-redesign baseline was p95 28.6 ms). `repro_runtime.py browse` passed at Movies p95 31–34 ms; a 1280 × 720 preview frame raised it to 36 ms through larger texture uploads and was not kept. Moving along a season's episode row measured p95 32 ms. `verify_ui.py browse` (8 checks), `repro_runtime.py sections`, `verify_settings.py`, `verify_details_layout.py` and `verify_movie_details.py` passed. The last two needed their library navigation updated for the genre/sort filter row; titles shown as title art are now read from their content description. `verify_details.py` and the live playback suites were not run: they change Plex state, and `verify_details.py` still expects Mark watched directly after Watch next on shows. The player title area was observed during a brief accidental playback, which Plex did not record as progress.
## Kaleidoscope startup animation - 2026-10-31
The iris was replaced with Kaleido Desktop's kaleidoscope (approved there from a canvas prototype): a mirrored field of shards turns and gathers into the six facets, then the existing fly-through exit, zoomed 30× instead of 52× because the mark is larger than the old lockup. The gather is fastest at its start, so the TV keeps the iris's safeguard: a 260 ms still, faint shard field that holds (at most 700 ms) until `busy` clears and four steady frames arrive. The Compose port draws only paths and gradients (Screen and Plus blend modes); there is no blur.
On the onn with the profiled release, a screen recording of a cold start (ignored `evidence/private/splash-kaleidoscope/`) showed the still field for about 0.8 s, the gather, the settled mark and the reveal into Home. Framestats from three cold starts, bucketed per 250 ms: the 75–190 ms frames fall in the first 0.75 s, inside the hold; during the gather runs 1–2 completed every frame within 26 ms at 15 frames per bucket, and run 3 had a few 30–41 ms frames with 13–15 frames per bucket. Frames from about 2.25 s include Home appearing beneath and reach 42–69 ms, as with the iris. GPU time stayed below 12 ms at p99. These are device samples, not a guarantee; the Fire TV and TCL were not measured. `Build.ps1 -Release -Test` and `repro_runtime.py sections` passed, and the optimized release was left on Home.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 390 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1 MiB

After

Width:  |  Height:  |  Size: 191 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 215 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 313 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

After

Width:  |  Height:  |  Size: 286 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 302 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 294 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 210 KiB

Before After
Before After

View file

@ -1,9 +1,12 @@
"""Stage a locally signed APK for Git distribution and tag-triggered Forgejo releases.""" """Stage a locally signed APK for Git distribution and tag-triggered Forgejo releases."""
import hashlib, json, pathlib, re, shutil, subprocess import hashlib, json, pathlib, re, shutil, subprocess
ROOT=pathlib.Path(__file__).resolve().parents[1] ROOT=pathlib.Path(__file__).resolve().parents[1]
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().splitlines() if '=' in l) version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l)
apk=ROOT/'app/build/outputs/apk/release/app-release.apk' apk=ROOT/'app/build/outputs/apk/release/app-release.apk'
if not apk.exists():raise SystemExit('Run Build.ps1 -Release first.') if not apk.exists():raise SystemExit('Run Build.ps1 -Release first.')
# The APK left by an earlier build must not be published under this version's name.
from verify_distribution import check_apk
check_apk(apk,version['versionName'],int(version['versionCode']))
out=ROOT/'distribution';out.mkdir(exist_ok=True) out=ROOT/'distribution';out.mkdir(exist_ok=True)
shutil.copyfile(apk,out/'Kaleido.apk') shutil.copyfile(apk,out/'Kaleido.apk')
digest=hashlib.sha256(apk.read_bytes()).hexdigest() digest=hashlib.sha256(apk.read_bytes()).hexdigest()
@ -11,8 +14,8 @@ digest=hashlib.sha256(apk.read_bytes()).hexdigest()
repo='https://git.elijahkuntz.com/Elijah/Kaleido' repo='https://git.elijahkuntz.com/Elijah/Kaleido'
tag='v'+version['versionName'] tag='v'+version['versionName']
# Only this version's section, matching the release body the app shows as notes. # Only this version's section, matching the release body the app shows as notes.
changelog=(ROOT/'CHANGELOG.md').read_text() if (ROOT/'CHANGELOG.md').exists() else '' changelog=(ROOT/'CHANGELOG.md').read_text(encoding='utf-8') if (ROOT/'CHANGELOG.md').exists() else ''
section=re.search(r'^## v?'+re.escape(version['versionName'])+r'[ \t]*$(.*?)(?=^## |\Z)',changelog,re.M|re.S) section=re.search(r'^## v?'+re.escape(version['versionName'])+r'[ \t]*$(.*?)(?=^## |\Z)',changelog,re.M|re.S)
manifest={'version':version['versionName'],'versionCode':int(version['versionCode']),'url':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk','checksumUrl':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk.sha256','notes':section.group(1).strip() if section else ''} manifest={'version':version['versionName'],'versionCode':int(version['versionCode']),'url':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk','checksumUrl':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk.sha256','notes':section.group(1).strip() if section else ''}
(out/'latest.json').write_text(json.dumps(manifest,indent=2)+'\n') (out/'latest.json').write_text(json.dumps(manifest,indent=2)+'\n',encoding='utf-8')
print('Packaged',tag,'SHA-256',digest) print('Packaged',tag,'SHA-256',digest)

View file

@ -37,8 +37,18 @@ def summarize(rows,period):
# 300 ms, is idle time (on weak GPUs every frame's latency exceeds one interval). # 300 ms, is idle time (on weak GPUs every frame's latency exceeds one interval).
skipped=sum(max(0,round((b['IntendedVsync']-a['IntendedVsync'])/period)-1) for a,b in zip(rows,rows[1:]) skipped=sum(max(0,round((b['IntendedVsync']-a['IntendedVsync'])/period)-1) for a,b in zip(rows,rows[1:])
if a['FrameCompleted']-a['IntendedVsync']>period and b['IntendedVsync']-a['IntendedVsync']<3e8) if a['FrameCompleted']-a['IntendedVsync']>period and b['IntendedVsync']-a['IntendedVsync']<3e8)
# What the viewer sees: refreshes that repeated the previous frame while frames kept coming.
# Buffer stuffing hides many slow UI frames, so this is stricter than latency and catches
# stalls the heuristic above misses. Invalid present times (0 or before the vsync) are skipped.
# A gap longer than ~6 frames counts only when the frame before it ran long enough to cause it;
# otherwise nothing was animating (e.g. a later image arriving after an idle pause).
shown=[r for r in rows if r.get('DisplayPresentTime',0)>r['IntendedVsync']]
def stalled(a,b):
gap=b['DisplayPresentTime']-a['DisplayPresentTime']
return 0<gap<3e8 and (gap<=6.5*period or a['FrameCompleted']-a['IntendedVsync']>=gap-period)
dropped=sum(max(0,round((b['DisplayPresentTime']-a['DisplayPresentTime'])/period)-1) for a,b in zip(shown,shown[1:]) if stalled(a,b))
pick=lambda v,p:v[min(len(v)-1,int((len(v)-1)*p))] pick=lambda v,p:v[min(len(v)-1,int((len(v)-1)*p))]
return {'frames':len(rows),'skipped':skipped,'median':round(pick(latency,.5),1),'p95':round(pick(latency,.95),1), return {'frames':len(rows),'skipped':skipped,'dropped':dropped,'median':round(pick(latency,.5),1),'p95':round(pick(latency,.95),1),
'max':round(latency[-1],1),'uiMax':round(ui[-1],1)} 'max':round(latency[-1],1),'uiMax':round(ui[-1],1)}
def measure(name,code,expect,window,results): def measure(name,code,expect,window,results):
@ -90,10 +100,10 @@ def main():
measure('tabs: home <- movies',21,lambda r:focus(r)=='Home',args.window*2,results) measure('tabs: home <- movies',21,lambda r:focus(r)=='Home',args.window*2,results)
summary={} summary={}
for name,runs in results.items(): for name,runs in results.items():
summary[name]={'skipped':[r['skipped'] for r in runs],'p95':max(r.get('p95',0) for r in runs),'max':max(r.get('max',0) for r in runs),'uiMax':max(r.get('uiMax',0) for r in runs)} summary[name]={'dropped':[r.get('dropped',0) for r in runs],'skipped':[r['skipped'] for r in runs],'p95':max(r.get('p95',0) for r in runs),'max':max(r.get('max',0) for r in runs),'uiMax':max(r.get('uiMax',0) for r in runs)}
report={'device':DEVICE,'transitions':summary,'runs':results} report={'device':DEVICE,'transitions':summary,'runs':results}
(OUT/f'transitions-{args.label}.json').write_text(json.dumps(report,indent=2)+'\n') (OUT/f'transitions-{args.label}.json').write_text(json.dumps(report,indent=2)+'\n')
print('\nSUMMARY',args.label,DEVICE) print('\nSUMMARY',args.label,DEVICE)
for name,s in summary.items():print(f" {name:28} skipped={s['skipped']} p95={s['p95']} max={s['max']} uiMax={s['uiMax']}") for name,s in summary.items():print(f" {name:28} dropped={s['dropped']} skipped={s['skipped']} p95={s['p95']} max={s['max']} uiMax={s['uiMax']}")
if __name__=='__main__':main() if __name__=='__main__':main()

View file

@ -3,14 +3,14 @@ import hashlib, json, os, pathlib, re, urllib.request, uuid
ROOT=pathlib.Path(__file__).resolve().parents[1] ROOT=pathlib.Path(__file__).resolve().parents[1]
API='https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido' API='https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido'
token=os.environ['KALEIDO_RELEASE_TOKEN'] token=os.environ['KALEIDO_RELEASE_TOKEN']
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().splitlines() if '=' in l) version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l)
tag='v'+version['versionName'] tag='v'+version['versionName']
ref=os.environ.get('RELEASE_REF','') ref=os.environ.get('RELEASE_REF','')
assert ref=='refs/tags/'+tag,'Tag must match version.properties exactly' assert ref=='refs/tags/'+tag,'Tag must match version.properties exactly'
out=ROOT/'distribution' out=ROOT/'distribution'
def notes(): def notes():
"""Only this version's changelog section; the app shows the body as release notes.""" """Only this version's changelog section; the app shows the body as release notes."""
text=(ROOT/'CHANGELOG.md').read_text() text=(ROOT/'CHANGELOG.md').read_text(encoding='utf-8')
m=re.search(r'^## v?'+re.escape(version['versionName'])+r'[ \t]*$(.*?)(?=^## |\Z)',text,re.M|re.S) m=re.search(r'^## v?'+re.escape(version['versionName'])+r'[ \t]*$(.*?)(?=^## |\Z)',text,re.M|re.S)
return m.group(1).strip() if m else '' return m.group(1).strip() if m else ''
assert hashlib.sha256((out/'Kaleido.apk').read_bytes()).hexdigest()==(out/'Kaleido.apk.sha256').read_text().split()[0] assert hashlib.sha256((out/'Kaleido.apk').read_bytes()).hexdigest()==(out/'Kaleido.apk.sha256').read_text().split()[0]

View file

@ -105,24 +105,28 @@ def credits():
marker=next(m for m in item['Marker'] if m['type']=='credits') marker=next(m for m in item['Marker'] if m['type']=='credits')
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c') adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(marker['startTimeOffset']+2000),'--ei','testMode','2','--ez','testValidation','true') adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(marker['startTimeOffset']+2000),'--ei','testMode','2','--ez','testValidation','true')
await_ready(7599);key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits') await_ready(7599)
def log():return adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
# Automatic credits open Up Next at once; with "Show button" the Skip credits button opens it.
deadline=time.monotonic()+4
while time.monotonic()<deadline and 'POSTPLAY focus=play' not in log():time.sleep(.2)
if 'POSTPLAY focus=play' not in log():
key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits')
screenshot('skip-credits-contrast');key(23) screenshot('skip-credits-contrast');key(23)
deadline=time.monotonic()+8 deadline=time.monotonic()+8
while time.monotonic()<deadline: while time.monotonic()<deadline and 'POSTPLAY focus=play' not in log():time.sleep(.1)
time.sleep(.1) assert 'POSTPLAY focus=play' in log(),'Up Next initial action never received focus'
ready=adb('logcat','-d','-s','KaleidoPlayback:I','*:S').decode(errors='replace') screenshot('up-next')
if 'POSTPLAY focus=play' in ready:break key(20) # any press stops the countdown
assert 'POSTPLAY focus=play' in ready,'Postplay initial action never received focus' time.sleep(6);root=snapshot();found=labels(root)
key(22);key(23) assert 'Up next' in found or 'UP NEXT' in found,'Cancellation failed to keep Up Next open'
wait(lambda r:'Autoplay off' in labels(r),'Autoplay cancellation') assert any(l.startswith('Season ') for l in found),'Season episodes absent'
screenshot('postplay-season-and-related');time.sleep(6) assert 'Related shows' in found,'Related shows absent'
root=snapshot();assert 'Up next' in labels(root),'Cancellation failed to keep postplay open' logs=log()
assert 'Episodes in this season' in labels(root),'Season episodes absent' assert 'AUTOPLAY cancelled' in logs and 'AUTOPLAY starting' not in logs,'Cancelled autoplay still advanced'
assert 'Related shows' in labels(root),'Related shows absent' key(4);time.sleep(1)
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace') assert 'POSTPLAY closed' in log(),'Back did not return to the video'
assert 'reason=skip-credits' in logs,'Skip credits did not open postplay' (OUT/'postplay-cancel.log').write_text(log())
assert 'AUTOPLAY starting' not in logs,'Cancelled autoplay still advanced' print('PASS credits -> Up Next, episode/related rows, any press stops autoplay, Back returns to video')
(OUT/'postplay-cancel.log').write_text(logs)
print('PASS skip credits -> postplay, episode/related rows, cancellable autoplay')
if __name__=='__main__':globals()[sys.argv[1]]() if __name__=='__main__':globals()[sys.argv[1]]()

View file

@ -26,7 +26,7 @@ def main():
label,setup,measured=sys.argv[1],sys.argv[2],sys.argv[3] label,setup,measured=sys.argv[1],sys.argv[2],sys.argv[3]
launch() launch()
for code in filter(None,setup.split(',')):adb('shell','input','keyevent',code);time.sleep(1.2) for code in filter(None,setup.split(',')):adb('shell','input','keyevent',code);time.sleep(1.2)
pid=adb('shell','pidof','tv.kaleido.app').decode().split()[0] pid=adb("shell","pidof","tv.kaleido.app").decode().split()[0];time.sleep(float(__import__("os").environ.get("KALEIDO_SETTLE","0")))
time.sleep(1) time.sleep(1)
adb('shell','atrace','--async_start','-b','16384','-a','tv.kaleido.app','gfx','view','sched','dalvik') adb('shell','atrace','--async_start','-b','16384','-a','tv.kaleido.app','gfx','view','sched','dalvik')
for code in measured.split(','):adb('shell','input','keyevent',code);time.sleep(1.5) for code in measured.split(','):adb('shell','input','keyevent',code);time.sleep(1.5)

View file

@ -34,6 +34,7 @@ def main():
parser.add_argument('--expect-width',type=int) parser.add_argument('--expect-width',type=int)
parser.add_argument('--expect-channels',type=int) parser.add_argument('--expect-channels',type=int)
parser.add_argument('--expect-audio-encoding',type=int) parser.add_argument('--expect-audio-encoding',type=int)
parser.add_argument('--fail-on-audio-underrun',action='store_true')
args=parser.parse_args() args=parser.parse_args()
folder=OUT/'playback-validation'/('onn' if DEVICE=='192.168.50.195:5555' else 'tcl')/args.label folder=OUT/'playback-validation'/('onn' if DEVICE=='192.168.50.195:5555' else 'tcl')/args.label
folder.mkdir(parents=True,exist_ok=True) folder.mkdir(parents=True,exist_ok=True)
@ -111,11 +112,13 @@ def main():
'errors':[r['code'] for r in records if r['event']=='error'],'errorDetails':[r for r in records if r['event'] in ('error','prepareFailure')],'finalSample':last,'seek':seek_result, 'errors':[r['code'] for r in records if r['event']=='error'],'errorDetails':[r for r in records if r['event'] in ('error','prepareFailure')],'finalSample':last,'seek':seek_result,
'expectsVideo':expects_video,'videoRendered':not expects_video or any(r.get('videoCounters',{}).get('rendered',0)>5 for r in samples), 'expectsVideo':expects_video,'videoRendered':not expects_video or any(r.get('videoCounters',{}).get('rendered',0)>5 for r in samples),
'closed':any(r['event']=='closed' for r in records),'before':watched(before),'after':watched(after), 'closed':any(r['event']=='closed' for r in records),'before':watched(before),'after':watched(after),
'audioUnderruns':[r for r in records if r['event']=='audioUnderrun'],
'transport':'private-local-fixture' if args.fixture else 'Plex','progressUnchanged':None if args.fixture else watched(before)==watched(after)} 'transport':'private-local-fixture' if args.fixture else 'Plex','progressUnchanged':None if args.fixture else watched(before)==watched(after)}
(folder/'result.json').write_text(json.dumps(result,indent=2)) (folder/'result.json').write_text(json.dumps(result,indent=2))
print(json.dumps({k:result[k] for k in ('label','readySeconds','firstFrame','audioAdvancing','videoDecoders','errors','progressUnchanged')}),flush=True) print(json.dumps({k:result[k] for k in ('label','readySeconds','firstFrame','audioAdvancing','videoDecoders','errors','progressUnchanged')}),flush=True)
print('Output:',last.get('video'),last.get('audio'),'mode:',last.get('mode'),'seek:',seek_result,flush=True) print('Output:',last.get('video'),last.get('audio'),'mode:',last.get('mode'),'seek:',seek_result,flush=True)
if ready is None:raise SystemExit('Playback did not become ready; see private evidence') if ready is None:raise SystemExit('Playback did not become ready; see private evidence')
if args.fail_on_audio_underrun and result['audioUnderruns']:raise SystemExit('Audio underrun detected; see private evidence')
if not result['closed']:raise SystemExit('Player did not close cleanly') if not result['closed']:raise SystemExit('Player did not close cleanly')
if result['progressUnchanged'] is False:raise SystemExit('Unexpected progress change; see before/after evidence') if result['progressUnchanged'] is False:raise SystemExit('Unexpected progress change; see before/after evidence')
if args.seek and not seek_result['correct']:raise SystemExit('Seek did not reach the expected absolute position') if args.seek and not seek_result['correct']:raise SystemExit('Seek did not reach the expected absolute position')

120
scripts/verify_040.py Normal file
View file

@ -0,0 +1,120 @@
"""Only 0.4.0 UI changes: TV artwork, category cards, Clear, and quick skip cues."""
import argparse, json, time, urllib.parse, urllib.request
from contextlib import contextmanager
from device import ROOT, adb, screenshot
from verify_ui import launch, key, focused, wait, focus, labels, snapshot, text, passed, position
def search_title(query, expected):
launch(); key(22, 3); focused('Search'); key(23)
focused('Movies, shows, episodes, people')
adb('shell', 'input', 'text', query)
wait(lambda r: expected in labels(r), 'Search fixture '+expected)
key(66); focused(expected)
def search_check():
search_title('hazbin', 'Hazbin Hotel')
key(23); text('Seasons'); key(4); focused('Hazbin Hotel')
# Return to the field, then Right at the end reaches Clear.
key(19)
wait(lambda r: focus(r)=='hazbin', 'Search field above results')
key(4) # Close the Android TV keyboard before navigating app buttons.
key(22); focused('Clear'); screenshot('040-search-clear')
key(23)
root=wait(lambda r:'Movies, shows, episodes, people' in labels(r), 'Clear resets results')
assert 'Hazbin Hotel' not in labels(root)
assert 'Your collection' not in labels(root) and 'Find something worth watching.' not in labels(root)
assert all('Voice search' not in n.get('content-desc','') for n in root.iter('node'))
assert not any(n.get('text')=='Clear' for n in root.iter('node'))
adb('shell', 'input', 'text', 'silo'); text('TV shows'); key(66); focused('Silo')
screenshot('040-search-new-query')
passed('Clear removes query/results, restores typing, and microphone is absent')
def details_check():
search_title('hazbin', 'Hazbin Hotel'); key(23); text('Seasons')
screenshot('040-show-artwork')
# Initial show entry may have its first season focused already.
if 'Season 1' not in focus(snapshot()):key(20)
focused('Season 1'); key(23)
wait(lambda r:'Hazbin Hotel' in labels(r) and 'Season 1' in labels(r), 'Season details')
screenshot('040-season-artwork')
root=snapshot()
assert any(n.get('content-desc')=='Back' for n in root.iter('node'))
# Moving across episode cards retains the fixed header and useful focus.
if not any(x in focus(root) for x in ['Dad Beat Dad','Hello Rosie','Overture']):key(20)
before=focus(snapshot()); key(22); after=focus(snapshot())
assert before!=after and after, 'Episode selection must move'
screenshot('040-season-next-episode')
key(4); focused('Season 1')
passed('Hazbin show/season art captured; episode movement and Back focus preserved')
def categories_check():
for moves, name in [(1, 'Movies'), (2, 'TV Shows')]:
launch(); key(22, moves); focused(name); key(20); focused('Discover')
key(22, 2); focused('Categories'); key(23)
wait(lambda r:focus(r) not in ('','Categories'), 'Category entry')
root=snapshot()
assert not any(x in labels(root) for x in ['FILM','SERIES']), 'Categories must only label genres'
assert not any(x in labels(root) for x in ['The Batman','Hazbin Hotel']), 'Artwork titles must not appear on categories'
time.sleep(2); screenshot('040-'+name.lower().replace(' ','-')+'-categories')
first=focus(snapshot()); key(22); second=focus(snapshot())
assert first!=second
key(20); below=focus(snapshot()); assert below!=second
key(19); focused(second); key(21); focused(first)
key(23)
wait(lambda r:any('titles' in s for s in labels(r)), 'Scoped category results')
key(4); focused(first)
passed(name+' artwork cards: horizontal/vertical navigation, open and Back restoration')
@contextmanager
def preserve_movie_progress():
cfg=dict(l.split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#'))
server=cfg['PLEX_SERVER_URL'].strip('"\'').rstrip('/')
headers={'X-Plex-Token':cfg['PLEX_TOKEN'].strip('"\''),'Accept':'application/json'}
def request(path, params=None):
url=server+path+('?' + urllib.parse.urlencode(params) if params else '')
with urllib.request.urlopen(urllib.request.Request(url,headers=headers),timeout=30) as response:return response.read()
original=json.loads(request('/library/metadata/9776'))['MediaContainer']['Metadata'][0]
try:yield
finally:
adb('shell','am','force-stop','tv.kaleido.app');time.sleep(.4)
# testValidation suppresses Plex timeline/scrobble writes. Verify that contract.
restored=json.loads(request('/library/metadata/9776'))['MediaContainer']['Metadata'][0]
assert restored.get('viewOffset',0)==original.get('viewOffset',0), 'Preserve fixture progress'
assert restored.get('viewCount',0)==original.get('viewCount',0), 'Preserve watched state'
def skip_check():
with preserve_movie_progress():quick_skip_check()
def quick_skip_check():
adb('shell','am','force-stop','tv.kaleido.app'); adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true')
deadline=time.monotonic()+45
while 'READY item=9776' not in adb('logcat','-d','-s','KaleidoPlayback:I').decode(errors='replace'):
assert time.monotonic()<deadline, 'Playback ready'; time.sleep(.5)
key(127); focused('Play'); key(4); time.sleep(.4)
before=position()
adb('shell','input','keyevent','22'); time.sleep(.16); screenshot('040-skip-forward')
time.sleep(1.3); after=position()
assert 8500<=after-before<=11500, (before,after)
adb('shell','input','keyevent','21'); time.sleep(.16); screenshot('040-skip-back')
time.sleep(1.3); back=position(); assert abs(back-before)<1600, (before,back)
adb('shell','input','keyevent','22'); adb('shell','input','keyevent','22')
time.sleep(.12); screenshot('040-skip-repeated'); time.sleep(1.4)
assert 18500<=position()-back<=21500, 'Repeated taps must accumulate'
root=snapshot(); assert '2 Fast 2 Furious' not in labels(root), 'Cue must leave controls hidden'
key(23); focused('Play'); key(19); focused('Playback timeline')
key(22); key(20); focused('Play')
key(4); key(4)
passed('Actual +/-10s and repeated +20s seeks; cue screenshots; timeout and timeline coexist')
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('check',choices=['search','details','categories','skip'])
globals()[parser.parse_args().check+'_check']()

View file

@ -0,0 +1,105 @@
"""Validate optional themes and the normal audio path on the authorized onn; restore the prior audio preferences."""
import re,time,sys,xml.etree.ElementTree as ET
from device import adb,OUT,screenshot
from verify_ui import launch,key,text,focused,focus,snapshot,labels,wait,passed
def settings(category):
launch();key(22,4);focused('Settings');key(23);focused('Switch account')
key(21);focused('Connection');key(20,category);key(22)
def choose(options,value):
key(23)
current=focus(snapshot())
assert current in options,(current,options)
delta=options.index(value)-options.index(current)
key(20 if delta>=0 else 19,abs(delta));focused(value);key(23)
def logs():return adb('logcat','-d','-s','KaleidoTheme:I','KaleidoPlayback:I','*:S').decode(errors='replace')
def wait_log(fragment,timeout=40):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
value=logs()
if fragment in value:return value
time.sleep(.5)
raise AssertionError('Missing log '+fragment)
def open_silo():
launch();key(22,3);focused('Search');key(23);text('Search')
adb('shell','input','text','silo')
text('TV shows');key(66);focused('Silo');key(23);text('Seasons')
if __name__=='__main__':
playback_only='--playback-only' in sys.argv
original_xml=None
if playback_only:
# UI preferences and persistence are checked separately; isolate the playback batch
# using only this debug app's private preferences, with byte-for-byte restoration.
original_xml=adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')
(OUT/'030-audio-original-preferences.xml').write_bytes(original_xml)
tree=ET.fromstring(original_xml)
for name,kind,value in [('themeMusic','boolean','true'),('themeVolume','int','20')]:
node=next((n for n in tree if n.get('name')==name),None)
if node is None:node=ET.SubElement(tree,kind,{'name':name})
node.set('value',value)
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > shared_prefs/preferences.xml"',data=ET.tostring(tree,encoding='utf-8',xml_declaration=True))
else:
settings(3);focused('Navigation sounds');key(20);focused('Theme music')
original_on=focus(snapshot()).endswith('On')
if not original_on:key(23)
key(20);focused('Theme music volume')
original_volume=re.search(r'(\d+)%$',focus(snapshot())).group(1)+'%'
choose([str(n)+'%' for n in range(10,101,10)],'20%');focused('Theme music volume')
settings(3);key(20);focused('Theme music');assert focus(snapshot()).endswith('On')
key(20);focused('Theme music volume');assert focus(snapshot()).endswith('20%')
screenshot('030-theme-settings')
passed('Theme toggle and theme volume persist through cold starts; dialogs restore focus')
try:
adb('logcat','-c');open_silo();wait_log('KaleidoTheme: READY volume=20%')
screenshot('030-silo-theme')
adb('logcat','-c');key(3);wait_log('STOP')
# Launchers may reopen Home rather than restore the previous Activity task.
# Enter the title through the normal remote flow before expecting music again.
open_silo();wait_log('PLAYING')
passed('Theme stops in the background and plays again on a title page')
# Show -> season -> neighbouring episode selection all retain a supported theme.
key(20)
wait(lambda r:'Season' in focus(r),'Season receives focus');key(23)
wait(lambda r:any(t=='Episodes' or t.startswith(('Play','Resume')) for t in labels(r)),'Season episode header')
wait_log('KaleidoTheme: READY volume=20%')
passed('Series and season/episode detail pages play the real inherited Plex theme')
# Actual video uses validation mode, which avoids changing Plex progress.
adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','0','--ez','testValidation','true')
wait_log('STOP');wait_log('READY item=7599')
time.sleep(4)
audit=adb('shell','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl')
(OUT/'030-audio-validation.jsonl').write_bytes(audit)
import json
events=[json.loads(line) for line in audit.decode().splitlines()]
assert any(e.get('event')=='audioAdvancing' for e in events),'Decoded audio must advance'
assert any(e.get('event')=='firstFrame' for e in events),'Video must render'
passed('Theme stops for actual video; audio and video advance')
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true')
wait_log('READY item=9776');time.sleep(4)
movie_audit=adb('shell','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl')
(OUT/'030-audio-movie-validation.jsonl').write_bytes(movie_audit)
movie_events=[json.loads(line) for line in movie_audit.decode().splitlines()]
assert any(e.get('event')=='audioAdvancing' for e in movie_events)
assert any(e.get('event')=='firstFrame' for e in movie_events)
passed('A real Plex-converted movie renders audio and video')
adb('shell','am','force-stop','tv.kaleido.app')
finally:
if playback_only:
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > shared_prefs/preferences.xml"',data=original_xml)
assert adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')==original_xml
else:
settings(3);key(20);focused('Theme music')
if focus(snapshot()).endswith('On')!=original_on:key(23)
key(20);focused('Theme music volume');choose([str(n)+'%' for n in range(10,101,10)],original_volume)
launch()
(OUT/'030-audio.log').write_text(logs())
passed('Prior theme preferences restored; device returned to Home')

View file

@ -45,7 +45,7 @@ def main():
screenshot('details-cast-restored') screenshot('details-cast-restored')
results.append('Actor titles match both Plex libraries; title and cast focus restore');print('PASS '+results[-1],flush=True) results.append('Actor titles match both Plex libraries; title and cast focus restore');print('PASS '+results[-1],flush=True)
key(4);key(4);focused('Home');key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23) key(4);key(4);focused('Home');key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Show library filters loaded');focused('Library');key(20) wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Show library filters loaded');focused('Library');key(20)
if show['title'] not in focus(snapshot()):key(21) if show['title'] not in focus(snapshot()):key(21)
focused(show['title']);key(23) focused(show['title']);key(23)
text('Seasons');focused('Watch next');text('Mark watched');key(22);focused('Mark watched');touched.add(SHOW);key(23);focused('Mark unwatched') text('Seasons');focused('Watch next');text('Mark watched');key(22);focused('Mark watched');touched.add(SHOW);key(23);focused('Mark unwatched')

View file

@ -4,11 +4,16 @@ from device import screenshot
from verify_ui import launch,key,focused,wait,focus,labels,snapshot from verify_ui import launch,key,focused,wait,focus,labels,snapshot
launch();key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23) launch();key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Show library loaded');focused('Library');key(20) wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Show library loaded');focused('Library');key(20)
if '3 Body Problem' not in focus(snapshot()):key(21) # The genre/sort filters sit between the section tabs and the grid.
if focus(snapshot()).startswith('Unwatched'):key(20)
# The grid is entered beneath the filter that held focus; walk back to the first column.
for _ in range(6):
if '3 Body Problem' in focus(snapshot()):break
key(21)
focused('3 Body Problem');key(23);focused('Watch next') focused('3 Body Problem');key(23);focused('Watch next')
root=snapshot();screenshot('show-layout-current') root=snapshot();screenshot('show-layout-current')
title=next(n for n in root.iter('node') if n.get('text')=='3 Body Problem') title=next(n for n in root.iter('node') if '3 Body Problem' in (n.get('text'),n.get('content-desc')))
bounds=list(map(int,re.findall(r'\d+',title.get('bounds')))) bounds=list(map(int,re.findall(r'\d+',title.get('bounds'))))
back=next((n for n in root.iter('node') if n.get('content-desc')=='Back'),None) back=next((n for n in root.iter('node') if n.get('content-desc')=='Back'),None)
print('Title bounds:',bounds,'Back visible:',back is not None,flush=True) print('Title bounds:',bounds,'Back visible:',back is not None,flush=True)

View file

@ -0,0 +1,56 @@
"""Check that an APK really is the release it is published as.
Used by package_release.py before staging, and by CI against the checked-in distribution:
a stale or debug APK must not pass because its checksum and manifest were regenerated around it.
"""
import argparse, hashlib, json, os, pathlib, re, shutil, subprocess, sys
ROOT=pathlib.Path(__file__).resolve().parents[1]
PACKAGE='tv.kaleido.app'
def properties():
return dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l)
def aapt2():
names=['aapt2.exe','aapt2'] if os.name=='nt' else ['aapt2']
roots=[ROOT/'.tools/sdk']+[pathlib.Path(os.environ[k]) for k in ('ANDROID_HOME','ANDROID_SDK_ROOT') if os.environ.get(k)]
for root in roots:
tools=sorted((root/'build-tools').glob('*'),key=lambda p:[int(x) if x.isdigit() else 0 for x in p.name.split('.')],reverse=True) if (root/'build-tools').is_dir() else []
for folder in tools:
for name in names:
if (folder/name).is_file():return str(folder/name)
found=shutil.which('aapt2')
if found:return found
raise SystemExit('aapt2 was not found. Install Android build-tools or set ANDROID_HOME.')
def badging(apk):
"""(package, versionName, versionCode, debuggable) from the APK's own manifest."""
out=subprocess.run([aapt2(),'dump','badging',str(apk)],capture_output=True,text=True,check=True).stdout
m=re.search(r"^package: name='([^']+)' versionCode='(\d+)' versionName='([^']+)'",out,re.M)
if not m:raise SystemExit(f'Could not read the version of {apk}.')
return m.group(1),m.group(3),int(m.group(2)),'application-debuggable' in out
def check_apk(apk,version_name,version_code):
package,name,code,debuggable=badging(apk)
problems=[]
if package!=PACKAGE:problems.append(f'package is {package}, expected {PACKAGE}')
if (name,code)!=(version_name,version_code):problems.append(f'APK is {name} ({code}), expected {version_name} ({version_code}); rebuild it')
if debuggable:problems.append('APK is a debuggable build, not the release')
if problems:raise SystemExit(f'{apk}: '+'; '.join(problems)+'.')
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--release',action='store_true',help='also require the distribution to match version.properties (tag builds)')
args=parser.parse_args()
out=ROOT/'distribution';apk=out/'Kaleido.apk'
if not apk.exists():print('No distribution to verify.');return
digest=hashlib.sha256(apk.read_bytes()).hexdigest()
if (out/'Kaleido.apk.sha256').read_text().split()[0]!=digest:raise SystemExit('Kaleido.apk does not match Kaleido.apk.sha256.')
manifest=json.loads((out/'latest.json').read_text(encoding='utf-8'))
check_apk(apk,manifest['version'],int(manifest['versionCode']))
if args.release:
version=properties()
if (manifest['version'],int(manifest['versionCode']))!=(version['versionName'],int(version['versionCode'])):
raise SystemExit('distribution/latest.json does not match version.properties; run scripts/package_release.py.')
print('Distribution verified:',manifest['version'],f"({manifest['versionCode']})",'SHA-256',digest)
if __name__=='__main__':main()

View file

@ -0,0 +1,21 @@
"""Reproduce only the Continue Watching episode-row reentry focus regression."""
from device import screenshot
from verify_ui import launch,key,snapshot,focus,focused,labels,wait
launch();key(20,2)
for _ in range(20):
if 'Hazbin Hotel' in focus(snapshot()):break
key(22)
else:raise AssertionError('Hazbin Hotel fixture is missing from Continue Watching')
focused('S1 · E7');key(23);focused('Resume from')
key(20);focused('7. Hello Rosie!')
key(21,7);focused('1. Overture')
assert '7. Hello Rosie!' not in labels(snapshot()),'Episode 7 must be offscreen before leaving'
key(4);focused('Hazbin Hotel');key(23);focused('Resume from')
wait(lambda r:'7. Hello Rosie!' in labels(r),'Reopened row reveals the entry episode')
key(20);focused('7. Hello Rosie!')
screenshot('episode-row-reentry-031')
print('PASS Home → Hazbin S1E7 → episode 1 → Back → reopen → Down focuses episode 7',flush=True)
key(4);focused('Hazbin Hotel');key(4)
wait(lambda r:focus(r) in ('Play','Resume'),'Home hero focus')
key(19);focused('Home')

View file

@ -0,0 +1,77 @@
"""Read-only D-pad checks for exact search, scoped genres and jumps beyond the first catalog page."""
import json,time,urllib.parse,urllib.request
from device import ROOT,adb,screenshot
from verify_ui import launch,key,text,focused,focus,snapshot,labels,wait,passed
LETTERS=['#']+list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
def first_at_letter(section,media_type,letter,genre=''):
cfg=dict(l.split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#'))
base=cfg['PLEX_SERVER_URL'].strip('"\'').rstrip('/')
headers={'X-Plex-Token':cfg['PLEX_TOKEN'].strip('"\''),'Accept':'application/json'}
def get(path,params):
request=urllib.request.Request(base+path+'?'+urllib.parse.urlencode(params),headers=headers)
with urllib.request.urlopen(request,timeout=30) as response:return json.load(response)['MediaContainer']
sections=get('/library/sections',{})['Directory']
section=next(s['key'] for s in sections if s['type']==media_type)
params={'type':'1' if media_type=='movie' else '2'}
if genre:
genres=get('/library/sections/'+section+'/genre',{})['Directory']
params['genre']=next(g['key'] for g in genres if g['title']==genre)
chars=get('/library/sections/'+section+'/firstCharacter',params)['Directory']
offset=0
for item in chars:
if item['title']==letter:break
offset+=item['size']
params.update({'sort':'titleSort:asc','X-Plex-Container-Start':offset,'X-Plex-Container-Size':1})
return get('/library/sections/'+section+'/all',params)['Metadata'][0]['title'],offset
def enter_rail():
for _ in range(10):
# A rail entry reports its letter in more than one label, e.g. "# #".
value=(focus(snapshot()).split() or [''])[0]
if value in LETTERS:return value
key(22)
raise AssertionError('Right edge must enter letter bar; focus='+focus(snapshot()))
def jump(letter,expected):
current=enter_rail()
delta=LETTERS.index(letter)-LETTERS.index(current)
key(20 if delta>=0 else 19,abs(delta));focused(letter)
key(23)
# OK keeps the letter selected; Left explicitly enters the target title.
time.sleep(2);focused(letter);key(21);focused(expected)
key(23);wait(lambda r:any(s in labels(r) for s in ['Play','Resume','Seasons','Synopsis']),'Title details open')
key(4);focused(expected)
def section_check(tab,media_type):
launch();key(22,1 if tab=='Movies' else 2);focused(tab)
key(20);focused('Discover');key(22);focused('Library');key(23);focused('Library')
text('Z');screenshot('030-'+media_type+'-library')
key(20);key(20)
expected,offset=first_at_letter('',media_type,'S')
jump('S',expected)
passed(f'{tab} A-Z reaches S at absolute index {offset}, enters title and restores focus')
key(4);focused('Discover');key(22,2);focused('Categories');key(23)
# Genres are server-supplied and alphabetically ordered; move within the first row.
wait(lambda r:focus(r) not in ('','Categories'),'Category tile receives focus')
for _ in range(8):
if focus(snapshot())=='Animation':break
key(22)
focused('Animation');key(23);text('Z')
expected,offset=first_at_letter('',media_type,'S','Animation')
jump('S',expected)
screenshot('030-'+media_type+'-animation-jump')
key(4);focused('Animation');key(4);focused('Discover')
passed(f'{tab} Animation stays scoped and supports letter jump, details Back and category Back')
if __name__=='__main__':
for tab,kind in [('Movies','movie'),('TV Shows','show')]:section_check(tab,kind)
launch()
key(22,3);focused('Search');key(23);text('Search')
adb('shell','input','text','silo')
text('TV shows');key(66);focused('Silo')
# The first reachable result must be the exact series, never the unrelated movie row.
key(23);text('Seasons');screenshot('030-exact-silo-search')
key(4);focused('Silo');key(4);key(4)
passed('Silo search enters the exact series first and restores the result on Back')

View file

@ -4,15 +4,17 @@ from device import screenshot
from verify_ui import launch,key,focused,wait,focus,labels,snapshot from verify_ui import launch,key,focused,wait,focus,labels,snapshot
launch();key(22);focused('Movies');key(20);focused('Discover');key(22);focused('Library');key(23) launch();key(22);focused('Movies');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Movie library loaded') wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Movie library loaded')
key(20) key(20)
wait(lambda r:bool(focus(r)) and focus(r) not in ('Library','Discover') and 'All genres' not in focus(r),'Movie card focus') # The genre/sort filters sit between the section tabs and the grid.
if focus(snapshot()).startswith('Unwatched'):key(20)
wait(lambda r:bool(focus(r)) and focus(r) not in ('Library','Discover') and not focus(r).startswith('Unwatched'),'Movie card focus')
selected=focus(snapshot());key(23) selected=focus(snapshot());key(23)
wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Movie play action') wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Movie play action')
root=snapshot();screenshot('movie-details-0.1.11') root=snapshot();screenshot('movie-details-0.1.11')
back=next((n for n in root.iter('node') if n.get('content-desc')=='Back'),None) back=next((n for n in root.iter('node') if n.get('content-desc')=='Back'),None)
assert back is not None,'Movie Back control must be visible on entry' assert back is not None,'Movie Back control must be visible on entry'
assert any(n.get('text') and n.get('text') in selected and int(re.findall(r'\d+',n.get('bounds'))[1])>=88 for n in root.iter('node')),'Movie title must remain below the safe header' assert any((n.get('text') or n.get('content-desc')) and (n.get('text') or n.get('content-desc')) in selected and int(re.findall(r'\d+',n.get('bounds'))[1])>=88 for n in root.iter('node')),'Movie title must remain below the safe header'
print('PASS movie safe header and initial action focus',flush=True) print('PASS movie safe header and initial action focus',flush=True)
key(20) key(20)
wait(lambda r:focus(r) not in ('Play','') and not focus(r).startswith('Resume'),'Cast or related row focus') wait(lambda r:focus(r) not in ('Play','') and not focus(r).startswith('Resume'),'Cast or related row focus')

View file

@ -0,0 +1,78 @@
"""Focused 0.5 checks: bitrate and actual audio switching, plus show-only Shuffle placement."""
import argparse,json,time,urllib.parse,urllib.request
from device import adb,OUT,screenshot
from inspect_server import get,base,token
from validate_playback import audit
from verify_ui import key,focused,text,wait,labels,focus,snapshot,launch,passed
def wait_for(check,description,timeout=50):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
if check():return
time.sleep(.25)
raise AssertionError(description)
def audio():
item=get('/library/metadata/870')['Metadata'][0]
part=item['Media'][0]['Part'][0]
streams=[s for s in part['Stream'] if s['streamType']==2]
original=next((s for s in streams if s.get('selected')),streams[0])
stereo=next(s for s in streams if s.get('channels')==2)
preferences=adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')
def restore_track():
request=urllib.request.Request(base+'/library/parts/'+str(part['id'])+'?'+urllib.parse.urlencode({'audioStreamID':original['id'],'allParts':1}),method='PUT',headers={'X-Plex-Token':token})
with urllib.request.urlopen(request,timeout=20) as r:assert r.status==200
try:
for mode in (0,2):
restore_track()
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','run-as','tv.kaleido.app','rm','-f','files/playback-validation.jsonl')
print('Checking audio mode',mode,flush=True)
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','870','--el','testOffset','90000','--ei','testMode',str(mode),'--ez','testValidation','true')
wait_for(lambda:any(r['event']=='sample' and r.get('playing') and r.get('position',0)>90000 for r in audit()[1]),'Playback ready')
key(127);focused('Play')
wait_for(lambda:(lambda s:bool(s) and not s[-1]['playing'])([r for r in audit()[1] if r['event']=='sample']),'Playback paused')
key(22,4);focused('Playback options');key(23);focused('Audio ·')
if mode==0:
key(20);focused('Quality ·');key(23);focused('Original quality · 19.1 Mbps')
screenshot('050-original-bitrate');key(4);focused('Quality ·');key(19);focused('Audio ·')
key(23);text('Audio tracks')
screenshot('050-audio-tracks-'+str(mode))
# The selected Plex default receives initial focus.
delta=streams.index(stereo)-streams.index(original)
key(20 if delta>=0 else 19,abs(delta));focused(stereo['displayTitle'])
before=[r for r in audit()[1] if r['event']=='sample'][-1]['position']
key(23);focused('Playback options')
wait_for(lambda:any(r['event']=='selectedTracks' and any(a.get('channels')==2 for a in r.get('audio',[])) for r in audit()[1]),'Stereo track must actually be selected')
wait_for(lambda:(lambda s:bool(s) and s[-1]['state']==3)([r for r in audit()[1] if r['event']=='sample']),'Track switch ready')
samples=[r for r in audit()[1] if r['event']=='sample']
assert not samples[-1]['playing'],'Paused state must survive track switch'
assert abs(samples[-1]['position']-before)<2500,'Track switch must preserve position'
key(126)
wait_for(lambda:(lambda s:bool(s) and s[-1].get('audio',{}).get('channels')==2 and s[-1].get('playing'))([r for r in audit()[1] if r['event']=='sample']),'Selected stereo audio must play')
raw,records=audit();(OUT/('050-track-switch-'+str(mode)+'.jsonl')).write_bytes(raw)
assert not any(r['event']=='error' for r in records)
passed('Actual stereo selection, position and pause preservation in '+('Original' if mode==0 else 'Plex conversion'))
finally:
adb('shell','am','force-stop','tv.kaleido.app');restore_track()
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > shared_prefs/preferences.xml"',data=preferences)
def show():
launch();key(22,3);focused('Search');key(23)
focused('Movies, shows, episodes, people')
adb('shell','input','text','silo');text('TV shows');key(66);focused('Silo');key(23);text('Seasons')
root=text('Shuffle episodes');screenshot('050-show-shuffle')
# Focus starts on the season rail. Reach its action row and explicitly focus Shuffle.
if 'Season' in focus(root):key(19)
wait(lambda r:any(x in focus(r) for x in ('Play','Resume','Watch next','Shuffle')),'Show actions')
if 'Shuffle' not in focus(snapshot()):key(22)
focused('Shuffle episodes')
key(20);focused('Season 1');key(23)
wait(lambda r:'Episodes' in labels(r) or any(x.startswith(('Play','Resume')) for x in labels(r)),'Season page')
assert not any('Shuffle' in s for s in labels(snapshot())),'Shuffle must not appear on seasons'
screenshot('050-season-without-shuffle')
passed('Show Shuffle is remote-focusable and absent from season pages')
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('check',choices=['audio','show']);args=parser.parse_args()
(audio if args.check=='audio' else show)()

View file

@ -0,0 +1,132 @@
"""Previous episode, timed auto-skip with remote cancellation, server-picker Back and resume refresh.
Requires the **debug** build (test intents and run-as). Playback runs as validation, so it reports no
Plex progress. The refresh check moves one Continue Watching offset and restores it; the auto-skip
preferences are restored as found.
"""
import json,pathlib,re,sys,time,urllib.request,urllib.parse
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from device import adb,ROOT,screenshot
from verify_ui import key,snapshot,focus,labels,wait,focused,text,launch
from repro_runtime import await_ready
PREFS='shared_prefs/preferences.xml'
INTRO_EPISODE=11621 # The Big Bang Theory 10x24: intro marker 117.4-146.7 s
SILO_FIRST,SILO_SECOND=7599,8594
def logs(tag='KaleidoPlayback'):return adb('logcat','-d','-s',f'{tag}:I','AndroidRuntime:E','*:S').decode(errors='replace')
def wait_log(needle,timeout=30,tag='KaleidoPlayback'):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
if needle in logs(tag):return
time.sleep(.3)
raise AssertionError(f'Log never showed {needle!r}')
def start(item,offset):
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item),'--el','testOffset',str(offset),'--ei','testMode','1','--ez','testValidation','true')
await_ready(item)
def read_prefs():return adb('shell','run-as','tv.kaleido.app','cat',PREFS).decode()
def write_prefs(xml):
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > '+PREFS+'"',data=xml.encode())
def with_int(xml,name,value):
entry=f'<int name="{name}" value="{value}" />'
pattern=re.compile(r'<int name="'+name+r'" value="-?\d+" />')
return pattern.sub(entry,xml) if pattern.search(xml) else xml.replace('</map>',f' {entry}\n</map>')
def auto_skip():
start(INTRO_EPISODE,112000)
wait_log('AUTOSKIP countdown intro seconds=5')
root=wait(lambda r:'Skipping intro' in labels(r),'Pending skip reads "Skipping intro", without a number')
assert not any(re.search(r'Skip(ping)? intro.*\d',l) for l in labels(root)),'Skip button shows a numeric countdown'
screenshot('auto-skip-pending')
wait_log(f'AUTOSKIP intro item={INTRO_EPISODE}',timeout=15)
assert 'AUTOSKIP cancelled' not in logs()
print('PASS intro skips itself after the countdown, shown as a fill rather than a number',flush=True)
for code,name in ((20,'Down'),(4,'Back')):
start(INTRO_EPISODE,112000)
wait_log('AUTOSKIP countdown intro')
key(code);wait_log('AUTOSKIP cancelled intro',timeout=5)
time.sleep(7)
assert f'AUTOSKIP intro item={INTRO_EPISODE}' not in logs(),f'{name} did not cancel the automatic skip'
root=wait(lambda r:'Skip intro' in labels(r),'Manual Skip intro stays available after cancelling')
assert adb('shell','pidof','tv.kaleido.app').strip(),'Player process exited'
assert 'Skipping intro' not in labels(root)
print(f'PASS {name} cancels the automatic skip and leaves the player open',flush=True)
screenshot('auto-skip-cancelled')
key(4);key(4)
def previous_episode():
start(SILO_SECOND,90000)
key(127);focused('Play');screenshot('player-bar-episode')
key(21);focused('Back 10 seconds');key(21);focused('Previous episode');key(23)
await_ready(SILO_FIRST)
assert 'FATAL EXCEPTION' not in logs(),'Previous episode crashed'
print('PASS Previous episode replaced the player with the earlier episode',flush=True)
time.sleep(2);key(127);focused('Play')
# The series' first episode has no previous one once its season list has loaded.
wait(lambda r:'Next episode' in labels(r) and 'Previous episode' not in labels(r),'No Previous episode on the first episode')
key(21);focused('Back 10 seconds');key(21)
assert 'Back 10 seconds' in focus(snapshot()) or 'Exit playback' in focus(snapshot())
print('PASS first episode offers Next but not Previous',flush=True)
key(4);key(4)
def server_picker():
launch();key(22,4);focused('Settings');key(23);focused('Switch account');key(22)
if 'Choose server' not in focus(snapshot()):print('SKIP no account-linked server list (server-token session)');key(4);return
key(23);text('Choose your Plex server');screenshot('server-picker')
key(4)
wait(lambda r:'Choose your Plex server' not in labels(r) and 'Choose server' in labels(r),'Back closes the server picker over Settings')
assert adb('shell','pidof','tv.kaleido.app').strip()
key(22) # Choose server again, now via the Cancel button
if 'Choose server' not in focus(snapshot()):key(21)
focused('Choose server');key(23);text('Choose your Plex server')
for _ in range(12):
if focus(snapshot())=='Cancel':break
key(20)
focused('Cancel');key(23)
wait(lambda r:'Choose your Plex server' not in labels(r) and 'Choose server' in labels(r),'Cancel closes the server picker')
print('PASS Back and Cancel close Settings > Choose server',flush=True)
key(4)
def plex(path,params):
env=dict(l.strip().split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#'))
url=env['PLEX_SERVER_URL'].strip('"\'').rstrip('/')+path+'?'+urllib.parse.urlencode(params)
req=urllib.request.Request(url,headers={'X-Plex-Token':env['PLEX_TOKEN'].strip('"\''),'Accept':'application/json','X-Plex-Client-Identifier':'kaleido-development','X-Plex-Product':'Kaleido'})
with urllib.request.urlopen(req,timeout=20) as r:return r.read()
def offset(item,field='viewOffset'):
from inspect_server import get
return int(get(f'/library/metadata/{item}')['Metadata'][0].get(field,0))
def set_offset(item,ms):plex('/:/progress',{'key':str(item),'identifier':'com.plexapp.plugins.library','time':str(ms),'state':'stopped'})
def refresh():
original=offset(SILO_FIRST)
# Continue Watching progress is compared in 5% steps; move by more than one step each time.
step=offset(SILO_FIRST,'duration')*6//100
try:
launch();time.sleep(4);adb('logcat','-c')
# Watched elsewhere while Kaleido is in the background: shown promptly on return.
key('KEYCODE_HOME');time.sleep(3)
set_offset(SILO_FIRST,original+step)
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
began=time.monotonic();wait_log('APPLIED',timeout=10,tag='KaleidoSync')
print(f'PASS returning to Kaleido applied Continue Watching changes in {time.monotonic()-began:.1f}s',flush=True)
# Watched elsewhere while Kaleido stays open: the background poll picks it up.
time.sleep(3);adb('logcat','-c');set_offset(SILO_FIRST,original+2*step);began=time.monotonic()
wait_log('APPLIED',timeout=25,tag='KaleidoSync')
print(f'PASS open Kaleido applied a progress change from another device in {time.monotonic()-began:.1f}s',flush=True)
finally:
set_offset(SILO_FIRST,original)
assert offset(SILO_FIRST)==original,'Fixture progress was not restored'
if __name__=='__main__':
phases=sys.argv[1:] or ['previous_episode','auto_skip','server_picker','refresh']
original=read_prefs()
try:
if 'auto_skip' in phases:
write_prefs(with_int(with_int(original,'autoSkipIntroSeconds',5),'autoSkipCreditsSeconds',0))
for phase in phases:globals()[phase]()
finally:
write_prefs(original)
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')

View file

@ -10,7 +10,10 @@ key(20);focused('Remote quality');key(23)
wait(lambda r:any(q in focus(r) for q in ('Original quality','4K','1080p','720p','480p')),'Remote quality choices');key(4);focused('Remote quality') wait(lambda r:any(q in focus(r) for q in ('Original quality','4K','1080p','720p','480p')),'Remote quality choices');key(4);focused('Remote quality')
key(20);focused('Watched status');key(23);focused('80%');key(4);focused('Watched status') key(20);focused('Watched status');key(23);focused('80%');key(4);focused('Watched status')
key(20);focused('Autoplay next episode');key(23);focused('After 5 seconds');key(4);focused('Autoplay next episode') key(20);focused('Autoplay next episode');key(23);focused('After 5 seconds');key(4);focused('Autoplay next episode')
key(20);focused('Skip intros');key(20);focused('Skip credits') key(20);focused('Skip intros');key(23)
wait(lambda r:any(q in focus(r) for q in ('Show button','Automatically after')),'Skip intro delay choices');key(4);focused('Skip intros')
key(20);focused('Skip credits');key(23)
wait(lambda r:any(q in focus(r) for q in ('Show button','Automatically after')),'Skip credits delay choices');key(4);focused('Skip credits')
print('PASS playback dialogs cancel back to their controls',flush=True) print('PASS playback dialogs cancel back to their controls',flush=True)
screenshot('settings-playback-current') screenshot('settings-playback-current')
key(21);focused('Playback');key(20);focused('Subtitles');key(22);focused('Size');key(23);focused('Normal');key(4);focused('Size') key(21);focused('Playback');key(20);focused('Subtitles');key(22);focused('Size');key(23);focused('Normal');key(4);focused('Size')

View file

@ -10,7 +10,8 @@ def key(code,count=1):
def snapshot(): def snapshot():
adb('shell','uiautomator','dump','/data/local/tmp/kaleido-window.xml') adb('shell','uiautomator','dump','/data/local/tmp/kaleido-window.xml')
return ET.fromstring(adb('shell','cat','/data/local/tmp/kaleido-window.xml')) return ET.fromstring(adb('shell','cat','/data/local/tmp/kaleido-window.xml'))
def labels(root):return [n.get('text','') for n in root.iter('node') if n.get('text')] # Title art exposes its title as a content description rather than text.
def labels(root):return [n.get('text','') for n in root.iter('node') if n.get('text')]+[n.get('content-desc') for n in root.iter('node') if n.get('content-desc') and not n.get('text')]
def focus(root): def focus(root):
n=next((n for n in root.iter('node') if n.get('focused')=='true'),None) n=next((n for n in root.iter('node') if n.get('focused')=='true'),None)
if n is None:return '' if n is None:return ''
@ -46,7 +47,7 @@ def browse():
key(4);focused(selected);passed('Discovery details returns to the same focused card') key(4);focused(selected);passed('Discovery details returns to the same focused card')
key(19);wait(lambda r:focus(r) in ('Play','Resume'),'Return to Home hero');key(19);focused('Home');key(22);text('Recently released');focused('Movies') key(19);wait(lambda r:focus(r) in ('Play','Resume'),'Return to Home hero');key(19);focused('Home');key(22);text('Recently released');focused('Movies')
capture('movies-discover');key(20);focused('Discover');key(22);focused('Library');key(23) capture('movies-discover');key(20);focused('Discover');key(22);focused('Library');key(23)
text('All genres ⌄');focused('Library');capture('movies-library') wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Library filters');focused('Library');capture('movies-library')
passed('Movies prioritizes recent releases and retains a separate filtered A-Z grid') passed('Movies prioritizes recent releases and retains a separate filtered A-Z grid')
key(20);wait(lambda r:bool(focus(r)) and 'Library' not in focus(r),'Library content or filter focus') key(20);wait(lambda r:bool(focus(r)) and 'Library' not in focus(r),'Library content or filter focus')
key(4);focused('Discover');key(19);focused('Movies');key(22) key(4);focused('Discover');key(19);focused('Movies');key(22)
@ -92,14 +93,14 @@ def player():
passed('Compact player controls over actual video') passed('Compact player controls over actual video')
key(19);focused('Playback timeline');key(22);capture('timeline');key(20);focused('Play') key(19);focused('Playback timeline');key(22);capture('timeline');key(20);focused('Play')
passed('D-pad Up focuses timeline, Right seeks, Down returns to play') passed('D-pad Up focuses timeline, Right seeks, Down returns to play')
key(22,2);focused('Audio tracks');key(23);text('Audio');capture('audio') key(22,2);focused('Audio tracks');key(23);text('Audio tracks');capture('audio')
key(4);focused('Audio tracks');key(22);focused('Subtitles');key(23);text('Off');capture('subtitles') key(4);focused('Audio tracks');key(22);focused('Subtitles');key(23);text('Off');capture('subtitles')
passed('Audio and subtitle panels open, close, and restore focus') passed('Audio and subtitle panels open, close, and restore focus')
key(4);focused('Subtitles');key(22);focused('Playback options');key(23);text('Playback options') key(4);focused('Subtitles');key(22);focused('Playback options');key(23);text('Playback options')
key(20);focused('Speed');key(23);text('Playback speed');focused('Normal');key(20);focused('1.25×');key(23) key(20,2);focused('Speed');key(23);text('Playback speed');focused('Normal');key(20);focused('1.25×');key(23)
focused('Playback options');key(23);text('Speed · 1.25×');key(4);focused('Playback options') focused('Playback options');key(23);text('Speed · 1.25×');key(4);focused('Playback options')
key(23);text('Playback options');key(23);text('Playback quality');focused('Original quality');key(20);focused('4K');key(19);focused('Original quality');key(23) key(23);text('Playback options');key(20);key(23);text('Playback quality');focused('Original quality');key(20);focused('4K');key(19);focused('Original quality');key(23)
focused('Playback options');time.sleep(5);key(23);text('Quality · Original quality');key(4);focused('Playback options') focused('Playback options');time.sleep(5);key(23);wait(lambda r:any(s.startswith('Quality · Original quality') for s in labels(r)),'Original bitrate quality label');key(4);focused('Playback options')
passed('Player gear changes speed and switches a conversion to Original quality while retaining focus') passed('Player gear changes speed and switches a conversion to Original quality while retaining focus')
key(4) key(4)
wait(lambda r:focus(r)=='' and '2 Fast 2 Furious' not in labels(r),'Controls hidden by Back') wait(lambda r:focus(r)=='' and '2 Fast 2 Furious' not in labels(r),'Controls hidden by Back')

View file

@ -1,2 +1,2 @@
versionName=0.2.1 versionName=0.8.1
versionCode=14 versionCode=25