Compare commits
No commits in common. "main" and "v0.1.2" have entirely different histories.
|
|
@ -35,11 +35,6 @@ 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')
|
||||||
|
|
|
||||||
1
.gitignore
vendored
|
|
@ -12,7 +12,6 @@ evidence/private/
|
||||||
*.keystore
|
*.keystore
|
||||||
*.jks
|
*.jks
|
||||||
.idea/
|
.idea/
|
||||||
.DS_Store
|
|
||||||
*.iml
|
*.iml
|
||||||
/Home screen.jpg
|
/Home screen.jpg
|
||||||
/Individual library.jpg
|
/Individual library.jpg
|
||||||
|
|
|
||||||
42
AGENTS.md
|
|
@ -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 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.
|
- The authorized test device is the onn at **192.168.50.195:5555**, package **tv.kaleido.app**, activity **.MainActivity**. Always specify the ADB serial. Do not modify its launcher, accessibility services, other apps, or other devices.
|
||||||
- `.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. Entering the rows compacts it into a Silo-style preview of the focused card (its own image, top-right); Up/Back restores the hero.
|
- **Home:** large cinematic hero with playback/information actions and integrated landscape Continue Watching. Do not replace it with the compact section preview.
|
||||||
- **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.
|
- **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.
|
||||||
- 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,17 +35,7 @@ Install `app/build/outputs/apk/release/app-release.apk` instead for performance/
|
||||||
|
|
||||||
## Testing suite
|
## Testing suite
|
||||||
|
|
||||||
Use `& $KaleidoPython` before the Python commands below. **Never run competing device/UI tests in parallel.**
|
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.
|
||||||
|
|
||||||
**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 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
|
|
@ -55,21 +45,12 @@ Run only checks relevant to the change. Live playback tests change real Plex pro
|
||||||
| `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 → Up Next countdown → next episode READY; **debug** |
|
| `scripts/repro_runtime.py postplay` | Natural ending → five-second countdown → next episode READY; **debug** |
|
||||||
| `scripts/repro_runtime.py credits` | Credits → Up Next (mini-player), season/related rows, any-press cancel, Back to video; **debug** |
|
| `scripts/repro_runtime.py credits` | Visible Skip credits, season/related rows and cancellable countdown; **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/trace_transition.py <label> <setup> <keys>` | atrace one transition and list slow UI frames with their nested work |
|
|
||||||
| `scripts/profile_home.py <label>` | Hero → Continue Watching frame timing; profiled **release**; `--cold --cycles 1` checks the first transition |
|
| `scripts/profile_home.py <label>` | Hero → Continue Watching frame timing; profiled **release**; `--cold --cycles 1` checks the first transition |
|
||||||
| `scripts/verify_navigation_sounds.py` | Sound toggle and cold-start persistence; leaves sounds On |
|
| `scripts/verify_navigation_sounds.py` | Sound toggle and cold-start persistence; leaves sounds On |
|
||||||
| `scripts/verify_details.py` | Cast/actor navigation, related shows and watched sync; temporarily marks validated unwatched movie/show fixtures, then restores them |
|
|
||||||
| `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_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:
|
||||||
|
|
||||||
|
|
@ -86,17 +67,12 @@ 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, 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.
|
- Direct stream is the default preference, with original-file and conversion options available in-player. Augment Plex's existing HEVC target; competing transcode targets previously forced unnecessary H.264 conversion. A server decision to copy video does not itself prove successful rendering.
|
||||||
- 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. 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).
|
- Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them.
|
||||||
- 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
|
||||||
|
|
||||||
|
|
@ -112,8 +88,6 @@ 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.
|
||||||
|
|
|
||||||
149
CHANGELOG.md
|
|
@ -1,154 +1,5 @@
|
||||||
# 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
|
|
||||||
|
|
||||||
- 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.
|
|
||||||
- Remove the Go to show button from season and episode pages; Back returns to the show, and quick actions still offer Go to show.
|
|
||||||
- Play buttons are solid white only when focused, so an unfocused Play no longer looks selected.
|
|
||||||
|
|
||||||
## 0.2.0
|
|
||||||
|
|
||||||
- Search works fully with the remote: press Down or the keyboard's Search key to reach results, grouped into Movies, TV shows, Episodes and People. Search by voice with the microphone, the remote's search key or the Assistant.
|
|
||||||
- Hold OK (or press Menu) on any title for quick actions: play or resume, start over, mark watched, remove from Continue Watching, or go to the season or show.
|
|
||||||
- Title pages add a Trailer button and a Trailers & extras row, a version picker for titles with several files, and a fuller media line with HDR/Dolby Vision, audio channels and bitrate. Season pages list episodes with synopses and air dates; episode pages show the rest of their season and link to the show.
|
|
||||||
- Rows with more titles end in View all. Back from the rows returns to the top before leaving Kaleido. A second movie or TV library can be chosen from Discover and is remembered.
|
|
||||||
- New settings: a separate remote-connection quality (1080p by default), autoplay countdown or off, automatic intro and credit skipping, and subtitle size and style with a preview. OK skips a visible intro or credits.
|
|
||||||
- Stacked multi-part movies play through every part. Kaleido finds your server again if its address changes. A finished movie returns to its page, and focus returns to Play after playback.
|
|
||||||
- Fix chapter numbering, menus that opened away from the current choice, a misleading checkmark in Playback options, season cards without their show name, faint focus on light posters, and Try again repeating the action that failed.
|
|
||||||
|
|
||||||
## 0.1.11
|
|
||||||
|
|
||||||
- Give movie information the fitted poster, cinematic backdrop and safe header placement used by TV shows. Add related movies from Plex beneath the cast.
|
|
||||||
- Keep open libraries current: check Plex for library changes every 15 seconds and refresh Home and the active movie/TV section silently, with a 60-second fallback. Preserve filters, loaded titles and D-pad focus; pause checks during playback and while the app is in the background.
|
|
||||||
|
|
||||||
## 0.1.10
|
|
||||||
|
|
||||||
- Play the original media file first at Original quality, preserving supported 4K video, Dolby Vision/HDR metadata and multichannel audio instead of unnecessarily converting to 1080p/stereo.
|
|
||||||
- Automatically fall back to Plex when the native player cannot render the source video, including files that previously produced audio without a picture. Movie controls identify server conversions of video or audio.
|
|
||||||
- Use Android's standard mono PCM output mask when a source specifies a center-only mono layout, fixing the tested 24-bit/96 kHz WAV without changing its sample rate. Preserve multichannel layouts and compressed-audio passthrough.
|
|
||||||
- Honor Plex's selected audio and subtitle tracks during native playback, including Subtitles Off, and serialize stream changes to keep seeks and quality changes from competing.
|
|
||||||
|
|
||||||
## 0.1.9
|
|
||||||
|
|
||||||
- Move Seasons up on TV show pages so the artwork and season labels fit together on the first screen.
|
|
||||||
- Constrain show descriptions to the movie-detail text width, with full text in an artwork-led Synopsis panel styled to match title details. Fade artwork to near-black behind lower rows and as details scroll.
|
|
||||||
- Combine newly added seasons from the same Plex show into one card. Multiple seasons open the show's full season list; a single season still opens directly.
|
|
||||||
- Make Movies and TV navigation enter Discover immediately, without waiting for catalog scrolling. Preserve a quick Down press while switching tabs and focus visible cards before scrolling.
|
|
||||||
- Align horizontal focus and scrolling with the next frame, retain each requested D-pad step, and prepare nearby cards ahead of navigation. Prevent unnecessary focus searches above the top navigation.
|
|
||||||
|
|
||||||
## 0.1.8
|
|
||||||
|
|
||||||
- Add cast portraits with character names to title information. Select an actor to browse their movies and shows across your Plex libraries.
|
|
||||||
- Add Mark watched / Mark unwatched buttons that synchronize movies, series and episodes with Plex.
|
|
||||||
- Put Seasons first on TV show pages, followed by Cast and related shows supplied by Plex.
|
|
||||||
- Redesign TV show information with a full backdrop, fitted poster and stable header placement. Add text shadows and stronger contrast for readable descriptions and ratings.
|
|
||||||
- Redesign Settings with a category rail and consistent controls for Connection, Playback, Interface and Updates.
|
|
||||||
- Refresh the screenshots and rewrite the README around the app's features and installation.
|
|
||||||
|
|
||||||
## 0.1.7
|
|
||||||
|
|
||||||
- Give the launcher banner and app icon a soft colored background: deep sea-glass light from the top right fading to a warm glow at the bottom left, behind the unchanged six-facet mark.
|
|
||||||
|
|
||||||
## 0.1.6
|
|
||||||
|
|
||||||
- Replace the separate playback mode and transcode quality settings with one quality list: Original quality (the default), then 4K, 1080p, 720p and 480p. Existing preferences carry over.
|
|
||||||
- Tapping Left or Right during playback now skips 10 seconds without showing the controls; quick taps add up. Holding Left or Right still opens the timeline for scrubbing.
|
|
||||||
- Opening the controls straight to the timeline, by holding Left/Right or pressing fast-forward, now keeps focus on the timeline instead of jumping to Play.
|
|
||||||
|
|
||||||
## 0.1.5
|
|
||||||
|
|
||||||
- Show update download progress on the update button and with a progress bar under it.
|
|
||||||
- Keep focus on the update button while it downloads and after the installer closes, so the remote no longer jumps to Home from Settings.
|
|
||||||
- Offer Install again after the installer is cancelled, without downloading the update again.
|
|
||||||
- Stop Settings from scrolling when moving between buttons, show only the new version's notes above the update buttons, and make focused primary buttons clearly stand out.
|
|
||||||
|
|
||||||
## 0.1.4
|
|
||||||
|
|
||||||
- Halve the pause when switching between Home, Movies and TV Shows: cards fill in over a few frames under the page fade, and the tab highlights before the section changes.
|
|
||||||
- Remove the freeze on the first move from the Home hero to the rows below, and the skipped frames when moving between Movies/TV rows.
|
|
||||||
- The Library tab is now labelled "Library", and pressing Right from it moves to the genre, watch and sort controls instead of opening Home.
|
|
||||||
- Reduce background image decoding and overdraw for smoother browsing on Fire TV Stick and other lower-powered TVs.
|
|
||||||
|
|
||||||
## 0.1.3
|
|
||||||
|
|
||||||
- Redesign the startup animation: the six-facet aperture opens like a camera iris with light leaking through its gaps, a sheen crosses the mark, and the wordmark slides out from behind it.
|
|
||||||
- Fly through the aperture's center into Home instead of crossfading, with the app settling into place behind it.
|
|
||||||
- Hold the closed iris briefly while startup data arrives, so cold-start loading no longer stutters the animation.
|
|
||||||
|
|
||||||
## 0.1.2
|
## 0.1.2
|
||||||
|
|
||||||
- Add navigation tap sounds with a persistent On/Off setting under Settings > Interface. Sounds default to On and follow the TV's system sound-effects setting.
|
- Add navigation tap sounds with a persistent On/Off setting under Settings > Interface. Sounds default to On and follow the TV's system sound-effects setting.
|
||||||
|
|
|
||||||
83
README.md
|
|
@ -1,80 +1,43 @@
|
||||||
# Kaleido
|
# Kaleido
|
||||||
|
|
||||||
A Plex client for Android TV, designed for browsing from the couch. Kaleido puts your movies, shows and next episodes up front, with large artwork and controls that work with a remote.
|
A native Kotlin / Jetpack Compose / Media3 client for personal Plex movie and television libraries on Android TV 9 and newer. Built for a remote, with cinematic server artwork, focused content rows, discovery hubs, paged libraries, and an original dark visual design inspired by the supplied references.
|
||||||
|
|
||||||
**[Download the latest release](https://git.elijahkuntz.com/Elijah/Kaleido/releases/latest)** · Android TV 9 or newer · Requires a Plex Media Server
|
## Build on Windows
|
||||||
|
|
||||||
## What's in the app
|
1. Run `scripts/bootstrap.py` with Python 3 to download an isolated JDK 17, Gradle 8.13, and Android command-line tools under `.tools/`.
|
||||||
|
2. Set `JAVA_HOME` to the extracted JDK directory and run `.tools/sdk/cmdline-tools/latest/bin/sdkmanager.bat --sdk_root=<absolute .tools/sdk path> "platforms;android-36" "build-tools;35.0.0"`. Accept the SDK license when prompted.
|
||||||
|
3. Run `./Build.ps1 -Test` for the debug APK, unit tests, and lint. Run `./Build.ps1 -Release` for the optimized release APK.
|
||||||
|
|
||||||
### Find something to watch
|
Open the project root in Android Studio to use an existing local Android SDK instead. Set `ANDROID_HOME` and use the bundled Gradle distribution or the wrapper.
|
||||||
|
|
||||||
- **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.
|
The first local build creates `.tools/kaleido-signing.jks`. **Keep a private backup of this file and its credentials. Every app update must use the same signing key.** Debug and release builds share this local key so the test installation can receive the release through the updater. CI uses an ephemeral validation key and publishes only the locally signed distribution APK. For alternate signing, set `KALEIDO_KEYSTORE`, `KALEIDO_STORE_PASSWORD`, `KALEIDO_KEY_ALIAS`, and `KALEIDO_KEY_PASSWORD`.
|
||||||
- **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 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.
|
|
||||||
- **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.
|
|
||||||
|
|
||||||
### Watch the way you want
|
## Connect
|
||||||
|
|
||||||
Original quality plays the source video where your TV supports it. You can also ask Plex to convert to 4K, 1080p, 720p or 480p, with a separate limit for remote connections away from home. Titles with several versions let you pick one.
|
Open Kaleido and enter its code at [plex.tv/link](https://plex.tv/link). Settings → Sign in with Plex can link an account while keeping the current connection until successful server selection; Back cancels linking. Choose a server if more than one is available. The client tests the discovered server connections and prefers TLS. A manual server URL / token connection is also available. The credentials are AES-GCM encrypted with an Android Keystore key, never backed up, and removed on sign-out. Local HTTP servers remain supported. Account tokens are sent only to Plex account endpoints; server tokens are sent to the selected Plex server.
|
||||||
|
|
||||||
Choose audio tracks, subtitles, playback speed and chapters from the player. Tap Left or Right to skip ten seconds, or hold to scrub through the timeline with thumbnail previews. Skip intros and credits with a button or automatically, and let the next episode start after a countdown you choose. Subtitle size and style are adjustable. Previews and skip markers appear when Plex supplies them; HDR and format support depend on your TV and server.
|
`.env` and signing keys are ignored by Git. No test credentials are included in source code, BuildConfig, resources, or APKs. `scripts/device.py seed` is an optional debug-only provisioning helper: it sends `.env` credentials to private app data over the already-authorized ADB connection. Kaleido immediately encrypts them and deletes the staging file. Release builds never read this staging file.
|
||||||
|
|
||||||
### Keep your place
|
## Remote and playback
|
||||||
|
|
||||||
Playback progress and watched status sync with Plex, so your place carries across clients. Mark a movie, episode, season or whole show watched or unwatched from its page or its quick actions. You can set the playback percentage that counts as watched, too.
|
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.
|
||||||
|
|
||||||
Settings groups connection, playback, subtitles, interface and updates in one place. Navigation tap sounds can be turned on or off. The built-in updater checks for releases and downloads new versions without another manual sideload.
|
Direct stream is the default, requesting original resolution and remuxing where supported, with transcoding fallback. The player gear also exposes original-file playback, transcoding, audio, subtitles, speed, quality, 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.
|
||||||
|
|
||||||
## Install
|
## Updates and releases
|
||||||
|
|
||||||
1. Download **Kaleido.apk** from the [latest release](https://git.elijahkuntz.com/Elijah/Kaleido/releases/latest) and install it on your Android TV.
|
Kaleido checks [the public repository releases](https://git.elijahkuntz.com/Elijah/Kaleido/releases) on launch and foreground entry, at most once per six hours. Settings offers an immediate check. It downloads the release APK over HTTPS, checks its supplied SHA-256 when available, and verifies the package name, increasing Android version code, and installed signing certificate before opening Android's package installer. Android requires a one-time “allow from this source” permission and confirmation for each installation.
|
||||||
2. Open Kaleido and enter the code at [plex.tv/link](https://plex.tv/link).
|
|
||||||
3. Choose your Plex server and start browsing.
|
|
||||||
|
|
||||||
A manual server URL and token connection is also available. For future updates, use **Settings → Updates**. Android will ask you to confirm the installation.
|
To publish a version:
|
||||||
|
|
||||||
## Screenshots
|
1. Increment **both** fields in `version.properties` and update `CHANGELOG.md`.
|
||||||
|
2. Run `./Build.ps1 -Release -Test`, then `python scripts/package_release.py`.
|
||||||
|
3. Commit the source and `distribution/`, push `main`, and push the matching `v<versionName>` tag.
|
||||||
|
|
||||||
Captured from Kaleido **0.6.0** running on Android TV with a live Plex library. Select a screenshot to view it at full resolution.
|
The Forgejo workflow builds, tests, and lints the source, verifies the prebuilt signed distribution, then publishes its APK and checksum using Forgejo's repository-scoped token. The private production signing key never leaves the developer machine. The checked-in APK also provides a repository-file update channel, with an immutable tag URL in `distribution/latest.json`, for installations before the first Forgejo release is ready.
|
||||||
|
|
||||||
**Home** — a cinematic feature with playback actions and integrated Continue Watching.
|
## Structure and references
|
||||||
|
|
||||||
[](docs/screenshots/home.webp)
|
`PlexApi.kt` owns Plex transport and server-relative API calls; `SecureSession.kt` owns credential encryption; `KaleidoViewModel.kt` owns navigation and async screen data; `Screens.kt` and `Theme.kt` implement the TV UI; `Playback.kt` owns Media3, stream negotiation, track selection, lifecycle, and timeline reporting; `AppUpdater.kt` verifies updates. Artwork has bounded memory and disk caches. Library data is paged in batches of 100.
|
||||||
|
|
||||||
Moving into the rows compacts the feature into a preview of the focused card, with its artwork, ratings, cast and formats.
|
Implementation follows the [official Plex Media Server API](https://developer.plex.tv/pms/), [Android Compose guidance](https://developer.android.com/compose), and [Media3 documentation](https://developer.android.com/media/media3). This is an independent client, unaffiliated with Plex. No existing Plex client source is copied.
|
||||||
|
|
||||||
[](docs/screenshots/home-rows.webp)
|
|
||||||
|
|
||||||
| Movie discovery | TV discovery |
|
|
||||||
| --- | --- |
|
|
||||||
| [](docs/screenshots/movies.webp) | [](docs/screenshots/tv.webp) |
|
|
||||||
|
|
||||||
| Movie information and cast | TV show information and seasons |
|
|
||||||
| --- | --- |
|
|
||||||
| [](docs/screenshots/details.webp) | [](docs/screenshots/show.webp) |
|
|
||||||
|
|
||||||
| Season episodes | Cast and related shows |
|
|
||||||
| --- | --- |
|
|
||||||
| [](docs/screenshots/season.webp) | [](docs/screenshots/related.webp) |
|
|
||||||
|
|
||||||
| A–Z library | Categories |
|
|
||||||
| --- | --- |
|
|
||||||
| [](docs/screenshots/library.webp) | [](docs/screenshots/categories.webp) |
|
|
||||||
|
|
||||||
| Actor filmography | Settings |
|
|
||||||
| --- | --- |
|
|
||||||
| [](docs/screenshots/actors.webp) | [](docs/screenshots/settings.webp) |
|
|
||||||
|
|
||||||
## Build from source
|
|
||||||
|
|
||||||
Kaleido is written in Kotlin with Jetpack Compose and Media3. On Windows, the local toolchain can be set up with `scripts/bootstrap.py`, then built with:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
.\Build.ps1 -Release -Test
|
|
||||||
```
|
|
||||||
|
|
||||||
See the [development guide](docs/development.md) for setup and releases, the [design notes](docs/design-system.md), and [device testing](docs/runtime-verification.md).
|
|
||||||
|
|
||||||
Kaleido is in active development. It is an independent project and is not affiliated with Plex.
|
|
||||||
|
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -11,34 +11,6 @@ import kotlinx.coroutines.runBlocking
|
||||||
class BrowsePolicyTest {
|
class BrowsePolicyTest {
|
||||||
private fun title(id:String,type:String="movie")=Title.parse(JSONObject("""{"ratingKey":"$id","type":"$type","art":"/art/$id","title":"Title $id","originallyAvailableAt":"2026-10-01"}"""))
|
private fun title(id:String,type:String="movie")=Title.parse(JSONObject("""{"ratingKey":"$id","type":"$type","art":"/art/$id","title":"Title $id","originallyAvailableAt":"2026-10-01"}"""))
|
||||||
|
|
||||||
@Test fun recentSeasonsGroupByPlexShowIdentityAndPreserveRecency()=runBlocking {
|
|
||||||
val latest=title("s3","season").copy(parentId="show-a",parentTitle="Same name",title="Season 3")
|
|
||||||
val single=title("s1","season").copy(parentId="show-b",parentTitle="Same name",title="Season 1")
|
|
||||||
val older=title("s2","season").copy(parentId="show-a",parentTitle="Same name",title="Season 2")
|
|
||||||
val show=title("show-a","show");val loaded=mutableListOf<String>()
|
|
||||||
val result=groupRecentSeasons(listOf(latest,single,older,latest)){id->loaded+=id;show}
|
|
||||||
assertEquals(listOf("show-a","s1"),result.map{it.id})
|
|
||||||
assertEquals(show,result.first()) // Real show metadata, artwork, counts and navigation.
|
|
||||||
assertEquals("Same name · Season 1",result.last().title)
|
|
||||||
assertEquals(listOf("show-a"),loaded)
|
|
||||||
}
|
|
||||||
@Test fun recentSeasonsKeepUnknownParentsSeparateAndLimitAfterGrouping()=runBlocking {
|
|
||||||
val unknown=listOf(title("unknown1","season"),title("unknown2","season"))
|
|
||||||
val seasons=(1..24).map{title("s$it","season").copy(parentId="p$it")}
|
|
||||||
val result=groupRecentSeasons(unknown+seasons){error("Single seasons need no show request")}
|
|
||||||
assertEquals(18,result.size)
|
|
||||||
assertEquals(listOf("unknown1","unknown2","s1"),result.take(3).map{it.id})
|
|
||||||
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}"""))
|
||||||
assertFalse(show.fullyWatched);assertEquals(20,show.remainingEpisodes)
|
assertFalse(show.fullyWatched);assertEquals(20,show.remainingEpisodes)
|
||||||
|
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import android.content.Intent
|
|
||||||
import androidx.lifecycle.ViewModelProvider
|
|
||||||
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
|
|
||||||
import java.net.ServerSocket
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean
|
|
||||||
import kotlin.concurrent.thread
|
|
||||||
|
|
||||||
/** Exercises the real foreground timer and ViewModel against a changing HTTP library.
|
|
||||||
* Only the in-memory API endpoint is replaced; the encrypted user session and Plex stay untouched. */
|
|
||||||
@RunWith(AndroidJUnit4::class)
|
|
||||||
class LibrarySyncIntegrationTest {
|
|
||||||
@Test fun openClientReceivesNewMediaWithoutReloading()=runBlocking {
|
|
||||||
val instrumentation=InstrumentationRegistry.getInstrumentation()
|
|
||||||
val app=instrumentation.targetContext.applicationContext as KaleidoApplication
|
|
||||||
val original=app.api.session ?: error("A private test session is required")
|
|
||||||
val activity=instrumentation.startActivitySync(Intent(app,MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
|
|
||||||
lateinit var vm:KaleidoViewModel
|
|
||||||
fun main(action:()->Unit)=instrumentation.runOnMainSync(action)
|
|
||||||
main{vm=ViewModelProvider(activity)[KaleidoViewModel::class.java]}
|
|
||||||
fun await(description:String,check:()->Boolean) {
|
|
||||||
val deadline=System.currentTimeMillis()+25_000
|
|
||||||
while(true){var ready=false;main{ready=check()};if(ready)return
|
|
||||||
check(System.currentTimeMillis()<deadline){description};Thread.sleep(100)}
|
|
||||||
}
|
|
||||||
await("Initial real library load"){!vm.busy&&vm.sections.isNotEmpty()&&vm.homeHubs.isNotEmpty()}
|
|
||||||
val movie=vm.sections.first{it.type=="movie"}
|
|
||||||
val changed=AtomicBoolean(false)
|
|
||||||
val revisionRequests=java.util.concurrent.atomic.AtomicInteger()
|
|
||||||
val server=ServerSocket(0)
|
|
||||||
val worker=thread(isDaemon=true,name="LibrarySyncTestServer") {
|
|
||||||
while(!server.isClosed)try{server.accept().use{socket->
|
|
||||||
val input=socket.getInputStream().bufferedReader()
|
|
||||||
val request=input.readLine().orEmpty()
|
|
||||||
while(!input.readLine().isNullOrEmpty()){}
|
|
||||||
val path=request.split(' ').getOrElse(1){"/"}.substringBefore('?')
|
|
||||||
val added=changed.get()
|
|
||||||
val title="""{"ratingKey":"sync-${if(added)"new" else "old"}","type":"movie","title":"${if(added)"Newly added" else "Existing"} movie"}"""
|
|
||||||
val container=when(path){
|
|
||||||
"/library/sections"->{revisionRequests.incrementAndGet();"""{"Directory":[{"key":"${movie.id}","title":${JSONObject.quote(movie.title)},"type":"movie","contentChangedAt":${if(added)2 else 1}}]}"""}
|
|
||||||
"/hubs","/hubs/sections/${movie.id}"->"""{"Hub":[{"hubIdentifier":"movie.recentlyadded","title":"Recently added","Metadata":[$title]}]}"""
|
|
||||||
"/library/sections/${movie.id}/all"->"""{"size":1,"totalSize":1,"Metadata":[$title]}"""
|
|
||||||
else->"{}"
|
|
||||||
}
|
|
||||||
val body="""{"MediaContainer":$container}""".toByteArray()
|
|
||||||
val output=socket.getOutputStream()
|
|
||||||
output.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray());output.write(body);output.flush()
|
|
||||||
}}catch(_:java.io.IOException){if(!server.isClosed)throw AssertionError("Test HTTP server failed")}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
main{vm.setForeground(false);app.api.session=original.copy(server="http://127.0.0.1:${server.localPort}");vm.tab("movies")}
|
|
||||||
await("Initial section snapshot"){!vm.busy&&vm.library.firstOrNull()?.id=="sync-old"}
|
|
||||||
main{vm.setForeground(true)}
|
|
||||||
await("First foreground sync"){vm.homeHubs.any{h->h.items.any{it.id=="sync-old"}}}
|
|
||||||
changed.set(true)
|
|
||||||
await("New media must reach Home and active library without restarting"){
|
|
||||||
vm.homeHubs.any{h->h.items.any{it.id=="sync-new"}}&&vm.library.firstOrNull()?.id=="sync-new"
|
|
||||||
}
|
|
||||||
main{assertEquals("movies",vm.page.kind);assertFalse(vm.busy);assertNull(vm.error)}
|
|
||||||
assertTrue("Revision was polled again",revisionRequests.get()>=3)
|
|
||||||
main{vm.setForeground(false)}
|
|
||||||
val stoppedAt=revisionRequests.get();Thread.sleep(700)
|
|
||||||
assertEquals("Background sync must stop",stoppedAt,revisionRequests.get())
|
|
||||||
}finally {
|
|
||||||
main{vm.setForeground(false);app.api.session=original;vm.tab("home");vm.initialize()}
|
|
||||||
server.close();worker.join(1000)
|
|
||||||
activity.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -30,7 +30,7 @@ class LivePlexTest {
|
||||||
assertTrue(filtered.items.isNotEmpty());assertTrue(filtered.total<=first.total)
|
assertTrue(filtered.items.isNotEmpty());assertTrue(filtered.total<=first.total)
|
||||||
val title=first.items.first();val detail=api.details(title.id)
|
val title=first.items.first();val detail=api.details(title.id)
|
||||||
assertEquals(title.title,detail.title);assertTrue(detail.media.first().parts.first().key.startsWith("/library/parts/"))
|
assertEquals(title.title,detail.title);assertTrue(detail.media.first().parts.first().key.startsWith("/library/parts/"))
|
||||||
assertTrue(api.search(title.title).titles.any{it.id==title.id})
|
assertTrue(api.search(title.title).any{it.id==title.id})
|
||||||
assertTrue(api.hubs().isNotEmpty());assertTrue(api.hubs(section.id).isNotEmpty())
|
assertTrue(api.hubs().isNotEmpty());assertTrue(api.hubs(section.id).isNotEmpty())
|
||||||
}
|
}
|
||||||
@Test fun liveShowsSeasonsEpisodesAndMarkers()=runBlocking {
|
@Test fun liveShowsSeasonsEpisodesAndMarkers()=runBlocking {
|
||||||
|
|
@ -49,8 +49,7 @@ class LivePlexTest {
|
||||||
@Test fun liveGeneratedPreviewAndNewSeasons()=runBlocking {
|
@Test fun liveGeneratedPreviewAndNewSeasons()=runBlocking {
|
||||||
val showSection=api.sections().first{it.type=="show"}
|
val showSection=api.sections().first{it.type=="show"}
|
||||||
val seasons=api.recentSeasons(showSection.id)
|
val seasons=api.recentSeasons(showSection.id)
|
||||||
assertTrue(seasons.isNotEmpty());assertTrue(seasons.all{it.type=="show"||it.type=="season"&&it.parentTitle.isNotBlank()})
|
assertTrue(seasons.isNotEmpty());assertTrue(seasons.all{it.type=="season"&&it.parentTitle.isNotBlank()})
|
||||||
assertEquals(seasons.size,seasons.map{if(it.type=="show")it.id else it.parentId.ifBlank{it.id}}.distinct().size)
|
|
||||||
val episode=api.details("7599") // Known live test episode with generated preview indexes.
|
val episode=api.details("7599") // Known live test episode with generated preview indexes.
|
||||||
assertTrue(episode.chapters.isNotEmpty())
|
assertTrue(episode.chapters.isNotEmpty())
|
||||||
val preview=api.previewPath(episode,90000) ?: error("No server preview path")
|
val preview=api.previewPath(episode,90000) ?: error("No server preview path")
|
||||||
|
|
@ -61,7 +60,7 @@ class LivePlexTest {
|
||||||
}
|
}
|
||||||
@Test fun liveDirectStreamCopiesSupportedVideo()=runBlocking {
|
@Test fun liveDirectStreamCopiesSupportedVideo()=runBlocking {
|
||||||
val episode=api.details("7599") // HEVC test episode supported by this onn.
|
val episode=api.details("7599") // HEVC test episode supported by this onn.
|
||||||
val decision=api.container("/video/:/transcode/universal/decision",api.transcodeParams(episode,"kaleido-remux-regression",1,90000,StreamQuality.Original))
|
val decision=api.container("/video/:/transcode/universal/decision",api.transcodeParams(episode,"kaleido-remux-regression",1,90000,20000))
|
||||||
val streams=decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()}.flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}
|
val streams=decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()}.flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}
|
||||||
assertEquals("copy",streams.first{it.optInt("streamType")==1}.optString("decision"))
|
assertEquals("copy",streams.first{it.optInt("streamType")==1}.optString("decision"))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
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)}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import android.media.AudioFormat
|
|
||||||
import android.media.AudioTrack
|
|
||||||
import androidx.media3.common.C
|
|
||||||
import androidx.media3.common.Format
|
|
||||||
import androidx.media3.common.MimeTypes
|
|
||||||
import org.junit.Assert.*
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
|
||||||
class PlaybackCompatibilityTest {
|
|
||||||
@Test fun monoPcmHasAPlayableMaskWithoutChangingSamples() {
|
|
||||||
val source=Format.Builder().setSampleMimeType(MimeTypes.AUDIO_RAW).setChannelCount(1)
|
|
||||||
.setChannelMask(AudioFormat.CHANNEL_OUT_FRONT_CENTER).setSampleRate(96000).setPcmEncoding(C.ENCODING_PCM_24BIT).build()
|
|
||||||
val output=compatiblePcmFormat(source)
|
|
||||||
assertEquals(96000,output.sampleRate);assertEquals(source.pcmEncoding,output.pcmEncoding)
|
|
||||||
assertEquals(1,output.channelCount);assertEquals(AudioFormat.CHANNEL_OUT_MONO,output.channelMask)
|
|
||||||
// The default sink converts integer PCM to 16 bit before opening AudioTrack.
|
|
||||||
assertTrue(AudioTrack.getMinBufferSize(output.sampleRate,output.channelMask,C.ENCODING_PCM_16BIT)>0)
|
|
||||||
}
|
|
||||||
@Test fun multichannelPcmAndBitstreamsKeepTheirLayout() {
|
|
||||||
val pcm=Format.Builder().setSampleMimeType(MimeTypes.AUDIO_RAW).setChannelCount(6)
|
|
||||||
.setChannelMask(AudioFormat.CHANNEL_OUT_5POINT1).setSampleRate(48000).setPcmEncoding(C.ENCODING_PCM_16BIT).build()
|
|
||||||
val eac3=pcm.buildUpon().setSampleMimeType(MimeTypes.AUDIO_E_AC3).build()
|
|
||||||
assertSame(pcm,compatiblePcmFormat(pcm));assertSame(eac3,compatiblePcmFormat(eac3))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.hardware.display.DisplayManager
|
|
||||||
import android.media.AudioManager
|
|
||||||
import android.media.MediaCodecList
|
|
||||||
import android.os.Build
|
|
||||||
import androidx.test.platform.app.InstrumentationRegistry
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
import org.junit.Assume.assumeTrue
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
/** Explicit opt-in capability inventory. No session credentials are exported. */
|
|
||||||
class PlaybackValidationSetupTest {
|
|
||||||
@Test fun privateValidationContext() {
|
|
||||||
assumeTrue(InstrumentationRegistry.getArguments().getString("validationSetup")=="true")
|
|
||||||
val app=InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as KaleidoApplication
|
|
||||||
val codecs=JSONArray()
|
|
||||||
MediaCodecList(MediaCodecList.ALL_CODECS).codecInfos.filterNot{it.isEncoder}.forEach { codec->
|
|
||||||
codec.supportedTypes.forEach { type->
|
|
||||||
runCatching {
|
|
||||||
val caps=codec.getCapabilitiesForType(type)
|
|
||||||
codecs.put(JSONObject().put("name",codec.name).put("mime",type)
|
|
||||||
.put("hardware",if(Build.VERSION.SDK_INT>=29)codec.isHardwareAccelerated else JSONObject.NULL)
|
|
||||||
.put("profiles",JSONArray(caps.profileLevels.map{JSONObject().put("profile",it.profile).put("level",it.level)})))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val displays=app.getSystemService(DisplayManager::class.java).displays.map { display->
|
|
||||||
JSONObject().put("id",display.displayId).put("name",display.name)
|
|
||||||
.put("hdrTypes",JSONArray(display.hdrCapabilities.supportedHdrTypes.toList()))
|
|
||||||
.put("mode",display.mode.toString())
|
|
||||||
}
|
|
||||||
val audio=app.getSystemService(AudioManager::class.java)
|
|
||||||
val outputs=audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS).map { device->
|
|
||||||
JSONObject().put("id",device.id).put("type",device.type).put("name",device.productName)
|
|
||||||
.put("encodings",JSONArray(device.encodings.toList())).put("channels",JSONArray(device.channelCounts.toList()))
|
|
||||||
}
|
|
||||||
val report=JSONObject().put("model",Build.MODEL).put("sdk",Build.VERSION.SDK_INT)
|
|
||||||
.put("codecs",codecs).put("displays",JSONArray(displays)).put("audioOutputs",JSONArray(outputs))
|
|
||||||
.put("mediaVolume",audio.getStreamVolume(AudioManager.STREAM_MUSIC))
|
|
||||||
.put("mediaMuted",audio.isStreamMute(AudioManager.STREAM_MUSIC))
|
|
||||||
app.openFileOutput("validation-capabilities.json",Context.MODE_PRIVATE).use{it.write(report.toString(2).toByteArray())}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<application>
|
|
||||||
<activity android:name=".HdmiValidationActivity" android:exported="true" />
|
|
||||||
</application>
|
|
||||||
</manifest>
|
|
||||||
|
|
@ -1,54 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.media.tv.TvContract
|
|
||||||
import android.media.tv.TvView
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.view.Gravity
|
|
||||||
import android.widget.FrameLayout
|
|
||||||
import android.widget.TextView
|
|
||||||
import org.json.JSONObject
|
|
||||||
|
|
||||||
/** Temporary, public-TIF HDMI observer. No capture permissions or device settings changes. */
|
|
||||||
class HdmiValidationActivity:Activity() {
|
|
||||||
private lateinit var tv:TvView
|
|
||||||
private lateinit var label:TextView
|
|
||||||
private fun extras(bundle:Bundle?)=bundle?.let{b->b.keySet().joinToString{key->"$key=${b.get(key)}"}}.orEmpty()
|
|
||||||
private fun record(event:String,data:String="") {
|
|
||||||
val line=JSONObject().put("event",event).put("detail",data).put("elapsedMs",android.os.SystemClock.elapsedRealtime()).toString()
|
|
||||||
openFileOutput("hdmi-validation.jsonl",MODE_APPEND).use{it.write((line+"\n").toByteArray())}
|
|
||||||
label.text="HDMI validation · $event"
|
|
||||||
}
|
|
||||||
override fun onCreate(state:Bundle?) {
|
|
||||||
super.onCreate(state)
|
|
||||||
window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
|
||||||
setTurnScreenOn(true)
|
|
||||||
window.decorView.systemUiVisibility=android.view.View.SYSTEM_UI_FLAG_FULLSCREEN or android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or android.view.View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
|
||||||
val input=intent.getStringExtra("inputId") ?: return finish()
|
|
||||||
tv=TvView(this)
|
|
||||||
label=TextView(this).apply{setTextColor(android.graphics.Color.WHITE);setBackgroundColor(0x99000000.toInt());setPadding(18,10,18,10)}
|
|
||||||
val root=FrameLayout(this).apply {
|
|
||||||
addView(tv,FrameLayout.LayoutParams(-1,-1))
|
|
||||||
addView(label,FrameLayout.LayoutParams(-2,-2,Gravity.BOTTOM or Gravity.START))
|
|
||||||
}
|
|
||||||
setContentView(root)
|
|
||||||
openFileOutput("hdmi-validation.jsonl",MODE_PRIVATE).close()
|
|
||||||
tv.setCallback(object:TvView.TvInputCallback() {
|
|
||||||
override fun onVideoAvailable(inputId:String){record("videoAvailable")}
|
|
||||||
override fun onVideoUnavailable(inputId:String,reason:Int){record("videoUnavailable",reason.toString())}
|
|
||||||
override fun onConnectionFailed(inputId:String){record("connectionFailed")}
|
|
||||||
override fun onDisconnected(inputId:String){record("disconnected")}
|
|
||||||
override fun onVideoSizeChanged(inputId:String,width:Int,height:Int){record("size","${width}x$height")}
|
|
||||||
override fun onTracksChanged(inputId:String,tracks:MutableList<android.media.tv.TvTrackInfo>?) {
|
|
||||||
record("tracks",tracks?.joinToString { t->
|
|
||||||
if(t.type==android.media.tv.TvTrackInfo.TYPE_VIDEO)"video ${t.videoWidth}x${t.videoHeight} ${t.videoFrameRate} ${extras(t.extra)}"
|
|
||||||
else "type=${t.type} ${t.extra}"
|
|
||||||
}.orEmpty())
|
|
||||||
}
|
|
||||||
override fun onTvMessage(inputId:String,type:Int,args:Bundle){record("message:$type",args.toString())}
|
|
||||||
})
|
|
||||||
record("tuning",input)
|
|
||||||
runCatching{tv.tune(input,TvContract.buildChannelUriForPassthroughInput(input))}.onFailure{record("tuneFailed",it.javaClass.simpleName)}
|
|
||||||
}
|
|
||||||
override fun onDestroy(){if(::tv.isInitialized)tv.reset();super.onDestroy()}
|
|
||||||
}
|
|
||||||
|
|
@ -4,15 +4,9 @@
|
||||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||||
<uses-feature android:name="android.software.leanback" android:required="true" />
|
<uses-feature android:name="android.software.leanback" android:required="true" />
|
||||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||||
<uses-feature android:name="android.hardware.microphone" android:required="false" />
|
|
||||||
<!-- Voice search uses the TV's speech recognizer when it has one. -->
|
|
||||||
<queries><intent><action android:name="android.speech.action.RECOGNIZE_SPEECH" /></intent></queries>
|
|
||||||
<application android:name=".KaleidoApplication" android:label="Kaleido" android:icon="@drawable/icon" android:banner="@drawable/banner" android:theme="@style/Theme.Kaleido" android:allowBackup="false" android:usesCleartextTraffic="true" android:supportsRtl="true">
|
<application android:name=".KaleidoApplication" android:label="Kaleido" android:icon="@drawable/icon" android:banner="@drawable/banner" android:theme="@style/Theme.Kaleido" android:allowBackup="false" android:usesCleartextTraffic="true" android:supportsRtl="true">
|
||||||
<activity android:name=".MainActivity" android:exported="true" android:screenOrientation="landscape" android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|uiMode" android:launchMode="singleTop">
|
<activity android:name=".MainActivity" android:exported="true" android:screenOrientation="landscape" android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|uiMode" android:launchMode="singleTop">
|
||||||
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LEANBACK_LAUNCHER" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
|
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LEANBACK_LAUNCHER" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
|
||||||
<intent-filter><action android:name="android.intent.action.SEARCH" /></intent-filter>
|
|
||||||
<intent-filter><action android:name="com.google.android.gms.actions.SEARCH_ACTION" /><category android:name="android.intent.category.DEFAULT" /></intent-filter>
|
|
||||||
<meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />
|
|
||||||
</activity>
|
</activity>
|
||||||
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.files" android:exported="false" android:grantUriPermissions="true"><meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /></provider>
|
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.files" android:exported="false" android:grantUriPermissions="true"><meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /></provider>
|
||||||
</application>
|
</application>
|
||||||
|
|
|
||||||
|
|
@ -6,14 +6,3 @@ HPLtv/kaleido/app/DiscoveryScreensKt**->**(**)**
|
||||||
HPLtv/kaleido/app/ThemeKt**->**(**)**
|
HPLtv/kaleido/app/ThemeKt**->**(**)**
|
||||||
HPLtv/kaleido/app/NavigationSoundsKt**->**(**)**
|
HPLtv/kaleido/app/NavigationSoundsKt**->**(**)**
|
||||||
HPLtv/kaleido/app/NavigationSoundController;->**(**)**
|
HPLtv/kaleido/app/NavigationSoundController;->**(**)**
|
||||||
HPLtv/kaleido/app/TitleDetailsKt**->**(**)**
|
|
||||||
HPLtv/kaleido/app/SettingsScreenKt**->**(**)**
|
|
||||||
HPLtv/kaleido/app/LibraryNavigationKt**->**(**)**
|
|
||||||
HPLtv/kaleido/app/ScreensKt**->**(**)**
|
|
||||||
HPLtv/kaleido/app/TitleActionsNode;->**(**)**
|
|
||||||
HPLtv/kaleido/app/TitleActionsElement;->**(**)**
|
|
||||||
HPLtv/kaleido/app/Title;->**(**)**
|
|
||||||
HPLtv/kaleido/app/Media;->**(**)**
|
|
||||||
HPLtv/kaleido/app/FramePrefetch;->**(**)**
|
|
||||||
HPLtv/kaleido/app/FramePrefetchKt;->**(**)**
|
|
||||||
HPLtv/kaleido/app/CacheWindows;->**(**)**
|
|
||||||
|
|
|
||||||
|
|
@ -14,12 +14,6 @@ import java.security.MessageDigest
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
data class Release(val version: String,val url: String,val checksumUrl: String?,val notes: String)
|
data class Release(val version: String,val url: String,val checksumUrl: String?,val notes: String)
|
||||||
/** Release bodies may hold the whole changelog; keep only [version]'s section. */
|
|
||||||
fun releaseNotes(body: String,version: String): String {
|
|
||||||
val heading=Regex("^## v?"+Regex.escape(version)+"[ \t]*$",RegexOption.MULTILINE).find(body) ?: return body.trim()
|
|
||||||
val end=Regex("^## ",RegexOption.MULTILINE).find(body,heading.range.last+1)?.range?.first ?: body.length
|
|
||||||
return body.substring(heading.range.last+1,end).trim()
|
|
||||||
}
|
|
||||||
object Versions {
|
object Versions {
|
||||||
fun newer(candidate: String,current: String): Boolean {
|
fun newer(candidate: String,current: String): Boolean {
|
||||||
fun parts(v:String)=v.removePrefix("v").split('.').map {it.toIntOrNull() ?: return emptyList<Int>()}
|
fun parts(v:String)=v.removePrefix("v").split('.').map {it.toIntOrNull() ?: return emptyList<Int>()}
|
||||||
|
|
@ -41,12 +35,12 @@ class AppUpdater(private val context: Context) {
|
||||||
if(manifest.isBlank())return@withContext null
|
if(manifest.isBlank())return@withContext null
|
||||||
val m=JSONObject(manifest)
|
val m=JSONObject(manifest)
|
||||||
if(!Versions.newer(m.getString("version"),BuildConfig.VERSION_NAME))return@withContext null
|
if(!Versions.newer(m.getString("version"),BuildConfig.VERSION_NAME))return@withContext null
|
||||||
return@withContext Release(m.getString("version"),checkedUrl(m.getString("url")),checkedUrl(m.getString("checksumUrl")),releaseNotes(m.optString("notes"),m.getString("version")))
|
return@withContext Release(m.getString("version"),checkedUrl(m.getString("url")),checkedUrl(m.getString("checksumUrl")),m.optString("notes"))
|
||||||
}
|
}
|
||||||
val j=JSONObject(raw);if(j.optBoolean("draft")||j.optBoolean("prerelease")||!Versions.newer(j.optString("tag_name"),BuildConfig.VERSION_NAME))return@withContext null
|
val j=JSONObject(raw);if(j.optBoolean("draft")||j.optBoolean("prerelease")||!Versions.newer(j.optString("tag_name"),BuildConfig.VERSION_NAME))return@withContext null
|
||||||
val assets=j.optJSONArray("assets").objects();val apk=assets.firstOrNull{it.optString("name")=="Kaleido.apk"} ?: assets.firstOrNull{it.optString("name").endsWith(".apk")} ?: error("This release has no Android APK.")
|
val assets=j.optJSONArray("assets").objects();val apk=assets.firstOrNull{it.optString("name")=="Kaleido.apk"} ?: assets.firstOrNull{it.optString("name").endsWith(".apk")} ?: error("This release has no Android APK.")
|
||||||
val sha=assets.firstOrNull{it.optString("name")==apk.optString("name")+".sha256"}
|
val sha=assets.firstOrNull{it.optString("name")==apk.optString("name")+".sha256"}
|
||||||
Release(j.getString("tag_name").removePrefix("v"),checkedUrl(apk.getString("browser_download_url")),sha?.getString("browser_download_url")?.let(::checkedUrl),releaseNotes(j.optString("body"),j.getString("tag_name").removePrefix("v")))
|
Release(j.getString("tag_name").removePrefix("v"),checkedUrl(apk.getString("browser_download_url")),sha?.getString("browser_download_url")?.let(::checkedUrl),j.optString("body"))
|
||||||
}
|
}
|
||||||
suspend fun download(release: Release,onProgress: (Int)->Unit): File = withContext(Dispatchers.IO) {
|
suspend fun download(release: Release,onProgress: (Int)->Unit): File = withContext(Dispatchers.IO) {
|
||||||
val dir=File(context.cacheDir,"updates").apply{mkdirs()};val part=File(dir,"Kaleido.apk.part");val file=File(dir,"Kaleido.apk");part.delete();file.delete()
|
val dir=File(context.cacheDir,"updates").apply{mkdirs()};val part=File(dir,"Kaleido.apk.part");val file=File(dir,"Kaleido.apk");part.delete();file.delete()
|
||||||
|
|
|
||||||
|
|
@ -4,24 +4,15 @@ 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.core.Animatable
|
import androidx.compose.animation.Crossfade
|
||||||
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
|
||||||
|
|
@ -33,16 +24,10 @@ 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. */
|
||||||
* 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 {
|
||||||
* [header] artwork is scaled whole into the top-right of a screen-sized frame and fades into the page
|
override val cacheKey="kaleido-browse-contrast-v2-$cinematic"
|
||||||
* 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)
|
||||||
|
|
@ -52,96 +37,26 @@ private class BrowseContrast(val cinematic:Boolean,val header:Boolean,val wash:B
|
||||||
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,header&&!cinematic,wash)).crossfade(false).build()
|
.transformations(BrowseContrast(cinematic)).crossfade(false).build()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The new artwork fades in over the old one; only its layer alpha changes per frame. */
|
@Composable internal fun BrowseBackdrop(api:PlexApi,path:String,modifier:Modifier,cinematic:Boolean=false,animate:Boolean=false) {
|
||||||
@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,header,wash,animate){browseBackdropRequest(context,api,path,cinematic,header,wash)?.newBuilder()?.placeholderMemoryCacheKey(previous)?.build()}
|
val request=remember(path,api.session?.server,cinematic,animate){browseBackdropRequest(context,api,path,cinematic)?.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}}
|
||||||
}
|
}
|
||||||
FadingArtwork(bitmap,modifier,contentScale,alignment)
|
Crossfade(bitmap,modifier=modifier,animationSpec=tween(220),label="heroArtwork"){loaded->
|
||||||
}else AsyncImage(request,contentDescription=null,modifier=modifier,contentScale=contentScale,alignment=alignment,onSuccess={previous=it.result.memoryCacheKey})
|
loaded?.let{Image(it.asImageBitmap(),null,contentScale=ContentScale.Crop,modifier=Modifier.fillMaxSize())}
|
||||||
|
}
|
||||||
|
}else AsyncImage(request,contentDescription=null,modifier=modifier,contentScale=ContentScale.Crop,onSuccess={previous=it.result.memoryCacheKey})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,6 @@ import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||||
import androidx.compose.material.icons.filled.PlayArrow
|
import androidx.compose.material.icons.filled.PlayArrow
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.runtime.*
|
import androidx.compose.runtime.*
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
|
@ -26,8 +24,6 @@ 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
|
||||||
|
|
@ -35,17 +31,6 @@ 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 kotlinx.coroutines.flow.first
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.text.KeyboardActions
|
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
|
||||||
import androidx.compose.ui.semantics.contentDescription
|
|
||||||
import androidx.compose.ui.semantics.semantics
|
|
||||||
import androidx.compose.ui.text.TextRange
|
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
|
||||||
import androidx.compose.ui.text.input.TextFieldValue
|
|
||||||
|
|
||||||
@Composable fun Brand() {
|
@Composable fun Brand() {
|
||||||
Row(verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
|
Row(verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
|
||||||
|
|
@ -56,40 +41,19 @@ import androidx.compose.ui.text.input.TextFieldValue
|
||||||
|
|
||||||
@Composable fun TopBar(vm:KaleidoViewModel,navigation:DiscoveryNavigation?=null) {
|
@Composable fun TopBar(vm:KaleidoViewModel,navigation:DiscoveryNavigation?=null) {
|
||||||
val initialFocus by remember{derivedStateOf{vm.focusId.isBlank()}}
|
val initialFocus by remember{derivedStateOf{vm.focusId.isBlank()}}
|
||||||
val scope=rememberCoroutineScope();val pendingTab=remember{arrayOfNulls<Job>(1)}
|
|
||||||
val focusedTab=remember{arrayOf(vm.page.kind)}
|
|
||||||
// Let the focus highlight draw before the new section composes in its long frame,
|
|
||||||
// so the press responds at once. A quick second move replaces the pending switch.
|
|
||||||
fun select(kind:String){vm.tab(kind);vm.focusId="tab:$kind"}
|
|
||||||
fun activate(kind:String){pendingTab[0]?.cancel();pendingTab[0]=scope.launch{withFrameNanos{};withFrameNanos{};if(vm.page.kind!=kind)select(kind)}}
|
|
||||||
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
|
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
|
||||||
// Extend the scrim beyond the controls so it dissolves into the scene without a hard edge.
|
// Extend the scrim beyond the controls so it dissolves into the scene without a hard edge.
|
||||||
Box(Modifier.fillMaxWidth().height(62.dp).onPreviewKeyEvent {
|
Box(Modifier.fillMaxWidth().height(62.dp).drawBehind {
|
||||||
// There is no destination above the header. Letting repeated Up events run
|
|
||||||
// Compose's default search measures offscreen lazy rows looking for one.
|
|
||||||
it.type==KeyEventType.KeyDown&&it.key==Key.DirectionUp
|
|
||||||
}.drawBehind {
|
|
||||||
val depth=if(immersive)size.height*1.8f else size.height
|
val depth=if(immersive)size.height*1.8f else size.height
|
||||||
val colors=if(!immersive)listOf(Ink,Ink)else if(navigation?.scrolled==true)listOf(Color.Black.copy(alpha=.93f),Color.Black.copy(alpha=.66f),Color.Black.copy(alpha=.18f),Color.Transparent)else listOf(Color.Black.copy(alpha=.64f),Color.Black.copy(alpha=.22f),Color.Transparent)
|
val colors=if(!immersive)listOf(Ink,Ink)else if(navigation?.scrolled==true)listOf(Color.Black.copy(alpha=.93f),Color.Black.copy(alpha=.66f),Color.Black.copy(alpha=.18f),Color.Transparent)else listOf(Color.Black.copy(alpha=.64f),Color.Black.copy(alpha=.22f),Color.Transparent)
|
||||||
drawRect(Brush.verticalGradient(colors,endY=depth),size=Size(size.width,depth))
|
drawRect(Brush.verticalGradient(colors,endY=depth),size=Size(size.width,depth))
|
||||||
}.padding(horizontal=Cinema.gutter)) {
|
}.padding(horizontal=Cinema.gutter)) {
|
||||||
Box(Modifier.align(Alignment.CenterStart)){Brand()}
|
Box(Modifier.align(Alignment.CenterStart)){Brand()}
|
||||||
Row(Modifier.align(Alignment.Center).onPreviewKeyEvent{
|
Row(Modifier.align(Alignment.Center).onPreviewKeyEvent{
|
||||||
if(navigation!=null&&it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
|
if(navigation!=null&&it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){navigation.enter?.invoke();true}else false
|
||||||
pendingTab[0]?.cancel()
|
}.focusProperties{if(navigation!=null)down=navigation.entry},horizontalArrangement=Arrangement.spacedBy(16.dp),verticalAlignment=Alignment.CenterVertically) {
|
||||||
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.of(target).enter?.invoke()
|
|
||||||
true
|
|
||||||
}else false
|
|
||||||
}.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={if(vm.page.kind!=kind)vm.tab(kind)}){if(vm.page.kind!=kind)vm.tab(kind)}
|
||||||
focusedTab[0]=kind
|
|
||||||
// A tab already has focus. Don't schedule its delayed initial-focus
|
|
||||||
// request again when the section changes: it can steal the next press.
|
|
||||||
vm.focusId="tab:$kind"
|
|
||||||
if(vm.page.kind!=kind)activate(kind)
|
|
||||||
}){pendingTab[0]?.cancel();if(vm.page.kind!=kind)select(kind)}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(9.dp)) {
|
Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(9.dp)) {
|
||||||
|
|
@ -102,39 +66,16 @@ import androidx.compose.ui.text.input.TextFieldValue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** [episodeTitles] labels episodes by number and name, for rows already inside their show. [onClick] replaces opening details. */
|
@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null) {
|
||||||
/** [selectedItem] is marked and is where [entryFocus] enters, e.g. the episode a season page shows. */
|
|
||||||
@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null,entryFocus:FocusRequester?=null,episodeTitles:Boolean=false,initialItem:String?=null,selectedItem:String?=initialItem,up:FocusRequester?=null,onFocused:((Title)->Unit)?=null,onClick:((Title)->Unit)?=null) {
|
|
||||||
val initial=remember(rowId){items.indexOfFirst{it.id==initialItem}.coerceAtLeast(0)}
|
|
||||||
val entry=items.indexOfFirst{it.id==selectedItem}.takeIf{it>=0} ?: initial
|
|
||||||
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(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()) {
|
||||||
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)}
|
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,onMove={anticipateTileMove(vm,items,index,it,0)})}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
|
||||||
* 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) {
|
|
||||||
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
|
||||||
Key.DirectionRight->if(columns==0||index%columns<columns-1)index+1 else -1
|
Key.DirectionRight->if(columns==0||index%columns<columns-1)index+1 else -1
|
||||||
|
|
@ -145,12 +86,12 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
|
||||||
items.getOrNull(target)?.let{vm.anticipate(it,backdrop=false)}
|
items.getOrNull(target)?.let{vm.anticipate(it,backdrop=false)}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,initialFocus:Boolean=false,modifier:Modifier=Modifier,onMove:(Key)->Unit={},episodeTitle:Boolean=false,current:Boolean=false,onFocused:((Title)->Unit)?=null,onClick:((Title)->Unit)?=null) {
|
@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,onMove:(Key)->Unit={}) {
|
||||||
var focused by remember{mutableStateOf(false)}
|
var focused by remember{mutableStateOf(false)}
|
||||||
val requester=remember{FocusRequester()}
|
val requester=remember{FocusRequester()}
|
||||||
val scale by animateFloatAsState(if(focused)1.035f else 1f,tween(180),label="artworkFocus")
|
val scale by animateFloatAsState(if(focused)1.035f else 1f,tween(180),label="artworkFocus")
|
||||||
LaunchedEffect(Unit){if(vm.focusId==focusKey||initialFocus){delay(220);runCatching{requester.requestFocus()}}}
|
LaunchedEffect(Unit){if(vm.focusId==focusKey){delay(220);runCatching{requester.requestFocus()}}}
|
||||||
Column(modifier.then(if(fillWidth)Modifier.fillMaxWidth()else Modifier.width(if(landscape)216.dp else 132.dp)).onPreviewKeyEvent{if(it.type==KeyEventType.KeyDown)onMove(it.key);false}.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused;if(it.isFocused){vm.focusId=focusKey;onFocused?.invoke(item)}}.titleActions{vm.showActions(item)}.clickable{if(onClick!=null)onClick(item)else vm.open(item)}) {
|
Column((if(fillWidth)Modifier.fillMaxWidth()else Modifier.width(if(landscape)216.dp else 132.dp)).onPreviewKeyEvent{if(it.type==KeyEventType.KeyDown)onMove(it.key);false}.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey}.clickable{vm.open(item)}) {
|
||||||
Box(Modifier.fillMaxWidth().aspectRatio(if(landscape)16f/9f else 2f/3f).graphicsLayer{shadowElevation=if(focused)12.dp.toPx()else 0f;shape=RoundedCornerShape(Cinema.radius)}.clip(RoundedCornerShape(Cinema.radius))) {
|
Box(Modifier.fillMaxWidth().aspectRatio(if(landscape)16f/9f else 2f/3f).graphicsLayer{shadowElevation=if(focused)12.dp.toPx()else 0f;shape=RoundedCornerShape(Cinema.radius)}.clip(RoundedCornerShape(Cinema.radius))) {
|
||||||
val artwork=if(landscape&&item.type=="episode")item.thumb.ifBlank{item.art}else if(landscape)item.art.ifBlank{item.thumb}else item.thumb
|
val artwork=if(landscape&&item.type=="episode")item.thumb.ifBlank{item.art}else if(landscape)item.art.ifBlank{item.thumb}else item.thumb
|
||||||
Artwork(vm.api,artwork,Modifier.fillMaxSize(),if(landscape)720 else 450,if(landscape)405 else 675)
|
Artwork(vm.api,artwork,Modifier.fillMaxSize(),if(landscape)720 else 450,if(landscape)405 else 675)
|
||||||
|
|
@ -158,178 +99,95 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
|
||||||
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.015f)).fillMaxHeight().background(Accent,RoundedCornerShape(1.dp)))
|
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.015f)).fillMaxHeight().background(Accent,RoundedCornerShape(1.dp)))
|
||||||
}
|
}
|
||||||
WatchBadge(item,vm.watchedPercent)
|
WatchBadge(item,vm.watchedPercent)
|
||||||
if(current&&!focused)Box(Modifier.align(Alignment.TopStart).padding(6.dp).background(Color.Black.copy(alpha=.7f),RoundedCornerShape(3.dp)).padding(horizontal=6.dp,vertical=2.dp)){Text("Now viewing",color=Accent,fontSize=9.sp,lineHeight=12.sp)}
|
if(focused)Box(Modifier.fillMaxSize().border(1.5.dp,Accent,RoundedCornerShape(Cinema.radius)))
|
||||||
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(Cinema.radius)).padding(2.dp).border(1.dp,Color.Black.copy(alpha=.55f),RoundedCornerShape(Cinema.radius)))
|
|
||||||
}
|
}
|
||||||
Text(if(episodeTitle&&item.type=="episode")"${item.index}. ${item.title}"else if(item.type=="clip")item.title else if(landscape)item.displayTitle else item.title,color=if(focused)Accent else Cinema.secondary,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp))
|
Text(if(landscape)item.displayTitle else item.title,color=if(focused)Accent else Cinema.secondary,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp))
|
||||||
Text(if(episodeTitle&&item.type=="episode")listOf(if(item.duration>0)"${item.duration/60000} min"else "",item.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(" · ")
|
Text(if(landscape)item.subtitle else item.year.ifBlank{item.subtitle},color=Muted,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=1.dp))
|
||||||
else if(landscape)item.subtitle else item.year.ifBlank{item.subtitle},color=Muted,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=1.dp))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable fun LibraryScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation) {
|
@Composable fun LibraryScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation) {
|
||||||
// Discover is a retained DiscoveryScreen (see KaleidoApp); this is only the A–Z library.
|
if(!vm.allTitles){DiscoveryScreen(vm,home=false,navigation=navigation);return}
|
||||||
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)}
|
||||||
val discoverFocus=remember{FocusRequester()};val libraryFocus=remember{FocusRequester()};val categoriesFocus=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
|
|
||||||
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,modifier=Modifier.focusRequester(discoverFocus).focusProperties{right=libraryFocus},onClick={vm.setAll(false)})
|
NavigationLabel("Discover",!vm.allTitles){vm.setAll(false)}
|
||||||
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("Library · A–Z",vm.allTitles,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",Modifier.focusRequester(sectionFocus).focusProperties{left=categoriesFocus}){sectionMenu=true}
|
if(vm.sections.count{it.type==vm.section?.type}>1)TvButton(vm.section?.title ?: "Library"){sectionMenu=true}
|
||||||
|
else if(!vm.allTitles)Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp)
|
||||||
}
|
}
|
||||||
if(vm.categories&&vm.genre.isBlank()) {
|
if(vm.section==null&&!vm.busy)EmptyState("No $name library","This server has no matching library.")
|
||||||
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.unwatched)"Unwatched ✓"else "Unwatched",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus},selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)}
|
TvButton((if(vm.genre.isBlank())"All genres"else vm.genres.firstOrNull{it.first==vm.genre}?.second ?: "Genre")+" ⌄"){genreMenu=true}
|
||||||
TvButton((sortLabels.firstOrNull{it.first==vm.sort}?.second ?: "Title: A–Z")+" ⌄",Modifier.focusProperties{right=FocusRequester.Cancel}){sortMenu=true}
|
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")+" ⌄"){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()}}
|
||||||
LaunchedEffect(vm.libraryJumpRequest){
|
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()) {
|
||||||
val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size} ?: return@LaunchedEffect
|
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)})}
|
||||||
grid.scrollToItem(index)
|
if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another genre or watch filter.")}
|
||||||
}
|
|
||||||
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 DetailsScreen(vm:KaleidoViewModel) {
|
||||||
|
val item=vm.detail ?: return
|
||||||
|
LazyColumn(contentPadding=PaddingValues(bottom=32.dp),verticalArrangement=Arrangement.spacedBy(15.dp),modifier=Modifier.fillMaxSize()) {
|
||||||
|
item(key="details") {
|
||||||
|
Box(Modifier.fillMaxWidth().height(if(item.type in listOf("movie","episode"))432.dp else 304.dp)) {
|
||||||
|
Artwork(vm.api,item.art,Modifier.fillMaxSize(),1920,1080)
|
||||||
|
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.83f),Ink.copy(alpha=.05f)))))
|
||||||
|
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Color.Black.copy(alpha=.12f),.5f to Color.Transparent,1f to Ink)))
|
||||||
|
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=18.dp)){vm.back()}
|
||||||
|
Column(Modifier.align(Alignment.CenterStart).padding(start=Cinema.gutter,top=30.dp).width(490.dp)) {
|
||||||
|
if(item.type=="episode")Text(item.grandparentTitle,color=Cinema.secondary,fontSize=12.sp,lineHeight=17.sp,fontWeight=FontWeight.Medium)
|
||||||
|
Text(item.title,color=Accent,fontSize=34.sp,lineHeight=37.sp,fontWeight=FontWeight.Bold,letterSpacing=(-1).sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(bottom=9.dp))
|
||||||
|
Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) {
|
||||||
|
Text(listOf(item.subtitle,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.5.sp,lineHeight=19.sp,maxLines=if(item.type in listOf("movie","episode"))4 else 3,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=11.dp,bottom=18.dp))
|
||||||
|
if(item.type!="collection")Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
|
||||||
|
ActionButton(if(item.offset>0)"Resume · ${item.offset/60000} min"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,primary=true,initialFocus=true){vm.play(item)}
|
||||||
|
if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay){vm.play(item,true)}
|
||||||
|
if(item.type in listOf("movie","episode"))IconControl(if(item.isWatched(vm.watchedPercent))Icons.Outlined.CheckCircle else Icons.Outlined.Check,"Mark ${if(item.isWatched(vm.watchedPercent))"unwatched"else "watched"}",selected=item.isWatched(vm.watchedPercent)){vm.mark(item)}
|
||||||
|
}
|
||||||
|
if(item.media.isNotEmpty())Text(item.media.first().let{m->listOf(m.resolution.uppercase(),m.videoCodec.uppercase(),m.audioCodec.uppercase()).joinToString(" · ")},color=Muted,fontSize=9.sp,lineHeight=13.sp,modifier=Modifier.padding(top=16.dp))
|
||||||
|
if(item.cast.isNotEmpty())Text(item.cast.take(5).joinToString(" · "),color=Cinema.quiet,fontSize=10.sp,lineHeight=15.sp,maxLines=2,modifier=Modifier.padding(top=8.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(vm.children.isNotEmpty())item{MediaRow(vm,if(item.type=="show")"Seasons"else if(item.type=="season")"Episodes"else "In this collection",vm.children,"children:${item.id}",landscape=item.type=="season")}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable fun SearchScreen(vm:KaleidoViewModel) {
|
@Composable fun SearchScreen(vm:KaleidoViewModel) {
|
||||||
val field=remember{FocusRequester()};val resultsFocus=remember{FocusRequester()};val clearFocus=remember{FocusRequester()}
|
Column(Modifier.fillMaxSize().padding(horizontal=Cinema.gutter)) {
|
||||||
val keyboard=LocalSoftwareKeyboardController.current
|
Row(Modifier.fillMaxWidth().padding(top=12.dp,bottom=18.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(25.dp)) {
|
||||||
var value by remember{mutableStateOf(TextFieldValue(vm.query,TextRange(vm.query.length)))}
|
Text("Search",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)
|
||||||
fun query(text:String){value=TextFieldValue(text,TextRange(text.length));vm.search(text)}
|
val requester=remember{FocusRequester()}
|
||||||
LaunchedEffect(vm.query){if(vm.query!=value.text)value=TextFieldValue(vm.query,TextRange(vm.query.length))}
|
LaunchedEffect(Unit){delay(150);requester.requestFocus()}
|
||||||
val groups=remember(vm.searchResults,vm.query){searchGroups(vm.searchResults.titles,vm.query)}
|
OutlinedTextField(vm.query,{vm.search(it)},placeholder={Text("Movies, shows, episodes",fontSize=12.sp)},leadingIcon={Icon(Icons.Outlined.Search,null,Modifier.size(19.dp))},singleLine=true,modifier=Modifier.weight(1f).height(49.dp).focusRequester(requester),shape=RoundedCornerShape(6.dp),textStyle=androidx.compose.ui.text.TextStyle(fontSize=13.sp),colors=OutlinedTextFieldDefaults.colors(unfocusedBorderColor=Color.White.copy(alpha=.15f),focusedBorderColor=Accent))
|
||||||
val people=vm.searchResults.people
|
Text(if(vm.query.isBlank())"Your collection"else "${vm.searchResults.size} results",color=Muted,fontSize=11.sp)
|
||||||
val hasResults=groups.isNotEmpty()||people.isNotEmpty()
|
|
||||||
fun enterResults(){keyboard?.hide();runCatching{resultsFocus.requestFocus()}}
|
|
||||||
Column(Modifier.fillMaxSize()) {
|
|
||||||
Row(Modifier.fillMaxWidth().padding(start=Cinema.gutter,end=Cinema.gutter,top=12.dp,bottom=12.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(18.dp)) {
|
|
||||||
Text("Search",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp,modifier=Modifier.padding(end=7.dp))
|
|
||||||
// Returning from a result's details restores that result instead.
|
|
||||||
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,
|
|
||||||
keyboardOptions=KeyboardOptions(imeAction=ImeAction.Search),keyboardActions=KeyboardActions(onSearch={if(hasResults)enterResults()else keyboard?.hide()}),
|
|
||||||
// Down enters results; Right at the end reaches Clear without deleting character by character.
|
|
||||||
modifier=Modifier.weight(1f).height(49.dp).focusRequester(field).onPreviewKeyEvent{
|
|
||||||
if(it.type!=KeyEventType.KeyDown)false
|
|
||||||
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&&value.text.isNotEmpty()&&value.selection.collapsed&&value.selection.end==value.text.length){keyboard?.hide();runCatching{clearFocus.requestFocus()};true}
|
|
||||||
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))
|
|
||||||
if(value.text.isNotEmpty())ActionButton("Clear",Icons.Outlined.Close,modifier=Modifier.focusRequester(clearFocus).focusProperties{left=field;if(hasResults)down=resultsFocus}){
|
|
||||||
// Move focus before removing this button from the composition.
|
|
||||||
runCatching{field.requestFocus()};query("")
|
|
||||||
}
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
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.
|
|
||||||
LazyColumn(Modifier.fillMaxSize(),contentPadding=PaddingValues(top=4.dp,bottom=30.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) {
|
|
||||||
groups.forEachIndexed{index,group->
|
|
||||||
item(key="search-${group.first}"){MediaRow(vm,group.first,group.second,"search-${group.first}",landscape=group.first=="Episodes",entryFocus=if(index==0)resultsFocus else null)}
|
|
||||||
}
|
|
||||||
if(people.isNotEmpty())item(key="search-people"){PeopleRow(vm,people,if(groups.isEmpty())resultsFocus else null)}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun searchGroups(titles:List<Title>,query:String=""):List<Pair<String,List<Title>>> = rankSearchGroups(
|
|
||||||
titles,query,Title::type
|
|
||||||
){title->listOf(title.title,title.parentTitle,title.grandparentTitle)}
|
|
||||||
|
|
||||||
@Composable private fun PeopleRow(vm:KaleidoViewModel,people:List<CastMember>,entryFocus:FocusRequester?) {
|
|
||||||
Column {
|
|
||||||
Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading("People")}
|
|
||||||
LazyRow(contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer(fallback=entryFocus ?: FocusRequester.Default)) {
|
|
||||||
itemsIndexed(people,key={_,it->it.id}){index,actor->
|
|
||||||
var focused by remember{mutableStateOf(false)}
|
|
||||||
Column(Modifier.width(108.dp).then(if(index==0&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier).navigationSound().onFocusChanged{focused=it.isFocused}
|
|
||||||
.clickable{vm.openActor(actor)}.semantics{contentDescription=actor.name},horizontalAlignment=Alignment.CenterHorizontally) {
|
|
||||||
ActorPortrait(vm.api,actor,Modifier.size(86.dp).then(if(focused)Modifier.border(2.dp,Accent,CircleShape)else Modifier))
|
|
||||||
Text(actor.name,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=14.sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
if(vm.query.isBlank())Text("Find something worth watching.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(top=8.dp))
|
||||||
|
LazyVerticalGrid(GridCells.Fixed(3),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),contentPadding=PaddingValues(top=8.dp,bottom=30.dp)) {
|
||||||
|
itemsIndexed(vm.searchResults,key={_,it->it.id}){index,item->MediaTile(vm,item,"search:${item.id}",landscape=true,fillWidth=true,onMove={anticipateTileMove(vm,vm.searchResults,index,it,3)})}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
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")
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import android.media.AudioFormat
|
|
||||||
import androidx.media3.common.Format
|
|
||||||
import androidx.media3.common.MimeTypes
|
|
||||||
import androidx.media3.common.util.UnstableApi
|
|
||||||
import androidx.media3.exoplayer.audio.AudioSink
|
|
||||||
import androidx.media3.exoplayer.audio.ForwardingAudioSink
|
|
||||||
|
|
||||||
/** Android rejects a center-only PCM mask; one-channel audio uses its standard mono output. */
|
|
||||||
@androidx.annotation.OptIn(UnstableApi::class)
|
|
||||||
internal class CompatibleAudioSink(sink:AudioSink):ForwardingAudioSink(sink) {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
override fun configure(config:AudioSink.AudioSinkConfig) {
|
|
||||||
val format=compatiblePcmFormat(config.format)
|
|
||||||
super.configure(if(format===config.format)config else AudioSink.AudioSinkConfig.Builder(format)
|
|
||||||
.setPreferredBufferSizeOverride(config.preferredBufferSizeOverride)
|
|
||||||
.setOutputChannelMapping(config.outputChannelMapping)
|
|
||||||
.setTimeline(config.timeline).setMediaPeriodId(config.mediaPeriodId).build())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@androidx.annotation.OptIn(UnstableApi::class)
|
|
||||||
internal fun compatiblePcmFormat(format:Format):Format =
|
|
||||||
if(format.sampleMimeType==MimeTypes.AUDIO_RAW&&format.channelCount==1&&format.channelMask!=AudioFormat.CHANNEL_OUT_MONO)
|
|
||||||
format.buildUpon().setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build()
|
|
||||||
else format
|
|
||||||
|
|
@ -40,16 +40,10 @@ import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
class DiscoveryNavigation {
|
class DiscoveryNavigation {
|
||||||
val top=FocusRequester()
|
|
||||||
var scrolled by mutableStateOf(false)
|
|
||||||
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 entry=FocusRequester()
|
||||||
val section=FocusRequester()
|
val section=FocusRequester()
|
||||||
|
val top=FocusRequester()
|
||||||
|
var scrolled by mutableStateOf(false)
|
||||||
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. */
|
||||||
|
|
|
||||||
|
|
@ -4,29 +4,20 @@ 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.animation.core.Animatable
|
|
||||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
|
||||||
import androidx.compose.animation.core.tween
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.animation.core.Animatable
|
||||||
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
|
||||||
import androidx.compose.material.icons.outlined.Info
|
import androidx.compose.material.icons.outlined.Info
|
||||||
import androidx.compose.material.icons.outlined.ChevronRight
|
import androidx.compose.material.icons.outlined.ChevronRight
|
||||||
import androidx.compose.runtime.*
|
import androidx.compose.runtime.*
|
||||||
import androidx.compose.runtime.snapshots.Snapshot
|
|
||||||
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
|
||||||
|
|
@ -36,11 +27,6 @@ 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
|
||||||
|
|
@ -51,22 +37,8 @@ import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.coroutineScope
|
import kotlinx.coroutines.coroutineScope
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.activity.compose.BackHandler
|
|
||||||
import androidx.compose.animation.core.animateFloatAsState
|
|
||||||
import androidx.compose.ui.geometry.Offset
|
|
||||||
import androidx.compose.ui.graphics.Shadow
|
|
||||||
import androidx.compose.material.icons.outlined.GridView
|
|
||||||
|
|
||||||
/** Movies, TV and Home's second row show posters; the rest landscape cards (wider TV episodes). */
|
@Composable fun HomeScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation)=DiscoveryScreen(vm,true,navigation)
|
||||||
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. */
|
|
||||||
internal const val VIEW_ALL="view-all"
|
|
||||||
/** Captions sit over artwork-led backdrops; a soft shadow keeps them readable on bright scenes. */
|
|
||||||
internal val CaptionShadow=Shadow(Color.Black.copy(alpha=.9f),Offset(0f,1.5f),6f)
|
|
||||||
internal fun isContinueHub(hub:Hub)=listOf("continue","ondeck","inprogress").any{hub.id.contains(it,true)}
|
|
||||||
|
|
||||||
private object BrowseScroll:BringIntoViewSpec {
|
private object BrowseScroll:BringIntoViewSpec {
|
||||||
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float)=0f
|
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float)=0f
|
||||||
|
|
@ -77,275 +49,101 @@ 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. */
|
||||||
* The preview never scrolls. Only the bounded catalog below it moves.
|
@Composable fun DiscoveryScreen(vm:KaleidoViewModel,home:Boolean,navigation:DiscoveryNavigation) {
|
||||||
*
|
val destination=if(home)"home"else vm.page.kind
|
||||||
* Home, Movies and TV stay composed once shown: while [active] is false the screen is neither placed
|
val source=if(home)vm.homeHubs else vm.discoverHubs
|
||||||
* 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)}
|
val restore=remember(hubs){hubs.withIndex().firstNotNullOfOrNull{(row,h)->val column=h.items.indexOfFirst{"${h.id}:${it.id}"==vm.focusId};if(column>=0)row to column else null}}
|
||||||
val restore=remember(hubs){
|
val initialRow=restore?.let{it.first+if(home)1 else 0} ?: 0
|
||||||
val focused=Snapshot.withoutReadObservation{vm.focusId}
|
// Keep the hero and adjacent rows prepared across the large Home scroll.
|
||||||
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}
|
// Without a behind window, every return discards and recomposes those cards.
|
||||||
}
|
val list=if(home)rememberLazyListState(initialFirstVisibleItemIndex=initialRow,
|
||||||
val initialRow=restore?.second ?: 0
|
cacheWindow=remember{LazyLayoutCacheWindow(aheadFraction=1f,behindFraction=1f)})
|
||||||
// Keep the hero/preview and two rows either side prepared across vertical moves (about two
|
else rememberLazyListState(initialFirstVisibleItemIndex=initialRow)
|
||||||
// viewports). Prefetch only uses spare or idle frame time (FramePrefetch), so a wider window
|
val rowStates=remember(hubs){List(hubs.size){row->LazyListState(firstVisibleItemIndex=if(restore?.first==row)restore.second else 0)}}
|
||||||
// costs no frames; a one-viewport window composed rows mid-scroll when moving back up.
|
val requesters=remember(hubs){mutableMapOf<Pair<Int,Int>,FocusRequester>()}
|
||||||
val list=rememberLazyListState(initialFirstVisibleItemIndex=initialRow,prefetchStrategy=remember{budgetedCacheWindow(ahead=2f,behind=2f)})
|
val columns=remember(hubs){mutableMapOf<Int,Int>()}
|
||||||
// The window only fills after the list has scrolled, and a change of rows resets it, so the
|
|
||||||
// next move composed rows mid-animation (a ~200 ms stall on the onn). Once the screen settles,
|
|
||||||
// nudge it so those rows compose in idle frames, then undo it.
|
|
||||||
LaunchedEffect(list,hubs){
|
|
||||||
if(hubs.isEmpty())return@LaunchedEffect
|
|
||||||
snapshotFlow{active()}.first{it}
|
|
||||||
awaitSteadyFrames(4)
|
|
||||||
if(list.isScrollInProgress)return@LaunchedEffect
|
|
||||||
val moved=list.scrollBy(1f)
|
|
||||||
val at=list.firstVisibleItemIndex to list.firstVisibleItemScrollOffset
|
|
||||||
repeat(45){withFrameNanos{}}
|
|
||||||
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
|
|
||||||
// state and each card's requester by stable Plex IDs so surviving rows/cards retain them.
|
|
||||||
val rowStateByHub=remember(destination){mutableMapOf<String,LazyListState>()}
|
|
||||||
val rowStates=remember(hubs){hubs.associate{hub->hub.id to rowStateByHub.getOrPut(hub.id){LazyListState(
|
|
||||||
firstVisibleItemIndex=if(restore?.first==hub.id)restore.third else 0,prefetchStrategy=budgetedCacheWindow(ahead=1f,behind=.5f))}}}
|
|
||||||
val requesters=remember(destination){mutableMapOf<String,FocusRequester>()}
|
|
||||||
val columns=remember(destination){mutableMapOf<String,String>()}
|
|
||||||
val pendingColumns=remember(destination){mutableMapOf<String,String>()}
|
|
||||||
val horizontalTimes=remember(destination){mutableMapOf<String,Long>()}
|
|
||||||
val navigationJob=remember{arrayOfNulls<Job>(1)}
|
val navigationJob=remember{arrayOfNulls<Job>(1)}
|
||||||
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"&&active()}}
|
val sectionEntry by remember{derivedStateOf{vm.focusId=="discovery-entry"}}
|
||||||
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 context=LocalContext.current
|
val heroFade=remember{Animatable(1f)}
|
||||||
LaunchedEffect(nextFeature){
|
LaunchedEffect(nextFeature?.item?.id){
|
||||||
val next=nextFeature?.item
|
if(home)nextFeature?.item?.let{vm.anticipate(it,cinematic=true)}
|
||||||
if(home&&next!=null)vm.anticipate(next,cinematic=true)
|
if(home&&selectedFeature!=null&&nextFeature!=null)heroFade.animateTo(0f,tween(100))
|
||||||
// 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)
|
||||||
// Home only: the large hero while it holds focus; a compact preview of the focused card otherwise.
|
var heroActive by remember{mutableStateOf(restore==null)}
|
||||||
// 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,rotating,featureIndex){
|
LaunchedEffect(home,features,heroActive,rotating,featureIndex){
|
||||||
snapshotFlow{heroMode.value&&active()}.collectLatest{if(home&&it&&rotating&&features.size>1){delay(12000);featureIndex=(featureIndex+1)%features.size}}
|
if(home&&heroActive&&rotating&&features.size>1){delay(12000);featureIndex=(featureIndex+1)%features.size}
|
||||||
}
|
}
|
||||||
val heroFocus=remember{FocusRequester()}
|
val heroFocus=remember{FocusRequester()}
|
||||||
val staging=remember{CardStaging()}
|
val rowOffset=if(home)1 else 0
|
||||||
LaunchedEffect(staging){delay(1000);staging.entering=false}
|
suspend fun moveToRow(row:Int,column:Int)=coroutineScope {
|
||||||
suspend fun focusHero(){repeat(4){withFrameNanos{};if(runCatching{heroFocus.requestFocus()}.getOrDefault(false))return}}
|
val state=rowStates.getOrNull(row) ?: return@coroutineScope
|
||||||
suspend fun moveToRow(hubId:String,titleId:String)=coroutineScope {
|
val scrolling=launch{list.animateBrowseTo(row+rowOffset)}
|
||||||
val row=hubs.indexOfFirst{it.id==hubId}
|
state.scrollToItem(column)
|
||||||
val hub=hubs.getOrNull(row) ?: return@coroutineScope
|
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==row+rowOffset}&&state.layoutInfo.visibleItemsInfo.any{it.index==column}}.first{it}
|
||||||
val column=hub.items.indexOfFirst{it.id==titleId}
|
withFrameNanos{}
|
||||||
if(column<0)return@coroutineScope
|
runCatching{requesters.getOrPut(row to column){FocusRequester()}.requestFocus()}
|
||||||
val state=rowStates[hub.id] ?: return@coroutineScope
|
|
||||||
val focusKey="$hubId:$titleId"
|
|
||||||
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 scrolling=launch{list.animateBrowseTo(row)}
|
|
||||||
if(!state.layoutInfo.visibleItemsInfo.any{it.index==column})state.requestScrollToItem(column)
|
|
||||||
if(!focused) {
|
|
||||||
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==row}&&state.layoutInfo.visibleItemsInfo.any{it.index==column}}.first{it}
|
|
||||||
// A card that replaced another (a live refresh) may compose a frame or two later; until it
|
|
||||||
// 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)}
|
||||||
focusHero();scrolling.join()
|
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==0}}.first{it}
|
||||||
|
withFrameNanos{};runCatching{heroFocus.requestFocus()};scrolling.join()
|
||||||
}
|
}
|
||||||
/** Whether focus is inside this screen; a card key in [KaleidoViewModel.focusId] alone doesn't mean it is. */
|
LaunchedEffect(home,features.isNotEmpty()){if(home&&vm.focusId=="home-feature"){list.scrollToItem(0);withFrameNanos{};runCatching{heroFocus.requestFocus()}}}
|
||||||
val screenFocus=remember{booleanArrayOf(false)}
|
DisposableEffect(navigation,list,hubs){
|
||||||
LaunchedEffect(hubs) {
|
|
||||||
val old=previousHubs
|
|
||||||
if(old==hubs)return@LaunchedEffect
|
|
||||||
navigationJob[0]?.cancel();navigationJob[0]=null
|
|
||||||
val focus=Snapshot.withoutReadObservation{vm.focusId}
|
|
||||||
val oldRow=old.indexOfFirst{hub->hub.items.any{"${hub.id}:${it.id}"==focus}}
|
|
||||||
val oldHub=old.getOrNull(oldRow)
|
|
||||||
val oldColumn=oldHub?.items?.indexOfFirst{"${oldHub.id}:${it.id}"==focus} ?: -1
|
|
||||||
val oldTitle=oldHub?.items?.getOrNull(oldColumn)
|
|
||||||
|
|
||||||
val hubIds=hubs.map{it.id}.toSet()
|
|
||||||
val cardKeys=hubs.flatMap{hub->hub.items.map{"${hub.id}:${it.id}"}+"${hub.id}:$VIEW_ALL"}.toSet()
|
|
||||||
rowStateByHub.keys.retainAll(hubIds)
|
|
||||||
requesters.keys.retainAll(cardKeys)
|
|
||||||
columns.keys.retainAll(hubIds)
|
|
||||||
pendingColumns.keys.retainAll(hubIds)
|
|
||||||
horizontalTimes.keys.retainAll(hubIds)
|
|
||||||
hubs.forEach{hub->
|
|
||||||
if(columns[hub.id]?.let{id->hub.items.any{it.id==id}}!=true)hub.items.firstOrNull()?.let{columns[hub.id]=it.id} ?: columns.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
|
|
||||||
// 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) {
|
|
||||||
val sameHub=hubs.firstOrNull{it.id==oldHub.id}
|
|
||||||
val target=sameHub?.let{hub->hub.items.firstOrNull{it.id==oldTitle.id}?.let{hub to it}}
|
|
||||||
?: hubs.firstNotNullOfOrNull{hub->hub.items.firstOrNull{it.id==oldTitle.id}?.let{hub to it}}
|
|
||||||
?: (sameHub?.takeIf{it.items.isNotEmpty()} ?: hubs.withIndex().filter{it.value.items.isNotEmpty()}
|
|
||||||
.minByOrNull{kotlin.math.abs(it.index-oldRow)}?.value)
|
|
||||||
?.let{hub->hub to hub.items[oldColumn.coerceIn(0,hub.items.lastIndex)]}
|
|
||||||
if(target!=null) {
|
|
||||||
val (hub,item)=target
|
|
||||||
val survived=hub.id==oldHub.id&&item.id==oldTitle.id
|
|
||||||
columns[hub.id]=item.id;pendingColumns[hub.id]=item.id
|
|
||||||
vm.focusId="${hub.id}:${item.id}"
|
|
||||||
hovered.value=item;heroActive=false
|
|
||||||
if(!survived)navigationJob[0]=scope.launch{withFrameNanos{};moveToRow(hub.id,item.id)}
|
|
||||||
}else {
|
|
||||||
hovered.value=null
|
|
||||||
if(home&&feature!=null) {
|
|
||||||
vm.focusId="home-feature";heroActive=true
|
|
||||||
navigationJob[0]=scope.launch{list.scrollToItem(0);focusHero()}
|
|
||||||
}else if(!home) {
|
|
||||||
vm.focusId="discovery-entry"
|
|
||||||
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{local.section.requestFocus()}}
|
|
||||||
}else {
|
|
||||||
vm.focusId=""
|
|
||||||
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{navigation.top.requestFocus()}}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LaunchedEffect(home,features.isNotEmpty()){if(home&&active()&&vm.focusId=="home-feature"){heroActive=true;list.scrollToItem(0);focusHero()}}
|
|
||||||
DisposableEffect(local,list,hubs){
|
|
||||||
navigation.scrolled=false
|
navigation.scrolled=false
|
||||||
local.enter={
|
navigation.enter={(if(home)activeFeature.value else hubs.firstOrNull()?.items?.firstOrNull())?.let{vm.anticipate(it,cinematic=home)};navigationJob[0]?.cancel();navigationJob[0]=scope.launch{list.animateBrowseTo(0);rowStates.firstOrNull()?.scrollToItem(0);withFrameNanos{};runCatching{(if(home)heroFocus else navigation.section).requestFocus()}}}
|
||||||
navigationJob[0]?.cancel()
|
onDispose{navigation.enter=null}
|
||||||
// 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.
|
|
||||||
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 {
|
|
||||||
if(heroActive)runCatching{heroFocus.requestFocus()}
|
|
||||||
navigationJob[0]=scope.launch{moveToHero()}
|
|
||||||
activeFeature.value?.let{vm.anticipate(it,cinematic=true)}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
onDispose{local.enter=null}
|
|
||||||
}
|
|
||||||
LaunchedEffect(navigation.pendingEntry,destination) {
|
|
||||||
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.
|
|
||||||
var catalogFocus by remember{mutableStateOf(false)}
|
|
||||||
val inCatalog by remember{derivedStateOf{catalogFocus&&vm.focusId!="home-feature"}}
|
|
||||||
BackHandler(enabled=inCatalog&&vm.playing==null) {
|
|
||||||
navigationJob[0]?.cancel()
|
|
||||||
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.
|
|
||||||
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.
|
|
||||||
val seenReturn=remember{intArrayOf(vm.playbackReturn)}
|
|
||||||
LaunchedEffect(vm.playbackReturn) {
|
|
||||||
if(vm.playbackReturn==seenReturn[0])return@LaunchedEffect
|
|
||||||
seenReturn[0]=vm.playbackReturn
|
|
||||||
if(!active())return@LaunchedEffect
|
|
||||||
withFrameNanos{}
|
|
||||||
val key=vm.focusId
|
|
||||||
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)}
|
|
||||||
val sectionChoices=vm.sections.filter{it.type==vm.section?.type}
|
|
||||||
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().onFocusChanged{screenFocus[0]=it.hasFocus}) {
|
BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||||
val heroHeight=maxHeight*.80f-62.dp
|
val heroHeight=maxHeight*.80f-62.dp
|
||||||
if(home)HomeBackdrop(vm.api,preview,feature,heroMode,vm.colourWash)
|
if(home)HomeBackdrop(vm.api,hovered,feature,heroActive)
|
||||||
else FocusedPreviewCanvas(vm,preview,hubs.firstOrNull()?.items?.firstOrNull(),vm.colourWash)
|
else FocusedPreviewCanvas(vm,hovered,hubs.firstOrNull()?.items?.firstOrNull(),destination)
|
||||||
if(home) {
|
Column(Modifier.fillMaxSize().padding(top=62.dp)) {
|
||||||
val lift=with(density){HeaderLift.toPx()}
|
if(!home) {
|
||||||
// Leaving for the rows, the hero lifts away as the preview rises in; the reverse settles it back.
|
Row(Modifier.fillMaxWidth().height(39.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) {
|
||||||
HeaderLayer({compact.value},{heroMode.value},true,lift,Modifier.padding(top=62.dp).fillMaxWidth().height(heroHeight)) {
|
Text(title,color=Accent,fontSize=19.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(end=20.dp))
|
||||||
feature?.let{item->Box(Modifier.fillMaxSize()) {
|
if(!home) {
|
||||||
|
NavigationLabel("Discover",true,modifier=Modifier.focusRequester(navigation.section).focusProperties{up=navigation.top;down=navigation.entry},initialFocus=sectionEntry){}
|
||||||
|
NavigationLabel("Library · A–Z",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry}){vm.setAll(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),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)) {
|
||||||
FadingCopy(selectedFeature,{it.item.id},lift,contentAlignment=Alignment.BottomStart){HeroCopy(vm,it)}
|
Column(Modifier.graphicsLayer{alpha=heroFade.value}) {
|
||||||
|
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{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
|
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{moveToRow(0,0)};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)}
|
||||||
|
|
@ -355,91 +153,34 @@ 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=posterRow(hub,row,destination)
|
val poster=hub.items.firstOrNull()?.type in listOf("movie","show","season")&&!hub.title.contains("Continue",true)&&(destination=="movies"||destination=="tv"||row==1)
|
||||||
val wideEpisode=destination=="tv"&&!poster
|
val wideEpisode=destination=="tv"&&!poster
|
||||||
val continuing=isContinueHub(hub)
|
Column {
|
||||||
// A row with more titles than Plex returned ends with a "View all" card.
|
Text(hub.title,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=5.dp))
|
||||||
val viewAll=hub.more&&hub.key.isNotBlank()
|
LazyRow(state=rowStates[row],contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=3.dp,bottom=3.dp),horizontalArrangement=Arrangement.spacedBy(10.dp)) {
|
||||||
fun idAt(index:Int)=if(index==hub.items.size)VIEW_ALL else hub.items[index].id
|
itemsIndexed(hub.items,key={_,t->t.id},contentType={_,_->poster}) {column,item->
|
||||||
fun indexOf(id:String)=if(id==VIEW_ALL)hub.items.size else hub.items.indexOfFirst{it.id==id}
|
val requester=requesters.getOrPut(row to column){FocusRequester()}
|
||||||
fun rowKeys(column:Int)=Modifier.onPreviewKeyEvent{event->
|
BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)navigation.entry else null,requester,
|
||||||
|
Modifier.onPreviewKeyEvent{event->
|
||||||
if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionLeft,Key.DirectionRight)) {
|
if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionLeft,Key.DirectionRight)) {
|
||||||
val pendingId=pendingColumns[hub.id]
|
val target=column+if(event.key==Key.DirectionLeft)-1 else 1
|
||||||
val pendingIndex=pendingId?.let(::indexOf)?.takeIf{it>=0} ?: column
|
if(target in hub.items.indices) {
|
||||||
val target=pendingIndex+if(event.key==Key.DirectionLeft)-1 else 1
|
vm.anticipate(hub.items[target],cinematic=home)
|
||||||
if(target in 0 until hub.items.size+if(viewAll)1 else 0) {
|
|
||||||
val now=event.nativeKeyEvent.eventTime
|
|
||||||
val rapid=now-(horizontalTimes[hub.id] ?: 0L)<160L
|
|
||||||
horizontalTimes[hub.id]=now
|
|
||||||
pendingColumns[hub.id]=idAt(target)
|
|
||||||
navigationJob[0]?.cancel()
|
navigationJob[0]?.cancel()
|
||||||
val state=rowStates[hub.id]!!
|
val state=rowStates[row]
|
||||||
navigationJob[0]=scope.launch {
|
|
||||||
// KeyDown/KeyUp can arrive between frames. Commit focus once
|
|
||||||
// on the next frame, so accessibility doesn't force an extra
|
|
||||||
// catalog layout between those events. Bursts keep the latest
|
|
||||||
// logical column instead of dropping a move while awaiting layout.
|
|
||||||
withFrameNanos{}
|
|
||||||
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}
|
||||||
|
if(visible)runCatching{requesters.getOrPut(row to target){FocusRequester()}.requestFocus()}
|
||||||
|
navigationJob[0]=scope.launch {
|
||||||
val anchor=(target-1).coerceAtLeast(0)
|
val anchor=(target-1).coerceAtLeast(0)
|
||||||
if(visible&&!rapid) {
|
if(visible) {
|
||||||
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{state.scrollToItem(anchor);withFrameNanos{};runCatching{requesters.getOrPut(row to target){FocusRequester()}.requestFocus()}}
|
||||||
// Schedule one layout for the next frame instead of forcing
|
|
||||||
// synchronous composition between rapid remote events.
|
|
||||||
state.requestScrollToItem(anchor)
|
|
||||||
snapshotFlow{state.layoutInfo.visibleItemsInfo.any{it.index==target}}.first{it}
|
|
||||||
withFrameNanos{};runCatching{requesters.getOrPut("${hub.id}:${idAt(target)}"){FocusRequester()}.requestFocus()}
|
|
||||||
}
|
|
||||||
// A held direction snaps to the latest anchor. Repeatedly
|
|
||||||
// cancelling pixel animations and decoding transient backdrops
|
|
||||||
// costs more than the focus move; predict only after it settles.
|
|
||||||
if(rapid){delay(70);hub.items.getOrNull(target)?.let{anticipateCard(it)}}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
|
|
@ -447,35 +188,20 @@ 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&&feature!=null)moveToHero()else{withFrameNanos{};runCatching{(if(home)navigation.top else local.section).requestFocus()}}}
|
navigationJob[0]=scope.launch{if(home)moveToHero()else{withFrameNanos{};runCatching{navigation.section.requestFocus()}}}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
navigationJob[0]?.cancel()
|
navigationJob[0]?.cancel()
|
||||||
val target=row+if(event.key==Key.DirectionUp)-1 else 1
|
val target=row+if(event.key==Key.DirectionUp)-1 else 1
|
||||||
if(target in hubs.indices) {
|
if(target in hubs.indices) {
|
||||||
val targetHub=hubs[target]
|
val col=(columns[target] ?: 0).coerceAtMost(hubs[target].items.lastIndex)
|
||||||
val selectedId=columns[targetHub.id]
|
vm.anticipate(hubs[target].items[col],cinematic=home)
|
||||||
val col=targetHub.items.indexOfFirst{it.id==selectedId}.takeIf{it>=0} ?: 0
|
navigationJob[0]=scope.launch{moveToRow(target,col)}
|
||||||
anticipateCard(hubs[target].items[col])
|
|
||||||
navigationJob[0]=scope.launch{moveToRow(targetHub.id,targetHub.items[col].id)}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
}else false
|
}else false
|
||||||
}
|
},onHovered={columns[row]=column;hovered.value=it;heroActive=false})
|
||||||
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))
|
|
||||||
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->
|
|
||||||
val focusKey="${hub.id}:${item.id}"
|
|
||||||
val requester=requesters.getOrPut(focusKey){FocusRequester()}
|
|
||||||
val rail=rowStates[hub.id]!!
|
|
||||||
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") {
|
|
||||||
val focusKey="${hub.id}:$VIEW_ALL"
|
|
||||||
ViewAllCard(vm,hub,focusKey,poster,wideEpisode,requesters.getOrPut(focusKey){FocusRequester()},rowKeys(hub.items.size))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -489,290 +215,59 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
|
||||||
Spacer(Modifier.height(14.dp));TvButton("Open library",onClick={vm.setAll(true)});Spacer(Modifier.height(8.dp));TvButton("Try again",onClick={vm.retry()})
|
Spacer(Modifier.height(14.dp));TvButton("Open library",onClick={vm.setAll(true)});Spacer(Modifier.height(8.dp));TvButton("Try again",onClick={vm.retry()})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(sectionMenu)ChoiceDialog("Libraries",sectionChoices.map{it.title},sectionChoices.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(sectionChoices[it]);sectionMenu=false}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Home's compact header: the preview block Movies and TV show above their rows. */
|
|
||||||
/** Home's compact header (after Silo's): its height below the top bar, and its title art. */
|
|
||||||
private val HomePreviewHeight=228.dp
|
|
||||||
private val HomeLogo=DpSize(300.dp,64.dp)
|
|
||||||
/** Movies and TV use the same preview below their Discover/Library/Categories line, slightly smaller. */
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The hero ([hero]) or the compact preview, faded and lifted by [progress] in its own layer: one
|
|
||||||
* animation, no per-frame composition or layout. Both stay composed: the hidden one is a zero-alpha
|
|
||||||
* layer, which the renderer skips, without semantics. Composing the hero again on every return to it
|
|
||||||
* cost a frame there.
|
|
||||||
*/
|
|
||||||
@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. */
|
/** 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) {
|
@Composable private fun HomeBackdrop(api:PlexApi,hovered:State<Title?>,feature:Title?,heroActive:Boolean) {
|
||||||
val target=if(heroMode.value)feature?.let{it.art.ifBlank{it.thumb} to true}else preview.value?.let{previewArt(it) to false}
|
var displayed by remember{mutableStateOf<Title?>(null)}
|
||||||
// Keep the last artwork while the preview waits for its first resting card.
|
val current=if(heroActive)feature else hovered.value ?: feature
|
||||||
val last=remember{arrayOfNulls<Pair<String,Boolean>>(1)}
|
LaunchedEffect(current?.id){if(!heroActive)delay(90);displayed=current}
|
||||||
val shown=target ?: last[0] ?: feature?.let{it.art.ifBlank{it.thumb} to true}
|
(displayed ?: feature)?.let{BrowseBackdrop(api,it.art.ifBlank{it.thumb},Modifier.fillMaxSize(),cinematic=true,animate=heroActive)}
|
||||||
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) {
|
@Composable private fun FocusedPreviewCanvas(vm:KaleidoViewModel,hovered:State<Title?>,fallback:Title?,destination:String) {
|
||||||
val feature=preview.value ?: fallback
|
var displayed by remember{mutableStateOf<Title?>(null)}
|
||||||
|
val current=hovered.value
|
||||||
|
LaunchedEffect(current?.id){delay(120);displayed=current}
|
||||||
|
val feature=displayed ?: fallback
|
||||||
|
val metadata by produceState(feature,feature?.id){value=feature;feature?.let{value=vm.previewDetails(it)}}
|
||||||
Box(Modifier.fillMaxSize()) {
|
Box(Modifier.fillMaxSize()) {
|
||||||
feature?.let{BrowseBackdrop(vm.api,previewArt(it),Modifier.fillMaxSize(),header=true,wash=wash,animate=true)}
|
feature?.let{item->
|
||||||
Box(Modifier.padding(start=Cinema.gutter,top=104.dp).height(SectionPreviewHeight)) {
|
BrowseBackdrop(vm.api,item.art,Modifier.fillMaxSize())
|
||||||
PreviewBlock(vm,feature,SectionLogo)
|
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(". ")}) {
|
||||||
|
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. */
|
@Composable private fun BrowseCard(vm:KaleidoViewModel,item:Title,focusKey:String,poster:Boolean,wideEpisode:Boolean,entry:FocusRequester?,requester:FocusRequester,modifier:Modifier,onHovered:(Title)->Unit) {
|
||||||
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
|
|
||||||
* 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 cards are composed whole: they come from
|
|
||||||
* 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 {
|
|
||||||
var entering=true
|
|
||||||
private var count=0
|
|
||||||
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) {
|
|
||||||
var focused by remember{mutableStateOf(false)}
|
var focused by remember{mutableStateOf(false)}
|
||||||
val stage=remember{staging.frames()}
|
|
||||||
var filled by remember{mutableStateOf(stage<0)}
|
|
||||||
if(!filled)LaunchedEffect(Unit){repeat(stage+1){withFrameNanos{}};filled=true}
|
|
||||||
val width=if(poster)120.dp else if(wideEpisode)264.dp else 214.dp
|
val width=if(poster)120.dp else if(wideEpisode)264.dp else 214.dp
|
||||||
val image=if(poster)item.poster.ifBlank{item.thumb}else if(item.type=="episode")item.still.ifBlank{item.thumb}.ifBlank{item.art}else item.art.ifBlank{item.thumb}
|
val image=if(poster)item.poster.ifBlank{item.thumb}else if(item.type=="episode")item.still.ifBlank{item.thumb}.ifBlank{item.art}else item.art.ifBlank{item.thumb}
|
||||||
// Only the card being restored launches an effect; checking inside one per card cost a
|
LaunchedEffect(Unit){if(vm.focusId==focusKey){withFrameNanos{};runCatching{requester.requestFocus()};onHovered(item)}}
|
||||||
// coroutine for every card in a newly shown section.
|
Column(modifier.width(width).then(if(entry!=null)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).navigationSound().onFocusChanged{
|
||||||
if(remember{Snapshot.withoutReadObservation{vm.focusId==focusKey}})LaunchedEffect(Unit){withFrameNanos{};runCatching{requester.requestFocus()};onHovered(item)}
|
|
||||||
// A slight lift read in the layer: no animation or recomposition per card, bounds never move.
|
|
||||||
Column(modifier.width(width).graphicsLayer{val lift=if(focused)1.05f else 1f;scaleX=lift;scaleY=lift}.then(if(entry!=null)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).navigationSound().onFocusChanged{
|
|
||||||
focused=it.isFocused
|
focused=it.isFocused
|
||||||
if(it.isFocused){vm.focusId=focusKey;onHovered(item)}
|
if(it.isFocused){vm.focusId=focusKey;onHovered(item)}
|
||||||
}.titleActions{vm.showActions(item,continuing)}.clickable{vm.open(item)}.clearAndSetSemantics{
|
}.clickable{vm.open(item)}.clearAndSetSemantics{
|
||||||
contentDescription=listOf(item.displayTitle,item.subtitle,item.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(". ")
|
contentDescription=listOf(item.displayTitle,item.subtitle,item.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(". ")
|
||||||
this.focused=focused;role=Role.Button
|
this.focused=focused;role=Role.Button
|
||||||
onClick{vm.open(item);true}
|
onClick{vm.open(item);true}
|
||||||
}) {
|
}) {
|
||||||
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) {
|
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&&!poster)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))
|
||||||
}
|
}
|
||||||
WatchBadge(item,vm.watchedPercent)
|
WatchBadge(item,vm.watchedPercent)
|
||||||
}else Box(Modifier.fillMaxSize().background(Panel))
|
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Color.White,RoundedCornerShape(4.dp)))
|
||||||
// A white ring with a dark inner edge stays visible on white and black artwork alike.
|
|
||||||
if(focused)Box(Modifier.fillMaxSize().border(3.dp,Color.White,RoundedCornerShape(4.dp)).padding(3.dp).border(1.dp,Color.Black.copy(alpha=.6f),RoundedCornerShape(2.dp)))
|
|
||||||
}
|
}
|
||||||
// Placeholder height matches the titles' fixed heights, so card bounds never change.
|
Text(item.displayTitle,color=if(focused)Accent else Cinema.secondary,fontSize=10.5.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=5.dp).height(16.dp))
|
||||||
if(!filled)Spacer(Modifier.height(if(poster)21.dp else 35.dp))
|
if(!poster)Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else if(item.offset>0)"${((item.duration-item.offset)/60000).coerceAtLeast(0)} min left"else item.year,color=Muted,fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.height(14.dp))
|
||||||
else {
|
|
||||||
// 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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The last card of a row with more titles: opens the hub's full list. */
|
|
||||||
@Composable private fun ViewAllCard(vm:KaleidoViewModel,hub:Hub,focusKey:String,poster:Boolean,wideEpisode:Boolean,requester:FocusRequester,modifier:Modifier) {
|
|
||||||
var focused by remember{mutableStateOf(false)}
|
|
||||||
val lift by animateFloatAsState(if(focused)1.05f else 1f,tween(150),label="viewAllFocus")
|
|
||||||
if(remember{Snapshot.withoutReadObservation{vm.focusId==focusKey}})LaunchedEffect(Unit){withFrameNanos{};runCatching{requester.requestFocus()}}
|
|
||||||
Column(modifier.width(if(poster)120.dp else if(wideEpisode)264.dp else 214.dp).graphicsLayer{scaleX=lift;scaleY=lift}.focusRequester(requester).navigationSound().onFocusChanged{
|
|
||||||
focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey
|
|
||||||
}.clickable{vm.openHub(hub)}.clearAndSetSemantics{
|
|
||||||
contentDescription="View all ${hub.title}";this.focused=focused;role=Role.Button;onClick{vm.openHub(hub);true}
|
|
||||||
}) {
|
|
||||||
Box(Modifier.fillMaxWidth().aspectRatio(if(poster)2f/3f else 16f/9f).clip(RoundedCornerShape(4.dp)).background(if(focused)Accent else Color.White.copy(alpha=.08f)),contentAlignment=Alignment.Center) {
|
|
||||||
Column(horizontalAlignment=Alignment.CenterHorizontally,verticalArrangement=Arrangement.spacedBy(6.dp)) {
|
|
||||||
Icon(Icons.Outlined.GridView,null,tint=if(focused)Ink else Accent,modifier=Modifier.size(22.dp))
|
|
||||||
Text("View all",color=if(focused)Ink else Accent,fontSize=11.sp,fontWeight=FontWeight.SemiBold)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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()}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
@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())
|
|
||||||
|
|
@ -1,18 +1,18 @@
|
||||||
package tv.kaleido.app
|
package tv.kaleido.app
|
||||||
|
|
||||||
data class HomeFeature(val item:Title)
|
data class HomeFeature(val item:Title,val reason:String)
|
||||||
|
|
||||||
/** 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>):List<HomeFeature> {
|
||||||
val excluded=continuing.flatMap{listOf(it.id,it.grandparentId,it.parentId)}.filter{it.isNotBlank()}.toSet()
|
val excluded=continuing.flatMap{listOf(it.id,it.grandparentId,it.parentId)}.filter{it.isNotBlank()}.toSet()
|
||||||
fun eligible(item:Title)=item.type in listOf("movie","show")&&item.art.isNotBlank()&&
|
fun eligible(item:Title)=item.type in listOf("movie","show")&&item.art.isNotBlank()&&
|
||||||
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)},
|
recent.filter{eligible(it)&&it.releaseDate.isNotBlank()}.sortedByDescending{it.releaseDate}.take(18).shuffled().map{HomeFeature(it,"Recently released")},
|
||||||
rated.filter{eligible(it)&&it.viewedLeafCount==0}.shuffled(random).map{HomeFeature(it)},
|
rated.filter{eligible(it)&&it.viewedLeafCount==0}.shuffled().map{HomeFeature(it,"Highly rated · Unwatched")},
|
||||||
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)}
|
.flatMap{it.items}.filter(::eligible).distinctBy{it.id}.shuffled().map{HomeFeature(it,"Suggested for you")}
|
||||||
)
|
)
|
||||||
val seen=mutableSetOf<String>()
|
val seen=mutableSetOf<String>()
|
||||||
return buildList {
|
return buildList {
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,5 @@ class KaleidoApplication: Application(), ImageLoaderFactory {
|
||||||
val scope = CoroutineScope(SupervisorJob()+Dispatchers.IO)
|
val scope = CoroutineScope(SupervisorJob()+Dispatchers.IO)
|
||||||
val secure by lazy { SecureSession(this) }
|
val secure by lazy { SecureSession(this) }
|
||||||
val api by lazy { PlexApi(secure.clientId).apply { session=secure.load() } }
|
val api by lazy { PlexApi(secure.clientId).apply { session=secure.load() } }
|
||||||
override fun newImageLoader() = ImageLoader.Builder(this).okHttpClient(api.http).memoryCache { MemoryCache.Builder(this).maxSizePercent(.12).build() }.diskCache { DiskCache.Builder().directory(cacheDir.resolve("artwork")).maxSizeBytes(250L*1024*1024).build() }.crossfade(250)
|
override fun newImageLoader() = ImageLoader.Builder(this).okHttpClient(api.http).memoryCache { MemoryCache.Builder(this).maxSizePercent(.12).build() }.diskCache { DiskCache.Builder().directory(cacheDir.resolve("artwork")).maxSizeBytes(250L*1024*1024).build() }.crossfade(250).build()
|
||||||
// Coil defaults to four concurrent decodes, which starves the UI and render threads
|
|
||||||
// on four-core TV hardware while a newly shown section loads its rows.
|
|
||||||
.bitmapFactoryMaxParallelism(2).build()
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,6 @@ import androidx.lifecycle.viewModelScope
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.mutableFloatStateOf
|
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.async
|
import kotlinx.coroutines.async
|
||||||
|
|
@ -21,25 +19,9 @@ import coil.imageLoader
|
||||||
import coil.request.Disposable
|
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.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="")
|
||||||
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 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
|
||||||
|
|
@ -53,120 +35,46 @@ 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
|
||||||
private var discoverHubsState by mutableStateOf(emptyList<Hub>())
|
var discoverHubs by mutableStateOf(emptyList<Hub>()); private set
|
||||||
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()&§ionId!=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 searchResults by mutableStateOf(emptyList<Title>()); private set
|
||||||
var actorTitles by mutableStateOf(emptyList<Title>()); private set
|
|
||||||
var markingId by mutableStateOf<String?>(null); private set
|
|
||||||
var searchResults by mutableStateOf(SearchResults()); private set
|
|
||||||
/** 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 contextFromContinue by mutableStateOf(false); private set
|
|
||||||
var hubTitles by mutableStateOf(emptyList<Title>()); private set
|
|
||||||
/** Bumped when playback closes, so the screen below can restore its focus. */
|
|
||||||
var playbackReturn by mutableIntStateOf(0); private set
|
|
||||||
private var retryAction:(()->Unit)?=null
|
|
||||||
private var previousTab="home"
|
|
||||||
/** 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. */
|
|
||||||
val episodeSelections=androidx.compose.runtime.mutableStateMapOf<String,String>()
|
|
||||||
var query by mutableStateOf(""); private set
|
var query by mutableStateOf(""); private set
|
||||||
var pin by mutableStateOf<Pin?>(null); private set
|
var pin by mutableStateOf<Pin?>(null); private set
|
||||||
var servers by mutableStateOf(emptyList<Server>()); private set
|
var servers by mutableStateOf(emptyList<Server>()); private set
|
||||||
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
|
||||||
var updateStatus by mutableStateOf(""); private set
|
var updateStatus by mutableStateOf(""); private set
|
||||||
var downloadedApk by mutableStateOf<File?>(null); private set
|
var downloadedApk by mutableStateOf<File?>(null); private set
|
||||||
var downloading by mutableStateOf(false); private set
|
var downloading by mutableStateOf(false); private set
|
||||||
var downloadProgress by mutableFloatStateOf(0f); private set
|
var playbackMode by mutableStateOf(preferences.getInt("playbackModeV2",1)); private set
|
||||||
/** A verified APK for [update], kept so a cancelled installer can be reopened without downloading again. */
|
|
||||||
var readyApk by mutableStateOf<File?>(null); private set
|
|
||||||
var streamQuality by mutableStateOf(savedStreamQuality()); 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. */
|
|
||||||
var autoplaySeconds by mutableIntStateOf(preferences.getInt("autoplaySeconds",5)); private set
|
|
||||||
/** Seconds the Skip intro/credits button counts down before skipping by itself; 0 only shows the button. */
|
|
||||||
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 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. */
|
|
||||||
var debugMode by mutableStateOf<Int?>(null); private set
|
|
||||||
var debugValidation=false; 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
|
||||||
|
var quality by mutableStateOf(preferences.getInt("quality",20000)); private set
|
||||||
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
|
|
||||||
/** 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 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 val featureSeed=kotlin.random.Random.nextInt()
|
|
||||||
private val previews=PreviewMetadata(viewModelScope){api.details(it.id)}
|
private val previews=PreviewMetadata(viewModelScope){api.details(it.id)}
|
||||||
private var predictedArtwork:Disposable?=null
|
private var predictedArtwork:Disposable?=null
|
||||||
private var predictedArtworkKey=""
|
private var predictedArtworkKey=""
|
||||||
|
|
@ -174,8 +82,6 @@ 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")
|
||||||
|
|
@ -187,26 +93,21 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
|
||||||
if(session!=null) initialize() else linkAccount()
|
if(session!=null) initialize() else linkAccount()
|
||||||
checkUpdate(false)
|
checkUpdate(false)
|
||||||
}
|
}
|
||||||
/** [retry] repeats this action from the error dialog; without it, Try again reloads the page. */
|
private fun launchLoad(block: suspend () -> Unit) {
|
||||||
private fun launchLoad(retry:(()->Unit)?=null,block: suspend () -> Unit) {
|
|
||||||
val generation=++loadGeneration
|
val generation=++loadGeneration
|
||||||
loadJob?.cancel()
|
loadJob?.cancel()
|
||||||
loadJob=viewModelScope.launch {
|
loadJob=viewModelScope.launch {
|
||||||
busy=true;error=null
|
busy=true;error=null
|
||||||
try { block() } catch(e: CancellationException){throw e} catch(e: Exception){retryAction=retry;error=e.message ?: "Something went wrong. Please try again."} finally {if(generation==loadGeneration)busy=false}
|
try { block() } catch(e: CancellationException){throw e} catch(e: Exception){error=e.message ?: "Something went wrong. Please try again."} finally {if(generation==loadGeneration)busy=false}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private fun fail(message:String,retry:(()->Unit)?){retryAction=retry;error=message}
|
fun dismissError(){error=null}
|
||||||
fun dismissError(){error=null;retryAction=null}
|
|
||||||
/** The connection in use is on this network; remote connections use [remoteQuality]. */
|
|
||||||
val localConnection get()=session?.server?.let(::isLocalAddress) ?: true
|
|
||||||
val activeQuality get()=if(localConnection)streamQuality else remoteQuality
|
|
||||||
fun initialize() {
|
fun initialize() {
|
||||||
if(initializeJob?.isActive==true)return
|
if(initializeJob?.isActive==true)return
|
||||||
initializeJob=viewModelScope.launch {
|
initializeJob=viewModelScope.launch {
|
||||||
busy=true;error=null
|
busy=true;error=null
|
||||||
try {
|
try {
|
||||||
val validated=reconnect(session ?: return@launch)
|
val validated=api.validate(session ?: return@launch)
|
||||||
api.session=validated;session=validated;application.secure.save(validated)
|
api.session=validated;session=validated;application.secure.save(validated)
|
||||||
sections=api.sections();homeHubs=loadHome()
|
sections=api.sections();homeHubs=loadHome()
|
||||||
if(page.kind in listOf("movies","tv"))loadPage(true)
|
if(page.kind in listOf("movies","tv"))loadPage(true)
|
||||||
|
|
@ -214,113 +115,28 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
|
||||||
finally{if(loadJob?.isActive!=true)busy=false}
|
finally{if(loadJob?.isActive!=true)busy=false}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
private suspend fun loadHome(): List<Hub> = coroutineScope {
|
||||||
* Validate the saved address. If it no longer answers (a changed LAN address, a rotated
|
|
||||||
* plex.direct name, or leaving the network), ask plex.tv for this server's current connections.
|
|
||||||
*/
|
|
||||||
private suspend fun reconnect(saved:Session):Session = try{api.validate(saved)}catch(e:CancellationException){throw e}catch(e:Exception){
|
|
||||||
if(saved.accountToken.isBlank()||e is PlexException&&e.status in listOf(401,403))throw e
|
|
||||||
val server=runCatching{api.servers(saved.accountToken)}.getOrNull()?.let{list->
|
|
||||||
list.firstOrNull{it.id==saved.machineId&&saved.machineId.isNotBlank()} ?: list.firstOrNull{it.name==saved.serverName}
|
|
||||||
} ?: throw e
|
|
||||||
api.connect(server,saved.accountToken)
|
|
||||||
}
|
|
||||||
private suspend fun loadHome():List<Hub> {
|
|
||||||
val fresh=fetchHome(sections);homeFeatures=fresh.features;return fresh.hubs
|
|
||||||
}
|
|
||||||
private suspend fun fetchHome(sources:List<Section>): HomeContent = coroutineScope {
|
|
||||||
val hubs=async { api.hubs() }; val deck=async { runCatching { api.onDeck() }.getOrDefault(emptyList()) }
|
val hubs=async { api.hubs() }; val deck=async { runCatching { api.onDeck() }.getOrDefault(emptyList()) }
|
||||||
val recommendations=async {sources.map{s->async{runCatching{api.hubs(s.id)}.getOrDefault(emptyList())}}.awaitAll().flatten()}
|
val recommendations=async {sections.map{s->async{runCatching{api.hubs(s.id)}.getOrDefault(emptyList())}}.awaitAll().flatten()}
|
||||||
val recent=async {sources.map{s->async{runCatching{api.library(s.id,sort="originallyAvailableAt:desc",size=18).items}.getOrDefault(emptyList())}}.awaitAll().flatten()}
|
val recent=async {sections.map{s->async{runCatching{api.library(s.id,sort="originallyAvailableAt:desc").items.take(18)}.getOrDefault(emptyList())}}.awaitAll().flatten()}
|
||||||
val rated=async {sources.map{s->async{runCatching{api.library(s.id,sort="audienceRating:desc",unwatched=true,size=24).items}.getOrDefault(emptyList())}}.awaitAll().flatten()}
|
val rated=async {sections.map{s->async{runCatching{api.library(s.id,sort="audienceRating:desc",unwatched=true).items.take(24)}.getOrDefault(emptyList())}}.awaitAll().flatten()}
|
||||||
val h=hubs.await();val d=deck.await()
|
val h=hubs.await();val d=deck.await()
|
||||||
HomeContent(if(d.isEmpty()) h else listOf(Hub("continue","Continue Watching",d))+h.filterNot { it.title.equals("Continue Watching",true) },
|
homeFeatures=homeFeatures(recent.await(),rated.await(),recommendations.await(),d)
|
||||||
homeFeatures(recent.await(),rated.await(),recommendations.await(),d,kotlin.random.Random(featureSeed)))
|
if(d.isEmpty()) h else listOf(Hub("continue","Continue Watching",d))+h.filterNot { it.title.equals("Continue Watching",true) }
|
||||||
}
|
|
||||||
/** Lifecycle-owned, silent sync; never competes with playback or a user-requested load. */
|
|
||||||
fun setForeground(value:Boolean) {
|
|
||||||
foreground=value
|
|
||||||
librarySyncJob?.cancel();librarySyncJob=null
|
|
||||||
if(!value)return
|
|
||||||
librarySyncJob=viewModelScope.launch {
|
|
||||||
// Kept across background spells: returning compares against what was last applied,
|
|
||||||
// so Continue Watching changes made on another device show up within a second.
|
|
||||||
var interval=ResumeSyncDelayMillis
|
|
||||||
var backoff=LibrarySync.POLL_MS
|
|
||||||
while(isActive) {
|
|
||||||
delay(interval);interval=backoff
|
|
||||||
val sync=librarySync?.takeIf{librarySyncSession==session} ?: newLibrarySync().also{librarySync=it;librarySyncSession=session}
|
|
||||||
if(session==null||playing!=null||busy||markingId!=null||initializeJob?.isActive==true)continue
|
|
||||||
try{sync.check();backoff=LibrarySync.POLL_MS}
|
|
||||||
catch(e:CancellationException){throw e}
|
|
||||||
catch(_:Exception){backoff=(backoff*2).coerceAtMost(LibrarySync.FALLBACK_MS)}
|
|
||||||
interval=backoff
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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 {
|
|
||||||
val expectedSession=session ?: return false
|
|
||||||
val expectedPage=page;val generation=loadGeneration
|
|
||||||
val expectedSection=section;val expectedSort=sort;val expectedGenre=genre;val expectedUnwatched=unwatched;val expectedCategories=categories;val expectedAllTitles=allTitles
|
|
||||||
val freshSections=api.sections()
|
|
||||||
val freshHome=fetchHome(freshSections)
|
|
||||||
val sectionPage=expectedPage.kind in listOf("movies","tv")
|
|
||||||
// Keep the underlying filtered section fresh while its details/actor page is open,
|
|
||||||
// so Back can restore the same grid and card instead of resetting to Discover.
|
|
||||||
val sectionKind=pages.first().kind
|
|
||||||
val active=if(sectionKind in listOf("movies","tv"))freshSections.firstOrNull{it.id==expectedSection?.id}
|
|
||||||
?: freshSections.firstOrNull{it.type==if(sectionKind=="movies")"movie"else "show"}else null
|
|
||||||
// Preserve the loaded range and selected filters, instead of resetting the A-Z grid.
|
|
||||||
val freshSection=active?.let{s->
|
|
||||||
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),type=plexLibraryType(s.type))
|
|
||||||
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)+
|
|
||||||
if(seasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",seasons))else emptyList()
|
|
||||||
SectionContent(rows,newGenres,p)
|
|
||||||
}
|
|
||||||
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)}
|
|
||||||
// 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.
|
|
||||||
if(!foreground||session!=expectedSession||page!=expectedPage||generation!=loadGeneration||
|
|
||||||
section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched||categories!=expectedCategories||allTitles!=expectedAllTitles||
|
|
||||||
playing!=null||busy||markingId!=null)return false
|
|
||||||
sections=freshSections;homeHubs=freshHome.hubs;homeFeatures=freshHome.features
|
|
||||||
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
|
|
||||||
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}
|
|
||||||
if(freshChildren!=null&&detail?.id==detailSnapshot?.id)children=freshChildren
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
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,path:String=item.art.ifBlank{item.thumb},header:Boolean=false) {
|
fun anticipate(item:Title,cinematic:Boolean=false,backdrop:Boolean=true) {
|
||||||
previews.anticipate(item)
|
previews.anticipate(item)
|
||||||
val wash=header&&colourWash
|
val path=item.art.ifBlank{item.thumb}
|
||||||
val key=if(backdrop)"$cinematic:$header:$wash:$path"else ""
|
val key=if(backdrop)"$cinematic:$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,header,wash)?.let{predictedArtwork=application.imageLoader.enqueue(it.newBuilder().dispatcher(artworkPrefetchDispatcher).build())}
|
if(backdrop)browseBackdropRequest(application,api,path,cinematic)?.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
|
||||||
|
|
@ -338,346 +154,84 @@ 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();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery();clearServerState()
|
sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
|
||||||
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();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery();clearServerState()
|
sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
|
||||||
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();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()}
|
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()}
|
||||||
/** 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;cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv"))allTitles=false;pages=listOf(Page(kind));loadPage(true)}
|
||||||
if(pages.size==1&&page.kind==kind)return
|
fun open(item: Title){detailsCache[item.id]=item;pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()}
|
||||||
// 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!="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()}
|
|
||||||
/** Opens an episode's show, or a season's show. */
|
|
||||||
fun openShow(item:Title){val id=if(item.type=="episode")item.grandparentId else item.parentId;if(id.isBlank())return;pages=pages+Page("details",id,if(item.type=="episode")item.grandparentTitle else item.parentTitle,focusId);loadPage()}
|
|
||||||
fun openSeason(item:Title){if(item.parentId.isBlank())return;episodeSelections.remove(item.parentId);pages=pages+Page("group",item.parentId,item.parentTitle,focusId);loadPage()}
|
|
||||||
/** "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 openSearch(text:String=""){if(page.kind!="search")tab("search");if(text.isNotBlank())search(text)}
|
|
||||||
fun showActions(item:Title,fromContinue:Boolean=false){contextItem=item;contextFromContinue=fromContinue}
|
|
||||||
fun dismissActions(){contextItem=null;contextFromContinue=false}
|
|
||||||
fun removeFromContinueWatching(item:Title){
|
|
||||||
viewModelScope.launch {
|
|
||||||
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)}}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** 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 chooseMedia(item:Title,index:Int){mediaChoices[item.id]=index}
|
|
||||||
fun openActor(actor:CastMember){
|
|
||||||
if(actor.id.isBlank())return
|
|
||||||
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);if(pages.last().kind in listOf("movies","tv")&&focusId.startsWith("library:"))libraryFocusRequest++;loadPage();return true}
|
if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);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!="home"){tab("home");return true}
|
if(page.kind!="home"){tab("home");return true}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
fun retry(){val action=retryAction;retryAction=null;error=null;if(action!=null)action() else if(session==null)linkAccount() else if(sections.isEmpty())initialize() else loadPage()}
|
fun retry(){if(session==null)linkAccount() else if(sections.isEmpty())initialize() else loadPage()}
|
||||||
private fun loadPage(resetLibrary: Boolean=false) {
|
private fun loadPage(resetLibrary: Boolean=false) {
|
||||||
when(page.kind){
|
when(page.kind){
|
||||||
"home" -> if(homeHubs.isEmpty())launchLoad { homeHubs=loadHome() }
|
"home" -> if(homeHubs.isEmpty())launchLoad { homeHubs=loadHome() }
|
||||||
"movies","tv" -> {
|
"movies","tv" -> {
|
||||||
if(sections.isEmpty()){initialize();return}
|
if(sections.isEmpty()){initialize();return}
|
||||||
val type=if(page.kind=="movies")"movie"else "show"
|
val type=if(page.kind=="movies")"movie"else "show"
|
||||||
if(!resetLibrary&&!sectionStale&§ion?.type==type&&library.isNotEmpty()&&discoverHubs.isNotEmpty())return
|
if(!resetLibrary&§ion?.type==type&&library.isNotEmpty()&&discoverHubs.isNotEmpty())return
|
||||||
sectionStale=false
|
loadJob?.cancel();section=sections.firstOrNull{it.type==type};sort="titleSort:asc";genre="";unwatched=false;allTitles=false
|
||||||
// Each destination remembers the library chosen for it, e.g. "4K Movies".
|
val s=section ?: return
|
||||||
val preferred=preferences.getString("section.$type",null)
|
val cached=sectionCache[s.id]
|
||||||
loadSection(sections.firstOrNull{it.type==type&&it.id==preferred} ?: sections.firstOrNull{it.type==type})
|
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
|
||||||
"hub" -> {
|
launchLoad {coroutineScope {
|
||||||
hubTitles=emptyList()
|
val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id)}
|
||||||
val key=page.id
|
val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(type=="show")async{runCatching{api.recentSeasons(s.id)}.getOrDefault(emptyList())}else null
|
||||||
launchLoad({loadPage()}) {hubTitles=api.hubItems(key)}
|
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()
|
||||||
"details","group" -> {
|
sectionCache[s.id]=SectionContent(rows,genreList,p)
|
||||||
detail=detailsCache[page.id];children=emptyList();detailRelated=emptyList()
|
discoverHubs=rows;genres=genreList;library=p.items;total=p.total
|
||||||
launchLoad {
|
}}
|
||||||
val id=page.id;val d=detailsCache[id]?.let{previews.details(it)} ?: api.details(id)
|
|
||||||
detail=d;detailsCache[id]=d;previews.remember(d)
|
|
||||||
coroutineScope {
|
|
||||||
// An episode lists its season's episodes, so neighbours are one move away.
|
|
||||||
val groups=async{if(d.type in listOf("show","season","collection"))api.children(id)
|
|
||||||
else if(d.type=="episode"&&d.parentId.isNotBlank())runCatching{api.children(d.parentId)}.getOrDefault(emptyList())else emptyList()}
|
|
||||||
val related=async{try{when(d.type){"show"->api.relatedShows(id).filter{it.id!=id};"movie"->api.relatedMovies(id);else->emptyList()}}catch(e:CancellationException){throw e}catch(_:Exception){emptyList()}}
|
|
||||||
children=groups.await();detailRelated=related.await()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"actor" -> {
|
|
||||||
val actor=page.actor ?: return
|
|
||||||
actorTitles=emptyList()
|
|
||||||
launchLoad {actorTitles=api.actorTitles(actor,sections)}
|
|
||||||
}
|
}
|
||||||
|
"details","group" -> { detail=detailsCache[page.id];children=emptyList();launchLoad { val id=page.id;val d=detailsCache[id]?.let{previews.details(it)} ?: api.details(id);detail=d;detailsCache[id]=d;previews.remember(d);if(d.type in listOf("show","season","collection"))children=api.children(id) } }
|
||||||
"search" -> {busy=false;error=null}
|
"search" -> {busy=false;error=null}
|
||||||
"settings" -> {busy=false;error=null}
|
"settings" -> {busy=false;error=null}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** Shows [s] in its destination, from cache when possible, with default filters. */
|
fun chooseSection(s: Section){section=s;genre="";sort="titleSort:asc";launchLoad {genres=api.genres(s.id);discoverHubs=api.hubs(s.id);val p=api.library(s.id);library=p.items;total=p.total}}
|
||||||
private fun loadSection(s:Section?) {
|
fun setAll(value: Boolean){focusId=if(value)"library-entry"else "discovery-entry";allTitles=value}
|
||||||
loadJob?.cancel();resetCategoryArtwork(s?.id);section=s;sort="titleSort:asc";genre="";unwatched=false
|
fun filter(sortValue: String=sort,genreValue: String=genre,unwatchedValue: Boolean=unwatched){sort=sortValue;genre=genreValue;unwatched=unwatchedValue;refreshLibrary()}
|
||||||
categories=false;libraryJumpIndex=-1;libraryJumpLetter=null
|
private fun refreshLibrary()=launchLoad { val p=api.library(section?.id ?: return@launchLoad,0,sort,genre,unwatched);library=p.items;total=p.total }
|
||||||
if(s==null){discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList();return}
|
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}}
|
||||||
val cached=sectionCache[s.id]
|
fun search(text: String){query=text;searchJob?.cancel();searchJob=viewModelScope.launch {delay(350);if(text.isBlank()){searchResults=emptyList();return@launch};busy=true;error=null;try{searchResults=api.search(text)}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message}finally{busy=false}}}
|
||||||
if(cached!=null){discoverHubs=cached.hubs;genres=cached.genres;library=cached.library.items;total=cached.library.total;busy=false;return}
|
fun mark(item: Title)=launchLoad {
|
||||||
discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList()
|
|
||||||
launchLoad({loadSection(s)}) {
|
|
||||||
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 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()
|
|
||||||
SectionContent(rows,genreList,p)
|
|
||||||
}
|
|
||||||
fun chooseSection(s: Section){
|
|
||||||
if(s.id==section?.id)return
|
|
||||||
val keepCategories=categories
|
|
||||||
preferences.edit().putString("section.${s.type}",s.id).apply()
|
|
||||||
cancelAnticipation();focusId=if(allTitles)"library-entry"else "discovery-entry";loadSection(s)
|
|
||||||
if(keepCategories){allTitles=true;categories=true;focusId="categories-entry"}
|
|
||||||
}
|
|
||||||
fun setAll(value: Boolean){
|
|
||||||
// Genre filtering belongs to Categories; the Library grid always lists the whole section.
|
|
||||||
val hadGenre=genre.isNotBlank();focusId=if(value)"library-entry"else "discovery-entry";allTitles=value;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null
|
|
||||||
if(hadGenre)refreshLibrary()
|
|
||||||
}
|
|
||||||
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&§ion?.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) {
|
|
||||||
if(markingId!=null)return
|
|
||||||
markingId=item.id
|
|
||||||
// A navigation request must not cancel an already submitted Plex watched write.
|
|
||||||
viewModelScope.launch {
|
|
||||||
try {
|
|
||||||
api.watched(item,!item.isWatched(watchedPercent));refreshWatchedItems(item)
|
api.watched(item,!item.isWatched(watchedPercent));refreshWatchedItems(item)
|
||||||
homeHubs=loadHome()
|
|
||||||
}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)
|
||||||
if(d.type in listOf("show","season")) {
|
|
||||||
api.children(d.id).forEach{updated[it.id]=it}
|
|
||||||
api.allEpisodes(d.id).forEach{updated[it.id]=it}
|
|
||||||
}
|
|
||||||
if(d.type=="episode")for(id in listOf(d.parentId,d.grandparentId).filter{it.isNotBlank()}) {
|
if(d.type=="episode")for(id in listOf(d.parentId,d.grandparentId).filter{it.isNotBlank()}) {
|
||||||
try{updated[id]=api.details(id)}catch(e:CancellationException){throw e}catch(_:Exception){detailsCache.remove(id)}
|
try{updated[id]=api.details(id)}catch(e:CancellationException){throw e}catch(_:Exception){detailsCache.remove(id)}
|
||||||
}
|
}
|
||||||
// Only /metadata details are complete; children/allLeaves are summary records.
|
previews.clear();updated.values.forEach{previews.remember(it)};detailsCache.putAll(updated);detail=detail?.let{updated[it.id] ?: it}
|
||||||
// Merge their watched fields without poisoning full metadata/cast caches.
|
fun refreshed(hubs:List<Hub>)=hubs.map{h->h.copy(items=h.items.map{updated[it.id] ?: it})}
|
||||||
val fullIds=if(d.type=="episode")setOf(d.id,d.parentId,d.grandparentId)else setOf(d.id)
|
|
||||||
fun refreshedTitle(existing:Title):Title {
|
|
||||||
val fresh=updated[existing.id] ?: return existing
|
|
||||||
return if(existing.id in fullIds)fresh else existing.copy(watched=fresh.watched,offset=fresh.offset,leafCount=fresh.leafCount,viewedLeafCount=fresh.viewedLeafCount)
|
|
||||||
}
|
|
||||||
previews.clear();updated.keys.forEach{detailsCache.remove(it)}
|
|
||||||
updated.filterKeys{it in fullIds}.values.forEach{previews.remember(it);detailsCache[it.id]=it}
|
|
||||||
detail=detail?.let(::refreshedTitle)
|
|
||||||
fun refreshed(hubs:List<Hub>)=hubs.map{h->h.copy(items=h.items.map(::refreshedTitle))}
|
|
||||||
homeHubs=refreshed(homeHubs);discoverHubs=refreshed(discoverHubs)
|
homeHubs=refreshed(homeHubs);discoverHubs=refreshed(discoverHubs)
|
||||||
library=library.map(::refreshedTitle);children=children.map(::refreshedTitle)
|
library=library.map{updated[it.id] ?: it};children=children.map{updated[it.id] ?: it}
|
||||||
searchResults=searchResults.copy(titles=searchResults.titles.map(::refreshedTitle))
|
searchResults=searchResults.map{updated[it.id] ?: it}
|
||||||
hubTitles=hubTitles.map(::refreshedTitle)
|
homeFeatures=homeFeatures.map{it.copy(item=updated[it.item.id] ?: it.item)}.filterNot{it.item.fullyWatched}
|
||||||
actorTitles=actorTitles.map(::refreshedTitle);detailRelated=detailRelated.map(::refreshedTitle)
|
sectionCache.clear()
|
||||||
homeFeatures=homeFeatures.map{it.copy(item=refreshedTitle(it.item))}.filterNot{it.item.fullyWatched}
|
|
||||||
sectionCache.clear();characterOffsetCache.clear()
|
|
||||||
}
|
}
|
||||||
fun play(item: Title,fromStart: Boolean=false):Unit=launchLoad({play(item,fromStart)}) {
|
fun play(item: Title,fromStart: Boolean=false)=launchLoad {
|
||||||
shuffleEpisodes=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
|
||||||
|
|
@ -691,129 +245,30 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** The episode before [item]: the previous one in the show, or the previous shuffle pick. */
|
fun followingEpisode(item:Title):Title? {val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>=0)episodeQueue.getOrNull(i+1)else null}
|
||||||
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};if(i>=0)episodes.getOrNull(i+1)else null
|
val i=episodes.indexOfFirst{it.id==item.id};val next=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){error=e.message ?: "The next episode could not be loaded."}finally{transitioningEpisode=false}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** The server ended this session: leave the player and explain, offering to resume from the saved position. */
|
fun stopPlayback(){playing=null;sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();launchLoad {homeHubs=loadHome();detail?.let {if(it.type in listOf("movie","episode"))detail=api.details(it.id)}}}
|
||||||
fun playbackStoppedByServer(item:Title,message:String){
|
fun choosePlaybackMode(value: Int){playbackMode=value;preferences.edit().putInt("playbackModeV2",value).apply()}
|
||||||
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(){
|
|
||||||
val finished=playing
|
|
||||||
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.
|
|
||||||
detail?.let{if(finished?.type=="episode"&&it.type in listOf("season","episode"))episodeSelections[it.id]=finished.id}
|
|
||||||
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()
|
|
||||||
detail?.let {
|
|
||||||
if(it.type in listOf("movie","episode"))detail=api.details(it.id)
|
|
||||||
val season=when(it.type){"season"->it.id;"episode"->it.parentId;else->""}
|
|
||||||
if(season.isNotBlank())try{val fresh=api.children(season);if(detail?.id==it.id)children=fresh}catch(e:CancellationException){throw e}catch(_:Exception){}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 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.
|
|
||||||
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
|
|
||||||
fun chooseStreamQuality(value: StreamQuality){streamQuality=value;preferences.edit().putString("streamQuality",value.name).apply()}
|
|
||||||
fun chooseRemoteQuality(value: StreamQuality){remoteQuality=value;preferences.edit().putString("remoteQuality",value.name).apply()}
|
|
||||||
/** 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 chooseAutoplaySeconds(value:Int){autoplaySeconds=value.coerceAtLeast(0);preferences.edit().putInt("autoplaySeconds",autoplaySeconds).apply()}
|
|
||||||
fun chooseAutoSkipIntro(seconds:Int){autoSkipIntroSeconds=seconds.coerceIn(0,60);preferences.edit().putInt("autoSkipIntroSeconds",autoSkipIntroSeconds).remove("autoSkipIntro").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 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 chooseQuality(value: Int){quality=value;preferences.edit().putInt("quality",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(!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch
|
||||||
updateStatus="Checking for updates…"
|
updateStatus="Checking for updates…"
|
||||||
try{val previous=update?.version;update=updater.latest();if(update?.version!=previous)readyApk=null;preferences.edit().putLong("lastUpdateCheck",System.currentTimeMillis()).apply();updateStatus=if(update==null)"Kaleido is up to date." else "Version ${update!!.version} is available."}catch(e:Exception){updateStatus="Update check failed. ${e.message}"}
|
try{update=updater.latest();preferences.edit().putLong("lastUpdateCheck",System.currentTimeMillis()).apply();updateStatus=if(update==null)"Kaleido is up to date." else "Version ${update!!.version} is available."}catch(e:Exception){updateStatus="Update check failed. ${e.message}"}
|
||||||
}}
|
}}
|
||||||
fun downloadUpdate() {
|
fun downloadUpdate(){val release=update ?: return; if(downloading)return;viewModelScope.launch {downloading=true;try {downloadedApk=updater.download(release){progress -> updateStatus="Downloading update · $progress%"};updateStatus="Update verified. Ready to install."}catch(e:Exception){updateStatus=e.message ?: "Download failed."}finally{downloading=false}}}
|
||||||
val release=update ?: return
|
|
||||||
if(downloading)return
|
|
||||||
readyApk?.takeIf{it.exists()}?.let{downloadedApk=it;updateStatus="Opening the installer…";return}
|
|
||||||
viewModelScope.launch {
|
|
||||||
downloading=true;downloadProgress=0f
|
|
||||||
try {
|
|
||||||
val apk=updater.download(release){progress->downloadProgress=progress/100f;updateStatus="Downloading update · $progress%"}
|
|
||||||
readyApk=apk;downloadedApk=apk;updateStatus="Update verified. Opening the installer…"
|
|
||||||
}catch(e:Exception){updateStatus=e.message ?: "Download failed."}finally{downloading=false}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fun clearDownload(){downloadedApk=null}
|
fun clearDownload(){downloadedApk=null}
|
||||||
/** Back from the system installer without updating: the verified APK can be installed again. */
|
fun debugPlay(id: String,offset: Long,mode: Int){if(!BuildConfig.DEBUG)return;launchLoad {playing=null;delay(150);playbackMode=mode;playing=api.details(id).copy(offset=offset);startFromZero=false}}
|
||||||
fun installerReturned(){if(readyApk!=null&&!downloading)updateStatus="Update downloaded. Select Install ${update?.version.orEmpty()} to finish."}
|
|
||||||
fun debugPlay(id: String,offset: Long,mode: Int,validation:Boolean=false){if(!BuildConfig.DEBUG)return;launchLoad {playing=null;delay(150);debugValidationFile=null;debugMode=mode.takeIf{it>=0};debugValidation=validation;playing=api.details(id).copy(offset=offset);startFromZero=false}}
|
|
||||||
/** Private, opt-in test media uses the same controller and SurfaceView as Plex playback. */
|
|
||||||
fun debugPlayFixture(name:String){
|
|
||||||
if(!BuildConfig.DEBUG||!name.matches(Regex("[a-z0-9-]+")))return
|
|
||||||
launchLoad {
|
|
||||||
val folder=File(application.filesDir,"validation").canonicalFile
|
|
||||||
val fixture=Title.parse(JSONObject(File(folder,"$name.json").readText()))
|
|
||||||
val file=File(folder,fixture.media.first().parts.first().key).canonicalFile
|
|
||||||
require(file.parentFile==folder&&file.isFile)
|
|
||||||
playing=null;delay(150);debugMode=0;debugValidation=true;debugValidationFile=file
|
|
||||||
playing=fixture;startFromZero=true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,134 +0,0 @@
|
||||||
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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
/** Check a cheap server revision first; periodically refresh even on older servers without revisions. */
|
|
||||||
internal class LibrarySync(
|
|
||||||
private val revision:suspend ()->String,
|
|
||||||
private val refresh:suspend ()->Boolean,
|
|
||||||
private val now:()->Long
|
|
||||||
) {
|
|
||||||
private var accepted:String?=null
|
|
||||||
private var refreshedAt:Long?=null
|
|
||||||
suspend fun check() {
|
|
||||||
val current=revision()
|
|
||||||
val last=refreshedAt
|
|
||||||
if(current!=accepted||last==null||now()-last>=FALLBACK_MS) {
|
|
||||||
// Navigation may supersede the snapshot while it loads. Retry instead of accepting it.
|
|
||||||
if(refresh()){accepted=current;refreshedAt=now()}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
companion object {
|
|
||||||
const val POLL_MS=15_000L
|
|
||||||
const val FALLBACK_MS=60_000L
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -21,50 +21,23 @@ class MainActivity: ComponentActivity() {
|
||||||
if(packageManager.canRequestPackageInstalls()) pendingApk?.let(::installApk)
|
if(packageManager.canRequestPackageInstalls()) pendingApk?.let(::installApk)
|
||||||
}
|
}
|
||||||
fun installApk(file: File) {
|
fun installApk(file: File) {
|
||||||
// Consume the request first: a denied permission or cancelled installer must not
|
pendingApk=file
|
||||||
// reopen on the next visit to Settings. Settings offers Install again instead.
|
|
||||||
model.clearDownload();pendingApk=file
|
|
||||||
if(!packageManager.canRequestPackageInstalls()) {
|
if(!packageManager.canRequestPackageInstalls()) {
|
||||||
unknownSources.launch(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,Uri.parse("package:$packageName")));return
|
unknownSources.launch(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,Uri.parse("package:$packageName")));return
|
||||||
}
|
}
|
||||||
val uri=FileProvider.getUriForFile(this,"$packageName.files",file)
|
val uri=FileProvider.getUriForFile(this,"$packageName.files",file)
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
startActivity(Intent(Intent.ACTION_INSTALL_PACKAGE).setDataAndType(uri,"application/vnd.android.package-archive").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
|
startActivity(Intent(Intent.ACTION_INSTALL_PACKAGE).setDataAndType(uri,"application/vnd.android.package-archive").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
|
||||||
pendingApk=null
|
pendingApk=null;model.clearDownload()
|
||||||
}
|
}
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
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.
|
|
||||||
window.setBackgroundDrawable(null)
|
|
||||||
debugPlayback(intent)
|
debugPlayback(intent)
|
||||||
searchIntent(intent)
|
|
||||||
}
|
}
|
||||||
override fun onNewIntent(intent: Intent) {super.onNewIntent(intent);setIntent(intent);debugPlayback(intent);searchIntent(intent)}
|
override fun onNewIntent(intent: Intent) {super.onNewIntent(intent);setIntent(intent);debugPlayback(intent)}
|
||||||
/** System and Assistant searches ("search for Silo in Kaleido") open Search with their query. */
|
private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG)intent.getStringExtra("testTitleId")?.let{model.debugPlay(it,intent.getLongExtra("testOffset",90000),intent.getIntExtra("testMode",0))}}
|
||||||
private fun searchIntent(intent: Intent) {
|
override fun onStart() { super.onStart(); model.checkUpdate(false) }
|
||||||
if(intent.action!=Intent.ACTION_SEARCH&&intent.action!="com.google.android.gms.actions.SEARCH_ACTION")return
|
|
||||||
val query=intent.getStringExtra(android.app.SearchManager.QUERY).orEmpty().trim()
|
|
||||||
if(model.session!=null)model.openSearch(query)
|
|
||||||
}
|
|
||||||
/** Open the native text field; voice input belongs to the Android TV keyboard. */
|
|
||||||
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.openSearch();return true}
|
|
||||||
return super.onKeyDown(keyCode,event)
|
|
||||||
}
|
|
||||||
override fun onSearchRequested(): Boolean {
|
|
||||||
if(model.session==null||model.playing!=null)return false
|
|
||||||
model.openSearch();return true
|
|
||||||
}
|
|
||||||
private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG){
|
|
||||||
intent.getStringExtra("testFixture")?.let{model.debugPlayFixture(it);return}
|
|
||||||
intent.getStringExtra("testTitleId")?.let{model.debugPlay(it,intent.getLongExtra("testOffset",90000),intent.getIntExtra("testMode",0),intent.getBooleanExtra("testValidation",false))}
|
|
||||||
}}
|
|
||||||
override fun onStart() { super.onStart(); model.checkUpdate(false);model.setForeground(true) }
|
|
||||||
override fun onStop() { model.setForeground(false);super.onStop() }
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,37 +1,16 @@
|
||||||
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)
|
||||||
@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 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 Part(val id: String, val key: String, val streams: List<Stream>,val indexes:String="",val duration:Long=0,val size:Long=0)
|
data class Part(val id: String, val key: String, val streams: List<Stream>,val indexes:String="")
|
||||||
@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>,
|
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) {
|
data class Marker(val type: String, val start: Long, val end: Long)
|
||||||
val resolutionLabel get()=when(resolution.lowercase()){"4k"->"4K";"sd"->"SD";""->"";else->if(resolution.all(Char::isDigit))"${resolution}p"else resolution.uppercase()}
|
data class Chapter(val index:Int,val title:String,val start:Long,val end:Long,val thumb:String)
|
||||||
val channelLabel get()=when(audioChannels){0->"";1->"Mono";2->"Stereo";6->"5.1";8->"7.1";else->"$audioChannels ch"}
|
data class Title(
|
||||||
val atmos get()=parts.firstOrNull()?.streams.orEmpty().any{it.type==2&&it.title.contains("Atmos",true)}
|
|
||||||
val size get()=parts.sumOf{it.size}
|
|
||||||
/** One line describing this version, e.g. "4K · Dolby Vision · HEVC · EAC3 7.1 Atmos · 17 Mbps". */
|
|
||||||
fun description(includeSize:Boolean=false):String = listOf(resolutionLabel,dynamicRange,videoCodec.uppercase(),
|
|
||||||
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 "")
|
|
||||||
.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"
|
|
||||||
@Immutable data class Marker(val type: String, val start: Long, val end: Long)
|
|
||||||
@Immutable data class Chapter(val index:Int,val title:String,val start:Long,val end:Long,val thumb:String)
|
|
||||||
@Immutable data class CastMember(val id:String,val name:String,val role:String,val thumb:String) {
|
|
||||||
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"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@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,
|
||||||
|
|
@ -39,9 +18,7 @@ internal fun fileSize(bytes:Long):String = if(bytes>=1_000_000_000L)String.forma
|
||||||
val index: Int, val parentIndex: Int, val leafCount: Int, val viewedLeafCount: Int,
|
val index: Int, val parentIndex: Int, val leafCount: Int, val viewedLeafCount: Int,
|
||||||
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 theme:String=""
|
|
||||||
) {
|
) {
|
||||||
val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0)
|
val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0)
|
||||||
val fullyWatched get() = isWatched()
|
val fullyWatched get() = isWatched()
|
||||||
|
|
@ -53,57 +30,28 @@ internal fun fileSize(bytes:Long):String = if(bytes>=1_000_000_000L)String.forma
|
||||||
type in listOf("show","season")&&leafCount>0 -> "$remainingEpisodes episodes remaining"
|
type in listOf("show","season")&&leafCount>0 -> "$remainingEpisodes episodes remaining"
|
||||||
else -> ""
|
else -> ""
|
||||||
}
|
}
|
||||||
/** Seasons and episodes are ambiguous without their show, except where the show is already shown. */
|
val displayTitle get() = if (type == "episode") grandparentTitle.ifBlank { title } else title
|
||||||
val displayTitle get() = when(type) {
|
val subtitle get() = when(type) { "episode" -> "S${parentIndex} · E${index} $title"; "season" -> "$leafCount episodes"; "show" -> "${year} · $leafCount episodes"; else -> listOf(year, if(duration>0) "${duration/60000} min" else "", genres.firstOrNull().orEmpty()).filter { it.isNotBlank() }.joinToString(" · ") }
|
||||||
"episode" -> grandparentTitle.ifBlank { title }
|
|
||||||
"season" -> if(parentTitle.isNotBlank()&&!title.startsWith(parentTitle))"$parentTitle · $title" else title
|
|
||||||
else -> title
|
|
||||||
}
|
|
||||||
val subtitle get() = when(type) { "episode" -> "S${parentIndex} · E${index} $title"; "season" -> "$leafCount episodes"; "show" -> "${year} · $leafCount episodes"; "clip" -> listOf(extraLabel,if(duration>0)clockTime(duration)else "").filter{it.isNotBlank()}.joinToString(" · "); else -> listOf(year, if(duration>0) "${duration/60000} min" else "", genres.firstOrNull().orEmpty()).filter { it.isNotBlank() }.joinToString(" · ") }
|
|
||||||
val progress get() = if(duration>0) (offset.toFloat()/duration).coerceIn(0f,1f) else 0f
|
val progress get() = if(duration>0) (offset.toFloat()/duration).coerceIn(0f,1f) else 0f
|
||||||
val extraLabel get() = when(subtype) {
|
|
||||||
"trailer"->"Trailer";"behindTheScenes"->"Behind the scenes";"deletedScene"->"Deleted scene";"featurette"->"Featurette"
|
|
||||||
"interview"->"Interview";"sceneOrSample"->"Scene";"short"->"Short";else->if(type=="clip")"Extra"else ""
|
|
||||||
}
|
|
||||||
/** Extras Kaleido can play: local or proxied clips with a media file. */
|
|
||||||
val playableExtras get() = extras.filter{it.media.firstOrNull()?.parts?.isNotEmpty()==true}
|
|
||||||
val trailer get() = playableExtras.firstOrNull{it.subtype=="trailer"}
|
|
||||||
companion object {
|
companion object {
|
||||||
fun parse(j: JSONObject): Title = Title(
|
fun parse(j: JSONObject): Title = Title(
|
||||||
j.optString("ratingKey",j.optString("key")), j.optString("key"), j.optString("type"), j.optString("title"), j.optString("summary"),
|
j.optString("ratingKey",j.optString("key")), j.optString("key"), j.optString("type"), j.optString("title"), j.optString("summary"),
|
||||||
j.optString("thumb",j.optString("parentThumb",j.optString("grandparentThumb"))), j.optString("art",j.optString("grandparentArt")), j.optString("year"),j.optLong("duration"),j.optLong("viewOffset"),
|
j.optString("thumb",j.optString("parentThumb",j.optString("grandparentThumb"))), j.optString("art",j.optString("grandparentArt")), j.optString("year"),j.optLong("duration"),j.optLong("viewOffset"),
|
||||||
j.optInt("viewCount")>0,AudienceScore.parseAll(j).joinToString(" · "){it.label},j.optString("contentRating"),j.optString("parentTitle"),j.optString("grandparentTitle"),j.optString("parentRatingKey"),j.optString("grandparentRatingKey"),
|
j.optInt("viewCount")>0,AudienceScore.parseAll(j).joinToString(" · "){it.label},j.optString("contentRating"),j.optString("parentTitle"),j.optString("grandparentTitle"),j.optString("parentRatingKey"),j.optString("grandparentRatingKey"),
|
||||||
j.optInt("index"),j.optInt("parentIndex"),j.optInt("leafCount"),j.optInt("viewedLeafCount"),j.optJSONArray("Genre").objects().map { it.optString("tag") },j.optJSONArray("Role").objects().take(10).map { it.optString("tag") },
|
j.optInt("index"),j.optInt("parentIndex"),j.optInt("leafCount"),j.optInt("viewedLeafCount"),j.optJSONArray("Genre").objects().map { it.optString("tag") },j.optJSONArray("Role").objects().take(10).map { it.optString("tag") },
|
||||||
j.optJSONArray("Media").objects().map(::parseMedia),
|
j.optJSONArray("Media").objects().map { m -> Media(m.optString("id"),m.optString("container"),m.optString("videoCodec"),m.optString("audioCodec"),m.optString("videoResolution"),m.optInt("width"),m.optInt("height"),m.optInt("bitrate"),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")) }) },
|
||||||
j.optJSONArray("Marker").objects().map { Marker(it.optString("type"),it.optLong("startTimeOffset"),it.optLong("endTimeOffset")) },
|
j.optJSONArray("Marker").objects().map { Marker(it.optString("type"),it.optLong("startTimeOffset"),it.optLong("endTimeOffset")) },
|
||||||
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="clearLogo"}?.optString("url").orEmpty(),
|
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="clearLogo"}?.optString("url").orEmpty(),
|
||||||
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="coverPoster"}?.optString("url").orEmpty(),
|
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="coverPoster"}?.optString("url").orEmpty(),
|
||||||
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="snapshot"}?.optString("url").orEmpty(),
|
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="snapshot"}?.optString("url").orEmpty(),
|
||||||
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().map{Chapter(it.optInt("index"),it.optString("title","Chapter ${it.optInt("index")+1}"),it.optLong("startTimeOffset"),it.optLong("endTimeOffset"),it.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.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 {
|
|
||||||
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 video=m.optJSONArray("Part").objects().flatMap{it.optJSONArray("Stream").objects()}.firstOrNull{it.optInt("streamType")==1}
|
|
||||||
return Media(m.optString("id"),m.optString("container"),m.optString("videoCodec"),m.optString("audioCodec"),m.optString("videoResolution"),m.optInt("width"),m.optInt("height"),m.optInt("bitrate"),parts,
|
|
||||||
video?.let(::dynamicRange).orEmpty(),m.optInt("audioChannels"))
|
|
||||||
}
|
|
||||||
internal fun dynamicRange(video:JSONObject):String = when {
|
|
||||||
video.optBoolean("DOVIPresent") -> "Dolby Vision"
|
|
||||||
video.optString("colorTrc")=="smpte2084" -> "HDR10"
|
|
||||||
video.optString("colorTrc")=="arib-std-b67" -> "HLG"
|
|
||||||
else -> ""
|
|
||||||
}
|
|
||||||
/** Plex chapter indexes are already 1-based; untitled chapters are numbered by position. */
|
|
||||||
internal fun chapterTitle(title:String,position:Int)=title.ifBlank{"Chapter ${position+1}"}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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. */
|
||||||
@Immutable data class AudienceScore(val source:String,val value:Double) {
|
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 {
|
||||||
|
|
@ -129,21 +77,8 @@ internal fun fileSize(bytes:Long):String = if(bytes>=1_000_000_000L)String.forma
|
||||||
|
|
||||||
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. */
|
data class Hub(val id: String, val title: String, val items: List<Title>)
|
||||||
@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)
|
|
||||||
@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)
|
||||||
|
|
||||||
/** Whether a server address is on this network: plex.direct names encode the server's IP. */
|
|
||||||
internal fun isLocalAddress(url:String):Boolean {
|
|
||||||
val host=runCatching{java.net.URI(url).host}.getOrNull()?.lowercase()?.trim('[',']') ?: return false
|
|
||||||
val ip=if(host.endsWith(".plex.direct"))host.substringBefore('.').replace('-','.')else host
|
|
||||||
if(host=="localhost"||host.endsWith(".local")||!host.contains('.')&&!host.contains(':'))return true
|
|
||||||
val octets=ip.split('.').map{it.toIntOrNull() ?: return ip.startsWith("fd")||ip.startsWith("fe80")}
|
|
||||||
if(octets.size!=4||octets.any{it !in 0..255})return false
|
|
||||||
val (a,b)=octets
|
|
||||||
return a==10||a==127||a==192&&b==168||a==172&&b in 16..31||a==169&&b==254||a==100&&b in 64..127
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -40,55 +40,25 @@ import android.util.Log
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import kotlinx.coroutines.sync.Mutex
|
|
||||||
import kotlinx.coroutines.sync.withLock
|
|
||||||
|
|
||||||
data class TimelineReport(val position: Long,val state: String,val duration: Long,val final: Boolean=false)
|
data class TimelineReport(val position: Long,val state: String,val duration: Long,val final: Boolean=false)
|
||||||
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
||||||
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"})))
|
||||||
private val renderers=object:DefaultRenderersFactory(app) {
|
val player=ExoPlayer.Builder(app,DefaultRenderersFactory(app).setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing()).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply {
|
||||||
override fun buildAudioSink(context:android.content.Context,enableFloatOutput:Boolean,enableAudioOutputPlaybackParams:Boolean):androidx.media3.exoplayer.audio.AudioSink =
|
|
||||||
CompatibleAudioSink(androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context)
|
|
||||||
.setEnableFloatOutput(enableFloatOutput)
|
|
||||||
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
|
|
||||||
.build())
|
|
||||||
}.setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing()
|
|
||||||
val player=ExoPlayer.Builder(app,renderers).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply {
|
|
||||||
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),true)
|
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),true)
|
||||||
setHandleAudioBecomingNoisy(true)
|
setHandleAudioBecomingNoisy(true)
|
||||||
}
|
}
|
||||||
val mediaSession=MediaSession.Builder(app,player).setId("kaleido-${UUID.randomUUID()}").build()
|
val mediaSession=MediaSession.Builder(app,player).setId("kaleido-${UUID.randomUUID()}").build()
|
||||||
private val validation=BuildConfig.DEBUG&&vm.debugValidation
|
var mode by mutableIntStateOf(vm.playbackMode);private set
|
||||||
private val localValidationFile=if(validation)vm.debugValidationFile else null
|
|
||||||
private val audit=if(validation)PlaybackValidationLog(app,item,player)else null
|
|
||||||
/** The version chosen on the details page, and its parts (stacked files) on one combined timeline. */
|
|
||||||
val mediaIndex=vm.mediaIndex(item)
|
|
||||||
val media=item.media.getOrElse(mediaIndex){item.media.first()}
|
|
||||||
private val parts=media.parts
|
|
||||||
private val local=vm.localConnection
|
|
||||||
private val quality get()=vm.activeQuality
|
|
||||||
// Preserve the actual file first; Plex's generic HLS profile can convert even with directStream=1.
|
|
||||||
var mode by mutableIntStateOf(vm.debugMode ?: if(quality==StreamQuality.Original)0 else 2);private set
|
|
||||||
private var serverConverting by mutableStateOf(false)
|
|
||||||
private var serverAudioConverting by mutableStateOf(false)
|
|
||||||
val qualityLabel get()=when {
|
|
||||||
mode==2->"Converting · "+quality.conversion.label
|
|
||||||
serverConverting->if(serverAudioConverting)"Converted video and audio"else "Converted video"
|
|
||||||
serverAudioConverting->"Original video · Converted audio"
|
|
||||||
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
|
||||||
var duration by mutableLongStateOf(item.duration.takeIf{it>0} ?: parts.sumOf{it.duration});private set
|
var duration by mutableLongStateOf(item.duration);private set
|
||||||
var bufferedPosition by mutableLongStateOf(position);private set
|
var bufferedPosition by mutableLongStateOf(position);private set
|
||||||
var scrubPosition by mutableStateOf<Long?>(null);private set
|
var scrubPosition by mutableStateOf<Long?>(null);private set
|
||||||
var playbackRate by mutableFloatStateOf(1f);private set
|
var playbackRate by mutableFloatStateOf(1f);private set
|
||||||
|
|
@ -96,260 +66,95 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
||||||
var isPlaying by mutableStateOf(false);private set
|
var isPlaying by mutableStateOf(false);private set
|
||||||
var ended by mutableStateOf(false);private set
|
var ended by mutableStateOf(false);private set
|
||||||
var tracks by mutableStateOf(Tracks.EMPTY);private set
|
var tracks by mutableStateOf(Tracks.EMPTY);private set
|
||||||
var partIndex by mutableIntStateOf(partFor(parts,position));private set
|
var activeSubtitle by mutableStateOf(item.media.first().parts.first().streams.firstOrNull{it.type==3&&it.selected}?.id ?: "0");private set
|
||||||
val part get()=parts[partIndex.coerceIn(0,parts.lastIndex)]
|
var activeAudio by mutableStateOf(item.media.first().parts.first().streams.firstOrNull{it.type==2&&it.selected}?.id.orEmpty());private set
|
||||||
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 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 streamSelectionMutex=Mutex()
|
|
||||||
private var fallbackPending=false
|
|
||||||
private var nativeSelectionApplied=false
|
|
||||||
private val reports=Channel<TimelineReport>(Channel.UNLIMITED)
|
private val reports=Channel<TimelineReport>(Channel.UNLIMITED)
|
||||||
// Trailers and other extras are not library progress.
|
|
||||||
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 {
|
private val reportJob=app.scope.launch {
|
||||||
val watched=WatchedProgress{api.watched(item,true,server);withContext(Dispatchers.Main){if(api.session==server)vm.refreshWatched(item)}}
|
val watched=WatchedProgress{api.watched(item,true);withContext(Dispatchers.Main){vm.refreshWatched(item)}}
|
||||||
for(r in reports) {
|
for(r in reports) {
|
||||||
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)}
|
|
||||||
// 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;ended=state==Player.STATE_ENDED
|
||||||
// A stacked file continues with its next part; only the last part ends the title.
|
|
||||||
if(state==Player.STATE_ENDED&&!preparing&&partIndex<parts.lastIndex){
|
|
||||||
val next=partStart(parts,partIndex+1)
|
|
||||||
Log.i("KaleidoPlayback","PART ${partIndex+1} of ${parts.size} ended; continuing at $next")
|
|
||||||
scope.launch{prepare(mode,next,true)};return
|
|
||||||
}
|
|
||||||
ended=state==Player.STATE_ENDED
|
|
||||||
if(state==Player.STATE_READY) {preparing=false;error=null;Log.i("KaleidoPlayback","READY item=${item.id} mode=$mode position=${player.currentPosition} video=${player.videoFormat?.codecs} size=${player.videoSize.width}x${player.videoSize.height}")}
|
if(state==Player.STATE_READY) {preparing=false;error=null;Log.i("KaleidoPlayback","READY item=${item.id} mode=$mode position=${player.currentPosition} video=${player.videoFormat?.codecs} size=${player.videoSize.width}x${player.videoSize.height}")}
|
||||||
if(ended) {position=duration;report("stopped");Log.i("KaleidoPlayback","ENDED")}
|
if(ended) {position=duration;report("stopped");Log.i("KaleidoPlayback","ENDED")}
|
||||||
}
|
}
|
||||||
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;Log.i("KaleidoPlayback","TRACKS audio=${value.groups.count{it.type==C.TRACK_TYPE_AUDIO}} text=${value.groups.count{it.type==C.TRACK_TYPE_TEXT}}")}
|
||||||
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}}")
|
|
||||||
// Some extractors expose only audio for an unsupported video codec (e.g. VC-1).
|
|
||||||
if(value.groups.isNotEmpty()&&media.videoCodec.isNotBlank()&&
|
|
||||||
value.groups.none{it.type==C.TRACK_TYPE_VIDEO&&it.isSupported(true)}) {
|
|
||||||
fallback("unsupportedVideo");return
|
|
||||||
}
|
|
||||||
if(mode==0&&!nativeSelectionApplied&&value.groups.isNotEmpty()) {
|
|
||||||
nativeSelectionApplied=true
|
|
||||||
applyNativeSelection(C.TRACK_TYPE_AUDIO,activeAudio)
|
|
||||||
applyNativeSelection(C.TRACK_TYPE_TEXT,activeSubtitle)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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(serverStopped)return
|
if(mode<2){scope.launch{prepare(mode+1,position)}}else{loading=false;error="Playback failed (${e.errorCodeName}). Check the server transcoder, network connection, and media availability."}
|
||||||
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)}}
|
scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=player.bufferedPosition.coerceIn(0,duration);val d=player.duration;if(d>0)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. */
|
private fun currentPosition() = 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) {
|
suspend fun prepare(newMode: Int,offset: Long,resume:Boolean=true) {
|
||||||
if(closed||serverStopped)return
|
if(closed)return
|
||||||
serverStopped=true
|
preparing=true;loading=true;error=null;ended=false;player.stop()
|
||||||
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) {
|
|
||||||
if(closed||serverStopped||mode>=2||localValidationFile!=null||fallbackPending)return
|
|
||||||
fallbackPending=true
|
|
||||||
val session=streamSession;val offset=if(preparing)position else currentPosition();val resume=player.playWhenReady
|
|
||||||
scope.launch {
|
|
||||||
try {prepareMutex.withLock {
|
|
||||||
if(!closed&&session==streamSession&&!checkServerStopped(offset)) {
|
|
||||||
audit?.event("fallback",org.json.JSONObject().put("reason",reason).put("fromMode",mode).put("offset",offset))
|
|
||||||
prepareInternal(mode+1,offset,resume)
|
|
||||||
}
|
|
||||||
}}finally{fallbackPending=false}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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) {
|
|
||||||
if(closed||serverStopped)return
|
|
||||||
preparing=true;loading=true;error=null;ended=false;nativeSelectionApplied=false
|
|
||||||
serverConverting=false;serverAudioConverting=false
|
|
||||||
// Empty track events from stop must not be mistaken for a missing video track.
|
|
||||||
player.stop()
|
|
||||||
selector.parameters=selector.buildUponParameters().clearOverrides().build()
|
|
||||||
try {
|
try {
|
||||||
if(mode>0)runCatching{api.stopTranscode(streamSession,server)}
|
if(mode>0)runCatching{api.stopTranscode(streamSession)}
|
||||||
mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=offset
|
mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=if(mode>0)offset else 0L
|
||||||
partIndex=partFor(parts,offset)
|
val media=item.media.first();val part=media.parts.first()
|
||||||
val partOffsetMs=(offset-partOffset).coerceAtLeast(0)
|
|
||||||
position=offset
|
|
||||||
audit?.event("prepare",org.json.JSONObject().put("mode",mode).put("offset",offset))
|
|
||||||
val part=part
|
|
||||||
val builder=MediaItem.Builder().setMediaId(item.id).setMediaMetadata(MediaMetadata.Builder().setTitle(item.title).setArtist(item.grandparentTitle).build())
|
val builder=MediaItem.Builder().setMediaId(item.id).setMediaMetadata(MediaMetadata.Builder().setTitle(item.title).setArtist(item.grandparentTitle).build())
|
||||||
if(mode==0) {
|
if(mode==0) {
|
||||||
builder.setUri(if(localValidationFile!=null)android.net.Uri.fromFile(localValidationFile).toString()else api.url(part.key))
|
builder.setUri(api.url(part.key))
|
||||||
builder.setSubtitleConfigurations(part.streams.filter{it.type==3&&it.key.isNotBlank()&&it.codec in listOf("srt","webvtt","vtt","ass","ssa")}.map {s ->
|
builder.setSubtitleConfigurations(part.streams.filter{it.type==3&&it.key.isNotBlank()&&it.codec in listOf("srt","webvtt","vtt","ass","ssa")}.map {s ->
|
||||||
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==activeSubtitle)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).toMutableMap().apply {
|
val p=api.transcodeParams(item,streamSession,mode,offset,vm.quality)
|
||||||
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()}
|
|
||||||
.flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}
|
|
||||||
serverConverting=streams.any{it.optInt("streamType")==1&&it.optString("decision")=="transcode"}
|
|
||||||
serverAudioConverting=streams.any{it.optInt("streamType")==2&&it.optString("decision")=="transcode"}
|
|
||||||
audit?.event("decision",org.json.JSONObject().apply{
|
|
||||||
listOf("generalDecisionCode","generalDecisionText","directPlayDecisionCode","directPlayDecisionText","transcodeDecisionCode","transcodeDecisionText").forEach{k->if(decision.has(k))put(k,decision.get(k))}
|
|
||||||
}
|
|
||||||
.put("streams",org.json.JSONArray(streams.map{s->
|
|
||||||
org.json.JSONObject().apply{listOf("streamType","codec","decision","profile","bitDepth","colorTrc","DOVIProfile").forEach{k->if(s.has(k))put(k,s.get(k))}}
|
|
||||||
})))
|
|
||||||
if(decision.optInt("generalDecisionCode")>=2000)throw PlexException(decision.optString("generalDecisionText","Server cannot convert this media."))
|
if(decision.optInt("generalDecisionCode")>=2000)throw PlexException(decision.optString("generalDecisionText","Server cannot convert this media."))
|
||||||
builder.setUri(api.url("/video/:/transcode/universal/start.m3u8",p)).setMimeType(MimeTypes.APPLICATION_M3U8)
|
builder.setUri(api.url("/video/:/transcode/universal/start.m3u8",p)).setMimeType(MimeTypes.APPLICATION_M3U8)
|
||||||
}
|
}
|
||||||
// Plex HLS exposes the part's original timeline, including a seek-start offset:
|
// Plex HLS exposes the original absolute timeline, including a seek-start offset.
|
||||||
// never add the requested offset again.
|
player.setMediaItem(builder.build(),offset);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")
|
||||||
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){if(newMode<2)prepare(newMode+1,offset)else{preparing=false;loading=false;error=e.message ?: "The server could not start playback."}}
|
||||||
}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))
|
|
||||||
if(newMode<2&&localValidationFile==null)prepareInternal(newMode+1,offset,resume)else{preparing=false;loading=false;error=e.message ?: "The server could not start playback."}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fun seekTo(target:Long){
|
|
||||||
val clamped=target.coerceIn(0,duration)
|
|
||||||
val resume=player.playWhenReady
|
|
||||||
// Another part, or a conversion that starts after the target, needs a new stream.
|
|
||||||
if(partFor(parts,clamped)!=partIndex||mode>0&&clamped<streamStart)scope.launch{prepare(mode,clamped,resume)}
|
|
||||||
else{player.seekTo(clamped-partOffset);position=clamped;report(if(isPlaying)"playing"else "paused")}
|
|
||||||
}
|
}
|
||||||
|
fun seekTo(target:Long){val clamped=target.coerceIn(0,duration);if(mode>0&&clamped<streamStart){val resume=player.playWhenReady;scope.launch{prepare(mode,clamped,resume)}}else{player.seekTo(clamped);position=clamped;report(if(isPlaying)"playing"else "paused")}}
|
||||||
fun toggle(){if(player.isPlaying)player.pause()else{if(ended)seekTo(0);player.play()}}
|
fun toggle(){if(player.isPlaying)player.pause()else{if(ended)seekTo(0);player.play()}}
|
||||||
fun retry(){scope.launch{prepare(mode,position)}}
|
fun retry(){scope.launch{prepare(mode,position)}}
|
||||||
fun changeQuality(value:StreamQuality){val resume=player.playWhenReady;vm.chooseActiveQuality(value);scope.launch{prepare(if(value==StreamQuality.Original)0 else 2,position,resume)}}
|
fun changeMode(value:Int){val resume=player.playWhenReady;vm.choosePlaybackMode(value);scope.launch{prepare(value,position,resume)}}
|
||||||
|
fun changeQuality(value:Int){val resume=player.playWhenReady;vm.chooseQuality(value);if(mode>0)scope.launch{prepare(mode,position,resume)}}
|
||||||
fun changeSpeed(value:Float){playbackRate=value;player.setPlaybackSpeed(value)}
|
fun changeSpeed(value:Float){playbackRate=value;player.setPlaybackSpeed(value)}
|
||||||
/** Moves the pending seek target; repeated presses accumulate into one seek after [settle] ms. */
|
fun scrubBy(delta:Long){scrubPosition=((scrubPosition ?: position)+delta).coerceIn(0,duration);seekJob?.cancel();seekJob=scope.launch{delay(650);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();if(!preparing)position=currentPosition();report("paused")}
|
fun pause(){player.pause();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()
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* The current part's stream for a selected stream ID. Each part of a stacked file has its own
|
|
||||||
* stream IDs; Plex applies a selection to all parts, so match by position among that type.
|
|
||||||
*/
|
|
||||||
fun currentStream(id:String):Stream? {
|
|
||||||
part.streams.firstOrNull{it.id==id}?.let{return it}
|
|
||||||
val source=parts.firstOrNull{p->p.streams.any{it.id==id}} ?: return null
|
|
||||||
val stream=source.streams.first{it.id==id}
|
|
||||||
val ordinal=source.streams.filter{it.type==stream.type}.indexOf(stream)
|
|
||||||
return part.streams.filter{it.type==stream.type}.getOrNull(ordinal)
|
|
||||||
}
|
|
||||||
private fun nativeTrack(type:Int,stream:Stream):Pair<Int,Int>? {
|
|
||||||
val candidates=tracks.groups.withIndex().filter{it.value.type==type}.flatMap{g->(0 until g.value.length).map{g.index to it}}
|
|
||||||
if(stream.key.isNotBlank())return candidates.firstOrNull{(g,t)->tracks.groups[g].getTrackFormat(t).id==stream.id}
|
|
||||||
val ordinal=part.streams.filter{it.type==stream.type&&it.key.isBlank()}.indexOfFirst{it.id==stream.id}
|
|
||||||
return candidates.filter{(g,t)->tracks.groups[g].getTrackFormat(t).id !in part.streams.filter{it.key.isNotBlank()}.map{it.id}}.getOrNull(ordinal)
|
|
||||||
}
|
|
||||||
private fun applyNativeSelection(type:Int,id:String) {
|
|
||||||
if(type==C.TRACK_TYPE_TEXT&&id=="0") {
|
|
||||||
selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return
|
|
||||||
}
|
|
||||||
val stream=currentStream(id) ?: return
|
|
||||||
val match=nativeTrack(type,stream) ?: return
|
|
||||||
if(tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second)
|
|
||||||
else fallback("unsupportedSelectedTrack")
|
|
||||||
}
|
|
||||||
fun selectServerStream(stream:Stream?,type:Int) {
|
fun selectServerStream(stream:Stream?,type:Int) {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
streamSelectionMutex.withLock {
|
try {
|
||||||
try {prepareMutex.withLock selection@{
|
val part=item.media.first().parts.first()
|
||||||
if(closed)return@selection
|
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 part=part
|
if(mode>0){prepare(mode,position,player.playWhenReady);return@launch}
|
||||||
val selected=stream?.let{currentStream(it.id)}
|
|
||||||
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=selected?.let{nativeTrack(type,it)}
|
val groups=tracks.groups.withIndex().filter{it.value.type==type}
|
||||||
if(match!=null&&tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second)
|
val matching=groups.flatMap{g->(0 until g.value.length).map{g.index to it}}.firstOrNull{(g,t)->tracks.groups[g].getTrackFormat(t).id==stream.id}
|
||||||
else prepareInternal(if(type==C.TRACK_TYPE_AUDIO)1 else 2,offset,resume)
|
val matchingExternal=if(type==C.TRACK_TYPE_TEXT&&stream.key.isNotBlank())matching else null
|
||||||
}}catch(e:CancellationException){throw e}catch(e:Exception){error="Could not change the selected track. Please try again."}
|
val streamIndex=part.streams.filter{it.type==(if(type==C.TRACK_TYPE_AUDIO)2 else 3)&&it.key.isBlank()}.indexOfFirst{it.id==stream.id}
|
||||||
|
val candidates=groups.flatMap{g->(0 until g.value.length).map{g.index to it}}
|
||||||
|
val match=matchingExternal ?: matching ?: candidates.getOrNull(streamIndex)
|
||||||
|
if(match!=null)select(type,match.first,match.second)
|
||||||
|
else prepare(2,position) // Image subtitles and unsupported embedded tracks are burned by Plex.
|
||||||
|
}catch(e:Exception){error=e.message ?: "Could not change the selected track."}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();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. */
|
|
||||||
enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:Int) {
|
|
||||||
Original("Original quality",0,0,0),
|
|
||||||
UltraHD("4K · 80 Mbps",3840,2160,80000),
|
|
||||||
FullHD("1080p · 20 Mbps",1920,1080,20000),
|
|
||||||
HD("720p · 8 Mbps",1280,720,8000),
|
|
||||||
SD("480p · 3 Mbps",720,480,3000);
|
|
||||||
/** Target used when Plex must convert; Original falls back to 1080p if direct streaming fails. */
|
|
||||||
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. */
|
|
||||||
enum class SubtitleSize(val label:String,val scale:Float,val plexPercent:Int) {
|
|
||||||
Small("Small",.8f,80),Normal("Normal",1f,100),Large("Large",1.25f,125),ExtraLarge("Extra large",1.5f,150)
|
|
||||||
}
|
|
||||||
enum class SubtitleStyle(val label:String) {
|
|
||||||
Box("White on black"),Shadow("White with shadow"),Outline("White with outline"),Yellow("Yellow with outline"),System("Follow TV caption settings")
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -19,178 +19,62 @@ 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 modes=listOf("Original file","Direct stream","Transcode")
|
||||||
val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f)
|
val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f)
|
||||||
// Audio is also named here so it is discoverable without recognizing the speaker icon.
|
|
||||||
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}")
|
|
||||||
// A submenu returns focus to the option that opened it.
|
|
||||||
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",listOf("Mode · ${modes[controller.mode]}","Audio language","Subtitles","Speed · ${controller.playbackRate}×","Transcode quality", "Chapters"),0,dismiss){index->open(when(index){0->4;1->1;2->2;3->5;4->6;else->7})}
|
||||||
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()}
|
4->TrackPanel("Playback mode",modes,controller.mode,dismiss){controller.changeMode(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{"${it}×"},speeds.indexOf(controller.playbackRate),dismiss){controller.changeSpeed(speeds[it]);close()}
|
||||||
|
6->TrackPanel("Transcode quality",listOf("1080p · 20 Mbps","4K · 80 Mbps"),if(vm.quality>20000)1 else 0,dismiss){controller.changeQuality(if(it==0)20000 else 80000);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()}
|
|
||||||
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")}×"
|
@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)
|
||||||
val path=upcoming?.let{it.still.ifBlank{it.thumb}.ifBlank{it.art}} ?: item.art.ifBlank{item.thumb}
|
var autoplay by remember{mutableStateOf(true)}
|
||||||
Box(modifier.fillMaxSize().background(Ink)) {
|
var seconds by remember{mutableIntStateOf(5)}
|
||||||
Box(Modifier.align(Alignment.TopEnd).width(640.dp).aspectRatio(16f/9f)) {
|
LaunchedEffect(autoplay,upcoming?.id) {
|
||||||
if(path.isNotBlank())Artwork(vm.api,path,Modifier.fillMaxSize(),960,540,animate=false)
|
if(autoplay&&upcoming!=null){seconds=5;android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}");repeat(5){delay(1000);seconds--};android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()}
|
||||||
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(0f to Ink,.42f to Ink.copy(alpha=.72f),1f to Color.Transparent)))
|
|
||||||
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(.35f to Color.Transparent,1f to Ink)))
|
|
||||||
}
|
}
|
||||||
Box(Modifier.offset(UpNextFrame.x,UpNextFrame.y).size(UpNextFrame.width,UpNextFrame.height).background(Color.Black))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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}
|
val season=vm.episodeQueue.filter{it.parentId==item.parentId}
|
||||||
Box(Modifier.fillMaxSize().onPreviewKeyEvent{
|
LazyColumn(Modifier.fillMaxSize().background(Color.Black.copy(alpha=.93f)),contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=29.dp),verticalArrangement=Arrangement.spacedBy(15.dp)) {
|
||||||
if(it.type==KeyEventType.KeyDown&&counting){cancelled=true;android.util.Log.i("KaleidoPlayback","AUTOPLAY cancelled item=${item.id}")}
|
item {
|
||||||
false
|
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) {
|
||||||
// The video itself is the PlayerView beneath; this is its focus target and outline.
|
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)
|
||||||
var videoFocused by remember{mutableStateOf(false)}
|
Column(Modifier.weight(1f)) {
|
||||||
Box(Modifier.offset(UpNextFrame.x-4.dp,UpNextFrame.y-4.dp).size(UpNextFrame.width+8.dp,UpNextFrame.height+8.dp)
|
Text(upcoming?.displayTitle ?: item.displayTitle,color=Accent,fontSize=21.sp,fontWeight=FontWeight.SemiBold)
|
||||||
.focusRequester(videoFocus).focusProperties{right=if(upcoming!=null)playFocus else FocusRequester.Default}
|
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))
|
||||||
.navigationSound().onFocusChanged{videoFocused=it.isFocused}
|
Row(horizontalArrangement=Arrangement.spacedBy(10.dp),verticalAlignment=Alignment.CenterVertically) {
|
||||||
.border(if(videoFocused)2.dp else 1.dp,Color.White.copy(alpha=if(videoFocused)1f else .16f),RoundedCornerShape(8.dp))
|
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()}
|
||||||
.semantics{contentDescription="Return to "+item.displayTitle}.clickable(onClick=watchVideo))
|
if(upcoming!=null)TvButton(if(autoplay)"Cancel autoplay"else "Autoplay off"){autoplay=!autoplay;android.util.Log.i("KaleidoPlayback","AUTOPLAY ${if(autoplay)"enabled"else "cancelled"} item=${item.id}")}
|
||||||
NowPlaying(item,controller,videoFocused,Modifier.offset(UpNextFrame.x,UpNextFrame.y+UpNextFrame.height+10.dp).width(UpNextFrame.width))
|
TvButton("Back to video"){autoplay=false;dismiss()}
|
||||||
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
|
if(season.isNotEmpty())item {PostPlayRail(vm,"Episodes in this season",season){autoplay=false;vm.play(it,true)}}
|
||||||
Box(Modifier.padding(top=6.dp).fillMaxWidth().height(3.dp).clip(RoundedCornerShape(2.dp)).background(Color.White.copy(alpha=.22f))) {
|
if(vm.relatedShows.isNotEmpty())item {PostPlayRail(vm,"Related shows",vm.relatedShows){autoplay=false;vm.stopPlayback();vm.open(it)}}
|
||||||
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) {
|
@Composable private fun PostPlayRail(vm:KaleidoViewModel,label:String,titles:List<Title>,choose:(Title)->Unit) {
|
||||||
Column {
|
Column {
|
||||||
Text(label,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=8.dp))
|
Text(label,color=Accent,fontSize=16.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=8.dp))
|
||||||
LazyRow(state=rememberLazyListState(start),horizontalArrangement=Arrangement.spacedBy(12.dp)) {
|
LazyRow(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(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)}) {
|
Column(Modifier.width(167.dp).navigationSound().onFocusChanged{focused=it.isFocused}.semantics{contentDescription=title.displayTitle+" "+title.subtitle}.clickable{choose(title)}) {
|
||||||
Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).clip(RoundedCornerShape(6.dp))) {
|
Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).clip(RoundedCornerShape(4.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(6.dp)))
|
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(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(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(caption(title),color=Cinema.quiet,fontSize=10.sp,lineHeight=14.sp,maxLines=1)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,71 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Base64
|
|
||||||
import androidx.media3.common.*
|
|
||||||
import androidx.media3.common.util.UnstableApi
|
|
||||||
import androidx.media3.exoplayer.*
|
|
||||||
import androidx.media3.exoplayer.analytics.AnalyticsListener
|
|
||||||
import androidx.media3.exoplayer.audio.AudioSink
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.channels.Channel
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
|
|
||||||
/** Opt-in debug evidence only: never serialize media URLs, headers, or session credentials. */
|
|
||||||
@androidx.annotation.OptIn(UnstableApi::class)
|
|
||||||
internal class PlaybackValidationLog(app:KaleidoApplication,item:Title,private val player:ExoPlayer):AnalyticsListener {
|
|
||||||
private val lines=Channel<String>(Channel.UNLIMITED)
|
|
||||||
init {
|
|
||||||
app.scope.launch(Dispatchers.IO) {
|
|
||||||
app.openFileOutput("playback-validation.jsonl",Context.MODE_PRIVATE).bufferedWriter().use { out->
|
|
||||||
for(line in lines){out.write(line);out.newLine();out.flush()}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
event("source",JSONObject().put("id",item.id).put("title",item.title).put("type",item.type)
|
|
||||||
.put("media",JSONArray(item.media.map{JSONObject().put("videoCodec",it.videoCodec).put("audioCodec",it.audioCodec)
|
|
||||||
.put("width",it.width).put("height",it.height).put("container",it.container).put("bitrate",it.bitrate)})))
|
|
||||||
}
|
|
||||||
fun event(name:String,data:JSONObject=JSONObject()) {
|
|
||||||
data.put("event",name).put("elapsedMs",android.os.SystemClock.elapsedRealtime())
|
|
||||||
lines.trySend(data.toString())
|
|
||||||
}
|
|
||||||
private fun format(f:Format):JSONObject=JSONObject().put("mime",f.sampleMimeType).put("codecs",f.codecs)
|
|
||||||
.put("width",f.width).put("height",f.height).put("fps",f.frameRate).put("channels",f.channelCount).put("channelMask",f.channelMask).put("sampleRate",f.sampleRate).put("pcmEncoding",f.pcmEncoding)
|
|
||||||
.apply { f.colorInfo?.let { c->
|
|
||||||
put("colorSpace",c.colorSpace).put("colorRange",c.colorRange).put("colorTransfer",c.colorTransfer)
|
|
||||||
put("hdrStaticInfo",c.hdrStaticInfo?.let{Base64.encodeToString(it,Base64.NO_WRAP)} ?: JSONObject.NULL)
|
|
||||||
}}
|
|
||||||
fun sample(mode:Int) {
|
|
||||||
event("sample",JSONObject().put("mode",mode).put("state",player.playbackState).put("playing",player.isPlaying)
|
|
||||||
.put("position",player.currentPosition).put("buffered",player.bufferedPosition).put("duration",player.duration)
|
|
||||||
.put("video",player.videoFormat?.let(::format)).put("audio",player.audioFormat?.let(::format))
|
|
||||||
.put("videoCounters",player.videoDecoderCounters?.let(::counters)).put("audioCounters",player.audioDecoderCounters?.let(::counters)))
|
|
||||||
}
|
|
||||||
private fun counters(c:DecoderCounters):JSONObject {
|
|
||||||
c.ensureUpdated()
|
|
||||||
return JSONObject().put("queued",c.queuedInputBufferCount).put("rendered",c.renderedOutputBufferCount)
|
|
||||||
.put("dropped",c.droppedBufferCount).put("skipped",c.skippedOutputBufferCount)
|
|
||||||
.put("maxConsecutiveDropped",c.maxConsecutiveDroppedBufferCount)
|
|
||||||
}
|
|
||||||
override fun onVideoDecoderInitialized(t:AnalyticsListener.EventTime,name:String,a:Long,b:Long){event("videoDecoder",JSONObject().put("name",name))}
|
|
||||||
override fun onAudioDecoderInitialized(t:AnalyticsListener.EventTime,name:String,a:Long,b:Long){event("audioDecoder",JSONObject().put("name",name))}
|
|
||||||
override fun onVideoInputFormatChanged(t:AnalyticsListener.EventTime,f:Format,reuse:DecoderReuseEvaluation?){event("videoFormat",format(f))}
|
|
||||||
override fun onAudioInputFormatChanged(t:AnalyticsListener.EventTime,f:Format,reuse:DecoderReuseEvaluation?){event("audioFormat",format(f))}
|
|
||||||
override fun onRenderedFirstFrame(t:AnalyticsListener.EventTime,output:Any,renderTimeMs:Long){event("firstFrame")}
|
|
||||||
override fun onAudioPositionAdvancing(t:AnalyticsListener.EventTime,startTimeMs:Long){event("audioAdvancing")}
|
|
||||||
override fun onAudioTrackInitialized(t:AnalyticsListener.EventTime,c:AudioSink.AudioTrackConfig){
|
|
||||||
event("audioTrack",JSONObject().put("encoding",c.encoding).put("sampleRate",c.sampleRate)
|
|
||||||
.put("channelMask",c.channelConfig).put("offload",c.offload).put("tunneling",c.tunneling))
|
|
||||||
}
|
|
||||||
override fun onAudioUnderrun(t:AnalyticsListener.EventTime,size:Int,duration:Long,elapsed:Long){event("audioUnderrun",JSONObject().put("elapsedMsSinceFeed",elapsed))}
|
|
||||||
override fun onPlayerError(t:AnalyticsListener.EventTime,e:PlaybackException){
|
|
||||||
val http=generateSequence<Throwable>(e){it.cause}.filterIsInstance<androidx.media3.datasource.HttpDataSource.InvalidResponseCodeException>().firstOrNull()
|
|
||||||
event("error",JSONObject().put("code",e.errorCodeName).put("httpStatus",http?.responseCode)
|
|
||||||
.put("causes",JSONArray(generateSequence<Throwable>(e){it.cause}.map{cause->
|
|
||||||
JSONObject().put("type",cause.javaClass.simpleName).put("frames",JSONArray(cause.stackTrace.take(4).map{"${it.className}.${it.methodName}:${it.lineNumber}"}))
|
|
||||||
}.toList())))
|
|
||||||
}
|
|
||||||
fun finish(mode:Int){sample(mode);event("closed");lines.close()}
|
|
||||||
}
|
|
||||||
|
|
@ -5,18 +5,12 @@ 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
|
||||||
import androidx.compose.foundation.*
|
import androidx.compose.foundation.*
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.media3.ui.CaptionStyleCompat
|
|
||||||
import androidx.media3.ui.SubtitleView
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.*
|
import androidx.compose.material.icons.filled.*
|
||||||
|
|
@ -28,14 +22,10 @@ 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
|
||||||
|
|
@ -67,21 +57,7 @@ import kotlinx.coroutines.delay
|
||||||
var trackMenu by remember{mutableIntStateOf(0)}
|
var trackMenu by remember{mutableIntStateOf(0)}
|
||||||
var postPlay by remember{mutableStateOf(false)}
|
var postPlay by remember{mutableStateOf(false)}
|
||||||
var seekFocus by remember{mutableStateOf(false)}
|
var seekFocus by remember{mutableStateOf(false)}
|
||||||
// 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 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()}
|
||||||
|
|
@ -91,70 +67,23 @@ import kotlinx.coroutines.delay
|
||||||
fun interacted(){interaction=System.currentTimeMillis()}
|
fun interacted(){interaction=System.currentTimeMillis()}
|
||||||
fun closeTracks(){restoreMenuFocus=trackMenu;trackMenu=0;interacted()}
|
fun closeTracks(){restoreMenuFocus=trackMenu;trackMenu=0;interacted()}
|
||||||
LaunchedEffect(item.id){vm.loadEpisodeContext(item)}
|
LaunchedEffect(item.id){vm.loadEpisodeContext(item)}
|
||||||
LaunchedEffect(controller.ended){
|
LaunchedEffect(controller.ended){if(controller.ended&&item.type=="episode"){android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=ended");postPlay=true}}
|
||||||
if(!controller.ended)return@LaunchedEffect
|
|
||||||
if(item.type=="episode"){android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=ended");postPlay=true}
|
|
||||||
// A finished movie or extra returns to its details instead of resting on the last frame.
|
|
||||||
else vm.stopPlayback()
|
|
||||||
}
|
|
||||||
// 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")}}}
|
|
||||||
fun skip(marker:Marker){
|
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
// 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>()}
|
|
||||||
var autoSkip by remember{mutableStateOf<Marker?>(null)}
|
|
||||||
var autoSkipTotal by remember{mutableLongStateOf(0)}
|
|
||||||
var autoSkipRemaining by remember{mutableLongStateOf(0)}
|
|
||||||
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->when(event){Lifecycle.Event.ON_STOP->controller.enterBackground();Lifecycle.Event.ON_START->controller.enterForeground();else->{}}}
|
val observer=LifecycleEventObserver{_,event->if(event==Lifecycle.Event.ON_STOP)controller.pause()}
|
||||||
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()}
|
||||||
}
|
}
|
||||||
// Up Next owns focus while open: hiding the controls behind it must not take focus back.
|
LaunchedEffect(controls,interaction,controller.isPlaying,trackMenu) {
|
||||||
LaunchedEffect(controls,interaction,controller.isPlaying,trackMenu,postPlay) {
|
if(controls&&controller.isPlaying&&trackMenu==0){delay(5000);controls=false}
|
||||||
if(controls&&controller.isPlaying&&trackMenu==0&&!postPlay){delay(5000);controls=false}
|
|
||||||
}
|
}
|
||||||
LaunchedEffect(controls) {if(!controls&&!postPlay){timelineReveal=false;delay(210);if(!postPlay)runCatching{rootFocus.requestFocus()}}}
|
LaunchedEffect(controls) {if(!controls){delay(210);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()};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}}
|
||||||
// Leaving Up Next returns to the full-screen video without revealing the controls.
|
fun goBack(){if(postPlay)postPlay=false else if(trackMenu!=0)closeTracks()else if(controls)controls=false else vm.stopPlayback()}
|
||||||
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()
|
||||||
|
|
@ -164,24 +93,13 @@ import kotlinx.coroutines.delay
|
||||||
android.view.KeyEvent.KEYCODE_MEDIA_PAUSE->{controller.pause();controls=true;true}
|
android.view.KeyEvent.KEYCODE_MEDIA_PAUSE->{controller.pause();controls=true;true}
|
||||||
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.
|
android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER->{if(!visible){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->{if(!visible){controller.scrubBy(if(event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_LEFT)-10000 else 10000);controls=true;seekFocus=true;true}else false}
|
||||||
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
|
|
||||||
when {
|
|
||||||
// Quick taps accumulate a seek and show a brief directional cue.
|
|
||||||
!visible&&event.nativeKeyEvent.repeatCount==0->{quickSkip(delta);true}
|
|
||||||
// Holding reveals the timeline and keeps scrubbing until it takes focus.
|
|
||||||
!visible||seekFocus->{controller.scrubBy(delta);controls=true;seekFocus=true;true}
|
|
||||||
else->false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
android.view.KeyEvent.KEYCODE_DPAD_UP,android.view.KeyEvent.KEYCODE_DPAD_DOWN->{if(!visible){controls=true;seekFocus=event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_UP;true}else false}
|
android.view.KeyEvent.KEYCODE_DPAD_UP,android.view.KeyEvent.KEYCODE_DPAD_DOWN->{if(!visible){controls=true;seekFocus=event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_UP;true}else false}
|
||||||
else->false
|
else->false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}.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
|
||||||
|
|
@ -190,76 +108,47 @@ 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().layout{measurable,constraints->
|
}},modifier=Modifier.fillMaxSize(),onRelease={it.player=null})
|
||||||
val f=upNext.value
|
if(controller.loading)CircularProgressIndicator(color=Accent,strokeWidth=2.dp,modifier=Modifier.align(Alignment.Center).size(30.dp))
|
||||||
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,.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)) {
|
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)) {
|
||||||
// The title art and facts the browse previews and details use, at playback scale.
|
Row(Modifier.fillMaxWidth().padding(bottom=7.dp),verticalAlignment=Alignment.Bottom) {
|
||||||
Row(Modifier.fillMaxWidth().padding(bottom=10.dp),verticalAlignment=Alignment.Bottom) {
|
Text(item.displayTitle,color=Accent,fontSize=18.sp,lineHeight=23.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f))
|
||||||
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(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))
|
Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else listOf("Original","Direct stream","Transcoding")[controller.mode],color=Color.White.copy(alpha=.62f),fontSize=10.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=350.dp))
|
||||||
}
|
}
|
||||||
// Elapsed and remaining time sit at the timeline's ends and follow a pending scrub.
|
SeekTimeline(controller,item,Modifier.fillMaxWidth().focusRequester(timelineFocus).focusProperties{down=playFocus},::interacted)
|
||||||
val shownPosition=controller.scrubPosition ?: controller.position
|
Box(Modifier.fillMaxWidth().height(40.dp)) {
|
||||||
Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) {
|
Row(Modifier.align(Alignment.CenterStart),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
|
||||||
Text(clockTime(shownPosition),color=Color.White.copy(alpha=.82f),fontSize=10.sp,lineHeight=14.sp,maxLines=1,modifier=Modifier.width(58.dp))
|
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Exit playback",size=30.dp,iconSize=18.dp,onFocused=::interacted){vm.stopPlayback()}
|
||||||
SeekTimeline(controller,item,Modifier.weight(1f).focusRequester(timelineFocus).focusProperties{down=playFocus},::interacted)
|
Text(clockTime(controller.position),color=Color.White.copy(alpha=.78f),fontSize=10.sp,lineHeight=14.sp)
|
||||||
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))
|
|
||||||
}
|
}
|
||||||
Box(Modifier.fillMaxWidth().padding(top=6.dp).height(48.dp)) {
|
Row(Modifier.align(Alignment.Center),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(16.dp)) {
|
||||||
Row(Modifier.align(Alignment.CenterStart),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.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()}
|
||||||
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Exit playback",size=32.dp,iconSize=19.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){vm.stopPlayback()}
|
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,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.toggle();controls=true;interacted()}
|
||||||
Text("Ends "+endsAt(controller),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,maxLines=1)
|
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()}
|
||||||
}
|
|
||||||
// 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)) {
|
||||||
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()}
|
Text("−"+clockTime(controller.duration-controller.position),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,modifier=Modifier.padding(end=8.dp))
|
||||||
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()}
|
if(item.type=="episode")IconControl(Icons.Outlined.SkipNext,"Next episode",size=30.dp,iconSize=21.dp,onFocused=::interacted){vm.nextEpisode(item)}
|
||||||
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.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.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)146.dp else 45.dp)) {
|
val marker=item.markers.firstOrNull{controller.position>=it.start&&controller.position<it.end&&it.type in listOf("intro","credits")}
|
||||||
val counting=autoSkip==marker&&autoSkipTotal>0
|
if(marker!=null&&!postPlay)Box(Modifier.align(Alignment.BottomEnd).padding(end=Cinema.gutter,bottom=if(visible)130.dp else 45.dp)) {
|
||||||
SkipMarkerButton(marker.type=="intro",if(counting)1f-(autoSkipRemaining.toFloat()/autoSkipTotal).coerceIn(0f,1f)else null){autoSkip=null;autoSkipped+=marker;skip(marker);interacted()}
|
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))){if(marker.type=="credits"&&item.type=="episode"){controller.pause();android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=skip-credits");postPlay=true}else controller.seekTo(marker.end);interacted()}
|
||||||
}}
|
}
|
||||||
if(postPlay)PostPlayScreen(vm,item,controller,::leaveUpNext){vm.nextEpisode(item)}
|
if(postPlay)PostPlayScreen(vm,item,{postPlay=false;controls=true},{vm.nextEpisode(item)})
|
||||||
controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})}
|
controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})}
|
||||||
if(trackMenu==1)AudioTrackPanel(controller,::closeTracks,::closeTracks)
|
if(trackMenu in 1..2) {
|
||||||
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=item.media.firstOrNull()?.parts?.firstOrNull()?.streams.orEmpty().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}
|
||||||
val active=controller.currentStream(if(trackMenu==1)controller.activeAudio else controller.activeSubtitle)
|
val selected=streams.indexOfFirst{it.id==(if(trackMenu==1)controller.activeAudio else controller.activeSubtitle)}+if(trackMenu==2)1 else 0
|
||||||
val selected=streams.indexOfFirst{it.id==active?.id}+if(trackMenu==2)1 else 0
|
|
||||||
TrackPanel(if(trackMenu==1)"Audio"else "Subtitles",options,selected,::closeTracks){index->
|
TrackPanel(if(trackMenu==1)"Audio"else "Subtitles",options,selected,::closeTracks){index->
|
||||||
val stream=if(trackMenu==2)streams.getOrNull(index-1)else streams.getOrNull(index)
|
val stream=if(trackMenu==2)streams.getOrNull(index-1)else streams.getOrNull(index)
|
||||||
if(options.isNotEmpty())controller.selectServerStream(stream,type)
|
if(options.isNotEmpty())controller.selectServerStream(stream,type)
|
||||||
|
|
@ -270,87 +159,6 @@ 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. */
|
|
||||||
@Composable private fun endsAt(controller:PlaybackController):String {
|
|
||||||
val format=android.text.format.DateFormat.getTimeFormat(LocalContext.current)
|
|
||||||
val remaining=((controller.duration-controller.position).coerceAtLeast(0)/controller.playbackRate.coerceAtLeast(.25f)).toLong()
|
|
||||||
return format.format(java.util.Date(System.currentTimeMillis()+remaining))
|
|
||||||
}
|
|
||||||
|
|
||||||
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
|
||||||
/** [screenHeight]: size text against a full-screen frame, for a preview smaller than the video. */
|
|
||||||
internal fun applySubtitleStyle(view:SubtitleView,size:SubtitleSize,style:SubtitleStyle,screenHeight:Int?=null) {
|
|
||||||
val black=android.graphics.Color.BLACK;val white=android.graphics.Color.WHITE;val clear=android.graphics.Color.TRANSPARENT
|
|
||||||
var scale=size.scale
|
|
||||||
val caption=when(style) {
|
|
||||||
SubtitleStyle.Box->CaptionStyleCompat.DEFAULT
|
|
||||||
SubtitleStyle.Shadow->CaptionStyleCompat(white,clear,clear,CaptionStyleCompat.EDGE_TYPE_DROP_SHADOW,black,null)
|
|
||||||
SubtitleStyle.Outline->CaptionStyleCompat(white,clear,clear,CaptionStyleCompat.EDGE_TYPE_OUTLINE,black,null)
|
|
||||||
SubtitleStyle.Yellow->CaptionStyleCompat(0xFFFFE14D.toInt(),clear,clear,CaptionStyleCompat.EDGE_TYPE_OUTLINE,black,null)
|
|
||||||
SubtitleStyle.System->{
|
|
||||||
val captioning=view.context.getSystemService(android.view.accessibility.CaptioningManager::class.java)
|
|
||||||
scale*=captioning?.fontScale ?: 1f
|
|
||||||
captioning?.let{CaptionStyleCompat.createFromCaptionStyle(it.userStyle)} ?: CaptionStyleCompat.DEFAULT
|
|
||||||
}
|
|
||||||
}
|
|
||||||
view.setStyle(caption)
|
|
||||||
// Embedded ASS/SSA colours and positions still apply; the chosen size always does.
|
|
||||||
view.setApplyEmbeddedFontSizes(false)
|
|
||||||
if(screenHeight!=null)view.setFixedTextSize(android.util.TypedValue.COMPLEX_UNIT_PX,screenHeight*SubtitleView.DEFAULT_TEXT_SIZE_FRACTION*scale)
|
|
||||||
else view.setFractionalTextSize(SubtitleView.DEFAULT_TEXT_SIZE_FRACTION*scale)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable private fun SeekTimeline(controller:PlaybackController,item:Title,modifier:Modifier,onInteraction:()->Unit) {
|
@Composable private fun SeekTimeline(controller:PlaybackController,item:Title,modifier:Modifier,onInteraction:()->Unit) {
|
||||||
var focused by remember{mutableStateOf(false)}
|
var focused by remember{mutableStateOf(false)}
|
||||||
val displayed=controller.scrubPosition ?: controller.position
|
val displayed=controller.scrubPosition ?: controller.position
|
||||||
|
|
@ -382,19 +190,15 @@ internal fun applySubtitleStyle(view:SubtitleView,size:SubtitleSize,style:Subtit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** [selected] shows a checkmark; [focusIndex] only places focus, e.g. in a menu without a selection. */
|
@Composable internal fun TrackPanel(title:String,options:List<String>,selected:Int,dismiss:()->Unit,choose:(Int)->Unit) {
|
||||||
@Composable internal fun TrackPanel(title:String,options:List<String>,selected:Int,dismiss:()->Unit,focusIndex:Int=selected,choose:(Int)->Unit) {
|
|
||||||
val density=LocalDensity.current
|
val density=LocalDensity.current
|
||||||
val initial=(if(focusIndex>=0)focusIndex else 0).coerceIn(0,(options.size-1).coerceAtLeast(0))
|
|
||||||
// Start scrolled near the focused row: a lazy row that isn't composed can't take focus.
|
|
||||||
val list=rememberLazyListState(initialFirstVisibleItemIndex=(initial-2).coerceAtLeast(0))
|
|
||||||
val offset=with(density){IntOffset(-44.dp.roundToPx(),-108.dp.roundToPx())}
|
val offset=with(density){IntOffset(-44.dp.roundToPx(),-108.dp.roundToPx())}
|
||||||
Popup(alignment=Alignment.BottomEnd,offset=offset,onDismissRequest=dismiss,properties=PopupProperties(focusable=true)) {
|
Popup(alignment=Alignment.BottomEnd,offset=offset,onDismissRequest=dismiss,properties=PopupProperties(focusable=true)) {
|
||||||
Column(Modifier.width(280.dp).heightIn(max=330.dp).clip(RoundedCornerShape(10.dp)).background(Color(0xF5222222)).padding(13.dp).onPreviewKeyEvent{if(it.key==Key.Back){if(it.type==KeyEventType.KeyDown)dismiss();true}else if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionLeft){dismiss();true}else false}) {
|
Column(Modifier.width(280.dp).heightIn(max=330.dp).clip(RoundedCornerShape(10.dp)).background(Color(0xF5222222)).padding(13.dp).onPreviewKeyEvent{if(it.key==Key.Back){if(it.type==KeyEventType.KeyDown)dismiss();true}else if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionLeft){dismiss();true}else false}) {
|
||||||
Text(title,color=Accent,fontSize=15.sp,lineHeight=20.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=9.dp,top=5.dp,bottom=10.dp))
|
Text(title,color=Accent,fontSize=15.sp,lineHeight=20.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=9.dp,top=5.dp,bottom=10.dp))
|
||||||
if(options.isEmpty())Text("No tracks available",color=Muted,fontSize=12.sp,modifier=Modifier.padding(10.dp))
|
if(options.isEmpty())Text("No tracks available",color=Muted,fontSize=12.sp,modifier=Modifier.padding(10.dp))
|
||||||
LazyColumn(state=list,verticalArrangement=Arrangement.spacedBy(2.dp)) {
|
LazyColumn(verticalArrangement=Arrangement.spacedBy(2.dp)) {
|
||||||
items(options.size){index->TrackOption(options[index],index==selected,index==initial){choose(index)}}
|
items(options.size){index->TrackOption(options[index],index==selected,index==selected||selected<0&&index==0){choose(index)}}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,10 @@
|
||||||
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
|
||||||
|
|
@ -18,10 +15,6 @@ 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
|
||||||
|
|
@ -34,24 +27,16 @@ 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 = coroutineScope {
|
suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map<String,String> = emptyMap()): String = withContext(Dispatchers.IO) {
|
||||||
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()
|
||||||
val call=http.newCall(req)
|
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() ?: "{}" }
|
||||||
// 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() ?: "{}" }
|
|
||||||
}
|
}
|
||||||
} finally { abort.cancel() }
|
fun url(path: String, params: Map<String,String> = emptyMap()): String {
|
||||||
}
|
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(), server: Session? = session): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params,server),server?.serverToken).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()}
|
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 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.")
|
||||||
|
|
@ -70,121 +55,58 @@ 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()) {
|
||||||
// Probe together, but accept in preference order (local first, relay last): the best
|
val results=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } }.awaitAll()
|
||||||
// answering address wins without waiting for slower, less preferred probes to time out.
|
results.firstOrNull { it.isSuccess }?.getOrNull()?.let { return@coroutineScope it }
|
||||||
val attempts=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } }
|
last=results.lastOrNull()?.exceptionOrNull() ?: last
|
||||||
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.")
|
||||||
}
|
}
|
||||||
suspend fun sections() = container("/library/sections").optJSONArray("Directory").objects().filter { it.optString("type") in listOf("movie","show") }.map { Section(it.optString("key"),it.optString("title"),it.optString("type")) }
|
suspend fun sections() = container("/library/sections").optJSONArray("Directory").objects().filter { it.optString("type") in listOf("movie","show") }.map { Section(it.optString("key"),it.optString("title"),it.optString("type")) }
|
||||||
/** A small response: no catalog, artwork, or metadata downloads on an unchanged library. */
|
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)) }.filter { it.items.isNotEmpty() && it.items.first().type in listOf("movie","show","episode","season","collection") }}
|
||||||
suspend fun libraryRevision():String = container("/library/sections").optJSONArray("Directory").objects()
|
|
||||||
.filter{it.optString("type") in listOf("movie","show")}.sortedBy{it.optString("key")}
|
|
||||||
.joinToString("|"){j->listOf("key","title","type","contentChangedAt","scannedAt","updatedAt").joinToString(":"){j.optString(it)}}
|
|
||||||
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. */
|
|
||||||
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.
|
container("/library/sections/$section/all",mapOf("type" to "3","sort" to "addedAt:desc","X-Plex-Container-Size" to "18")).optJSONArray("Metadata").objects().map{j->
|
||||||
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)
|
Title.parse(j).let{it.copy(title=listOf(it.parentTitle,it.title).filter{v->v.isNotBlank()}.joinToString(" · "))}
|
||||||
groupRecentSeasons(seasons,::details)
|
|
||||||
}
|
}
|
||||||
/** 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")
|
suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false): LibraryPage = withContext(Dispatchers.Default){
|
||||||
.optJSONArray("Metadata").objects().filterNot{it.optBoolean("selected")}
|
val p=mutableMapOf("X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to "100","sort" to sort)
|
||||||
.map{it.optString("key")}.filter{it.startsWith('/')||it.startsWith("https://")}.distinct()
|
if(genre.isNotBlank())p["genre"]=genre
|
||||||
|
if(unwatched)p["unwatched"]="1"
|
||||||
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)
|
|
||||||
p.putAll(libraryFilterParameters(genre,unwatched,type))
|
|
||||||
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 = 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> = 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 relatedMovies(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=="movie"&&it.id!=id}.distinctBy{it.id}}
|
fun previewPath(item:Title,time:Long):String? {
|
||||||
/** Actor tags are server-local. Query each accessible movie/show library, with pagination. */
|
val part=item.media.firstOrNull()?.parts?.firstOrNull()
|
||||||
suspend fun actorTitles(actor:CastMember,sections:List<Section>):List<Title> = coroutineScope {
|
if(part!=null&&part.indexes.split(',').contains("sd"))return "/library/parts/${part.id}/indexes/sd/${time.coerceAtLeast(0)/5000*5000}"
|
||||||
require(actor.id.isNotBlank()){"This cast member has no Plex library identifier."}
|
|
||||||
sections.filter{it.type in listOf("movie","show")}.map { section->async {
|
|
||||||
val found=mutableListOf<Title>();var start=0
|
|
||||||
do {
|
|
||||||
val data=container("/library/sections/${section.id}/all",mapOf("actor" to actor.id,"sort" to "titleSort:asc","X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to "100"))
|
|
||||||
val batch=withContext(Dispatchers.Default){data.optJSONArray("Metadata").objects().map(Title::parse)}
|
|
||||||
found.addAll(batch.filter{it.type in listOf("movie","show")});start+=batch.size
|
|
||||||
}while(batch.isNotEmpty()&&start<data.optInt("totalSize",start))
|
|
||||||
found
|
|
||||||
}}.awaitAll().flatten().distinctBy{it.id}.sortedBy{it.title.lowercase(java.util.Locale.ROOT)}
|
|
||||||
}
|
|
||||||
fun previewPath(item:Title,time:Long,mediaIndex:Int=0):String? {
|
|
||||||
val parts=item.media.getOrNull(mediaIndex)?.parts.orEmpty()
|
|
||||||
val partIndex=partFor(parts,time)
|
|
||||||
val part=parts.getOrNull(partIndex)
|
|
||||||
val local=time.coerceAtLeast(0)-partStart(parts,partIndex)
|
|
||||||
if(part!=null&&part.indexes.split(',').contains("sd"))return "/library/parts/${part.id}/indexes/sd/${local.coerceAtLeast(0)/5000*5000}"
|
|
||||||
return item.chapters.lastOrNull{it.start<=time}?.thumb?.takeIf{it.isNotBlank()}
|
return item.chapters.lastOrNull{it.start<=time}?.thumb?.takeIf{it.isNotBlank()}
|
||||||
}
|
}
|
||||||
suspend fun children(id: String): List<Title> = container("/library/metadata/$id/children").optJSONArray("Metadata").objects().map(Title::parse)
|
suspend fun children(id: String): List<Title> = container("/library/metadata/$id/children").optJSONArray("Metadata").objects().map(Title::parse)
|
||||||
suspend fun allEpisodes(id: String): List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/allLeaves").optJSONArray("Metadata").objects().map(Title::parse)}
|
suspend fun allEpisodes(id: String): List<Title> = container("/library/metadata/$id/allLeaves").optJSONArray("Metadata").objects().map(Title::parse)
|
||||||
suspend fun collections(section: String): List<Title> = container("/library/sections/$section/collections").optJSONArray("Metadata").objects().map(Title::parse)
|
suspend fun collections(section: String): List<Title> = container("/library/sections/$section/collections").optJSONArray("Metadata").objects().map(Title::parse)
|
||||||
suspend fun search(query: String): SearchResults = withContext(Dispatchers.Default) {
|
suspend fun search(query: String): List<Title> = container("/hubs/search",mapOf("query" to query,"limit" to "60","includeCollections" to "1")).optJSONArray("Hub").objects().flatMap { it.optJSONArray("Metadata").objects().map(Title::parse) }.filter { it.type in listOf("movie","show","episode","collection") }.distinctBy { it.id }
|
||||||
val hubs=container("/hubs/search",mapOf("query" to query,"limit" to "40","includeCollections" to "1")).optJSONArray("Hub").objects()
|
suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) }
|
||||||
val titles=hubs.flatMap{it.optJSONArray("Metadata").objects().map(Title::parse)}.filter{it.type in listOf("movie","show","season","episode","collection")}.distinctBy{it.id}
|
suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String) {
|
||||||
val people=hubs.filter{it.optString("type")=="actor"}.flatMap{it.optJSONArray("Directory").objects()}.map(CastMember::parse).filter{it.id.isNotBlank()&&it.name.isNotBlank()}.distinctBy{it.id}
|
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))
|
||||||
SearchResults(titles,people)
|
|
||||||
}
|
|
||||||
/** 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 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) }
|
|
||||||
/** Reports progress; a stream the server stopped (Plex dashboard "Stop", or shutdown) comes back as a termination. */
|
|
||||||
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")
|
||||||
}
|
}
|
||||||
fun image(path: String, width: Int = 600, height: Int = 900): String? = if(path.isBlank() || session==null) null else url("/photo/:/transcode",mapOf("url" to path,"width" to width.toString(),"height" to height.toString(),"minSize" to "1","upscale" to "0"))
|
fun image(path: String, width: Int = 600, height: Int = 900): String? = if(path.isBlank() || session==null) null else url("/photo/:/transcode",mapOf("url" to path,"width" to width.toString(),"height" to height.toString(),"minSize" to "1","upscale" to "0"))
|
||||||
fun transcodeParams(item: Title, sessionId: String, mode: Int, offset: Long, quality: StreamQuality, mediaIndex:Int=0, partIndex:Int=0, local:Boolean=true, subtitleSize:Int=100): Map<String,String> = buildMap {
|
fun transcodeParams(item: Title, sessionId: String, mode: Int, offset: Long, quality: Int): Map<String,String> = buildMap {
|
||||||
put("path",item.key);put("mediaIndex",mediaIndex.toString());put("partIndex",partIndex.toString());put("protocol","hls");put("session",sessionId);put("offset",(offset/1000.0).toString())
|
put("path",item.key);put("mediaIndex","0");put("partIndex","0");put("protocol","hls");put("session",sessionId);put("offset",(offset/1000.0).toString())
|
||||||
put("directPlay","0");put("directStream",if(mode==1) "1" else "0");put("directStreamAudio","1");put("directStreamVideo",if(mode==1) "1" else "0")
|
put("directPlay","0");put("directStream",if(mode==1) "1" else "0");put("directStreamAudio","1");put("directStreamVideo",if(mode==1) "1" else "0")
|
||||||
val original=item.media.getOrNull(mediaIndex) ?: item.media.firstOrNull()
|
val original=item.media.firstOrNull()
|
||||||
put("maxVideoBitrate",if(mode==1)maxOf(original?.bitrate ?: 0,100000).toString()else quality.kbps.toString())
|
put("maxVideoBitrate",if(mode==1)maxOf(original?.bitrate ?: 0,100000).toString()else quality.toString())
|
||||||
put("videoResolution",if(mode==1&&original!=null&&original.width>0)"${original.width}x${original.height}"else "${quality.width}x${quality.height}")
|
put("videoResolution",if(mode==1&&original!=null&&original.width>0)"${original.width}x${original.height}"else if(quality>20000)"3840x2160"else "1920x1080")
|
||||||
put("videoQuality","100");put("audioBoost","100");put("subtitleSize",subtitleSize.toString());put("location",if(local)"lan"else "wan");put("hasMDE","1");put("fastSeek","1")
|
put("videoQuality","100");put("audioBoost","100");put("subtitleSize","100");put("location","lan");put("hasMDE","1");put("fastSeek","1")
|
||||||
put("X-Plex-Client-Identifier",clientId);put("X-Plex-Product","Kaleido");put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV")
|
put("X-Plex-Client-Identifier",clientId);put("X-Plex-Product","Kaleido");put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV")
|
||||||
// Augment the existing target. Separate targets make Plex prefer H.264 conversion even for HEVC it could copy.
|
// Augment the existing target. Separate targets make Plex prefer H.264 conversion even for HEVC it could copy.
|
||||||
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, server: Session? = session) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId),server) }
|
suspend fun stopTranscode(sessionId: String) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId)) }
|
||||||
}
|
|
||||||
|
|
||||||
/** Index of the part containing [time] on the title's combined timeline. */
|
|
||||||
internal fun partFor(parts:List<Part>,time:Long):Int {
|
|
||||||
var start=0L
|
|
||||||
for((i,p) in parts.withIndex()){if(p.duration<=0||time<start+p.duration||i==parts.lastIndex)return i;start+=p.duration}
|
|
||||||
return 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"
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.async
|
|
||||||
import kotlinx.coroutines.awaitAll
|
|
||||||
import kotlinx.coroutines.coroutineScope
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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 {
|
|
||||||
seasons.distinctBy{it.id}.groupBy{it.parentId.ifBlank{"season:${it.id}"}}.values.take(18).map { group->async {
|
|
||||||
val season=group.first()
|
|
||||||
val single=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()
|
|
||||||
}
|
|
||||||
|
|
@ -4,7 +4,6 @@ package tv.kaleido.app
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.animation.Crossfade
|
import androidx.compose.animation.Crossfade
|
||||||
import androidx.compose.animation.core.Animatable
|
import androidx.compose.animation.core.Animatable
|
||||||
import androidx.compose.animation.core.LinearEasing
|
|
||||||
import androidx.compose.animation.core.tween
|
import androidx.compose.animation.core.tween
|
||||||
import androidx.compose.animation.core.animateFloatAsState
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
import androidx.compose.foundation.*
|
import androidx.compose.foundation.*
|
||||||
|
|
@ -23,11 +22,8 @@ import androidx.compose.ui.draw.clip
|
||||||
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.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
|
||||||
|
|
@ -36,64 +32,25 @@ 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 androidx.compose.foundation.gestures.BringIntoViewSpec
|
|
||||||
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
|
|
||||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.withTimeoutOrNull
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import androidx.compose.ui.platform.LocalDensity
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||||
import androidx.compose.ui.input.key.KeyInputModifierNode
|
|
||||||
import androidx.compose.ui.node.ModifierNodeElement
|
|
||||||
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,colorFilter:androidx.compose.ui.graphics.ColorFilter?=null) {
|
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true) {
|
||||||
val context=LocalContext.current
|
val context=LocalContext.current
|
||||||
// The server already scales to width × height. Stating that size lets Coil resolve cache
|
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)}}.crossfade(if(animate)180 else 0).build()}}
|
||||||
// hits while composing, instead of each painter waiting for layout to measure it.
|
AsyncImage(model=model,contentDescription=null,contentScale=ContentScale.Crop,modifier=modifier.background(Panel))
|
||||||
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,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=isDiscovery(vm)
|
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
|
||||||
val discoveries=remember{LinkedHashSet<String>()}
|
val screenKey=vm.page.kind+":"+vm.page.id+if(vm.page.kind in listOf("movies","tv")) ":${vm.allTitles}"else ""
|
||||||
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)}
|
||||||
|
|
@ -102,83 +59,49 @@ import java.io.File
|
||||||
val order=listOf("home","movies","tv","search","settings")
|
val order=listOf("home","movies","tv","search","settings")
|
||||||
direction=if(order.indexOf(vm.page.kind)<order.indexOf(previousDestination))-1f else 1f
|
direction=if(order.indexOf(vm.page.kind)<order.indexOf(previousDestination))-1f else 1f
|
||||||
previousDestination=vm.page.kind
|
previousDestination=vm.page.kind
|
||||||
entrance.snapTo(0f)
|
entrance.snapTo(0f);entrance.animateTo(1f,tween(280))
|
||||||
// A new section composes its rows in one or two long frames. Start the slide after
|
|
||||||
// them (bounded) so it doesn't open with a jump.
|
|
||||||
withTimeoutOrNull(300){awaitSteadyFrames(2)}
|
|
||||||
entrance.animateTo(1f,tween(280))
|
|
||||||
}
|
}
|
||||||
// A restored Activity after process eviction still needs the cold-start cover.
|
// A restored Activity after process eviction still needs the cold-start cover.
|
||||||
var startup by remember{mutableStateOf(true)}
|
var startup by remember{mutableStateOf(true)}
|
||||||
var brandReady by remember{mutableStateOf(false)}
|
var brandReady by remember{mutableStateOf(false)}
|
||||||
val splashExit=remember{Animatable(0f)}
|
val splash=remember{Animatable(1f)}
|
||||||
LaunchedEffect(brandReady){
|
LaunchedEffect(brandReady){
|
||||||
if(startup&&brandReady){
|
if(startup&&brandReady){
|
||||||
withTimeoutOrNull(600){snapshotFlow{!vm.busy}.first{it}}
|
withTimeoutOrNull(600){snapshotFlow{!vm.busy}.first{it}}
|
||||||
splashExit.animateTo(1f,tween(StartupExitMillis,easing=LinearEasing));startup=false
|
splash.animateTo(0f,tween(360));startup=false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// The server picker covers every page, so Back closes it before navigating underneath.
|
BackHandler(enabled=vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){
|
||||||
BackHandler(enabled=vm.servers.isNotEmpty()||vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){
|
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()
|
||||||
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{vm.lastInteraction=android.os.SystemClock.uptimeMillis();startup}) {
|
Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{startup}) {
|
||||||
// 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)) {
|
|
||||||
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 {
|
||||||
// Per-draw alpha: an offscreen full-screen layer per frame is costly on weak GPUs.
|
|
||||||
Column(Modifier.fillMaxSize().graphicsLayer{
|
Column(Modifier.fillMaxSize().graphicsLayer{
|
||||||
compositingStrategy=CompositingStrategy.ModulateAlpha
|
|
||||||
alpha=.18f+.82f*entrance.value
|
alpha=.18f+.82f*entrance.value
|
||||||
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")) TopBar(vm)
|
||||||
// Home, Movies and TV stay composed once shown; only the one on screen is measured,
|
stateHolder.SaveableStateProvider(screenKey) {
|
||||||
// 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)
|
|
||||||
"hub"->HubScreen(vm)
|
|
||||||
"search"->SearchScreen(vm)
|
"search"->SearchScreen(vm)
|
||||||
"settings"->CohesiveSettingsScreen(vm,install)
|
"settings"->SettingsScreen(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)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
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.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(splash.value){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)}
|
||||||
|
|
@ -198,89 +121,34 @@ 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)})};if(vm.session!=null){Spacer(Modifier.height(6.dp));TvButton("Cancel",onClick={vm.dismissServerPicker()})}}
|
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)})}}
|
||||||
}
|
}
|
||||||
|
@Composable fun SettingsScreen(vm: KaleidoViewModel,install: (File)->Unit) {
|
||||||
|
var confirmSignOut by remember{mutableStateOf(false)};var modeDialog by remember{mutableStateOf(false)};var qualityDialog by remember{mutableStateOf(false)};var watchedDialog by remember{mutableStateOf(false)}
|
||||||
|
LaunchedEffect(vm.downloadedApk){vm.downloadedApk?.let(install)}
|
||||||
|
LazyColumn(contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=17.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) {
|
||||||
|
item {Text("Settings",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)}
|
||||||
|
item{SettingsPanel("Plex connection") {Text(vm.session?.serverName.orEmpty(),color=Color.White,fontSize=20.sp,fontWeight=FontWeight.Bold);Text(if(vm.accountToken.isBlank())"Server connection · Link your Plex account to discover your servers"else "Plex account linked · Session encrypted with Android Keystore",color=Muted,fontSize=12.sp);Spacer(Modifier.height(14.dp));Row(horizontalArrangement=Arrangement.spacedBy(10.dp)){TvButton("Sign in with Plex",initialFocus=true,onClick={vm.beginAccountLink()});if(vm.accountToken.isNotBlank())TvButton("Choose server",onClick={vm.switchServer()});TvButton("Sign out",onClick={confirmSignOut=true})}}}
|
||||||
|
item{SettingsPanel("Playback") {Row(horizontalArrangement=Arrangement.spacedBy(12.dp)){TvButton("Mode: "+listOf("Original","Direct stream","Transcode")[vm.playbackMode],onClick={modeDialog=true});TvButton("Transcode quality: "+if(vm.quality>20000)"4K · 80 Mbps"else "1080p · 20 Mbps",onClick={qualityDialog=true})};Text("Direct stream is the default. Playback mode, audio, subtitles, speed, and quality can also be changed in the player.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(top=12.dp))}}
|
||||||
|
item{SettingsPanel("Watched status") {
|
||||||
|
TvButton("Mark watched at ${vm.watchedPercent}%",onClick={watchedDialog=true})
|
||||||
|
Text("A resumed title gets its checkmark at this playback percentage. Completed titles keep their Plex watched status.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
|
||||||
|
}}
|
||||||
|
item{SettingsPanel("Interface") {
|
||||||
|
TvButton("Navigation sounds: "+if(vm.navigationSounds)"On"else "Off",onClick={vm.chooseNavigationSounds(!vm.navigationSounds)})
|
||||||
|
Text("Play the TV's system tap when focus moves. Follows your TV's sound-effects setting.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
|
||||||
|
}}
|
||||||
|
item{SettingsPanel("Software updates") {Text("Kaleido ${BuildConfig.VERSION_NAME}",color=Color.White,fontSize=20.sp,fontWeight=FontWeight.Bold);Text(vm.updateStatus,color=Muted,fontSize=12.sp,modifier=Modifier.padding(vertical=8.dp));Text("Updates are checked automatically every six hours while Kaleido is in use.",color=Muted,fontSize=12.sp);Spacer(Modifier.height(14.dp));Row(horizontalArrangement=Arrangement.spacedBy(10.dp)){TvButton("Check for updates",onClick={vm.checkUpdate()});if(vm.update!=null&&!vm.downloading)TvButton("Download & install ${vm.update!!.version}",primary=true,onClick={vm.downloadUpdate()})};vm.update?.let{if(it.notes.isNotBlank())Text(it.notes.take(1800),color=Muted,fontSize=11.sp,modifier=Modifier.padding(top=12.dp))};Text("git.elijahkuntz.com/Elijah/Kaleido",color=Accent,fontSize=10.sp,modifier=Modifier.padding(top=14.dp))}}
|
||||||
|
}
|
||||||
|
if(confirmSignOut)ChoiceDialog("Sign out of Plex?",listOf("Keep watching","Sign out"),0,{confirmSignOut=false}){if(it==1)vm.signOut();confirmSignOut=false}
|
||||||
|
if(watchedDialog) {
|
||||||
|
val thresholds=listOf(50,60,70,75,80,85,90,95,100)
|
||||||
|
ChoiceDialog("Mark watched after",thresholds.map{"$it%"},thresholds.indexOf(vm.watchedPercent),{watchedDialog=false}){vm.chooseWatchedPercent(thresholds[it]);watchedDialog=false}
|
||||||
|
}
|
||||||
|
if(modeDialog)ChoiceDialog("Playback mode",listOf("Automatic · Original quality","Direct stream · Remux when possible","Transcode · Compatibility mode"),vm.playbackMode,{modeDialog=false}){vm.choosePlaybackMode(it);modeDialog=false}
|
||||||
|
if(qualityDialog)ChoiceDialog("Transcode quality",listOf("1080p · 20 Mbps","4K · 80 Mbps"),if(vm.quality>20000)1 else 0,{qualityDialog=false}){vm.chooseQuality(if(it==0)20000 else 80000);qualityDialog=false}
|
||||||
|
}
|
||||||
|
@Composable fun SettingsPanel(title: String,content: @Composable ColumnScope.()->Unit) {Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(9.dp)).background(Panel.copy(alpha=.65f)).padding(18.dp)){Eyebrow(title);Spacer(Modifier.height(11.dp));content()}}
|
||||||
@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={dismiss();retry()});TvButton("Dismiss",onClick=dismiss)}}}}
|
||||||
/** [heldSelect]: opened by a held OK, so its repeats and release must not choose the first option. */
|
@Composable fun ChoiceDialog(title: String,options: List<String>,selected: Int,dismiss: ()->Unit,choose: (Int)->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(360.dp).heightIn(max=390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(21.dp)){Text(title,color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=14.dp));LazyColumn(verticalArrangement=Arrangement.spacedBy(4.dp)){items(options.size){i->TvButton(options[i],Modifier.fillMaxWidth(),selected=i==selected,initialFocus=i==selected||selected<0&&i==0,onClick={choose(i)})}}}}}
|
||||||
@Composable fun ChoiceDialog(title: String,options: List<String>,selected: Int,dismiss: ()->Unit,heldSelect:Boolean=false,choose: (Int)->Unit) {
|
|
||||||
// Open scrolled to the selection: an uncomposed lazy row cannot take the initial focus.
|
|
||||||
val list=rememberLazyListState(initialFirstVisibleItemIndex=(selected-2).coerceAtLeast(0))
|
|
||||||
val armed=remember{booleanArrayOf(!heldSelect)}
|
|
||||||
Dialog(onDismissRequest=dismiss){Column(Modifier.onPreviewKeyEvent{event->
|
|
||||||
val native=event.nativeKeyEvent
|
|
||||||
val select=native.keyCode in listOf(android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER,android.view.KeyEvent.KEYCODE_NUMPAD_ENTER)
|
|
||||||
if(armed[0]||!select)false else if(native.action==android.view.KeyEvent.ACTION_DOWN&&native.repeatCount==0){armed[0]=true;false}else true
|
|
||||||
}.width(360.dp).heightIn(max=390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(21.dp)){Text(title,color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=14.dp));LazyColumn(state=list,verticalArrangement=Arrangement.spacedBy(4.dp)){items(options.size){i->TvButton(options[i],Modifier.fillMaxWidth(),selected=i==selected,initialFocus=i==selected||selected<0&&i==0,onClick={choose(i)})}}}}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Long-press OK or Menu on a title: the actions the official app keeps behind its context menu. */
|
|
||||||
@Composable fun TitleActions(vm:KaleidoViewModel,item:Title) {
|
|
||||||
val watched=item.isWatched(vm.watchedPercent)
|
|
||||||
val actions=buildList<Pair<String,()->Unit>> {
|
|
||||||
if(item.type=="clip")add("Play" to {vm.play(item)})
|
|
||||||
else if(item.type!="collection") {
|
|
||||||
add((if(item.offset>0)"Resume from ${clockTime(item.offset)}" else if(item.type in listOf("show","season"))"Watch next" else "Play") to {vm.play(item)})
|
|
||||||
if(item.offset>0)add("Play from the beginning" to {vm.play(item,true)})
|
|
||||||
}
|
|
||||||
if(item.type!="clip")add("More information" to {vm.open(item)})
|
|
||||||
if(item.type in listOf("movie","show","season","episode"))add((if(watched)"Mark unwatched" else "Mark watched") to {vm.mark(item)})
|
|
||||||
if(vm.contextFromContinue&&item.type in listOf("movie","episode"))add("Remove from Continue Watching" to {vm.removeFromContinueWatching(item)})
|
|
||||||
if(item.type=="episode"&&item.parentId.isNotBlank())add("Go to season ${item.parentIndex}" to {vm.openSeason(item)})
|
|
||||||
if(item.type=="episode"&&item.grandparentId.isNotBlank()||item.type=="season"&&item.parentId.isNotBlank())add("Go to show" to {vm.openShow(item)})
|
|
||||||
}
|
|
||||||
ChoiceDialog(item.displayTitle,actions.map{it.first},-1,vm::dismissActions,heldSelect=true){index->vm.dismissActions();actions[index].second()}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens [onLongPress] when OK is held or the remote's Menu key is pressed, without also
|
|
||||||
* triggering the click that a held OK would send on release.
|
|
||||||
*/
|
|
||||||
fun Modifier.titleActions(onLongPress:()->Unit):Modifier = this then TitleActionsElement(onLongPress)
|
|
||||||
|
|
||||||
// A node, not composed{}: every browse card carries this, and a sub-composition per card is costly.
|
|
||||||
private class TitleActionsElement(val onLongPress:()->Unit):ModifierNodeElement<TitleActionsNode>() {
|
|
||||||
override fun create()=TitleActionsNode(onLongPress)
|
|
||||||
override fun update(node:TitleActionsNode){node.onLongPress=onLongPress}
|
|
||||||
override fun equals(other:Any?)=other is TitleActionsElement&&other.onLongPress===onLongPress
|
|
||||||
override fun hashCode()=System.identityHashCode(onLongPress)
|
|
||||||
}
|
|
||||||
private class TitleActionsNode(var onLongPress:()->Unit):Modifier.Node(),KeyInputModifierNode {
|
|
||||||
private var held=false
|
|
||||||
override fun onPreKeyEvent(event:androidx.compose.ui.input.key.KeyEvent):Boolean {
|
|
||||||
val native=event.nativeKeyEvent
|
|
||||||
val select=native.keyCode==android.view.KeyEvent.KEYCODE_DPAD_CENTER||native.keyCode==android.view.KeyEvent.KEYCODE_ENTER||native.keyCode==android.view.KeyEvent.KEYCODE_NUMPAD_ENTER
|
|
||||||
return when {
|
|
||||||
native.keyCode==android.view.KeyEvent.KEYCODE_MENU->{if(native.action==android.view.KeyEvent.ACTION_UP)onLongPress();true}
|
|
||||||
!select->false
|
|
||||||
native.action==android.view.KeyEvent.ACTION_DOWN&&native.repeatCount==0->{held=false;false}
|
|
||||||
native.action==android.view.KeyEvent.ACTION_DOWN->{if(!held){held=true;onLongPress()};true}
|
|
||||||
native.action==android.view.KeyEvent.ACTION_UP&&held->{held=false;true}
|
|
||||||
else->false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
override fun onKeyEvent(event:androidx.compose.ui.input.key.KeyEvent)=false
|
|
||||||
}
|
|
||||||
|
|
||||||
/** "View all" for a row: every title the Plex hub holds. */
|
|
||||||
@Composable fun HubScreen(vm:KaleidoViewModel) {
|
|
||||||
Column(Modifier.fillMaxSize().background(Ink).padding(top=20.dp)) {
|
|
||||||
Row(Modifier.fillMaxWidth().padding(start=34.dp,end=Cinema.gutter,bottom=20.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(18.dp)) {
|
|
||||||
IconControl(androidx.compose.material.icons.Icons.AutoMirrored.Outlined.ArrowBack,"Back"){vm.back()}
|
|
||||||
Column {
|
|
||||||
Eyebrow("View all")
|
|
||||||
Text(vm.page.name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(vertical=3.dp))
|
|
||||||
Text(if(vm.busy)"Loading…"else "${vm.hubTitles.size} titles",color=Muted,fontSize=11.sp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(vm.hubTitles.isEmpty()&&!vm.busy)Text("Nothing to show here right now.",color=Muted,fontSize=14.sp,modifier=Modifier.padding(horizontal=Cinema.gutter))
|
|
||||||
// Episode rows read best as landscape stills; everything else as posters.
|
|
||||||
val landscape=vm.hubTitles.firstOrNull()?.type in listOf("episode","clip")
|
|
||||||
val columns=if(landscape)4 else 6
|
|
||||||
LazyVerticalGrid(GridCells.Fixed(columns),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,bottom=28.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp)) {
|
|
||||||
itemsIndexed(vm.hubTitles,key={_,item->item.id}){index,item->
|
|
||||||
MediaTile(vm,item,"hub:${item.id}",landscape=landscape,fillWidth=true,initialFocus=index==0&&!vm.focusId.startsWith("hub:"),onMove={anticipateTileMove(vm,vm.hubTitles,index,it,columns)})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,82 +0,0 @@
|
||||||
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()
|
|
||||||
|
|
@ -1,643 +0,0 @@
|
||||||
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
|
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import androidx.compose.animation.animateColorAsState
|
|
||||||
import androidx.compose.animation.core.animateFloatAsState
|
|
||||||
import androidx.compose.animation.core.tween
|
|
||||||
import androidx.compose.foundation.ScrollState
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.focusGroup
|
|
||||||
import androidx.compose.foundation.gestures.BringIntoViewSpec
|
|
||||||
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
|
|
||||||
import androidx.compose.foundation.layout.*
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.runtime.*
|
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.focus.FocusRequester
|
|
||||||
import androidx.compose.ui.focus.focusProperties
|
|
||||||
import androidx.compose.ui.focus.focusRequester
|
|
||||||
import androidx.compose.ui.focus.focusRestorer
|
|
||||||
import androidx.compose.ui.focus.onFocusChanged
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.graphicsLayer
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
/** Compact TV settings with a stable category rail and explicit left/right focus routing. */
|
|
||||||
@Composable
|
|
||||||
fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
|
|
||||||
val categories = remember { listOf("Connection", "Playback", "Subtitles", "Interface", "Updates") }
|
|
||||||
var selectedCategory by rememberSaveable { mutableIntStateOf(0) }
|
|
||||||
var confirmSignOut by remember { mutableStateOf(false) }
|
|
||||||
var qualityDialog by remember { mutableStateOf(false) }
|
|
||||||
var watchedDialog by remember { mutableStateOf(false) }
|
|
||||||
var remoteDialog 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 subtitleStyleDialog by remember { mutableStateOf(false) }
|
|
||||||
var themeVolumeDialog by remember { mutableStateOf(false) }
|
|
||||||
val remoteFocus = remember { FocusRequester() }
|
|
||||||
val autoplayFocus = remember { FocusRequester() }
|
|
||||||
val introFocus = remember { FocusRequester() }
|
|
||||||
val creditsFocus = 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 entryFocus = remember { List(categories.size) { FocusRequester() } }
|
|
||||||
val watchedFocus = remember { FocusRequester() }
|
|
||||||
val serverActionFocus = remember { FocusRequester() }
|
|
||||||
val signOutActionFocus = remember { FocusRequester() }
|
|
||||||
val updateFocus = remember { FocusRequester() }
|
|
||||||
val updateDownloadFocus = remember { FocusRequester() }
|
|
||||||
var dialogRestoreFocus by remember { mutableStateOf<FocusRequester?>(null) }
|
|
||||||
var settingsFocused by remember { mutableStateOf(false) }
|
|
||||||
val paused = remember { booleanArrayOf(false) }
|
|
||||||
|
|
||||||
LaunchedEffect(vm.downloadedApk) { vm.downloadedApk?.let(install) }
|
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
delay(140)
|
|
||||||
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) {
|
|
||||||
if (paused[0]) {
|
|
||||||
vm.installerReturned()
|
|
||||||
if (!settingsFocused) runCatching { updateFocus.requestFocus() }
|
|
||||||
}
|
|
||||||
onPauseOrDispose { paused[0] = true }
|
|
||||||
}
|
|
||||||
|
|
||||||
Column(
|
|
||||||
Modifier.fillMaxSize()
|
|
||||||
.background(Ink)
|
|
||||||
.onFocusChanged { settingsFocused = it.hasFocus }
|
|
||||||
.padding(horizontal = Cinema.gutter, vertical = 22.dp)
|
|
||||||
) {
|
|
||||||
Row(verticalAlignment = Alignment.Bottom) {
|
|
||||||
Column(Modifier.weight(1f)) {
|
|
||||||
Text(
|
|
||||||
"Settings",
|
|
||||||
color = Accent,
|
|
||||||
fontSize = 29.sp,
|
|
||||||
lineHeight = 34.sp,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
letterSpacing = (-.8).sp
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
"Playback, preferences and software updates",
|
|
||||||
color = Muted,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
lineHeight = 15.sp,
|
|
||||||
modifier = Modifier.padding(top = 3.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Spacer(Modifier.height(25.dp))
|
|
||||||
|
|
||||||
Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(28.dp)) {
|
|
||||||
Column(
|
|
||||||
Modifier.width(205.dp).fillMaxHeight().focusGroup(),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(5.dp)
|
|
||||||
) {
|
|
||||||
Eyebrow("Categories")
|
|
||||||
Spacer(Modifier.height(7.dp))
|
|
||||||
categories.forEachIndexed { index, category ->
|
|
||||||
SettingsCategoryItem(
|
|
||||||
label = category,
|
|
||||||
selected = selectedCategory == index,
|
|
||||||
requester = categoryFocus[index],
|
|
||||||
upTarget = categoryFocus[(index - 1).coerceAtLeast(0)],
|
|
||||||
downTarget = categoryFocus[(index + 1).coerceAtMost(categories.lastIndex)],
|
|
||||||
rightTarget = entryFocus[index],
|
|
||||||
onFocused = { selectedCategory = index },
|
|
||||||
onClick = { selectedCategory = index }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Box(Modifier.width(1.dp).fillMaxHeight().background(Color.White.copy(alpha = .10f)))
|
|
||||||
|
|
||||||
CompositionLocalProvider(LocalBringIntoViewSpec provides SettingsScroll) {
|
|
||||||
Column(
|
|
||||||
Modifier.weight(1f).fillMaxHeight()
|
|
||||||
.verticalScroll(remember(selectedCategory) { ScrollState(0) })
|
|
||||||
.focusGroup(),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(20.dp)
|
|
||||||
) {
|
|
||||||
when (selectedCategory) {
|
|
||||||
0 -> {
|
|
||||||
SettingsSectionDescription("Manage the server and account used by Kaleido.")
|
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
|
||||||
Text(
|
|
||||||
vm.session?.serverName.orEmpty().ifBlank { "Plex connection" },
|
|
||||||
color = Accent,
|
|
||||||
fontSize = 19.sp,
|
|
||||||
lineHeight = 24.sp,
|
|
||||||
fontWeight = FontWeight.SemiBold
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
if (vm.accountToken.isBlank()) {
|
|
||||||
"Server connection · Link your Plex account to discover your servers"
|
|
||||||
} else {
|
|
||||||
"Plex account linked · Session encrypted with Android Keystore"
|
|
||||||
},
|
|
||||||
color = Muted,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
lineHeight = 16.sp
|
|
||||||
)
|
|
||||||
vm.session?.server?.let { address ->
|
|
||||||
Text(
|
|
||||||
(if (vm.localConnection) "Local connection" else "Remote connection") + " · " +
|
|
||||||
address.removePrefix("https://").removePrefix("http://").substringBefore('/'),
|
|
||||||
color = Muted,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
lineHeight = 16.sp,
|
|
||||||
maxLines = 1,
|
|
||||||
overflow = TextOverflow.Ellipsis
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(9.dp)) {
|
|
||||||
SettingsActionButton(
|
|
||||||
if (vm.accountToken.isBlank()) "Sign in with Plex" else "Switch account",
|
|
||||||
requester = entryFocus[0],
|
|
||||||
leftTarget = categoryFocus[0],
|
|
||||||
rightTarget = if (vm.accountToken.isNotBlank()) serverActionFocus else signOutActionFocus,
|
|
||||||
onClick = { vm.beginAccountLink() }
|
|
||||||
)
|
|
||||||
if (vm.accountToken.isNotBlank()) {
|
|
||||||
SettingsActionButton(
|
|
||||||
"Choose server",
|
|
||||||
requester = serverActionFocus,
|
|
||||||
leftTarget = categoryFocus[0],
|
|
||||||
rightTarget = signOutActionFocus,
|
|
||||||
onClick = { vm.switchServer() }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
SettingsActionButton(
|
|
||||||
"Sign out",
|
|
||||||
requester = signOutActionFocus,
|
|
||||||
leftTarget = categoryFocus[0],
|
|
||||||
onClick = { dialogRestoreFocus = signOutActionFocus; confirmSignOut = true }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
1 -> {
|
|
||||||
SettingsSectionDescription("Choose how Plex delivers video and when a title counts as watched.")
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Playback quality",
|
|
||||||
description = "On your home network. Original plays the source; a resolution asks Plex to convert.",
|
|
||||||
value = vm.streamQuality.label,
|
|
||||||
requester = entryFocus[1],
|
|
||||||
leftTarget = categoryFocus[1],
|
|
||||||
onClick = { dialogRestoreFocus = entryFocus[1]; qualityDialog = true }
|
|
||||||
)
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Remote quality",
|
|
||||||
description = "Away from home or through Plex Relay, where bandwidth is limited.",
|
|
||||||
value = vm.remoteQuality.label,
|
|
||||||
requester = remoteFocus,
|
|
||||||
leftTarget = categoryFocus[1],
|
|
||||||
onClick = { dialogRestoreFocus = remoteFocus; remoteDialog = true }
|
|
||||||
)
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Watched status",
|
|
||||||
description = "A resumed title receives its checkmark at this playback percentage.",
|
|
||||||
value = "${vm.watchedPercent}%",
|
|
||||||
requester = watchedFocus,
|
|
||||||
leftTarget = categoryFocus[1],
|
|
||||||
onClick = { dialogRestoreFocus = watchedFocus; watchedDialog = true }
|
|
||||||
)
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Autoplay next episode",
|
|
||||||
description = "Up Next counts down to the next episode. Any remote press stops it.",
|
|
||||||
value = autoplayLabel(vm.autoplaySeconds),
|
|
||||||
requester = autoplayFocus,
|
|
||||||
leftTarget = categoryFocus[1],
|
|
||||||
onClick = { dialogRestoreFocus = autoplayFocus; autoplayDialog = true }
|
|
||||||
)
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Skip intros",
|
|
||||||
description = "Uses intro markers from your Plex server. Any remote press cancels an automatic skip.",
|
|
||||||
value = autoSkipLabel(vm.autoSkipIntroSeconds),
|
|
||||||
requester = introFocus,
|
|
||||||
leftTarget = categoryFocus[1],
|
|
||||||
onClick = { dialogRestoreFocus = introFocus; introDialog = true }
|
|
||||||
)
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Skip credits",
|
|
||||||
description = "Automatic: episodes open Up Next as the credits start; movies skip past them after the delay.",
|
|
||||||
value = autoSkipLabel(vm.autoSkipCreditsSeconds),
|
|
||||||
requester = creditsFocus,
|
|
||||||
leftTarget = categoryFocus[1],
|
|
||||||
onClick = { dialogRestoreFocus = creditsFocus; creditsDialog = true }
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
"Completed titles keep their Plex watched status.",
|
|
||||||
color = Cinema.quiet,
|
|
||||||
fontSize = 10.sp,
|
|
||||||
lineHeight = 14.sp,
|
|
||||||
modifier = Modifier.padding(start = 1.dp, top = 1.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
2 -> {
|
|
||||||
SettingsSectionDescription("Choose how text subtitles look. Image subtitles keep their own style.")
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Size",
|
|
||||||
description = "Also sizes subtitles Plex adds to converted video.",
|
|
||||||
value = vm.subtitleSize.label,
|
|
||||||
requester = entryFocus[2],
|
|
||||||
leftTarget = categoryFocus[2],
|
|
||||||
onClick = { dialogRestoreFocus = entryFocus[2]; subtitleSizeDialog = true }
|
|
||||||
)
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Style",
|
|
||||||
description = "Text colour, outline and background.",
|
|
||||||
value = vm.subtitleStyle.label,
|
|
||||||
requester = subtitleStyleFocus,
|
|
||||||
leftTarget = categoryFocus[2],
|
|
||||||
onClick = { dialogRestoreFocus = subtitleStyleFocus; subtitleStyleDialog = true }
|
|
||||||
)
|
|
||||||
SubtitlePreview(vm.subtitleSize, vm.subtitleStyle)
|
|
||||||
}
|
|
||||||
|
|
||||||
3 -> {
|
|
||||||
SettingsSectionDescription("Choose how Kaleido looks and sounds while you browse.")
|
|
||||||
SettingsValueRow(
|
|
||||||
title = "Navigation sounds",
|
|
||||||
description = "Play the TV's system tap when focus moves. Follows the TV sound-effects setting.",
|
|
||||||
value = if (vm.navigationSounds) "On" else "Off",
|
|
||||||
requester = entryFocus[3],
|
|
||||||
leftTarget = categoryFocus[3],
|
|
||||||
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 -> {
|
|
||||||
SettingsSectionDescription("Install the latest updates published for Kaleido.")
|
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
|
||||||
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("Updates are checked automatically every six hours while Kaleido is in use.", color = Muted, fontSize = 10.sp, lineHeight = 15.sp)
|
|
||||||
}
|
|
||||||
vm.update?.let { release ->
|
|
||||||
if (release.notes.isNotBlank()) {
|
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
|
||||||
Eyebrow("What's new in ${release.version}")
|
|
||||||
Text(
|
|
||||||
release.notes.take(1800),
|
|
||||||
color = Cinema.secondary,
|
|
||||||
fontSize = 10.sp,
|
|
||||||
lineHeight = 15.sp
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Row(
|
|
||||||
Modifier.focusRequester(updateFocus).focusRestorer(),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(9.dp)
|
|
||||||
) {
|
|
||||||
SettingsActionButton(
|
|
||||||
"Check for updates",
|
|
||||||
requester = entryFocus[4],
|
|
||||||
leftTarget = categoryFocus[4],
|
|
||||||
rightTarget = if (vm.update != null) updateDownloadFocus else null,
|
|
||||||
onClick = { vm.checkUpdate() }
|
|
||||||
)
|
|
||||||
vm.update?.let { release ->
|
|
||||||
val label = when {
|
|
||||||
vm.downloading -> "Downloading… ${(vm.downloadProgress * 100).toInt()}%"
|
|
||||||
vm.readyApk != null -> "Install ${release.version}"
|
|
||||||
else -> "Download & install ${release.version}"
|
|
||||||
}
|
|
||||||
SettingsActionButton(
|
|
||||||
label,
|
|
||||||
requester = updateDownloadFocus,
|
|
||||||
leftTarget = categoryFocus[4],
|
|
||||||
primary = true,
|
|
||||||
onClick = { vm.downloadUpdate() }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (vm.downloading) {
|
|
||||||
androidx.compose.material3.LinearProgressIndicator(
|
|
||||||
progress = { vm.downloadProgress },
|
|
||||||
modifier = Modifier.width(340.dp).height(3.dp),
|
|
||||||
color = Accent,
|
|
||||||
trackColor = Color.White.copy(alpha = .14f),
|
|
||||||
gapSize = 0.dp,
|
|
||||||
drawStopIndicator = {}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Text("git.elijahkuntz.com/Elijah/Kaleido", color = Accent, fontSize = 10.sp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (confirmSignOut) {
|
|
||||||
ChoiceDialog("Sign out of Plex?", listOf("Keep watching", "Sign out"), 0, { confirmSignOut = false }) {
|
|
||||||
if (it == 1) vm.signOut()
|
|
||||||
confirmSignOut = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (watchedDialog) {
|
|
||||||
val thresholds = listOf(50, 60, 70, 75, 80, 85, 90, 95, 100)
|
|
||||||
ChoiceDialog("Mark watched after", thresholds.map { "$it%" }, thresholds.indexOf(vm.watchedPercent), { watchedDialog = false }) {
|
|
||||||
vm.chooseWatchedPercent(thresholds[it])
|
|
||||||
watchedDialog = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (remoteDialog) {
|
|
||||||
ChoiceDialog("Remote quality", StreamQuality.entries.map { it.label }, vm.remoteQuality.ordinal, { remoteDialog = false }) {
|
|
||||||
vm.chooseRemoteQuality(StreamQuality.entries[it])
|
|
||||||
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) {
|
|
||||||
val choices = listOf(0, 5, 10, 15, 30)
|
|
||||||
ChoiceDialog("Autoplay next episode", choices.map(::autoplayLabel), choices.indexOf(vm.autoplaySeconds), { autoplayDialog = false }) {
|
|
||||||
vm.chooseAutoplaySeconds(choices[it])
|
|
||||||
autoplayDialog = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (subtitleSizeDialog) {
|
|
||||||
ChoiceDialog("Subtitle size", SubtitleSize.entries.map { it.label }, vm.subtitleSize.ordinal, { subtitleSizeDialog = false }) {
|
|
||||||
vm.chooseSubtitleSize(SubtitleSize.entries[it])
|
|
||||||
subtitleSizeDialog = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (subtitleStyleDialog) {
|
|
||||||
ChoiceDialog("Subtitle style", SubtitleStyle.entries.map { it.label }, vm.subtitleStyle.ordinal, { subtitleStyleDialog = false }) {
|
|
||||||
vm.chooseSubtitleStyle(SubtitleStyle.entries[it])
|
|
||||||
subtitleStyleDialog = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (qualityDialog) {
|
|
||||||
ChoiceDialog("Playback quality", StreamQuality.entries.map { it.label }, vm.streamQuality.ordinal, { qualityDialog = false }) {
|
|
||||||
vm.chooseStreamQuality(StreamQuality.entries[it])
|
|
||||||
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"
|
|
||||||
/** 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. */
|
|
||||||
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
|
||||||
@Composable
|
|
||||||
private fun SubtitlePreview(size: SubtitleSize, style: SubtitleStyle) {
|
|
||||||
Box(
|
|
||||||
Modifier.fillMaxWidth().height(150.dp).clip(RoundedCornerShape(Cinema.radius))
|
|
||||||
.background(androidx.compose.ui.graphics.Brush.linearGradient(listOf(Color(0xFF3B4A5A), Color(0xFFB9A27A), Color(0xFF2A2F36))))
|
|
||||||
) {
|
|
||||||
androidx.compose.ui.viewinterop.AndroidView(
|
|
||||||
factory = { context -> androidx.media3.ui.SubtitleView(context) },
|
|
||||||
update = { view ->
|
|
||||||
applySubtitleStyle(view, size, style, view.resources.displayMetrics.heightPixels)
|
|
||||||
view.setBottomPaddingFraction(.12f)
|
|
||||||
view.setCues(listOf(androidx.media3.common.text.Cue.Builder().setText("Subtitles will look like this.").build()))
|
|
||||||
},
|
|
||||||
modifier = Modifier.fillMaxSize()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Keep sideways moves still, scrolling only when a control is outside the pane. */
|
|
||||||
private object SettingsScroll:BringIntoViewSpec {
|
|
||||||
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float):Float = when {
|
|
||||||
offset<0f->offset
|
|
||||||
offset+size>containerSize->offset+size-containerSize
|
|
||||||
else->0f
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun SettingsSectionDescription(description: String) {
|
|
||||||
Text(description, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun SettingsCategoryItem(
|
|
||||||
label: String,
|
|
||||||
selected: Boolean,
|
|
||||||
requester: FocusRequester,
|
|
||||||
upTarget: FocusRequester,
|
|
||||||
downTarget: FocusRequester,
|
|
||||||
rightTarget: FocusRequester,
|
|
||||||
onFocused: () -> Unit,
|
|
||||||
onClick: () -> Unit
|
|
||||||
) {
|
|
||||||
var focused by remember { mutableStateOf(false) }
|
|
||||||
val background by animateColorAsState(
|
|
||||||
if (focused) Accent else if (selected) Color.White.copy(alpha = .09f) else Color.Transparent,
|
|
||||||
tween(150),
|
|
||||||
label = "settingsCategoryBackground"
|
|
||||||
)
|
|
||||||
val scale by animateFloatAsState(if (focused) 1.025f else 1f, tween(160), label = "settingsCategoryScale")
|
|
||||||
Row(
|
|
||||||
Modifier.fillMaxWidth().height(40.dp)
|
|
||||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
|
||||||
.focusRequester(requester)
|
|
||||||
.focusProperties {
|
|
||||||
left = FocusRequester.Cancel
|
|
||||||
right = rightTarget
|
|
||||||
up = upTarget
|
|
||||||
down = downTarget
|
|
||||||
}
|
|
||||||
.navigationSound()
|
|
||||||
.onFocusChanged {
|
|
||||||
focused = it.isFocused
|
|
||||||
if (it.isFocused) onFocused()
|
|
||||||
}
|
|
||||||
.clip(RoundedCornerShape(Cinema.radius))
|
|
||||||
.background(background)
|
|
||||||
.clickable(onClick = onClick)
|
|
||||||
.padding(horizontal = 11.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically
|
|
||||||
) {
|
|
||||||
Box(
|
|
||||||
Modifier.width(2.dp).height(17.dp)
|
|
||||||
.background(if (selected) (if (focused) Ink else Accent.copy(alpha = .72f)) else Color.Transparent, RoundedCornerShape(2.dp))
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
label,
|
|
||||||
color = if (focused) Ink else if (selected) Accent else Muted,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
lineHeight = 16.sp,
|
|
||||||
fontWeight = if (focused || selected) FontWeight.SemiBold else FontWeight.Medium,
|
|
||||||
modifier = Modifier.padding(start = 10.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun SettingsValueRow(
|
|
||||||
title: String,
|
|
||||||
description: String,
|
|
||||||
value: String,
|
|
||||||
requester: FocusRequester,
|
|
||||||
leftTarget: FocusRequester,
|
|
||||||
rightTarget: FocusRequester? = null,
|
|
||||||
onClick: () -> Unit
|
|
||||||
) {
|
|
||||||
var focused by remember { mutableStateOf(false) }
|
|
||||||
val background by animateColorAsState(if (focused) Accent else Color.White.copy(alpha = .045f), tween(150), label = "settingsValueBackground")
|
|
||||||
val foreground = if (focused) Ink else Accent
|
|
||||||
Row(
|
|
||||||
Modifier.fillMaxWidth().heightIn(min = 58.dp)
|
|
||||||
.focusRequester(requester)
|
|
||||||
.focusProperties {
|
|
||||||
left = leftTarget
|
|
||||||
right = rightTarget ?: FocusRequester.Cancel
|
|
||||||
}
|
|
||||||
.navigationSound()
|
|
||||||
.onFocusChanged { focused = it.isFocused }
|
|
||||||
.clip(RoundedCornerShape(Cinema.radius))
|
|
||||||
.background(background)
|
|
||||||
.clickable(onClick = onClick)
|
|
||||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically
|
|
||||||
) {
|
|
||||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
|
||||||
Text(title, color = foreground, fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold)
|
|
||||||
Text(
|
|
||||||
description,
|
|
||||||
color = if (focused) Ink.copy(alpha = .72f) else Muted,
|
|
||||||
fontSize = 10.sp,
|
|
||||||
lineHeight = 14.sp,
|
|
||||||
maxLines = 2,
|
|
||||||
overflow = TextOverflow.Ellipsis
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.width(15.dp))
|
|
||||||
Text(
|
|
||||||
value,
|
|
||||||
color = if (focused) Ink else Accent,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
lineHeight = 15.sp,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
maxLines = 1,
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
|
||||||
modifier = Modifier.widthIn(max = 190.dp).padding(start = 5.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun SettingsActionButton(
|
|
||||||
label: String,
|
|
||||||
requester: FocusRequester,
|
|
||||||
leftTarget: FocusRequester,
|
|
||||||
rightTarget: FocusRequester? = null,
|
|
||||||
primary: Boolean = false,
|
|
||||||
onClick: () -> Unit
|
|
||||||
) {
|
|
||||||
var focused by remember { mutableStateOf(false) }
|
|
||||||
val background by animateColorAsState(
|
|
||||||
if (focused) Accent else if (primary) Color.White.copy(alpha = .21f) else Color.White.copy(alpha = .09f),
|
|
||||||
tween(150),
|
|
||||||
label = "settingsActionBackground"
|
|
||||||
)
|
|
||||||
val scale by animateFloatAsState(if (focused) 1.025f else 1f, tween(160), label = "settingsActionScale")
|
|
||||||
Box(
|
|
||||||
Modifier.height(36.dp).graphicsLayer { scaleX = scale; scaleY = scale }
|
|
||||||
.focusRequester(requester)
|
|
||||||
.focusProperties {
|
|
||||||
left = leftTarget
|
|
||||||
right = rightTarget ?: FocusRequester.Cancel
|
|
||||||
}
|
|
||||||
.navigationSound()
|
|
||||||
.onFocusChanged { focused = it.isFocused }
|
|
||||||
.clip(RoundedCornerShape(Cinema.radius))
|
|
||||||
.background(background)
|
|
||||||
.clickable(onClick = onClick)
|
|
||||||
.padding(horizontal = 13.dp),
|
|
||||||
contentAlignment = Alignment.Center
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
label,
|
|
||||||
color = if (focused) Ink else Accent,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
lineHeight = 15.sp,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
maxLines = 1,
|
|
||||||
overflow = TextOverflow.Ellipsis
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,237 +1,96 @@
|
||||||
package tv.kaleido.app
|
package tv.kaleido.app
|
||||||
|
|
||||||
import androidx.compose.animation.core.Animatable
|
import androidx.compose.animation.core.Animatable
|
||||||
import androidx.compose.animation.core.CubicBezierEasing
|
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||||
import androidx.compose.animation.core.LinearEasing
|
import androidx.compose.animation.core.LinearEasing
|
||||||
import androidx.compose.animation.core.tween
|
import androidx.compose.animation.core.tween
|
||||||
import androidx.compose.foundation.Canvas
|
import androidx.compose.foundation.Canvas
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.*
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import androidx.compose.ui.geometry.Rect
|
|
||||||
import androidx.compose.ui.geometry.Size
|
|
||||||
import androidx.compose.ui.graphics.BlendMode
|
|
||||||
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.Path
|
import androidx.compose.ui.graphics.Path
|
||||||
import androidx.compose.ui.graphics.PathFillType
|
import androidx.compose.ui.graphics.drawscope.withTransform
|
||||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
import androidx.compose.ui.graphics.drawscope.clipPath
|
import androidx.compose.ui.graphics.vector.PathParser
|
||||||
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 kotlinx.coroutines.flow.first
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import kotlinx.coroutines.withTimeoutOrNull
|
import androidx.compose.ui.unit.dp
|
||||||
import kotlin.math.PI
|
import androidx.compose.ui.unit.sp
|
||||||
import kotlin.math.cos
|
|
||||||
import kotlin.math.exp
|
|
||||||
import kotlin.math.ln
|
|
||||||
import kotlin.math.max
|
|
||||||
import kotlin.math.sin
|
import kotlin.math.sin
|
||||||
|
|
||||||
private class KaleidoFacet(val points:List<Offset>,val centroid:Offset,val color:Color,val angle:Float)
|
private data class ApertureFacet(val path:Path,val color:Color,val center:Offset)
|
||||||
|
|
||||||
// Exact geometry and colors from brand_mark.xml, centered on its 64-unit viewport.
|
// Exact geometry and colors from brand_mark.xml. The six pieces move independently
|
||||||
// Each facet carries its centroid and the angle of its hexagon edge's outward normal.
|
// into the existing aperture; the completed mark is never rotated or redesigned.
|
||||||
private val kaleidoFacets=listOf(
|
private val apertureFacets=listOf(
|
||||||
floatArrayOf(33f,4f,55.5f,17f,42.5f,24.5f,33f,19f) to 0xFFC3E8D3,
|
Triple("M33,4 L55.5,17 L42.5,24.5 L33,19 Z",0xFFC3E8D3,Offset(43f,14f)),
|
||||||
floatArrayOf(56.5f,19f,56.5f,45f,43.5f,37.5f,43.5f,26.5f) to 0xFF71B9B0,
|
Triple("M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z",0xFF71B9B0,Offset(50f,32f)),
|
||||||
floatArrayOf(55.5f,47f,33f,60f,33f,45f,42.5f,39.5f) to 0xFF3D7C7B,
|
Triple("M55.5,47 L33,60 L33,45 L42.5,39.5 Z",0xFF3D7C7B,Offset(43f,50f)),
|
||||||
floatArrayOf(31f,60f,8.5f,47f,21.5f,39.5f,31f,45f) to 0xFFD0A977,
|
Triple("M31,60 L8.5,47 L21.5,39.5 L31,45 Z",0xFFD0A977,Offset(21f,50f)),
|
||||||
floatArrayOf(7.5f,45f,7.5f,19f,20.5f,26.5f,20.5f,37.5f) to 0xFFE9D8AE,
|
Triple("M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z",0xFFE9D8AE,Offset(14f,32f)),
|
||||||
floatArrayOf(8.5f,17f,31f,4f,31f,19f,21.5f,24.5f) to 0xFFEEF2DD
|
Triple("M8.5,17 L31,4 L31,19 L21.5,24.5 Z",0xFFEEF2DD,Offset(21f,14f))
|
||||||
).mapIndexed { index,(points,color) ->
|
).map{(path,color,center)->ApertureFacet(PathParser().parsePathString(path).toPath(),Color(color),center)}
|
||||||
val corners=points.toList().chunked(2){Offset(it[0]-32f,it[1]-32f)}
|
|
||||||
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.
|
|
||||||
private const val InnerRadius=13.6f
|
|
||||||
private const val MarkBox=140f
|
|
||||||
// Timeline in ms. The shard field fades in, still, until GatherEnd and holds there until startup is ready; the
|
|
||||||
// gather then plays in motion time (timeline minus GatherEnd). Completion is reported at IntroEnd; the timeline
|
|
||||||
// keeps running to TimelineEnd only so the mark stays alive while the exit plays or startup loads.
|
|
||||||
private const val GatherEnd=260f
|
|
||||||
private const val IntroEnd=GatherEnd+1700f
|
|
||||||
private const val TimelineEnd=GatherEnd+8000f
|
|
||||||
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 EmphasizedDecelerate=CubicBezierEasing(.05f,.7f,.1f,1f)
|
|
||||||
private val Standard=CubicBezierEasing(.4f,0f,.2f,1f)
|
|
||||||
private val InOut=CubicBezierEasing(.45f,0f,.55f,1f)
|
|
||||||
// Applied in log space: a brief pull back, then an accelerating flight.
|
|
||||||
private val Flight=CubicBezierEasing(.55f,-.06f,.8f,.36f)
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
/** A facet turned [rotation] about the mark center, shrunk and spun about its own centroid, then offset. */
|
/** One finite brand sequence, followed by a settled mark while startup data loads. */
|
||||||
private fun Path.facet(facet:KaleidoFacet,center:Offset,unit:Float,rotation:Float=0f,scale:Float=1f,spin:Float=0f,offset:Offset=Offset.Zero) {
|
@Composable fun StartupSplash(alpha:Float,onComplete:()->Unit) {
|
||||||
val cr=cos(rotation);val sr=sin(rotation);val cs=cos(spin);val ss=sin(spin)
|
|
||||||
facet.points.forEachIndexed { index,point ->
|
|
||||||
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()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A loose facet shape with its centroid at [position]. */
|
|
||||||
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 ->
|
|
||||||
val x=point.x-facet.centroid.x;val y=point.y-facet.centroid.y
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
close()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun Path.hexagon(center:Offset,radius:Float) {
|
|
||||||
for(index in 0 until 6) {
|
|
||||||
val angle=(-90.0+60*index)*PI/180
|
|
||||||
val x=center.x+cos(angle).toFloat()*radius;val y=center.y+sin(angle).toFloat()*radius
|
|
||||||
if(index==0)moveTo(x,y)else lineTo(x,y)
|
|
||||||
}
|
|
||||||
close()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Scale for the screen behind the splash, so it settles into place as the aperture opens. */
|
|
||||||
fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(phase(exit,.25f,1f)))
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The cold-start brand sequence, the same as Kaleido Desktop: a kaleidoscope. A mirrored field of shards turns
|
|
||||||
* and gathers into the mark's six facets once [ready]; small shards circle the mark if startup runs on. [exit]
|
|
||||||
* (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) {
|
|
||||||
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.
|
||||||
// The field fades in faint and still straight away, so the first cold-start frames
|
timeline.animateTo(1f,tween(2600,easing=LinearEasing))
|
||||||
// can hitch there without being noticed.
|
|
||||||
timeline.animateTo(GatherEnd,tween(GatherEnd.toInt(),easing=LinearEasing))
|
|
||||||
// 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
|
|
||||||
// the gather, fastest at its start, never runs through it.
|
|
||||||
withTimeoutOrNull(700){
|
|
||||||
snapshotFlow{ready()}.first{it}
|
|
||||||
awaitSteadyFrames(4)
|
|
||||||
}
|
|
||||||
timeline.animateTo(TimelineEnd,tween((TimelineEnd-GatherEnd).toInt(),easing=LinearEasing))
|
|
||||||
}
|
|
||||||
LaunchedEffect(Unit){
|
|
||||||
snapshotFlow{timeline.value>=IntroEnd}.first{it}
|
|
||||||
complete()
|
complete()
|
||||||
}
|
}
|
||||||
val paths=remember{List(4){Path()}}
|
Box(Modifier.fillMaxSize().graphicsLayer{this.alpha=alpha}.background(Ink)
|
||||||
Canvas(Modifier.fillMaxSize().clearAndSetSemantics{contentDescription="Kaleido starting"}) {
|
.clearAndSetSemantics{contentDescription="Kaleido starting"},contentAlignment=Alignment.Center) {
|
||||||
|
Canvas(Modifier.fillMaxSize()) {
|
||||||
val time=timeline.value
|
val time=timeline.value
|
||||||
val motion=time-GatherEnd
|
val origin=Offset(size.width/2,size.height/2-32.dp.toPx())
|
||||||
val prelude=EmphasizedDecelerate.transform(phase(time,0f,GatherEnd))
|
val unit=112.dp.toPx()/64f
|
||||||
val q=exit()
|
val glow=sin(phase(time,0f,.88f)*Math.PI).toFloat().coerceAtLeast(0f)
|
||||||
val dp=density
|
drawCircle(Brush.radialGradient(listOf(Color(0xFF71B9B0).copy(alpha=.16f*glow),Color.Transparent),
|
||||||
val zoom=if(q>0f)exp(ln(FlightZoom)*Flight.transform(q))else 1f
|
center=origin,radius=230.dp.toPx()),radius=230.dp.toPx(),center=origin)
|
||||||
val unit=MarkBox*dp/64f*zoom
|
apertureFacets.forEachIndexed { index,facet ->
|
||||||
val origin=center
|
val start=.06f+index*.045f
|
||||||
val gather=Emphasized.transform(phase(motion,0f,1450f))
|
val raw=phase(time,start,start+.34f)
|
||||||
// The whole field turns a little less than half a revolution as it gathers.
|
val arrival=FastOutSlowInEasing.transform(raw)
|
||||||
val field=rad(-150f)*(1f-Emphasized.transform(phase(motion,0f,1550f)))
|
val direction=(facet.center-Offset(32f,32f))/18f
|
||||||
val (surface,aperture,shape,ring)=paths
|
val distance=190f*(1f-arrival)
|
||||||
|
// A tapered light trail leads each sea-glass/ivory facet inward.
|
||||||
// Splash surface: Ink everywhere, with the aperture's center cut away on exit.
|
if(raw>0f&&raw<1f) {
|
||||||
val hole=InOut.transform(phase(q,.12f,.5f))
|
val head=origin+direction*((distance+23f)*unit)
|
||||||
if(hole<=0f)drawRect(Ink)
|
val tail=head+direction*((20f+80f*(1f-arrival))*unit)
|
||||||
else {
|
drawLine(Brush.linearGradient(listOf(facet.color.copy(alpha=.5f*sin(raw*Math.PI).toFloat()),Color.Transparent),head,tail),
|
||||||
surface.rewind();surface.fillType=PathFillType.EvenOdd
|
head,tail,strokeWidth=1.3.dp.toPx())
|
||||||
surface.addRect(Rect(Offset.Zero,size));surface.hexagon(origin,InnerRadius*unit)
|
|
||||||
drawPath(surface,Ink)
|
|
||||||
if(hole<1f){aperture.rewind();aperture.hexagon(origin,InnerRadius*unit);drawPath(aperture,Ink,alpha=1f-hole)}
|
|
||||||
}
|
}
|
||||||
|
withTransform({
|
||||||
// The kaleidoscope's mirror lines, turning with the field.
|
translate(origin.x-32f*unit,origin.y-32f*unit)
|
||||||
val lines=max(.5f*prelude,InOut.transform(phase(motion,0f,450f)))*(1f-Standard.transform(phase(motion,1100f,1700f)))
|
scale(unit,unit,pivot=Offset.Zero)
|
||||||
if(lines>0f) for(index in 0 until 6) {
|
translate(direction.x*distance,direction.y*distance)
|
||||||
val angle=field+rad(-90f+60*index)
|
scale(.72f+.28f*arrival,.72f+.28f*arrival,pivot=facet.center)
|
||||||
val end=origin+Offset(cos(angle),sin(angle))*(640f*dp)
|
}) {
|
||||||
drawLine(Brush.linearGradient(0f to Light.copy(alpha=.2f*lines),1f to Color.Transparent,start=origin,end=end),origin,end,dp)
|
drawPath(facet.path,facet.color,alpha=phase(raw,0f,.42f))
|
||||||
}
|
val glint=sin(phase(time,.64f+index*.018f,.78f+index*.018f)*Math.PI).toFloat().coerceAtLeast(0f)
|
||||||
|
if(raw==1f)drawPath(facet.path,Color.White,alpha=.22f*glint)
|
||||||
val bloom=.09f*InOut.transform(phase(motion,200f,1000f))*(1f-Standard.transform(phase(motion,1500f,2600f)))
|
|
||||||
if(bloom>.001f) {
|
|
||||||
val radius=300f*dp
|
|
||||||
drawCircle(Brush.radialGradient(0f to SeaGlass.copy(alpha=bloom),.45f to SeaGlass.copy(alpha=bloom*.3f),1f to Color.Transparent,
|
|
||||||
center=origin,radius=radius),radius,origin,blendMode=BlendMode.Plus)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Shards spiral inward, faster than the field turns, and vanish into the center.
|
|
||||||
val inward=Emphasized.transform(phase(motion,0f,1350f))
|
|
||||||
kaleidoFacets.forEachIndexed { s,facet ->
|
|
||||||
shards.forEachIndexed { j,shard ->
|
|
||||||
val appear=max(.3f*prelude,Standard.transform(phase(motion,j*50f+s*25,j*50f+s*25+420)))
|
|
||||||
val vanish=Standard.transform(phase(motion,750f+j*45,1350f+j*45))
|
|
||||||
if(appear>0f&&vanish<1f) {
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Row(Modifier.offset(y=65.dp),horizontalArrangement=Arrangement.spacedBy(7.dp),verticalAlignment=Alignment.CenterVertically) {
|
||||||
// The six facets ride in from the field and lock into the mark.
|
"KALEIDO".forEachIndexed { index,letter ->
|
||||||
kaleidoFacets.forEachIndexed { s,facet ->
|
Text(letter.toString(),color=Color(0xFFEEF2DD),fontSize=28.sp,fontWeight=FontWeight.Medium,
|
||||||
val radius=240f*dp*(1f-gather);val angle=facet.angle+field
|
modifier=Modifier.graphicsLayer {
|
||||||
shape.rewind()
|
val reveal=FastOutSlowInEasing.transform(phase(timeline.value,.48f+index*.025f,.66f+index*.025f))
|
||||||
shape.facet(facet,origin,unit,field,mix(.55f,1f,gather),rad(-60f)*(1f-gather),Offset(cos(angle),sin(angle))*radius)
|
this.alpha=reveal
|
||||||
drawPath(shape,facet.color,alpha=max(.3f*prelude,Standard.transform(phase(motion,s*25f,s*25f+420))))
|
translationY=14.dp.toPx()*(1f-reveal)
|
||||||
}
|
})
|
||||||
|
|
||||||
// A ring pulses out as the facets lock.
|
|
||||||
val pulse=phase(motion,1380f,2050f)
|
|
||||||
if(pulse>0f&&pulse<1f) {
|
|
||||||
ring.rewind();ring.hexagon(origin,(30f+24f*EmphasizedDecelerate.transform(pulse))*unit)
|
|
||||||
drawPath(ring,SeaGlass,alpha=.45f*(1f-pulse),style=Stroke(1.5f*dp))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Still starting: small shards keep circling the mark.
|
|
||||||
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 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,
|
|
||||||
start=origin+direction*(position-width),end=origin+direction*(position+width)),origin-Offset(reach,reach),Size(reach*2,reach*2))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -33,12 +33,6 @@ import androidx.compose.ui.unit.sp
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
val Ink=Color(0xFF090909)
|
val Ink=Color(0xFF090909)
|
||||||
|
|
||||||
/** Suspends until [count] consecutive frames each arrive within 24 ms of the previous one. */
|
|
||||||
suspend fun awaitSteadyFrames(count:Int) {
|
|
||||||
var previous=withFrameNanos{it};var steady=0
|
|
||||||
while(steady<count){val now=withFrameNanos{it};steady=if(now-previous<24_000_000L)steady+1 else 0;previous=now}
|
|
||||||
}
|
|
||||||
val Panel=Color(0xFF1B1B1B)
|
val Panel=Color(0xFF1B1B1B)
|
||||||
val Muted=Color(0xFFA5A5A5)
|
val Muted=Color(0xFFA5A5A5)
|
||||||
val Accent=Color(0xFFF1F1F1)
|
val Accent=Color(0xFFF1F1F1)
|
||||||
|
|
@ -54,13 +48,12 @@ object Cinema {
|
||||||
}
|
}
|
||||||
@Composable fun TvButton(label: String,modifier: Modifier=Modifier,selected: Boolean=false,primary: Boolean=false,initialFocus: Boolean=false,onClick: ()->Unit) {
|
@Composable fun TvButton(label: String,modifier: Modifier=Modifier,selected: Boolean=false,primary: Boolean=false,initialFocus: Boolean=false,onClick: ()->Unit) {
|
||||||
var focused by remember { mutableStateOf(false) };val requester=remember {FocusRequester()}
|
var focused by remember { mutableStateOf(false) };val requester=remember {FocusRequester()}
|
||||||
// Only focus is solid white; a primary action is a brighter tint, so focus stays obvious.
|
val bg by animateColorAsState(if(focused) Accent else if(primary)Color(0xFFDEDEDE) else if(selected)Color.White.copy(alpha=.16f)else Color.White.copy(alpha=.08f),tween(150),label="buttonBackground")
|
||||||
val bg by animateColorAsState(if(focused) Accent else if(primary)Color.White.copy(alpha=.24f) else if(selected)Color.White.copy(alpha=.16f)else Color.White.copy(alpha=.08f),tween(150),label="buttonBackground")
|
val fg=if(focused||primary) Ink else Accent
|
||||||
val fg=if(focused) Ink else Accent
|
|
||||||
val scale by animateFloatAsState(if(focused)1.025f else 1f,tween(160),label="buttonScale")
|
val scale by animateFloatAsState(if(focused)1.025f else 1f,tween(160),label="buttonScale")
|
||||||
LaunchedEffect(initialFocus){if(initialFocus){withFrameNanos{};runCatching{requester.requestFocus()}}}
|
LaunchedEffect(initialFocus){if(initialFocus){withFrameNanos{};runCatching{requester.requestFocus()}}}
|
||||||
Box(modifier.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused}.clip(RoundedCornerShape(Cinema.radius)).background(bg).clickable(onClick=onClick).padding(horizontal=13.dp,vertical=8.dp)) {
|
Box(modifier.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused}.clip(RoundedCornerShape(Cinema.radius)).background(bg).clickable(onClick=onClick).padding(horizontal=13.dp,vertical=8.dp)) {
|
||||||
Text(label,color=fg,fontSize=12.sp,lineHeight=16.sp,fontWeight=if(primary)FontWeight.SemiBold else FontWeight.Medium,maxLines=1)
|
Text(label,color=fg,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Composable fun SectionHeading(title: String, subtitle: String?=null) {
|
@Composable fun SectionHeading(title: String, subtitle: String?=null) {
|
||||||
|
|
@ -72,9 +65,8 @@ object Cinema {
|
||||||
var focused by remember{mutableStateOf(false)}
|
var focused by remember{mutableStateOf(false)}
|
||||||
val requester=remember{FocusRequester()}
|
val requester=remember{FocusRequester()}
|
||||||
val scale by animateFloatAsState(if(focused)1.025f else 1f,tween(160),label="actionScale")
|
val scale by animateFloatAsState(if(focused)1.025f else 1f,tween(160),label="actionScale")
|
||||||
// Only focus is solid white, as with TvButton; an unfocused Play must not look selected.
|
val background by animateColorAsState(if(focused||primary)Accent else Color.White.copy(alpha=.12f),tween(160),label="actionSurface")
|
||||||
val background by animateColorAsState(if(focused)Accent else if(primary)Color.White.copy(alpha=.24f)else Color.White.copy(alpha=.12f),tween(160),label="actionSurface")
|
val foreground=if(focused||primary)Ink else Accent
|
||||||
val foreground=if(focused)Ink else Accent
|
|
||||||
LaunchedEffect(initialFocus){if(initialFocus){withFrameNanos{};runCatching{requester.requestFocus()}}}
|
LaunchedEffect(initialFocus){if(initialFocus){withFrameNanos{};runCatching{requester.requestFocus()}}}
|
||||||
Row(modifier.height(34.dp).graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused}.clip(RoundedCornerShape(5.dp)).background(background).clickable(onClick=onClick).padding(horizontal=14.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
|
Row(modifier.height(34.dp).graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused}.clip(RoundedCornerShape(5.dp)).background(background).clickable(onClick=onClick).padding(horizontal=14.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
|
||||||
Icon(icon,null,tint=foreground,modifier=Modifier.size(17.dp))
|
Icon(icon,null,tint=foreground,modifier=Modifier.size(17.dp))
|
||||||
|
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
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()
|
|
||||||
|
|
@ -1,289 +0,0 @@
|
||||||
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
|
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import androidx.compose.foundation.*
|
|
||||||
import androidx.compose.foundation.layout.*
|
|
||||||
import androidx.compose.foundation.lazy.*
|
|
||||||
import androidx.compose.foundation.gestures.BringIntoViewSpec
|
|
||||||
import androidx.compose.foundation.gestures.animateScrollBy
|
|
||||||
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
|
|
||||||
import androidx.compose.foundation.lazy.grid.*
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material.icons.Icons
|
|
||||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
|
||||||
import androidx.compose.material.icons.filled.PlayArrow
|
|
||||||
import androidx.compose.material.icons.outlined.*
|
|
||||||
import androidx.compose.material3.*
|
|
||||||
import androidx.compose.runtime.*
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.focus.*
|
|
||||||
import androidx.compose.ui.input.key.*
|
|
||||||
import androidx.compose.ui.geometry.Offset
|
|
||||||
import androidx.compose.ui.graphics.Brush
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.Shadow
|
|
||||||
import androidx.compose.ui.graphics.graphicsLayer
|
|
||||||
import androidx.compose.ui.layout.ContentScale
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.platform.LocalDensity
|
|
||||||
import androidx.compose.ui.semantics.*
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import androidx.compose.ui.window.Dialog
|
|
||||||
import androidx.compose.ui.window.DialogProperties
|
|
||||||
import coil.compose.AsyncImage
|
|
||||||
import coil.request.ImageRequest
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
|
|
||||||
@Composable fun DetailsScreen(vm:KaleidoViewModel) {
|
|
||||||
val item=vm.detail ?: return
|
|
||||||
val actionFocus=remember(item.id){FocusRequester()}
|
|
||||||
val childFocus=remember(item.id){FocusRequester()}
|
|
||||||
val castFocus=remember(item.id){FocusRequester()}
|
|
||||||
val restoreFocus=remember(item.id){vm.focusId}
|
|
||||||
val restoreRow=remember(item.id){listOf("cast:","children:","related:","extras:").any{restoreFocus.startsWith("$it${item.id}:")}}
|
|
||||||
val list=rememberLazyListState()
|
|
||||||
val backdropFadeDistance=with(LocalDensity.current){180.dp.toPx()}
|
|
||||||
val extras=item.playableExtras
|
|
||||||
// Season and episode pages show one episode in the header; focus in the season row chooses it.
|
|
||||||
val episodic=item.type in listOf("season","episode")
|
|
||||||
val selectedId=vm.episodeSelections[item.id]
|
|
||||||
val selected=when {
|
|
||||||
!episodic->item
|
|
||||||
item.type=="episode"&&(selectedId==null||selectedId==item.id)->item
|
|
||||||
else->vm.children.firstOrNull{it.id==selectedId} ?: if(item.type=="episode")item else nextUp(vm.children,vm.watchedPercent) ?: item
|
|
||||||
}
|
|
||||||
// Row records are summaries; show full metadata once focus settles, keeping the row's progress.
|
|
||||||
var full by remember(item.id){mutableStateOf<Title?>(null)}
|
|
||||||
LaunchedEffect(selected.id){if(selected!==item&&selected.type=="episode"){kotlinx.coroutines.delay(250);full=vm.previewDetails(selected)}}
|
|
||||||
val shown=if(selected===item)item else full?.takeIf{it.id==selected.id}?.copy(watched=selected.watched,offset=selected.offset) ?: selected
|
|
||||||
LaunchedEffect(item.id,vm.children.isNotEmpty(),vm.detailRelated.isNotEmpty()) {
|
|
||||||
// Lazy items in display order, so a restored row is revealed at its real index.
|
|
||||||
val rows=buildList {
|
|
||||||
add("details")
|
|
||||||
if(vm.children.isNotEmpty())add("children")
|
|
||||||
if(item.castMembers.isNotEmpty())add("cast")
|
|
||||||
if(extras.isNotEmpty())add("extras")
|
|
||||||
if(vm.detailRelated.isNotEmpty())add("related")
|
|
||||||
}
|
|
||||||
val target=listOf("children","cast","extras","related").firstOrNull{restoreFocus.startsWith("$it:${item.id}:")}?.let{rows.indexOf(it)}?.takeIf{it>0}
|
|
||||||
// Async rows may not exist during the first restored layout. Reveal the
|
|
||||||
// requested row after it loads, then its card restores the exact focus.
|
|
||||||
if(target!=null)list.scrollToItem(target)
|
|
||||||
}
|
|
||||||
// Back from playback focuses Play/Resume rather than the first control on the page.
|
|
||||||
val seenReturn=remember{intArrayOf(vm.playbackReturn)}
|
|
||||||
// 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()}}}
|
|
||||||
Box(Modifier.fillMaxSize().background(Ink)) {
|
|
||||||
// The browse previews' framing, so opening a title keeps its artwork in place; a season's
|
|
||||||
// artwork follows the episode it shows. Scroll is read in the layer, never in composition.
|
|
||||||
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)
|
|
||||||
},header=true,wash=vm.colourWash,animate=true)
|
|
||||||
// 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
|
|
||||||
CompositionLocalProvider(LocalBringIntoViewSpec provides DetailsScroll) {
|
|
||||||
LazyColumn(state=list,contentPadding=PaddingValues(bottom=30.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) {
|
|
||||||
item(key="details-${item.id}"){DetailHeader(vm,shown,item,actionFocus,below,!restoreRow)}
|
|
||||||
// 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(episodic)MediaRow(vm,if(item.type=="season")item.title else "Season ${item.parentIndex}",vm.children,"children:${item.id}",landscape=true,entryFocus=childFocus,episodeTitles=true,
|
|
||||||
initialItem=selected.id,selectedItem=selected.id,up=actionFocus,onFocused={vm.episodeSelections[item.id]=it.id},onClick={vm.play(it)})
|
|
||||||
else MediaRow(vm,if(item.type=="show")"Seasons"else "In this collection",vm.children,"children:${item.id}",entryFocus=childFocus)
|
|
||||||
}
|
|
||||||
if(item.castMembers.isNotEmpty())item(key="cast-${item.id}"){CastRail(vm,item,actionFocus,castFocus)}
|
|
||||||
if(extras.isNotEmpty())item(key="extras-${item.id}"){MediaRow(vm,"Trailers & extras",extras,"extras:${item.id}",landscape=true,onClick={vm.play(it)})}
|
|
||||||
if(vm.detailRelated.isNotEmpty())item(key="related-${item.id}"){MediaRow(vm,if(item.type=="movie")"Related movies"else "Related shows",vm.detailRelated,"related:${item.id}")}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Do not pin an already visible action a third of the way down the screen. */
|
|
||||||
private object DetailsScroll:BringIntoViewSpec {
|
|
||||||
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float):Float = when {
|
|
||||||
offset<12f->offset-12f
|
|
||||||
offset+size>containerSize-12f->offset+size-containerSize+12f
|
|
||||||
else->0f
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The header, after the browse previews: title art, facts and format, synopsis, then actions.
|
|
||||||
* [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)}
|
|
||||||
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 showVersions by remember(item.id){mutableStateOf(false)}
|
|
||||||
val media=item.media.getOrNull(vm.mediaIndex(item))
|
|
||||||
// Scrolls sideways only if a title has more actions than fit the page.
|
|
||||||
if(item.type!="collection")Row(Modifier.padding(top=9.dp).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)}
|
|
||||||
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")) {
|
|
||||||
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)}
|
|
||||||
}
|
|
||||||
item.trailer?.let{trailer->ActionButton("Trailer",Icons.Outlined.Movie,modifier=actionNavigation){vm.play(trailer)}}
|
|
||||||
// Name the version by resolution unless several share it, e.g. two 1080p encodes.
|
|
||||||
if(item.media.size>1)ActionButton(if(item.media.map{it.resolutionLabel}.distinct().size==item.media.size&&media?.resolutionLabel?.isNotBlank()==true)"Version · ${media.resolutionLabel}"
|
|
||||||
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(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}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Playback from the header returns to Play, not to the season row card focused last. */
|
|
||||||
private fun played(vm:KaleidoViewModel,page:Title){vm.focusId="actions:${page.id}"}
|
|
||||||
|
|
||||||
/** "Jul 11, 2004" in the TV's locale, from Plex's ISO date. */
|
|
||||||
internal fun airDate(iso:String):String = runCatching{
|
|
||||||
java.time.LocalDate.parse(iso.take(10)).format(java.time.format.DateTimeFormatter.ofLocalizedDate(java.time.format.FormatStyle.MEDIUM))
|
|
||||||
}.getOrDefault("")
|
|
||||||
|
|
||||||
/** A season's next episode: in progress, else the first unwatched, else the first. */
|
|
||||||
internal fun nextUp(episodes:List<Title>,watchedPercent:Int)=episodes.firstOrNull{it.offset>0&&!it.isWatched(watchedPercent)}
|
|
||||||
?: episodes.firstOrNull{!it.isWatched(watchedPercent)} ?: episodes.firstOrNull()
|
|
||||||
|
|
||||||
@Composable private fun SynopsisDialog(api:PlexApi,item:Title,onDismiss:()->Unit) {
|
|
||||||
val scroll=rememberScrollState()
|
|
||||||
val scope=rememberCoroutineScope()
|
|
||||||
val step=with(LocalDensity.current){100.dp.toPx()}
|
|
||||||
Dialog(onDismissRequest=onDismiss,properties=DialogProperties(usePlatformDefaultWidth=false,decorFitsSystemWindows=false)) {
|
|
||||||
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha=.42f)).padding(Cinema.gutter),contentAlignment=Alignment.Center) {
|
|
||||||
Row(Modifier.width(760.dp).heightIn(max=420.dp).clip(RoundedCornerShape(Cinema.radius)).background(Ink).border(1.dp,Accent.copy(alpha=.12f),RoundedCornerShape(Cinema.radius)).padding(28.dp).onPreviewKeyEvent {
|
|
||||||
if(it.type==KeyEventType.KeyDown&&it.key in listOf(Key.DirectionUp,Key.DirectionDown)) {
|
|
||||||
scope.launch{scroll.animateScrollBy(if(it.key==Key.DirectionUp)-step else step)};true
|
|
||||||
}else false
|
|
||||||
},horizontalArrangement=Arrangement.spacedBy(28.dp),verticalAlignment=Alignment.Top) {
|
|
||||||
Artwork(api,item.poster.ifBlank{item.thumb},Modifier.padding(top=4.dp).width(128.dp).height(192.dp).clip(RoundedCornerShape(Cinema.radius)),384,576,animate=false,contentScale=ContentScale.Fit)
|
|
||||||
Column(Modifier.weight(1f)) {
|
|
||||||
Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.spacedBy(18.dp),verticalAlignment=Alignment.Top) {
|
|
||||||
Column(Modifier.weight(1f)) {
|
|
||||||
Eyebrow("Synopsis")
|
|
||||||
Text(item.title,color=Accent,fontSize=26.sp,lineHeight=32.sp,fontWeight=FontWeight.SemiBold,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=6.dp))
|
|
||||||
Text(listOf(item.year,item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Muted,fontSize=10.sp,lineHeight=14.sp,modifier=Modifier.padding(top=6.dp))
|
|
||||||
}
|
|
||||||
IconControl(Icons.Outlined.Close,"Close",initialFocus=true,onClick=onDismiss)
|
|
||||||
}
|
|
||||||
Box(Modifier.padding(top=18.dp,bottom=16.dp).fillMaxWidth().height(1.dp).background(Accent.copy(alpha=.1f)))
|
|
||||||
Text(item.summary,color=Cinema.secondary,fontSize=12.5.sp,lineHeight=20.sp,modifier=Modifier.weight(1f,fill=false).verticalScroll(scroll))
|
|
||||||
Text(if(scroll.maxValue>0)"↑ ↓ Scroll · Back to close"else "Back to close",color=Cinema.quiet,fontSize=9.sp,lineHeight=13.sp,modifier=Modifier.padding(top=20.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@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 row=rememberLazyListState(initialFirstVisibleItemIndex=initial)
|
|
||||||
val entryIndex by rememberRowEntry(row,0)
|
|
||||||
Column {
|
|
||||||
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)) {
|
|
||||||
itemsIndexed(item.castMembers,key={index,actor->actor.id.ifBlank{"${actor.name}-$index"}}){index,actor->
|
|
||||||
val key="cast:${item.id}:${actor.id.ifBlank{actor.name}}"
|
|
||||||
var focused by remember{mutableStateOf(false)}
|
|
||||||
val requester=remember{FocusRequester()}
|
|
||||||
LaunchedEffect(Unit){if(vm.focusId==key){withFrameNanos{};runCatching{requester.requestFocus()}}}
|
|
||||||
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
|
|
||||||
}.clickable(enabled=actor.id.isNotBlank()){vm.openActor(actor)}.clearAndSetSemantics{
|
|
||||||
contentDescription=listOf(actor.name,actor.role).filter{it.isNotBlank()}.joinToString(". ")
|
|
||||||
this.focused=focused;role=Role.Button
|
|
||||||
if(actor.id.isNotBlank())onClick{vm.openActor(actor);true}
|
|
||||||
},horizontalAlignment=Alignment.CenterHorizontally) {
|
|
||||||
ActorPortrait(vm.api,actor,Modifier.size(86.dp).then(if(focused)Modifier.border(2.dp,Accent,CircleShape)else Modifier))
|
|
||||||
Text(actor.name,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=14.sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp).height(28.dp))
|
|
||||||
Text(actor.role,color=Muted,fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.height(12.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable internal fun ActorPortrait(api:PlexApi,actor:CastMember,modifier:Modifier) {
|
|
||||||
val context=LocalContext.current
|
|
||||||
val request=remember(actor.thumb,api.session?.server){api.image(actor.thumb,256,256)?.let{url->ImageRequest.Builder(context).data(url).apply{api.headers().forEach{(k,v)->addHeader(k,v)}}.crossfade(false).build()}}
|
|
||||||
Box(modifier.clip(CircleShape).background(Panel),contentAlignment=Alignment.Center) {
|
|
||||||
Icon(Icons.Outlined.Person,null,tint=Muted,modifier=Modifier.fillMaxSize(.5f))
|
|
||||||
AsyncImage(request,null,modifier=Modifier.fillMaxSize(),contentScale=ContentScale.Crop)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable fun ActorScreen(vm:KaleidoViewModel) {
|
|
||||||
val actor=vm.page.actor ?: return
|
|
||||||
Column(Modifier.fillMaxSize().background(Ink).padding(top=20.dp)) {
|
|
||||||
Row(Modifier.fillMaxWidth().padding(start=34.dp,end=Cinema.gutter,bottom=22.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(18.dp)) {
|
|
||||||
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back"){vm.back()}
|
|
||||||
ActorPortrait(vm.api,actor,Modifier.size(65.dp))
|
|
||||||
Column {
|
|
||||||
Eyebrow("In your libraries")
|
|
||||||
Text(actor.name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(vertical=3.dp))
|
|
||||||
Text(if(vm.busy)"Finding movies and shows…"else "${vm.actorTitles.size} titles",color=Muted,fontSize=11.sp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(vm.actorTitles.isEmpty()&&!vm.busy)Text("No titles with this actor in your libraries.",color=Muted,fontSize=14.sp,modifier=Modifier.padding(horizontal=Cinema.gutter))
|
|
||||||
LazyVerticalGrid(GridCells.Fixed(6),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,bottom=28.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp)) {
|
|
||||||
itemsIndexed(vm.actorTitles,key={_,item->item.id}){index,item->
|
|
||||||
MediaTile(vm,item,"actor:${actor.id}:${item.id}",fillWidth=true,initialFocus=index==0&&!vm.focusId.startsWith("actor:${actor.id}:"),onMove={anticipateTileMove(vm,vm.actorTitles,index,it,6)})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1 +1 @@
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="320dp" android:height="180dp" android:viewportWidth="320" android:viewportHeight="180"><path android:pathData="M0,0h320v180h-320z"><aapt:attr name="android:fillColor"><gradient android:type="linear" android:startX="320" android:startY="0" android:endX="0" android:endY="180"><item android:offset="0" android:color="#FF1B403C"/><item android:offset="0.5" android:color="#FF101414"/><item android:offset="1" android:color="#FF30241A"/></gradient></aapt:attr></path><path android:pathData="M0,0h320v180h-320z"><aapt:attr name="android:fillColor"><gradient android:type="radial" android:centerX="160.0" android:centerY="90.0" android:gradientRadius="198.4"><item android:offset="0.35" android:color="#00000000"/><item android:offset="1" android:color="#73000000"/></gradient></aapt:attr></path><group android:translateX="108.8" android:translateY="38.8" android:scaleX="1.6" android:scaleY="1.6"><path android:fillColor="#C3E8D3" android:pathData="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path android:fillColor="#71B9B0" android:pathData="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path android:fillColor="#3D7C7B" android:pathData="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path android:fillColor="#D0A977" android:pathData="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path android:fillColor="#E9D8AE" android:pathData="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path android:fillColor="#EEF2DD" android:pathData="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></group></vector>
|
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="320dp" android:height="180dp" android:viewportWidth="320" android:viewportHeight="180"><path android:fillColor="#090909" android:pathData="M0,0h320v180h-320z"/><group android:translateX="108.8" android:translateY="38.8" android:scaleX="1.6" android:scaleY="1.6"><path android:fillColor="#C3E8D3" android:pathData="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path android:fillColor="#71B9B0" android:pathData="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path android:fillColor="#3D7C7B" android:pathData="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path android:fillColor="#D0A977" android:pathData="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path android:fillColor="#E9D8AE" android:pathData="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path android:fillColor="#EEF2DD" android:pathData="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></group></vector>
|
||||||
|
|
|
||||||
|
|
@ -1 +1 @@
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"><path android:pathData="M0,0h108v108h-108z"><aapt:attr name="android:fillColor"><gradient android:type="linear" android:startX="108" android:startY="0" android:endX="0" android:endY="108"><item android:offset="0" android:color="#FF1B403C"/><item android:offset="0.5" android:color="#FF101414"/><item android:offset="1" android:color="#FF30241A"/></gradient></aapt:attr></path><path android:pathData="M0,0h108v108h-108z"><aapt:attr name="android:fillColor"><gradient android:type="radial" android:centerX="54.0" android:centerY="54.0" android:gradientRadius="67.0"><item android:offset="0.35" android:color="#00000000"/><item android:offset="1" android:color="#73000000"/></gradient></aapt:attr></path><group android:translateX="22" android:translateY="22" android:scaleX="1" android:scaleY="1"><path android:fillColor="#C3E8D3" android:pathData="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path android:fillColor="#71B9B0" android:pathData="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path android:fillColor="#3D7C7B" android:pathData="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path android:fillColor="#D0A977" android:pathData="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path android:fillColor="#E9D8AE" android:pathData="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path android:fillColor="#EEF2DD" android:pathData="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></group></vector>
|
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"><path android:fillColor="#090909" android:pathData="M0,0h108v108h-108z"/><group android:translateX="22" android:translateY="22"><path android:fillColor="#C3E8D3" android:pathData="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path android:fillColor="#71B9B0" android:pathData="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path android:fillColor="#3D7C7B" android:pathData="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path android:fillColor="#D0A977" android:pathData="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path android:fillColor="#E9D8AE" android:pathData="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path android:fillColor="#EEF2DD" android:pathData="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></group></vector>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
<resources>
|
|
||||||
<string name="app_name">Kaleido</string>
|
|
||||||
<string name="search_hint">Movies, shows, episodes, people</string>
|
|
||||||
</resources>
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:label="@string/app_name"
|
|
||||||
android:hint="@string/search_hint"
|
|
||||||
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer" />
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
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(""))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
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"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import kotlinx.coroutines.runBlocking
|
|
||||||
import org.junit.Assert.*
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class LibrarySyncTest {
|
|
||||||
@Test fun detectsNewMediaWithoutRestartAndSkipsUnchangedLibraries()=runBlocking {
|
|
||||||
var revision="before";var clock=0L;var refreshes=0
|
|
||||||
val sync=LibrarySync({revision},{refreshes++;true},{clock})
|
|
||||||
sync.check();assertEquals(1,refreshes)
|
|
||||||
clock+=15_000;sync.check();assertEquals(1,refreshes)
|
|
||||||
revision="new episode";sync.check();assertEquals(2,refreshes)
|
|
||||||
clock+=59_999;sync.check();assertEquals(2,refreshes)
|
|
||||||
clock++;sync.check();assertEquals(3,refreshes)
|
|
||||||
}
|
|
||||||
@Test fun discardedOrFailedRefreshIsRetried()=runBlocking {
|
|
||||||
var applies=false;var attempts=0;var failRequest=true
|
|
||||||
val sync=LibrarySync({"revision"},{attempts++;if(failRequest)throw java.io.IOException();applies},{0})
|
|
||||||
try{sync.check();fail("Expected failure")}catch(_:java.io.IOException){}
|
|
||||||
failRequest=false;sync.check();assertEquals(2,attempts)
|
|
||||||
applies=true;sync.check();assertEquals(3,attempts)
|
|
||||||
sync.check();assertEquals(3,attempts)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
@ -1,69 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
import org.junit.Assert.*
|
|
||||||
import org.junit.Test
|
|
||||||
class PlaybackModelTest {
|
|
||||||
private fun title(type:String,id:String=type)=Title(id,"/library/metadata/$id",type,"Title $id","","","","",0,0,false,"","","","","","",0,0,0,0,emptyList(),emptyList(),emptyList(),emptyList())
|
|
||||||
|
|
||||||
@Test fun localAddresses() {
|
|
||||||
assertTrue(isLocalAddress("http://192.168.50.10:32400"))
|
|
||||||
assertTrue(isLocalAddress("https://192-168-50-10.0123abcd.plex.direct:32400"))
|
|
||||||
assertTrue(isLocalAddress("https://10-0-0-4.0123abcd.plex.direct:32400"))
|
|
||||||
assertTrue(isLocalAddress("http://172.20.1.2:32400"))
|
|
||||||
assertTrue(isLocalAddress("http://tower:32400"))
|
|
||||||
assertFalse(isLocalAddress("https://73-21-104-9.0123abcd.plex.direct:32400"))
|
|
||||||
assertFalse(isLocalAddress("http://172.40.1.2:32400"))
|
|
||||||
assertFalse(isLocalAddress("https://plex.example.com"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun stackedPartsShareOneTimeline() {
|
|
||||||
val parts=listOf(Part("1","/a",emptyList(),duration=1000),Part("2","/b",emptyList(),duration=2000),Part("3","/c",emptyList(),duration=500))
|
|
||||||
assertEquals(0,partFor(parts,0));assertEquals(0,partFor(parts,999))
|
|
||||||
assertEquals(1,partFor(parts,1000));assertEquals(2,partFor(parts,3200))
|
|
||||||
// Past the end, or without durations, stays within the parts.
|
|
||||||
assertEquals(2,partFor(parts,9000))
|
|
||||||
assertEquals(0,partFor(listOf(Part("1","/a",emptyList())),5000))
|
|
||||||
assertEquals(0L,partStart(parts,0));assertEquals(3000L,partStart(parts,2))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun untitledChaptersAreNumberedFromOne() {
|
|
||||||
assertEquals("Chapter 1",Title.chapterTitle("",0))
|
|
||||||
assertEquals("Opening",Title.chapterTitle("Opening",3))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun versionDescriptions() {
|
|
||||||
val uhd=Media("1","mkv","hevc","eac3","4k",3840,2160,16808,listOf(Part("p","/k",listOf(Stream("a",2,"eac3","English","English (EAC3 7.1 Atmos)",true,"",8,1)),size=12_521_383_389)),"Dolby Vision",8)
|
|
||||||
assertEquals("4K · Dolby Vision · HEVC · EAC3 7.1 Atmos · 17 Mbps",uhd.description())
|
|
||||||
assertTrue(uhd.description(includeSize=true).endsWith("12.5 GB"))
|
|
||||||
assertEquals("1080p",Media("2","mp4","h264","aac","1080",1920,1080,0,emptyList()).resolutionLabel)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun searchGroupsFollowBrowsingOrder() {
|
|
||||||
val groups=searchGroups(listOf(title("episode","e"),title("show","s"),title("movie","m")),query="")
|
|
||||||
assertEquals(listOf("Movies","TV shows","Episodes"),groups.map{it.first})
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun seasonsNameTheirShow() {
|
|
||||||
val season=title("season").copy(title="Season 1",parentTitle="The 4400")
|
|
||||||
assertEquals("The 4400 · Season 1",season.displayTitle)
|
|
||||||
assertEquals("The 4400 · Season 2",season.copy(title="The 4400 · Season 2").displayTitle)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun speedLabels() {
|
|
||||||
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() {
|
|
||||||
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)
|
|
||||||
assertEquals("3",nextUp(listOf(watched,unwatched,started),80)?.id)
|
|
||||||
assertEquals("2",nextUp(listOf(watched,unwatched),80)?.id)
|
|
||||||
assertEquals("1",nextUp(listOf(watched),80)?.id)
|
|
||||||
assertNull(nextUp(emptyList(),80))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
package tv.kaleido.app
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class ReleaseNotesTest {
|
|
||||||
private val changelog="# Kaleido releases\n\n## 0.1.4\n\n- Smoother browsing.\n- Library focus.\n\n## 0.1.3\n\n- Aperture splash.\n"
|
|
||||||
|
|
||||||
@Test fun keepsOnlyTheReleasedVersionsSection() {
|
|
||||||
assertEquals("- Smoother browsing.\n- Library focus.",releaseNotes(changelog,"0.1.4"))
|
|
||||||
assertEquals("- Aperture splash.",releaseNotes(changelog,"0.1.3"))
|
|
||||||
}
|
|
||||||
@Test fun leavesNotesWithoutAMatchingHeadingIntact() {
|
|
||||||
assertEquals("- Only this release.",releaseNotes("\n- Only this release.\n","0.1.5"))
|
|
||||||
assertEquals(changelog.trim(),releaseNotes(changelog,"0.1.40"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
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 })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,76 +0,0 @@
|
||||||
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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1 +1 @@
|
||||||
2fd832eb90633d1519c15abccc122970a3c5ef51933da35634b8a5b1429d5bc3 Kaleido.apk
|
5cbfcb3048504ff7926850a46fc38a9a57118fe60fc2e1a356b508fe16a14da2 Kaleido.apk
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"version": "0.8.1",
|
"version": "0.1.2",
|
||||||
"versionCode": 25,
|
"versionCode": 3,
|
||||||
"url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.8.1/distribution/Kaleido.apk",
|
"url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.2/distribution/Kaleido.apk",
|
||||||
"checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.8.1/distribution/Kaleido.apk.sha256",
|
"checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.2/distribution/Kaleido.apk.sha256",
|
||||||
"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."
|
"notes": "0.1.2\n\n- Add navigation tap sounds with a persistent On/Off setting under Settings > Interface. Sounds default to On and follow the TV's system sound-effects setting.\n- Reduce Home hero-to-Continue Watching stutter by preparing nearby rows and retaining them across return navigation.\n- Include the navigation-sound focus paths in the baseline profile for optimized release navigation.\n"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,105 +0,0 @@
|
||||||
# Kaleido 0.1.11 polish audit — 2026-10-27
|
|
||||||
|
|
||||||
> **Status:** the bugs and polish items below, and the missing features marked in section 4, were addressed in **0.2.0**. See [runtime verification](runtime-verification.md) for what was and wasn't verified on a device.
|
|
||||||
|
|
||||||
Scope: a full read of `app/src/main` plus hands-on D-pad testing of the installed **release 0.1.11** on the onn (192.168.50.195). No code was changed and nothing was installed. Screenshots are in the ignored `evidence/private/audit-2026-10-27/` folder; file names are cited as *(shot: name)*.
|
|
||||||
|
|
||||||
Side effect: playing *Hazbin Hotel* S2·E2 for about three minutes moved its Plex resume point from 15 to 18 minutes. The app was left on Home.
|
|
||||||
|
|
||||||
Labels: **Verified** = reproduced on the TV. **Code** = confirmed by reading the source but not exercised on the TV.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Major bugs
|
|
||||||
|
|
||||||
| # | Area | Finding | Evidence |
|
|
||||||
|---|---|---|---|
|
|
||||||
| M1 | Search | **You can't reach search results with the D-pad.** Once the search field has focus, Down, Right and the keyboard's Done key all leave focus in the field. Back is the only way out, and it leaves Search for Home. On a remote, Search is effectively unusable. `SearchScreen` has no focus link from the `OutlinedTextField` to the grid, and the field consumes the arrow keys. No UI script covers Search (`verify_ui.py` has no search step). | Verified with `uiautomator` focus dumps after Down/Down/Right *(shots: search4, search5, ime)* |
|
|
||||||
| M2 | Home | **One Back press from anywhere in the Home rows exits the app.** Pressing Back with focus four rows down went straight to the launcher. Most TV apps first return focus to the top (hero/tabs) and only exit from there. `KaleidoViewModel.back()` returns `false` on Home regardless of scroll position. | Verified *(shots: rows → back1)* |
|
|
||||||
| M3 | Playback | **Only the first media version and the first part are ever used.** Everything uses `item.media.first()` / `parts.first()` (`Playback.kt`, `PlexApi.transcodeParams` with `mediaIndex=0`/`partIndex=0`). A movie with 4K and 1080p versions can't be switched, and a stacked multi-part movie (CD1/CD2) stops after part 1. | Code |
|
|
||||||
| M4 | Connection | **The stored server address is never re-discovered.** `initialize()` only validates the saved `session.server` URL. If the server's LAN IP changes, the TV leaves the LAN, or a plex.direct address rotates, startup shows "Cannot load this server" until the user opens Settings → Choose server. The official app retries every connection from `plex.tv/api/v2/resources`. | Code |
|
|
||||||
|
|
||||||
## 2. Functional bugs
|
|
||||||
|
|
||||||
| # | Area | Finding | Evidence |
|
|
||||||
|---|---|---|---|
|
|
||||||
| F1 | Player | **Chapter names are off by one.** The first chapter appears as "Chapter 2 · 0:00". `Models.kt` builds the fallback title as `Chapter ${index+1}`, but Plex chapter `index` is already 1-based. | Verified *(shot: chapters)* |
|
|
||||||
| F2 | Player | **Track lists don't open at the current item.** In the Chapters list at 18:35, focus opened on the first chapter. `TrackOption` gives initial focus only to the selected row, which `LazyColumn` hasn't composed while it's off-screen, so the list never scrolls to it. The same applies to long subtitle lists (this episode has more than 7 languages). | Verified *(shot: chapters)* |
|
|
||||||
| F3 | Player | **"Playback options" shows a checkmark on its first row** ("✓ Quality · Original quality"), as if it were a selected choice. `PlaybackOptions` passes `selected=0` to `TrackPanel`. | Verified *(shot: opts)* |
|
|
||||||
| F4 | Player | **"Chapters" is always listed**, even for titles with no chapters. It then opens a panel that says "No tracks available". | Code |
|
|
||||||
| F5 | Details | **After playback, focus returns to the Back arrow instead of Resume/Play.** | Verified *(shot: afterplay)* |
|
|
||||||
| F6 | Home | **Season items in "Recently Added TV" are labelled only "Season 1"**, with no show name or subtitle. `BrowseCard` uses `displayTitle`, which equals `title` for seasons. (`recentSeasons` adds the show name for the TV tab, but Home's `/hubs` items don't get it.) | Verified *(shot: rows)* |
|
|
||||||
| F7 | Movies/TV | **A second movie or TV library is only half supported.** The library switcher appears only in the A–Z view, and Discover always shows the first library. `chooseSection` doesn't reset `unwatched`, doesn't build the "New seasons" row and isn't cached. Changing tabs drops back to the first library. | Code |
|
|
||||||
| F8 | Player (movies) | **A finished movie sits on its last frame.** Post-play only runs for episodes, and auto-hide requires `isPlaying`, so the player stays open with its controls showing. The official app returns to the details page. | Code |
|
|
||||||
| F9 | Errors | **"Try again" doesn't retry what failed.** `ErrorDialog` calls `vm.retry()`, which reloads the page. After a failed `play()` or Mark watched, it reloads instead of retrying the action. | Code |
|
|
||||||
| F10 | Movie details | **Down from Play lands on the second cast member** (Jessica Biel), not the first. Geometric focus search picks the nearest card. | Verified *(shot: mdetail2)* |
|
|
||||||
| F11 | Details | **Restoring focus to Cast doesn't work on movie pages.** When returning from an actor page to a movie, the scroll target for `cast:` is only computed when `vm.children` is non-empty (shows). | Code |
|
|
||||||
| F12 | Playback | **Every conversion request says `location=lan`**, and Original quality always tries the source file first. On a remote or relay connection, that means a full-bitrate direct play with no remote-quality limit. | Code |
|
|
||||||
| F13 | Misc | `selectServerStream` catches `Exception` without rethrowing `CancellationException`, unlike the rest of the codebase. | Code |
|
|
||||||
|
|
||||||
## 3. Polish and UX
|
|
||||||
|
|
||||||
| # | Area | Finding | Evidence |
|
|
||||||
|---|---|---|---|
|
|
||||||
| P1 | Browse | **The focus ring is nearly invisible on light posters.** Discover/Home poster cards show focus only as a 2 dp white border and a slight text-colour change, with no scale. On *Toy Story 5*, focus couldn't be seen; a dump confirmed it was there. (`MediaTile` in the A–Z grid does scale; `BrowseCard` doesn't.) | Verified *(shot: s8)* |
|
|
||||||
| P2 | Home | **Card captions are hard to read over bright backdrops.** Row captions sit directly on the full-bleed backdrop (e.g. "Fire Country S5 · E3"). | Verified *(shot: rows)* |
|
|
||||||
| P3 | Season page | **The season page doesn't show the show name.** The header says only "Season 1". | Verified *(shot: season)* |
|
|
||||||
| P4 | Season page | **Season episodes are hard to scan.** Each episode card repeats the show name ("The 4400") as its title and puts the episode name in small subtitle text. There are no synopses, runtimes or air dates, and episodes sit in a horizontal row. | Verified *(shot: season)* |
|
|
||||||
| P5 | Episode page | **The episode page is a dead end.** It has no link to its show or season and no list of neighbouring episodes. | Verified *(shot: epdetail)* |
|
|
||||||
| P6 | Search | **Results aren't grouped or ranked by type.** "silo" returned 32 results, mostly Silo episodes in server order. There are no Movies/Shows/Episodes groups and no actor results. | Verified *(shot: search4)* |
|
|
||||||
| P7 | Skip intro | **Skip intro/credits takes several presses.** OK while it's showing reveals the controls instead of skipping. Reaching the button takes Up→timeline→Up, and there's no auto-skip option. | Code + `repro_runtime.py credits` key path |
|
|
||||||
| P8 | Settings | **The Connection page says "Sign in with Plex" while already signed in.** "Switch account" would be clearer. It also doesn't show the server address or connection type (local/remote/relay). | Verified *(shot: settings)* |
|
|
||||||
| P9 | Navigation | **Back from Search or Settings always goes to Home**, not the tab you came from. | Verified |
|
|
||||||
| P10 | Details | **"Resume · 15 min" reads like "15 minutes left".** "Resume from 15:02" or "13 min left" would be unambiguous. | Verified *(shot: epdetail)* |
|
|
||||||
| P11 | Details | **The media line is thin.** It shows "4K · AV1 · EAC3", with no HDR/Dolby Vision, channel layout (5.1/Atmos), file size or bitrate. | Verified *(shot: mdetail)* |
|
|
||||||
| P12 | Player | **The player shows no clock or "Ends at" time.** The episode name is in very small (10 sp) text. | Verified *(shot: play3)* |
|
|
||||||
| P13 | Player | **The Options menu repeats the Audio and Subtitles buttons**, and speed reads "1.0×". | Verified *(shot: opts)* |
|
|
||||||
| P14 | Browse | **Partly watched movies show no progress bar on poster cards.** `BrowseCard` draws progress only for landscape cards. | Code |
|
|
||||||
| P15 | Browse | **Hub rows can't be expanded.** They're capped at 18 items (`count=18`) and have no "View all". | Code |
|
|
||||||
|
|
||||||
## 4. Missing features compared with the official Plex Android TV app
|
|
||||||
|
|
||||||
Music is excluded, since it's deliberately left out. Items marked † may also be intentional omissions; I've listed them so you can decide.
|
|
||||||
|
|
||||||
**Browsing and library**
|
|
||||||
|
|
||||||
- An A–Z jump bar or letter picker. 272 TV titles and the movie library page in 100 at a time with no shortcut.
|
|
||||||
- Collections and playlists. `PlexApi.collections()` exists but nothing calls it. There are no collection or playlist tabs.
|
|
||||||
- Richer filters and sorts: year/decade, resolution, content rating, critic rating, last viewed, date added (oldest first).
|
|
||||||
- *(Added in 0.2.0)* Card context actions (long-press / Menu): Mark watched, Remove from Continue Watching, Go to show/season.
|
|
||||||
- *(Added in 0.2.0)* Extras and trailers. `details()` requests `includeExtras=1`, but nothing displays them, and there's no Trailer button.
|
|
||||||
- Director, writer and studio credits on detail pages.
|
|
||||||
- Theme music on show pages.†
|
|
||||||
- Photo libraries. `sections()` filters to movie/show only.†
|
|
||||||
- Watchlist and Plex's online "Discover" content, Live TV/DVR.†
|
|
||||||
|
|
||||||
**Playback**
|
|
||||||
|
|
||||||
- *(Added in 0.2.0)* A version picker for multiple media versions (see M3).
|
|
||||||
- Choosing audio and subtitles before playback, on the details page.
|
|
||||||
- Refresh-rate and resolution matching. Nothing sets the frame-rate strategy or display mode; Media3's default only switches when the change is seamless. This onn exposes a single 4K59.94 mode, so it couldn't be tested here.
|
|
||||||
- *(Size and style added in 0.2.0)* Subtitle appearance (size, colour, background, position) and subtitle sync offset; audio boost and night mode.
|
|
||||||
- Preferences for default audio/subtitle language and automatic subtitle selection.
|
|
||||||
- *(Added in 0.2.0)* Autoplay-next on/off and countdown length. The post-play countdown is fixed at 5 seconds and can only be cancelled each time.
|
|
||||||
- *(Added in 0.2.0)* Auto-skip intros and credits.
|
|
||||||
- *(Added in 0.2.0)* A separate quality limit for remote connections (see F12).
|
|
||||||
|
|
||||||
**Accounts and the platform**
|
|
||||||
|
|
||||||
- Plex Home / managed-user switching, with PIN entry.
|
|
||||||
- *(Voice and system search added in 0.2.0)* Android TV home integration: Watch Next / Continue Watching channel, recommendation channels, and voice or global search (`SEARCH` intent). The manifest has only the launcher intent.
|
|
||||||
- Deep links into titles (from other apps or the system search).
|
|
||||||
|
|
||||||
## 5. Areas that held up well
|
|
||||||
|
|
||||||
- Hero, Continue Watching, Movies/TV Discover and the A–Z grid rendered correctly with stable card bounds, and focus came back correctly from details pages.
|
|
||||||
- Direct-play H.264/EAC3 started quickly. Resume position, timeline sync, ±10 s taps, and the subtitle, audio, options and chapter panels all opened and closed with Back as expected.
|
|
||||||
- Mark watched/unwatched, cast → actor pages, related titles, the Synopsis dialog, the update flow, and settings categories behaved as designed.
|
|
||||||
- The updater checks the host and checksum and compares signing certificates, and the session is encrypted with Android Keystore.
|
|
||||||
|
|
||||||
## 6. Suggested priority
|
|
||||||
|
|
||||||
1. **M1** (Search unreachable), **M2** (Back exits), **F6/P3/P4** (missing show names), **F1–F3** (player menus).
|
|
||||||
2. **M4** (reconnect), **M3** (versions/parts), **F7** (multiple libraries), **F8** (movie end), **P1** (focus visibility).
|
|
||||||
3. Missing features, starting with an A–Z jump bar, card context actions, Watch Next integration, collections, and subtitle/autoplay preferences.
|
|
||||||
4. Add a Search step to `verify_ui.py browse`, since nothing currently exercises it.
|
|
||||||
|
|
@ -5,18 +5,14 @@ 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, 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.
|
- 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.
|
||||||
- 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.
|
- Features use original Plex clear-logo artwork within 264 × 80 dp, falling back to title text. Detail title: 34/37 sp. Library title: 29/34 sp. Discovery rail heading: 17/22 sp. Supporting information: 10/14 sp.
|
||||||
- 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.
|
|
||||||
- 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. 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 a cold-start aperture assembly. It uses muted sea-glass and warm ivory facets around a dark center, with no letterform or sparkle.
|
||||||
- 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).
|
||||||
|
|
||||||
## Focus and motion
|
## Focus and motion
|
||||||
|
|
@ -25,23 +21,18 @@ The interface gives artwork priority. App chrome uses neutral near-black, charco
|
||||||
- Text actions scale to 1.025 over 160 ms. Navigation uses text, an understated selected underline, and a translucent charcoal focus surface.
|
- Text actions scale to 1.025 over 160 ms. Navigation uses text, an understated selected underline, and a translucent charcoal focus surface.
|
||||||
- Navigation focus changes use Android's native UI tick. Settings > Interface > Navigation sounds toggles it immediately and persists across process restarts; it defaults to On and follows the TV's global sound-effects setting. Initial startup focus and repeated notifications for the same target are silent. The shared focus observer covers navigation, cards, buttons, dialogs, playback options and the timeline without changing key handling.
|
- Navigation focus changes use Android's native UI tick. Settings > Interface > Navigation sounds toggles it immediately and persists across process restarts; it defaults to On and follows the TV's global sound-effects setting. Initial startup focus and repeated notifications for the same target are silent. The shared focus observer covers navigation, cards, buttons, dialogs, playback options and the timeline without changing key handling.
|
||||||
- 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 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 navigation replaces the queued metadata target and cancels superseded artwork prefetches. 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 retain their existing list strategy. Card sizes, row targets and the large cinematic Home layout are unchanged.
|
||||||
- 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.
|
- 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. The cold-start sequence lasts 2.6 seconds: six light trails converge, the exact aperture facets assemble radially without spinning, a soft glow and facet glint settle, and the wordmark reveals letter by letter. Completion drives the cover dismissal, with up to 600 ms extra for loading followed by a 360 ms crossfade. 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.
|
|
||||||
- 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.
|
|
||||||
- Horizontal rows prepare one viewport ahead and retain half a viewport behind. New card artwork/text fills over up to three frames at fixed bounds. Horizontal focus commits on a frame boundary; a pending column accumulates rapid D-pad steps before committing the latest target, keeping accessibility layout work out of the gap between KeyDown and KeyUp.
|
|
||||||
- Horizontal presses less than 160 ms apart snap to the latest anchor and wait 70 ms before speculative metadata/artwork. Spaced presses retain the 140 ms scroll animation and immediate prediction.
|
|
||||||
- New seasons groups additions by Plex parent show ID, preserving newest-first order. Multiple seasons use the real show metadata and open its season list; single-season additions retain direct season navigation. The query samples 100 seasons before selecting up to 18 distinct shows, so one series import cannot occupy every card.
|
|
||||||
|
|
||||||
## Player
|
## Player
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
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. OK reveals them; Back hides them before exiting. Audio and subtitle panels open above their icons and restore focus when dismissed. A gear exposes playback mode, audio, subtitles, speed, transcode quality, and chapters. Direct stream is the saved default. The timeline includes buffered progress and server-generated video/chapter previews. Skip actions have opaque contrast surfaces.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
# Kaleido development
|
|
||||||
|
|
||||||
Build setup, release packaging and implementation notes. For app features and installation, see the [README](../README.md).
|
|
||||||
|
|
||||||
## Build on Windows
|
|
||||||
|
|
||||||
1. Run `scripts/bootstrap.py` with Python 3 to download an isolated JDK 17, Gradle 8.13, and Android command-line tools under `.tools/`.
|
|
||||||
2. Set `JAVA_HOME` to the extracted JDK directory and run `.tools/sdk/cmdline-tools/latest/bin/sdkmanager.bat --sdk_root=<absolute .tools/sdk path> "platforms;android-36" "build-tools;35.0.0"`. Accept the SDK license when prompted.
|
|
||||||
3. Run `./Build.ps1 -Test` for the debug APK, unit tests, and lint. Run `./Build.ps1 -Release` for the optimized release APK.
|
|
||||||
|
|
||||||
Open the project root in Android Studio to use an existing local Android SDK instead. Set `ANDROID_HOME` and use the bundled Gradle distribution or the wrapper.
|
|
||||||
|
|
||||||
The first local build creates `.tools/kaleido-signing.jks`. **Keep a private backup of this file and its credentials. Every app update must use the same signing key.** Debug and release builds share this local key so the test installation can receive the release through the updater. CI uses an ephemeral validation key and publishes only the locally signed distribution APK. For alternate signing, set `KALEIDO_KEYSTORE`, `KALEIDO_STORE_PASSWORD`, `KALEIDO_KEY_ALIAS`, and `KALEIDO_KEY_PASSWORD`.
|
|
||||||
|
|
||||||
## Connect
|
|
||||||
|
|
||||||
Open Kaleido and enter its code at [plex.tv/link](https://plex.tv/link). Settings → Sign in with Plex can link an account while keeping the current connection until successful server selection; Back cancels linking. Choose a server if more than one is available. The client tests the discovered server connections and prefers TLS. A manual server URL / token connection is also available. The credentials are AES-GCM encrypted with an Android Keystore key, never backed up, and removed on sign-out. Local HTTP servers remain supported. Account tokens are sent only to Plex account endpoints; server tokens are sent to the selected Plex server.
|
|
||||||
|
|
||||||
`.env` and signing keys are ignored by Git. No test credentials are included in source code, BuildConfig, resources, or APKs. `scripts/device.py seed` is an optional debug-only provisioning helper: it sends `.env` credentials to private app data over the already-authorized ADB connection. Kaleido immediately encrypts them and deletes the staging file. Release builds never read this staging file.
|
|
||||||
|
|
||||||
## Remote and playback
|
|
||||||
|
|
||||||
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. 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
|
|
||||||
|
|
||||||
Kaleido checks [the public repository releases](https://git.elijahkuntz.com/Elijah/Kaleido/releases) on launch and foreground entry, at most once per six hours. Settings offers an immediate check. It downloads the release APK over HTTPS, checks its supplied SHA-256 when available, and verifies the package name, increasing Android version code, and installed signing certificate before opening Android's package installer. Android requires a one-time “allow from this source” permission and confirmation for each installation.
|
|
||||||
|
|
||||||
To publish a version:
|
|
||||||
|
|
||||||
1. Increment **both** fields in `version.properties` and update `CHANGELOG.md`.
|
|
||||||
2. Run `./Build.ps1 -Release -Test`, then `python scripts/package_release.py`.
|
|
||||||
3. Commit the source and `distribution/`, push `main`, and push the matching `v<versionName>` tag.
|
|
||||||
|
|
||||||
The Forgejo workflow builds, tests, and lints the source, verifies the prebuilt signed distribution, then publishes its APK and checksum using Forgejo's repository-scoped token. The private production signing key never leaves the developer machine. The checked-in APK also provides a repository-file update channel, with an immutable tag URL in `distribution/latest.json`, for installations before the first Forgejo release is ready.
|
|
||||||
|
|
||||||
## Structure and references
|
|
||||||
|
|
||||||
`PlexApi.kt` owns Plex transport and server-relative API calls; `SecureSession.kt` owns credential encryption; `KaleidoViewModel.kt` owns navigation and async screen data; `Screens.kt` and `Theme.kt` implement the TV UI; `Playback.kt` owns Media3, stream negotiation, track selection, lifecycle, and timeline reporting; `AppUpdater.kt` verifies updates. Artwork has bounded memory and disk caches. Library data is paged in batches of 100.
|
|
||||||
|
|
||||||
Implementation follows the [official Plex Media Server API](https://developer.plex.tv/pms/), [Android Compose guidance](https://developer.android.com/compose), and [Media3 documentation](https://developer.android.com/media/media3). This is an independent client, unaffiliated with Plex. No existing Plex client source is copied.
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
# Dedicated playback validation — 2026-10-26
|
|
||||||
|
|
||||||
This records the 0.1.9 baseline investigation. The subsequent 0.1.10 fixes and release checks are recorded in [runtime verification](runtime-verification.md).
|
|
||||||
|
|
||||||
Tested the onn 4K Plus (`192.168.50.195:5555`) connected to the TCL TV over HDMI, using 0.1.9 source plus opt-in debug instrumentation. These results describe this device chain and these fixtures. They are not a certification of every file, display, receiver, or Dolby profile.
|
|
||||||
|
|
||||||
## Main finding
|
|
||||||
|
|
||||||
The native file path can render 4K video and output multichannel audio, but the production **Original quality** path requests Plex HLS and unnecessarily converts the tested 4K sources. A 3840×2160 HEVC/AAC 5.1 source reached the player as 1920×1080 HEVC/AAC stereo. A 3840×1608 Dolby Vision profile 8/EAC3 7.1 source reached it as 1920×804 HEVC PQ/AAC stereo, losing Dolby Vision signaling. The latter was repeated with HDR formats fully enabled. Both files retained their source resolution/audio on forced native playback.
|
|
||||||
|
|
||||||
This is a fidelity failure even though converted playback starts and renders. The previous live HEVC remux integration test covers a different, 1080p episode; its passing result does not cover these 4K cases. No production playback negotiation fix or new release was published during this validation.
|
|
||||||
|
|
||||||
## HDR and Dolby Vision
|
|
||||||
|
|
||||||
Verification combines Media3 input format, the selected decoder, rendered-frame counters, the SurfaceView's compositor state, and the ONN HDMI transmitter/HWC status. Output signaling is stronger evidence than the server's decision or advertised capabilities. It still cannot establish panel calibration, correct tone mapping, or perceptual image accuracy remotely.
|
|
||||||
|
|
||||||
| Source | Observed native playback / HDMI output | Result |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| Dolby Vision profile 5, HEVC MP4, 1080p | `dvhe.05.03`, Dolby Vision HEVC decoder, rendered test pattern; `DolbyVision-Std` | Rendering and signaling pass; local fixture, Plex delivery untested |
|
|
||||||
| Dolby Vision profile 8, HEVC MKV, 4K | `dvhe.08.06`, Dolby Vision HEVC decoder; `DolbyVision-Std` | Rendering and signaling pass |
|
|
||||||
| Dolby Vision profile 10, AV1 MKV, 4K | `dav1.10.08`, Dolby Vision AV1 decoder; `DolbyVision-Std` | Rendering and signaling pass |
|
|
||||||
| HDR10, HEVC MP4, 4K | BT.2020/PQ input, HEVC hardware decoder; `HDR10-GAMMA_ST2084` | Rendering and signaling pass with Dolby Vision temporarily excluded |
|
|
||||||
| HDR10, AV1 MKV, 4K | BT.2020/PQ input with mastering metadata, AV1 hardware decoder; `HDR10-GAMMA_ST2084` | Rendering and signaling pass with Dolby Vision temporarily excluded |
|
|
||||||
| HLG, HEVC MKV, 4K | HLG input, HEVC hardware decoder; `HDR10-GAMMA_HLG` | Rendering and signaling pass under the original HLG-priority policy |
|
|
||||||
| Dolby Vision profile 7 candidate | Frames rendered, but source advertises contradictory BT.709/SDR metadata | Inconclusive; not a valid reference for profile 7 enhancement-layer fidelity |
|
|
||||||
| HDR10+ dynamic metadata | No independently identified reference tested | Not covered |
|
|
||||||
|
|
||||||
The initial ONN configuration manually disabled Dolby Vision and HDR10. Clearing Android's disabled-format list, and even selecting Automatic, did **not** update its vendor `HLG priority` policy. That policy produced SDR for tested Dolby Vision inputs and HLG for a PQ source. Toggling Dolby Vision off/on through the normal manual-format UI updated the vendor policy to `DV_HDR10_HLG priority`, after which profile 5/8/10 output was confirmed as Dolby Vision. Excluding Dolby Vision while leaving HDR10 enabled selected `HDR10_HLG priority` and allowed isolated HDR10 checks. With System-preferred conversion, a HDR10 source can otherwise leave the device as Dolby Vision; that is device conversion and must be distinguished from the input format.
|
|
||||||
|
|
||||||
The profile 5 fixture is Dolby's unencrypted [official color pattern](https://ott.dolby.com/OnDelKits/DolbyVision_OSS_Media_Kit/clear/color_pattern_24_dvhe_05_1920x1080.mp4), verified locally as profile 5 with compatibility ID 0. It was copied into Kaleido's private debug fixture directory and exercised through the same controller and SurfaceView. It was not uploaded to the Plex library. The HDMI status strings also correspond to the [Amlogic transmitter implementation](https://nest-open-source.googlesource.com/manifest_repos/kernel/+/1650886512330522da41d487bb2ce75fd5da5ec8/drivers/amlogic/media/vout/hdmitx/hdmi_tx_20/hdmi_tx_main.c).
|
|
||||||
|
|
||||||
## Other video and audio
|
|
||||||
|
|
||||||
Native rendering passed for AVC 8-bit and a 10-bit AVC candidate, HEVC 8/10-bit SDR, AV1 HDR, VP9, and MPEG-4 Part 2. MP4, MKV, and AVI were exercised. Source resolutions ranged from SD to 4K. The VC-1 MKV sample advanced audio without producing a video format or rendered frame during a 55-second observation. **Normal Plex playback of that same sample converted it to 1080p HEVC/AAC and rendered successfully.** It is not counted as native VC-1 support.
|
|
||||||
|
|
||||||
| Audio source | Observed player output | Result / limit |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| AAC, including 5.1 | PCM 16-bit, including six-channel output | Played |
|
|
||||||
| AC3 | AC3 bitstream, stereo / 5.1 fixtures | Played; output position advanced |
|
|
||||||
| EAC3, including 7.1 and an Atmos-tagged fixture | EAC3 bitstream, six/eight channels | Played; receiver Atmos/object decoding not verified |
|
|
||||||
| DTS | DTS bitstream, 5.1 | Played; output position advanced |
|
|
||||||
| DTS-HD Master Audio | DTS-HD input selected, **DTS core** output | Compatible playback; full DTS-HD passthrough not demonstrated |
|
|
||||||
| TrueHD, Atmos-tagged 7.1 | TrueHD bitstream accepted by AudioTrack | Played; receiver sound and Atmos/object decoding not verified |
|
|
||||||
| FLAC stereo, Vorbis 5.1, Opus 7.1 | PCM output with corresponding channel counts | Played; no bit-perfect claim |
|
|
||||||
| MP2 / MP3 | PCM stereo | Played |
|
|
||||||
| Generated 16-bit / 48 kHz stereo WAV | PCM 16-bit / 48 kHz stereo | Played; local fixture |
|
|
||||||
| Generated 24-bit / 96 kHz mono WAV | Failed before AudioTrack initialization | Reproduced `ERROR_CODE_FAILED_RUNTIME_CHECK`; `getAudioTrackMinBufferSize` check failed during output configuration. Other high-resolution PCM combinations remain untested |
|
|
||||||
|
|
||||||
One 4K AV1/TrueHD run sustained 61.8 seconds after playback began, rendering 1,475 frames with one dropped frame and no subsequent buffering samples. Most other matrix cases observed approximately 10–12 seconds of steady playback. This is a compatibility sweep, not a feature-length soak or perceptual lip-sync test. Initial native-file probes encountered HTTP-status fallbacks; later repeated native probes succeeded. The initial HTTP status was not captured, so transport reliability is not certified by the later passes.
|
|
||||||
|
|
||||||
Pause, three backward 10-second seeks, resume and exit passed for native Dolby Vision and the Plex HLS path. The HLS test crossed the original start offset and reached the correct absolute position without doubling the resume offset. No tested Plex item's watched count, last-viewed timestamp, or resume position changed.
|
|
||||||
|
|
||||||
## TCL HDMI observation
|
|
||||||
|
|
||||||
A debug-only `TvView` activity tuned the verified HDMI 1 hardware input through Android's public TV Input Framework. TCL reported `videoAvailable` and a 3840×2160/60 input. Its standard ADB screenshot attempts while HDMI was active produced no usable image, including a failed file-based capture. The vendor track extras did not provide a dependable changing HDR indication. Thus **ADB via this TCL is not a reliable capture of the actual HDMI picture**. No capture-protection bypass was attempted. The confirmed HDR output results above use ONN transmitter/HWC diagnostics; they do not replace a physical screen/receiver check.
|
|
||||||
|
|
||||||
## Reproduction and evidence
|
|
||||||
|
|
||||||
`scripts/inventory_playback.py` inventories actual Plex metadata. `scripts/validate_playback.py` cold-launches one case at a time, records delivered formats/decoder counters/audio output, optionally seeks, closes the player, and verifies unchanged Plex progress. `--mode 0` forces a native file, `--mode -1` follows the saved production preference, and `--observe-hdmi` reads an already tuned TCL observer. Local `--fixture` files require matching Title-style JSON metadata and explicitly bypass Plex delivery. A fixture failure does not request a Plex conversion for that synthetic ID.
|
|
||||||
|
|
||||||
Validation is debug-only and opt-in. It suppresses timeline/scrobble writes while retaining normal playback otherwise. The capability inventory exports no credentials. Telemetry excludes URLs, headers, tokens, and exception messages; raw source metadata and captures stay under ignored `evidence/private/playback-validation/`. A missing video track on a movie is a failure, not an audio-only pass. A blank ADB HEVC capture alone is not a failure when decoder counters demonstrate rendering.
|
|
||||||
|
|
||||||
`assembleDebug testDebugUnitTest lintDebug` passed (five unit tests), as did Python compilation and `git diff --check`. Playback failures and limitations above are recorded test outcomes, not passing checks. The signed 0.1.9 release remains the published update; validation instrumentation is local work.
|
|
||||||
|
|
||||||
The original HDR state was restored through the manual-format UI and verified: `user_disabled_hdr_formats=1,2`, `are_user_disabled_hdr_formats_allowed=0`, `hdr_conversion_mode=2`, `hdr_force_conversion_type=-1`. The vendor policy returned to `HLG priority`; a final HLG run rendered and reported `HDR10-GAMMA_HLG`. Dolby Vision and HDR10 are therefore disabled again, matching the user's original setup.
|
|
||||||
|
|
||||||
The temporary on-device fixtures and telemetry were removed. Both ONN and TCL were reinstalled in place with the original published, non-debuggable 0.1.9 APK (version code 10; SHA-256 `ddc9b089bd02aaa0e636e27786159d86419dba8eba8e9995a569a3a9902b576b`). Both confirmed ART `speed-profile` compilation. Sessions and app data were retained.
|
|
||||||
|
|
@ -1,103 +1,7 @@
|
||||||
# Device regression review - 2026-10-23
|
# Device regression review - 2026-10-23
|
||||||
|
|
||||||
For the 2026-10-26 codec/HDR sweep and its native-versus-converted playback findings, see [Dedicated playback validation](playback-validation-2026-10-26.md). It includes confirmed Dolby Vision/HDR10/HLG signaling, audio output limits, the TCL HDMI capture limitation, and the restored HDR settings.
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
- 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.
|
|
||||||
- The shown episode is kept per page in the ViewModel. Back from playback shows the last episode played and reloads the season's progress; focus returns to the card you played, or to Play when playback started there. Recording focus whenever the action row gained focus broke related-title focus restoration (`verify_details.py`), so only Play/Start over clicks record it.
|
|
||||||
- Go to show left the season/episode header (it stays in quick actions). `ActionButton` primary actions are a tint until focused.
|
|
||||||
- Verified on the onn with Cyberpunk: Edgerunners and the Silo fixtures (Play → 8594, card → 7604, return focus, Back to the show), `verify_ui.py browse` and `player`, `repro_runtime.py controls/episode/postplay/credits/sections/browse` (profiled release median 16 ms / p95 36 ms), `verify_details.py`, `verify_details_layout.py`, `verify_movie_details.py`, `verify_settings.py` and the unit tests. `verify_details_layout.py` now moves right until Synopsis (the fixture gained a Trailer button), and `verify_settings.py` accepts the saved Remote quality and Subtitle style rather than requiring defaults.
|
|
||||||
|
|
||||||
## 2026-10-27 audit fixes, quick actions, extras, voice search and new settings (0.2.0)
|
|
||||||
|
|
||||||
Addresses the findings in [the 0.1.11 audit](audit-2026-10-27.md).
|
|
||||||
|
|
||||||
- Search had no remote path from the text field to its results and was untested. Down, Right-at-end and the keyboard's Search action now leave the field; results are grouped rows (Movies, TV shows, Seasons, Collections, Episodes, People). `verify_ui.py browse` gained a Search step (type, keyboard Search, open a result, Back restores it, Back returns to the previous tab). The microphone uses Google TV's `com.google.android.katniss` voice input directly; the onn otherwise shows a recognizer chooser. `ACTION_SEARCH` intents open Search with their query.
|
|
||||||
- Back from Home rows now focuses the hero (Discover on Movies/TV) before exiting. Focus must move before the list scrolls, or the removed card clears it.
|
|
||||||
- A `focusRestorer()` without a fallback overrode explicit `down` targets and chose the geometrically nearest card (e.g. the second cast member below Play). Rows now pass their entry card as the fallback.
|
|
||||||
- Long-press OK / Menu actions use a `Modifier.Node`. A `composed {}` modifier and a per-card focus animation on every Home card measurably slowed browsing (median 25 ms / p95 38 ms); with the node and a layer-only lift, five profiled-release runs of `repro_runtime.py browse` measured median 15–17 ms and p95 29, 32, 32, 38 and 46 ms. Four met the <40 ms target; the variance is device noise around the 0.1.11 record (15 ms / 27 ms). The baseline profile now covers `ScreensKt`, the actions node, `Title` and `Media`.
|
|
||||||
- Moving the skip-marker lookup to the top of the player recomposed the whole player every position tick, re-applying subtitle styling and keeping the window from going idle. It is now `derivedStateOf`.
|
|
||||||
- `repro_runtime.py episode` and `credits` pressed Pause at a fixed 6–9 s after a cold launch and failed identically on 0.1.11 code; they now wait for the player's READY log like `controls`.
|
|
||||||
- Verified on the onn: all `verify_ui.py browse` (8) and `player` (7) checks, `verify_settings.py`, `verify_details.py`, `verify_details_layout.py`, `verify_movie_details.py`, `repro_runtime.py sections/controls/episode/postplay/credits/browse`, 25 instrumentation tests and 14 unit tests. Hands-on: actions sheet, season episode list, episode season row, Trailer playback ending back on the movie page, View all, chapter numbering, the Version picker on the server's one two-version episode, voice input and the subtitle preview.
|
|
||||||
- Not verified on a device: remote-connection quality (no remote connection here; `isLocalAddress` is unit-tested), stacked multi-part playback (no such files on the server), automatic server re-discovery after an address change, and subtitle styles over real subtitles in playback (the Settings preview uses the player's own `SubtitleView`).
|
|
||||||
|
|
||||||
## 2026-10-27 movie details and foreground library sync (0.1.11)
|
|
||||||
|
|
||||||
- Movies now share TV shows' fitted poster, cinematic backdrop and safe header; related movie cards come from Plex's related metadata endpoint, below Cast.
|
|
||||||
- Foreground sync checks the small `/library/sections` revision response every 15 seconds. Content changes trigger a staged Home/active-section refresh, with a 60-second fallback for servers without useful revision fields. Current filters and loaded range survive. No loading overlay is shown, and unchanged state compares equal to avoid unnecessary UI updates. Playback/background pause the loop; connection failures back off to 60 seconds.
|
|
||||||
- Home feature selection keeps the same random seed for the current process, avoiding reshuffling unchanged content on each refresh. Browse rails and focus requesters use stable hub/title IDs across updates; removing a focused title selects a nearby surviving card.
|
|
||||||
- Seven unit tests passed, including revision changes, unchanged-library polling, fallback refreshes and retries after failed/superseded updates. `LibrarySyncIntegrationTest` passed on the onn in 42 seconds: its local HTTP fixture changes revision/content and the real ViewModel timer updates Home and the active movie library without a restart. It substitutes only the API's in-memory endpoint, restoring it afterward; it does not import/delete media on Plex or overwrite the encrypted session. This validates the client refresh path, not a real server scan/import event.
|
|
||||||
- `scripts/verify_movie_details.py` passed against real Plex content on the profiled release: safe movie header and initial action focus, related movies, opening a related title, and Back restoration. Screenshots `movie-details-0.1.11.png` and `movie-related-0.1.11.png` were inspected for fitted artwork and readable rows. Release build and lint passed; existing lint warnings remain. No playback or broad navigation sweep was needed for these changes.
|
|
||||||
|
|
||||||
## Browsing
|
## Browsing
|
||||||
|
|
||||||
- Cold-start switching to Movies reproduced an empty page: tab loading cancelled server initialization before library discovery finished. Initialization now has its own job; section requests update their cache and visible results atomically. `scripts/repro_runtime.py sections` passes the same startup switch, TV loading and cached Movies return.
|
- Cold-start switching to Movies reproduced an empty page: tab loading cancelled server initialization before library discovery finished. Initialization now has its own job; section requests update their cache and visible results atomically. `scripts/repro_runtime.py sections` passes the same startup switch, TV loading and cached Movies return.
|
||||||
|
|
@ -166,102 +70,3 @@ For a quiet device with system effects already enabled, run `python -c "import s
|
||||||
Private evidence includes `home-baseline-results.json`, `home-trace-baseline-atrace.txt`, `home-complete-results.json`, `home-complete-cold-results.json`, `navigation-audio-results.json`, `navigation-audio-off-atrace.txt`, `navigation-audio-on-atrace.txt`, and the On/Off setting screenshots. `Build.ps1 -Release -Test` passed with three unit tests and zero lint errors. These measurements were taken on the local optimized test build before versioning the changes as 0.1.2. The installed test build retains the existing session and was left on Home with navigation sounds On.
|
Private evidence includes `home-baseline-results.json`, `home-trace-baseline-atrace.txt`, `home-complete-results.json`, `home-complete-cold-results.json`, `navigation-audio-results.json`, `navigation-audio-off-atrace.txt`, `navigation-audio-on-atrace.txt`, and the On/Off setting screenshots. `Build.ps1 -Release -Test` passed with three unit tests and zero lint errors. These measurements were taken on the local optimized test build before versioning the changes as 0.1.2. The installed test build retains the existing session and was left on Home with navigation sounds On.
|
||||||
|
|
||||||
All six `verify_ui.py browse` checks passed with the sound setting and cache window, including focus restoration, separate Movies/TV layouts, A–Z grids and PIN cancellation preserving the session. The broader `repro_runtime.py browse` check initially failed at p95 42 ms (48 ms with tracing), with further card composition/measurement during rapid movement. Including the new sound modifier/controller in the app's baseline profile brought the final profiled release to median 15 ms / p95 36 ms, GPU p95 7 ms, and stable horizontal Y coordinates at 182 px. Some stress-test frames still miss 60 Hz. `browse --trace` now records this exact regression loop to `browse-regression-atrace.txt` for future diagnosis.
|
All six `verify_ui.py browse` checks passed with the sound setting and cache window, including focus restoration, separate Movies/TV layouts, A–Z grids and PIN cancellation preserving the session. The broader `repro_runtime.py browse` check initially failed at p95 42 ms (48 ms with tracing), with further card composition/measurement during rapid movement. Including the new sound modifier/controller in the app's baseline profile brought the final profiled release to median 15 ms / p95 36 ms, GPU p95 7 ms, and stable horizontal Y coordinates at 182 px. Some stress-test frames still miss 60 Hz. `browse --trace` now records this exact regression loop to `browse-regression-atrace.txt` for future diagnosis.
|
||||||
|
|
||||||
## Aperture startup animation - 2026-10-24
|
|
||||||
|
|
||||||
The cold-start splash was prototyped as a dp-accurate canvas page (ignored `evidence/private/splash/index.html`), approved, then ported to `StartupSplash.kt` with the same geometry, timings and cubic-bezier curves. The exit cuts the aperture's inner hexagon out of the splash surface with an even-odd path and zooms it about 52× in log space, so the real app beneath is revealed through the mark; the content layer scales from 1.14 to 1 only while the cover exists.
|
|
||||||
|
|
||||||
Frame statistics from three profiled release cold starts (`dumpsys gfxinfo framestats`, bucketed per 250 ms) first showed 100–125 ms frames about 0.3–0.7 s after launch: startup data arriving and Home composing beneath the splash, with high UI-thread time. Starting the animation a few frames late did not avoid them because they follow the data, not the first frame. Skipping the hidden app's draw until the exit made no measurable difference and was reverted. The final sequence instead runs a 260 ms light-gathering phase on the nearly still closed iris, then holds until `busy` clears and four consecutive frames arrive within 24 ms (capped at 700 ms). On the final build every frame from the iris opening through the start of the exit completed within 25 ms in all three runs, at 15 frames per 250 ms. Frames after the reveal include Home itself and show higher latency without dropping below 15 frames per bucket. These are device samples, not a guarantee.
|
|
||||||
|
|
||||||
The hold adds roughly 0.5 s before the iris opens when Plex data takes that long; loading previously overlapped the animation. `Build.ps1 -Release -Test` passed; `repro_runtime.py sections` passed and all six `verify_ui.py browse` checks passed on the final release. A screen recording of the actual cold start (`kaleido-aperture-startup.mp4`, contact sheet `aperture-sheet.png`) was inspected. The optimized release was left on Home.
|
|
||||||
|
|
||||||
## Browsing transitions on three devices - 2026-10-24
|
|
||||||
|
|
||||||
The user authorized two weaker devices alongside the onn: a Fire TV Stick 4K (AFTKM, Fire OS 8 / Android 11, 32-bit, 1.7 GB) and a TCL Smart TV Pro (MT5896, Android 14, 1080p UI on a 4K panel, slowest GPU). Each was provisioned with `device.py seed` on a debug build, then the optimized release was installed over it with `speed-profile` compilation. `scripts/profile_transitions.py` measures skipped vsyncs and UI-thread time for each D-pad transition from `gfxinfo framestats`; its first cycle is the first pass after launch, and gaps after fast frames or longer than 300 ms count as idle. `scripts/trace_transition.py` breaks a transition's slow UI frames into their nested atrace slices.
|
|
||||||
|
|
||||||
Findings:
|
|
||||||
|
|
||||||
- Top-tab switches were the worst stall everywhere: about 30 ms disposing the old section, then one 150 ms+ measure pass composing every visible card (Coil painters about 3 ms per card, text layout about 1.4 ms per label), while four Coil decoders and a young GC competed for four cores.
|
|
||||||
- Home's lookahead cache only fills after the list has scrolled, so the first hero → row move after launch composed the lower rows mid-animation. A screen recording on the onn showed a 204 ms freeze. Movies/TV had no cache window and skipped 1–2 frames on each row move.
|
|
||||||
- The onn runs two accessibility services (Button Mapper, Luma launcher), adding 1–3 ms of Compose semantics work per frame. Its steady frames are render-bound but drop nothing. These device settings were not changed.
|
|
||||||
- Converting contrast-baked backdrops to hardware bitmaps removed render-thread uploads but made the TCL's GPU skip 9–14 frames on Home row moves (0 with software bitmaps), so it was reverted. Explicit card image sizes and a staged-card build were also A/B tested.
|
|
||||||
|
|
||||||
Changes: staged card fill-in while a section enters, a cache window and one-time 1 px nudge on every discovery list, tab activation two frames after focus, the page entrance starting after composition settles with per-draw alpha, Coil decode parallelism 2, no redundant window background, explicit card image sizes, and no per-card restoration coroutine.
|
|
||||||
|
|
||||||
Results (skipped frames per cycle; UI-thread maximum):
|
|
||||||
|
|
||||||
| Transition | onn before → after | Fire Stick before → after |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| Home → Movies | 11/7/8, 160 ms → 9/3/6/6, 88 ms | 12/5/5, 153 ms → 8/3/2/2, 69 ms |
|
|
||||||
| Movies → Home | 7/6/5, 104 ms → 3/4/5/3, 67 ms | 4/3/4, 61 ms → 2/2/2/1, 52 ms |
|
|
||||||
| Movies row → row | 2/2/1 → 0/0/0/0 | 1/1/0 → 0/0/0/0 |
|
|
||||||
| Home hero/row moves | 0–1 per move, both before and after | 0 per move, both before and after |
|
|
||||||
|
|
||||||
On the TCL, Home → Movies measured 196 ms of UI time before and 88 ms in the one completed final sample. Its final full run was skipped at the user's request because its ADB link kept dropping; the partial final run and the A/B runs showed no regressions. Movies row ← row still skips two frames on the onn. Returning from Movies still disposes and composes whole sections. Retaining sections across tabs would remove that cost but needs per-section navigation state.
|
|
||||||
|
|
||||||
`Build.ps1 -Release -Test` passed. On the onn, all six `verify_ui.py browse` checks and `repro_runtime.py sections` passed. A recording confirmed the staged cards fill in under the fade without bound changes. The final release was left installed on all three devices. Private evidence: `transitions-*.json`, `transitions-*-frames.txt`, `trace-*.txt` and the `onn-*` recordings in `evidence/private/`.
|
|
||||||
|
|
||||||
## Settings update flow on the Fire Stick - 2026-10-24
|
|
||||||
|
|
||||||
The user found that pressing "Download & install" on the Fire Stick appeared to do nothing, and after cancelling the package installer every D-pad press in Settings opened Home. Cause: the button was removed while downloading, so focus was lost with it; with nothing focused, the next press searched from the top bar and focused (which opens) Home. On TV, Compose's default bring-into-view pinned focused controls near a third of the screen height, so sideways moves scrolled Settings, and focused/unfocused primary buttons were nearly the same white. Release bodies carried the whole changelog.
|
|
||||||
|
|
||||||
The update action now stays in place and reports progress ("Downloading… n%" plus a progress bar), then offers "Install" for the verified APK, which reopens the installer without downloading again. Returning from the installer refreshes the status and restores focus to the update actions if nothing is focused. Settings scrolls only far enough to keep the focused control 56 dp from the edges, and shows only the new version's notes above the buttons. `publish_release.py` and `package_release.py` publish just the version's changelog section; `releaseNotes()` trims older full-changelog bodies, with unit coverage.
|
|
||||||
|
|
||||||
Verified on the Fire Stick with a build labelled 0.1.3 against published 0.1.4: check, download, installer, Back, then Left/Up/Down/Right all stayed within Settings with focus on "Install 0.1.4". The LAN download takes under a second, so a throwaway build that slowed the download loop (not committed) was used to capture "Downloading… 8%" with the progress bar. Completing the in-app update itself was left to the user.
|
|
||||||
|
|
||||||
## Quality setting and silent skips - 2026-10-24
|
|
||||||
|
|
||||||
Playback mode and transcode quality are now one `StreamQuality` preference: Original quality (direct stream of the source video, falling back to a 1080p conversion) and 4K/1080p/720p/480p conversions, in Settings and the player gear. Earlier `playbackModeV2`/`quality` preferences migrate on first read. With the controls hidden, a Left/Right tap now only moves a pending seek (350 ms settle, so quick taps add up); a key repeat reveals the controls with the timeline focused. Play's initial focus no longer takes focus back after a timeline reveal.
|
|
||||||
|
|
||||||
On the onn, `verify_ui.py player` passed all seven checks, including two new ones: a Right tap skipped at least 9 s (projected from the Android media-session position) with no controls, and `input keyevent --longpress 22` revealed the focused timeline. `repro_runtime.py controls` passed. While video plays with controls visible, their clock updates keep `uiautomator` from dumping and it silently returns the previous hierarchy; the player checks now wait for the `READY` log line before pausing and inspect the screen while paused. A focus-loss theory based on those stale dumps was ruled out with a temporary focus log.
|
|
||||||
|
|
||||||
## Title information, cast and Settings - 2026-10-25
|
|
||||||
|
|
||||||
Cast cards use real Plex Role portraits, names, roles and server-local actor identifiers. Selecting an actor queries every accessible movie/show section with pagination. Series information keeps Seasons ahead of Cast and Plex's related-show hubs. The labelled watched actions use Plex scrobble/unscrobble, refresh descendants and preserve full metadata when merging summary records. Writes survive navigation and repeated submissions are ignored until the refresh completes.
|
|
||||||
|
|
||||||
`verify_details.py` passed on the optimized release on the onn: movie watched/unwatched persisted in Plex; John Cena's 13 titles matched results from both libraries; actor/title/cast return focus restored; marking the eight-episode series updated every episode; related shows opened and returned to the selected card. The harness validated initially unwatched, zero-resume fixtures (Matchbox `36486`, 3 Body Problem `16413`), then restored and rechecked both. It did not play content or alter existing resume points.
|
|
||||||
|
|
||||||
The TV show header initially moved its title to y=21 px when Compose's default TV bring-into-view pinned the focused action higher on screen. `verify_details_layout.py` reproduced that failure. The revised header uses a full-screen backdrop, fitted poster and top-aligned information; scrolling only reveals controls outside the viewport. The regression check passed with title bounds `[392,136,849,212]`, Back visible and Seasons first. Text shadows and a dark fade improve description/rating contrast; filled action buttons retain crisp text without that shadow.
|
|
||||||
|
|
||||||
Settings now uses Connection / Playback / Interface / Updates categories. The underlying account, preferences and signed-updater behavior are preserved. Raw captures and server-specific verification results remain in ignored `evidence/private/`; the README gallery contains reviewed screenshots from the release build.
|
|
||||||
|
|
||||||
Final 0.1.8 verification: `Build.ps1 -Release -Test` passed; `verify_settings.py` passed category focus, Original quality / 80% dialog cancellation, live update checking and sign-out cancellation. `verify_navigation_sounds.py` passed Off and On persistence across cold starts, leaving sounds On. All six `verify_ui.py browse` checks passed, including real Plex PIN cancellation. The final signed APK (version code 9) was installed in place and profile compiled; the encrypted session and playback preferences were retained. The app was returned to Home. The release gallery includes nine new 1920 × 1080 captures, encoded as lossless WebP and checked for pixel equality with their source PNGs.
|
|
||||||
|
|
||||||
## Show details, season grouping and remote navigation - 2026-10-26 (0.1.9)
|
|
||||||
|
|
||||||
Show information now uses a 248 dp minimum header, with the fitted poster starting at 56 dp and description width capped at 560 dp. On the onn, the 3 Body Problem title stays at `[392,112,849,188]`, Back remains visible, and the full Season 1 caption fits inside the first screen. Truncated text opens a near-black, poster-led Synopsis panel with the existing typography and circular close control. The release layout check passed opening, D-pad scrolling, Close, Back and restoration to Synopsis. Scrolled Cast screenshots show a near-black background: the header artwork fades completely over the first 180 dp of scrolling, while the lower-screen scrim is opaque.
|
|
||||||
|
|
||||||
New seasons samples 100 Plex season records, deduplicates by parent show ID, then selects up to 18 groups in recency order. Multiple seasons use the actual parent show's metadata and open its season list; single seasons still open directly. Identity/order/limit tests and the live Plex query passed. The TV screenshot shows one Punkin Chunkin card among the other shows.
|
|
||||||
|
|
||||||
A rapid Right/Down sequence reproduced a dropped Down press in 0.1.8. Tab activation waited two frames, and delayed initial-focus effects could reclaim focus after the next move. The release queues entry for the intended destination, records already-focused tabs, and enters the fixed Discover control without waiting for catalog resets. Rapid Movies/Down and TV/Down, re-entry after catalog scrolling, and a four-step horizontal out-and-back check passed on the onn. The startup section regression and all six `verify_ui.py browse` checks passed, including live PIN cancellation preserving the session.
|
|
||||||
|
|
||||||
Performance was measured with the signed release and confirmed ART `speed-profile` compilation, retaining both accessibility services and all device settings. Initial browsing samples missed the p95 <40 ms gate. A controlled comparison rebuilt unchanged 0.1.8 source with version code 10 solely to allow an in-place install; it measured median 16 ms / p95 53 ms on the same current content. Tracing showed offscreen composition and layout between rapid key events. Horizontal rows now cache one viewport ahead and half a viewport behind, stage new card content at fixed bounds, and commit pending column changes on frame boundaries. Spaced presses retain their animation; presses less than 160 ms apart snap to the latest anchor and defer speculative artwork until 70 ms of settling. Up at the top bar does not run a lazy focus search. The final onn browsing check passed with median 17 ms / p95 34 ms, GPU p95 7 ms and zero horizontal Y drift (63 rendered frames). Some frames still missed 60 Hz; this is a device sample, not a guarantee.
|
|
||||||
|
|
||||||
The macOS checkout was reattached to the existing repository history without replacing its source files. Builds reused an existing JDK 17 with Gradle 8.13 and an isolated SDK 36, and used the original private signing key. `assembleRelease testDebugUnitTest lintDebug` passed (five unit tests); the signed debug build passed all 21 Android integration tests against the existing encrypted session. An outdated integration-test transcode argument was updated to `StreamQuality.Original`. Scripts accept `KALEIDO_ADB` for the local ADB executable and retain the authorized serial selection. Private keys, toolchains and raw device evidence remain ignored.
|
|
||||||
|
|
||||||
On the TCL (`192.168.50.200:5555`), 0.1.9 installed in place and ART confirmed `speed-profile` after a lost compilation reply. Rapid tab/Down, scrolled catalog re-entry and the horizontal round-trip passed. A longer transition run lost its ADB transport; `device.py` now reconnects when the serial disappears as well as on closed/offline errors. A shorter, complete Movies sample (`profile_transitions.py --skip-home`) measured tab → Discover p95 22.7 ms, Discover → row 23.2 ms and row → row 46.1 ms (baseline 74.8 ms). Entering Movies measured p95 94.2 ms / maximum 106.4 ms, versus baseline 106.8 / 150.1 ms. These are individual samples; the weaker TV still misses frames on section composition, and the interrupted run is not counted as a complete pass. Both comparisons retained the existing session and settings.
|
|
||||||
|
|
||||||
|
|
||||||
## Native playback and release performance — 2026-10-26 (0.1.10)
|
|
||||||
|
|
||||||
Original quality now opens the actual file first. On the ONN, the default path retained 3840×2160 HEVC/AAC 5.1 and 3840×1608 Dolby Vision/EAC3 7.1 instead of the baseline's 1080p/stereo conversion. Plex-selected audio is applied to native tracks, Subtitles Off disables native text tracks, and unsupported selected tracks retain server fallback. A nonempty audio-only track list for a declared video now triggers fallback: the VC-1 sample automatically reached rendered 1080p HEVC through Plex. Stream preparation is serialized, and fallback checks its session generation before replacing a newer stream. Movie controls identify server conversions.
|
|
||||||
|
|
||||||
The failing mono WAV contained a center-only PCM speaker mask. The audio sink normalizes one-channel PCM to Android's standard mono output, preserving rate, channel count, timeline and channel mapping. The 24-bit/96 kHz source played at 96 kHz through the existing 16-bit PCM sink; standard 16-bit/48 kHz stereo also passed. Multichannel PCM and encoded bitstreams retain their layout. This is a playback compatibility fix, not a new claim of bit-perfect 24-bit output.
|
|
||||||
|
|
||||||
Debug functional checks passed native Dolby Vision profiles 5/8/10, EAC3 7.1, AV1/TrueHD 7.1, Opus 7.1, DTS-HD input with DTS-core output, FLAC, selected AC3, and backward seeking. The AV1/TrueHD steady run covered 61.8 seconds with 1,483 rendered frames, one dropped frame and no later buffering samples. All seven remote player checks passed, including switching a conversion to Original quality. The Android runner reported OK for 24 tests (the capability inventory is opt-in); five host unit tests and release/debug builds plus lint passed. Native next-episode validation was not completed after the testing interruption and is not counted as a pass.
|
|
||||||
|
|
||||||
The user reported severe lag while the devices still had temporary debug APKs installed. Both were confirmed `DEBUGGABLE`, version code 11, with ART `run-from-apk`. They were restored to the exact published 0.1.9 release, without clearing data, and profile compiled. A subsequent controlled ONN comparison used only non-debuggable production-signed APKs with ART `speed-profile`. Three cold starts measured activity startup median 431 ms for 0.1.9 versus 423 ms for 0.1.10. Home readiness, including UI-dump polling overhead, was 6.720 versus 6.773 seconds. A full Home/Movies transition cycle recorded 26 versus 23 skipped vsyncs overall; Movies entry p95 was 79.7 versus 75.6 ms, with 11 skipped vsyncs in each. Individual transitions varied by a few milliseconds. The release comparison showed no material navigation/startup regression; it does not promise zero stutter. The TCL repeat was skipped at the user's request.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
## 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.
|
|
||||||
|
|
|
||||||
|
Before Width: | Height: | Size: 390 KiB |
|
Before Width: | Height: | Size: 166 KiB |
|
Before Width: | Height: | Size: 191 KiB |
|
Before Width: | Height: | Size: 225 KiB |
|
Before Width: | Height: | Size: 215 KiB |
|
Before Width: | Height: | Size: 313 KiB |
|
Before Width: | Height: | Size: 286 KiB |
|
Before Width: | Height: | Size: 302 KiB |
|
Before Width: | Height: | Size: 219 KiB |
|
Before Width: | Height: | Size: 53 KiB |
|
Before Width: | Height: | Size: 294 KiB |
|
Before Width: | Height: | Size: 210 KiB |
|
|
@ -1,28 +0,0 @@
|
||||||
"""Compare optimized release builds on one authorized device at a time."""
|
|
||||||
import argparse,json,pathlib,re,statistics,subprocess,sys,time
|
|
||||||
from device import adb,DEVICE,OUT
|
|
||||||
from verify_ui import wait,labels,focus
|
|
||||||
|
|
||||||
def main():
|
|
||||||
p=argparse.ArgumentParser();p.add_argument('label');p.add_argument('--cycles',type=int,default=3);p.add_argument('--nav-cycles',type=int,default=1)
|
|
||||||
args=p.parse_args();folder=OUT/'release-comparison';folder.mkdir(exist_ok=True)
|
|
||||||
package=adb('shell','dumpsys','package','tv.kaleido.app').decode()
|
|
||||||
assert 'DEBUGGABLE' not in re.search(r'pkgFlags=\[(.*?)\]',package)[1],'Performance tests require a release APK'
|
|
||||||
assert 'status=speed-profile' in package,'Apply the matching ART profile before comparison'
|
|
||||||
result={'device':DEVICE,'version':re.search(r'versionName=(\S+)',package)[1],'startup':[]}
|
|
||||||
adb('shell','input','keyevent','KEYCODE_WAKEUP')
|
|
||||||
for i in range(args.cycles):
|
|
||||||
adb('shell','am','force-stop','tv.kaleido.app');start=time.monotonic()
|
|
||||||
raw=adb('shell','am','start','-W','-n','tv.kaleido.app/.MainActivity').decode()
|
|
||||||
wait(lambda r:'Continue Watching' in labels(r) and focus(r)=='Home' and
|
|
||||||
all(n.get('content-desc')!='Kaleido starting' for n in r.iter('node')),'Cold Home ready',timeout=45)
|
|
||||||
row={'homeReadySeconds':round(time.monotonic()-start,3)}
|
|
||||||
row.update({k:int(v) for k,v in re.findall(r'(ThisTime|TotalTime|WaitTime): (\d+)',raw)})
|
|
||||||
result['startup'].append(row);print('STARTUP',args.label,i+1,row,flush=True)
|
|
||||||
result['medianHomeReadySeconds']=statistics.median(r['homeReadySeconds'] for r in result['startup'])
|
|
||||||
result['medianActivityMs']=statistics.median(r['TotalTime'] for r in result['startup'])
|
|
||||||
(folder/(args.label+'.json')).write_text(json.dumps(result,indent=2))
|
|
||||||
nav=subprocess.run([sys.executable,str(pathlib.Path(__file__).with_name('profile_transitions.py')),args.label,'--cycles',str(args.nav_cycles)])
|
|
||||||
if nav.returncode:raise SystemExit(nav.returncode)
|
|
||||||
print('COMPLETE',args.label,'activity median',result['medianActivityMs'],'Home median',result['medianHomeReadySeconds'],flush=True)
|
|
||||||
if __name__=='__main__':main()
|
|
||||||
|
|
@ -1,76 +0,0 @@
|
||||||
"""Exercise the actual release UI, measure startup/rebuffering, restore resume time."""
|
|
||||||
import argparse,json,os,pathlib,re,shlex,time,urllib.parse,urllib.request
|
|
||||||
if pathlib.Path('/etc/ssl/cert.pem').exists():os.environ.setdefault('SSL_CERT_FILE','/etc/ssl/cert.pem')
|
|
||||||
from device import adb,OUT,DEVICE
|
|
||||||
from verify_ui import launch,key,focused,wait,labels,focus,snapshot
|
|
||||||
from inspect_server import get,base,token
|
|
||||||
|
|
||||||
def session():
|
|
||||||
raw=adb('shell','dumpsys','media_session').decode(errors='replace')
|
|
||||||
m=re.search(r'package=tv\.kaleido\.app.*?PlaybackState \{state=(\w+)\(\d+\), position=(\d+).*?speed=([\d.]+), updated=(\d+)',raw,re.S)
|
|
||||||
return {'state':m[1],'position':int(m[2]),'speed':float(m[3]),'updated':int(m[4])} if m else {}
|
|
||||||
|
|
||||||
def main():
|
|
||||||
p=argparse.ArgumentParser();p.add_argument('label');p.add_argument('id');p.add_argument('--seconds',type=int,default=60);args=p.parse_args()
|
|
||||||
folder=OUT/'release-comparison';folder.mkdir(exist_ok=True)
|
|
||||||
pkg=adb('shell','dumpsys','package','tv.kaleido.app').decode()
|
|
||||||
assert 'DEBUGGABLE' not in re.search(r'pkgFlags=\[(.*?)\]',pkg)[1]
|
|
||||||
assert 'status=speed-profile' in pkg
|
|
||||||
before=get('/library/metadata/'+args.id)['Metadata'][0];title=before['title']
|
|
||||||
(folder/(args.label+'-before.json')).write_text(json.dumps(before,indent=2))
|
|
||||||
# A previous ADB tap can leave Android in touch mode across app restarts.
|
|
||||||
adb('shell','input','keyevent','19')
|
|
||||||
launch()
|
|
||||||
for target in ['Movies','TV Shows','Search']:key(22);focused(target)
|
|
||||||
key(23);wait(lambda r:'Movies, shows, episodes' in labels(r),'Search field')
|
|
||||||
adb('shell','input','text',shlex.quote(title.replace(' ','%s')))
|
|
||||||
wait(lambda r:title in labels(r),'Matching search result')
|
|
||||||
ime=adb('shell','dumpsys','input_method').decode(errors='replace')
|
|
||||||
if re.search(r'mInputShown=true|isInputViewShown=true',ime):key(4)
|
|
||||||
# EditText has the same text as the result; Tab exits editing without entering
|
|
||||||
# Android touch mode, and the focused poster is verified before activation.
|
|
||||||
key(61)
|
|
||||||
wait(lambda r:any(n.get('focused')=='true' and n.get('class')!='android.widget.EditText' and title in labels(n) for n in r.iter('node')),'Movie result focus')
|
|
||||||
key(23)
|
|
||||||
root=wait(lambda r:any(s=='Play' or s.startswith('Resume') for s in labels(r)),'Movie actions')
|
|
||||||
wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Playback action focus')
|
|
||||||
if 'Start over' in labels(root):key(22);focused('Start over')
|
|
||||||
print('PLAYBACK_START',args.label,flush=True)
|
|
||||||
adb('logcat','-c');start=time.monotonic();key(23)
|
|
||||||
ready=None;samples=[];ready_logs=''
|
|
||||||
while time.monotonic()-start<70:
|
|
||||||
s=session();s['elapsed']=round(time.monotonic()-start,3);samples.append(s)
|
|
||||||
ready_logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
|
|
||||||
if s.get('state')=='PLAYING' and 'READY item='+args.id in ready_logs:ready=s['elapsed'];break
|
|
||||||
time.sleep(.7)
|
|
||||||
assert ready is not None,'Release playback did not become ready'
|
|
||||||
print('PLAYBACK_READY',args.label,ready,flush=True)
|
|
||||||
steady_start=time.monotonic();last='PLAYING';rebuffers=0
|
|
||||||
while time.monotonic()-steady_start<args.seconds:
|
|
||||||
s=session();s['elapsed']=round(time.monotonic()-start,3);samples.append(s)
|
|
||||||
if s.get('state')=='BUFFERING' and last!='BUFFERING':rebuffers+=1
|
|
||||||
last=s.get('state');time.sleep(1)
|
|
||||||
(folder/(args.label+'-measurement.json')).write_text(json.dumps({'readySeconds':ready,'rebufferTransitions':rebuffers,'samples':samples},indent=2))
|
|
||||||
(folder/(args.label+'-surface.txt')).write_bytes(adb('shell','dumpsys','SurfaceFlinger'))
|
|
||||||
adb('shell','input','keyevent','127');time.sleep(1)
|
|
||||||
(folder/(args.label+'-player.png')).write_bytes(adb('exec-out','screencap','-p'))
|
|
||||||
for _ in range(2):key(4)
|
|
||||||
wait(lambda r:any(s in labels(r) for s in ['Continue Watching','Mark watched','Mark unwatched']),'Return to the originating page after playback')
|
|
||||||
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
|
|
||||||
(folder/(args.label+'-playback.log')).write_text(logs)
|
|
||||||
# Release builds use normal Plex progress reporting. Restore the prior resume time.
|
|
||||||
time.sleep(1)
|
|
||||||
query=urllib.parse.urlencode({'key':args.id,'time':int(before.get('viewOffset') or 0),'state':'stopped','identifier':'com.plexapp.plugins.library'})
|
|
||||||
req=urllib.request.Request(base.rstrip('/')+'/:/progress?'+query,headers={'X-Plex-Token':token})
|
|
||||||
with urllib.request.urlopen(req,timeout=30) as r:r.read()
|
|
||||||
after=get('/library/metadata/'+args.id)['Metadata'][0]
|
|
||||||
result={'device':DEVICE,'version':re.search(r'versionName=(\S+)',pkg)[1],'id':args.id,'readySeconds':ready,
|
|
||||||
'rebufferTransitions':rebuffers,'readyEvents':logs.count('READY item='+args.id+' '),'samples':samples,
|
|
||||||
'resumeRestored':int(after.get('viewOffset') or 0)==int(before.get('viewOffset') or 0),
|
|
||||||
'viewCountUnchanged':after.get('viewCount')==before.get('viewCount')}
|
|
||||||
(folder/(args.label+'-playback.json')).write_text(json.dumps(result,indent=2))
|
|
||||||
print(json.dumps({k:v for k,v in result.items() if k!='samples'}),flush=True)
|
|
||||||
assert 'FATAL EXCEPTION' not in logs and 'ERROR code=' not in logs,'Playback error in release'
|
|
||||||
assert result['resumeRestored'] and result['viewCountUnchanged'],'Plex progress restoration needs attention'
|
|
||||||
launch()
|
|
||||||
if __name__=='__main__':main()
|
|
||||||
|
|
@ -1,23 +1,13 @@
|
||||||
"""Operate only Kaleido on an authorized streamer. Credentials stay on stdin."""
|
"""Operate only Kaleido on the authorized onn streamer. Credentials stay on stdin."""
|
||||||
import argparse, json, os, pathlib, shutil, subprocess, sys, time, xml.etree.ElementTree as ET
|
import argparse, json, pathlib, subprocess, sys, time, xml.etree.ElementTree as ET
|
||||||
ROOT=pathlib.Path(__file__).resolve().parents[1]
|
ROOT=pathlib.Path(__file__).resolve().parents[1]
|
||||||
ADB=pathlib.Path(os.environ.get('KALEIDO_ADB') or shutil.which('adb') or r'C:\Users\Elijah\Desktop\platform-tools\adb.exe')
|
ADB=pathlib.Path(r'C:\Users\Elijah\Desktop\platform-tools\adb.exe')
|
||||||
# The onn is the default; KALEIDO_DEVICE selects another authorized test streamer.
|
DEVICE='192.168.50.195:5555'
|
||||||
DEVICE=os.environ.get('KALEIDO_DEVICE','192.168.50.195:5555')
|
|
||||||
OUT=ROOT/'evidence/private'
|
OUT=ROOT/'evidence/private'
|
||||||
OUT.mkdir(parents=True,exist_ok=True)
|
OUT.mkdir(parents=True,exist_ok=True)
|
||||||
def adb(*args, data=None):
|
def adb(*args, data=None):
|
||||||
for attempt in range(4):
|
|
||||||
p=subprocess.run([str(ADB),'-s',DEVICE,*args],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
p=subprocess.run([str(ADB),'-s',DEVICE,*args],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||||
error=p.stderr.decode(errors='replace')
|
if p.returncode: raise RuntimeError(p.stderr.decode(errors='replace'))
|
||||||
# The TCL's network ADB link drops intermittently; reconnecting restores it.
|
|
||||||
if p.returncode and attempt<3 and any(reason in error for reason in ('closed','offline',f"device '{DEVICE}' not found",f"no such device '{DEVICE}'")):
|
|
||||||
subprocess.run([str(ADB),'disconnect',DEVICE],capture_output=True);time.sleep(2)
|
|
||||||
subprocess.run([str(ADB),'connect',DEVICE],capture_output=True);time.sleep(2);continue
|
|
||||||
# It also occasionally fails a shell command silently. Retry, except key input,
|
|
||||||
# which may already have been delivered.
|
|
||||||
if p.returncode and attempt<3 and not error.strip() and args[:2]!=('shell','input'):time.sleep(1);continue
|
|
||||||
if p.returncode: raise RuntimeError(error)
|
|
||||||
return p.stdout
|
return p.stdout
|
||||||
def screenshot(name):
|
def screenshot(name):
|
||||||
path=OUT/(name+'.png');path.write_bytes(adb('exec-out','screencap','-p'));print(path)
|
path=OUT/(name+'.png');path.write_bytes(adb('exec-out','screencap','-p'));print(path)
|
||||||
|
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
"""Generate the launcher banner and app icon vector drawables from brand_mark.xml.
|
|
||||||
|
|
||||||
The mark is copied unchanged; only the background is drawn here: a diagonal light from
|
|
||||||
deep sea-glass (top right) through near-black to a warm tan glow (bottom left), echoing the
|
|
||||||
mark's cool and warm facets, with a soft vignette. Nothing covers the mark's dark aperture.
|
|
||||||
"""
|
|
||||||
import pathlib,re
|
|
||||||
ROOT=pathlib.Path(__file__).resolve().parents[1]
|
|
||||||
DRAWABLE=ROOT/'app/src/main/res/drawable'
|
|
||||||
MARK=re.findall(r'<path [^>]*/>',(DRAWABLE/'brand_mark.xml').read_text())
|
|
||||||
|
|
||||||
def color(hex6,alpha):return f'#{round(alpha*255):02X}{hex6}'
|
|
||||||
def gradient(kind,attrs,stops):
|
|
||||||
items=''.join(f'<item android:offset="{o}" android:color="{c}"/>' for o,c in stops)
|
|
||||||
return f'<aapt:attr name="android:fillColor"><gradient android:type="{kind}" {attrs}>{items}</gradient></aapt:attr>'
|
|
||||||
def tile(width,height,mark_scale,mark_x,mark_y):
|
|
||||||
cx,cy=width/2,height/2;rect=f'M0,0h{width}v{height}h-{width}z'
|
|
||||||
light=gradient('linear',f'android:startX="{width}" android:startY="0" android:endX="0" android:endY="{height}"',
|
|
||||||
[(0,'#FF1B403C'),(.5,'#FF101414'),(1,'#FF30241A')])
|
|
||||||
vignette=gradient('radial',f'android:centerX="{cx}" android:centerY="{cy}" android:gradientRadius="{width*.62:.1f}"',
|
|
||||||
[(.35,color('000000',0)),(1,color('000000',.45))])
|
|
||||||
group=f'<group android:translateX="{mark_x}" android:translateY="{mark_y}" android:scaleX="{mark_scale}" android:scaleY="{mark_scale}">'+''.join(MARK)+'</group>'
|
|
||||||
return ('<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" '
|
|
||||||
f'android:width="{width}dp" android:height="{height}dp" android:viewportWidth="{width}" android:viewportHeight="{height}">'
|
|
||||||
f'<path android:pathData="{rect}">{light}</path><path android:pathData="{rect}">{vignette}</path>'+group+'</vector>\n')
|
|
||||||
|
|
||||||
(DRAWABLE/'banner.xml').write_text(tile(320,180,1.6,108.8,38.8))
|
|
||||||
(DRAWABLE/'icon.xml').write_text(tile(108,108,1,22,22))
|
|
||||||
print('Wrote banner.xml and icon.xml')
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
"""Inventory real Plex formats. Raw metadata stays in ignored private evidence."""
|
|
||||||
import collections,json,os,pathlib,urllib.parse
|
|
||||||
if pathlib.Path('/etc/ssl/cert.pem').exists():os.environ.setdefault('SSL_CERT_FILE','/etc/ssl/cert.pem')
|
|
||||||
from inspect_server import get
|
|
||||||
|
|
||||||
OUT=pathlib.Path(__file__).resolve().parents[1]/'evidence/private/playback-validation'
|
|
||||||
OUT.mkdir(parents=True,exist_ok=True)
|
|
||||||
def main():
|
|
||||||
sections=get('/library/sections').get('Directory',[])
|
|
||||||
(OUT/'sections.json').write_text(json.dumps(sections,indent=2))
|
|
||||||
items=[]
|
|
||||||
for section in sections:
|
|
||||||
if section.get('type') not in ('movie','show','artist'):continue
|
|
||||||
kind={'movie':'1','show':'4','artist':'10'}[section['type']]
|
|
||||||
start=0
|
|
||||||
while True:
|
|
||||||
params={'type':kind,'includeMedia':'1','includeMediaAnalysis':'1','X-Plex-Container-Start':start,'X-Plex-Container-Size':200}
|
|
||||||
data=get('/library/sections/'+section['key']+'/all?'+urllib.parse.urlencode(params))
|
|
||||||
batch=data.get('Metadata',[])
|
|
||||||
for item in batch:item['_section']=section['key']
|
|
||||||
items.extend(batch);start+=len(batch)
|
|
||||||
if not batch or start>=int(data.get('totalSize',start)):break
|
|
||||||
print('Inventoried',section['type'],start,'items',flush=True)
|
|
||||||
(OUT/'inventory.json').write_text(json.dumps(items))
|
|
||||||
for label,field in [('Video','videoCodec'),('Audio','audioCodec'),('Containers','container')]:
|
|
||||||
counts=collections.Counter(media.get(field,'none') for item in items for media in item.get('Media',[]))
|
|
||||||
print(label,dict(counts),flush=True)
|
|
||||||
if __name__=='__main__':main()
|
|
||||||
|
|
@ -1,21 +1,15 @@
|
||||||
"""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, 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(encoding='utf-8').splitlines() if '=' in l)
|
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().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()
|
||||||
(out/'Kaleido.apk.sha256').write_text(digest+' Kaleido.apk\n')
|
(out/'Kaleido.apk.sha256').write_text(digest+' Kaleido.apk\n')
|
||||||
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.
|
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':(ROOT/'CHANGELOG.md').read_text().split('\n## ')[1].split('\n## ')[0] if (ROOT/'CHANGELOG.md').exists() else ''}
|
||||||
changelog=(ROOT/'CHANGELOG.md').read_text(encoding='utf-8') if (ROOT/'CHANGELOG.md').exists() else ''
|
(out/'latest.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
||||||
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 ''}
|
|
||||||
(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)
|
||||||
|
|
|
||||||
|
|
@ -1,109 +0,0 @@
|
||||||
"""Time individual D-pad focus transitions on Home and Movies with gfxinfo framestats.
|
|
||||||
|
|
||||||
Select the device with KALEIDO_DEVICE (default: the onn). Use an optimized release
|
|
||||||
with the baseline profile installed and speed-profile compilation, and never run
|
|
||||||
another device test alongside it. Results stay in ignored evidence/private/.
|
|
||||||
|
|
||||||
For each transition this reports the frames drawn in the following window, the
|
|
||||||
vsyncs skipped between them (visible stutter), and frame latency percentiles.
|
|
||||||
"""
|
|
||||||
import argparse,json,time
|
|
||||||
from device import adb,OUT,DEVICE
|
|
||||||
from verify_ui import launch,key,wait,focus,focused,snapshot
|
|
||||||
|
|
||||||
HERO=('Play','Resume')
|
|
||||||
LABEL='run'
|
|
||||||
def card(r):return focus(r) not in ('','Home','Movies','TV Shows','Discover','Library')+HERO
|
|
||||||
def changed(previous):return lambda r:card(r) and focus(r)!=previous
|
|
||||||
|
|
||||||
def frames(raw):
|
|
||||||
rows=[]
|
|
||||||
for block in raw.split('---PROFILEDATA---')[1::2]:
|
|
||||||
lines=[line.strip() for line in block.splitlines() if line.strip()]
|
|
||||||
if not lines:continue
|
|
||||||
names=lines[0].rstrip(',').split(',')
|
|
||||||
for line in lines[1:]:
|
|
||||||
values=line.rstrip(',').split(',')
|
|
||||||
if len(values)!=len(names):continue
|
|
||||||
row=dict(zip(names,map(int,values)))
|
|
||||||
if row['Flags']==0 and row['FrameCompleted']>row['IntendedVsync']:rows.append(row)
|
|
||||||
return sorted(rows,key=lambda r:r['IntendedVsync'])
|
|
||||||
|
|
||||||
def summarize(rows,period):
|
|
||||||
if not rows:return {'frames':0,'skipped':0}
|
|
||||||
latency=sorted((r['FrameCompleted']-r['IntendedVsync'])/1e6 for r in rows)
|
|
||||||
ui=sorted((r['SyncQueued']-r['IntendedVsync'])/1e6 for r in rows)
|
|
||||||
# A gap after a slow frame is a stall; a gap after a fast frame, or one longer than
|
|
||||||
# 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:])
|
|
||||||
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))]
|
|
||||||
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)}
|
|
||||||
|
|
||||||
def measure(name,code,expect,window,results):
|
|
||||||
time.sleep(.8)
|
|
||||||
adb('shell','dumpsys','gfxinfo','tv.kaleido.app','reset')
|
|
||||||
adb('shell','input','keyevent',str(code));time.sleep(window)
|
|
||||||
raw=adb('shell','dumpsys','gfxinfo','tv.kaleido.app','framestats').decode(errors='replace')
|
|
||||||
rows=frames(raw)
|
|
||||||
with open(OUT/f'transitions-{LABEL}-frames.txt','a') as log:log.write(f'### {name}\n'+raw.split('---PROFILEDATA---')[1]+'\n')
|
|
||||||
# The display's frame interval is the shortest step between measured frames.
|
|
||||||
steps=[b['IntendedVsync']-a['IntendedVsync'] for a,b in zip(rows,rows[1:]) if b['IntendedVsync']>a['IntendedVsync']]
|
|
||||||
results.setdefault(name,[]).append(summarize(rows,min(steps) if steps else 1e9/60))
|
|
||||||
print(name,json.dumps(results[name][-1]),flush=True)
|
|
||||||
return wait(expect,name+' destination')
|
|
||||||
|
|
||||||
def resummarize(label):
|
|
||||||
"""Recompute a saved run's per-transition stalls from its raw framestats."""
|
|
||||||
text=(OUT/f'transitions-{label}-frames.txt').read_text();totals={}
|
|
||||||
for chunk in text.split('### ')[1:]:
|
|
||||||
name,raw=chunk.split('\n',1);rows=frames('---PROFILEDATA---\n'+raw+'---PROFILEDATA---')
|
|
||||||
steps=[b['IntendedVsync']-a['IntendedVsync'] for a,b in zip(rows,rows[1:]) if b['IntendedVsync']>a['IntendedVsync']]
|
|
||||||
totals.setdefault(name,[]).append(summarize(rows,min(steps) if steps else 1e9/60))
|
|
||||||
return totals
|
|
||||||
|
|
||||||
def main():
|
|
||||||
parser=argparse.ArgumentParser();parser.add_argument('label');parser.add_argument('--cycles',type=int,default=3)
|
|
||||||
parser.add_argument('--window',type=float,default=1.2);parser.add_argument('--skip-movies',action='store_true');parser.add_argument('--skip-home',action='store_true');args=parser.parse_args()
|
|
||||||
global LABEL;LABEL=args.label;(OUT/f'transitions-{LABEL}-frames.txt').unlink(missing_ok=True)
|
|
||||||
results={}
|
|
||||||
launch()
|
|
||||||
for _ in range(0 if args.skip_home else args.cycles):
|
|
||||||
measure('home: tab -> hero',20,lambda r:focus(r) in HERO,args.window,results)
|
|
||||||
root=measure('home: hero -> row',20,card,args.window,results)
|
|
||||||
first=focus(root)
|
|
||||||
root=measure('home: row -> row',20,changed(first),args.window,results)
|
|
||||||
measure('home: row <- row',19,lambda r:focus(r)==first,args.window,results)
|
|
||||||
measure('home: hero <- row',19,lambda r:focus(r) in HERO,args.window,results)
|
|
||||||
measure('home: tab <- hero',19,lambda r:focus(r)=='Home',args.window,results)
|
|
||||||
if not args.skip_movies:
|
|
||||||
for _ in range(args.cycles):
|
|
||||||
measure('tabs: home -> movies',22,lambda r:focus(r)=='Movies' and 'Recently released' in [n.get('text') for n in r.iter('node')],args.window*2,results)
|
|
||||||
measure('movies: tab -> discover',20,lambda r:focus(r)=='Discover',args.window,results)
|
|
||||||
root=measure('movies: discover -> row',20,card,args.window,results)
|
|
||||||
first=focus(root)
|
|
||||||
measure('movies: row -> row',20,changed(first),args.window,results)
|
|
||||||
measure('movies: row <- row',19,lambda r:focus(r)==first,args.window,results)
|
|
||||||
measure('movies: discover <- row',19,lambda r:focus(r)=='Discover',args.window,results)
|
|
||||||
measure('movies: tab <- discover',19,lambda r:focus(r)=='Movies',args.window,results)
|
|
||||||
measure('tabs: home <- movies',21,lambda r:focus(r)=='Home',args.window*2,results)
|
|
||||||
summary={}
|
|
||||||
for name,runs in results.items():
|
|
||||||
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}
|
|
||||||
(OUT/f'transitions-{args.label}.json').write_text(json.dumps(report,indent=2)+'\n')
|
|
||||||
print('\nSUMMARY',args.label,DEVICE)
|
|
||||||
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()
|
|
||||||
|
|
@ -1,18 +1,13 @@
|
||||||
"""Publish the checked-in, signed APK using Forgejo's repository-scoped CI token."""
|
"""Publish the checked-in, signed APK using Forgejo's repository-scoped CI token."""
|
||||||
import hashlib, json, os, pathlib, re, urllib.request, uuid
|
import hashlib, json, os, pathlib, 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(encoding='utf-8').splitlines() if '=' in l)
|
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().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():
|
|
||||||
"""Only this version's changelog section; the app shows the body as release notes."""
|
|
||||||
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)
|
|
||||||
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]
|
||||||
def call(path,data=None,method=None,content='application/json'):
|
def call(path,data=None,method=None,content='application/json'):
|
||||||
req=urllib.request.Request(API+path,data=data,method=method,headers={'Authorization':'token '+token,'Content-Type':content})
|
req=urllib.request.Request(API+path,data=data,method=method,headers={'Authorization':'token '+token,'Content-Type':content})
|
||||||
|
|
@ -20,7 +15,7 @@ def call(path,data=None,method=None,content='application/json'):
|
||||||
try:release=call('/releases/tags/'+tag)
|
try:release=call('/releases/tags/'+tag)
|
||||||
except urllib.error.HTTPError as e:
|
except urllib.error.HTTPError as e:
|
||||||
if e.code!=404:raise
|
if e.code!=404:raise
|
||||||
release=call('/releases',json.dumps({'tag_name':tag,'name':'Kaleido '+version['versionName'],'body':notes(),'draft':True,'prerelease':False}).encode(),'POST')
|
release=call('/releases',json.dumps({'tag_name':tag,'name':'Kaleido '+version['versionName'],'body':(ROOT/'CHANGELOG.md').read_text(),'draft':True,'prerelease':False}).encode(),'POST')
|
||||||
existing={a['name']:a for a in release.get('assets',[])}
|
existing={a['name']:a for a in release.get('assets',[])}
|
||||||
for name in ['Kaleido.apk','Kaleido.apk.sha256']:
|
for name in ['Kaleido.apk','Kaleido.apk.sha256']:
|
||||||
if name in existing:continue
|
if name in existing:continue
|
||||||
|
|
|
||||||
|
|
@ -16,18 +16,10 @@ def sections():
|
||||||
key(21);wait(lambda r:'Recently released' in labels(r),'Cached Movies must return');focused('Movies')
|
key(21);wait(lambda r:'Recently released' in labels(r),'Cached Movies must return');focused('Movies')
|
||||||
print('PASS startup tab switch, TV loading, and cached section return')
|
print('PASS startup tab switch, TV loading, and cached section return')
|
||||||
|
|
||||||
def await_ready(item,timeout=45):
|
|
||||||
# A pause sent while the player is still preparing is overridden when playback starts.
|
|
||||||
deadline=time.monotonic()+timeout
|
|
||||||
while time.monotonic()<deadline:
|
|
||||||
if f'READY item={item}' in adb('logcat','-d','-s','KaleidoPlayback:I').decode(errors='replace'):time.sleep(1);return
|
|
||||||
time.sleep(.5)
|
|
||||||
raise AssertionError(f'Playback of {item} never became ready')
|
|
||||||
|
|
||||||
def controls():
|
def controls():
|
||||||
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
|
adb('shell','am','force-stop','tv.kaleido.app')
|
||||||
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','1','--ez','testValidation','true')
|
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','1')
|
||||||
await_ready(7599);key(127);focused('Play')
|
time.sleep(9);key(127);focused('Play')
|
||||||
screenshot('direct-stream-episode')
|
screenshot('direct-stream-episode')
|
||||||
key(4);wait(lambda r:not labels(r),'One Back must hide controls rather than only clearing focus')
|
key(4);wait(lambda r:not labels(r),'One Back must hide controls rather than only clearing focus')
|
||||||
key(23);focused('Play');key(126);time.sleep(6)
|
key(23);focused('Play');key(126);time.sleep(6)
|
||||||
|
|
@ -67,8 +59,8 @@ def episode():
|
||||||
item=titles[0];expected=str(titles[1]['ratingKey'])
|
item=titles[0];expected=str(titles[1]['ratingKey'])
|
||||||
adb('shell','am','force-stop','tv.kaleido.app')
|
adb('shell','am','force-stop','tv.kaleido.app')
|
||||||
adb('logcat','-c')
|
adb('logcat','-c')
|
||||||
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item['ratingKey']),'--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true')
|
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item['ratingKey']),'--el','testOffset','90000','--ei','testMode','2')
|
||||||
await_ready(item["ratingKey"]);key(127);focused('Play')
|
time.sleep(9);key(127);focused('Play')
|
||||||
for _ in range(6):
|
for _ in range(6):
|
||||||
if 'Next episode' in focus(snapshot()):break
|
if 'Next episode' in focus(snapshot()):break
|
||||||
key(22)
|
key(22)
|
||||||
|
|
@ -82,12 +74,12 @@ def episode():
|
||||||
assert 'item='+expected in logs,'Next episode did not become the active player'
|
assert 'item='+expected in logs,'Next episode did not become the active player'
|
||||||
print('PASS next episode replaced player with expected title')
|
print('PASS next episode replaced player with expected title')
|
||||||
|
|
||||||
def postplay(mode=2):
|
def postplay():
|
||||||
from inspect_server import get
|
from inspect_server import get
|
||||||
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
|
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
|
||||||
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(item['duration']-12000),'--ei','testMode',str(mode),'--ez','testValidation','true')
|
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(item['duration']-12000),'--ei','testMode','2')
|
||||||
deadline=time.monotonic()+(90 if mode<=0 else 45)
|
deadline=time.monotonic()+45
|
||||||
while time.monotonic()<deadline:
|
while time.monotonic()<deadline:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
|
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
|
||||||
|
|
@ -104,29 +96,25 @@ def credits():
|
||||||
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
|
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
|
||||||
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')
|
||||||
await_ready(7599)
|
time.sleep(6);key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits')
|
||||||
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 and 'POSTPLAY focus=play' not in log():time.sleep(.1)
|
while time.monotonic()<deadline:
|
||||||
assert 'POSTPLAY focus=play' in log(),'Up Next initial action never received focus'
|
time.sleep(.1)
|
||||||
screenshot('up-next')
|
ready=adb('logcat','-d','-s','KaleidoPlayback:I','*:S').decode(errors='replace')
|
||||||
key(20) # any press stops the countdown
|
if 'POSTPLAY focus=play' in ready:break
|
||||||
time.sleep(6);root=snapshot();found=labels(root)
|
assert 'POSTPLAY focus=play' in ready,'Postplay initial action never received focus'
|
||||||
assert 'Up next' in found or 'UP NEXT' in found,'Cancellation failed to keep Up Next open'
|
key(22);key(23)
|
||||||
assert any(l.startswith('Season ') for l in found),'Season episodes absent'
|
wait(lambda r:'Autoplay off' in labels(r),'Autoplay cancellation')
|
||||||
assert 'Related shows' in found,'Related shows absent'
|
screenshot('postplay-season-and-related');time.sleep(6)
|
||||||
logs=log()
|
root=snapshot();assert 'Up next' in labels(root),'Cancellation failed to keep postplay open'
|
||||||
assert 'AUTOPLAY cancelled' in logs and 'AUTOPLAY starting' not in logs,'Cancelled autoplay still advanced'
|
assert 'Episodes in this season' in labels(root),'Season episodes absent'
|
||||||
key(4);time.sleep(1)
|
assert 'Related shows' in labels(root),'Related shows absent'
|
||||||
assert 'POSTPLAY closed' in log(),'Back did not return to the video'
|
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
|
||||||
(OUT/'postplay-cancel.log').write_text(log())
|
assert 'reason=skip-credits' in logs,'Skip credits did not open postplay'
|
||||||
print('PASS credits -> Up Next, episode/related rows, any press stops autoplay, Back returns to video')
|
assert 'AUTOPLAY starting' not in logs,'Cancelled autoplay still advanced'
|
||||||
|
(OUT/'postplay-cancel.log').write_text(logs)
|
||||||
|
print('PASS skip credits -> postplay, episode/related rows, cancellable autoplay')
|
||||||
|
|
||||||
if __name__=='__main__':globals()[sys.argv[1]]()
|
globals()[sys.argv[1]]()
|
||||||
|
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
"""Trace one D-pad transition and summarize Kaleido's slow UI-thread frames.
|
|
||||||
|
|
||||||
Usage: trace_transition.py <label> <setup keys> <measured keys>
|
|
||||||
Keys are comma-separated keycodes (19 up, 20 down, 21 left, 22 right); setup runs
|
|
||||||
after launch and is not measured. Select the device with KALEIDO_DEVICE. Raw atrace
|
|
||||||
output and the summary stay in ignored evidence/private/.
|
|
||||||
"""
|
|
||||||
import collections,re,sys,time
|
|
||||||
from device import adb,OUT
|
|
||||||
from verify_ui import launch
|
|
||||||
|
|
||||||
SLICE=re.compile(r'^\s*(.+?)-(\d+)\s+\(\s*(\d+)\)\s+\[\d+\]\s+\S+\s+([\d.]+): tracing_mark_write: ([BE])\|(\d+)(?:\|(.*))?$')
|
|
||||||
|
|
||||||
def slices(text,pid):
|
|
||||||
stacks=collections.defaultdict(list);done=[]
|
|
||||||
for line in text.splitlines():
|
|
||||||
m=SLICE.match(line)
|
|
||||||
if not m or m.group(3)!=pid:continue
|
|
||||||
tid=int(m.group(2));at=float(m.group(4))*1000
|
|
||||||
if m.group(5)=='B':stacks[tid].append((m.group(7) or '',at))
|
|
||||||
elif stacks[tid]:
|
|
||||||
name,start=stacks[tid].pop();done.append((tid,len(stacks[tid]),name,start,at-start))
|
|
||||||
return done
|
|
||||||
|
|
||||||
def main():
|
|
||||||
label,setup,measured=sys.argv[1],sys.argv[2],sys.argv[3]
|
|
||||||
launch()
|
|
||||||
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];time.sleep(float(__import__("os").environ.get("KALEIDO_SETTLE","0")))
|
|
||||||
time.sleep(1)
|
|
||||||
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)
|
|
||||||
raw=adb('shell','atrace','--async_stop','-a','tv.kaleido.app','gfx','view','sched','dalvik').decode(errors='replace')
|
|
||||||
(OUT/f'trace-{label}.txt').write_text(raw)
|
|
||||||
found=slices(raw,pid);main_tid=int(pid)
|
|
||||||
frames=[s for s in found if s[0]==main_tid and s[2].startswith('Choreographer#doFrame')]
|
|
||||||
lines=[f'{len(frames)} UI frames; slow (>12 ms) frames with their longest nested work:']
|
|
||||||
for tid,depth,name,start,length in frames:
|
|
||||||
if length<12:continue
|
|
||||||
inner=[s for s in found if s[0]==main_tid and s[3]>=start and s[3]+s[4]<=start+length and s[1]>depth]
|
|
||||||
top=sorted(inner,key=lambda s:-s[4])[:8]
|
|
||||||
lines.append(f' {name} {length:.1f} ms')
|
|
||||||
lines+=[f' {" "*(s[1]-depth-1)}{s[2][:90]} {s[4]:.1f}' for s in sorted(top,key=lambda s:(s[3],s[1]))]
|
|
||||||
render=[s for s in found if s[2]=='DrawFrame' or s[2].startswith('DrawFrames')]
|
|
||||||
if render:lines.append(f'RenderThread DrawFrame max {max(s[4] for s in render):.1f} ms over {len(render)} frames')
|
|
||||||
(OUT/f'trace-{label}-summary.txt').write_text('\n'.join(lines)+'\n')
|
|
||||||
print('\n'.join(lines))
|
|
||||||
|
|
||||||
if __name__=='__main__':main()
|
|
||||||
|
|
@ -1,129 +0,0 @@
|
||||||
"""Exercise real Plex playback through Kaleido's opt-in debug validation mode.
|
|
||||||
|
|
||||||
One device at a time. No timeline/scrobble writes in validation mode. Raw reports
|
|
||||||
and screenshots remain private; source media and track preferences are untouched.
|
|
||||||
"""
|
|
||||||
import argparse,json,os,pathlib,subprocess,time
|
|
||||||
if pathlib.Path('/etc/ssl/cert.pem').exists():os.environ.setdefault('SSL_CERT_FILE','/etc/ssl/cert.pem')
|
|
||||||
from device import adb,DEVICE,OUT
|
|
||||||
from inspect_server import get
|
|
||||||
|
|
||||||
def audit():
|
|
||||||
try:raw=adb('exec-out','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl')
|
|
||||||
except RuntimeError:return b'',[]
|
|
||||||
records=[]
|
|
||||||
for line in raw.splitlines():
|
|
||||||
try:records.append(json.loads(line))
|
|
||||||
except json.JSONDecodeError:pass # The writer can be appending its last line.
|
|
||||||
return raw,records
|
|
||||||
|
|
||||||
def snapshot_signal():
|
|
||||||
command='for p in /sys/class/amhdmitx/amhdmitx0/attr /sys/class/amhdmitx/amhdmitx0/hdmi_hdr_status /sys/class/amhdmitx/amhdmitx0/hdr_status /sys/class/video/frame_format /sys/module/amdolby_vision/parameters/dolby_vision_status /sys/module/amdolby_vision/parameters/dolby_vision_mode; do if [ -r "$p" ]; then printf "%s=" "$p"; cat "$p"; fi; done'
|
|
||||||
return adb('shell',command)
|
|
||||||
|
|
||||||
def watched(item):return {k:item.get(k) for k in ('viewOffset','viewCount','lastViewedAt')}
|
|
||||||
|
|
||||||
def main():
|
|
||||||
parser=argparse.ArgumentParser()
|
|
||||||
parser.add_argument('id');parser.add_argument('label');parser.add_argument('--mode',type=int,default=-1)
|
|
||||||
parser.add_argument('--seconds',type=float,default=12);parser.add_argument('--offset',type=int,default=90000)
|
|
||||||
parser.add_argument('--seek',action='store_true');parser.add_argument('--screenshot',action='store_true')
|
|
||||||
parser.add_argument('--observe-hdmi',action='store_true',help='Read the already tuned TCL debug HDMI observer during ONN playback')
|
|
||||||
parser.add_argument('--fixture',type=pathlib.Path,help='Private local test media with a matching .json metadata file; bypasses Plex transport')
|
|
||||||
parser.add_argument('--expect-mode',type=int,choices=(0,1,2))
|
|
||||||
parser.add_argument('--expect-width',type=int)
|
|
||||||
parser.add_argument('--expect-channels',type=int)
|
|
||||||
parser.add_argument('--expect-audio-encoding',type=int)
|
|
||||||
parser.add_argument('--fail-on-audio-underrun',action='store_true')
|
|
||||||
args=parser.parse_args()
|
|
||||||
folder=OUT/'playback-validation'/('onn' if DEVICE=='192.168.50.195:5555' else 'tcl')/args.label
|
|
||||||
folder.mkdir(parents=True,exist_ok=True)
|
|
||||||
before=json.loads(args.fixture.with_suffix('.json').read_text()) if args.fixture else get('/library/metadata/'+args.id)['Metadata'][0]
|
|
||||||
expects_video=any(m.get('videoCodec') for m in before.get('Media',[]))
|
|
||||||
(folder/'source.json').write_text(json.dumps(before,indent=2))
|
|
||||||
adb('shell','input','keyevent','KEYCODE_WAKEUP')
|
|
||||||
adb('shell','am','force-stop','tv.kaleido.app')
|
|
||||||
adb('shell','run-as','tv.kaleido.app','rm','-f','files/playback-validation.jsonl')
|
|
||||||
if args.fixture:
|
|
||||||
name=args.fixture.stem
|
|
||||||
if not name.replace('-','').isalnum() or name.lower()!=name:raise SystemExit('Use a lowercase alphanumeric fixture name')
|
|
||||||
adb('shell','run-as','tv.kaleido.app','mkdir','-p','files/validation')
|
|
||||||
for path in (args.fixture,args.fixture.with_suffix('.json')):
|
|
||||||
tmp='/data/local/tmp/kaleido-validation-'+path.name
|
|
||||||
adb('push',str(path),tmp)
|
|
||||||
adb('shell','run-as','tv.kaleido.app','cp',tmp,'files/validation/'+path.name)
|
|
||||||
adb('shell','rm','-f',tmp)
|
|
||||||
start=time.monotonic()
|
|
||||||
if args.fixture:adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testFixture',args.fixture.stem)
|
|
||||||
else:adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',args.id,'--el','testOffset',str(args.offset),'--ei','testMode',str(args.mode),'--ez','testValidation','true')
|
|
||||||
ready=None;records=[]
|
|
||||||
while time.monotonic()-start<55:
|
|
||||||
_,records=audit()
|
|
||||||
if args.fixture and any(r['event'] in ('error','prepareFailure') for r in records):break
|
|
||||||
samples=[r for r in records if r['event']=='sample']
|
|
||||||
if samples:
|
|
||||||
last=samples[-1]
|
|
||||||
video=last.get('videoCounters',{})
|
|
||||||
if last.get('playing') and (video.get('rendered',0)>5 or not expects_video and any(r['event']=='audioAdvancing' for r in records)):
|
|
||||||
ready=round(time.monotonic()-start,2);break
|
|
||||||
time.sleep(.8)
|
|
||||||
if ready is not None:time.sleep(args.seconds)
|
|
||||||
raw,records=audit();(folder/'audit-steady.jsonl').write_bytes(raw)
|
|
||||||
(folder/'signal-steady.txt').write_bytes(snapshot_signal())
|
|
||||||
(folder/'surface-steady.txt').write_bytes(adb('shell','dumpsys','SurfaceFlinger'))
|
|
||||||
if args.observe_hdmi:
|
|
||||||
import device
|
|
||||||
original=device.DEVICE
|
|
||||||
try:
|
|
||||||
device.DEVICE='192.168.50.200:5555'
|
|
||||||
(folder/'tcl-hdmi.jsonl').write_bytes(adb('exec-out','run-as','tv.kaleido.app','cat','files/hdmi-validation.jsonl'))
|
|
||||||
(folder/'tcl-picture.png').write_bytes(adb('exec-out','screencap','-p'))
|
|
||||||
finally:device.DEVICE=original
|
|
||||||
if args.screenshot:(folder/'onn-picture.png').write_bytes(adb('exec-out','screencap','-p'))
|
|
||||||
seek_result=None
|
|
||||||
if args.seek and ready is not None:
|
|
||||||
adb('shell','input','keyevent','127');time.sleep(1.5)
|
|
||||||
_,paused=audit();old=[r for r in paused if r['event']=='sample'][-1]['position']
|
|
||||||
for _ in range(3):
|
|
||||||
_,current=audit();position=[r for r in current if r['event']=='sample'][-1]['position']
|
|
||||||
adb('shell','input','keyevent','89')
|
|
||||||
deadline=time.monotonic()+25
|
|
||||||
while time.monotonic()<deadline:
|
|
||||||
time.sleep(.8);_,check=audit();sample=[r for r in check if r['event']=='sample'][-1]
|
|
||||||
if sample['state']==3 and abs(sample['position']-(position-10000))<2200:break
|
|
||||||
_,rewound=audit();new=[r for r in rewound if r['event']=='sample'][-1]['position']
|
|
||||||
adb('shell','input','keyevent','126');time.sleep(3)
|
|
||||||
seek_result={'from':old,'to':new,'expectedDelta':-30000,'correct':abs((old-new)-30000)<2500}
|
|
||||||
for _ in range(3):
|
|
||||||
adb('shell','input','keyevent','4');time.sleep(.8)
|
|
||||||
_,r=audit()
|
|
||||||
if any(x['event']=='closed' for x in r):break
|
|
||||||
time.sleep(1)
|
|
||||||
raw,records=audit();(folder/'audit.jsonl').write_bytes(raw)
|
|
||||||
samples=[r for r in records if r['event']=='sample']
|
|
||||||
steady=[r for r in samples if r.get('playing')]
|
|
||||||
last=steady[-1] if steady else {}
|
|
||||||
after=before if args.fixture else get('/library/metadata/'+args.id)['Metadata'][0]
|
|
||||||
result={'label':args.label,'id':args.id,'device':DEVICE,'requestedMode':args.mode,'readySeconds':ready,
|
|
||||||
'firstFrame':any(r['event']=='firstFrame' for r in records),'audioAdvancing':any(r['event']=='audioAdvancing' for r in records),
|
|
||||||
'videoDecoders':[r['name'] for r in records if r['event']=='videoDecoder'],
|
|
||||||
'audioDecoders':[r['name'] for r in records if r['event']=='audioDecoder'],
|
|
||||||
'audioTracks':[r for r in records if r['event']=='audioTrack'],
|
|
||||||
'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),
|
|
||||||
'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)}
|
|
||||||
(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('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 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 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.expect_mode is not None and last.get('mode')!=args.expect_mode:raise SystemExit('Unexpected delivery mode')
|
|
||||||
if args.expect_width is not None and last.get('video',{}).get('width')!=args.expect_width:raise SystemExit('Unexpected delivered video width')
|
|
||||||
if args.expect_channels is not None and last.get('audio',{}).get('channels')!=args.expect_channels:raise SystemExit('Unexpected delivered audio channel count')
|
|
||||||
if args.expect_audio_encoding is not None and (not result['audioTracks'] or result['audioTracks'][-1]['encoding']!=args.expect_audio_encoding):raise SystemExit('Unexpected audio output encoding')
|
|
||||||
if __name__=='__main__':main()
|
|
||||||
|
|
@ -1,120 +0,0 @@
|
||||||
"""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']()
|
|
||||||
|
|
@ -1,105 +0,0 @@
|
||||||
"""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')
|
|
||||||
|
|
@ -1,76 +0,0 @@
|
||||||
"""Live details/cast/related checks on the onn. Temporarily toggles unwatched fixtures.
|
|
||||||
|
|
||||||
The movie and every episode of the show must start unwatched with no resume point.
|
|
||||||
Both are restored, including on failure. Do not run beside another device/UI test.
|
|
||||||
"""
|
|
||||||
import json,time,urllib.parse,urllib.request
|
|
||||||
from device import adb,OUT,screenshot
|
|
||||||
from inspect_server import get,base,token
|
|
||||||
from verify_ui import launch,key,text,focused,wait,focus,labels,snapshot
|
|
||||||
|
|
||||||
MOVIE='36486' # Matchbox: first recent-release movie on the private test server.
|
|
||||||
SHOW='16413' # 3 Body Problem: first A-Z show, eight initially unwatched episodes.
|
|
||||||
|
|
||||||
def metadata(ident):return get('/library/metadata/'+ident)['Metadata'][0]
|
|
||||||
def leaves(ident):return get('/library/metadata/'+ident+'/allLeaves').get('Metadata',[])
|
|
||||||
def clean(item):return not item.get('viewCount',0) and not item.get('viewOffset',0)
|
|
||||||
|
|
||||||
def reset(ident):
|
|
||||||
# Cleanup uses Plex's same endpoint if a failing UI cannot restore the fixture.
|
|
||||||
path='/:/unscrobble?'+urllib.parse.urlencode({'key':ident,'identifier':'com.plexapp.plugins.library'})
|
|
||||||
request=urllib.request.Request(base+path,headers={'X-Plex-Token':token,'Accept':'application/json'})
|
|
||||||
with urllib.request.urlopen(request,timeout=20) as response:assert response.status==200
|
|
||||||
|
|
||||||
def main():
|
|
||||||
movie=metadata(MOVIE);show=metadata(SHOW);episodes=leaves(SHOW)
|
|
||||||
assert clean(movie),'Movie fixture has existing watched/resume state; choose another fixture'
|
|
||||||
assert episodes and all(clean(e) for e in episodes),'Show fixture has existing watched/resume state; choose another fixture'
|
|
||||||
results=[];touched=set()
|
|
||||||
try:
|
|
||||||
launch();key(22);focused('Movies');text('Recently released');key(20);focused('Discover');key(20);key(23)
|
|
||||||
text(movie['title']);text('Cast');focused('Play');text('Mark watched')
|
|
||||||
key(22);focused('Mark watched');touched.add(MOVIE);key(23);focused('Mark unwatched')
|
|
||||||
assert metadata(MOVIE).get('viewCount',0)>0
|
|
||||||
screenshot('details-movie-watched');key(23);focused('Mark watched');assert clean(metadata(MOVIE))
|
|
||||||
results.append('Movie watched/unwatched persisted in Plex');print('PASS '+results[-1],flush=True)
|
|
||||||
key(21);focused('Play');key(20)
|
|
||||||
actor=movie['Role'][0];focused(actor['tag']);key(23)
|
|
||||||
expected=[]
|
|
||||||
for section in get('/library/sections').get('Directory',[]):
|
|
||||||
if section['type'] in ('movie','show'):
|
|
||||||
expected.extend(get('/library/sections/'+section['key']+'/all?actor='+str(actor['id'])).get('Metadata',[]))
|
|
||||||
expected={j['ratingKey']:j for j in expected};text(actor['tag']);text(str(len(expected))+' titles')
|
|
||||||
wait(lambda r:focus(r) not in ('','Back'),'Actor title grid focus');first=focus(snapshot());key(22);second=focus(snapshot());key(23)
|
|
||||||
wait(lambda r:'Cast' in labels(r),'Selected actor title details');key(4);focused(second);key(4);focused(actor['tag'])
|
|
||||||
screenshot('details-cast-restored')
|
|
||||||
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)
|
|
||||||
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)
|
|
||||||
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')
|
|
||||||
assert metadata(SHOW).get('viewedLeafCount')==len(episodes)
|
|
||||||
assert all(e.get('viewCount',0)>0 for e in leaves(SHOW))
|
|
||||||
screenshot('details-show-watched');key(23);focused('Mark watched')
|
|
||||||
assert metadata(SHOW).get('viewedLeafCount',0)==0 and all(clean(e) for e in leaves(SHOW))
|
|
||||||
results.append('Series watched/unwatched updates every episode in Plex');print('PASS '+results[-1],flush=True)
|
|
||||||
related=get('/library/metadata/'+SHOW+'/related').get('Hub',[])
|
|
||||||
expected_related={m['ratingKey'] for h in related for m in h.get('Metadata',[]) if m.get('type')=='show' and m['ratingKey']!=SHOW}
|
|
||||||
assert expected_related,'Related-show fixture missing server-generated hubs'
|
|
||||||
key(21);focused('Watch next');key(20);text('Seasons');key(20);focused(show['Role'][0]['tag']);key(20)
|
|
||||||
# Trailers & extras, when Plex has them, sit between Cast and Related shows.
|
|
||||||
if 'Trailers & extras' in labels(snapshot()):wait(lambda r:'Trailer' in focus(r) or 'Extra' in focus(r) or 'Scene' in focus(r) or 'Behind' in focus(r),'Extras row focus');key(20)
|
|
||||||
text('Related shows')
|
|
||||||
selected=focus(snapshot());assert selected and selected not in ('Watch next','Mark watched')
|
|
||||||
screenshot('details-related-shows');key(23);focused('Watch next');key(4);focused(selected)
|
|
||||||
results.append('Server-related shows render, open and restore focus');print('PASS '+results[-1],flush=True)
|
|
||||||
key(4,3);focused('Home')
|
|
||||||
finally:
|
|
||||||
for ident in touched:
|
|
||||||
changed=not clean(metadata(ident)) if ident==MOVIE else any(not clean(e) for e in leaves(ident))
|
|
||||||
if changed:reset(ident)
|
|
||||||
assert clean(metadata(MOVIE)) and all(clean(e) for e in leaves(SHOW)),'Fixture restoration failed'
|
|
||||||
(OUT/'details-feature-results.json').write_text(json.dumps(results,indent=2)+'\n')
|
|
||||||
print('PASS original unwatched/resume state restored for both fixtures',flush=True)
|
|
||||||
|
|
||||||
if __name__=='__main__':main()
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
"""Check a fresh show page keeps its Back control and description in the safe area."""
|
|
||||||
import re
|
|
||||||
from device import screenshot
|
|
||||||
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)
|
|
||||||
wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Show library loaded');focused('Library');key(20)
|
|
||||||
# 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')
|
|
||||||
root=snapshot();screenshot('show-layout-current')
|
|
||||||
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'))))
|
|
||||||
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)
|
|
||||||
assert bounds[1]>=88,'Show title was scrolled above the safe header area on initial focus'
|
|
||||||
assert back is not None,'Back control must remain visible on initial show entry'
|
|
||||||
back_bounds=list(map(int,re.findall(r'\d+',back.get('bounds'))))
|
|
||||||
assert back_bounds[1]>=0 and back_bounds[3]>back_bounds[1],'Back control must stay inside the visible header'
|
|
||||||
assert 'Seasons' in labels(root),'Seasons must lead the rows beneath show information'
|
|
||||||
screen=list(map(int,re.findall(r'\d+',root.find('node').get('bounds'))))
|
|
||||||
captions=[n for n in root.iter('node') if re.fullmatch(r'Season \d+',n.get('text',''))]
|
|
||||||
assert captions,'Season captions must be visible without scrolling'
|
|
||||||
for caption in captions:
|
|
||||||
box=list(map(int,re.findall(r'\d+',caption.get('bounds'))))
|
|
||||||
assert box[3]<=screen[3]-24,'Season caption must fit inside the bottom safe area'
|
|
||||||
summary=max((n for n in root.iter('node') if len(n.get('text',''))>120),key=lambda n:len(n.get('text')))
|
|
||||||
summary_bounds=list(map(int,re.findall(r'\d+',summary.get('bounds'))))
|
|
||||||
assert summary_bounds[2]-summary_bounds[0]<=screen[2]*560/960+2,'Show synopsis must use the bounded movie-detail text width'
|
|
||||||
print('PASS safe show header, bounded synopsis, and complete season captions on initial entry')
|
|
||||||
# Trailer and other actions depend on the fixture; move right until Synopsis.
|
|
||||||
for _ in range(5):
|
|
||||||
if 'Synopsis' in focus(snapshot()):break
|
|
||||||
key(22)
|
|
||||||
focused('Synopsis');key(23);focused('Close')
|
|
||||||
dialog=snapshot();screenshot('show-full-synopsis')
|
|
||||||
assert summary.get('text') in labels(dialog),'Full synopsis must remain available in the dialog'
|
|
||||||
key(20);key(19);focused('Close');key(23);focused('Synopsis')
|
|
||||||
key(23);focused('Close');key(4);focused('Synopsis')
|
|
||||||
print('PASS full synopsis opens, scrolls, and restores focus after Close or Back')
|
|
||||||
key(20);focused('Season 1');key(20)
|
|
||||||
wait(lambda r:'Cast' in labels(r) and bool(focus(r)) and 'Season 1' not in focus(r),'Cast focus beneath Seasons')
|
|
||||||
screenshot('show-scrolled-cast')
|
|
||||||
print('PASS Seasons-to-Cast navigation; captured scrolled backdrop for visual review')
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
"""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()
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
"""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')
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
"""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')
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
"""Targeted movie detail layout and related-title check on the authorized onn."""
|
|
||||||
import re
|
|
||||||
from device import screenshot
|
|
||||||
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)
|
|
||||||
wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Movie library loaded')
|
|
||||||
key(20)
|
|
||||||
# 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)
|
|
||||||
wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Movie play action')
|
|
||||||
root=snapshot();screenshot('movie-details-0.1.11')
|
|
||||||
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 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)
|
|
||||||
key(20)
|
|
||||||
wait(lambda r:focus(r) not in ('Play','') and not focus(r).startswith('Resume'),'Cast or related row focus')
|
|
||||||
for _ in range(3):
|
|
||||||
root=snapshot()
|
|
||||||
if 'Related movies' in labels(root):break
|
|
||||||
key(20)
|
|
||||||
assert 'Related movies' in labels(root),'Plex related movies must appear beneath Cast'
|
|
||||||
key(20)
|
|
||||||
root=wait(lambda r:bool(focus(r)) and 'Related movies' in labels(r),'Related movie focus')
|
|
||||||
screenshot('movie-related-0.1.11')
|
|
||||||
key(23)
|
|
||||||
wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Related movie opens')
|
|
||||||
key(4)
|
|
||||||
wait(lambda r:bool(focus(r)) and 'Related movies' in labels(r),'Related movie restores row focus')
|
|
||||||
print('PASS related movies open and Back restores the selected card',flush=True)
|
|
||||||
key(4);focused(selected);key(4);key(4)
|
|
||||||