Compare commits

...
39 Commits
Author SHA1 Message Date
github-actions[bot] 0ba2ecd90a chore: bump version to 1.18.2 2026-02-19 10:34:06 +00:00
edde746 60ef83bd3a fix: add missing setLogLevel handler to Android MPV plugin 2026-02-19 11:33:12 +01:00
edde746 89c7b79867 fix: use identifier as fallback key for EPG channels 2026-02-19 09:13:00 +01:00
edde746 bfe7d54dcf feat: add kBlurArtwork mode for store screenshots
Blurs all artwork and rotates vowels in metadata when enabled.
2026-02-19 05:45:46 +01:00
github-actions[bot] d9bfb73146 chore: bump version to 1.18.1 2026-02-19 04:10:20 +00:00
edde746 fc2aa53197 fix: only auto-focus overlay sheets in dpad mode 2026-02-19 01:55:45 +01:00
edde746 9bf9a6f23b fix: clear stale back-key flags on overlay sheet close 2026-02-19 00:39:44 +01:00
edde746 9e7c66f66a refactor: migrate bottom sheets to overlay system 2026-02-19 00:18:35 +01:00
edde746 63d711ae43 refactor: overlay-based bottom sheets for video player 2026-02-18 23:06:44 +01:00
edde746 7c651eb61f fix: cap ExoPlayer buffer size 2026-02-18 21:17:50 +01:00
edde746 3bba440e18 fix: enable largeHeap for ExoPlayer OOM 2026-02-18 19:13:40 +01:00
edde746 1f44ac6050 docs: add Live TV to readme 2026-02-18 16:35:06 +01:00
edde746 8d5b5d2e0c fix: guard against post-disposal stream controller access 2026-02-18 09:20:48 +01:00
edde746 aae1b1c45c refactor: clean up release script and fastlane configs 2026-02-18 09:15:20 +01:00
github-actions[bot] b74cacd660 chore: bump version to 1.18.0 2026-02-18 07:08:11 +00:00
edde746 1fc0d0458b fix: dpad back navigation for settings sub-screens 2026-02-18 08:06:48 +01:00
edde746 64c0c9979b fix: dpad focus and navigation for Live TV guide 2026-02-18 08:06:05 +01:00
edde746 b419ff5507 fix: custom dpad navigation for sidenav
close #479
2026-02-18 07:55:16 +01:00
edde746 f508013aa5 fix(ios): remove processing background mode 2026-02-18 06:51:44 +01:00
edde746 756eb8d6f0 feat: add ambient lighting effect
close #477
2026-02-18 06:51:20 +01:00
edde746 83e04b64da fix: correct D-pad focus navigation order on media detail screen 2026-02-18 03:30:04 +01:00
edde746andGitHub 408bf8577d Merge pull request #476 from Sphyix/playback-fix
setLogLevel macOS playback
2026-02-18 02:21:59 +01:00
Federico 90e8223c74 setLogLevel missing 2026-02-18 02:18:06 +01:00
edde746andGitHub b1377ea4a1 Merge pull request #473 from Sphyix/playback-fix
Fix playback on macOS
2026-02-18 01:20:57 +01:00
Federico 348aa69a50 Update Info.plist 2026-02-17 17:58:53 +01:00
edde746andGitHub 1913d49117 Merge pull request #471 from AmyJeanes/remove-continue-watching-mid-progress
fix: show 'mark as unwatched' for in progress items
2026-02-17 10:59:38 +01:00
edde746 2bc2c0a0ec feat: use FlTextureGL for Linux mpv video rendering 2026-02-17 08:55:29 +01:00
edde746 544fccf82d fix: update universal_gamepad 2026-02-17 07:51:18 +01:00
edde746 71bfd3ca2f fix: force LF line endings for shell scripts and Dockerfiles 2026-02-17 03:37:49 +01:00
edde746 f2f7bb3508 chore: bump universal_gamepad to 1.1.1 2026-02-17 03:37:03 +01:00
edde746 c98add8065 fix: resolve UI freezes during video playback on Steam Deck
- Default MPV native log level to "warn" instead of "v" (Linux/Windows),
  add setLogLevel method channel to raise it when debug logging is enabled
- Coalesce MPV render requests via atomic compare_exchange on needs_redraw_
- Clear redraw flag before render so new redraws queue during current frame
2026-02-17 03:11:52 +01:00
Amy Jeanes 56b7cb842e show mark as unwatched for mid progress items 2026-02-17 01:24:07 +00:00
edde746 223a5d2219 chore: bump os_media_controls 2026-02-17 01:21:07 +01:00
edde746 66611b9bc3 feat: dockerfile-based steam build with layer caching 2026-02-17 01:20:10 +01:00
edde746 35f56c8a80 feat: steam build script 2026-02-16 23:32:51 +01:00
edde746 653eee1453 feat: add steam deploy script 2026-02-16 21:56:47 +01:00
edde746 29f5dc00c4 feat: populate audio output device menu and group by backend 2026-02-16 21:56:22 +01:00
edde746 9d04833b3e fix: only consume nav keys in video player 2026-02-16 18:34:12 +01:00
github-actions[bot] a55b255d05 chore: update cask to 1.17.0 2026-02-16 16:20:30 +00:00
120 changed files with 3927 additions and 2385 deletions
+19
View File
@@ -0,0 +1,19 @@
.git
build/
.dart_tool/
.idea/
*.tar.gz
nul
libmpv-prefix/
steamfiles/
pubspec_overrides.yaml
# Flutter ephemeral / generated plugin symlinks
linux/flutter/ephemeral/
windows/flutter/
macos/Flutter/
ios/Flutter/
android/.gradle/
android/app/build/
.flutter-plugins
.flutter-plugins-dependencies
+3
View File
@@ -0,0 +1,3 @@
*.sh text eol=lf
*.Dockerfile text eol=lf
Dockerfile text eol=lf
+4 -4
View File
@@ -429,13 +429,13 @@ jobs:
- name: Cache APT packages
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
packages: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
version: 1.1
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
- name: Cache libmpv build
id: libmpv-cache
@@ -537,13 +537,13 @@ jobs:
- name: Cache APT packages
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
packages: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
version: 1.1
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
- name: Cache libmpv build
id: libmpv-cache
+2 -2
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "1.16.1"
sha256 "56a079818bec9d332a2dc9a16d54b20cb477f5d8f104c1870fc1e936acf78d36"
version "1.17.0"
sha256 "6c113c19f550c01bead3263e9f6afd9e066673a631b665fd94761ed54731b41f"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
+9 -5
View File
@@ -13,15 +13,13 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
## Download
### Mobile
<a href='https://apps.apple.com/us/app/id6754315964'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
<a href='https://www.amazon.com/gp/product/B0GK65CVS1'><img height='60' alt='Available at the Amazon App Store' src='./assets/amazon-badge.png'/></a>
### Desktop
- [Windows (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg)
- [Linux (x64)](https://github.com/edde746/plezy/releases/latest) - .deb, .rpm, .pkg.tar.zst, and portable tar.gz available
- [Windows (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
- [macOS (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg)
- [Linux (x64, arm64)](https://github.com/edde746/plezy/releases/latest) - .deb, .rpm, .pkg.tar.zst, and portable tar.gz available
- [NixOS/Nix](https://github.com/mio-19/nurpkgs/tree/main/pkgs/plezy) - Community package by [@mio-19](https://github.com/mio-19)
- **Homebrew** (macOS):
```bash
@@ -49,6 +47,12 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
- Progress sync and resume
- Auto-play next episode
### 📺 Live TV & DVR
- EPG guide grid
- Channel tuning
- DVR recording rules and scheduled recordings
- Multi-server DVR support
### 📥 Downloads
- Download media for offline viewing
- Background downloads with queue management
+10
View File
@@ -0,0 +1,10 @@
# Autogenerated by fastlane
#
# Ensure this file is checked in to source control!
source "https://rubygems.org"
gem 'fastlane'
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
eval_gemfile(plugins_path) if File.exist?(plugins_path)
+244
View File
@@ -0,0 +1,244 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.8)
abbrev (0.1.2)
addressable (2.8.8)
public_suffix (>= 2.0.2, < 8.0)
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.4.0)
aws-partitions (1.1215.0)
aws-sdk-core (3.242.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
base64
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
aws-sdk-kms (1.122.0)
aws-sdk-core (~> 3, >= 3.241.4)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.213.0)
aws-sdk-core (~> 3, >= 3.241.4)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
base64 (0.2.0)
benchmark (0.5.0)
bigdecimal (4.0.1)
claide (1.1.0)
colored (1.2)
colored2 (3.1.2)
commander (4.6.0)
highline (~> 2.0.0)
csv (3.3.5)
declarative (0.0.20)
digest-crc (0.7.0)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.6.20240107)
dotenv (2.8.1)
emoji_regex (3.2.3)
excon (0.112.0)
faraday (1.10.5)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
faraday-httpclient (~> 1.0)
faraday-multipart (~> 1.0)
faraday-net_http (~> 1.0)
faraday-net_http_persistent (~> 1.0)
faraday-patron (~> 1.0)
faraday-rack (~> 1.0)
faraday-retry (~> 1.0)
ruby2_keywords (>= 0.0.4)
faraday-cookie_jar (0.0.8)
faraday (>= 0.8.0)
http-cookie (>= 1.0.0)
faraday-em_http (1.0.0)
faraday-em_synchrony (1.0.1)
faraday-excon (1.1.0)
faraday-httpclient (1.0.1)
faraday-multipart (1.2.0)
multipart-post (~> 2.0)
faraday-net_http (1.0.2)
faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday-retry (1.0.3)
faraday_middleware (1.2.1)
faraday (~> 1.0)
fastimage (2.4.0)
fastlane (2.232.1)
CFPropertyList (>= 2.3, < 4.0.0)
abbrev (~> 0.1.2)
addressable (>= 2.8, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.197)
babosa (>= 1.0.3, < 2.0.0)
base64 (~> 0.2.0)
benchmark (>= 0.1.0)
bundler (>= 1.17.3, < 5.0.0)
colored (~> 1.2)
commander (~> 4.6)
csv (~> 3.3)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 1.0.0)
faraday (~> 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
fastlane-sirp (>= 1.0.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, <= 2.1.1)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
http-cookie (~> 1.0.5)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
logger (>= 1.6, < 2.0)
mini_magick (>= 4.9.4, < 5.0.0)
multipart-post (>= 2.0.0, < 3.0.0)
mutex_m (~> 0.3.0)
naturally (~> 2.2)
nkf (~> 0.2.0)
optparse (>= 0.1.1, < 1.0.0)
ostruct (>= 0.1.0)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.5)
simctl (~> 1.6.3)
terminal-notifier (>= 2.0.0, < 3.0.0)
terminal-table (~> 3)
tty-screen (>= 0.6.3, < 1.0.0)
tty-spinner (>= 0.8.0, < 1.0.0)
word_wrap (~> 1.0.0)
xcodeproj (>= 1.13.0, < 2.0.0)
xcpretty (~> 0.4.1)
xcpretty-travis-formatter (>= 0.0.3, < 2.0.0)
fastlane-plugin-amazon_appstore (1.4.0)
faraday (~> 1.0)
faraday_middleware (~> 1.0)
fastlane-sirp (1.0.0)
sysrandom (~> 1.0)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.96.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-core (0.18.0)
addressable (~> 2.5, >= 2.5.1)
googleauth (~> 1.9)
httpclient (>= 2.8.3, < 3.a)
mini_mime (~> 1.0)
mutex_m
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
google-apis-iamcredentials_v1 (0.26.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-playcustomapp_v1 (0.17.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-storage_v1 (0.60.0)
google-apis-core (>= 0.15.0, < 2.a)
google-cloud-core (1.8.0)
google-cloud-env (>= 1.0, < 3.a)
google-cloud-errors (~> 1.0)
google-cloud-env (2.1.1)
faraday (>= 1.0, < 3.a)
google-cloud-errors (1.5.0)
google-cloud-storage (1.58.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-core (>= 0.18, < 2)
google-apis-iamcredentials_v1 (~> 0.18)
google-apis-storage_v1 (>= 0.42)
google-cloud-core (~> 1.6)
googleauth (~> 1.9)
mini_mime (~> 1.0)
googleauth (1.11.2)
faraday (>= 1.0, < 3.a)
google-cloud-env (~> 2.1)
jwt (>= 1.4, < 3.0)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
signet (>= 0.16, < 2.a)
highline (2.0.3)
http-cookie (1.0.8)
domain_name (~> 0.5)
httpclient (2.9.0)
mutex_m
jmespath (1.6.2)
json (2.18.1)
jwt (2.10.2)
base64
logger (1.7.0)
mini_magick (4.13.2)
mini_mime (1.1.5)
multi_json (1.19.1)
multipart-post (2.4.1)
mutex_m (0.3.0)
nanaimo (0.4.0)
naturally (2.3.0)
nkf (0.2.0)
optparse (0.8.1)
os (1.1.4)
ostruct (0.6.3)
plist (3.7.2)
public_suffix (7.0.2)
rake (13.3.1)
representable (3.2.0)
declarative (< 0.1.0)
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
rexml (3.4.4)
rouge (3.28.0)
ruby2_keywords (0.0.5)
rubyzip (2.4.1)
security (0.1.5)
signet (0.21.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
jwt (>= 1.5, < 4.0)
multi_json (~> 1.10)
simctl (1.6.10)
CFPropertyList
naturally
sysrandom (1.0.5)
terminal-notifier (2.0.0)
terminal-table (3.0.2)
unicode-display_width (>= 1.1.1, < 3)
trailblazer-option (0.1.2)
tty-cursor (0.7.1)
tty-screen (0.8.2)
tty-spinner (0.9.3)
tty-cursor (~> 0.7)
uber (0.1.0)
unicode-display_width (2.6.0)
word_wrap (1.0.0)
xcodeproj (1.27.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.4.0)
rexml (>= 3.3.6, < 4.0)
xcpretty (0.4.1)
rouge (~> 3.28.0)
xcpretty-travis-formatter (1.0.1)
xcpretty (~> 0.2, >= 0.0.7)
PLATFORMS
arm64-darwin-25
ruby
DEPENDENCIES
fastlane
fastlane-plugin-amazon_appstore
BUNDLED WITH
2.7.2
+3
View File
@@ -55,6 +55,9 @@ android {
signingConfig = signingConfigs.getByName("release")
}
// If key.properties doesn't exist, it will use debug signing for CI builds
ndk {
debugSymbolLevel = "FULL"
}
}
}
+1
View File
@@ -43,6 +43,7 @@
android:icon="@mipmap/ic_launcher"
android:banner="@drawable/tv_banner"
android:appCategory="video"
android:largeHeap="true"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
@@ -36,6 +36,7 @@ import androidx.media3.common.Tracks
import androidx.media3.common.VideoSize
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
@@ -202,7 +203,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
}
}
fun initialize(): Boolean {
fun initialize(bufferSizeBytes: Int? = null): Boolean {
if (isInitialized) {
Log.d(TAG, "Already initialized")
return true
@@ -337,8 +338,17 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
val wrappedRenderersFactory = AssRenderersFactory(handler, renderersFactory)
val loadControl = DefaultLoadControl.Builder().apply {
if (bufferSizeBytes != null && bufferSizeBytes > 0) {
setTargetBufferBytes(bufferSizeBytes)
setPrioritizeTimeOverSizeThresholds(false)
Log.d(TAG, "Buffer byte limit set to ${bufferSizeBytes / 1024 / 1024}MB")
}
}.build()
exoPlayer = ExoPlayer.Builder(activity)
.setTrackSelector(trackSelector!!)
.setLoadControl(loadControl)
.setAudioAttributes(audioAttributes, false) // We handle audio focus manually
.setMediaSourceFactory(mediaSourceFactory)
.setRenderersFactory(wrappedRenderersFactory)
@@ -96,7 +96,7 @@ class ExoPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> handleInitialize(result)
"initialize" -> handleInitialize(call, result)
"dispose" -> handleDispose(result)
"open" -> handleOpen(call, result)
"play" -> handlePlay(result)
@@ -125,7 +125,7 @@ class ExoPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
}
}
private fun handleInitialize(result: MethodChannel.Result) {
private fun handleInitialize(call: MethodCall, result: MethodChannel.Result) {
val currentActivity = activity
if (currentActivity == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
@@ -138,12 +138,14 @@ class ExoPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
return
}
val bufferSizeBytes = call.argument<Int>("bufferSizeBytes")
currentActivity.runOnUiThread {
try {
playerCore = ExoPlayerCore(currentActivity).apply {
delegate = this@ExoPlayerPlugin
}
val success = playerCore?.initialize() ?: false
val success = playerCore?.initialize(bufferSizeBytes = bufferSizeBytes) ?: false
// Start hidden
playerCore?.setVisible(false)
@@ -102,6 +102,7 @@ class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
"openContentFd" -> handleOpenContentFd(call, result)
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
"setLogLevel" -> result.success(null)
else -> result.notImplemented()
}
}
+9 -35
View File
@@ -4,37 +4,6 @@ Dotenv.load("../../.env")
default_platform(:android)
platform :android do
desc "Deploy a new version to the Google Play"
lane :deploy do
gradle(task: "clean bundleRelease")
# Get version code from pubspec.yaml
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
pubspec_content = File.read(pubspec_path)
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
if version_match
version_code = version_match[2].to_i
UI.message("Using version code: #{version_code}")
else
UI.user_error!("Could not extract version code from pubspec.yaml")
end
upload_to_play_store(
version_code: version_code,
skip_upload_changelogs: true,
skip_upload_metadata: true,
skip_upload_images: true,
skip_upload_screenshots: true
)
end
desc "Build release AAB"
lane :build do
# Navigate to Flutter project root and build
sh("cd #{ENV['PWD']}/.. && flutter build appbundle --dart-define=ENABLE_IN_APP_REVIEW=true")
end
desc "Build and deploy to Google Play Store"
lane :release do
# Build the Flutter app
@@ -52,12 +21,17 @@ platform :android do
UI.user_error!("Could not extract version code from pubspec.yaml")
end
# Upload to Play Store
upload_to_play_store(
track: "internal",
release_status: "draft",
track: "production",
release_status: "completed",
version_code: version_code,
aab: "../build/app/outputs/bundle/release/app-release.aab"
)
upload_to_amazon_appstore(
apk: "../build/app/outputs/bundle/release/app-release.aab",
overwrite_upload: true,
overwrite_upload_mode: 'reuse'
)
end
end
end
+5
View File
@@ -0,0 +1,5 @@
# Autogenerated by fastlane
#
# Ensure this file is checked in to source control!
gem 'fastlane-plugin-amazon_appstore'
-1
View File
@@ -52,7 +52,6 @@
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>processing</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
+1 -30
View File
@@ -4,35 +4,6 @@ Dotenv.load("../../.env")
default_platform(:ios)
platform :ios do
desc "Push a new beta build to TestFlight"
lane :beta do
build_app(workspace: "Runner.xcworkspace", scheme: "Runner")
upload_to_testflight
end
desc "Push a new release build to the App Store"
lane :release do
build_app(workspace: "Runner.xcworkspace", scheme: "Runner")
upload_to_app_store
end
desc "Build release IPA"
lane :build do
# Navigate to Flutter project root and build
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true")
end
desc "Build and deploy to TestFlight"
lane :deploy_testflight do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true")
# Upload to TestFlight
upload_to_testflight(
skip_waiting_for_build_processing: true
)
end
desc "Build and deploy to App Store"
lane :deploy_appstore do
# Build the Flutter app
@@ -46,4 +17,4 @@ platform :ios do
skip_screenshots: true, # https://github.com/fastlane/fastlane/issues/29735
)
end
end
end
+4
View File
@@ -71,6 +71,10 @@ class SelectKeyUpSuppressor {
_suppressSelectUntilKeyUp = true;
}
static void clearSuppression() {
_suppressSelectUntilKeyUp = false;
}
static bool consumeIfSuppressed(KeyEvent event) {
if (!_suppressSelectUntilKeyUp) return false;
if (event.logicalKey.isSelectKey) {
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "Videoversionen",
"pipButton": "Bild-in-Bild Modus",
"aspectRatioButton": "Seitenverhältnis",
"ambientLighting": "Umgebungsbeleuchtung",
"ambientLightingOn": "Umgebungsbeleuchtung aktivieren",
"ambientLightingOff": "Umgebungsbeleuchtung deaktivieren",
"fullscreenButton": "Vollbild aktivieren",
"exitFullscreenButton": "Vollbild verlassen",
"alwaysOnTopButton": "Immer im Vordergrund",
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "Video versions",
"pipButton": "Picture-in-Picture mode",
"aspectRatioButton": "Aspect ratio",
"ambientLighting": "Ambient lighting",
"ambientLightingOn": "Enable ambient lighting",
"ambientLightingOff": "Disable ambient lighting",
"fullscreenButton": "Enter fullscreen",
"exitFullscreenButton": "Exit fullscreen",
"alwaysOnTopButton": "Always on top",
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "Versiones de video",
"pipButton": "Modo PiP (Imagen en Imagen)",
"aspectRatioButton": "Relación de aspecto",
"ambientLighting": "Iluminación ambiental",
"ambientLightingOn": "Activar iluminación ambiental",
"ambientLightingOff": "Desactivar iluminación ambiental",
"fullscreenButton": "Entrar en pantalla completa",
"exitFullscreenButton": "Salir de pantalla completa",
"alwaysOnTopButton": "Siempre visible",
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "Versions vidéo",
"pipButton": "Mode PiP (Picture-in-Picture)",
"aspectRatioButton": "Format d'image",
"ambientLighting": "Éclairage ambiant",
"ambientLightingOn": "Activer l'éclairage ambiant",
"ambientLightingOff": "Désactiver l'éclairage ambiant",
"fullscreenButton": "Passer en mode plein écran",
"exitFullscreenButton": "Quitter le mode plein écran",
"alwaysOnTopButton": "Always on top",
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "Versioni video",
"pipButton": "Modalità Picture-in-Picture",
"aspectRatioButton": "Proporzioni",
"ambientLighting": "Illuminazione ambientale",
"ambientLightingOn": "Attiva illuminazione ambientale",
"ambientLightingOff": "Disattiva illuminazione ambientale",
"fullscreenButton": "Attiva schermo intero",
"exitFullscreenButton": "Esci da schermo intero",
"alwaysOnTopButton": "Sempre in primo piano",
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "동영상 버전",
"pipButton": "픽처 인 픽처 모드",
"aspectRatioButton": "화면비율",
"ambientLighting": "주변 조명",
"ambientLightingOn": "주변 조명 켜기",
"ambientLightingOff": "주변 조명 끄기",
"fullscreenButton": "전체화면",
"exitFullscreenButton": "전체화면 종료",
"alwaysOnTopButton": "창 최상위 고정",
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "Videoversies",
"pipButton": "Beeld-in-beeld modus",
"aspectRatioButton": "Beeldverhouding",
"ambientLighting": "Omgevingsverlichting",
"ambientLightingOn": "Omgevingsverlichting inschakelen",
"ambientLightingOff": "Omgevingsverlichting uitschakelen",
"fullscreenButton": "Volledig scherm activeren",
"exitFullscreenButton": "Volledig scherm verlaten",
"alwaysOnTopButton": "Altijd bovenop",
+2 -2
View File
@@ -4,9 +4,9 @@
/// To regenerate, run: `dart run slang`
///
/// Locales: 9
/// Strings: 6642 (738 per locale)
/// Strings: 6669 (741 per locale)
///
/// Built on 2026-02-16 at 00:20 UTC
/// Built on 2026-02-18 at 03:36 UTC
// coverage:ignore-file
// ignore_for_file: type=lint, unused_import
+8 -2
View File
@@ -474,6 +474,9 @@ class _TranslationsVideoControlsDe implements TranslationsVideoControlsEn {
@override String get versionsButton => 'Videoversionen';
@override String get pipButton => 'Bild-in-Bild Modus';
@override String get aspectRatioButton => 'Seitenverhältnis';
@override String get ambientLighting => 'Umgebungsbeleuchtung';
@override String get ambientLightingOn => 'Umgebungsbeleuchtung aktivieren';
@override String get ambientLightingOff => 'Umgebungsbeleuchtung deaktivieren';
@override String get fullscreenButton => 'Vollbild aktivieren';
@override String get exitFullscreenButton => 'Vollbild verlassen';
@override String get alwaysOnTopButton => 'Immer im Vordergrund';
@@ -1517,6 +1520,9 @@ extension on TranslationsDe {
'videoControls.versionsButton' => 'Videoversionen',
'videoControls.pipButton' => 'Bild-in-Bild Modus',
'videoControls.aspectRatioButton' => 'Seitenverhältnis',
'videoControls.ambientLighting' => 'Umgebungsbeleuchtung',
'videoControls.ambientLightingOn' => 'Umgebungsbeleuchtung aktivieren',
'videoControls.ambientLightingOff' => 'Umgebungsbeleuchtung deaktivieren',
'videoControls.fullscreenButton' => 'Vollbild aktivieren',
'videoControls.exitFullscreenButton' => 'Vollbild verlassen',
'videoControls.alwaysOnTopButton' => 'Immer im Vordergrund',
@@ -1734,11 +1740,11 @@ extension on TranslationsDe {
'liveTv.overnight' => 'Nacht',
'liveTv.morning' => 'Morgen',
'liveTv.daytime' => 'Tagsüber',
_ => null,
} ?? switch (path) {
'liveTv.evening' => 'Abend',
'liveTv.lateNight' => 'Spätnacht',
'liveTv.whatsOn' => 'Jetzt im TV',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => 'Kanal ansehen',
'downloads.title' => 'Downloads',
'downloads.manage' => 'Verwalten',
+14 -2
View File
@@ -1025,6 +1025,15 @@ class TranslationsVideoControlsEn {
/// en: 'Aspect ratio'
String get aspectRatioButton => 'Aspect ratio';
/// en: 'Ambient lighting'
String get ambientLighting => 'Ambient lighting';
/// en: 'Enable ambient lighting'
String get ambientLightingOn => 'Enable ambient lighting';
/// en: 'Disable ambient lighting'
String get ambientLightingOff => 'Disable ambient lighting';
/// en: 'Enter fullscreen'
String get fullscreenButton => 'Enter fullscreen';
@@ -3000,6 +3009,9 @@ extension on Translations {
'videoControls.versionsButton' => 'Video versions',
'videoControls.pipButton' => 'Picture-in-Picture mode',
'videoControls.aspectRatioButton' => 'Aspect ratio',
'videoControls.ambientLighting' => 'Ambient lighting',
'videoControls.ambientLightingOn' => 'Enable ambient lighting',
'videoControls.ambientLightingOff' => 'Disable ambient lighting',
'videoControls.fullscreenButton' => 'Enter fullscreen',
'videoControls.exitFullscreenButton' => 'Exit fullscreen',
'videoControls.alwaysOnTopButton' => 'Always on top',
@@ -3217,11 +3229,11 @@ extension on Translations {
'liveTv.overnight' => 'Overnight',
'liveTv.morning' => 'Morning',
'liveTv.daytime' => 'Daytime',
_ => null,
} ?? switch (path) {
'liveTv.evening' => 'Evening',
'liveTv.lateNight' => 'Late Night',
'liveTv.whatsOn' => 'What\'s On',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => 'Watch Channel',
'collections.title' => 'Collections',
'collections.collection' => 'Collection',
+8 -2
View File
@@ -474,6 +474,9 @@ class _TranslationsVideoControlsEs implements TranslationsVideoControlsEn {
@override String get versionsButton => 'Versiones de video';
@override String get pipButton => 'Modo PiP (Imagen en Imagen)';
@override String get aspectRatioButton => 'Relación de aspecto';
@override String get ambientLighting => 'Iluminación ambiental';
@override String get ambientLightingOn => 'Activar iluminación ambiental';
@override String get ambientLightingOff => 'Desactivar iluminación ambiental';
@override String get fullscreenButton => 'Entrar en pantalla completa';
@override String get exitFullscreenButton => 'Salir de pantalla completa';
@override String get alwaysOnTopButton => 'Siempre visible';
@@ -1517,6 +1520,9 @@ extension on TranslationsEs {
'videoControls.versionsButton' => 'Versiones de video',
'videoControls.pipButton' => 'Modo PiP (Imagen en Imagen)',
'videoControls.aspectRatioButton' => 'Relación de aspecto',
'videoControls.ambientLighting' => 'Iluminación ambiental',
'videoControls.ambientLightingOn' => 'Activar iluminación ambiental',
'videoControls.ambientLightingOff' => 'Desactivar iluminación ambiental',
'videoControls.fullscreenButton' => 'Entrar en pantalla completa',
'videoControls.exitFullscreenButton' => 'Salir de pantalla completa',
'videoControls.alwaysOnTopButton' => 'Siempre visible',
@@ -1734,11 +1740,11 @@ extension on TranslationsEs {
'liveTv.overnight' => 'Madrugada',
'liveTv.morning' => 'Mañana',
'liveTv.daytime' => 'Día',
_ => null,
} ?? switch (path) {
'liveTv.evening' => 'Noche',
'liveTv.lateNight' => 'Trasnoche',
'liveTv.whatsOn' => 'En emisión',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => 'Ver canal',
'collections.title' => 'Colecciones',
'collections.collection' => 'Colección',
+8 -2
View File
@@ -474,6 +474,9 @@ class _TranslationsVideoControlsFr implements TranslationsVideoControlsEn {
@override String get versionsButton => 'Versions vidéo';
@override String get pipButton => 'Mode PiP (Picture-in-Picture)';
@override String get aspectRatioButton => 'Format d\'image';
@override String get ambientLighting => 'Éclairage ambiant';
@override String get ambientLightingOn => 'Activer l\'éclairage ambiant';
@override String get ambientLightingOff => 'Désactiver l\'éclairage ambiant';
@override String get fullscreenButton => 'Passer en mode plein écran';
@override String get exitFullscreenButton => 'Quitter le mode plein écran';
@override String get alwaysOnTopButton => 'Always on top';
@@ -1517,6 +1520,9 @@ extension on TranslationsFr {
'videoControls.versionsButton' => 'Versions vidéo',
'videoControls.pipButton' => 'Mode PiP (Picture-in-Picture)',
'videoControls.aspectRatioButton' => 'Format d\'image',
'videoControls.ambientLighting' => 'Éclairage ambiant',
'videoControls.ambientLightingOn' => 'Activer l\'éclairage ambiant',
'videoControls.ambientLightingOff' => 'Désactiver l\'éclairage ambiant',
'videoControls.fullscreenButton' => 'Passer en mode plein écran',
'videoControls.exitFullscreenButton' => 'Quitter le mode plein écran',
'videoControls.alwaysOnTopButton' => 'Always on top',
@@ -1734,11 +1740,11 @@ extension on TranslationsFr {
'liveTv.overnight' => 'Nuit',
'liveTv.morning' => 'Matin',
'liveTv.daytime' => 'Journée',
_ => null,
} ?? switch (path) {
'liveTv.evening' => 'Soirée',
'liveTv.lateNight' => 'Nuit tardive',
'liveTv.whatsOn' => 'En ce moment',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => 'Regarder la chaîne',
'collections.title' => 'Collections',
'collections.collection' => 'Collection',
+8 -2
View File
@@ -474,6 +474,9 @@ class _TranslationsVideoControlsIt implements TranslationsVideoControlsEn {
@override String get versionsButton => 'Versioni video';
@override String get pipButton => 'Modalità Picture-in-Picture';
@override String get aspectRatioButton => 'Proporzioni';
@override String get ambientLighting => 'Illuminazione ambientale';
@override String get ambientLightingOn => 'Attiva illuminazione ambientale';
@override String get ambientLightingOff => 'Disattiva illuminazione ambientale';
@override String get fullscreenButton => 'Attiva schermo intero';
@override String get exitFullscreenButton => 'Esci da schermo intero';
@override String get alwaysOnTopButton => 'Sempre in primo piano';
@@ -1517,6 +1520,9 @@ extension on TranslationsIt {
'videoControls.versionsButton' => 'Versioni video',
'videoControls.pipButton' => 'Modalità Picture-in-Picture',
'videoControls.aspectRatioButton' => 'Proporzioni',
'videoControls.ambientLighting' => 'Illuminazione ambientale',
'videoControls.ambientLightingOn' => 'Attiva illuminazione ambientale',
'videoControls.ambientLightingOff' => 'Disattiva illuminazione ambientale',
'videoControls.fullscreenButton' => 'Attiva schermo intero',
'videoControls.exitFullscreenButton' => 'Esci da schermo intero',
'videoControls.alwaysOnTopButton' => 'Sempre in primo piano',
@@ -1734,11 +1740,11 @@ extension on TranslationsIt {
'liveTv.overnight' => 'Notte',
'liveTv.morning' => 'Mattina',
'liveTv.daytime' => 'Giorno',
_ => null,
} ?? switch (path) {
'liveTv.evening' => 'Sera',
'liveTv.lateNight' => 'Notte tarda',
'liveTv.whatsOn' => 'In onda ora',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => 'Guarda canale',
'downloads.title' => 'Download',
'downloads.manage' => 'Gestisci',
+8 -2
View File
@@ -474,6 +474,9 @@ class _TranslationsVideoControlsKo implements TranslationsVideoControlsEn {
@override String get versionsButton => '동영상 버전';
@override String get pipButton => '픽처 인 픽처 모드';
@override String get aspectRatioButton => '화면비율';
@override String get ambientLighting => '주변 조명';
@override String get ambientLightingOn => '주변 조명 켜기';
@override String get ambientLightingOff => '주변 조명 끄기';
@override String get fullscreenButton => '전체화면';
@override String get exitFullscreenButton => '전체화면 종료';
@override String get alwaysOnTopButton => '창 최상위 고정';
@@ -1517,6 +1520,9 @@ extension on TranslationsKo {
'videoControls.versionsButton' => '동영상 버전',
'videoControls.pipButton' => '픽처 인 픽처 모드',
'videoControls.aspectRatioButton' => '화면비율',
'videoControls.ambientLighting' => '주변 조명',
'videoControls.ambientLightingOn' => '주변 조명 켜기',
'videoControls.ambientLightingOff' => '주변 조명 끄기',
'videoControls.fullscreenButton' => '전체화면',
'videoControls.exitFullscreenButton' => '전체화면 종료',
'videoControls.alwaysOnTopButton' => '창 최상위 고정',
@@ -1734,11 +1740,11 @@ extension on TranslationsKo {
'liveTv.overnight' => '심야',
'liveTv.morning' => '아침',
'liveTv.daytime' => '낮',
_ => null,
} ?? switch (path) {
'liveTv.evening' => '저녁',
'liveTv.lateNight' => '심야 방송',
'liveTv.whatsOn' => '지금 방송 중',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => '채널 시청',
'collections.title' => '컬렉션',
'collections.collection' => '컬렉션',
+8 -2
View File
@@ -474,6 +474,9 @@ class _TranslationsVideoControlsNl implements TranslationsVideoControlsEn {
@override String get versionsButton => 'Videoversies';
@override String get pipButton => 'Beeld-in-beeld modus';
@override String get aspectRatioButton => 'Beeldverhouding';
@override String get ambientLighting => 'Omgevingsverlichting';
@override String get ambientLightingOn => 'Omgevingsverlichting inschakelen';
@override String get ambientLightingOff => 'Omgevingsverlichting uitschakelen';
@override String get fullscreenButton => 'Volledig scherm activeren';
@override String get exitFullscreenButton => 'Volledig scherm verlaten';
@override String get alwaysOnTopButton => 'Altijd bovenop';
@@ -1517,6 +1520,9 @@ extension on TranslationsNl {
'videoControls.versionsButton' => 'Videoversies',
'videoControls.pipButton' => 'Beeld-in-beeld modus',
'videoControls.aspectRatioButton' => 'Beeldverhouding',
'videoControls.ambientLighting' => 'Omgevingsverlichting',
'videoControls.ambientLightingOn' => 'Omgevingsverlichting inschakelen',
'videoControls.ambientLightingOff' => 'Omgevingsverlichting uitschakelen',
'videoControls.fullscreenButton' => 'Volledig scherm activeren',
'videoControls.exitFullscreenButton' => 'Volledig scherm verlaten',
'videoControls.alwaysOnTopButton' => 'Altijd bovenop',
@@ -1734,11 +1740,11 @@ extension on TranslationsNl {
'liveTv.overnight' => 'Nacht',
'liveTv.morning' => 'Ochtend',
'liveTv.daytime' => 'Overdag',
_ => null,
} ?? switch (path) {
'liveTv.evening' => 'Avond',
'liveTv.lateNight' => 'Late avond',
'liveTv.whatsOn' => 'Nu op TV',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => 'Kanaal bekijken',
'downloads.title' => 'Downloads',
'downloads.manage' => 'Beheren',
+8 -2
View File
@@ -474,6 +474,9 @@ class _TranslationsVideoControlsSv implements TranslationsVideoControlsEn {
@override String get versionsButton => 'Videoversioner';
@override String get pipButton => 'Bild-i-bild läge';
@override String get aspectRatioButton => 'Bildförhållande';
@override String get ambientLighting => 'Ambientbelysning';
@override String get ambientLightingOn => 'Aktivera ambientbelysning';
@override String get ambientLightingOff => 'Inaktivera ambientbelysning';
@override String get fullscreenButton => 'Aktivera helskärm';
@override String get exitFullscreenButton => 'Avsluta helskärm';
@override String get alwaysOnTopButton => 'Alltid överst';
@@ -1517,6 +1520,9 @@ extension on TranslationsSv {
'videoControls.versionsButton' => 'Videoversioner',
'videoControls.pipButton' => 'Bild-i-bild läge',
'videoControls.aspectRatioButton' => 'Bildförhållande',
'videoControls.ambientLighting' => 'Ambientbelysning',
'videoControls.ambientLightingOn' => 'Aktivera ambientbelysning',
'videoControls.ambientLightingOff' => 'Inaktivera ambientbelysning',
'videoControls.fullscreenButton' => 'Aktivera helskärm',
'videoControls.exitFullscreenButton' => 'Avsluta helskärm',
'videoControls.alwaysOnTopButton' => 'Alltid överst',
@@ -1734,11 +1740,11 @@ extension on TranslationsSv {
'liveTv.overnight' => 'Natt',
'liveTv.morning' => 'Morgon',
'liveTv.daytime' => 'Dagtid',
_ => null,
} ?? switch (path) {
'liveTv.evening' => 'Kväll',
'liveTv.lateNight' => 'Sen kväll',
'liveTv.whatsOn' => 'På TV nu',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => 'Titta på kanal',
'downloads.title' => 'Nedladdningar',
'downloads.manage' => 'Hantera',
+8 -2
View File
@@ -474,6 +474,9 @@ class _TranslationsVideoControlsZh implements TranslationsVideoControlsEn {
@override String get versionsButton => '视频版本';
@override String get pipButton => '画中画模式';
@override String get aspectRatioButton => '宽高比';
@override String get ambientLighting => '氛围灯光';
@override String get ambientLightingOn => '开启氛围灯光';
@override String get ambientLightingOff => '关闭氛围灯光';
@override String get fullscreenButton => '进入全屏';
@override String get exitFullscreenButton => '退出全屏';
@override String get alwaysOnTopButton => '置顶窗口';
@@ -1517,6 +1520,9 @@ extension on TranslationsZh {
'videoControls.versionsButton' => '视频版本',
'videoControls.pipButton' => '画中画模式',
'videoControls.aspectRatioButton' => '宽高比',
'videoControls.ambientLighting' => '氛围灯光',
'videoControls.ambientLightingOn' => '开启氛围灯光',
'videoControls.ambientLightingOff' => '关闭氛围灯光',
'videoControls.fullscreenButton' => '进入全屏',
'videoControls.exitFullscreenButton' => '退出全屏',
'videoControls.alwaysOnTopButton' => '置顶窗口',
@@ -1734,11 +1740,11 @@ extension on TranslationsZh {
'liveTv.overnight' => '凌晨',
'liveTv.morning' => '上午',
'liveTv.daytime' => '白天',
_ => null,
} ?? switch (path) {
'liveTv.evening' => '晚上',
'liveTv.lateNight' => '深夜',
'liveTv.whatsOn' => '正在播出',
_ => null,
} ?? switch (path) {
'liveTv.watchChannel' => '观看频道',
'downloads.title' => '下载',
'downloads.manage' => '管理',
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "Videoversioner",
"pipButton": "Bild-i-bild läge",
"aspectRatioButton": "Bildförhållande",
"ambientLighting": "Ambientbelysning",
"ambientLightingOn": "Aktivera ambientbelysning",
"ambientLightingOff": "Inaktivera ambientbelysning",
"fullscreenButton": "Aktivera helskärm",
"exitFullscreenButton": "Avsluta helskärm",
"alwaysOnTopButton": "Alltid överst",
+3
View File
@@ -320,6 +320,9 @@
"versionsButton": "视频版本",
"pipButton": "画中画模式",
"aspectRatioButton": "宽高比",
"ambientLighting": "氛围灯光",
"ambientLightingOn": "开启氛围灯光",
"ambientLightingOff": "关闭氛围灯光",
"fullscreenButton": "进入全屏",
"exitFullscreenButton": "退出全屏",
"alwaysOnTopButton": "置顶窗口",
+1 -1
View File
@@ -34,7 +34,7 @@ class LiveTvChannel {
factory LiveTvChannel.fromJson(Map<String, dynamic> json) {
return LiveTvChannel(
key: json['key'] as String? ?? json['ratingKey'] as String? ?? '',
key: json['key'] as String? ?? json['ratingKey'] as String? ?? json['identifier'] as String? ?? json['channelIdentifier'] as String? ?? '',
identifier: json['identifier'] as String? ?? json['channelIdentifier'] as String?,
callSign: json['callSign'] as String?,
title: json['title'] as String? ?? json['callSign'] as String?,
+2 -1
View File
@@ -1,3 +1,4 @@
import '../widgets/plex_optimized_image.dart' show kBlurArtwork, obfuscateText;
import 'plex_metadata.dart';
/// Represents a Plex hub/recommendation section (e.g., Trending Movies, Top Thrillers)
@@ -54,7 +55,7 @@ class PlexHub {
return PlexHub(
hubKey: json['key'] as String? ?? '',
title: json['title'] as String? ?? 'Unknown',
title: kBlurArtwork ? obfuscateText(json['title'] as String? ?? 'Unknown') : json['title'] as String? ?? 'Unknown',
type: json['type'] as String? ?? 'hub',
hubIdentifier: json['hubIdentifier'] as String?,
size: (json['size'] as num?)?.toInt() ?? metadataList.length,
+18 -1
View File
@@ -1,6 +1,7 @@
import 'package:json_annotation/json_annotation.dart';
import '../services/settings_service.dart' show EpisodePosterMode;
import '../widgets/plex_optimized_image.dart' show kBlurArtwork, obfuscateText;
import 'mixins/multi_server_fields.dart';
import 'plex_role.dart';
@@ -382,6 +383,13 @@ class PlexMetadata with MultiServerFields {
return false;
}
/// Returns true if this item has started but not finished playback
/// Only applicable for individual items (movies, episodes)
bool get hasActiveProgress {
if (duration == null || viewOffset == null) return false;
return viewOffset! > 0 && viewOffset! < duration!;
}
// Helper to determine if content is watched
bool get isWatched {
// For series/seasons, check if all episodes are watched
@@ -393,7 +401,16 @@ class PlexMetadata with MultiServerFields {
return viewCount != null && viewCount! > 0;
}
factory PlexMetadata.fromJson(Map<String, dynamic> json) => _$PlexMetadataFromJson(json);
factory PlexMetadata.fromJson(Map<String, dynamic> json) =>
_$PlexMetadataFromJson(kBlurArtwork ? _obfuscateJson(json) : json);
static Map<String, dynamic> _obfuscateJson(Map<String, dynamic> json) {
final copy = Map<String, dynamic>.from(json);
for (final key in const ['title', 'summary', 'tagline', 'grandparentTitle', 'parentTitle', 'studio']) {
if (copy[key] is String) copy[key] = obfuscateText(copy[key] as String);
}
return copy;
}
Map<String, dynamic> toJson() => _$PlexMetadataToJson(this);
}
+11 -1
View File
@@ -1,5 +1,6 @@
import 'package:json_annotation/json_annotation.dart';
import '../widgets/plex_optimized_image.dart' show kBlurArtwork, obfuscateText;
import 'mixins/multi_server_fields.dart';
part 'plex_playlist.g.dart';
@@ -94,7 +95,16 @@ class PlexPlaylist with MultiServerFields {
/// Playlists don't track viewed leaf count
int? get viewedLeafCount => null;
factory PlexPlaylist.fromJson(Map<String, dynamic> json) => _$PlexPlaylistFromJson(json);
factory PlexPlaylist.fromJson(Map<String, dynamic> json) {
if (kBlurArtwork) {
final copy = Map<String, dynamic>.from(json);
for (final key in const ['title', 'summary']) {
if (copy[key] is String) copy[key] = obfuscateText(copy[key] as String);
}
return _$PlexPlaylistFromJson(copy);
}
return _$PlexPlaylistFromJson(json);
}
Map<String, dynamic> toJson() => _$PlexPlaylistToJson(this);
+3 -6
View File
@@ -2,11 +2,8 @@ import '../player_native.dart';
/// Linux implementation of [Player].
///
/// Uses libmpv with OpenGL rendering via GtkGLArea.
/// The mpv video is rendered to a GtkGLArea positioned behind
/// the Flutter view using a GtkOverlay, with transparent regions
/// in the Flutter UI allowing the video to show through.
/// Uses libmpv with FlTextureGL — video is rendered to an offscreen FBO
/// and composited GPU-side via Flutter's Texture widget.
class PlayerLinux extends PlayerNative {
@override
int? get textureId => null; // Uses GtkGLArea, not Flutter texture
// textureId is set during initialize() via PlayerNative
}
+6
View File
@@ -142,6 +142,12 @@ abstract class Player {
/// Get an MPV property value by name.
Future<String?> getProperty(String name);
/// Set the native MPV log message level (e.g., "warn", "v", "debug").
///
/// This controls the volume of log messages sent from the native player
/// over the event channel. Use "warn" in production and "v" for debugging.
Future<void> setLogLevel(String level);
/// Execute a raw MPV command.
///
/// [args] - Command and arguments as a list of strings.
+8 -1
View File
@@ -9,6 +9,8 @@ class PlayerAndroid extends PlayerBase {
static const _methodChannel = MethodChannel('com.plezy/exo_player');
static const _eventChannel = EventChannel('com.plezy/exo_player/events');
int? _bufferSizeBytes;
@override
MethodChannel get methodChannel => _methodChannel;
@@ -46,7 +48,9 @@ class PlayerAndroid extends PlayerBase {
if (initialized) return;
try {
final result = await methodChannel.invokeMethod<bool>('initialize');
final result = await methodChannel.invokeMethod<bool>('initialize', {
'bufferSizeBytes': _bufferSizeBytes,
});
initialized = result == true;
if (!initialized) {
throw Exception('Failed to initialize ExoPlayer');
@@ -181,6 +185,9 @@ class PlayerAndroid extends PlayerBase {
case 'speed':
await setRate(double.tryParse(value) ?? 1.0);
break;
case 'demuxer-max-bytes':
_bufferSizeBytes = int.tryParse(value);
break;
// Other properties are no-ops for ExoPlayer
}
}
+47 -2
View File
@@ -36,6 +36,7 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
int? get textureId => null;
StreamSubscription? _eventSubscription;
StreamSubscription? _logSubscription;
bool _disposed = false;
final _throttleSw = Stopwatch()..start();
int _lastEmitMs = 0;
@@ -63,7 +64,7 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
PlayerBase() {
_streams = createStreams();
_setupEventListener();
logController.stream.listen(_forwardToAppLogger);
_logSubscription = logController.stream.listen(_forwardToAppLogger);
}
void _forwardToAppLogger(PlayerLog log) {
@@ -89,6 +90,7 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
_eventSubscription = eventChannel.receiveBroadcastStream().listen(
_handleEvent,
onError: (error) {
if (_disposed) return;
errorController.add(error.toString());
},
);
@@ -108,8 +110,9 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
}
void _handleEvent(dynamic event) {
if (_disposed) return;
if (event is List && event.length == 2) {
final name = _propIdToName[event[0]];
final name = _propIdToName[event[0] as int];
if (name != null) {
handlePropertyChange(name, event[1]);
}
@@ -125,6 +128,7 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
/// Handle a property change event from the platform.
/// Subclasses can override this to handle platform-specific properties.
void handlePropertyChange(String name, dynamic value) {
if (_disposed) return;
switch (name) {
case 'pause':
final playing = value == false;
@@ -217,12 +221,48 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
case 'sid':
updateSelectedSubtitleTrack(value);
break;
case 'audio-device-list':
List? deviceList;
if (value is List) {
deviceList = value;
} else if (value is String && value.isNotEmpty) {
try {
final parsed = jsonDecode(value);
if (parsed is List) deviceList = parsed;
} catch (_) {}
}
if (deviceList != null) {
final devices = deviceList
.whereType<Map>()
.map((d) => AudioDevice(
name: d['name'] as String? ?? '',
description: d['description'] as String? ?? '',
))
.toList();
_state = _state.copyWith(audioDevices: devices);
audioDevicesController.add(devices);
}
break;
case 'audio-device':
if (value is String && value.isNotEmpty) {
final device = _state.audioDevices.cast<AudioDevice?>().firstWhere(
(d) => d?.name == value,
orElse: () => AudioDevice(name: value),
) ??
AudioDevice(name: value);
_state = _state.copyWith(audioDevice: device);
audioDeviceController.add(device);
}
break;
}
}
/// Handle a player event from the platform.
/// Subclasses can override this to handle platform-specific events.
void handlePlayerEvent(String name, Map? data) {
if (_disposed) return;
switch (name) {
case 'end-file':
final reason = data?['reason'] as String?;
@@ -401,6 +441,10 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
// ignore: no-empty-block - base no-op, overridden by platform subclasses
Future<void> setAudioPassthrough(bool enabled) async {}
@override
// ignore: no-empty-block - base no-op, overridden by platform subclasses
Future<void> setLogLevel(String level) async {}
// ============================================
// Lifecycle
// ============================================
@@ -411,6 +455,7 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
_disposed = true;
await _eventSubscription?.cancel();
await _logSubscription?.cancel();
await methodChannel.invokeMethod('dispose');
await closeStreamControllers();
}
+29 -4
View File
@@ -6,9 +6,15 @@ import '../font_loader.dart';
import '../models.dart';
import 'player_base.dart';
/// Shared native implementation of [Player] for iOS, macOS, and Android (MPV fallback).
/// Uses MPVKit via platform channels with Metal rendering (Apple) or native window (Android).
/// Shared native implementation of [Player] for iOS, macOS, Android (MPV fallback), and Linux.
/// Uses MPVKit via platform channels with Metal rendering (Apple), native window (Android),
/// or FlTextureGL (Linux).
class PlayerNative extends PlayerBase {
int? _textureIdValue;
@override
int? get textureId => _textureIdValue;
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
static const _eventChannel = EventChannel('com.plezy/mpv_player/events');
@@ -32,8 +38,14 @@ class PlayerNative extends PlayerBase {
if (initialized) return;
try {
final result = await methodChannel.invokeMethod<bool>('initialize');
initialized = result == true;
final result = await methodChannel.invokeMethod<Object>('initialize');
if (result is int) {
// Linux: initialize returns the texture ID
_textureIdValue = result;
initialized = true;
} else {
initialized = result == true;
}
if (!initialized) {
throw Exception('Failed to initialize player');
}
@@ -52,6 +64,8 @@ class PlayerNative extends PlayerBase {
await observeProperty('speed', 'double');
await observeProperty('aid', 'string');
await observeProperty('sid', 'string');
await observeProperty('audio-device-list', (Platform.isAndroid || Platform.isWindows) ? 'string' : 'node');
await observeProperty('audio-device', 'string');
} catch (e) {
errorController.add('Initialization failed: $e');
rethrow;
@@ -228,6 +242,17 @@ class PlayerNative extends PlayerBase {
await methodChannel.invokeMethod('command', {'args': args});
}
// ============================================
// Log Level
// ============================================
@override
Future<void> setLogLevel(String level) async {
checkDisposed();
await _ensureInitialized();
await methodChannel.invokeMethod('setLogLevel', {'level': level});
}
// ============================================
// Passthrough
// ============================================
+8 -1
View File
@@ -74,7 +74,14 @@ class _VideoState extends State<Video> {
}
Widget _buildVideoSurface() {
// For players that support video rect positioning (Windows, Linux),
// For players that use Flutter's texture pipeline (Linux FlTextureGL),
// render directly via the Texture widget.
final textureId = widget.player.textureId;
if (textureId != null) {
return Texture(textureId: textureId);
}
// For players that support video rect positioning (Windows),
// communicate layout changes to the native side.
if (widget.player is VideoRectSupport) {
return LayoutBuilder(
@@ -8,6 +8,7 @@ import '../../i18n/strings.g.dart';
import '../../providers/companion_remote_provider.dart';
import '../../utils/platform_detector.dart';
import '../../utils/app_logger.dart';
import '../../widgets/overlay_sheet.dart';
import 'pairing_screen.dart';
class MobileRemoteScreen extends StatefulWidget {
@@ -20,101 +21,103 @@ class MobileRemoteScreen extends StatefulWidget {
class _MobileRemoteScreenState extends State<MobileRemoteScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(t.companionRemote.title),
actions: [
Consumer<CompanionRemoteProvider>(
builder: (context, provider, child) {
if (provider.isConnected) {
return IconButton(
icon: const Icon(Icons.link_off),
onPressed: () async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(t.common.disconnect),
content: Text(t.companionRemote.remote.disconnectConfirm),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
TextButton(onPressed: () => Navigator.pop(context, true), child: Text(t.common.disconnect)),
],
),
);
return OverlaySheetHost(
child: Scaffold(
appBar: AppBar(
title: Text(t.companionRemote.title),
actions: [
Consumer<CompanionRemoteProvider>(
builder: (context, provider, child) {
if (provider.isConnected) {
return IconButton(
icon: const Icon(Icons.link_off),
onPressed: () async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(t.common.disconnect),
content: Text(t.companionRemote.remote.disconnectConfirm),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
TextButton(onPressed: () => Navigator.pop(context, true), child: Text(t.common.disconnect)),
],
),
);
if (confirmed == true && context.mounted) {
await context.read<CompanionRemoteProvider>().leaveSession();
}
},
tooltip: t.common.disconnect,
);
}
return const SizedBox.shrink();
},
),
],
),
body: Consumer<CompanionRemoteProvider>(
builder: (context, provider, child) {
if (provider.status == RemoteSessionStatus.reconnecting) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 24),
Text(t.companionRemote.remote.reconnecting, style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 8),
Text(
t.companionRemote.remote.attemptOf(current: provider.reconnectAttempts),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 32),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlinedButton(onPressed: () => provider.cancelReconnect(), child: Text(t.common.cancel)),
const SizedBox(width: 16),
FilledButton(
onPressed: () => provider.retryReconnectNow(),
child: Text(t.companionRemote.remote.retryNow),
),
],
),
],
),
);
}
if (!provider.isConnected) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.phonelink_off, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(
provider.status == RemoteSessionStatus.error
? provider.session?.errorMessage ?? t.companionRemote.remote.connectionError
: t.companionRemote.remote.notConnected,
style: const TextStyle(fontSize: 20, color: Colors.grey),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
FilledButton.icon(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => const PairingScreen()));
if (confirmed == true && context.mounted) {
await context.read<CompanionRemoteProvider>().leaveSession();
}
},
icon: const Icon(Icons.link),
label: Text(t.companionRemote.connectToDevice),
),
],
),
);
}
tooltip: t.common.disconnect,
);
}
return const SizedBox.shrink();
},
),
],
),
body: Consumer<CompanionRemoteProvider>(
builder: (context, provider, child) {
if (provider.status == RemoteSessionStatus.reconnecting) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 24),
Text(t.companionRemote.remote.reconnecting, style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 8),
Text(
t.companionRemote.remote.attemptOf(current: provider.reconnectAttempts),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 32),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlinedButton(onPressed: () => provider.cancelReconnect(), child: Text(t.common.cancel)),
const SizedBox(width: 16),
FilledButton(
onPressed: () => provider.retryReconnectNow(),
child: Text(t.companionRemote.remote.retryNow),
),
],
),
],
),
);
}
return const _RemoteControlLayout();
},
if (!provider.isConnected) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.phonelink_off, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(
provider.status == RemoteSessionStatus.error
? provider.session?.errorMessage ?? t.companionRemote.remote.connectionError
: t.companionRemote.remote.notConnected,
style: const TextStyle(fontSize: 20, color: Colors.grey),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
FilledButton.icon(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => const PairingScreen()));
},
icon: const Icon(Icons.link),
label: Text(t.companionRemote.connectToDevice),
),
],
),
);
}
return const _RemoteControlLayout();
},
),
),
);
}
@@ -150,11 +153,7 @@ class _RemoteControlContentState extends State<_RemoteControlContent> {
_sendCommand(RemoteCommandType.tabSearch);
}
final provider = context.read<CompanionRemoteProvider>();
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (_) => _SearchBottomSheet(provider: provider),
);
OverlaySheetController.of(context).show(builder: (_) => _SearchBottomSheet(provider: provider));
}
void _sendCommand(RemoteCommandType type) {
@@ -632,7 +631,7 @@ class _SearchBottomSheetState extends State<_SearchBottomSheet> {
if (trimmed.isNotEmpty) {
widget.provider.sendCommand(RemoteCommandType.search, data: {'query': trimmed});
}
Navigator.pop(context);
OverlaySheetController.of(context).close();
}
@override
+5 -4
View File
@@ -9,6 +9,7 @@ import '../focus/dpad_navigator.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../services/plex_client.dart';
import '../utils/plex_image_helper.dart';
import '../widgets/plex_optimized_image.dart' show blurArtwork;
import '../models/plex_metadata.dart';
import '../utils/content_utils.dart';
import '../models/plex_hub.dart';
@@ -1581,14 +1582,14 @@ class _DiscoverScreenState extends State<DiscoverScreen>
imageType: ImageType.art,
);
return CachedNetworkImage(
return blurArtwork(CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.cover,
placeholder: (context, url) =>
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
errorWidget: (context, url, error) =>
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
);
));
},
),
),
@@ -1649,7 +1650,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
imageType: ImageType.logo,
);
return CachedNetworkImage(
return blurArtwork(CachedNetworkImage(
imageUrl: logoUrl,
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
@@ -1696,7 +1697,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
),
);
},
);
), sigma: 10, clip: false);
},
),
)
+54 -53
View File
@@ -12,6 +12,7 @@ import '../utils/provider_extensions.dart';
import '../utils/app_logger.dart';
import '../widgets/media_grid_sliver.dart';
import '../widgets/focused_scroll_scaffold.dart';
import '../widgets/overlay_sheet.dart';
import 'libraries/sort_bottom_sheet.dart';
import 'libraries/state_messages.dart';
import '../mixins/refreshable.dart';
@@ -152,9 +153,7 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
}
void _showSortBottomSheet() {
showModalBottomSheet(
context: context,
isScrollControlled: true,
OverlaySheetController.of(context).show(
builder: (context) => SortBottomSheet(
sortOptions: _sortOptions,
selectedSort: _selectedSort,
@@ -231,57 +230,59 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
@override
Widget build(BuildContext context) {
return FocusedScrollScaffold(
title: Text(widget.hub.title),
actions: [
IconButton(
icon: AppIcon(Symbols.swap_vert_rounded, fill: 1, semanticLabel: t.libraries.sort),
onPressed: _showSortBottomSheet,
),
],
slivers: [
if (_errorMessage != null)
SliverFillRemaining(
child: ErrorStateWidget(
message: _errorMessage!,
icon: Symbols.error_outline_rounded,
onRetry: _loadMoreItems,
),
)
else if (_filteredItems.isEmpty && _isLoading)
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
else if (_filteredItems.isEmpty)
SliverFillRemaining(child: Center(child: Text(t.hubDetail.noItemsFound)))
else
Builder(
builder: (context) {
final episodePosterMode = context.watch<SettingsProvider>().episodePosterMode;
// Determine hub content type for layout decisions
final hasEpisodes = _filteredItems.any((item) => item.usesWideAspectRatio(episodePosterMode));
final hasNonEpisodes = _filteredItems.any((item) => !item.usesWideAspectRatio(episodePosterMode));
// Mixed hub = has both episodes AND non-episodes
final isMixedHub = hasEpisodes && hasNonEpisodes;
// Episode-only = all items are episodes with thumbnails
final isEpisodeOnlyHub = hasEpisodes && !hasNonEpisodes;
// Use 16:9 for episode-only hubs OR mixed hubs (with episode thumbnail mode)
final useWideLayout =
episodePosterMode == EpisodePosterMode.episodeThumbnail && (isEpisodeOnlyHub || isMixedHub);
return MediaGridSliver(
items: _filteredItems,
onRefresh: _handleItemRefresh,
usePaddingAwareExtent: true,
horizontalPadding: 16,
useWideAspectRatio: useWideLayout,
mixedHubContext: isMixedHub,
);
},
return OverlaySheetHost(
child: FocusedScrollScaffold(
title: Text(widget.hub.title),
actions: [
IconButton(
icon: AppIcon(Symbols.swap_vert_rounded, fill: 1, semanticLabel: t.libraries.sort),
onPressed: _showSortBottomSheet,
),
],
],
slivers: [
if (_errorMessage != null)
SliverFillRemaining(
child: ErrorStateWidget(
message: _errorMessage!,
icon: Symbols.error_outline_rounded,
onRetry: _loadMoreItems,
),
)
else if (_filteredItems.isEmpty && _isLoading)
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
else if (_filteredItems.isEmpty)
SliverFillRemaining(child: Center(child: Text(t.hubDetail.noItemsFound)))
else
Builder(
builder: (context) {
final episodePosterMode = context.watch<SettingsProvider>().episodePosterMode;
// Determine hub content type for layout decisions
final hasEpisodes = _filteredItems.any((item) => item.usesWideAspectRatio(episodePosterMode));
final hasNonEpisodes = _filteredItems.any((item) => !item.usesWideAspectRatio(episodePosterMode));
// Mixed hub = has both episodes AND non-episodes
final isMixedHub = hasEpisodes && hasNonEpisodes;
// Episode-only = all items are episodes with thumbnails
final isEpisodeOnlyHub = hasEpisodes && !hasNonEpisodes;
// Use 16:9 for episode-only hubs OR mixed hubs (with episode thumbnail mode)
final useWideLayout =
episodePosterMode == EpisodePosterMode.episodeThumbnail && (isEpisodeOnlyHub || isMixedHub);
return MediaGridSliver(
items: _filteredItems,
onRefresh: _handleItemRefresh,
usePaddingAwareExtent: true,
horizontalPadding: 16,
useWideAspectRatio: useWideLayout,
mixedHubContext: isMixedHub,
);
},
),
],
),
);
}
}
+140 -156
View File
@@ -4,8 +4,8 @@ import 'package:material_symbols_icons/symbols.dart';
import '../../models/plex_filter.dart';
import '../../widgets/app_bar_back_button.dart';
import '../../widgets/bottom_sheet_header.dart';
import '../../widgets/focusable_bottom_sheet.dart';
import '../../widgets/focusable_list_tile.dart';
import '../../widgets/overlay_sheet.dart';
import '../../utils/provider_extensions.dart';
import '../../i18n/strings.g.dart';
@@ -101,7 +101,7 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
void _applyFilters() {
widget.onFiltersChanged(_tempSelectedFilters);
Navigator.pop(context);
OverlaySheetController.of(context).close();
}
String _extractFilterValue(String key, String filterName) {
@@ -118,164 +118,148 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
@override
Widget build(BuildContext context) {
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: DraggableScrollableSheet(
initialChildSize: 0.7,
minChildSize: 0.5,
maxChildSize: 0.95,
expand: false,
builder: (context, scrollController) {
if (_currentFilter != null) {
// Show filter options view
return Column(
children: [
// Header with back button
BottomSheetHeader(
title: _currentFilter!.title,
leading: AppBarBackButton(style: BackButtonStyle.plain, onPressed: _goBack),
),
// Filter options list
if (_isLoadingValues)
const Expanded(child: Center(child: CircularProgressIndicator()))
else
Expanded(
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: _filterValues.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
final isSelected = !_tempSelectedFilters.containsKey(_currentFilter!.filter);
return FocusableListTile(
focusNode: _initialFocusNode,
title: Text(t.libraries.all),
selected: isSelected,
onTap: () {
setState(() {
_tempSelectedFilters.remove(_currentFilter!.filter);
});
_applyFilters();
},
);
}
final value = _filterValues[index - 1];
final filterValue = _extractFilterValue(value.key, _currentFilter!.filter);
final isSelected = _tempSelectedFilters[_currentFilter!.filter] == filterValue;
return FocusableListTile(
title: Text(value.title),
selected: isSelected,
onTap: () {
setState(() {
_tempSelectedFilters[_currentFilter!.filter] = filterValue;
// Cache the display name for this filter value
if (_filterDisplayNames.length > _maxCachedDisplayNames) {
_filterDisplayNames.clear();
}
_filterDisplayNames[_cacheKey(_currentFilter!.filter, filterValue)] = value.title;
});
_applyFilters();
},
);
},
),
),
],
);
}
// Show main filters view
return Column(
children: [
// Header
BottomSheetHeader(
title: t.libraries.filters,
leading: const AppIcon(Symbols.filter_alt_rounded, fill: 1),
action: _tempSelectedFilters.isNotEmpty
? TextButton.icon(
onPressed: () {
setState(() {
_tempSelectedFilters.clear();
});
_applyFilters();
},
icon: const AppIcon(Symbols.clear_all_rounded, fill: 1),
label: Text(t.libraries.clearAll),
)
: null,
),
// All Filters (boolean toggles first, then regular filters)
Expanded(
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: _sortedFilters.length,
itemBuilder: (context, index) {
final filter = _sortedFilters[index];
// Handle boolean filters as switches (unwatched, inProgress, unmatched, hdr, etc.)
if (_isBooleanFilter(filter)) {
final isActive =
_tempSelectedFilters.containsKey(filter.filter) && _tempSelectedFilters[filter.filter] == '1';
return FocusableSwitchListTile(
focusNode: index == 0 ? _initialFocusNode : null,
value: isActive,
onChanged: (value) {
setState(() {
if (value) {
_tempSelectedFilters[filter.filter] = '1';
} else {
_tempSelectedFilters.remove(filter.filter);
}
});
_applyFilters();
},
title: Text(filter.title),
);
}
// Regular navigable filters - show selected value instead of checkmark
final selectedValue = _tempSelectedFilters[filter.filter];
String? displayValue;
if (selectedValue != null) {
// Try to get the cached display name, fall back to the value itself
displayValue = _filterDisplayNames[_cacheKey(filter.filter, selectedValue)] ?? selectedValue;
}
if (_currentFilter != null) {
// Show filter options view
return Column(
children: [
// Header with back button
BottomSheetHeader(
title: _currentFilter!.title,
leading: AppBarBackButton(style: BackButtonStyle.plain, onPressed: _goBack),
),
// Filter options list
if (_isLoadingValues)
const Expanded(child: Center(child: CircularProgressIndicator()))
else
Expanded(
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: _filterValues.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
final isSelected = !_tempSelectedFilters.containsKey(_currentFilter!.filter);
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
title: Text(filter.title),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (displayValue != null)
Flexible(
child: Text(
displayValue,
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w500,
),
overflow: TextOverflow.ellipsis,
),
),
if (displayValue != null) const SizedBox(width: 8),
const AppIcon(Symbols.chevron_right_rounded, fill: 1),
],
),
onTap: () => _loadFilterValues(filter),
focusNode: _initialFocusNode,
title: Text(t.libraries.all),
selected: isSelected,
onTap: () {
setState(() {
_tempSelectedFilters.remove(_currentFilter!.filter);
});
_applyFilters();
},
);
},
),
}
final value = _filterValues[index - 1];
final filterValue = _extractFilterValue(value.key, _currentFilter!.filter);
final isSelected = _tempSelectedFilters[_currentFilter!.filter] == filterValue;
return FocusableListTile(
title: Text(value.title),
selected: isSelected,
onTap: () {
setState(() {
_tempSelectedFilters[_currentFilter!.filter] = filterValue;
// Cache the display name for this filter value
if (_filterDisplayNames.length > _maxCachedDisplayNames) {
_filterDisplayNames.clear();
}
_filterDisplayNames[_cacheKey(_currentFilter!.filter, filterValue)] = value.title;
});
_applyFilters();
},
);
},
),
],
);
},
),
),
],
);
}
// Show main filters view
return Column(
children: [
// Header
BottomSheetHeader(
title: t.libraries.filters,
leading: const AppIcon(Symbols.filter_alt_rounded, fill: 1),
action: _tempSelectedFilters.isNotEmpty
? TextButton.icon(
onPressed: () {
setState(() {
_tempSelectedFilters.clear();
});
_applyFilters();
},
icon: const AppIcon(Symbols.clear_all_rounded, fill: 1),
label: Text(t.libraries.clearAll),
)
: null,
),
// All Filters (boolean toggles first, then regular filters)
Expanded(
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: _sortedFilters.length,
itemBuilder: (context, index) {
final filter = _sortedFilters[index];
// Handle boolean filters as switches (unwatched, inProgress, unmatched, hdr, etc.)
if (_isBooleanFilter(filter)) {
final isActive =
_tempSelectedFilters.containsKey(filter.filter) && _tempSelectedFilters[filter.filter] == '1';
return FocusableSwitchListTile(
focusNode: index == 0 ? _initialFocusNode : null,
value: isActive,
onChanged: (value) {
setState(() {
if (value) {
_tempSelectedFilters[filter.filter] = '1';
} else {
_tempSelectedFilters.remove(filter.filter);
}
});
_applyFilters();
},
title: Text(filter.title),
);
}
// Regular navigable filters - show selected value instead of checkmark
final selectedValue = _tempSelectedFilters[filter.filter];
String? displayValue;
if (selectedValue != null) {
// Try to get the cached display name, fall back to the value itself
displayValue = _filterDisplayNames[_cacheKey(filter.filter, selectedValue)] ?? selectedValue;
}
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
title: Text(filter.title),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (displayValue != null)
Flexible(
child: Text(
displayValue,
style: TextStyle(color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.w500),
overflow: TextOverflow.ellipsis,
),
),
if (displayValue != null) const SizedBox(width: 8),
const AppIcon(Symbols.chevron_right_rounded, fill: 1),
],
),
onTap: () => _loadFilterValues(filter),
);
},
),
),
],
);
}
}
+170 -144
View File
@@ -23,6 +23,7 @@ import '../../utils/snackbar_helper.dart';
import '../../utils/content_utils.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../widgets/focusable_tab_chip.dart';
import '../../widgets/overlay_sheet.dart';
import '../../services/storage_service.dart';
import '../../mixins/refreshable.dart';
import '../../mixins/item_updatable.dart';
@@ -786,9 +787,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
),
);
} else {
showModalBottomSheet(
context: context,
isScrollControlled: true,
OverlaySheetController.of(context).show(
builder: (context) => _LibraryManagementSheet(
allLibraries: List.from(allLibraries),
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
@@ -1066,140 +1065,142 @@ class _LibrariesScreenState extends State<LibrariesScreen>
// Compute visible libraries (filtered from all libraries)
final visibleLibraries = allLibraries.where((lib) => !hiddenKeys.contains(lib.globalKey)).toList();
return Scaffold(
body: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: CustomScrollView(
controller: _outerScrollController,
slivers: [
DesktopSliverAppBar(
title: _buildAppBarTitle(visibleLibraries),
pinned: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
surfaceTintColor: Colors.transparent,
shadowColor: Colors.transparent,
scrolledUnderElevation: 0,
actions: [
if (allLibraries.isNotEmpty)
return OverlaySheetHost(
child: Scaffold(
body: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: CustomScrollView(
controller: _outerScrollController,
slivers: [
DesktopSliverAppBar(
title: _buildAppBarTitle(visibleLibraries),
pinned: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
surfaceTintColor: Colors.transparent,
shadowColor: Colors.transparent,
scrolledUnderElevation: 0,
actions: [
if (allLibraries.isNotEmpty)
Focus(
focusNode: _editButtonFocusNode,
onKeyEvent: _handleEditKeyEvent,
child: Container(
decoration: BoxDecoration(
color: _isEditFocused ? Colors.white.withValues(alpha: 0.2) : Colors.transparent,
borderRadius: const BorderRadius.all(Radius.circular(20)),
),
child: IconButton(
icon: const AppIcon(Symbols.edit_rounded, fill: 1),
tooltip: t.libraries.manageLibraries,
onPressed: _showLibraryManagementSheet,
),
),
),
Focus(
focusNode: _editButtonFocusNode,
onKeyEvent: _handleEditKeyEvent,
focusNode: _refreshButtonFocusNode,
onKeyEvent: _handleRefreshKeyEvent,
child: Container(
decoration: BoxDecoration(
color: _isEditFocused ? Colors.white.withValues(alpha: 0.2) : Colors.transparent,
color: _isRefreshFocused ? Colors.white.withValues(alpha: 0.2) : Colors.transparent,
borderRadius: const BorderRadius.all(Radius.circular(20)),
),
child: IconButton(
icon: const AppIcon(Symbols.edit_rounded, fill: 1),
tooltip: t.libraries.manageLibraries,
onPressed: _showLibraryManagementSheet,
icon: const AppIcon(Symbols.refresh_rounded, fill: 1),
tooltip: t.common.refresh,
onPressed: _refreshCurrentTab,
),
),
),
Focus(
focusNode: _refreshButtonFocusNode,
onKeyEvent: _handleRefreshKeyEvent,
child: Container(
decoration: BoxDecoration(
color: _isRefreshFocused ? Colors.white.withValues(alpha: 0.2) : Colors.transparent,
borderRadius: const BorderRadius.all(Radius.circular(20)),
),
child: IconButton(
icon: const AppIcon(Symbols.refresh_rounded, fill: 1),
tooltip: t.common.refresh,
onPressed: _refreshCurrentTab,
),
),
),
],
),
if (isLoadingLibraries)
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
else if (_errorMessage != null && visibleLibraries.isEmpty)
SliverFillRemaining(
child: ErrorStateWidget(
message: _errorMessage!,
icon: Symbols.error_outline_rounded,
onRetry: () {
final librariesProvider = context.read<LibrariesProvider>();
librariesProvider.refresh();
},
),
)
else if (visibleLibraries.isEmpty)
SliverFillRemaining(
child: EmptyStateWidget(message: t.libraries.noLibrariesFound, icon: Symbols.video_library_rounded),
)
else ...[
// Tab selector chips (only on mobile - desktop has them in app bar)
if (_selectedLibraryGlobalKey != null && !PlatformDetector.shouldUseSideNavigation(context))
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
_buildTabChip(t.libraries.tabs.recommended, 0),
const SizedBox(width: 8),
_buildTabChip(t.libraries.tabs.browse, 1),
const SizedBox(width: 8),
_buildTabChip(t.libraries.tabs.collections, 2),
const SizedBox(width: 8),
_buildTabChip(t.libraries.tabs.playlists, 3),
],
),
),
),
),
// Tab content
if (_selectedLibraryGlobalKey != null)
],
),
if (isLoadingLibraries)
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
else if (_errorMessage != null && visibleLibraries.isEmpty)
SliverFillRemaining(
child: TabBarView(
key: ValueKey(_selectedLibraryGlobalKey),
controller: tabController,
// Disable swipe on desktop - trackpad scrolling triggers accidental tab switches
// See: https://github.com/flutter/flutter/issues/11132
physics: PlatformDetector.isDesktop(context) ? const NeverScrollableScrollPhysics() : null,
children: [
LibraryRecommendedTab(
key: _recommendedTabKey,
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
isActive: tabController.index == 0,
suppressAutoFocus: suppressAutoFocus,
onDataLoaded: () => _handleTabDataLoaded(0),
onBack: focusTabBar,
),
LibraryBrowseTab(
key: _browseTabKey,
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
isActive: tabController.index == 1,
suppressAutoFocus: suppressAutoFocus,
onDataLoaded: () => _handleTabDataLoaded(1),
onBack: focusTabBar,
),
LibraryCollectionsTab(
key: _collectionsTabKey,
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
isActive: tabController.index == 2,
suppressAutoFocus: suppressAutoFocus,
onDataLoaded: () => _handleTabDataLoaded(2),
onBack: focusTabBar,
),
LibraryPlaylistsTab(
key: _playlistsTabKey,
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
isActive: tabController.index == 3,
suppressAutoFocus: suppressAutoFocus,
onDataLoaded: () => _handleTabDataLoaded(3),
onBack: focusTabBar,
),
],
child: ErrorStateWidget(
message: _errorMessage!,
icon: Symbols.error_outline_rounded,
onRetry: () {
final librariesProvider = context.read<LibrariesProvider>();
librariesProvider.refresh();
},
),
),
)
else if (visibleLibraries.isEmpty)
SliverFillRemaining(
child: EmptyStateWidget(message: t.libraries.noLibrariesFound, icon: Symbols.video_library_rounded),
)
else ...[
// Tab selector chips (only on mobile - desktop has them in app bar)
if (_selectedLibraryGlobalKey != null && !PlatformDetector.shouldUseSideNavigation(context))
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
_buildTabChip(t.libraries.tabs.recommended, 0),
const SizedBox(width: 8),
_buildTabChip(t.libraries.tabs.browse, 1),
const SizedBox(width: 8),
_buildTabChip(t.libraries.tabs.collections, 2),
const SizedBox(width: 8),
_buildTabChip(t.libraries.tabs.playlists, 3),
],
),
),
),
),
// Tab content
if (_selectedLibraryGlobalKey != null)
SliverFillRemaining(
child: TabBarView(
key: ValueKey(_selectedLibraryGlobalKey),
controller: tabController,
// Disable swipe on desktop - trackpad scrolling triggers accidental tab switches
// See: https://github.com/flutter/flutter/issues/11132
physics: PlatformDetector.isDesktop(context) ? const NeverScrollableScrollPhysics() : null,
children: [
LibraryRecommendedTab(
key: _recommendedTabKey,
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
isActive: tabController.index == 0,
suppressAutoFocus: suppressAutoFocus,
onDataLoaded: () => _handleTabDataLoaded(0),
onBack: focusTabBar,
),
LibraryBrowseTab(
key: _browseTabKey,
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
isActive: tabController.index == 1,
suppressAutoFocus: suppressAutoFocus,
onDataLoaded: () => _handleTabDataLoaded(1),
onBack: focusTabBar,
),
LibraryCollectionsTab(
key: _collectionsTabKey,
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
isActive: tabController.index == 2,
suppressAutoFocus: suppressAutoFocus,
onDataLoaded: () => _handleTabDataLoaded(2),
onBack: focusTabBar,
),
LibraryPlaylistsTab(
key: _playlistsTabKey,
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
isActive: tabController.index == 3,
suppressAutoFocus: suppressAutoFocus,
onDataLoaded: () => _handleTabDataLoaded(3),
onBack: focusTabBar,
),
],
),
),
],
],
],
),
),
),
);
@@ -1420,27 +1421,52 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
Future<void> _showLibraryMenuBottomSheet(BuildContext outerContext, PlexLibrary library) async {
final menuItems = widget.getLibraryMenuItems(library);
final selected = await showModalBottomSheet<String>(
context: outerContext,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(library.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
),
...menuItems.indexed.map(
(entry) => ListTile(
leading: AppIcon(entry.$2.icon, fill: 1),
title: Text(entry.$2.label),
onTap: () => Navigator.pop(context, entry.$2.value),
final controller = OverlaySheetController.maybeOf(outerContext);
final String? selected;
if (controller != null) {
selected = await controller.push<String>(
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(library.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
),
),
],
...menuItems.indexed.map(
(entry) => ListTile(
leading: AppIcon(entry.$2.icon, fill: 1),
title: Text(entry.$2.label),
onTap: () => controller.pop(entry.$2.value),
),
),
],
),
),
),
);
);
} else {
selected = await showModalBottomSheet<String>(
context: outerContext,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(library.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
),
...menuItems.indexed.map(
(entry) => ListTile(
leading: AppIcon(entry.$2.icon, fill: 1),
title: Text(entry.$2.label),
onTap: () => Navigator.pop(context, entry.$2.value),
),
),
],
),
),
);
}
if (selected != null && mounted) {
// Find the selected item to check if confirmation is needed
+67 -78
View File
@@ -4,8 +4,8 @@ import 'package:material_symbols_icons/symbols.dart';
import '../../focus/dpad_navigator.dart';
import '../../models/plex_sort.dart';
import '../../widgets/bottom_sheet_header.dart';
import '../../widgets/focusable_bottom_sheet.dart';
import '../../widgets/focusable_list_tile.dart';
import '../../widgets/overlay_sheet.dart';
import '../../i18n/strings.g.dart';
class SortBottomSheet extends StatefulWidget {
@@ -45,6 +45,11 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
if (ctx != null) {
Scrollable.ensureVisible(ctx, alignment: 0.5);
}
// Schedule after overlay's _autoFocus second callback so we override it.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_initialFocusNode.requestFocus();
});
});
}
@@ -68,7 +73,7 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
_currentDescending = descending;
});
widget.onSortChanged(sort, descending);
Navigator.pop(context);
OverlaySheetController.of(context).close();
}
void _handleClear() {
@@ -77,89 +82,73 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
_currentDescending = false;
});
widget.onClear?.call();
OverlaySheetController.of(context).close();
}
@override
Widget build(BuildContext context) {
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: DraggableScrollableSheet(
initialChildSize: 0.6,
minChildSize: 0.4,
maxChildSize: 0.9,
expand: false,
builder: (context, scrollController) {
return Column(
children: [
BottomSheetHeader(
title: t.libraries.sortBy,
action: widget.onClear != null
? TextButton(onPressed: _handleClear, child: Text(t.common.clear))
: null,
),
Expanded(
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: widget.sortOptions.length,
itemBuilder: (context, index) {
final sort = widget.sortOptions[index];
final isSelected = _currentSort?.key == sort.key;
return Column(
children: [
BottomSheetHeader(
title: t.libraries.sortBy,
action: widget.onClear != null ? TextButton(onPressed: _handleClear, child: Text(t.common.clear)) : null,
),
Expanded(
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: widget.sortOptions.length,
itemBuilder: (context, index) {
final sort = widget.sortOptions[index];
final isSelected = _currentSort?.key == sort.key;
return Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: (node, event) {
if (!event.isActionable) return KeyEventResult.ignored;
if (!isSelected) return KeyEventResult.ignored;
if (event.logicalKey.isLeftKey) {
_handleDirectionChange(sort, false);
return KeyEventResult.handled;
}
if (event.logicalKey.isRightKey) {
_handleDirectionChange(sort, true);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: FocusableRadioListTile<PlexSort>(
focusNode: (widget.selectedSort?.key == sort.key || (widget.selectedSort == null && index == 0))
? _initialFocusNode
: null,
title: Text(sort.title),
value: sort,
groupValue: _currentSort,
onChanged: (value) {
if (value != null) _handleSortSelect(value);
},
secondary: isSelected
? SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: AppIcon(Symbols.arrow_upward_rounded, fill: 1, size: 16),
),
ButtonSegment(
value: true,
icon: AppIcon(Symbols.arrow_downward_rounded, fill: 1, size: 16),
),
],
selected: {_currentDescending},
onSelectionChanged: (Set<bool> newSelection) {
_handleDirectionChange(sort, newSelection.first);
},
)
: null,
),
);
return Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: (node, event) {
if (!event.isActionable) return KeyEventResult.ignored;
if (!isSelected) return KeyEventResult.ignored;
if (event.logicalKey.isLeftKey) {
_handleDirectionChange(sort, false);
return KeyEventResult.handled;
}
if (event.logicalKey.isRightKey) {
_handleDirectionChange(sort, true);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: FocusableRadioListTile<PlexSort>(
focusNode: (widget.selectedSort?.key == sort.key || (widget.selectedSort == null && index == 0))
? _initialFocusNode
: null,
title: Text(sort.title),
value: sort,
groupValue: _currentSort,
onChanged: (value) {
if (value != null) _handleSortSelect(value);
},
secondary: isSelected
? SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(value: false, icon: AppIcon(Symbols.arrow_upward_rounded, fill: 1, size: 16)),
ButtonSegment(
value: true,
icon: AppIcon(Symbols.arrow_downward_rounded, fill: 1, size: 16),
),
],
selected: {_currentDescending},
onSelectionChanged: (Set<bool> newSelection) {
_handleDirectionChange(sort, newSelection.first);
},
)
: null,
),
),
],
);
},
),
);
},
),
),
],
);
}
}
+119 -115
View File
@@ -20,6 +20,7 @@ import '../../../widgets/alpha_scroll_handle.dart';
import '../../../widgets/focusable_media_card.dart';
import '../../../widgets/focusable_filter_chip.dart';
import '../../../widgets/media_grid_delegate.dart';
import '../../../widgets/overlay_sheet.dart';
import '../../../mixins/library_tab_focus_mixin.dart';
import '../folder_tree_view.dart';
import '../filters_bottom_sheet.dart';
@@ -482,52 +483,51 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
void _showGroupingBottomSheet() {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
var pendingGrouping = _selectedGrouping;
showModalBottomSheet(
context: context,
builder: (sheetContext) {
final options = _getGroupingOptions();
return StatefulBuilder(
builder: (context, setSheetState) {
return ListView.builder(
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (context, index) {
final grouping = options[index];
return RadioListTile<String>(
title: Text(_getGroupingLabel(grouping)),
value: grouping,
groupValue: pendingGrouping,
onChanged: (value) {
if (value == null) return;
setSheetState(() {
pendingGrouping = value;
});
OverlaySheetController.of(context)
.show(
builder: (sheetContext) {
final options = _getGroupingOptions();
return StatefulBuilder(
builder: (context, setSheetState) {
return ListView.builder(
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (context, index) {
final grouping = options[index];
return RadioListTile<String>(
title: Text(_getGroupingLabel(grouping)),
value: grouping,
groupValue: pendingGrouping,
onChanged: (value) {
if (value == null) return;
setSheetState(() {
pendingGrouping = value;
});
},
);
},
);
},
);
},
);
},
).then((_) {
if (!mounted) return;
if (pendingGrouping == _selectedGrouping) return;
setState(() {
_selectedGrouping = pendingGrouping;
});
StorageService.getInstance().then((storage) {
storage.saveLibraryGrouping(widget.library.globalKey, pendingGrouping);
});
_loadItems();
_loadFirstCharacters();
});
)
.then((_) {
if (!mounted) return;
if (pendingGrouping == _selectedGrouping) return;
setState(() {
_selectedGrouping = pendingGrouping;
});
StorageService.getInstance().then((storage) {
storage.saveLibraryGrouping(widget.library.globalKey, pendingGrouping);
});
_loadItems();
_loadFirstCharacters();
});
}
void _showFiltersBottomSheet() {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
showModalBottomSheet(
context: context,
isScrollControlled: true,
OverlaySheetController.of(context).show(
builder: (context) => FiltersBottomSheet(
filters: _filters,
selectedFilters: _selectedFilters,
@@ -557,46 +557,46 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
PlexSort? pendingSort = _selectedSort;
bool pendingDescending = _isSortDescending;
bool pendingCleared = false;
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => SortBottomSheet(
sortOptions: _sortOptions,
selectedSort: _selectedSort,
isSortDescending: _isSortDescending,
onSortChanged: (sort, descending) {
pendingSort = sort;
pendingDescending = descending;
pendingCleared = false;
},
onClear: () {
pendingSort = null;
pendingDescending = false;
pendingCleared = true;
},
),
).then((_) {
if (!mounted) return;
if (pendingCleared) {
setState(() {
_selectedSort = null;
_isSortDescending = false;
OverlaySheetController.of(context)
.show(
builder: (context) => SortBottomSheet(
sortOptions: _sortOptions,
selectedSort: _selectedSort,
isSortDescending: _isSortDescending,
onSortChanged: (sort, descending) {
pendingSort = sort;
pendingDescending = descending;
pendingCleared = false;
},
onClear: () {
pendingSort = null;
pendingDescending = false;
pendingCleared = true;
},
),
)
.then((_) {
if (!mounted) return;
if (pendingCleared) {
setState(() {
_selectedSort = null;
_isSortDescending = false;
});
_loadItems();
_loadFirstCharacters();
} else if (pendingSort != null &&
(pendingSort!.key != _selectedSort?.key || pendingDescending != _isSortDescending)) {
setState(() {
_selectedSort = pendingSort;
_isSortDescending = pendingDescending;
});
StorageService.getInstance().then((storage) {
storage.saveLibrarySort(widget.library.globalKey, pendingSort!.key, descending: pendingDescending);
});
_loadItems();
_loadFirstCharacters();
}
});
_loadItems();
_loadFirstCharacters();
} else if (pendingSort != null &&
(pendingSort!.key != _selectedSort?.key || pendingDescending != _isSortDescending)) {
setState(() {
_selectedSort = pendingSort;
_isSortDescending = pendingDescending;
});
StorageService.getInstance().then((storage) {
storage.saveLibrarySort(widget.library.globalKey, pendingSort!.key, descending: pendingDescending);
});
_loadItems();
_loadFirstCharacters();
}
});
}
/// Navigate focus from chips down to the grid item.
@@ -831,52 +831,56 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
// For folders mode, use FolderTreeView instead of grid/list
if (_selectedGrouping == 'folders') {
return Column(
children: [
_buildChipsBar(),
Expanded(
child: FolderTreeView(
libraryKey: widget.library.key,
serverId: widget.library.serverId,
onRefresh: updateItem,
return OverlaySheetHost(
child: Column(
children: [
_buildChipsBar(),
Expanded(
child: FolderTreeView(
libraryKey: widget.library.key,
serverId: widget.library.serverId,
onRefresh: updateItem,
),
),
),
],
],
),
);
}
// For list/grid modes, use Stack with chips layered on top of grid.
// This allows the grid to use Clip.none for focus decorations while
// the chips bar (with background) covers any overflow at the top.
return Stack(
children: [
// Grid fills the entire area, with top padding for chips bar
Positioned.fill(child: _buildScrollableContent()),
// Chips bar on top with solid background
Positioned(top: 0, left: 0, right: 0, child: _buildChipsBar()),
// Alpha jump bar / scroll handle on the right edge
if (_shouldShowAlphaJumpBar)
Positioned(
top: _chipsBarHeight,
right: 0,
bottom: 0,
child: _isPhone(context)
? AlphaScrollHandle(
firstCharacters: _firstCharacters,
onJump: _jumpToIndex,
currentFirstVisibleIndex: _currentFirstVisibleIndex,
isScrolling: _isScrollActive,
)
: AlphaJumpBar(
firstCharacters: _firstCharacters,
onJump: _jumpToIndex,
currentFirstVisibleIndex: _currentFirstVisibleIndex,
focusNode: _alphaJumpBarFocusNode,
onNavigateLeft: _navigateToGridNearScroll,
onBack: _navigateToGridNearScroll,
),
),
],
return OverlaySheetHost(
child: Stack(
children: [
// Grid fills the entire area, with top padding for chips bar
Positioned.fill(child: _buildScrollableContent()),
// Chips bar on top with solid background
Positioned(top: 0, left: 0, right: 0, child: _buildChipsBar()),
// Alpha jump bar / scroll handle on the right edge
if (_shouldShowAlphaJumpBar)
Positioned(
top: _chipsBarHeight,
right: 0,
bottom: 0,
child: _isPhone(context)
? AlphaScrollHandle(
firstCharacters: _firstCharacters,
onJump: _jumpToIndex,
currentFirstVisibleIndex: _currentFirstVisibleIndex,
isScrolling: _isScrollActive,
)
: AlphaJumpBar(
firstCharacters: _firstCharacters,
onJump: _jumpToIndex,
currentFirstVisibleIndex: _currentFirstVisibleIndex,
focusNode: _alphaJumpBarFocusNode,
onNavigateLeft: _navigateToGridNearScroll,
onBack: _navigateToGridNearScroll,
),
),
],
),
);
}
+7 -1
View File
@@ -6,6 +6,7 @@ import '../../focus/dpad_navigator.dart';
import '../../i18n/strings.g.dart';
import '../../models/livetv_channel.dart';
import '../../models/livetv_dvr.dart';
import '../../mixins/refreshable.dart';
import '../../mixins/tab_navigation_mixin.dart';
import '../../providers/multi_server_provider.dart';
import '../../utils/app_logger.dart';
@@ -23,7 +24,9 @@ class LiveTvScreen extends StatefulWidget {
State<LiveTvScreen> createState() => _LiveTvScreenState();
}
class _LiveTvScreenState extends State<LiveTvScreen> with SingleTickerProviderStateMixin, TabNavigationMixin {
class _LiveTvScreenState extends State<LiveTvScreen>
with SingleTickerProviderStateMixin, TabNavigationMixin
implements FocusableTab {
final _guideTabFocusNode = FocusNode(debugLabel: 'tab_chip_guide');
final _whatsOnTabFocusNode = FocusNode(debugLabel: 'tab_chip_whats_on');
final _guideTabKey = GlobalKey<GuideTabState>();
@@ -216,6 +219,9 @@ class _LiveTvScreenState extends State<LiveTvScreen> with SingleTickerProviderSt
});
}
@override
void focusActiveTabIfReady() => _focusCurrentTab();
// ---------------------------------------------------------------------------
// Action button key handlers
// ---------------------------------------------------------------------------
@@ -12,6 +12,7 @@ import '../../utils/live_tv_player_navigation.dart';
import '../../utils/plex_image_helper.dart';
import '../../widgets/app_icon.dart';
import '../../widgets/focused_scroll_scaffold.dart';
import '../../widgets/overlay_sheet.dart';
import 'program_details_sheet.dart';
/// Shows all upcoming airings of a show, matching the Plex "upcoming episodes" view.
@@ -126,39 +127,41 @@ class _LiveTvShowScheduleScreenState extends State<LiveTvShowScheduleScreen> {
@override
Widget build(BuildContext context) {
return FocusedScrollScaffold(
title: Text(widget.showTitle),
slivers: [
if (_isLoading)
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
else if (_programs.isEmpty)
SliverFillRemaining(child: Center(child: Text(t.liveTv.noPrograms)))
else
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final program = _programs[index];
final channel = _findChannel(program.channelIdentifier);
void onTap() {
if (program.isCurrentlyAiring && channel != null) {
_tuneChannel(channel);
} else {
_showProgramDetails(program, channel);
return OverlaySheetHost(
child: FocusedScrollScaffold(
title: Text(widget.showTitle),
slivers: [
if (_isLoading)
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
else if (_programs.isEmpty)
SliverFillRemaining(child: Center(child: Text(t.liveTv.noPrograms)))
else
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final program = _programs[index];
final channel = _findChannel(program.channelIdentifier);
void onTap() {
if (program.isCurrentlyAiring && channel != null) {
_tuneChannel(channel);
} else {
_showProgramDetails(program, channel);
}
}
}
return FocusableWrapper(
autofocus: index == 0,
autoScroll: true,
useComfortableZone: true,
useBackgroundFocus: true,
disableScale: true,
onSelect: onTap,
onBack: () => Navigator.pop(context),
child: _ScheduleListTile(program: program, channel: channel, onTap: onTap),
);
}, childCount: _programs.length),
),
],
return FocusableWrapper(
autofocus: index == 0,
autoScroll: true,
useComfortableZone: true,
useBackgroundFocus: true,
disableScale: true,
onSelect: onTap,
onBack: () => Navigator.pop(context),
child: _ScheduleListTile(program: program, channel: channel, onTap: onTap),
);
}, childCount: _programs.length),
),
],
),
);
}
}
+110 -91
View File
@@ -7,7 +7,8 @@ import '../../models/livetv_channel.dart';
import '../../models/livetv_program.dart';
import '../../utils/formatters.dart';
import '../../widgets/app_icon.dart';
import '../../widgets/focusable_bottom_sheet.dart';
import '../../widgets/overlay_sheet.dart';
import '../../widgets/plex_optimized_image.dart' show blurArtwork;
/// Shows a bottom sheet with program details and actions (Record, Watch Channel, Play).
void showProgramDetailsSheet(
@@ -17,17 +18,31 @@ void showProgramDetailsSheet(
required String? posterUrl,
required VoidCallback? onTuneChannel,
}) {
showModalBottomSheet(
context: context,
builder: (sheetContext) {
return _ProgramDetailsSheetContent(
program: program,
channel: channel,
posterUrl: posterUrl,
onTuneChannel: onTuneChannel,
);
},
);
final controller = OverlaySheetController.maybeOf(context);
if (controller != null) {
controller.show(
builder: (sheetContext) {
return _ProgramDetailsSheetContent(
program: program,
channel: channel,
posterUrl: posterUrl,
onTuneChannel: onTuneChannel,
);
},
);
} else {
showModalBottomSheet(
context: context,
builder: (sheetContext) {
return _ProgramDetailsSheetContent(
program: program,
channel: channel,
posterUrl: posterUrl,
onTuneChannel: onTuneChannel,
);
},
);
}
}
class _ProgramDetailsSheetContent extends StatefulWidget {
@@ -50,8 +65,6 @@ class _ProgramDetailsSheetContent extends StatefulWidget {
class _ProgramDetailsSheetContentState extends State<_ProgramDetailsSheetContent> {
final List<FocusNode> _buttonFocusNodes = [];
FocusNode get _initialFocusNode => _buttonFocusNodes.isNotEmpty ? _buttonFocusNodes.first : FocusNode();
@override
void initState() {
super.initState();
@@ -94,25 +107,34 @@ class _ProgramDetailsSheetContentState extends State<_ProgramDetailsSheetContent
final buttons = <Widget>[];
int buttonIndex = 0;
void closeSheet() {
final controller = OverlaySheetController.maybeOf(context);
if (controller != null) {
controller.close();
} else {
Navigator.of(context).pop();
}
}
if (program.isCurrentlyAiring && widget.onTuneChannel != null) {
final idx = buttonIndex;
buttons.add(
FocusableWrapper(
focusNode: _buttonFocusNodes[idx],
onSelect: () {
Navigator.of(context).pop();
closeSheet();
widget.onTuneChannel!();
},
onNavigateLeft: idx > 0 ? () => _focusButton(idx - 1) : null,
onNavigateRight: idx < _buttonFocusNodes.length - 1 ? () => _focusButton(idx + 1) : null,
onBack: () => Navigator.of(context).pop(),
onBack: closeSheet,
borderRadius: 100,
useBackgroundFocus: true,
disableScale: true,
child: FilledButton.icon(
style: FilledButton.styleFrom(tapTargetSize: MaterialTapTargetSize.shrinkWrap),
onPressed: () {
Navigator.of(context).pop();
closeSheet();
widget.onTuneChannel!();
},
icon: const AppIcon(Symbols.play_arrow_rounded),
@@ -162,19 +184,19 @@ class _ProgramDetailsSheetContentState extends State<_ProgramDetailsSheetContent
FocusableWrapper(
focusNode: _buttonFocusNodes[idx],
onSelect: () {
Navigator.of(context).pop();
closeSheet();
widget.onTuneChannel!();
},
onNavigateLeft: idx > 0 ? () => _focusButton(idx - 1) : null,
onNavigateRight: idx < _buttonFocusNodes.length - 1 ? () => _focusButton(idx + 1) : null,
onBack: () => Navigator.of(context).pop(),
onBack: closeSheet,
borderRadius: 100,
useBackgroundFocus: true,
disableScale: true,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(tapTargetSize: MaterialTapTargetSize.shrinkWrap),
onPressed: () {
Navigator.of(context).pop();
closeSheet();
widget.onTuneChannel!();
},
icon: const AppIcon(Symbols.live_tv_rounded),
@@ -185,79 +207,76 @@ class _ProgramDetailsSheetContentState extends State<_ProgramDetailsSheetContent
buttonIndex++;
}
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.posterUrl != null) ...[
ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(6)),
child: Image.network(
widget.posterUrl!,
width: 80,
height: 120,
fit: BoxFit.cover,
errorBuilder: (_, _, _) => const SizedBox.shrink(),
),
),
const SizedBox(width: 14),
],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(child: Text(program.displayTitle, style: theme.textTheme.titleMedium)),
if (program.isCurrentlyAiring)
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: const BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.all(Radius.circular(4)),
),
child: Text(
t.liveTv.live,
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 11),
),
),
],
),
const SizedBox(height: 4),
Text(
[
if (channel != null) channel.displayName,
if (program.startTime != null && program.endTime != null)
'${program.startTime!.hour.toString().padLeft(2, '0')}:${program.startTime!.minute.toString().padLeft(2, '0')} - ${program.endTime!.hour.toString().padLeft(2, '0')}:${program.endTime!.minute.toString().padLeft(2, '0')}',
if (program.durationMinutes > 0) formatDurationTextual(program.durationMinutes * 60000),
].join(' · '),
style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.onSurfaceVariant),
),
if (program.summary != null && program.summary!.isNotEmpty) ...[
const SizedBox(height: 12),
Text(
program.summary!,
style: theme.textTheme.bodyMedium,
maxLines: 4,
overflow: TextOverflow.ellipsis,
),
],
],
),
return Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.posterUrl != null) ...[
ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(6)),
child: blurArtwork(Image.network(
widget.posterUrl!,
width: 80,
height: 120,
fit: BoxFit.cover,
errorBuilder: (_, _, _) => const SizedBox.shrink(),
)),
),
const SizedBox(width: 14),
],
),
const SizedBox(height: 16),
Row(children: buttons),
],
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(child: Text(program.displayTitle, style: theme.textTheme.titleMedium)),
if (program.isCurrentlyAiring)
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: const BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.all(Radius.circular(4)),
),
child: Text(
t.liveTv.live,
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 11),
),
),
],
),
const SizedBox(height: 4),
Text(
[
if (channel != null) channel.displayName,
if (program.startTime != null && program.endTime != null)
'${program.startTime!.hour.toString().padLeft(2, '0')}:${program.startTime!.minute.toString().padLeft(2, '0')} - ${program.endTime!.hour.toString().padLeft(2, '0')}:${program.endTime!.minute.toString().padLeft(2, '0')}',
if (program.durationMinutes > 0) formatDurationTextual(program.durationMinutes * 60000),
].join(' · '),
style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.onSurfaceVariant),
),
if (program.summary != null && program.summary!.isNotEmpty) ...[
const SizedBox(height: 12),
Text(
program.summary!,
style: theme.textTheme.bodyMedium,
maxLines: 4,
overflow: TextOverflow.ellipsis,
),
],
],
),
),
],
),
const SizedBox(height: 16),
Row(children: buttons),
],
),
);
}
+45 -11
View File
@@ -17,6 +17,7 @@ import '../../../utils/formatters.dart';
import '../../../utils/plex_image_helper.dart';
import '../../../utils/live_tv_player_navigation.dart';
import '../../../widgets/app_icon.dart';
import '../../../widgets/overlay_sheet.dart';
import '../../../widgets/plex_optimized_image.dart';
import '../program_details_sheet.dart';
@@ -375,15 +376,21 @@ class GuideTabState extends State<GuideTab> {
});
_scrollToProgramTime(program);
}
} else {
// Already in program column — move to next program
_navigateToAdjacentProgram(_gridChannelIndex, forward: true);
}
return KeyEventResult.handled;
}
if (key.isLeftKey) {
if (_gridColumn == 1) {
setState(() {
_gridColumn = 0;
_focusedProgram = null;
});
// Try moving to previous program; if at first program, go back to channel column
if (!_navigateToAdjacentProgram(_gridChannelIndex, forward: false)) {
setState(() {
_gridColumn = 0;
_focusedProgram = null;
});
}
} else {
widget.onBack?.call();
}
@@ -424,6 +431,27 @@ class GuideTabState extends State<GuideTab> {
return programs.firstOrNull;
}
/// Navigate to the next or previous program on the same channel.
/// Returns true if navigation succeeded, false if at the boundary.
bool _navigateToAdjacentProgram(int channelIndex, {required bool forward}) {
if (channelIndex < 0 || channelIndex >= widget.channels.length) return false;
final channel = widget.channels[channelIndex];
final programs = _getProgramsForChannel(channel);
if (programs.isEmpty || _focusedProgram == null) return false;
final currentIndex = programs.indexWhere((p) => identical(p, _focusedProgram));
if (currentIndex < 0) return false;
final nextIndex = forward ? currentIndex + 1 : currentIndex - 1;
if (nextIndex < 0 || nextIndex >= programs.length) return false;
setState(() {
_focusedProgram = programs[nextIndex];
});
_scrollToProgramTime(_focusedProgram);
return true;
}
void _scrollToChannel(int index) {
if (!_gridVerticalController.hasClients) return;
final targetTop = index * _rowHeight;
@@ -440,9 +468,13 @@ class GuideTabState extends State<GuideTab> {
if (newOffset != null) {
final clamped = newOffset.clamp(0.0, _gridVerticalController.position.maxScrollExtent);
_gridVerticalController.jumpTo(clamped);
_gridVerticalController.animateTo(clamped, duration: const Duration(milliseconds: 150), curve: Curves.easeOut);
if (_channelVerticalController.hasClients) {
_channelVerticalController.jumpTo(clamped.clamp(0.0, _channelVerticalController.position.maxScrollExtent));
_channelVerticalController.animateTo(
clamped.clamp(0.0, _channelVerticalController.position.maxScrollExtent),
duration: const Duration(milliseconds: 150),
curve: Curves.easeOut,
);
}
}
}
@@ -477,11 +509,13 @@ class GuideTabState extends State<GuideTab> {
return const Center(child: CircularProgressIndicator());
}
return Focus(
focusNode: _guideFocusNode,
onFocusChange: (hasFocus) => setState(() => _hasFocus = hasFocus),
onKeyEvent: _handleKeyEvent,
child: _buildGuideGrid(theme),
return OverlaySheetHost(
child: Focus(
focusNode: _guideFocusNode,
onFocusChange: (hasFocus) => setState(() => _hasFocus = hasFocus),
onKeyEvent: _handleKeyEvent,
child: _buildGuideGrid(theme),
),
);
}
+17 -14
View File
@@ -22,6 +22,7 @@ import '../../../utils/plex_image_helper.dart';
import '../../../utils/provider_extensions.dart';
import '../../../widgets/app_icon.dart';
import '../../../widgets/focus_builders.dart';
import '../../../widgets/overlay_sheet.dart';
import '../../../utils/scroll_utils.dart';
import '../../../widgets/horizontal_scroll_with_arrows.dart';
import '../../../widgets/plex_optimized_image.dart';
@@ -222,20 +223,22 @@ class WhatsOnTabState extends State<WhatsOnTab> {
return Center(child: Text(t.liveTv.noPrograms));
}
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
clipBehavior: Clip.none,
itemCount: _hubs.length,
itemBuilder: (context, index) {
return _LiveTvHubSection(
key: _hubKeys[index],
hub: _hubs[index],
onTap: _onItemTap,
onLongPress: (entry) => _showProgramDetails(entry, _findChannel(entry.program.channelIdentifier)),
onVerticalNavigation: (isUp) => _handleVerticalNavigation(index, isUp),
onBack: widget.onBack,
);
},
return OverlaySheetHost(
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
clipBehavior: Clip.none,
itemCount: _hubs.length,
itemBuilder: (context, index) {
return _LiveTvHubSection(
key: _hubKeys[index],
hub: _hubs[index],
onTap: _onItemTap,
onLongPress: (entry) => _showProgramDetails(entry, _findChannel(entry.program.channelIdentifier)),
onVerticalNavigation: (isUp) => _handleVerticalNavigation(index, isUp),
onBack: widget.onBack,
);
},
),
);
}
}
+16
View File
@@ -671,6 +671,15 @@ class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener
}
});
}
// When content regains focus while on Live TV, focus the active guide/whats-on tab
final liveTvIndex = NavigationTab.indexFor(NavigationTabId.liveTv, isOffline: _isOffline, hasLiveTv: _hasLiveTv);
if (_currentIndex == liveTvIndex && liveTvIndex >= 0) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_liveTvKey.currentState case final FocusableTab focusable) {
focusable.focusActiveTabIfReady();
}
});
}
// When content regains focus while on Settings, restore focus to last focused setting
final settingsIndex = NavigationTab.indexFor(
NavigationTabId.settings,
@@ -876,6 +885,13 @@ class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener
focusable.focusActiveTabIfReady();
}
}
// Ensure the Live TV screen applies focus when brought into view
final liveTvIdx = NavigationTab.indexFor(NavigationTabId.liveTv, isOffline: _isOffline, hasLiveTv: _hasLiveTv);
if (index == liveTvIdx && liveTvIdx >= 0 && previousIndex != liveTvIdx) {
if (_liveTvKey.currentState case final FocusableTab focusable) {
focusable.focusActiveTabIfReady();
}
}
// Focus search input when selecting Search tab
if (NavigationTab.isTabAtIndex(NavigationTabId.search, index, isOffline: _isOffline, hasLiveTv: _hasLiveTv)) {
if (_searchKey.currentState case final SearchInputFocusable searchable) {
+42 -36
View File
@@ -98,6 +98,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
late final FocusNode _castFocusNode;
final ScrollController _castScrollController = ScrollController();
final _castSectionKey = GlobalKey();
final _seasonsSectionKey = GlobalKey();
String _toGlobalKey(String ratingKey, {String? serverId}) =>
'${serverId ?? widget.metadata.serverId ?? ''}:$ratingKey';
@@ -1039,19 +1040,19 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
final metadata = _fullMetadata ?? widget.metadata;
// For shows, go to seasons first
if (metadata.isShow && _seasons.isNotEmpty) {
_seasonsFocusNode.requestFocus();
return KeyEventResult.handled;
}
// For movies (or shows with no seasons): overview → cast → extras
// DOWN order: overview → seasons → cast → extras
if (metadata.summary != null) {
_overviewFocusNode.requestFocus();
_scrollSectionIntoView(_overviewSectionKey);
return KeyEventResult.handled;
}
if (metadata.isShow && _seasons.isNotEmpty) {
_seasonsFocusNode.requestFocus();
_scrollSectionIntoView(_seasonsSectionKey);
return KeyEventResult.handled;
}
if (metadata.role != null && metadata.role!.isNotEmpty) {
_castFocusNode.requestFocus();
_scrollSectionIntoView(_castSectionKey);
@@ -1145,20 +1146,23 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
return KeyEventResult.handled;
}
// UP: scroll to top and focus play button
// UP: overview → play button
if (key.isUpKey) {
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
_playButtonFocusNode.requestFocus();
return KeyEventResult.handled;
}
// DOWN: overview → cast → extras (first that exists)
if (key.isDownKey) {
final metadata = _fullMetadata ?? widget.metadata;
if (metadata.summary != null) {
_overviewFocusNode.requestFocus();
_scrollSectionIntoView(_overviewSectionKey);
} else if (metadata.role != null && metadata.role!.isNotEmpty) {
} else {
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
_playButtonFocusNode.requestFocus();
}
return KeyEventResult.handled;
}
// DOWN: cast → extras
if (key.isDownKey) {
final metadata = _fullMetadata ?? widget.metadata;
if (metadata.role != null && metadata.role!.isNotEmpty) {
_castFocusNode.requestFocus();
_scrollSectionIntoView(_castSectionKey);
} else if (_extras != null && _extras!.isNotEmpty) {
@@ -1179,20 +1183,19 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
final metadata = _fullMetadata ?? widget.metadata;
// UP: seasons (if show) or play button
// UP: always play button (overview is directly below play)
if (key.isUpKey) {
if (metadata.isShow && _seasons.isNotEmpty) {
_seasonsFocusNode.requestFocus();
} else {
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
_playButtonFocusNode.requestFocus();
}
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
_playButtonFocusNode.requestFocus();
return KeyEventResult.handled;
}
// DOWN: cast → extras → consume
// DOWN: seasons (if show) → cast → extras
if (key.isDownKey) {
if (metadata.role != null && metadata.role!.isNotEmpty) {
if (metadata.isShow && _seasons.isNotEmpty) {
_seasonsFocusNode.requestFocus();
_scrollSectionIntoView(_seasonsSectionKey);
} else if (metadata.role != null && metadata.role!.isNotEmpty) {
_castFocusNode.requestFocus();
_scrollSectionIntoView(_castSectionKey);
} else if (_extras != null && _extras!.isNotEmpty) {
@@ -1330,17 +1333,18 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
return KeyEventResult.handled;
}
// UP: cast → overview → seasons → play button (first that exists)
// UP: cast → seasons (if show) → overview → play button
if (key.isUpKey) {
final metadata = _fullMetadata ?? widget.metadata;
if (metadata.role != null && metadata.role!.isNotEmpty) {
_castFocusNode.requestFocus();
_scrollSectionIntoView(_castSectionKey);
} else if (metadata.isShow && _seasons.isNotEmpty) {
_seasonsFocusNode.requestFocus();
_scrollSectionIntoView(_seasonsSectionKey);
} else if (metadata.summary != null) {
_overviewFocusNode.requestFocus();
_scrollSectionIntoView(_overviewSectionKey);
} else if (_seasons.isNotEmpty) {
_seasonsFocusNode.requestFocus();
} else {
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
_playButtonFocusNode.requestFocus();
@@ -1383,13 +1387,14 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
return KeyEventResult.handled;
}
// UP: overview → seasons (if show) → play button
// UP: seasons (if show) → overview → play button
if (key.isUpKey) {
if (metadata.summary != null) {
if (metadata.isShow && _seasons.isNotEmpty) {
_seasonsFocusNode.requestFocus();
_scrollSectionIntoView(_seasonsSectionKey);
} else if (metadata.summary != null) {
_overviewFocusNode.requestFocus();
_scrollSectionIntoView(_overviewSectionKey);
} else if (metadata.isShow && _seasons.isNotEmpty) {
_seasonsFocusNode.requestFocus();
} else {
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
_playButtonFocusNode.requestFocus();
@@ -1755,12 +1760,12 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
imageType: ImageType.art,
);
return CachedNetworkImage(
return blurArtwork(CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.cover,
placeholder: (context, url) => const PlaceholderContainer(),
errorWidget: (context, url, error) => const PlaceholderContainer(),
);
));
},
)
: const PlaceholderContainer(),
@@ -1839,7 +1844,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
imageType: ImageType.logo,
);
return CachedNetworkImage(
return blurArtwork(CachedNetworkImage(
imageUrl: logoUrl,
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
@@ -1863,7 +1868,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
errorWidget: (context, url, error) {
return _buildTitleText(context, metadata.title);
},
);
), sigma: 10, clip: false);
},
),
)
@@ -1960,6 +1965,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
// Seasons (for TV shows)
if (isShow) ...[
Text(
key: _seasonsSectionKey,
t.discover.seasons,
style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
),
+3 -2
View File
@@ -5,6 +5,7 @@ import 'package:cached_network_image/cached_network_image.dart';
import '../../models/plex_home_user.dart';
import '../../theme/mono_tokens.dart';
import '../../i18n/strings.g.dart';
import '../../widgets/plex_optimized_image.dart' show blurArtwork;
class UserAvatarWidget extends StatelessWidget {
final PlexHomeUser user;
@@ -141,14 +142,14 @@ class UserAvatarWidget extends StatelessWidget {
children: [
// Avatar image
ClipOval(
child: CachedNetworkImage(
child: blurArtwork(CachedNetworkImage(
imageUrl: user.thumb,
width: size,
height: size,
fit: BoxFit.cover,
placeholder: (ctx, url) => _buildPlaceholderAvatar(theme),
errorWidget: (ctx, url, error) => _buildPlaceholderAvatar(theme),
),
)),
),
// Indicators (only show icon indicators when not using text labels)
@@ -7,6 +7,7 @@ import 'package:material_symbols_icons/symbols.dart';
import '../../i18n/strings.g.dart';
import '../../models/external_player_models.dart';
import '../../services/settings_service.dart';
import '../../focus/key_event_utils.dart';
import '../../widgets/desktop_app_bar.dart';
class ExternalPlayerScreen extends StatefulWidget {
@@ -45,64 +46,72 @@ class _ExternalPlayerScreenState extends State<ExternalPlayerScreen> {
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
return Focus(
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: const Scaffold(body: Center(child: CircularProgressIndicator())),
);
}
final knownPlayers = KnownPlayers.getForCurrentPlatform();
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.externalPlayer.title), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
Card(
child: SwitchListTile(
secondary: const AppIcon(Symbols.open_in_new_rounded, fill: 1),
title: Text(t.externalPlayer.useExternalPlayer),
subtitle: Text(t.externalPlayer.useExternalPlayerDescription),
value: _useExternalPlayer,
onChanged: (value) async {
setState(() => _useExternalPlayer = value);
await _settingsService.setUseExternalPlayer(value);
},
),
),
if (_useExternalPlayer) ...[
const SizedBox(height: 16),
return Focus(
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.externalPlayer.title), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
t.externalPlayer.selectPlayer,
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
// Known players
...knownPlayers.map((player) => _buildPlayerTile(player)),
// Custom players
if (_customPlayers.isNotEmpty) const Divider(),
..._customPlayers.map((player) => _buildPlayerTile(player, isCustom: true)),
// Add custom player button
const Divider(),
ListTile(
leading: const AppIcon(Symbols.add_rounded, fill: 1),
title: Text(t.externalPlayer.addCustomPlayer),
onTap: _showAddCustomPlayerDialog,
),
],
child: SwitchListTile(
secondary: const AppIcon(Symbols.open_in_new_rounded, fill: 1),
title: Text(t.externalPlayer.useExternalPlayer),
subtitle: Text(t.externalPlayer.useExternalPlayerDescription),
value: _useExternalPlayer,
onChanged: (value) async {
setState(() => _useExternalPlayer = value);
await _settingsService.setUseExternalPlayer(value);
},
),
),
],
]),
if (_useExternalPlayer) ...[
const SizedBox(height: 16),
Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
t.externalPlayer.selectPlayer,
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
// Known players
...knownPlayers.map((player) => _buildPlayerTile(player)),
// Custom players
if (_customPlayers.isNotEmpty) const Divider(),
..._customPlayers.map((player) => _buildPlayerTile(player, isCustom: true)),
// Add custom player button
const Divider(),
ListTile(
leading: const AppIcon(Symbols.add_rounded, fill: 1),
title: Text(t.externalPlayer.addCustomPlayer),
onTap: _showAddCustomPlayerDialog,
),
],
),
),
],
]),
),
),
),
],
],
),
),
);
}
+51 -46
View File
@@ -9,6 +9,7 @@ import 'package:logger/logger.dart';
import '../../i18n/strings.g.dart';
import '../../utils/app_logger.dart';
import '../../utils/snackbar_helper.dart';
import '../../focus/key_event_utils.dart';
import '../../widgets/desktop_app_bar.dart';
class LogsScreen extends StatefulWidget {
@@ -165,53 +166,57 @@ class _LogsScreenState extends State<LogsScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(t.screens.logs),
pinned: true,
actions: [
IconButton(
icon: const AppIcon(Symbols.refresh_rounded, fill: 1),
onPressed: _loadLogs,
tooltip: t.common.refresh,
),
IconButton(
icon: const AppIcon(Symbols.upload_rounded, fill: 1),
onPressed: _logs.isNotEmpty ? _uploadLogs : null,
tooltip: t.logs.uploadLogs,
),
IconButton(
icon: const AppIcon(Symbols.content_copy_rounded, fill: 1),
onPressed: _logs.isNotEmpty ? _copyAllLogs : null,
tooltip: t.logs.copyLogs,
),
IconButton(
icon: const AppIcon(Symbols.delete_outline_rounded, fill: 1),
onPressed: _logs.isNotEmpty ? _clearLogs : null,
tooltip: t.logs.clearLogs,
),
],
),
if (_logs.isEmpty)
SliverFillRemaining(child: Center(child: Text(t.messages.noLogsAvailable)))
else
SliverPadding(
padding: const EdgeInsets.all(8),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final log = _logs[index];
return _LogEntryCard(
log: log,
formatTime: _formatTime,
levelColor: _getLevelColor(log.level),
levelIcon: _getLevelIcon(log.level),
);
}, childCount: _logs.length),
),
return Focus(
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(t.screens.logs),
pinned: true,
actions: [
IconButton(
icon: const AppIcon(Symbols.refresh_rounded, fill: 1),
onPressed: _loadLogs,
tooltip: t.common.refresh,
),
IconButton(
icon: const AppIcon(Symbols.upload_rounded, fill: 1),
onPressed: _logs.isNotEmpty ? _uploadLogs : null,
tooltip: t.logs.uploadLogs,
),
IconButton(
icon: const AppIcon(Symbols.content_copy_rounded, fill: 1),
onPressed: _logs.isNotEmpty ? _copyAllLogs : null,
tooltip: t.logs.copyLogs,
),
IconButton(
icon: const AppIcon(Symbols.delete_outline_rounded, fill: 1),
onPressed: _logs.isNotEmpty ? _clearLogs : null,
tooltip: t.logs.clearLogs,
),
],
),
],
if (_logs.isEmpty)
SliverFillRemaining(child: Center(child: Text(t.messages.noLogsAvailable)))
else
SliverPadding(
padding: const EdgeInsets.all(8),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final log = _logs[index];
return _LogEntryCard(
log: log,
formatTime: _formatTime,
levelColor: _getLevelColor(log.level),
levelIcon: _getLevelIcon(log.level),
);
}, childCount: _logs.length),
),
),
],
),
),
);
}
+25 -16
View File
@@ -6,6 +6,7 @@ import '../../models/mpv_config_models.dart';
import '../../utils/dialogs.dart';
import '../../utils/snackbar_helper.dart';
import '../../services/settings_service.dart';
import '../../focus/key_event_utils.dart';
import '../../widgets/desktop_app_bar.dart';
class MpvConfigScreen extends StatefulWidget {
@@ -236,25 +237,33 @@ class _MpvConfigScreenState extends State<MpvConfigScreen> {
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
return Focus(
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: const Scaffold(body: Center(child: CircularProgressIndicator())),
);
}
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.screens.mpvConfig), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildPresetsCard(),
const SizedBox(height: 16),
_buildEntriesCard(),
const SizedBox(height: 24),
]),
return Focus(
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.screens.mpvConfig), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildPresetsCard(),
const SizedBox(height: 16),
_buildEntriesCard(),
const SizedBox(height: 24),
]),
),
),
),
],
],
),
),
);
}
+4 -1
View File
@@ -10,6 +10,7 @@ import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../focus/focus_memory_tracker.dart';
import '../../focus/input_mode_tracker.dart';
import '../../i18n/strings.g.dart';
import '../main_screen.dart';
import '../../mixins/refreshable.dart';
@@ -147,7 +148,9 @@ class _SettingsScreenState extends State<SettingsScreen> with FocusableTab {
@override
void focusActiveTabIfReady() {
_focusTracker.restoreFocus(fallbackKey: _kTheme);
if (InputModeTracker.isKeyboardMode(context)) {
_focusTracker.restoreFocus(fallbackKey: _kTheme);
}
}
/// Navigate focus to the sidebar
@@ -5,6 +5,7 @@ import 'package:flex_color_picker/flex_color_picker.dart';
import '../../i18n/strings.g.dart';
import '../../services/settings_service.dart';
import '../../utils/platform_detector.dart';
import '../../focus/key_event_utils.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../widgets/tv_color_picker.dart';
import '../../widgets/tv_number_spinner.dart';
@@ -282,18 +283,26 @@ class _SubtitleStylingScreenState extends State<SubtitleStylingScreen> {
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
return Focus(
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: const Scaffold(body: Center(child: CircularProgressIndicator())),
);
}
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.screens.subtitleStyling), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(delegate: SliverChildListDelegate([_buildStylingCard(), const SizedBox(height: 24)])),
),
],
return Focus(
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.screens.subtitleStyling), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(delegate: SliverChildListDelegate([_buildStylingCard(), const SizedBox(height: 24)])),
),
],
),
),
);
}
+87 -17
View File
@@ -36,6 +36,7 @@ import '../services/offline_watch_sync_service.dart';
import '../services/settings_service.dart';
import '../services/sleep_timer_service.dart';
import '../services/track_selection_service.dart';
import '../services/ambient_lighting_service.dart';
import '../services/video_filter_manager.dart';
import '../services/video_pip_manager.dart';
import '../services/pip_service.dart';
@@ -53,6 +54,7 @@ import '../utils/snackbar_helper.dart';
import '../utils/track_label_builder.dart' as tlb;
import '../utils/plex_url_helper.dart';
import '../utils/video_player_navigation.dart';
import '../widgets/overlay_sheet.dart';
import '../widgets/video_controls/video_controls.dart';
import '../focus/focusable_wrapper.dart';
import '../focus/input_mode_tracker.dart';
@@ -167,6 +169,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
VideoFilterManager? _videoFilterManager;
VideoPIPManager? _videoPIPManager;
ShaderService? _shaderService;
AmbientLightingService? _ambientLightingService;
final EpisodeNavigationService _episodeNavigation = EpisodeNavigationService();
// Watch Together provider reference (stored early to use in dispose)
@@ -387,6 +390,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
await player!.setProperty('sub-ass', 'yes'); // Enable libass
await player!.setProperty('demuxer-max-bytes', bufferSizeBytes.toString());
await player!.setProperty('msg-level', debugLoggingEnabled ? 'all=debug' : 'all=error');
await player!.setLogLevel(debugLoggingEnabled ? 'v' : 'warn');
await player!.setProperty('hwdec', _getHwdecValue(enableHardwareDecoding));
// Subtitle styling
@@ -1022,6 +1026,11 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// Shader Service (MPV only)
_shaderService = ShaderService(player!);
if (_shaderService!.isSupported) {
// Ambient Lighting Service
_ambientLightingService = AmbientLightingService(player!);
_shaderService!.ambientLightingService = _ambientLightingService;
_videoFilterManager?.ambientLightingService = _ambientLightingService;
await _applySavedShaderPreset();
}
}
@@ -1140,11 +1149,56 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
/// Cycle through BoxFit modes: contain → cover → fill → contain (for button)
void _cycleBoxFitMode() {
// Disable ambient lighting when switching boxfit modes
// (cover/fill change the video rect, making the baked-in shader incorrect)
_ambientLightingService?.disable();
setState(() {
_videoFilterManager?.cycleBoxFitMode();
});
}
/// Update video-aspect-override when player size changes.
/// The shader adapts automatically via built-in target_size uniform.
void _updateAmbientLightingOnResize(Size newSize) {
final ambientLighting = _ambientLightingService;
if (ambientLighting == null || !ambientLighting.isEnabled) return;
if (newSize.height == 0) return;
ambientLighting.updateOutputAspect(newSize.width / newSize.height);
}
/// Toggle ambient lighting effect on/off
Future<void> _toggleAmbientLighting() async {
final ambientLighting = _ambientLightingService;
if (ambientLighting == null || !ambientLighting.isSupported) return;
if (ambientLighting.isEnabled) {
await ambientLighting.disable();
_videoFilterManager?.updateVideoFilter();
} else {
// Get video display aspect ratio
final dwidth = await player?.getProperty('dwidth');
final dheight = await player?.getProperty('dheight');
if (dwidth == null || dheight == null) return;
final w = double.tryParse(dwidth);
final h = double.tryParse(dheight);
if (w == null || h == null || h == 0) return;
final videoAspect = w / h;
// Get player widget aspect ratio
final playerSize = _videoFilterManager?.playerSize;
if (playerSize == null || playerSize.height == 0) return;
final outputAspect = playerSize.width / playerSize.height;
// Force contain mode when enabling ambient lighting
_videoFilterManager?.resetToContain();
await ambientLighting.enable(videoAspect, outputAspect);
}
setState(() {});
}
/// Toggle between contain and cover modes only (for pinch gesture)
void _toggleContainCover() {
setState(() {
@@ -2125,23 +2179,21 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
final isCurrentRoute = ModalRoute.of(context)?.isCurrent ?? true;
// Screen-level Focus wraps ALL phases (loading + initialized).
// - autofocus: grabs focus when no deeper child claims it.
// - onKeyEvent: catch-all that consumes any event children didn't handle,
// preventing leaks to previous routes.
// - onKeyEvent: self-heals when this node has primary focus (no descendant
// focused). Nav keys are only consumed in that case; otherwise they pass
// through so DirectionalFocusAction can drive dpad nav in overlay sheets.
return Focus(
focusNode: _screenFocusNode,
autofocus: isCurrentRoute,
canRequestFocus: isCurrentRoute,
onKeyEvent: (node, event) {
if (!isCurrentRoute) return KeyEventResult.ignored;
// Safety net: if this screen-level node itself has primary focus
// (no descendant focused, e.g. after controls auto-hide), self-heal.
// BACK is excluded: on Android TV the BACK button fires both a key event
// and a system back gesture. Handling it here would double-pop because
// PopScope.onPopInvokedWithResult also processes the system back gesture.
// PopScope handles BACK navigation exclusively.
if (node.hasPrimaryFocus && !event.logicalKey.isBackKey) {
// Redirect focus to the first traversable descendant (video controls)
// and show controls immediately so the first key press isn't swallowed.
// Back keys always pass through — handled by PopScope (system back
// gesture) or overlay sheet's onKeyEvent.
if (event.logicalKey.isBackKey) return KeyEventResult.ignored;
// Self-heal: if this node itself has primary focus (no descendant
// focused, e.g. after controls auto-hide), redirect to first descendant.
if (node.hasPrimaryFocus) {
if (event.isActionable) {
_controlsVisible.value = true;
final descendants = node.traversalDescendants;
@@ -2149,10 +2201,19 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
descendants.first.requestFocus();
}
}
return event.logicalKey.isNavigationKey ? KeyEventResult.handled : KeyEventResult.ignored;
}
return KeyEventResult.handled;
// A descendant has focus — let events pass through so
// DirectionalFocusAction / ActivateAction can process them.
return KeyEventResult.ignored;
},
child: _isPlayerInitialized && player != null ? _buildVideoPlayer(context) : _buildLoadingSpinner(),
child: OverlaySheetHost(
child: Builder(
builder: (sheetContext) => _isPlayerInitialized && player != null
? _buildVideoPlayer(sheetContext)
: _buildLoadingSpinner(),
),
),
);
}
@@ -2163,11 +2224,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
return PopScope(
canPop: false, // Disable swipe-back gesture to prevent interference with timeline scrubbing
onPopInvokedWithResult: (didPop, result) {
// Only process system-initiated back gestures (didPop: false).
// Programmatic Navigator.pop() triggers didPop: true — ignore it here
// to avoid consuming the BackKeyCoordinator flag before the system back
// gesture arrives (which would cause a double-pop on Android TV).
if (!didPop) {
// If an overlay sheet is open, delegate back to it instead of
// exiting the player. This prevents the double-pop on Android TV
// where the system back gesture would otherwise reach both the
// sheet and the player's PopScope.
final sheetController = OverlaySheetController.maybeOf(context);
if (sheetController != null && sheetController.isOpen) {
sheetController.pop();
return;
}
if (BackKeyCoordinator.consumeIfHandled()) return;
BackKeyCoordinator.markHandled();
_handleBackButton();
@@ -2214,6 +2280,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
if (mounted && player != null) {
_videoFilterManager?.updatePlayerSize(newSize);
_videoPIPManager?.updatePlayerSize(newSize);
// Update ambient lighting shader if active (output aspect changed)
_updateAmbientLightingOnResize(newSize);
// Update Metal layer frame on iOS/macOS for rotation
player!.updateFrame();
}
@@ -2283,6 +2351,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
: null,
isLive: widget.isLive,
liveChannelName: _liveChannelName,
isAmbientLightingEnabled: _ambientLightingService?.isEnabled ?? false,
onToggleAmbientLighting: _toggleAmbientLighting,
),
);
},
+249
View File
@@ -0,0 +1,249 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import '../mpv/player/player.dart';
/// Generates and manages an ambient lighting GLSL shader that fills letterbox/pillarbox
/// bars with a blurred, dimmed version of the video edges.
///
/// Uses video-aspect-override to fill the window (eliminating black bars), then
/// a GLSL shader composites the sharp original video centered at correct aspect
/// over a blurred background.
///
/// The shader uses MPV's built-in `input_size` and `target_size` uniforms to
/// dynamically compute the video rect position. On window resize, only
/// `video-aspect-override` needs updating — no shader regeneration required.
class AmbientLightingService {
final Player _player;
String? _shaderPath;
bool _enabled = false;
/// Brightness multiplier for the blurred background (0.0-1.0).
static const double _brightness = 0.5;
AmbientLightingService(this._player);
bool get isEnabled => _enabled;
bool get isSupported => _player.playerType == 'mpv';
/// Enable ambient lighting effect.
///
/// [videoAspect] - the source video's display aspect ratio (width/height).
/// [outputAspect] - the player widget's aspect ratio (width/height).
Future<void> enable(double videoAspect, double outputAspect) async {
if (!isSupported) return;
try {
// Write static shader (only needs to happen once)
if (_shaderPath == null) {
_shaderPath = await _writeShaderToTemp(_generateShader());
}
if (kDebugMode) {
debugPrint('AmbientLightingService: Shader path: $_shaderPath');
}
// Set video-aspect-override to fill the entire output area
await _player.setProperty('video-aspect-override', outputAspect.toString());
// Append ambient lighting shader
await _player.command(['change-list', 'glsl-shaders', 'append', _shaderPath!]);
_enabled = true;
if (kDebugMode) {
debugPrint('AmbientLightingService: Enabled (video=$videoAspect, output=$outputAspect)');
}
} catch (e) {
if (kDebugMode) {
debugPrint('AmbientLightingService: Failed to enable: $e');
}
}
}
/// Disable ambient lighting effect and restore normal letterboxing.
Future<void> disable() async {
if (!_enabled) return;
try {
if (_shaderPath != null) {
await _player.command(['change-list', 'glsl-shaders', 'remove', _shaderPath!]);
}
await _player.setProperty('video-aspect-override', 'no');
_enabled = false;
if (kDebugMode) {
debugPrint('AmbientLightingService: Disabled');
}
} catch (e) {
if (kDebugMode) {
debugPrint('AmbientLightingService: Failed to disable: $e');
}
}
}
/// Re-append the ambient lighting shader to the chain.
/// Called by ShaderService after it rebuilds the shader chain (clr + append).
Future<void> reappendShader() async {
if (!_enabled || _shaderPath == null) return;
await _player.command(['change-list', 'glsl-shaders', 'append', _shaderPath!]);
}
/// Update video-aspect-override when the window resizes.
/// The shader adapts automatically via dynamic `target_size` uniform.
void updateOutputAspect(double outputAspect) {
if (!_enabled) return;
_player.setProperty('video-aspect-override', outputAspect.toString());
}
/// Generate a static multi-pass GLSL shader.
///
/// Uses MPV's built-in `input_size` (video dimensions) and `target_size`
/// (output dimensions) uniforms which update automatically on resize.
/// No baked-in aspect constants — fully adaptive.
///
/// Pipeline (all MAIN hooks):
/// 1. Save original video as ORIGINAL
/// 2. Downscale to 1/8 as SMALL (center 60% zoom)
/// 3-5. Three Kawase blur passes at 1/8 -> BLUR8C
/// 6. Downscale BLUR8C to 1/64 as TINY
/// 7-8. Two more Kawase blur passes at 1/64 -> GLOW
/// 9. Composite: video rect -> ORIGINAL, bars -> GLOW
String _generateShader() {
final br = _brightness.toStringAsFixed(2);
final buf = StringBuffer();
// Pass 1: Save original video
buf.writeln('//!HOOK MAIN');
buf.writeln('//!BIND HOOKED');
buf.writeln('//!SAVE ORIGINAL');
buf.writeln('//!DESC Ambient Lighting Save');
buf.writeln('vec4 hook() {');
buf.writeln(' return HOOKED_tex(HOOKED_pos);');
buf.writeln('}');
buf.writeln();
// Pass 2: Downscale to 1/8 with center zoom.
buf.writeln('//!HOOK MAIN');
buf.writeln('//!BIND ORIGINAL');
buf.writeln('//!SAVE SMALL');
buf.writeln('//!WIDTH ORIGINAL.w 8 /');
buf.writeln('//!HEIGHT ORIGINAL.h 8 /');
buf.writeln('//!DESC Ambient Lighting Downscale');
buf.writeln('vec4 hook() {');
buf.writeln(' vec2 uv = ORIGINAL_pos * 0.6 + 0.2;');
buf.writeln(' return ORIGINAL_tex(uv);');
buf.writeln('}');
buf.writeln();
// Pass 3-5: Three Kawase blur passes at 1/8 resolution.
const blur8Steps = [
('SMALL', 'BLUR8A', '2.0', 'Blur1'),
('BLUR8A', 'BLUR8B', '6.0', 'Blur2'),
('BLUR8B', 'BLUR8C', '12.0', 'Blur3'),
];
for (final (input, output, offset, desc) in blur8Steps) {
buf.writeln('//!HOOK MAIN');
buf.writeln('//!BIND $input');
buf.writeln('//!SAVE $output');
buf.writeln('//!WIDTH $input.w');
buf.writeln('//!HEIGHT $input.h');
buf.writeln('//!DESC Ambient Lighting $desc');
buf.writeln('vec4 hook() {');
buf.writeln(' vec2 ps = ${input}_pt;');
buf.writeln(' vec4 s = ${input}_tex(${input}_pos + vec2( $offset, $offset) * ps)');
buf.writeln(' + ${input}_tex(${input}_pos + vec2( $offset, -$offset) * ps)');
buf.writeln(' + ${input}_tex(${input}_pos + vec2(-$offset, $offset) * ps)');
buf.writeln(' + ${input}_tex(${input}_pos + vec2(-$offset, -$offset) * ps);');
buf.writeln(' return s * 0.25;');
buf.writeln('}');
buf.writeln();
}
// Pass 6: Downscale the already-blurred 1/8 texture to 1/64.
buf.writeln('//!HOOK MAIN');
buf.writeln('//!BIND BLUR8C');
buf.writeln('//!SAVE TINY');
buf.writeln('//!WIDTH BLUR8C.w 8 /');
buf.writeln('//!HEIGHT BLUR8C.h 8 /');
buf.writeln('//!DESC Ambient Lighting Downscale2');
buf.writeln('vec4 hook() {');
buf.writeln(' return BLUR8C_tex(BLUR8C_pos);');
buf.writeln('}');
buf.writeln();
// Pass 7-8: Two more Kawase blur passes at 1/64 for maximum diffusion.
const blur64Steps = [
('TINY', 'GLOW1', '3.0', 'Blur4'),
('GLOW1', 'GLOW', '6.0', 'Blur5'),
];
for (final (input, output, offset, desc) in blur64Steps) {
buf.writeln('//!HOOK MAIN');
buf.writeln('//!BIND $input');
buf.writeln('//!SAVE $output');
buf.writeln('//!WIDTH $input.w');
buf.writeln('//!HEIGHT $input.h');
buf.writeln('//!DESC Ambient Lighting $desc');
buf.writeln('vec4 hook() {');
buf.writeln(' vec2 ps = ${input}_pt;');
buf.writeln(' vec4 s = ${input}_tex(${input}_pos + vec2( $offset, $offset) * ps)');
buf.writeln(' + ${input}_tex(${input}_pos + vec2( $offset, -$offset) * ps)');
buf.writeln(' + ${input}_tex(${input}_pos + vec2(-$offset, $offset) * ps)');
buf.writeln(' + ${input}_tex(${input}_pos + vec2(-$offset, -$offset) * ps);');
buf.writeln(' return s * 0.25;');
buf.writeln('}');
buf.writeln();
}
// Pass 9: Composite — no //!SAVE so this replaces MAIN.
// Uses built-in input_size (video coded dims) and target_size (output dims)
// to dynamically compute where the video rect sits. These auto-update on resize.
buf.writeln('//!HOOK MAIN');
buf.writeln('//!BIND ORIGINAL');
buf.writeln('//!BIND GLOW');
buf.writeln('//!DESC Ambient Lighting Composite');
buf.writeln('vec4 hook() {');
buf.writeln(' float vid_aspect = input_size.x / input_size.y;');
buf.writeln(' float out_aspect = target_size.x / target_size.y;');
buf.writeln();
buf.writeln(' vec2 scale, off;');
buf.writeln(' if (vid_aspect > out_aspect) {');
buf.writeln(' float s = out_aspect / vid_aspect;');
buf.writeln(' scale = vec2(1.0, s);');
buf.writeln(' off = vec2(0.0, (1.0 - s) * 0.5);');
buf.writeln(' } else {');
buf.writeln(' float s = vid_aspect / out_aspect;');
buf.writeln(' scale = vec2(s, 1.0);');
buf.writeln(' off = vec2((1.0 - s) * 0.5, 0.0);');
buf.writeln(' }');
buf.writeln();
buf.writeln(' vec2 vid_pos = (ORIGINAL_pos - off) / scale;');
buf.writeln();
buf.writeln(' if (all(greaterThanEqual(vid_pos, vec2(0.0))) &&');
buf.writeln(' all(lessThanEqual(vid_pos, vec2(1.0)))) {');
buf.writeln(' return ORIGINAL_tex(vid_pos);');
buf.writeln(' }');
buf.writeln();
buf.writeln(' return GLOW_tex(ORIGINAL_pos) * $br;');
buf.writeln('}');
return buf.toString();
}
/// Write the shader to a temp file and return the path.
Future<String> _writeShaderToTemp(String shader) async {
final cacheDir = await getTemporaryDirectory();
final shaderDir = Directory(path.join(cacheDir.path, 'shaders'));
if (!shaderDir.existsSync()) {
shaderDir.createSync(recursive: true);
}
final file = File(path.join(shaderDir.path, 'ambient_lighting.glsl'));
await file.writeAsString(shader);
return file.path;
}
}
+40 -32
View File
@@ -240,6 +240,7 @@ class DownloadManagerService {
// Prevents concurrent _processQueue calls
bool _isProcessingQueue = false;
bool _disposed = false;
// Debounce timers for DB progress writes (keyed by globalKey).
// UI progress streams are still real-time; only the DB write is debounced.
@@ -626,6 +627,7 @@ class DownloadManagerService {
/// Callback: background_downloader progress update
void _onTaskProgress(TaskProgressUpdate update) {
if (_disposed) return;
final globalKey = update.task.metaData;
if (globalKey.isEmpty || update.progress < 0) return;
@@ -666,44 +668,49 @@ class DownloadManagerService {
/// Callback: background_downloader status change
void _onTaskStatusChanged(TaskStatusUpdate update) {
if (_disposed) return;
final globalKey = update.task.metaData;
if (globalKey.isEmpty) return;
appLogger.d('Background task status: ${update.status} for $globalKey');
switch (update.status) {
case TaskStatus.complete:
_onDownloadComplete(globalKey, update.task);
case TaskStatus.failed:
_onDownloadFailed(globalKey, update.exception?.description ?? 'Download failed');
case TaskStatus.notFound:
_onDownloadFailed(globalKey, 'File not found (404)');
case TaskStatus.canceled:
if (_pausingKeys.contains(globalKey)) {
// Expected cancel from holding-queue promotion during pause — ignore
try {
switch (update.status) {
case TaskStatus.complete:
_onDownloadComplete(globalKey, update.task);
case TaskStatus.failed:
_onDownloadFailed(globalKey, update.exception?.description ?? 'Download failed');
case TaskStatus.notFound:
_onDownloadFailed(globalKey, 'File not found (404)');
case TaskStatus.canceled:
if (_pausingKeys.contains(globalKey)) {
// Expected cancel from holding-queue promotion during pause — ignore
break;
}
final ctx = _pendingDownloadContext.remove(globalKey);
if (ctx != null) {
// Context still present → OS cancelled the task, not user code
// (user-initiated pause/cancel/delete removes context before cancellation completes)
appLogger.w('Download cancelled by system for $globalKey, re-queuing');
_database.updateBgTaskId(globalKey, null);
_transitionStatus(globalKey, DownloadStatus.queued);
_database.addToQueue(mediaGlobalKey: globalKey);
if (_lastClient != null) _processQueue(_lastClient!);
}
case TaskStatus.paused:
appLogger.d('Download paused by system for $globalKey');
case TaskStatus.waitingToRetry:
appLogger.d('Download waiting to retry for $globalKey');
case TaskStatus.enqueued:
case TaskStatus.running:
// If this item is being paused, the holding queue promoted it — cancel it
if (_pausingKeys.contains(globalKey)) {
FileDownloader().cancelTaskWithId(update.task.taskId);
}
break;
}
final ctx = _pendingDownloadContext.remove(globalKey);
if (ctx != null) {
// Context still present → OS cancelled the task, not user code
// (user-initiated pause/cancel/delete removes context before cancellation completes)
appLogger.w('Download cancelled by system for $globalKey, re-queuing');
_database.updateBgTaskId(globalKey, null);
_transitionStatus(globalKey, DownloadStatus.queued);
_database.addToQueue(mediaGlobalKey: globalKey);
if (_lastClient != null) _processQueue(_lastClient!);
}
case TaskStatus.paused:
appLogger.d('Download paused by system for $globalKey');
case TaskStatus.waitingToRetry:
appLogger.d('Download waiting to retry for $globalKey');
case TaskStatus.enqueued:
case TaskStatus.running:
// If this item is being paused, the holding queue promoted it — cancel it
if (_pausingKeys.contains(globalKey)) {
FileDownloader().cancelTaskWithId(update.task.taskId);
}
break;
}
} catch (e) {
appLogger.e('Error handling download status change for $globalKey', error: e);
}
}
@@ -1661,6 +1668,7 @@ class DownloadManagerService {
}
void dispose() {
_disposed = true;
for (final timer in _progressDebounceTimers.values) {
timer.cancel();
}
+1
View File
@@ -2037,6 +2037,7 @@ class PlexClient {
.where((ch) => ch.key.isNotEmpty)
.toList();
}
appLogger.d('EPG channels: container keys=${container?.keys.toList()}, size=${container?['size']}');
return [];
}, 'Failed to get EPG channels');
}
+26
View File
@@ -2,15 +2,21 @@ import 'package:flutter/foundation.dart';
import '../models/shader_preset.dart';
import '../mpv/player/player.dart';
import 'ambient_lighting_service.dart';
import 'shader_asset_loader.dart';
/// Service for applying GLSL shaders to the MPV video player.
///
/// Handles shader chain building, HDR detection, and runtime switching.
/// When ambient lighting is active, the ambient lighting shader is always appended last
/// in the chain after any upscaling/processing shaders.
class ShaderService {
final Player _player;
ShaderPreset _currentPreset = ShaderPreset.none;
/// Reference to ambient lighting service for re-appending its shader after chain rebuilds.
AmbientLightingService? ambientLightingService;
ShaderService(this._player);
/// The currently applied shader preset
@@ -41,6 +47,7 @@ class ShaderService {
}
await _clearShaders();
_currentPreset = ShaderPreset.none;
await _reappendAmbientLighting();
return;
}
}
@@ -52,6 +59,7 @@ class ShaderService {
// No shaders - clear any existing ones
await _clearShaders();
_currentPreset = preset;
await _reappendAmbientLighting();
return;
}
@@ -65,6 +73,9 @@ class ShaderService {
_currentPreset = preset;
// Re-append ambient lighting shader at end of chain
await _reappendAmbientLighting();
if (kDebugMode) {
debugPrint('ShaderService: Applied ${preset.name} with ${shaderPaths.length} shaders');
}
@@ -87,6 +98,21 @@ class ShaderService {
}
}
/// Re-append the ambient lighting shader if it's active.
/// Called after shader chain rebuilds to keep ambient lighting last.
Future<void> _reappendAmbientLighting() async {
final service = ambientLightingService;
if (service == null || !service.isEnabled) return;
try {
await service.reappendShader();
} catch (e) {
if (kDebugMode) {
debugPrint('ShaderService: Failed to re-append ambient lighting: $e');
}
}
}
/// Check if the current video content is HDR.
Future<bool> _isHdrContent() async {
try {
+1
View File
@@ -101,6 +101,7 @@ class SleepTimerService extends ChangeNotifier {
@override
void dispose() {
_timer?.cancel();
_completedController.close();
super.dispose();
}
}
+18 -3
View File
@@ -5,6 +5,7 @@ import '../mpv/mpv.dart';
import '../models/plex_media_version.dart';
import '../utils/app_logger.dart';
import 'ambient_lighting_service.dart';
/// Manages video filtering, aspect ratio modes, and subtitle positioning for video playback.
///
@@ -13,6 +14,7 @@ import '../utils/app_logger.dart';
/// - Video cropping calculations for fill screen mode
/// - Subtitle positioning adjustments based on crop parameters
/// - Debounced video filter updates on resize events
/// - Ambient-lighting-friendly reset to contain mode
class VideoFilterManager {
final Player player;
final List<PlexMediaVersion> availableVersions;
@@ -24,6 +26,9 @@ class VideoFilterManager {
/// Store the boxFitMode before entering PiP so it can be restored
int? _prePipBoxFitMode;
/// Ambient lighting service reference - when active, video-aspect-override is managed by ambient lighting
AmbientLightingService? ambientLightingService;
/// Track if a pinch gesture is occurring (public for gesture tracking)
bool isPinching = false;
@@ -54,6 +59,14 @@ class VideoFilterManager {
updateVideoFilter();
}
/// Reset to contain mode (mode 0). Used when enabling ambient lighting.
void resetToContain() {
if (_boxFitMode != 0) {
_boxFitMode = 0;
updateVideoFilter();
}
}
/// Toggle between contain and cover modes only (for pinch gesture)
void toggleContainCover() {
_boxFitMode = _boxFitMode == 0 ? 1 : 0;
@@ -89,11 +102,13 @@ class VideoFilterManager {
}
}
/// Update the video scaling and positioning based on current display mode
/// Update the video scaling and positioning based on current display mode.
/// When ambient lighting is active, video-aspect-override is managed by ambient lighting.
void updateVideoFilter() async {
try {
// Clear all video filters and manual scaling first
await player.setProperty('video-aspect-override', 'no');
if (ambientLightingService?.isEnabled != true) {
await player.setProperty('video-aspect-override', 'no');
}
await player.setProperty('sub-ass-force-margins', 'no');
await player.setProperty('panscan', '0');
@@ -8,6 +8,7 @@ import 'package:provider/provider.dart';
import '../../i18n/strings.g.dart';
import '../../utils/dialogs.dart';
import '../../utils/snackbar_helper.dart';
import '../../widgets/overlay_sheet.dart';
import '../models/watch_session.dart';
import '../providers/watch_together_provider.dart';
@@ -43,8 +44,7 @@ class WatchTogetherOverlay extends StatelessWidget {
}
void _showSessionMenu(BuildContext context, WatchTogetherProvider provider) {
showModalBottomSheet(
context: context,
OverlaySheetController.of(context).show(
builder: (context) => _SessionMenuSheet(provider: provider, onLeaveSession: onLeaveSession),
);
}
@@ -249,7 +249,7 @@ class _SessionMenuSheet extends StatelessWidget {
style: TextStyle(color: theme.colorScheme.error),
),
onTap: () {
Navigator.pop(context);
OverlaySheetController.of(context).close();
_confirmLeave(context);
},
contentPadding: EdgeInsets.zero,
+20 -7
View File
@@ -2,6 +2,8 @@ import 'package:flutter/material.dart';
import 'package:plezy/widgets/app_icon.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'overlay_sheet.dart';
/// A reusable header widget for bottom sheets
/// Provides consistent styling with title, optional leading widget, optional action, and close button
class BottomSheetHeader extends StatelessWidget {
@@ -68,9 +70,11 @@ class BottomSheetHeader extends StatelessWidget {
if (leading != null) {
resolvedLeading = leading;
} else if (onBack != null) {
resolvedLeading = IconButton(
icon: AppIcon(Symbols.arrow_back_rounded, fill: 1, color: iconColor),
onPressed: onBack,
resolvedLeading = ExcludeFocusTraversal(
child: IconButton(
icon: AppIcon(Symbols.arrow_back_rounded, fill: 1, color: iconColor),
onPressed: onBack,
),
);
} else if (icon != null) {
resolvedLeading = AppIcon(icon!, fill: 1, color: iconColor);
@@ -91,10 +95,19 @@ class BottomSheetHeader extends StatelessWidget {
if (resolvedLeading != null) ...[resolvedLeading, const SizedBox(width: 8)],
Expanded(child: Text(title, style: effectiveTitleStyle)),
?action,
IconButton(
focusNode: closeFocusNode,
icon: AppIcon(Symbols.close_rounded, fill: 1, color: iconColor),
onPressed: onClose ?? () => Navigator.pop(context),
ExcludeFocusTraversal(
child: IconButton(
focusNode: closeFocusNode,
icon: AppIcon(Symbols.close_rounded, fill: 1, color: iconColor),
onPressed: onClose ?? () {
final sheetController = OverlaySheetController.maybeOf(context);
if (sheetController != null) {
sheetController.close();
} else {
Navigator.pop(context);
}
},
),
),
],
),
+73 -90
View File
@@ -3,7 +3,6 @@ import 'package:material_symbols_icons/symbols.dart';
import '../models/plex_file_info.dart';
import '../i18n/strings.g.dart';
import 'bottom_sheet_header.dart';
import 'focusable_bottom_sheet.dart';
class FileInfoBottomSheet extends StatefulWidget {
final PlexFileInfo fileInfo;
@@ -32,100 +31,84 @@ class _FileInfoBottomSheetState extends State<FileInfoBottomSheet> {
@override
Widget build(BuildContext context) {
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: Container(
decoration: BoxDecoration(
color: Colors.grey[900],
borderRadius: const BorderRadius.only(topLeft: Radius.circular(16), topRight: Radius.circular(16)),
return Column(
children: [
// Header
BottomSheetHeader(
title: t.fileInfo.title,
icon: Symbols.info_rounded,
iconColor: Colors.white,
titleColor: Colors.white,
closeFocusNode: _initialFocusNode,
),
child: SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
// Header
BottomSheetHeader(
title: t.fileInfo.title,
icon: Symbols.info_rounded,
iconColor: Colors.white,
titleColor: Colors.white,
closeFocusNode: _initialFocusNode,
),
// Content
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
// Title
if (widget.title.isNotEmpty) ...[
Text(
widget.title,
style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
),
const SizedBox(height: 20),
],
// Video Section
_buildSectionHeader(t.fileInfo.video),
const SizedBox(height: 8),
_buildInfoRow(t.fileInfo.codec, widget.fileInfo.videoCodec ?? t.common.unknown),
_buildInfoRow(t.fileInfo.resolution, widget.fileInfo.resolutionFormatted),
_buildInfoRow(t.fileInfo.bitrate, widget.fileInfo.bitrateFormatted),
_buildInfoRow(t.fileInfo.frameRate, widget.fileInfo.frameRateFormatted),
_buildInfoRow(t.fileInfo.aspectRatio, widget.fileInfo.aspectRatioFormatted),
if (widget.fileInfo.videoProfile != null)
_buildInfoRow(t.fileInfo.profile, widget.fileInfo.videoProfile!),
if (widget.fileInfo.bitDepth != null)
_buildInfoRow(t.fileInfo.bitDepth, '${widget.fileInfo.bitDepth} bit'),
if (widget.fileInfo.colorSpace != null)
_buildInfoRow(t.fileInfo.colorSpace, widget.fileInfo.colorSpace!),
if (widget.fileInfo.colorRange != null)
_buildInfoRow(t.fileInfo.colorRange, widget.fileInfo.colorRange!),
if (widget.fileInfo.colorPrimaries != null)
_buildInfoRow(t.fileInfo.colorPrimaries, widget.fileInfo.colorPrimaries!),
if (widget.fileInfo.chromaSubsampling != null)
_buildInfoRow(t.fileInfo.chromaSubsampling, widget.fileInfo.chromaSubsampling!),
const SizedBox(height: 20),
// Audio Section
_buildSectionHeader(t.fileInfo.audio),
const SizedBox(height: 8),
_buildInfoRow(t.fileInfo.codec, widget.fileInfo.audioCodec ?? t.common.unknown),
_buildInfoRow(t.fileInfo.channels, widget.fileInfo.audioChannelsFormatted),
if (widget.fileInfo.audioProfile != null)
_buildInfoRow(t.fileInfo.profile, widget.fileInfo.audioProfile!),
const SizedBox(height: 20),
// File Section
_buildSectionHeader(t.fileInfo.file),
const SizedBox(height: 8),
if (widget.fileInfo.filePath != null)
_buildInfoRow(t.fileInfo.path, widget.fileInfo.filePath!, isMonospace: true),
_buildInfoRow(t.fileInfo.size, widget.fileInfo.fileSizeFormatted),
_buildInfoRow(t.fileInfo.container, widget.fileInfo.container ?? t.common.unknown),
_buildInfoRow(t.fileInfo.duration, widget.fileInfo.durationFormatted),
const SizedBox(height: 20),
// Advanced Section
_buildSectionHeader(t.fileInfo.advanced),
const SizedBox(height: 8),
_buildInfoRow(
t.fileInfo.optimizedForStreaming,
widget.fileInfo.optimizedForStreaming == true ? t.common.yes : t.common.no,
),
_buildInfoRow(
t.fileInfo.has64bitOffsets,
widget.fileInfo.has64bitOffsets == true ? t.common.yes : t.common.no,
),
],
),
// Content
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
// Title
if (widget.title.isNotEmpty) ...[
Text(
widget.title,
style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
),
const SizedBox(height: 20),
],
),
// Video Section
_buildSectionHeader(t.fileInfo.video),
const SizedBox(height: 8),
_buildInfoRow(t.fileInfo.codec, widget.fileInfo.videoCodec ?? t.common.unknown),
_buildInfoRow(t.fileInfo.resolution, widget.fileInfo.resolutionFormatted),
_buildInfoRow(t.fileInfo.bitrate, widget.fileInfo.bitrateFormatted),
_buildInfoRow(t.fileInfo.frameRate, widget.fileInfo.frameRateFormatted),
_buildInfoRow(t.fileInfo.aspectRatio, widget.fileInfo.aspectRatioFormatted),
if (widget.fileInfo.videoProfile != null)
_buildInfoRow(t.fileInfo.profile, widget.fileInfo.videoProfile!),
if (widget.fileInfo.bitDepth != null)
_buildInfoRow(t.fileInfo.bitDepth, '${widget.fileInfo.bitDepth} bit'),
if (widget.fileInfo.colorSpace != null) _buildInfoRow(t.fileInfo.colorSpace, widget.fileInfo.colorSpace!),
if (widget.fileInfo.colorRange != null) _buildInfoRow(t.fileInfo.colorRange, widget.fileInfo.colorRange!),
if (widget.fileInfo.colorPrimaries != null)
_buildInfoRow(t.fileInfo.colorPrimaries, widget.fileInfo.colorPrimaries!),
if (widget.fileInfo.chromaSubsampling != null)
_buildInfoRow(t.fileInfo.chromaSubsampling, widget.fileInfo.chromaSubsampling!),
const SizedBox(height: 20),
// Audio Section
_buildSectionHeader(t.fileInfo.audio),
const SizedBox(height: 8),
_buildInfoRow(t.fileInfo.codec, widget.fileInfo.audioCodec ?? t.common.unknown),
_buildInfoRow(t.fileInfo.channels, widget.fileInfo.audioChannelsFormatted),
if (widget.fileInfo.audioProfile != null)
_buildInfoRow(t.fileInfo.profile, widget.fileInfo.audioProfile!),
const SizedBox(height: 20),
// File Section
_buildSectionHeader(t.fileInfo.file),
const SizedBox(height: 8),
if (widget.fileInfo.filePath != null)
_buildInfoRow(t.fileInfo.path, widget.fileInfo.filePath!, isMonospace: true),
_buildInfoRow(t.fileInfo.size, widget.fileInfo.fileSizeFormatted),
_buildInfoRow(t.fileInfo.container, widget.fileInfo.container ?? t.common.unknown),
_buildInfoRow(t.fileInfo.duration, widget.fileInfo.durationFormatted),
const SizedBox(height: 20),
// Advanced Section
_buildSectionHeader(t.fileInfo.advanced),
const SizedBox(height: 8),
_buildInfoRow(
t.fileInfo.optimizedForStreaming,
widget.fileInfo.optimizedForStreaming == true ? t.common.yes : t.common.no,
),
_buildInfoRow(
t.fileInfo.has64bitOffsets,
widget.fileInfo.has64bitOffsets == true ? t.common.yes : t.common.no,
),
],
),
),
),
],
);
}
-77
View File
@@ -1,77 +0,0 @@
import 'package:flutter/material.dart';
import '../focus/input_mode_tracker.dart';
import '../focus/dpad_navigator.dart';
import '../focus/key_event_utils.dart';
/// A wrapper widget that provides autofocus functionality for bottom sheets.
///
/// When the sheet opens and keyboard/controller mode is active, this widget
/// will automatically request focus on the provided [initialFocusNode].
/// This enables keyboard/controller navigation within the sheet.
///
/// When opened via touch/mouse, no autofocus occurs to avoid showing
/// focus indicators unnecessarily.
class FocusableBottomSheet extends StatefulWidget {
/// The content of the bottom sheet.
final Widget child;
/// The FocusNode to focus when the sheet opens in keyboard mode.
/// If null, no autofocus occurs.
final FocusNode? initialFocusNode;
const FocusableBottomSheet({super.key, required this.child, this.initialFocusNode});
@override
State<FocusableBottomSheet> createState() => _FocusableBottomSheetState();
}
class _FocusableBottomSheetState extends State<FocusableBottomSheet> {
@override
void initState() {
super.initState();
// Clear any stale back key suppression from previous sheet closes
BackKeyUpSuppressor.clearSuppression();
_requestInitialFocus();
}
void _requestInitialFocus() {
if (widget.initialFocusNode == null) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
// Only autofocus when in keyboard/controller mode
if (InputModeTracker.isKeyboardMode(context)) {
widget.initialFocusNode?.requestFocus();
}
});
}
@override
void didUpdateWidget(FocusableBottomSheet oldWidget) {
super.didUpdateWidget(oldWidget);
// If the focus node changed, request focus on the new one
if (widget.initialFocusNode != oldWidget.initialFocusNode) {
_requestInitialFocus();
}
}
@override
Widget build(BuildContext context) {
return Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: (node, event) {
// Handle select key suppression (for when sheet was opened via select key)
if (SelectKeyUpSuppressor.consumeIfSuppressed(event)) {
return KeyEventResult.handled;
}
// Handle back key to close the bottom sheet
return handleBackKeyNavigation(context, event);
},
child: widget.child,
);
}
}
+1 -1
View File
@@ -41,7 +41,7 @@ class FocusedScrollScaffold extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Focus(
canRequestFocus: false,
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: Scaffold(
body: CustomScrollView(
+150 -94
View File
@@ -24,8 +24,8 @@ import '../utils/smart_deletion_handler.dart';
import '../utils/deletion_notifier.dart';
import '../theme/mono_tokens.dart';
import '../widgets/file_info_bottom_sheet.dart';
import '../widgets/focusable_bottom_sheet.dart';
import '../widgets/focusable_list_tile.dart';
import '../widgets/overlay_sheet.dart';
import '../i18n/strings.g.dart';
/// Helper class to store menu action data
@@ -130,7 +130,12 @@ class MediaContextMenuState extends State<MediaContextMenu> {
metadata!.viewedLeafCount != null &&
metadata.leafCount != null &&
metadata.viewedLeafCount! > 0 &&
metadata.viewedLeafCount! < widget.item.leafCount!;
metadata.viewedLeafCount! < metadata.leafCount!;
final hasActiveProgress =
mediaType != null &&
(mediaType == PlexMediaType.movie || mediaType == PlexMediaType.episode) &&
metadata?.hasActiveProgress == true;
// Check if we should use bottom sheet (on iOS and Android)
final useBottomSheet = Platform.isIOS || Platform.isAndroid;
@@ -154,14 +159,14 @@ class MediaContextMenuState extends State<MediaContextMenu> {
// Regular menu items for other types
// Mark as Watched
if (!metadata!.isWatched || isPartiallyWatched) {
if (!metadata!.isWatched || isPartiallyWatched || hasActiveProgress) {
menuActions.add(
_MenuAction(value: 'watch', icon: Symbols.check_circle_outline_rounded, label: t.mediaMenu.markAsWatched),
);
}
// Mark as Unwatched
if (metadata.isWatched || isPartiallyWatched) {
if (metadata.isWatched || isPartiallyWatched || hasActiveProgress) {
menuActions.add(
_MenuAction(
value: 'unwatch',
@@ -281,15 +286,26 @@ class MediaContextMenuState extends State<MediaContextMenu> {
_openedFromKeyboard = false;
if (useBottomSheet) {
// Show bottom sheet on mobile
selected = await showModalBottomSheet<String>(
context: context,
builder: (context) => _FocusableContextMenuSheet(
title: widget.item.title,
actions: menuActions,
focusFirstItem: openedFromKeyboard,
),
);
// Show overlay sheet if available, otherwise fall back to modal bottom sheet
final overlayController = OverlaySheetController.maybeOf(context);
if (overlayController != null) {
selected = await overlayController.show<String>(
builder: (context) => _FocusableContextMenuSheet(
title: widget.item.title,
actions: menuActions,
focusFirstItem: openedFromKeyboard,
),
);
} else {
selected = await showModalBottomSheet<String>(
context: context,
builder: (context) => _FocusableContextMenuSheet(
title: widget.item.title,
actions: menuActions,
focusFirstItem: openedFromKeyboard,
),
);
}
} else {
// Show custom focusable popup menu on larger screens
// Use stored tap position or fallback to widget position
@@ -524,12 +540,19 @@ class MediaContextMenuState extends State<MediaContextMenu> {
if (fileInfo != null && context.mounted) {
// Show file info bottom sheet
await showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => FileInfoBottomSheet(fileInfo: fileInfo, title: metadata.title),
);
final overlayController = OverlaySheetController.maybeOf(context);
if (overlayController != null) {
await overlayController.show(
builder: (context) => FileInfoBottomSheet(fileInfo: fileInfo, title: metadata.title),
);
} else {
await showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => FileInfoBottomSheet(fileInfo: fileInfo, title: metadata.title),
);
}
} else if (context.mounted) {
showErrorSnackBar(context, t.messages.fileInfoNotAvailable);
}
@@ -569,48 +592,77 @@ class MediaContextMenuState extends State<MediaContextMenu> {
_MenuAction(value: 'collection', icon: Symbols.collections_rounded, label: t.collections.collection),
];
final selected = useBottomSheet
? await showModalBottomSheet<String>(
context: context,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(t.common.addTo, style: Theme.of(context).textTheme.titleMedium),
),
...submenuActions.map((action) {
return ListTile(
leading: AppIcon(action.icon, fill: 1),
title: Text(action.label),
onTap: () => Navigator.pop(context, action.value),
);
}),
const SizedBox(height: 8),
],
),
),
)
: await showMenu<String>(
context: context,
position: RelativeRect.fromLTRB(
_tapPosition?.dx ?? 0,
_tapPosition?.dy ?? 0,
_tapPosition?.dx ?? 0,
_tapPosition?.dy ?? 0,
),
items: submenuActions.map((action) {
return PopupMenuItem<String>(
value: action.value,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [AppIcon(action.icon, fill: 1, size: 20), const SizedBox(width: 12), Text(action.label)],
String? selected;
if (useBottomSheet) {
final overlayController = OverlaySheetController.maybeOf(context);
if (overlayController != null) {
selected = await overlayController.push<String>(
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(t.common.addTo, style: Theme.of(context).textTheme.titleMedium),
),
);
}).toList(),
...submenuActions.map((action) {
return ListTile(
leading: AppIcon(action.icon, fill: 1),
title: Text(action.label),
onTap: () => overlayController.pop(action.value),
);
}),
const SizedBox(height: 8),
],
),
),
);
} else {
selected = await showModalBottomSheet<String>(
context: context,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(t.common.addTo, style: Theme.of(context).textTheme.titleMedium),
),
...submenuActions.map((action) {
return ListTile(
leading: AppIcon(action.icon, fill: 1),
title: Text(action.label),
onTap: () => Navigator.pop(context, action.value),
);
}),
const SizedBox(height: 8),
],
),
),
);
}
} else {
selected = await showMenu<String>(
context: context,
position: RelativeRect.fromLTRB(
_tapPosition?.dx ?? 0,
_tapPosition?.dy ?? 0,
_tapPosition?.dx ?? 0,
_tapPosition?.dy ?? 0,
),
items: submenuActions.map((action) {
return PopupMenuItem<String>(
value: action.value,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [AppIcon(action.icon, fill: 1, size: 20), const SizedBox(width: 12), Text(action.label)],
),
);
}).toList(),
);
}
// Handle the submenu selection
if (selected == 'playlist' && context.mounted) {
@@ -1238,43 +1290,47 @@ class _FocusableContextMenuSheetState extends State<_FocusableContextMenuSheet>
@override
Widget build(BuildContext context) {
return FocusableBottomSheet(
initialFocusNode: widget.focusFirstItem ? _initialFocusNode : null,
child: SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
widget.title,
style: Theme.of(context).textTheme.titleMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
widget.title,
style: Theme.of(context).textTheme.titleMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Flexible(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...widget.actions.asMap().entries.map((entry) {
final index = entry.key;
final action = entry.value;
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
leading: AppIcon(action.icon, fill: 1),
title: Text(action.label),
onTap: () {
final controller = OverlaySheetController.maybeOf(context);
if (controller != null) {
controller.close(action.value);
} else {
Navigator.pop(context, action.value);
}
},
hoverColor: action.hoverColor,
);
}),
],
),
),
Flexible(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...widget.actions.asMap().entries.map((entry) {
final index = entry.key;
final action = entry.value;
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
leading: AppIcon(action.icon, fill: 1),
title: Text(action.label),
onTap: () => Navigator.pop(context, action.value),
hoverColor: action.hoverColor,
);
}),
],
),
),
),
],
),
),
],
),
);
}
+457
View File
@@ -0,0 +1,457 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../focus/dpad_navigator.dart';
import '../focus/input_mode_tracker.dart';
import '../focus/key_event_utils.dart';
import '../utils/platform_detector.dart';
/// Entry in the sheet page stack.
class _OverlaySheetEntry {
final WidgetBuilder builder;
final Completer<dynamic> completer;
final FocusNode? initialFocusNode;
_OverlaySheetEntry({required this.builder, required this.completer, this.initialFocusNode});
}
/// Provides [OverlaySheetController] to descendants via [of] / [maybeOf].
class _OverlaySheetScope extends InheritedWidget {
final OverlaySheetController controller;
const _OverlaySheetScope({required this.controller, required super.child});
@override
bool updateShouldNotify(_OverlaySheetScope oldWidget) => controller != oldWidget.controller;
}
/// Controller for the overlay-based bottom sheet system.
///
/// Use [of] or [maybeOf] to access from descendants.
class OverlaySheetController {
final _OverlaySheetHostState _state;
OverlaySheetController._(this._state);
static OverlaySheetController of(BuildContext context) {
final scope = context.dependOnInheritedWidgetOfExactType<_OverlaySheetScope>();
assert(scope != null, 'No OverlaySheetHost found in context');
return scope!.controller;
}
static OverlaySheetController? maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<_OverlaySheetScope>()?.controller;
}
/// Whether a sheet is currently showing (including while animating closed).
bool get isOpen => _state._isOpen;
/// Show a bottom sheet with [builder] content. Returns a Future that completes
/// when the sheet is closed (with an optional result).
Future<T?> show<T>({
required WidgetBuilder builder,
BoxConstraints? constraints,
Color? backgroundColor,
bool barrierDismissible = true,
FocusNode? initialFocusNode,
}) {
return _state._show<T>(
builder: builder,
constraints: constraints,
backgroundColor: backgroundColor,
barrierDismissible: barrierDismissible,
initialFocusNode: initialFocusNode,
);
}
/// Push a sub-page within the open sheet. Returns a Future that completes
/// when the pushed page is popped (with an optional result).
Future<T?> push<T>({required WidgetBuilder builder, FocusNode? initialFocusNode}) {
return _state._push<T>(builder: builder, initialFocusNode: initialFocusNode);
}
/// Pop the top sub-page, or close the sheet if on the last page.
void pop([dynamic result]) {
_state._pop(result);
}
/// Force close the sheet, completing all pending completers.
void close([dynamic result]) {
_state._close(result);
}
/// Re-focus the first focusable descendant within the sheet.
/// Useful after internal page changes via setState.
void refocus() {
_state._refocus();
}
}
/// Host widget for the overlay-based bottom sheet system.
///
/// Sheets are rendered as overlays within this widget's Stack instead of as
/// modal routes, eliminating the route-based back-button race condition on
/// Android TV and providing centralized focus management for keyboard/dpad
/// navigation on all platforms.
///
/// Screens that contain a [PopScope] should check [OverlaySheetController.isOpen]
/// and skip their own back handling when a sheet is open.
class OverlaySheetHost extends StatefulWidget {
final Widget child;
const OverlaySheetHost({super.key, required this.child});
@override
State<OverlaySheetHost> createState() => _OverlaySheetHostState();
}
class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerProviderStateMixin {
late final AnimationController _animationController;
late final Animation<Offset> _slideAnimation;
late final Animation<double> _barrierAnimation;
late final OverlaySheetController _controller;
final List<_OverlaySheetEntry> _pageStack = [];
final _sheetFocusScopeNode = FocusScopeNode(debugLabel: 'OverlaySheetScope');
bool _isOpen = false;
bool _isClosing = false;
bool _barrierDismissible = true;
BoxConstraints? _constraints;
Color _backgroundColor = Colors.grey[900]!;
// Drag-to-dismiss state
double _dragOffset = 0;
bool _isDragging = false;
@override
void initState() {
super.initState();
_controller = OverlaySheetController._(this);
_animationController = AnimationController(duration: const Duration(milliseconds: 250), vsync: this);
_slideAnimation = Tween<Offset>(begin: const Offset(0, 1), end: Offset.zero).animate(
CurvedAnimation(parent: _animationController, curve: Curves.easeOutCubic, reverseCurve: Curves.easeInCubic),
);
_barrierAnimation = Tween<double>(
begin: 0,
end: 0.5,
).animate(CurvedAnimation(parent: _animationController, curve: Curves.easeOutCubic));
}
@override
void dispose() {
for (final entry in _pageStack) {
if (!entry.completer.isCompleted) {
entry.completer.complete(null);
}
}
_sheetFocusScopeNode.dispose();
_animationController.dispose();
super.dispose();
}
Future<T?> _show<T>({
required WidgetBuilder builder,
BoxConstraints? constraints,
Color? backgroundColor,
bool barrierDismissible = true,
FocusNode? initialFocusNode,
}) {
// If already open, close first (instant)
if (_isOpen) {
for (final entry in _pageStack) {
if (!entry.completer.isCompleted) {
entry.completer.complete(null);
}
}
_pageStack.clear();
_isClosing = false;
}
final completer = Completer<T?>();
final entry = _OverlaySheetEntry(builder: builder, completer: completer, initialFocusNode: initialFocusNode);
setState(() {
_pageStack.add(entry);
_isOpen = true;
_isClosing = false;
_barrierDismissible = barrierDismissible;
_constraints = constraints;
if (backgroundColor != null) _backgroundColor = backgroundColor;
_dragOffset = 0;
_isDragging = false;
});
BackKeyUpSuppressor.clearSuppression();
_animationController.forward(from: 0);
_autoFocus();
return completer.future;
}
Future<T?> _push<T>({required WidgetBuilder builder, FocusNode? initialFocusNode}) {
if (!_isOpen || _isClosing) {
return Future.value(null);
}
final completer = Completer<T?>();
final entry = _OverlaySheetEntry(builder: builder, completer: completer, initialFocusNode: initialFocusNode);
setState(() {
_pageStack.add(entry);
});
_autoFocus();
return completer.future;
}
void _pop([dynamic result]) {
if (!_isOpen || _isClosing || _pageStack.isEmpty) return;
if (_pageStack.length == 1) {
_close(result);
return;
}
final removed = _pageStack.removeLast();
if (!removed.completer.isCompleted) {
removed.completer.complete(result);
}
setState(() {});
_autoFocus();
}
void _close([dynamic result]) {
if (!_isOpen || _isClosing) return;
_isClosing = true;
_animationController.reverse().then((_) {
if (!mounted) return;
setState(() {
for (final entry in _pageStack) {
if (!entry.completer.isCompleted) {
entry.completer.complete(result);
}
}
_pageStack.clear();
_isOpen = false;
_isClosing = false;
_dragOffset = 0;
_isDragging = false;
});
// Clear stale back-key flags. handleBackKeyAction sets
// markClosedViaBackKey() expecting a route pop, but the overlay
// doesn't pop a route. Without clearing, the flag leaks into the
// next real route pop and disables KeyUp suppression, causing a
// double-pop on the underlying screen.
BackKeyUpSuppressor.clearSuppression();
});
}
void _autoFocus() {
if (!InputModeTracker.isKeyboardMode(context)) return;
// First post-frame: the FocusScope is now built and the node is attached.
// Grab scope focus immediately so key events (especially back) are trapped.
// Second post-frame: ListView.builder items are laid out and their
// FocusNodes are registered — focus the first descendant for dpad nav.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_isOpen) return;
_sheetFocusScopeNode.requestFocus();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_isOpen) return;
// If the current top entry has an initialFocusNode that is attached,
// focus that instead of the first descendant.
final topEntry = _pageStack.isNotEmpty ? _pageStack.last : null;
final initialNode = topEntry?.initialFocusNode;
if (initialNode != null && initialNode.context != null) {
initialNode.requestFocus();
} else {
_focusFirstDescendant();
}
// Clear stale select suppression from the press that opened this sheet,
// but only if no select key is currently held down. This handles:
// - Short press: key already released → clear flag (prevents first
// select inside the sheet from being eaten).
// - Long press: key still held → keep flag so KeyRepeat/KeyUp events
// from the long press are correctly suppressed.
if (!HardwareKeyboard.instance.logicalKeysPressed.any((k) => k.isSelectKey)) {
SelectKeyUpSuppressor.clearSuppression();
}
});
});
}
void _refocus() {
if (!InputModeTracker.isKeyboardMode(context)) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_isOpen) return;
_sheetFocusScopeNode.requestFocus();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_isOpen) return;
final topEntry = _pageStack.isNotEmpty ? _pageStack.last : null;
final initialNode = topEntry?.initialFocusNode;
if (initialNode != null && initialNode.context != null) {
initialNode.requestFocus();
} else {
_focusFirstDescendant();
}
});
});
}
void _focusFirstDescendant() {
final descendants = _sheetFocusScopeNode.traversalDescendants.toList();
if (descendants.isNotEmpty) {
descendants.first.requestFocus();
} else {
_sheetFocusScopeNode.requestFocus();
}
}
void _handleBack() {
if (_pageStack.length > 1) {
_pop();
} else {
_close();
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
// Suppress stale select key-ups
if (SelectKeyUpSuppressor.consumeIfSuppressed(event)) {
return KeyEventResult.handled;
}
// Suppress stale back key-ups
if (BackKeyUpSuppressor.consumeIfSuppressed(event)) {
return KeyEventResult.handled;
}
// Back key: pop sub-page or close sheet
if (event.logicalKey.isBackKey) {
return handleBackKeyAction(event, _handleBack);
}
// Let all other keys pass through. Directional keys need to reach
// Flutter's DirectionalFocusAction for dpad/arrow navigation, and
// select/enter keys need to reach ActivateAction for item taps.
// The FocusScope traps traversal within the sheet; the screen-level
// Focus catches any leaked nav keys.
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
// No PopScope here — the parent screen's PopScope should check
// OverlaySheetController.isOpen and delegate to us. This avoids
// the double-callback problem with nested PopScopes in one route.
return _OverlaySheetScope(
controller: _controller,
child: Stack(
children: [
widget.child,
if (_isOpen) ...[
// Barrier
AnimatedBuilder(
animation: _barrierAnimation,
builder: (context, child) {
return GestureDetector(
onTap: _barrierDismissible ? () => _close() : null,
child: Container(color: Colors.black.withValues(alpha: _barrierAnimation.value)),
);
},
),
// Sheet
_buildSheet(context),
],
],
),
);
}
Widget _buildSheet(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
final effectiveConstraints =
_constraints ??
BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
Widget sheet = FocusScope(
node: _sheetFocusScopeNode,
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: _handleKeyEvent,
child: SlideTransition(
position: _slideAnimation,
child: Align(
alignment: Alignment.bottomCenter,
child: Transform.translate(
offset: Offset(0, _dragOffset.clamp(0, double.infinity)),
child: Material(
color: _backgroundColor,
borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
clipBehavior: Clip.antiAlias,
child: SafeArea(
top: false,
child: ConstrainedBox(
constraints: effectiveConstraints,
child: _pageStack.isNotEmpty ? _pageStack.last.builder(context) : const SizedBox.shrink(),
),
),
),
),
),
),
),
);
// Swipe-down-to-dismiss (skip on TV where there's no touchscreen)
if (!PlatformDetector.isTV()) {
sheet = GestureDetector(
onVerticalDragStart: (_) {
_isDragging = true;
_dragOffset = 0;
},
onVerticalDragUpdate: (details) {
if (!_isDragging) return;
setState(() {
_dragOffset += details.delta.dy;
});
},
onVerticalDragEnd: (details) {
if (!_isDragging) return;
_isDragging = false;
final sheetHeight = effectiveConstraints.minHeight;
final velocity = details.primaryVelocity ?? 0;
if (_dragOffset > sheetHeight * 0.25 || velocity > 500) {
_close();
} else {
setState(() {
_dragOffset = 0;
});
}
},
child: sheet,
);
}
return sheet;
}
}
+46 -15
View File
@@ -1,4 +1,5 @@
import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:plezy/widgets/app_icon.dart';
import 'package:material_symbols_icons/symbols.dart';
@@ -7,6 +8,32 @@ import '../../services/plex_client.dart';
import '../utils/plex_image_helper.dart';
import 'media_card.dart';
/// Set to `true` to blur all artwork (for store screenshots).
const kBlurArtwork = false;
/// Wraps [child] with a blur filter when [kBlurArtwork] is `true`.
/// Rotates vowels (a→e, e→i, i→o, o→u, u→a) when [kBlurArtwork] is `true`.
String obfuscateText(String text) {
if (!kBlurArtwork) return text;
const from = 'aeiouAEIOU';
const to = 'eiouaEIOUA';
final buf = StringBuffer();
for (var i = 0; i < text.length; i++) {
final idx = from.indexOf(text[i]);
buf.write(idx >= 0 ? to[idx] : text[i]);
}
return buf.toString();
}
Widget blurArtwork(Widget child, {double sigma = 30, bool clip = true}) {
if (!kBlurArtwork) return child;
final filtered = ImageFiltered(
imageFilter: ImageFilter.blur(sigmaX: sigma, sigmaY: sigma),
child: child,
);
return clip ? ClipRect(child: filtered) : filtered;
}
class PlexOptimizedImage extends StatelessWidget {
final PlexClient? client;
final String? imagePath;
@@ -230,14 +257,16 @@ class PlexOptimizedImage extends StatelessWidget {
if (localFilePath != null) {
final file = File(localFilePath!);
if (file.existsSync()) {
return Image.file(
file,
width: width,
height: height,
fit: fit,
filterQuality: filterQuality,
alignment: alignment,
errorBuilder: (context, error, stackTrace) => _buildErrorWidget(context, error),
return blurArtwork(
Image.file(
file,
width: width,
height: height,
fit: fit,
filterQuality: filterQuality,
alignment: alignment,
errorBuilder: (context, error, stackTrace) => _buildErrorWidget(context, error),
),
);
}
}
@@ -249,15 +278,17 @@ class PlexOptimizedImage extends StatelessWidget {
// Fast path: skip LayoutBuilder when both dimensions are explicitly known
if (_hasKnownDimensions) {
return _buildCachedImage(context, width!, height!);
return blurArtwork(_buildCachedImage(context, width!, height!));
}
return LayoutBuilder(
builder: (context, constraints) {
final effectiveWidth = _resolvedDimension(width, constraints.maxWidth, 300.0);
final effectiveHeight = _resolvedDimension(height, constraints.maxHeight, 450.0);
return _buildCachedImage(context, effectiveWidth, effectiveHeight);
},
return blurArtwork(
LayoutBuilder(
builder: (context, constraints) {
final effectiveWidth = _resolvedDimension(width, constraints.maxWidth, 300.0);
final effectiveHeight = _resolvedDimension(height, constraints.maxHeight, 450.0);
return _buildCachedImage(context, effectiveWidth, effectiveHeight);
},
),
);
}
+60 -1
View File
@@ -76,6 +76,7 @@ class NavigationRailItem extends StatelessWidget {
child: Material(
color: Colors.transparent,
child: InkWell(
canRequestFocus: false,
onTap: onTap,
borderRadius: borderRadius,
child: Container(
@@ -256,10 +257,59 @@ class SideNavigationRailState extends State<SideNavigationRail> {
_kDownloads,
_kSettings,
_kReconnect,
'liveTv',
...libraries.map((lib) => lib.globalKey),
};
}
/// Ordered list of focusable keys matching visual top-to-bottom order.
List<String> _buildFocusOrder(List<PlexLibrary> visibleLibraries, {required bool hasLiveTv}) {
return [
if (widget.isOfflineMode && widget.onReconnect != null) _kReconnect,
if (!widget.isOfflineMode) ...[
_kHome,
_kLibraries,
if (_librariesExpanded) ...visibleLibraries.map((lib) => lib.globalKey),
if (hasLiveTv) 'liveTv',
_kSearch,
],
_kDownloads,
_kSettings,
];
}
/// Handle D-pad UP/DOWN by explicitly moving focus to the next/previous item.
KeyEventResult _handleVerticalNavigation(FocusNode node, KeyEvent event, List<String> focusOrder) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
final isDown = event.logicalKey == LogicalKeyboardKey.arrowDown;
final isUp = event.logicalKey == LogicalKeyboardKey.arrowUp;
if (!isDown && !isUp) return KeyEventResult.ignored;
final currentKey = _focusTracker.lastFocusedKey;
if (currentKey == null) return KeyEventResult.ignored;
final currentIndex = focusOrder.indexOf(currentKey);
if (currentIndex == -1) return KeyEventResult.ignored;
final nextIndex = isDown ? currentIndex + 1 : currentIndex - 1;
if (nextIndex < 0 || nextIndex >= focusOrder.length) return KeyEventResult.handled;
final nextNode = _focusTracker.nodeFor(focusOrder[nextIndex]);
if (nextNode == null) return KeyEventResult.ignored;
nextNode.requestFocus();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final ctx = nextNode.context;
if (ctx != null) {
Scrollable.ensureVisible(ctx,
alignment: 0.5, duration: const Duration(milliseconds: 200));
}
});
return KeyEventResult.handled;
}
/// Collapse the sidebar (resets touch-expand state).
void collapse() {
if (_isTouchExpanded) {
@@ -319,6 +369,8 @@ class SideNavigationRailState extends State<SideNavigationRail> {
_focusTracker.pruneExcept(_buildValidFocusKeys(allLibraries));
final isCollapsed = !_shouldExpand;
final hasLiveTv = context.watch<MultiServerProvider>().hasLiveTv;
final focusOrder = _buildFocusOrder(visibleLibraries, hasLiveTv: hasLiveTv);
// Listen to fullscreen changes for macOS
return ListenableBuilder(
@@ -344,7 +396,12 @@ class SideNavigationRailState extends State<SideNavigationRail> {
decoration: BoxDecoration(color: t.surface),
child: IgnorePointer(
ignoring: isCollapsed,
child: Column(
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: (node, event) =>
_handleVerticalNavigation(node, event, focusOrder),
child: Column(
children: [
// Safe area for status bar and macOS traffic lights
SizedBox(height: _getTopPadding(context)),
@@ -497,6 +554,7 @@ class SideNavigationRailState extends State<SideNavigationRail> {
),
],
),
),
),
),
),
@@ -596,6 +654,7 @@ class SideNavigationRailState extends State<SideNavigationRail> {
child: Material(
color: Colors.transparent,
child: InkWell(
canRequestFocus: false,
onTap: () {
setState(() {
_librariesExpanded = !_librariesExpanded;
@@ -89,6 +89,12 @@ class DesktopVideoControls extends StatefulWidget {
/// Channel name for live TV display
final String? liveChannelName;
/// Whether ambient lighting is enabled (passed to settings sheet)
final bool isAmbientLightingEnabled;
/// Called to toggle ambient lighting (passed to settings sheet)
final VoidCallback? onToggleAmbientLighting;
const DesktopVideoControls({
super.key,
required this.player,
@@ -135,6 +141,8 @@ class DesktopVideoControls extends StatefulWidget {
this.thumbnailUrlBuilder,
this.isLive = false,
this.liveChannelName,
this.isAmbientLightingEnabled = false,
this.onToggleAmbientLighting,
});
@override
@@ -680,6 +688,8 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
isLive: widget.isLive,
shaderService: widget.shaderService,
onShaderChanged: widget.onShaderChanged,
isAmbientLightingEnabled: widget.isAmbientLightingEnabled,
onToggleAmbientLighting: widget.onToggleAmbientLighting,
),
],
),
@@ -7,16 +7,19 @@ import '../../../utils/track_label_builder.dart';
import 'track_selection_sheet.dart';
/// Bottom sheet for selecting audio tracks
class AudioTrackSheet {
static void show(
BuildContext context,
Player player, {
Function(AudioTrack)? onTrackChanged,
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
TrackSelectionSheet.show<AudioTrack>(
context: context,
class AudioTrackSheet extends StatelessWidget {
final Player player;
final Function(AudioTrack)? onTrackChanged;
const AudioTrackSheet({
super.key,
required this.player,
this.onTrackChanged,
});
@override
Widget build(BuildContext context) {
return TrackSelectionSheet<AudioTrack>(
player: player,
title: t.videoControls.audioLabel,
icon: Symbols.audiotrack_rounded,
@@ -31,8 +34,6 @@ class AudioTrackSheet {
),
setTrack: (track) => player.selectAudioTrack(track),
onTrackChanged: onTrackChanged,
onOpen: onOpen,
onClose: onClose,
);
}
}
@@ -1,4 +1,7 @@
import 'package:flutter/material.dart';
import '../../../focus/key_event_utils.dart';
import '../../../focus/dpad_navigator.dart';
import 'video_sheet_header.dart';
/// Base class for video control bottom sheets providing common UI structure
@@ -18,50 +21,34 @@ class BaseVideoControlSheet extends StatelessWidget {
this.onBack,
});
/// Get consistent bottom sheet constraints across all video control sheets
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
/// Helper method to show a modal bottom sheet with consistent styling
static Future<T?> showSheet<T>({
required BuildContext context,
required WidgetBuilder builder,
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
onOpen?.call();
return showModalBottomSheet<T>(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: builder,
).whenComplete(() {
onClose?.call();
});
}
@override
Widget build(BuildContext context) {
Widget content = Column(
children: [
VideoSheetHeader(title: title, icon: icon, iconColor: iconColor, onBack: onBack),
const Divider(color: Colors.white24, height: 1),
Expanded(child: child),
],
);
// Intercept back key at the sub-page level so it triggers onBack
// instead of bubbling up to OverlaySheetHost which would close the sheet.
if (onBack != null) {
content = Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: (node, event) {
if (event.logicalKey.isBackKey) {
return handleBackKeyAction(event, onBack!);
}
return KeyEventResult.ignored;
},
child: content,
);
}
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
VideoSheetHeader(title: title, icon: icon, iconColor: iconColor, onBack: onBack),
const Divider(color: Colors.white24, height: 1),
Expanded(child: child),
],
),
),
child: SizedBox(height: MediaQuery.of(context).size.height * 0.75, child: content),
);
}
}
@@ -9,10 +9,9 @@ import '../../../services/download_storage_service.dart';
import '../../../models/plex_media_info.dart';
import '../../../utils/formatters.dart';
import '../../../utils/provider_extensions.dart';
import '../../../widgets/focusable_bottom_sheet.dart';
import '../../../widgets/focusable_list_tile.dart';
import '../../../widgets/overlay_sheet.dart';
import 'base_video_control_sheet.dart';
import 'video_control_sheet_launcher.dart';
import '../../plex_optimized_image.dart';
/// Bottom sheet for selecting chapters
@@ -30,42 +29,11 @@ class ChapterSheet extends StatefulWidget {
this.serverId,
});
static void show(
BuildContext context,
Player player,
List<PlexChapter> chapters,
bool chaptersLoaded, {
String? serverId,
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
VideoControlSheetLauncher.show(
context: context,
onOpen: onOpen,
onClose: onClose,
builder: (context) =>
ChapterSheet(player: player, chapters: chapters, chaptersLoaded: chaptersLoaded, serverId: serverId),
);
}
@override
State<ChapterSheet> createState() => _ChapterSheetState();
}
class _ChapterSheetState extends State<ChapterSheet> {
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_initialFocusNode = FocusNode(debugLabel: 'ChapterSheetInitialFocus');
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
/// Get the PlexClient for chapters, or null if unavailable (offline mode)
PlexClient? _tryGetClientForChapters(BuildContext context) {
@@ -79,9 +47,7 @@ class _ChapterSheetState extends State<ChapterSheet> {
@override
Widget build(BuildContext context) {
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: StreamBuilder<Duration>(
return StreamBuilder<Duration>(
stream: widget.player.streams.position,
initialData: widget.player.state.position,
builder: (context, positionSnapshot) {
@@ -125,7 +91,6 @@ class _ChapterSheetState extends State<ChapterSheet> {
: null;
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
leading: chapter.thumb != null
? Stack(
children: [
@@ -173,7 +138,7 @@ class _ChapterSheetState extends State<ChapterSheet> {
: null,
onTap: () {
widget.player.seek(chapter.startTime);
Navigator.pop(context);
OverlaySheetController.of(context).close();
},
);
},
@@ -186,7 +151,6 @@ class _ChapterSheetState extends State<ChapterSheet> {
child: content,
);
},
),
);
);
}
}
@@ -7,16 +7,19 @@ import '../../../utils/track_label_builder.dart';
import 'track_selection_sheet.dart';
/// Bottom sheet for selecting subtitle tracks
class SubtitleTrackSheet {
static void show(
BuildContext context,
Player player, {
Function(SubtitleTrack)? onTrackChanged,
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
TrackSelectionSheet.show<SubtitleTrack>(
context: context,
class SubtitleTrackSheet extends StatelessWidget {
final Player player;
final Function(SubtitleTrack)? onTrackChanged;
const SubtitleTrackSheet({
super.key,
required this.player,
this.onTrackChanged,
});
@override
Widget build(BuildContext context) {
return TrackSelectionSheet<SubtitleTrack>(
player: player,
title: t.videoControls.subtitlesLabel,
icon: Symbols.subtitles_rounded,
@@ -33,8 +36,6 @@ class SubtitleTrackSheet {
showOffOption: true,
createOffTrack: () => SubtitleTrack.off,
isOffTrack: (track) => track.id == 'no',
onOpen: onOpen,
onClose: onClose,
);
}
}
@@ -1,9 +1,8 @@
import 'package:flutter/material.dart';
import '../../../mpv/mpv.dart';
import '../../../widgets/focusable_bottom_sheet.dart';
import '../../../widgets/overlay_sheet.dart';
import 'base_video_control_sheet.dart';
import 'video_control_sheet_launcher.dart';
import '../helpers/track_filter_helper.dart';
import '../helpers/track_selection_helper.dart';
@@ -38,79 +37,26 @@ class TrackSelectionSheet<T> extends StatefulWidget {
this.isOffTrack,
});
static void show<T>({
required BuildContext context,
required Player player,
required String title,
required IconData icon,
required List<T> Function(Tracks?) extractTracks,
required T? Function(TrackSelection) getCurrentTrack,
required String Function(T track, int index) buildLabel,
required void Function(T track) setTrack,
Function(T)? onTrackChanged,
bool showOffOption = false,
T Function()? createOffTrack,
bool Function(T track)? isOffTrack,
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
VideoControlSheetLauncher.show(
context: context,
onOpen: onOpen,
onClose: onClose,
builder: (context) => TrackSelectionSheet<T>(
player: player,
title: title,
icon: icon,
extractTracks: extractTracks,
getCurrentTrack: getCurrentTrack,
buildLabel: buildLabel,
setTrack: setTrack,
onTrackChanged: onTrackChanged,
showOffOption: showOffOption,
createOffTrack: createOffTrack,
isOffTrack: isOffTrack,
),
);
}
@override
State<TrackSelectionSheet<T>> createState() => _TrackSelectionSheetState<T>();
}
class _TrackSelectionSheetState<T> extends State<TrackSelectionSheet<T>> {
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_initialFocusNode = FocusNode(debugLabel: 'TrackSelectionInitialFocus');
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: StreamBuilder<Tracks>(
stream: widget.player.streams.tracks,
initialData: widget.player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final availableTracks = TrackFilterHelper.extractAndFilterTracks<T>(tracks, widget.extractTracks);
return StreamBuilder<Tracks>(
stream: widget.player.streams.tracks,
initialData: widget.player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final availableTracks = TrackFilterHelper.extractAndFilterTracks<T>(tracks, widget.extractTracks);
final sheetChild = availableTracks.isEmpty
? TrackSelectionHelper.buildEmptyState<T>()
: _buildTrackList(availableTracks);
final sheetChild = availableTracks.isEmpty
? TrackSelectionHelper.buildEmptyState<T>()
: _buildTrackList(availableTracks);
return BaseVideoControlSheet(title: widget.title, icon: widget.icon, child: sheetChild);
},
),
return BaseVideoControlSheet(title: widget.title, icon: widget.icon, child: sheetChild);
},
);
}
@@ -135,16 +81,13 @@ class _TrackSelectionSheetState<T> extends State<TrackSelectionSheet<T>> {
final track = availableTracks[trackIndex];
final trackId = TrackSelectionHelper.getTrackId(track);
final selectedId = selectedTrack == null ? '' : TrackSelectionHelper.getTrackId(selectedTrack);
final shouldFocus = !widget.showOffOption && index == 0;
return TrackSelectionHelper.buildTrackTile<T>(
label: widget.buildLabel(track, trackIndex),
isSelected: trackId == selectedId,
focusNode: shouldFocus ? _initialFocusNode : null,
onTap: () {
widget.setTrack(track);
widget.onTrackChanged?.call(track);
Navigator.pop(context);
OverlaySheetController.of(context).close();
},
);
},
@@ -156,14 +99,13 @@ class _TrackSelectionSheetState<T> extends State<TrackSelectionSheet<T>> {
Widget _buildOffTile(bool isOffSelected) {
return TrackSelectionHelper.buildOffTile<T>(
isSelected: isOffSelected,
focusNode: _initialFocusNode,
onTap: () {
if (widget.createOffTrack != null) {
final offTrack = widget.createOffTrack!();
widget.setTrack(offTrack);
widget.onTrackChanged?.call(offTrack);
}
Navigator.pop(context);
OverlaySheetController.of(context).close();
},
);
}
@@ -2,10 +2,9 @@ import 'package:flutter/material.dart';
import 'package:plezy/widgets/app_icon.dart';
import 'package:material_symbols_icons/symbols.dart';
import '../../../models/plex_media_version.dart';
import '../../../widgets/focusable_bottom_sheet.dart';
import '../../../widgets/focusable_list_tile.dart';
import '../../../widgets/overlay_sheet.dart';
import 'base_video_control_sheet.dart';
import 'video_control_sheet_launcher.dart';
/// Bottom sheet for selecting video version
class VersionSheet extends StatefulWidget {
@@ -20,69 +19,31 @@ class VersionSheet extends StatefulWidget {
required this.onVersionSelected,
});
static void show(
BuildContext context,
List<PlexMediaVersion> availableVersions,
int selectedMediaIndex,
Function(int) onVersionSelected, {
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
VideoControlSheetLauncher.show(
context: context,
onOpen: onOpen,
onClose: onClose,
builder: (context) => VersionSheet(
availableVersions: availableVersions,
selectedMediaIndex: selectedMediaIndex,
onVersionSelected: onVersionSelected,
),
);
}
@override
State<VersionSheet> createState() => _VersionSheetState();
}
class _VersionSheetState extends State<VersionSheet> {
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_initialFocusNode = FocusNode(debugLabel: 'VersionSheetInitialFocus');
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: BaseVideoControlSheet(
title: 'Video Version',
icon: Symbols.video_file_rounded,
child: ListView.builder(
itemCount: widget.availableVersions.length,
itemBuilder: (context, index) {
final version = widget.availableVersions[index];
final isSelected = index == widget.selectedMediaIndex;
return BaseVideoControlSheet(
title: 'Video Version',
icon: Symbols.video_file_rounded,
child: ListView.builder(
itemCount: widget.availableVersions.length,
itemBuilder: (context, index) {
final version = widget.availableVersions[index];
final isSelected = index == widget.selectedMediaIndex;
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
title: Text(version.displayLabel, style: TextStyle(color: isSelected ? Colors.blue : Colors.white)),
trailing: isSelected ? const AppIcon(Symbols.check_rounded, fill: 1, color: Colors.blue) : null,
onTap: () {
Navigator.pop(context);
widget.onVersionSelected(index);
},
);
},
),
return FocusableListTile(
title: Text(version.displayLabel, style: TextStyle(color: isSelected ? Colors.blue : Colors.white)),
trailing: isSelected ? const AppIcon(Symbols.check_rounded, fill: 1, color: Colors.blue) : null,
onTap: () {
OverlaySheetController.of(context).close();
widget.onVersionSelected(index);
},
);
},
),
);
}
@@ -1,17 +0,0 @@
import 'package:flutter/material.dart';
import 'base_video_control_sheet.dart';
/// Helper class to launch video control sheets with consistent behavior
///
/// This eliminates the need for each sheet to duplicate the showSheet wrapper.
class VideoControlSheetLauncher {
/// Show a video control sheet with consistent styling and callbacks
static Future<T?> show<T>({
required BuildContext context,
required WidgetBuilder builder,
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
return BaseVideoControlSheet.showSheet<T>(context: context, onOpen: onOpen, onClose: onClose, builder: builder);
}
}
@@ -14,8 +14,8 @@ import '../../../services/shader_service.dart';
import '../../../services/sleep_timer_service.dart';
import '../../../utils/formatters.dart';
import '../../../utils/platform_detector.dart';
import '../../../widgets/focusable_bottom_sheet.dart';
import '../../../widgets/focusable_list_tile.dart';
import '../../../widgets/overlay_sheet.dart';
import '../widgets/sync_offset_control.dart';
import '../widgets/sleep_timer_content.dart';
import '../../../i18n/strings.g.dart';
@@ -31,7 +31,6 @@ class _SettingsMenuItem extends StatelessWidget {
final VoidCallback onTap;
final bool isHighlighted;
final bool allowValueOverflow;
final FocusNode? focusNode;
const _SettingsMenuItem({
required this.icon,
@@ -40,7 +39,6 @@ class _SettingsMenuItem extends StatelessWidget {
required this.onTap,
this.isHighlighted = false,
this.allowValueOverflow = false,
this.focusNode,
});
@override
@@ -52,7 +50,6 @@ class _SettingsMenuItem extends StatelessWidget {
);
return FocusableListTile(
focusNode: focusNode,
leading: AppIcon(icon, fill: 1, color: isHighlighted ? Colors.amber : Colors.white70),
title: Text(title, style: const TextStyle(color: Colors.white)),
trailing: Row(
@@ -86,6 +83,12 @@ class VideoSettingsSheet extends StatefulWidget {
/// Called when shader preset changes
final VoidCallback? onShaderChanged;
/// Whether ambient lighting is currently enabled
final bool isAmbientLightingEnabled;
/// Called to toggle ambient lighting on/off (null if unsupported)
final VoidCallback? onToggleAmbientLighting;
const VideoSettingsSheet({
super.key,
required this.player,
@@ -95,36 +98,10 @@ class VideoSettingsSheet extends StatefulWidget {
this.isLive = false,
this.shaderService,
this.onShaderChanged,
this.isAmbientLightingEnabled = false,
this.onToggleAmbientLighting,
});
static Future<void> show(
BuildContext context,
Player player,
int audioSyncOffset,
int subtitleSyncOffset, {
VoidCallback? onOpen,
VoidCallback? onClose,
bool canControl = true,
bool isLive = false,
ShaderService? shaderService,
VoidCallback? onShaderChanged,
}) {
return BaseVideoControlSheet.showSheet(
context: context,
onOpen: onOpen,
onClose: onClose,
builder: (context) => VideoSettingsSheet(
player: player,
audioSyncOffset: audioSyncOffset,
subtitleSyncOffset: subtitleSyncOffset,
canControl: canControl,
isLive: isLive,
shaderService: shaderService,
onShaderChanged: onShaderChanged,
),
);
}
@override
State<VideoSettingsSheet> createState() => _VideoSettingsSheetState();
}
@@ -136,23 +113,15 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
bool _enableHDR = true;
bool _showPerformanceOverlay = false;
bool _autoPlayNextEpisode = true;
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_audioSyncOffset = widget.audioSyncOffset;
_subtitleSyncOffset = widget.subtitleSyncOffset;
_initialFocusNode = FocusNode(debugLabel: 'VideoSettingsInitialFocus');
_loadSettings();
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
Future<void> _loadSettings() async {
final settings = await SettingsService.getInstance();
if (!mounted) return;
@@ -199,12 +168,14 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
setState(() {
_currentView = view;
});
OverlaySheetController.maybeOf(context)?.refocus();
}
void _navigateBack() {
setState(() {
_currentView = _SettingsView.menu;
});
OverlaySheetController.maybeOf(context)?.refocus();
}
String _getTitle() {
@@ -271,7 +242,6 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
builder: (context, snapshot) {
final currentRate = snapshot.data ?? 1.0;
return _SettingsMenuItem(
focusNode: _initialFocusNode,
icon: Symbols.speed_rounded,
title: t.videoSettings.playbackSpeed,
valueText: _formatSpeed(currentRate),
@@ -347,7 +317,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
final currentDevice = snapshot.data ?? widget.player.state.audioDevice;
final deviceLabel = currentDevice.description.isEmpty
? currentDevice.name
: '${currentDevice.name} · ${currentDevice.description}';
: currentDevice.description;
return _SettingsMenuItem(
icon: Symbols.speaker_rounded,
@@ -369,6 +339,29 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
onTap: () => _navigateTo(_SettingsView.shader),
),
// Ambient Lighting (MPV only)
if (widget.onToggleAmbientLighting != null)
ListTile(
leading: AppIcon(
Symbols.blur_on,
fill: 1,
color: widget.isAmbientLightingEnabled ? Colors.amber : Colors.white70,
),
title: Text(t.videoControls.ambientLighting, style: const TextStyle(color: Colors.white)),
trailing: Switch(
value: widget.isAmbientLightingEnabled,
onChanged: (_) {
widget.onToggleAmbientLighting?.call();
OverlaySheetController.of(context).close();
},
activeThumbColor: Colors.amber,
),
onTap: () {
widget.onToggleAmbientLighting?.call();
OverlaySheetController.of(context).close();
},
),
// Performance Overlay Toggle
ListTile(
leading: AppIcon(
@@ -412,7 +405,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
final settings = await SettingsService.getInstance();
await settings.setDefaultPlaybackSpeed(speed);
if (context.mounted) {
Navigator.pop(context); // Close sheet after selection
OverlaySheetController.of(context).close(); // Close sheet after selection
}
},
);
@@ -425,7 +418,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
Widget _buildSleepView() {
final sleepTimer = SleepTimerService();
return SleepTimerContent(player: widget.player, sleepTimer: sleepTimer, onCancel: () => Navigator.pop(context));
return SleepTimerContent(player: widget.player, sleepTimer: sleepTimer, onCancel: () => OverlaySheetController.of(context).close());
}
Widget _buildAudioSyncView() {
@@ -462,6 +455,27 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
);
}
/// Extract the audio backend name from a device name (e.g. "coreaudio" from "coreaudio/BuiltIn").
static String _audioBackend(String name) {
final slash = name.indexOf('/');
return slash > 0 ? name.substring(0, slash) : name;
}
/// Pretty-print a backend identifier.
static String _formatBackend(String backend) {
const labels = {
'coreaudio': 'CoreAudio',
'avfoundation': 'AVFoundation',
'wasapi': 'WASAPI',
'pulse': 'PulseAudio',
'pipewire': 'PipeWire',
'alsa': 'ALSA',
'jack': 'JACK',
'oss': 'OSS',
};
return labels[backend] ?? backend;
}
Widget _buildAudioDeviceView() {
return StreamBuilder<List<AudioDevice>>(
stream: widget.player.streams.audioDevices,
@@ -475,22 +489,44 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
builder: (context, selectedSnapshot) {
final currentDevice = selectedSnapshot.data ?? widget.player.state.audioDevice;
return ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) {
final device = devices[index];
final isSelected = device.name == currentDevice.name;
final label = device.description.isEmpty ? device.name : device.description;
// Check for duplicate descriptions (same physical device across multiple backends).
final descCounts = <String, int>{};
for (final d in devices) {
final desc = d.description.isEmpty ? d.name : d.description;
descCounts[desc] = (descCounts[desc] ?? 0) + 1;
}
final hasDuplicates = descCounts.values.any((c) => c > 1);
return ListTile(
title: Text(label, style: TextStyle(color: isSelected ? Colors.blue : Colors.white)),
trailing: isSelected ? const AppIcon(Symbols.check_rounded, fill: 1, color: Colors.blue) : null,
onTap: () {
widget.player.setAudioDevice(device);
Navigator.pop(context); // Close sheet after selection
},
);
},
if (!hasDuplicates) {
return _buildFlatDeviceList(devices, currentDevice);
}
// Group devices by backend, keeping "auto" at the top ungrouped.
final ungrouped = <AudioDevice>[];
final groups = <String, List<AudioDevice>>{};
for (final d in devices) {
final backend = _audioBackend(d.name);
if (!d.name.contains('/')) {
ungrouped.add(d);
} else {
(groups[backend] ??= []).add(d);
}
}
return ListView(
children: [
for (final d in ungrouped) _buildDeviceTile(d, currentDevice),
for (final entry in groups.entries) ...[
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Text(
_formatBackend(entry.key),
style: TextStyle(color: Colors.white.withValues(alpha: 0.5), fontSize: 12, fontWeight: FontWeight.w600),
),
),
for (final d in entry.value) _buildDeviceTile(d, currentDevice),
],
],
);
},
);
@@ -498,6 +534,27 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
);
}
Widget _buildFlatDeviceList(List<AudioDevice> devices, AudioDevice currentDevice) {
return ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) => _buildDeviceTile(devices[index], currentDevice),
);
}
Widget _buildDeviceTile(AudioDevice device, AudioDevice currentDevice) {
final isSelected = device.name == currentDevice.name;
final label = device.description.isEmpty ? device.name : device.description;
return ListTile(
title: Text(label, style: TextStyle(color: isSelected ? Colors.blue : Colors.white)),
trailing: isSelected ? const AppIcon(Symbols.check_rounded, fill: 1, color: Colors.blue) : null,
onTap: () {
widget.player.setAudioDevice(device);
OverlaySheetController.of(context).close();
},
);
}
Widget _buildShaderView() {
if (widget.shaderService == null) return const SizedBox.shrink();
@@ -522,7 +579,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
await widget.shaderService!.applyPreset(preset);
await shaderProvider.setPreset(preset);
widget.onShaderChanged?.call();
if (context.mounted) Navigator.pop(context);
if (context.mounted) OverlaySheetController.of(context).close();
},
);
},
@@ -557,36 +614,33 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
_currentView == _SettingsView.menu &&
(sleepTimer.isActive || _audioSyncOffset != 0 || _subtitleSyncOffset != 0 || isShaderActive);
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: BaseVideoControlSheet(
title: _getTitle(),
icon: _getIcon(),
iconColor: () {
if (isIconActive) return Colors.amber;
if (_currentView == _SettingsView.shader && isShaderActive) return Colors.amber;
return Colors.white;
}(),
onBack: _currentView != _SettingsView.menu ? _navigateBack : null,
child: () {
switch (_currentView) {
case _SettingsView.menu:
return _buildMenuView();
case _SettingsView.speed:
return _buildSpeedView();
case _SettingsView.sleep:
return _buildSleepView();
case _SettingsView.audioSync:
return _buildAudioSyncView();
case _SettingsView.subtitleSync:
return _buildSubtitleSyncView();
case _SettingsView.audioDevice:
return _buildAudioDeviceView();
case _SettingsView.shader:
return _buildShaderView();
}
}(),
),
return BaseVideoControlSheet(
title: _getTitle(),
icon: _getIcon(),
iconColor: () {
if (isIconActive) return Colors.amber;
if (_currentView == _SettingsView.shader && isShaderActive) return Colors.amber;
return Colors.white;
}(),
onBack: _currentView != _SettingsView.menu ? _navigateBack : null,
child: () {
switch (_currentView) {
case _SettingsView.menu:
return _buildMenuView();
case _SettingsView.speed:
return _buildSpeedView();
case _SettingsView.sleep:
return _buildSleepView();
case _SettingsView.audioSync:
return _buildAudioSyncView();
case _SettingsView.subtitleSync:
return _buildSubtitleSyncView();
case _SettingsView.audioDevice:
return _buildAudioDeviceView();
case _SettingsView.shader:
return _buildShaderView();
}
}(),
);
}
}
@@ -21,6 +21,7 @@ import '../../services/pip_service.dart';
import 'package:window_manager/window_manager.dart';
import '../../mpv/mpv.dart';
import '../overlay_sheet.dart';
import '../../focus/dpad_navigator.dart';
import '../../focus/focusable_wrapper.dart';
@@ -77,6 +78,8 @@ Widget plexVideoControlsBuilder(
String Function(Duration time)? thumbnailUrlBuilder,
bool isLive = false,
String? liveChannelName,
bool isAmbientLightingEnabled = false,
VoidCallback? onToggleAmbientLighting,
}) {
return PlexVideoControls(
player: player,
@@ -101,6 +104,8 @@ Widget plexVideoControlsBuilder(
thumbnailUrlBuilder: thumbnailUrlBuilder,
isLive: isLive,
liveChannelName: liveChannelName,
isAmbientLightingEnabled: isAmbientLightingEnabled,
onToggleAmbientLighting: onToggleAmbientLighting,
);
}
@@ -150,6 +155,12 @@ class PlexVideoControls extends StatefulWidget {
/// Channel name for live TV display
final String? liveChannelName;
/// Whether ambient lighting is enabled (passed to settings sheet)
final bool isAmbientLightingEnabled;
/// Called to toggle ambient lighting (passed to settings sheet)
final VoidCallback? onToggleAmbientLighting;
const PlexVideoControls({
super.key,
required this.player,
@@ -174,6 +185,8 @@ class PlexVideoControls extends StatefulWidget {
this.thumbnailUrlBuilder,
this.isLive = false,
this.liveChannelName,
this.isAmbientLightingEnabled = false,
this.onToggleAmbientLighting,
});
@override
@@ -905,6 +918,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
isLive: widget.isLive,
shaderService: widget.shaderService,
onShaderChanged: widget.onShaderChanged,
isAmbientLightingEnabled: widget.isAmbientLightingEnabled,
onToggleAmbientLighting: widget.player.playerType != 'exoplayer' ? widget.onToggleAmbientLighting : null,
);
}
@@ -1351,6 +1366,11 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
// TV back key fallback — Focus.onKeyEvent won't fire if _focusNode lost focus
if (PlatformDetector.isTV() && event.logicalKey.isBackKey) {
if (!_focusNode.hasFocus) {
// Skip if an overlay sheet is open — the sheet's FocusScope handles
// back keys via its own onKeyEvent. Without this check, this global
// handler would call Navigator.pop() alongside the sheet's handler.
final sheetOpen = OverlaySheetController.maybeOf(context)?.isOpen ?? false;
if (sheetOpen) return false;
final backResult = handleBackKeyAction(event, () {
if (!_showControls) {
_showControlsWithFocus();
@@ -1895,6 +1915,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
thumbnailUrlBuilder: widget.thumbnailUrlBuilder,
isLive: widget.isLive,
liveChannelName: widget.liveChannelName,
isAmbientLightingEnabled: widget.isAmbientLightingEnabled,
onToggleAmbientLighting: widget.player.playerType != 'exoplayer' ? widget.onToggleAmbientLighting : null,
),
);
}
@@ -6,6 +6,7 @@ import '../../../mpv/mpv.dart';
import '../../../services/sleep_timer_service.dart';
import '../../../utils/formatters.dart';
import '../../../utils/snackbar_helper.dart';
import '../../../widgets/overlay_sheet.dart';
import '../../../i18n/strings.g.dart';
/// Widget displaying list of sleep timer durations for selection
@@ -45,7 +46,12 @@ class SleepTimerDurationList extends StatelessWidget {
// Pause playback when timer completes
player.pause();
});
Navigator.pop(context);
final sheetController = OverlaySheetController.maybeOf(context);
if (sheetController != null) {
sheetController.close();
} else {
Navigator.pop(context);
}
// Show confirmation snackbar
showSuccessSnackBar(context, t.messages.sleepTimerSet(label: label));
@@ -7,6 +7,7 @@ import '../../../i18n/strings.g.dart';
import '../../../focus/focusable_wrapper.dart';
import '../../../utils/formatters.dart';
import '../painters/chapter_marker_painter.dart';
import '../../plex_optimized_image.dart' show blurArtwork;
/// Timeline slider with chapter markers for video playback
///
@@ -125,13 +126,13 @@ class _TimelineSliderState extends State<TimelineSlider> {
boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.5), blurRadius: 8, spreadRadius: 1)],
),
clipBehavior: Clip.antiAlias,
child: CachedNetworkImage(
child: blurArtwork(CachedNetworkImage(
imageUrl: thumbnailUrl,
fit: BoxFit.cover,
fadeInDuration: Duration.zero,
placeholder: (_, _) => const SizedBox.shrink(), // Show nothing for placeholder
errorWidget: (_, _, _) => const SizedBox.shrink(), // Show nothing for errors
),
)),
),
if (hasThumbnail) const SizedBox(height: 4),
Container(
@@ -11,6 +11,7 @@ import '../../../models/plex_media_version.dart';
import '../../../services/sleep_timer_service.dart';
import '../../../utils/platform_detector.dart';
import '../../../i18n/strings.g.dart';
import '../../../widgets/overlay_sheet.dart';
import '../sheets/audio_track_sheet.dart';
import '../sheets/chapter_sheet.dart';
import '../sheets/subtitle_track_sheet.dart';
@@ -48,6 +49,12 @@ class TrackChapterControls extends StatelessWidget {
final ShaderService? shaderService;
final VoidCallback? onShaderChanged;
/// Whether ambient lighting is enabled (passed to settings sheet)
final bool isAmbientLightingEnabled;
/// Called to toggle ambient lighting (passed to settings sheet)
final VoidCallback? onToggleAmbientLighting;
/// List of FocusNodes for the buttons (passed from parent for navigation)
final List<FocusNode>? focusNodes;
@@ -95,6 +102,8 @@ class TrackChapterControls extends StatelessWidget {
this.isLive = false,
this.shaderService,
this.onShaderChanged,
this.isAmbientLightingEnabled = false,
this.onToggleAmbientLighting,
});
/// Handle key event for button navigation
@@ -189,20 +198,24 @@ class TrackChapterControls extends StatelessWidget {
tracks: tracks,
isMobile: isMobile,
isDesktop: isDesktop,
onPressed: () async {
await VideoSettingsSheet.show(
context,
player,
audioSyncOffset,
subtitleSyncOffset,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
canControl: canControl,
isLive: isLive,
shaderService: shaderService,
onShaderChanged: onShaderChanged,
);
onLoadSeekTimes?.call();
onPressed: () {
onCancelAutoHide?.call();
OverlaySheetController.of(context).show(
builder: (_) => VideoSettingsSheet(
player: player,
audioSyncOffset: audioSyncOffset,
subtitleSyncOffset: subtitleSyncOffset,
canControl: canControl,
isLive: isLive,
shaderService: shaderService,
onShaderChanged: onShaderChanged,
isAmbientLightingEnabled: isAmbientLightingEnabled,
onToggleAmbientLighting: onToggleAmbientLighting,
),
).whenComplete(() {
onStartAutoHide?.call();
onLoadSeekTimes?.call();
});
},
);
},
@@ -222,13 +235,15 @@ class TrackChapterControls extends StatelessWidget {
tracks: tracks,
isMobile: isMobile,
isDesktop: isDesktop,
onPressed: () => AudioTrackSheet.show(
context,
player,
onTrackChanged: onAudioTrackChanged,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
onPressed: () {
onCancelAutoHide?.call();
OverlaySheetController.of(context).show(
builder: (_) => AudioTrackSheet(
player: player,
onTrackChanged: onAudioTrackChanged,
),
).whenComplete(() => onStartAutoHide?.call());
},
),
);
buttonIndex++;
@@ -246,13 +261,15 @@ class TrackChapterControls extends StatelessWidget {
tracks: tracks,
isMobile: isMobile,
isDesktop: isDesktop,
onPressed: () => SubtitleTrackSheet.show(
context,
player,
onTrackChanged: onSubtitleTrackChanged,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
onPressed: () {
onCancelAutoHide?.call();
OverlaySheetController.of(context).show(
builder: (_) => SubtitleTrackSheet(
player: player,
onTrackChanged: onSubtitleTrackChanged,
),
).whenComplete(() => onStartAutoHide?.call());
},
),
);
buttonIndex++;
@@ -270,15 +287,17 @@ class TrackChapterControls extends StatelessWidget {
tracks: tracks,
isMobile: isMobile,
isDesktop: isDesktop,
onPressed: () => ChapterSheet.show(
context,
player,
chapters,
chaptersLoaded,
serverId: serverId,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
onPressed: () {
onCancelAutoHide?.call();
OverlaySheetController.of(context).show(
builder: (_) => ChapterSheet(
player: player,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
serverId: serverId,
),
).whenComplete(() => onStartAutoHide?.call());
},
),
);
buttonIndex++;
@@ -296,14 +315,16 @@ class TrackChapterControls extends StatelessWidget {
tracks: tracks,
isMobile: isMobile,
isDesktop: isDesktop,
onPressed: () => VersionSheet.show(
context,
availableVersions,
selectedMediaIndex,
onSwitchVersion!,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
onPressed: () {
onCancelAutoHide?.call();
OverlaySheetController.of(context).show(
builder: (_) => VersionSheet(
availableVersions: availableVersions,
selectedMediaIndex: selectedMediaIndex,
onVersionSelected: onSwitchVersion!,
),
).whenComplete(() => onStartAutoHide?.call());
},
),
);
buttonIndex++;
-4
View File
@@ -70,10 +70,6 @@ set_target_properties(${BINARY_NAME}
)
# Bundle SDL3 from source so the build works on systems without libsdl3-dev
# (e.g. arm64 Linux where no distro package exists yet).
set(BUNDLE_SDL3 ON CACHE BOOL "" FORCE)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
+1 -1
View File
@@ -131,7 +131,7 @@ meson setup build \
-Dalsa=enabled \
-Dpulse=enabled \
-Dpipewire=enabled \
-Dwayland=enabled \
-Dwayland=disabled \
-Dx11=enabled
ninja -C build -j"$JOBS"
+3
View File
@@ -43,6 +43,7 @@ DISTROS = {
"libmpv2 | libmpv1",
"libepoxy0",
"libasound2",
"libevdev2",
"libglib2.0-0",
],
},
@@ -56,6 +57,7 @@ DISTROS = {
"mpv-libs",
"libepoxy",
"alsa-lib",
"libevdev",
"glib2",
],
},
@@ -69,6 +71,7 @@ DISTROS = {
"mpv",
"libepoxy",
"alsa-lib",
"libevdev",
"glib2",
],
},
+1
View File
@@ -11,6 +11,7 @@ add_executable(${BINARY_NAME}
"my_application.cc"
"mpv/mpv_player.cc"
"mpv/mpv_plugin.cc"
"mpv/mpv_texture.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
+45 -67
View File
@@ -43,19 +43,11 @@ MpvPlayer::~MpvPlayer() {
Dispose();
}
bool MpvPlayer::Initialize(GtkGLArea* gl_area) {
bool MpvPlayer::Initialize() {
if (mpv_) {
return true; // Already initialized.
}
gl_area_ = gl_area;
// Check if GL area is realized
if (!gtk_widget_get_realized(GTK_WIDGET(gl_area))) {
g_warning("MPV: GL area not realized yet");
return false;
}
// MPV requires C locale for numeric formatting
std::setlocale(LC_NUMERIC, "C");
@@ -67,11 +59,11 @@ bool MpvPlayer::Initialize(GtkGLArea* gl_area) {
}
// Configure mpv for embedded playback.
mpv_set_option_string(mpv_, "vo", "libmpv"); // Render via mpv_render_context_render()
mpv_set_option_string(mpv_, "vo", "libmpv");
mpv_set_option_string(mpv_, "hwdec", "auto");
mpv_set_option_string(mpv_, "keep-open", "yes");
// HDR tone mapping - ensures HDR content is properly converted to SDR
// HDR tone mapping
mpv_set_option_string(mpv_, "tone-mapping", "auto");
mpv_set_option_string(mpv_, "target-colorspace-hint", "no");
mpv_set_option_string(mpv_, "hdr-compute-peak", "auto");
@@ -81,8 +73,8 @@ bool MpvPlayer::Initialize(GtkGLArea* gl_area) {
mpv_set_option_string(mpv_, "osc", "no");
mpv_set_option_string(mpv_, "terminal", "no");
// Enable verbose logging for debugging.
mpv_request_log_messages(mpv_, "v");
// Default to warn-level logging
mpv_request_log_messages(mpv_, "warn");
// Initialize mpv.
int err = mpv_initialize(mpv_);
@@ -93,12 +85,20 @@ bool MpvPlayer::Initialize(GtkGLArea* gl_area) {
return false;
}
// Make the GL context current.
gtk_gl_area_make_current(gl_area_);
if (gtk_gl_area_get_error(gl_area_) != nullptr) {
g_warning("MPV: Failed to make GL context current");
mpv_terminate_destroy(mpv_);
mpv_ = nullptr;
// Set up event wakeup callback.
mpv_set_wakeup_callback(mpv_, OnMpvWakeup, this);
g_message("MPV: Initialization successful (render context deferred)");
return true;
}
bool MpvPlayer::InitRenderContext() {
if (mpv_gl_) {
return true; // Already created.
}
if (!mpv_) {
g_warning("MPV: Cannot create render context - mpv not initialized");
return false;
}
@@ -115,45 +115,37 @@ bool MpvPlayer::Initialize(GtkGLArea* gl_area) {
{MPV_RENDER_PARAM_INVALID, nullptr},
};
err = mpv_render_context_create(&mpv_gl_, mpv_, params);
int err = mpv_render_context_create(&mpv_gl_, mpv_, params);
if (err < 0) {
g_warning("MPV: mpv_render_context_create() failed: %s",
mpv_error_string(err));
mpv_terminate_destroy(mpv_);
mpv_ = nullptr;
return false;
}
// Set up event wakeup callback.
mpv_set_wakeup_callback(mpv_, OnMpvWakeup, this);
// Set up render update callback.
mpv_render_context_set_update_callback(mpv_gl_, OnMpvRenderUpdate, this);
g_message("MPV: Initialization successful");
g_message("MPV: Render context created successfully");
return true;
}
void MpvPlayer::Dispose() {
// Lock mutex to prevent race with OnMpvWakeup callbacks.
// This ensures no new event processing starts during dispose.
std::lock_guard<std::mutex> lock(callback_mutex_);
// Guard against multiple dispose calls (double-free protection)
if (disposed_.exchange(true)) {
return; // Already disposed
return;
}
// Cancel pending async commands
{
std::lock_guard<std::mutex> cmd_lock(pending_commands_mutex_);
for (auto& pair : pending_commands_) {
if (pair.second) pair.second(-1); // Call with error
if (pair.second) pair.second(-1);
}
pending_commands_.clear();
}
// Clear mpv callbacks BEFORE freeing to prevent new callbacks being scheduled
// Clear mpv callbacks BEFORE freeing
if (mpv_gl_) {
mpv_render_context_set_update_callback(mpv_gl_, nullptr, nullptr);
}
@@ -167,20 +159,18 @@ void MpvPlayer::Dispose() {
event_source_id_ = 0;
}
// Now safe to free render context
if (mpv_gl_) {
mpv_render_context_free(mpv_gl_);
mpv_gl_ = nullptr;
}
// And terminate mpv
if (mpv_) {
mpv_terminate_destroy(mpv_);
mpv_ = nullptr;
}
observed_properties_.clear();
gl_area_ = nullptr;
redraw_callback_ = nullptr;
}
void MpvPlayer::Command(const std::vector<std::string>& args) {
@@ -210,7 +200,6 @@ void MpvPlayer::CommandAsync(const std::vector<std::string>& args,
}
c_args.push_back(nullptr);
// Generate unique request ID and store callback
uint64_t request_id;
{
std::lock_guard<std::mutex> lock(pending_commands_mutex_);
@@ -218,10 +207,8 @@ void MpvPlayer::CommandAsync(const std::vector<std::string>& args,
pending_commands_[request_id] = std::move(callback);
}
// mpv_command_async returns immediately
int result = mpv_command_async(mpv_, request_id, c_args.data());
if (result < 0) {
// Submission failed, complete immediately with error
std::lock_guard<std::mutex> lock(pending_commands_mutex_);
auto it = pending_commands_.find(request_id);
if (it != pending_commands_.end()) {
@@ -253,7 +240,6 @@ void MpvPlayer::ObserveProperty(const std::string& name,
int id) {
if (disposed_ || !mpv_) return;
// Check if already observing.
if (observed_properties_.find(name) != observed_properties_.end()) {
return;
}
@@ -288,7 +274,7 @@ void MpvPlayer::Render(int width, int height, int fbo) {
.internal_format = 0,
};
int flip_y = 1;
int flip_y = 0;
mpv_render_param params[] = {
{MPV_RENDER_PARAM_OPENGL_FBO, &mpv_fbo},
@@ -312,42 +298,26 @@ void MpvPlayer::SetEventCallback(EventCallback callback) {
event_callback_ = std::move(callback);
}
void MpvPlayer::RequestRedraw() {
if (disposed_) return;
void MpvPlayer::SetRedrawCallback(RedrawCallback callback) {
std::lock_guard<std::mutex> lock(callback_mutex_);
redraw_callback_ = std::move(callback);
}
needs_redraw_.store(true);
if (gl_area_) {
// Queue redraw on main thread
GtkGLArea* area = gl_area_;
g_idle_add_full(
GDK_PRIORITY_REDRAW,
[](gpointer data) -> gboolean {
GtkGLArea* area = static_cast<GtkGLArea*>(data);
if (GTK_IS_GL_AREA(area)) {
gtk_gl_area_queue_render(area);
}
return G_SOURCE_REMOVE;
},
area,
nullptr);
}
void MpvPlayer::SetLogLevel(const std::string& level) {
if (disposed_ || !mpv_) return;
mpv_request_log_messages(mpv_, level.c_str());
}
void MpvPlayer::OnMpvWakeup(void* ctx) {
auto* player = static_cast<MpvPlayer*>(ctx);
// Don't schedule if already disposed (atomic check for early exit)
if (player->disposed_) return;
// Schedule event processing on the main thread.
g_idle_add_full(
G_PRIORITY_HIGH_IDLE,
[](gpointer data) -> gboolean {
auto* player = static_cast<MpvPlayer*>(data);
// Check disposed - atomic ensures we see updated value.
// Don't lock mutex here - ProcessEvents() calls SendPropertyChange/SendEvent
// which lock callback_mutex_, causing deadlock if we hold it here.
if (!player->disposed_ && player->mpv_) {
player->ProcessEvents();
}
@@ -359,8 +329,18 @@ void MpvPlayer::OnMpvWakeup(void* ctx) {
void MpvPlayer::OnMpvRenderUpdate(void* ctx) {
auto* player = static_cast<MpvPlayer*>(ctx);
// RequestRedraw already checks disposed_
player->RequestRedraw();
if (player->disposed_) return;
bool expected = false;
if (!player->needs_redraw_.compare_exchange_strong(expected, true)) {
return;
}
// Call the redraw callback to notify MpvTexture via the registrar
std::lock_guard<std::mutex> lock(player->callback_mutex_);
if (player->redraw_callback_) {
player->redraw_callback_();
}
}
bool MpvPlayer::ProcessEvents() {
@@ -382,7 +362,6 @@ bool MpvPlayer::ProcessEvents() {
void MpvPlayer::HandleMpvEvent(mpv_event* event) {
switch (event->event_id) {
case MPV_EVENT_COMMAND_REPLY: {
// Handle async command completion
uint64_t request_id = event->reply_userdata;
CommandCallback callback;
{
@@ -394,7 +373,6 @@ void MpvPlayer::HandleMpvEvent(mpv_event* event) {
}
}
if (callback) {
// Call callback on main thread
int error = event->error;
g_idle_add(
[](gpointer data) -> gboolean {

Some files were not shown because too many files have changed in this diff Show More