Compare commits

...
118 Commits
Author SHA1 Message Date
github-actions[bot] 888d232819 chore: bump version to 1.9.1 2025-12-05 20:14:02 +00:00
edde746 6c45706ea3 fix: improve item selection logic in playlist navigation
close #149
2025-12-05 21:12:29 +01:00
edde746 2a15126119 fix: macos playback crash
close #147
2025-12-05 20:50:29 +01:00
edde746 392ee575d0 fix: controls not reappearing on some android devices 2025-12-05 19:11:48 +01:00
edde746 6db21d93bb fix: hide hidden libraries on the home screen
close #145
2025-12-05 14:08:04 +01:00
edde746 4eed2aa3d2 fix: android app switching 2025-12-05 13:49:20 +01:00
edde746 cc9cdc8f26 fix: initialize language codes 2025-12-05 11:09:17 +01:00
edde746 20933d3543 fix: macos playback crash 2025-12-04 20:32:15 +01:00
github-actions[bot] dc01c5af2f chore: bump version to 1.9.0 2025-12-04 17:11:28 +00:00
edde746 aa1a05f207 fix: add missing dependencies 2025-12-04 18:09:18 +01:00
edde746 b3c64d62ab fix: don't crop ass subtitles 2025-12-04 18:08:41 +01:00
edde746 ac154082cd fix: hero bg stretching 2025-12-04 18:06:37 +01:00
edde746 01e5648e28 fix: hero image stretch & hub title overflow 2025-12-04 17:14:55 +01:00
edde746 1d50763d9b fix: android subtitle font 2025-12-04 16:39:07 +01:00
edde746 074a6e7e7d remove play store notice 2025-12-04 16:16:12 +01:00
edde746 252da585e3 fix: android track list parsing 2025-12-04 16:02:15 +01:00
edde746 7d75f6e749 fix: backspace on search 2025-12-04 13:29:12 +01:00
edde746 6b150f7304 fix: qr code sign in on mobile 2025-12-04 12:27:23 +01:00
edde746 e73bcd7e4b refactor: move non-reused widgets 2025-12-04 09:11:09 +01:00
edde746 8f817815e6 refactor: simplify file structure 2025-12-04 08:36:07 +01:00
edde746 ac7b867f54 refactor: util for keyboard activation 2025-12-04 07:52:37 +01:00
edde746 87dd16d322 refactor: remove unused code 2025-12-04 07:43:02 +01:00
edde746 04b8396d13 refactor: fix warnings 2025-12-04 06:17:29 +01:00
edde746 a4dccb0198 feat: use plex image transcoding 2025-12-04 06:05:15 +01:00
edde746 74b34bcc77 refactor: lower image cache size 2025-12-03 20:20:10 +01:00
edde746 6efc3638d4 fix: warning 2025-12-03 19:41:46 +01:00
edde746 7f23979e03 fix: limit mem cache resolution 2025-12-03 19:39:26 +01:00
edde746 d214ade2c6 fix(darwin): dispose crash 2025-12-03 19:28:57 +01:00
edde746 a71354d9c5 refactor: simplify fill mode 2025-12-03 18:31:52 +01:00
edde746andGitHub b1dd33ad7a Merge pull request #143 from Tazi0/feat/continue-watching-in-library
feat: continue watching in library
2025-12-03 17:21:21 +01:00
edde746 2231f42f55 refactor: discover page performance improvements 2025-12-03 17:09:10 +01:00
edde746 4339e00fe2 fix: properly dispose player on replacement 2025-12-03 15:17:05 +01:00
edde746 a7a4c641a7 chore: update mpvkit build 2025-12-03 15:00:03 +01:00
edde746 cd8592e7e3 add funding.yml 2025-12-03 13:32:29 +01:00
edde746 8a9d889311 fix: external subtitles 2025-12-03 13:14:36 +01:00
edde746 8b88862a10 fix: don't focus episode when tap navigating 2025-12-03 12:34:12 +01:00
edde746 09860f81c8 fix(ios): player rotation 2025-12-03 11:14:59 +01:00
edde746 dff51ca888 feat(windows): hdr support 2025-12-03 08:39:02 +01:00
edde746 ecf046a92d feat(linux): tone map 2025-12-03 09:20:37 +01:00
edde746 aaf3e3651b fix: hdr on ios & macos 2025-12-03 08:18:21 +01:00
edde746 78a5ff0fe0 fix: darwin playback crash 2025-12-03 06:16:19 +01:00
edde746 a6f0a0b6c0 refactor: format & deduplicate 2025-12-02 23:59:49 +01:00
edde746 865cba5f9a ci: ignore exit code 2025-12-02 19:34:33 +01:00
edde746 58fd282100 refactor: remove unused imports 2025-12-02 19:18:37 +01:00
edde746 75007a6f42 fix: hwdec toggle 2025-12-02 19:03:55 +01:00
edde746 6154480c99 refactor: fix warnings 2025-12-02 17:44:43 +01:00
edde746 7c6a121752 refactor: clean up 2025-12-02 17:41:06 +01:00
edde746 73eda7c918 refactor: simplify player classes 2025-12-02 17:20:59 +01:00
edde746 6d9a56fa73 refactor: fix naming 2025-12-02 16:53:54 +01:00
Tazio 08f92da41b feat: continue watching in library 2025-12-02 16:43:28 +01:00
edde746 a122fb048e Merge remote-tracking branch 'origin/main' into passthrough
# Conflicts:
#	lib/screens/video_player_screen.dart
#	lib/services/playback_initialization_service.dart
#	lib/widgets/video_controls/video_controls.dart
2025-12-02 15:58:04 +01:00
edde746 4cc2426bff fix: stretch fit 2025-12-02 15:46:19 +01:00
edde746 8a826f0035 fix: resume 2025-12-02 15:46:19 +01:00
edde746 ae4673bde7 linux 2025-12-02 15:46:19 +01:00
edde746 920658485f windows 2025-12-02 15:46:19 +01:00
edde746 e0fd77d7de android 2025-12-02 15:46:19 +01:00
edde746 1daded6ec6 ios 2025-12-02 15:46:19 +01:00
edde746 d9cdde66d8 macos 2025-12-02 15:46:19 +01:00
edde746andGitHub 0a6f7c358e Merge pull request #142 from Tazi0/feat/auto-skip
feat: auto skip
2025-12-01 17:41:36 +01:00
Tazio bc6ee79aef chore: code quality 2025-12-01 11:08:03 +01:00
Tazio bf7e10b1cb fix: translations of new options 2025-12-01 11:06:50 +01:00
Tazio e30d20e6d1 feat: auto skip 2025-12-01 10:50:48 +01:00
Mateusz Kaflowskiandedde746 055765ead7 android_adaptive_icon_fix
android_adaptive_icon_fix

android_adaptive_icon_fix

android_adaptive_icon_fix

android_adaptive_icon_fix
2025-11-27 23:23:34 +01:00
edde746andGitHub 26fc38a5ba Merge pull request #133 from Doezer/bug/fix-subtitle-saving
fix:  save stream selection per media for audio and subtitles
2025-11-27 05:20:37 +01:00
Doezer 5cbec2398a fix: return explicit boolean value in stream selection logic 2025-11-26 22:39:25 +01:00
Doezer e69644a98e fix: fix missing update in playback init & translate french comments 2025-11-26 22:39:25 +01:00
Doezer c21c5396cd fix: save stream selection per media for audio and subtitles (not just language pref) 2025-11-26 22:39:25 +01:00
edde746 01bb1126ef feat: keyboard navigation 2025-11-26 13:51:25 +01:00
edde746 0d0388f7a8 fix: change android subtitle font
close #131
2025-11-25 22:44:59 +01:00
edde746 6ae64e6057 fix: don't sign in with no servers 2025-11-25 09:43:54 +01:00
edde746 44dcdccb2c refactor: simplify rate limits 2025-11-25 05:04:35 +01:00
github-actions[bot] 10d4b3088f chore: bump version to 1.8.1 2025-11-25 03:07:42 +00:00
edde746 a7f1c8a13c fix: auto hide controls on mobile
close #129
2025-11-25 04:03:23 +01:00
edde746 516bf3a689 ci: release adjustments 2025-11-25 03:38:04 +01:00
edde746 141deb8da0 fix: profile switcher 2025-11-25 03:33:30 +01:00
edde746andGitHub 4bcdb01029 Merge pull request #128 from Doezer/doezer/fix-subtitle-language-check-in-track-match
bug: fix language detection in track match
2025-11-24 13:23:06 +01:00
Doezer 3b51249341 bug: fix user preference for subtitle 2025-11-24 12:17:58 +01:00
edde746 0585c9da21 fix: properly clear connections on switch 2025-11-23 06:30:53 +01:00
edde746 7ab8dfa3c3 refactor: simplify metadata server tagging 2025-11-23 05:10:42 +01:00
github-actions[bot] 8d0d220d78 chore: bump version to 1.8.0+20 2025-11-22 23:36:51 +00:00
edde746 3e0379996c ci: release workflow 2025-11-23 00:36:02 +01:00
edde746 6aecaaa44a refactor: simplify server tracking 2025-11-22 23:41:46 +01:00
edde746 21627f7a97 fix: android resume issue 2025-11-22 22:32:07 +01:00
edde746 cb8e0bfa79 ci: dead code checks 2025-11-22 16:03:51 +01:00
edde746 19601e87c7 refactor: clean up 2025-11-22 07:54:52 +01:00
edde746 3945aa7b58 fix: multi-server connectivity optimization 2025-11-22 06:52:21 +01:00
edde746 b455db4bdf refactor: clean up 2025-11-22 06:33:49 +01:00
edde746 38a447f57a refactor: format & split video controls 2025-11-22 05:58:08 +01:00
edde746 8a24157832 fix: library manager 2025-11-22 04:42:11 +01:00
edde746 166654d374 refactor: use play queues & other improvements 2025-11-22 03:24:01 +01:00
edde746 6e8a1a373e feat: remove server switcher 2025-11-21 23:59:39 +01:00
edde746 b1bed439eb fix: defer clearShuffle call to avoid setState during build 2025-11-21 03:52:59 +01:00
edde746 2562d3d4b6 fix: linux audio output issues 2025-11-21 02:36:37 +01:00
edde746 c27d9d09e4 fix: linux crash 2025-11-21 02:03:36 +01:00
edde746 3cb8b522f6 chore: bump version 2025-11-20 19:10:18 +01:00
edde746 9115db5e15 fix: ios media controls 2025-11-20 19:08:31 +01:00
edde746 d63c10482c chore: bump version 2025-11-20 15:56:48 +01:00
edde746 bd283dd039 fix: inactive pause fixes 2025-11-20 15:54:13 +01:00
edde746andGitHub 0403acc9d3 Merge pull request #123 from Doezer/main
Add missing translations
2025-11-19 23:34:54 +01:00
DoezerandGitHub b81eee7f34 Merge pull request #11 from Doezer/copilot/check-untranslated-strings
Translate 126 untranslated strings across SV, NL, IT, and ZH locales
2025-11-19 22:31:05 +01:00
copilot-swe-agent[bot]andDoezer 8cef2d9cb0 Translate untranslated strings across all languages
- Swedish (SV): Translated 29 strings including video controls and accessibility labels
- Dutch (NL): Translated 36 strings including video controls, auth, and navigation
- Italian (IT): Translated 32 strings including video controls and discover section
- Chinese (ZH): Translated 29 strings with complete video player UI localization
- German (DE): Already well-translated, verified existing translations

Total: 126 strings translated across all languages
Remaining untranslated strings are intentional (brand names, technical terms, format strings)

Co-authored-by: Doezer <11655673+Doezer@users.noreply.github.com>
2025-11-19 20:41:52 +00:00
copilot-swe-agent[bot] 2e042922f4 Initial plan 2025-11-19 20:35:39 +00:00
edde746 79fb716551 fix: linux media controls 2025-11-19 09:23:39 +01:00
edde746 37b0cf65b2 fix: https required servers issue 2025-11-18 20:47:31 +01:00
edde746andGitHub b8a7d8610c Merge pull request #119 from jamal2362/main1
Update german translation
2025-11-18 20:38:11 +01:00
Jamal ad3f26de30 Update german translation 2025-11-18 19:48:08 +01:00
edde746 f23ab5b96e fix: media card playlist compatibility 2025-11-18 19:03:17 +01:00
edde746 f4c52f4069 Merge branch 'accessibility' 2025-11-18 14:44:30 +01:00
edde746 9af87d2e02 refactor: wrap buttons in semantics 2025-11-18 14:44:00 +01:00
Manuel Cortez 6417a37366 Added semantics to app bar's back button. Fixed conflicts 2025-11-17 23:12:42 -06:00
Manuel Cortez e519304f2e added translation for 'tap to play' hint on media cards 2025-11-17 22:42:11 -06:00
Manuel Cortez d0bfcb107d Enhance semantic labels to hero section on discover screen 2025-11-17 22:30:49 -06:00
Manuel Cortez 2f307ee613 added proper semantic labels to media cards 2025-11-17 22:29:08 -06:00
Manuel Cortez e23f248427 Merge branch 'main' into accessibility 2025-11-15 22:36:14 -06:00
Manuel Cortez c6bd1ef867 Added missing translation file 2025-11-15 22:22:24 -06:00
Manuel Cortez 931bc9b931 Added semantic labels to media player controls 2025-11-15 22:17:04 -06:00
Manuel Cortez 3f4d5c2923 video_control_button: sets a semantic label properly for IconButtons 2025-11-15 22:07:30 -06:00
Manuel Cortez 1220dca88e Prepared translation files with new addition for accessibility enhancements 2025-11-15 22:05:41 -06:00
220 changed files with 35517 additions and 17091 deletions
+1
View File
@@ -0,0 +1 @@
github: edde746
+30 -5
View File
@@ -53,10 +53,11 @@ jobs:
find lib $([ -d test ] && echo test) -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f 2>/dev/null -print0 | xargs -0 dart format --output=none --set-exit-if-changed
- name: Analyze code
run: |
# Run flutter analyze and filter out info-level warnings
# Only fail on errors and warnings, not on info messages
flutter analyze 2>&1 | tee analyze_output.txt
# Check if there are any errors (not just info)
# Run flutter analyze
# Fails on errors or warnings only (info messages are allowed)
flutter analyze 2>&1 | tee analyze_output.txt || true
# Check output for errors or warnings
if grep -q "error •" analyze_output.txt; then
echo "❌ Analysis failed with errors"
exit 1
@@ -64,10 +65,34 @@ jobs:
echo "⚠️ Analysis completed with warnings"
exit 1
else
echo "✅ Analysis passed (info messages are allowed)"
echo "✅ Analysis passed!"
exit 0
fi
- name: Check for unused code
run: |
echo "🔍 Checking for unused code..."
dart run dart_code_linter:metrics check-unused-code lib 2>&1 | tee unused_code.txt
if grep -qi "no unused code found" unused_code.txt; then
echo "✅ No unused code found"
else
echo "❌ Found unused code:"
cat unused_code.txt
exit 1
fi
- name: Check for unused files
run: |
echo "🔍 Checking for unused files..."
dart run dart_code_linter:metrics check-unused-files lib 2>&1 | tee unused_files.txt
if grep -qi "no unused files found" unused_files.txt; then
echo "✅ No unused files found"
else
echo "❌ Found unused files:"
cat unused_files.txt
exit 1
fi
test:
name: Unit Tests
runs-on: ubuntu-latest
+82
View File
@@ -0,0 +1,82 @@
name: Release
on:
workflow_dispatch:
inputs:
version:
description: 'Version number (e.g., 1.9.0)'
required: true
type: string
permissions:
contents: write
actions: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Validate version format
run: |
if ! echo "${{ inputs.version }}" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Error: Version must be in semantic versioning format (e.g., 1.9.0)"
exit 1
fi
- name: Extract current build number
id: get_build
run: |
# Extract current build number from pubspec.yaml
CURRENT_VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //')
CURRENT_BUILD=$(echo "$CURRENT_VERSION" | cut -d'+' -f2)
NEW_BUILD=$((CURRENT_BUILD + 1))
echo "current_build=$CURRENT_BUILD" >> $GITHUB_OUTPUT
echo "new_build=$NEW_BUILD" >> $GITHUB_OUTPUT
echo "Current build: $CURRENT_BUILD"
echo "New build: $NEW_BUILD"
- name: Update pubspec.yaml
run: |
NEW_VERSION="${{ inputs.version }}+${{ steps.get_build.outputs.new_build }}"
sed -i "s/^version: .*/version: $NEW_VERSION/" pubspec.yaml
echo "Updated version to: $NEW_VERSION"
cat pubspec.yaml | grep '^version:'
- name: Configure Git
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: Commit version bump
run: |
git add pubspec.yaml
git commit -m "chore: bump version to ${{ inputs.version }}"
- name: Create Git tag
run: |
git tag "${{ inputs.version }}"
echo "Created tag: ${{ inputs.version }}"
- name: Push changes and tag
run: |
git push origin main
git push origin --tags
- name: Trigger build workflow
run: |
curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/build.yml/dispatches \
-d '{"ref":"main"}'
echo "Build workflow triggered successfully"
+4 -38
View File
@@ -17,8 +17,6 @@ Plezy is a modern Plex media client that provides a seamless streaming experienc
<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>
> Google Play version is in closed testing ([required by Google](https://support.google.com/googleplay/android-developer/answer/14151465#overview)). Join the [Google Group](https://groups.google.com/g/plezy-testers-2) to get access.
### Desktop
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.zip)
@@ -41,6 +39,7 @@ Plezy is a modern Plex media client that provides a seamless streaming experienc
### 🎬 Video Playback
- Wide codec support including HEVC, AV1, VP9, and more
- HDR and Dolby Vision support (iOS, macOS & Windows)
- Advanced subtitle rendering with full ASS/SSA support
- Audio and subtitle track selection with user profile preferences
- Playback progress sync and resume functionality
@@ -77,25 +76,6 @@ flutter run
## Development
### Code Quality
Before submitting changes, ensure your code passes all quality checks:
```bash
# Format code (including generated files)
dart format .
# Analyze code for issues
flutter analyze
# Run tests (if available)
flutter test
```
**Note**: CI checks exclude generated files (`.g.dart`, `.freezed.dart`) from formatting and analysis checks. You can run `dart format .` locally to format everything, but only your hand-written code will be validated in CI.
These checks are automatically run in CI for all pull requests.
### Code Generation
The project uses code generation for JSON serialization. After modifying model classes, run:
@@ -104,24 +84,10 @@ The project uses code generation for JSON serialization. After modifying model c
dart run build_runner build --delete-conflicting-outputs
```
## Building for Production
### Android
```bash
flutter build apk --release
# or
flutter build appbundle --release
```
### Desktop
```bash
flutter build macos --release
flutter build windows --release
flutter build linux --release
```
## Acknowledgments
- Built with [Flutter](https://flutter.dev)
- Media playback powered by [MediaKit](https://github.com/media-kit/media-kit)
- Designed for [Plex Media Server](https://www.plex.tv)
- Playback powered by [mpv](https://mpv.io)
- [MPVKit](https://github.com/mpvkit/MPVKit)
- [mpv-android](https://github.com/mpv-android/mpv-android)
+6
View File
@@ -4,3 +4,9 @@ analyzer:
exclude:
- "**/*.g.dart"
- "**/*.freezed.dart"
plugins:
- dart_code_linter
dart_code_linter:
rules:
- avoid-unused-parameters
+5 -1
View File
@@ -26,7 +26,7 @@ android {
applicationId = "com.edde746.plezy"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
minSdk = 26 // Required by libmpv-android
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
@@ -62,3 +62,7 @@ android {
flutter {
source = "../.."
}
dependencies {
implementation("dev.jdtech.mpv:libmpv:0.5.1")
}
@@ -0,0 +1,300 @@
package com.edde746.plezy.mpv
import android.app.Activity
import android.graphics.Color
import android.graphics.PixelFormat
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.TextureView
import dev.jdtech.mpv.MPVLib
interface MpvPlayerDelegate {
fun onPropertyChange(name: String, value: Any?)
fun onEvent(name: String, data: Map<String, Any>?)
}
class MpvPlayerCore(private val activity: Activity) :
SurfaceHolder.Callback,
MPVLib.EventObserver {
companion object {
private const val TAG = "MpvPlayerCore"
}
private var surfaceView: SurfaceView? = null
private var overlayLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? =
null
private var voInUse: String = "gpu"
var delegate: MpvPlayerDelegate? = null
var isInitialized: Boolean = false
private set
private fun ensureFlutterOverlayOnTop() {
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.post {
var flutterContainer: ViewGroup? = null
// First pass: look for FlutterView by name (debug builds)
for (i in 0 until contentView.childCount) {
val child = contentView.getChildAt(i)
if (child is ViewGroup && child.javaClass.name.contains("FlutterView")) {
flutterContainer = child
break
}
}
// Fallback for release (FlutterView may be obfuscated): pick the last ViewGroup
// that is not our mpv SurfaceView and has children.
if (flutterContainer == null) {
for (i in contentView.childCount - 1 downTo 0) {
val child = contentView.getChildAt(i)
if (child is ViewGroup && child != surfaceView?.parent && child.childCount > 0) {
flutterContainer = child
break
}
}
}
flutterContainer?.let { container ->
contentView.bringChildToFront(container)
for (j in 0 until container.childCount) {
val flutterChild = container.getChildAt(j)
if (flutterChild is SurfaceView) {
flutterChild.setZOrderOnTop(true)
flutterChild.setZOrderMediaOverlay(true)
flutterChild.holder.setFormat(PixelFormat.TRANSLUCENT)
break
} else if (flutterChild is TextureView) {
// TextureView uses alpha composition; ensure it stays above.
flutterChild.isOpaque = false
break
}
}
}
}
}
fun initialize(): Boolean {
if (isInitialized) {
Log.d(TAG, "Already initialized")
return true
}
try {
// Create SurfaceView for video rendering
surfaceView = SurfaceView(activity).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setBackgroundColor(Color.BLACK)
// Keep video composited in the normal view hierarchy (avoid hardware overlay promotion)
// so Flutter controls reliably draw above it in release builds.
alpha = 0.999f
holder.addCallback(this@MpvPlayerCore)
// Critical: Ensure SurfaceView renders BEHIND Flutter's view
setZOrderOnTop(false)
setZOrderMediaOverlay(false)
}
// Insert SurfaceView at bottom of view hierarchy (behind Flutter)
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.addView(surfaceView, 0)
// Find FlutterView and its internal FlutterSurfaceView, set it on top
for (i in 0 until contentView.childCount) {
val child = contentView.getChildAt(i)
if (child is ViewGroup && child.javaClass.name.contains("FlutterView")) {
contentView.bringChildToFront(child)
// Look inside FlutterView for FlutterSurfaceView
for (j in 0 until child.childCount) {
val flutterChild = child.getChildAt(j)
if (flutterChild is SurfaceView) {
// Put Flutter in media overlay layer (above our video which is in normal layer)
flutterChild.setZOrderOnTop(true)
flutterChild.setZOrderMediaOverlay(true)
flutterChild.holder.setFormat(PixelFormat.TRANSLUCENT)
break
}
}
break
}
}
// Repeat after layout settles to catch late-added Flutter surfaces (release builds)
ensureFlutterOverlayOnTop()
overlayLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
ensureFlutterOverlayOnTop()
}
contentView.viewTreeObserver.addOnGlobalLayoutListener(overlayLayoutListener)
Log.d(TAG, "SurfaceView added to content view")
// Initialize MPVLib
MPVLib.create(activity.applicationContext)
// Configure MPV defaults
setupMpvDefaults()
// Initialize MPV
MPVLib.init()
// Register event observer
MPVLib.addObserver(this)
isInitialized = true
Log.d(TAG, "Initialized successfully")
return true
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize: ${e.message}", e)
return false
}
}
private fun setupMpvDefaults() {
// Video output configuration
MPVLib.setOptionString("vo", "gpu")
MPVLib.setOptionString("gpu-context", "android")
// hwdec is set from Flutter via setProperty based on user preference
// Audio configuration
MPVLib.setOptionString("ao", "audiotrack")
}
// SurfaceHolder.Callback
override fun surfaceCreated(holder: SurfaceHolder) {
Log.d(TAG, "Surface created")
MPVLib.attachSurface(holder.surface)
MPVLib.setOptionString("force-window", "yes")
// Restore video output after surface is available
MPVLib.setPropertyString("vo", voInUse)
// Reassert overlay order whenever the surface is recreated
ensureFlutterOverlayOnTop()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
Log.d(TAG, "Surface changed: ${width}x${height}")
MPVLib.setPropertyString("android-surface-size", "${width}x${height}")
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
Log.d(TAG, "Surface destroyed")
// Disable video output before detaching (like mpv-android)
MPVLib.setPropertyString("vo", "null")
MPVLib.setOptionString("force-window", "no")
MPVLib.detachSurface()
}
// MPVLib.EventObserver
override fun eventProperty(property: String) {
// No value provided
}
override fun eventProperty(property: String, value: Long) {
activity.runOnUiThread {
delegate?.onPropertyChange(property, value)
}
}
override fun eventProperty(property: String, value: Double) {
activity.runOnUiThread {
delegate?.onPropertyChange(property, value)
}
}
override fun eventProperty(property: String, value: Boolean) {
activity.runOnUiThread {
delegate?.onPropertyChange(property, value)
}
}
override fun eventProperty(property: String, value: String) {
activity.runOnUiThread {
delegate?.onPropertyChange(property, value)
}
}
override fun event(eventId: Int) {
val eventName = when (eventId) {
MPVLib.MPV_EVENT_FILE_LOADED -> "file-loaded"
MPVLib.MPV_EVENT_END_FILE -> "end-file"
MPVLib.MPV_EVENT_PLAYBACK_RESTART -> "playback-restart"
else -> null
}
eventName?.let { name ->
activity.runOnUiThread {
delegate?.onEvent(name, null)
}
}
}
// Public API
fun setProperty(name: String, value: String) {
if (!isInitialized) return
MPVLib.setPropertyString(name, value)
}
fun getProperty(name: String): String? {
if (!isInitialized) return null
return try {
MPVLib.getPropertyString(name)
} catch (e: Exception) {
null
}
}
fun observeProperty(name: String, format: String) {
if (!isInitialized) return
val mpvFormat = when (format) {
"double" -> MPVLib.MPV_FORMAT_DOUBLE
"flag" -> MPVLib.MPV_FORMAT_FLAG
"string" -> MPVLib.MPV_FORMAT_STRING
"node" -> MPVLib.MPV_FORMAT_NODE
else -> MPVLib.MPV_FORMAT_NONE
}
MPVLib.observeProperty(name, mpvFormat)
}
fun command(args: Array<String>) {
if (!isInitialized || args.isEmpty()) return
MPVLib.command(args)
}
fun setVisible(visible: Boolean) {
activity.runOnUiThread {
surfaceView?.visibility = if (visible) View.VISIBLE else View.INVISIBLE
Log.d(TAG, "setVisible($visible)")
}
}
// Cleanup
fun dispose() {
Log.d(TAG, "Disposing")
MPVLib.removeObserver(this)
surfaceView?.holder?.removeCallback(this)
overlayLayoutListener?.let { listener ->
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
surfaceView?.let { contentView.removeView(it) }
surfaceView = null
MPVLib.destroy()
isInitialized = false
Log.d(TAG, "Disposed")
}
}
@@ -0,0 +1,225 @@
package com.edde746.plezy.mpv
import android.app.Activity
import android.util.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
EventChannel.StreamHandler, ActivityAware, MpvPlayerDelegate {
companion object {
private const val TAG = "MpvPlayerPlugin"
private const val METHOD_CHANNEL = "com.plezy/mpv_player"
private const val EVENT_CHANNEL = "com.plezy/mpv_player/events"
}
private lateinit var methodChannel: MethodChannel
private lateinit var eventChannel: EventChannel
private var eventSink: EventChannel.EventSink? = null
private var playerCore: MpvPlayerCore? = null
private var activity: Activity? = null
private var activityBinding: ActivityPluginBinding? = null
// FlutterPlugin
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
methodChannel.setMethodCallHandler(this)
eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
eventChannel.setStreamHandler(this)
Log.d(TAG, "Attached to engine")
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
Log.d(TAG, "Detached from engine")
}
// ActivityAware
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
Log.d(TAG, "Attached to activity")
}
override fun onDetachedFromActivity() {
playerCore?.dispose()
playerCore = null
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity")
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
Log.d(TAG, "Reattached to activity for config changes")
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity for config changes")
}
// EventChannel.StreamHandler
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events
Log.d(TAG, "Event stream connected")
}
override fun onCancel(arguments: Any?) {
eventSink = null
Log.d(TAG, "Event stream disconnected")
}
// MethodChannel.MethodCallHandler
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> handleInitialize(result)
"dispose" -> handleDispose(result)
"setProperty" -> handleSetProperty(call, result)
"getProperty" -> handleGetProperty(call, result)
"observeProperty" -> handleObserveProperty(call, result)
"command" -> handleCommand(call, result)
"setVisible" -> handleSetVisible(call, result)
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
else -> result.notImplemented()
}
}
private fun handleInitialize(result: MethodChannel.Result) {
val currentActivity = activity
if (currentActivity == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
return
}
if (playerCore?.isInitialized == true) {
Log.d(TAG, "Already initialized")
result.success(true)
return
}
currentActivity.runOnUiThread {
try {
playerCore = MpvPlayerCore(currentActivity).apply {
delegate = this@MpvPlayerPlugin
}
val success = playerCore?.initialize() ?: false
// Start hidden
playerCore?.setVisible(false)
Log.d(TAG, "Initialized: $success")
result.success(success)
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize: ${e.message}", e)
result.error("INIT_FAILED", e.message, null)
}
}
}
private fun handleDispose(result: MethodChannel.Result) {
activity?.runOnUiThread {
playerCore?.dispose()
playerCore = null
Log.d(TAG, "Disposed")
result.success(null)
} ?: result.success(null)
}
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val value = call.argument<String>("value")
if (name == null || value == null) {
result.error("INVALID_ARGS", "Missing 'name' or 'value'", null)
return
}
playerCore?.setProperty(name, value)
result.success(null)
}
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
if (name == null) {
result.error("INVALID_ARGS", "Missing 'name'", null)
return
}
val value = playerCore?.getProperty(name)
result.success(value)
}
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val format = call.argument<String>("format")
if (name == null || format == null) {
result.error("INVALID_ARGS", "Missing 'name' or 'format'", null)
return
}
playerCore?.observeProperty(name, format)
result.success(null)
}
private fun handleCommand(call: MethodCall, result: MethodChannel.Result) {
val args = call.argument<List<String>>("args")
if (args == null) {
result.error("INVALID_ARGS", "Missing 'args'", null)
return
}
playerCore?.command(args.toTypedArray())
result.success(null)
}
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
val visible = call.argument<Boolean>("visible")
if (visible == null) {
result.error("INVALID_ARGS", "Missing 'visible'", null)
return
}
playerCore?.setVisible(visible)
result.success(null)
}
// MpvPlayerDelegate
override fun onPropertyChange(name: String, value: Any?) {
eventSink?.success(
mapOf(
"type" to "property",
"name" to name,
"value" to value
)
)
}
override fun onEvent(name: String, data: Map<String, Any>?) {
val event = mutableMapOf<String, Any>(
"type" to "event",
"name" to name
)
data?.let { event["data"] = it }
eventSink?.success(event)
}
}
@@ -1,5 +1,12 @@
package com.edde746.plezy
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import com.edde746.plezy.mpv.MpvPlayerPlugin
class MainActivity : FlutterActivity()
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine.plugins.add(MpvPlayerPlugin())
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.
Binary file not shown.
-24
View File
@@ -2,10 +2,6 @@ PODS:
- connectivity_plus (0.0.1):
- Flutter
- Flutter (1.0.0)
- media_kit_libs_ios_video (1.0.4):
- Flutter
- media_kit_video (0.0.1):
- Flutter
- os_media_controls (0.0.1):
- Flutter
- package_info_plus (0.4.5):
@@ -21,34 +17,22 @@ PODS:
- FlutterMacOS
- url_launcher_ios (0.0.1):
- Flutter
- volume_controller (0.0.1):
- Flutter
- wakelock_plus (0.0.1):
- Flutter
DEPENDENCIES:
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
- Flutter (from `Flutter`)
- media_kit_libs_ios_video (from `.symlinks/plugins/media_kit_libs_ios_video/ios`)
- media_kit_video (from `.symlinks/plugins/media_kit_video/ios`)
- os_media_controls (from `.symlinks/plugins/os_media_controls/ios`)
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
- sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`)
- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)
- volume_controller (from `.symlinks/plugins/volume_controller/ios`)
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
EXTERNAL SOURCES:
connectivity_plus:
:path: ".symlinks/plugins/connectivity_plus/ios"
Flutter:
:path: Flutter
media_kit_libs_ios_video:
:path: ".symlinks/plugins/media_kit_libs_ios_video/ios"
media_kit_video:
:path: ".symlinks/plugins/media_kit_video/ios"
os_media_controls:
:path: ".symlinks/plugins/os_media_controls/ios"
package_info_plus:
@@ -61,24 +45,16 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/sqflite_darwin/darwin"
url_launcher_ios:
:path: ".symlinks/plugins/url_launcher_ios/ios"
volume_controller:
:path: ".symlinks/plugins/volume_controller/ios"
wakelock_plus:
:path: ".symlinks/plugins/wakelock_plus/ios"
SPEC CHECKSUMS:
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854
media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
volume_controller: 3657a1f65bedb98fa41ff7dc5793537919f31b12
wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
PODFILE CHECKSUM: 3c63482e143d1b91d2d2560aee9fb04ecc74ac7e
+40
View File
@@ -12,6 +12,9 @@
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
50DEEA8E23D1B433DE5341D6 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C12D873DE8572579684A82C /* Pods_Runner.framework */; };
6A48DFB02EA70C7100C1F7CD /* plezy.icon in Resources */ = {isa = PBXBuildFile; fileRef = 6A48DFAF2EA70C7100C1F7CD /* plezy.icon */; };
6A8A46212EDB320D0057B88C /* MPVKit-GPL in Frameworks */ = {isa = PBXBuildFile; productRef = 6A8A46202EDB320D0057B88C /* MPVKit-GPL */; };
6A8A46252EDB370C0057B88C /* MpvPlayerPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */; };
6A8A46262EDB370C0057B88C /* MpvPlayerCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
@@ -52,6 +55,8 @@
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
5B81FA7048BFA976F49D555E /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = "<group>"; };
6A48DFAF2EA70C7100C1F7CD /* plezy.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = plezy.icon; sourceTree = "<group>"; };
6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MpvPlayerCore.swift; sourceTree = "<group>"; };
6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MpvPlayerPlugin.swift; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
@@ -81,6 +86,7 @@
buildActionMask = 2147483647;
files = (
50DEEA8E23D1B433DE5341D6 /* Pods_Runner.framework in Frameworks */,
6A8A46212EDB320D0057B88C /* MPVKit-GPL in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -104,6 +110,15 @@
name = Frameworks;
sourceTree = "<group>";
};
6A8A46242EDB370C0057B88C /* MpvPlayer */ = {
isa = PBXGroup;
children = (
6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */,
6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */,
);
path = MpvPlayer;
sourceTree = "<group>";
};
875C8AEFBBA3759A1849D674 /* Pods */ = {
isa = PBXGroup;
children = (
@@ -153,6 +168,7 @@
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
6A8A46242EDB370C0057B88C /* MpvPlayer */,
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
97C147021CF9000F007C117D /* Info.plist */,
@@ -237,6 +253,9 @@
Base,
);
mainGroup = 97C146E51CF9000F007C117D;
packageReferences = (
6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */,
);
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
projectDirPath = "";
projectRoot = "";
@@ -376,6 +395,8 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
6A8A46252EDB370C0057B88C /* MpvPlayerPlugin.swift in Sources */,
6A8A46262EDB370C0057B88C /* MpvPlayerCore.swift in Sources */,
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
);
@@ -734,6 +755,25 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/edde746/MPVKit";
requirement = {
kind = revision;
revision = 0d0931fbbb25a3483a7edb46babd3f2f55abeefc;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
6A8A46202EDB320D0057B88C /* MPVKit-GPL */ = {
isa = XCSwiftPackageProductDependency;
package = 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */;
productName = "MPVKit-GPL";
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;
}
@@ -0,0 +1,14 @@
{
"originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee",
"pins" : [
{
"identity" : "mpvkit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "0d0931fbbb25a3483a7edb46babd3f2f55abeefc"
}
}
],
"version" : 3
}
@@ -0,0 +1,14 @@
{
"originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee",
"pins" : [
{
"identity" : "mpvkit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "0d0931fbbb25a3483a7edb46babd3f2f55abeefc"
}
}
],
"version" : 3
}
+5
View File
@@ -10,6 +10,11 @@ import AVFoundation
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
// Register MPV player plugin
if let registrar = self.registrar(forPlugin: "MpvPlayerPlugin") {
MpvPlayerPlugin.register(with: registrar)
}
// Configure audio session for media playback
do {
let session = AVAudioSession.sharedInstance()
+501
View File
@@ -0,0 +1,501 @@
import Libmpv
import UIKit
/// Protocol for receiving player events
protocol MpvPlayerDelegate: AnyObject {
func onPropertyChange(name: String, value: Any?)
func onEvent(name: String, data: [String: Any]?)
}
// Workaround for MoltenVK problems that cause flicker
// https://github.com/mpv-player/mpv/pull/13651
private class MetalLayer: CAMetalLayer {
override var drawableSize: CGSize {
get { return super.drawableSize }
set {
if Int(newValue.width) > 1 && Int(newValue.height) > 1 {
super.drawableSize = newValue
}
}
}
// Fix for target-colorspace-hint - needs main thread for EDR
@available(iOS 16.0, *)
override var wantsExtendedDynamicRangeContent: Bool {
get { return super.wantsExtendedDynamicRangeContent }
set {
if Thread.isMainThread {
super.wantsExtendedDynamicRangeContent = newValue
} else {
DispatchQueue.main.sync {
super.wantsExtendedDynamicRangeContent = newValue
}
}
}
}
}
/// Core MPV player using Metal rendering for iOS
class MpvPlayerCore: NSObject {
// MARK: - Properties
private var metalLayer: MetalLayer?
private var containerView: UIView? // Container for proper EDR activation
private var mpv: OpaquePointer?
private weak var window: UIWindow?
private lazy var queue = DispatchQueue(label: "mpv", qos: .userInitiated)
weak var delegate: MpvPlayerDelegate?
private(set) var isInitialized = false
// HDR settings
private var hdrEnabled = true // User preference for HDR
private var lastSigPeak: Double = 0.0 // Last known sig-peak for re-evaluation
// MARK: - Initialization
func initialize(in window: UIWindow) -> Bool {
guard !isInitialized else {
print("[MpvPlayerCore] Already initialized")
return true
}
self.window = window
// Create container view for proper EDR activation
// EDR requires the CAMetalLayer to be in a UIView hierarchy, not just window.layer
let container = UIView(frame: window.bounds)
container.backgroundColor = .clear
container.isUserInteractionEnabled = false
// Create Metal layer for video rendering
let layer = MetalLayer()
layer.frame = container.bounds
layer.contentsScale = UIScreen.main.nativeScale
layer.framebufferOnly = true
layer.backgroundColor = UIColor.black.cgColor
container.layer.addSublayer(layer)
containerView = container
metalLayer = layer
// Add container view to window (behind Flutter's root view controller)
window.insertSubview(container, at: 0)
print(
"[MpvPlayerCore] Metal layer added to window via container view, frame: \(layer.frame)")
// Initialize MPV with this Metal layer
guard setupMpv() else {
print("[MpvPlayerCore] Failed to setup MPV")
layer.removeFromSuperlayer()
container.removeFromSuperview()
metalLayer = nil
containerView = nil
return false
}
// Setup background/foreground notifications
setupNotifications()
isInitialized = true
print("[MpvPlayerCore] Initialized successfully with MPV")
return true
}
private func setupMpv() -> Bool {
guard let metalLayer = metalLayer else { return false }
mpv = mpv_create()
guard mpv != nil else {
print("[MpvPlayerCore] Failed to create MPV context")
return false
}
// Logging
#if DEBUG
checkError(mpv_request_log_messages(mpv, "info"))
#else
checkError(mpv_request_log_messages(mpv, "warn"))
#endif
// Set the Metal layer as the render target (must use local var for &)
var layer = metalLayer
checkError(mpv_set_option(mpv, "wid", MPV_FORMAT_INT64, &layer))
// Video output settings for Metal/Vulkan
checkError(mpv_set_option_string(mpv, "vo", "gpu-next"))
checkError(mpv_set_option_string(mpv, "gpu-api", "vulkan"))
checkError(mpv_set_option_string(mpv, "gpu-context", "moltenvk"))
checkError(mpv_set_option_string(mpv, "hwdec", "videotoolbox"))
checkError(mpv_set_option_string(mpv, "target-colorspace-hint", "yes"))
// Initialize MPV
let initResult = mpv_initialize(mpv)
if initResult < 0 {
print(
"[MpvPlayerCore] mpv_initialize failed: \(String(cString: mpv_error_string(initResult)))"
)
mpv_terminate_destroy(mpv)
mpv = nil
return false
}
// Set up wakeup callback for event handling
mpv_set_wakeup_callback(
mpv,
{ ctx in
let core = Unmanaged<MpvPlayerCore>.fromOpaque(ctx!).takeUnretainedValue()
core.readEvents()
}, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
// Observe video-params/sig-peak for HDR detection
mpv_observe_property(mpv, 0, "video-params/sig-peak", MPV_FORMAT_DOUBLE)
print("[MpvPlayerCore] MPV initialized successfully")
return true
}
// MARK: - Background/Foreground Handling
private func setupNotifications() {
NotificationCenter.default.addObserver(
self,
selector: #selector(enterBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(enterForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil
)
}
@objc private func enterBackground() {
// Disable video output to fix black screen when returning from background
print("[MpvPlayerCore] Entering background - disabling video")
if mpv != nil {
mpv_set_option_string(mpv, "vid", "no")
}
}
@objc private func enterForeground() {
// Re-enable video output
print("[MpvPlayerCore] Entering foreground - enabling video")
if mpv != nil {
mpv_set_option_string(mpv, "vid", "auto")
}
}
// MARK: - MPV Properties and Commands
func setProperty(_ name: String, value: String) {
guard mpv != nil else { return }
// Handle custom HDR toggle property
if name == "hdr-enabled" {
let enabled = value == "yes" || value == "true" || value == "1"
setHDREnabled(enabled)
return
}
mpv_set_property_string(mpv, name, value)
}
/// Enable or disable HDR mode
func setHDREnabled(_ enabled: Bool) {
hdrEnabled = enabled
print("[MpvPlayerCore] HDR enabled: \(enabled)")
// Update MPV's target-colorspace-hint
if mpv != nil {
mpv_set_property_string(mpv, "target-colorspace-hint", enabled ? "yes" : "no")
}
// Re-evaluate EDR mode with current sig-peak
DispatchQueue.main.async {
self.updateEDRMode(sigPeak: self.lastSigPeak)
}
}
func getProperty(_ name: String) -> String? {
guard mpv != nil else { return nil }
let cstr = mpv_get_property_string(mpv, name)
defer { mpv_free(cstr) }
return cstr.map { String(cString: $0) }
}
func observeProperty(_ name: String, format: String) {
guard mpv != nil else { return }
let mpvFormat: mpv_format
switch format {
case "double": mpvFormat = MPV_FORMAT_DOUBLE
case "flag": mpvFormat = MPV_FORMAT_FLAG
case "node": mpvFormat = MPV_FORMAT_NODE
case "string": mpvFormat = MPV_FORMAT_STRING
default: return
}
mpv_observe_property(mpv, 0, name, mpvFormat)
}
func command(_ args: [String]) {
guard mpv != nil, !args.isEmpty else { return }
command(args[0], args: Array(args.dropFirst()))
}
// MARK: - Visibility
func setVisible(_ visible: Bool) {
guard let container = containerView else { return }
if visible {
// Re-insert at the bottom of the window view stack
container.removeFromSuperview()
window?.insertSubview(container, at: 0)
}
container.isHidden = !visible
print("[MpvPlayerCore] setVisible(\(visible))")
}
func updateFrame(_ frame: CGRect? = nil) {
guard let metalLayer = metalLayer, let container = containerView else { return }
if let frame = frame {
container.frame = frame
metalLayer.frame = container.bounds
} else if let window = window {
container.frame = window.bounds
metalLayer.frame = container.bounds
}
// Update drawable size for proper scaling
let scale = UIScreen.main.nativeScale
metalLayer.drawableSize = CGSize(
width: metalLayer.frame.width * scale,
height: metalLayer.frame.height * scale
)
print("[MpvPlayerCore] updateFrame: \(container.frame)")
}
// MARK: - Private Helpers
private func command(_ cmd: String, args: [String] = []) {
guard mpv != nil else { return }
// Build array of C strings for mpv_command
var cargs: [UnsafeMutablePointer<CChar>?] = ([cmd] + args).map { strdup($0) }
cargs.append(nil) // null-terminate
defer {
for ptr in cargs {
free(ptr)
}
}
// mpv_command expects UnsafePointer, use withUnsafeBufferPointer for the conversion
cargs.withUnsafeBufferPointer { buffer in
var constPtrs = buffer.map { UnsafePointer($0) }
_ = mpv_command(mpv, &constPtrs)
}
}
private func readEvents() {
queue.async { [weak self] in
guard let self = self, let mpv = self.mpv else { return }
while true {
let event = mpv_wait_event(mpv, 0)
guard let eventPtr = event else { break }
if eventPtr.pointee.event_id == MPV_EVENT_NONE {
break
}
self.handleEvent(eventPtr.pointee)
}
}
}
private func handleEvent(_ event: mpv_event) {
switch event.event_id {
case MPV_EVENT_PROPERTY_CHANGE:
guard let data = event.data else { break }
let property = data.assumingMemoryBound(to: mpv_event_property.self).pointee
let name = String(cString: property.name)
handlePropertyChange(name: name, property: property)
case MPV_EVENT_FILE_LOADED:
DispatchQueue.main.async {
self.delegate?.onEvent(name: "file-loaded", data: nil)
}
case MPV_EVENT_END_FILE:
DispatchQueue.main.async {
self.delegate?.onEvent(name: "end-file", data: nil)
}
case MPV_EVENT_SHUTDOWN:
print("[MpvPlayerCore] MPV shutdown event")
case MPV_EVENT_LOG_MESSAGE:
if let msgPtr = event.data?.assumingMemoryBound(to: mpv_event_log_message.self) {
let msg = msgPtr.pointee
if let prefix = msg.prefix, let level = msg.level, let text = msg.text {
print(
"[MPV:\(String(cString: prefix))] \(String(cString: level)): \(String(cString: text))",
terminator: "")
}
}
default:
break
}
}
private func handlePropertyChange(name: String, property: mpv_event_property) {
var value: Any?
switch property.format {
case MPV_FORMAT_DOUBLE:
if let ptr = property.data {
value = ptr.assumingMemoryBound(to: Double.self).pointee
}
case MPV_FORMAT_FLAG:
if let ptr = property.data {
value = ptr.assumingMemoryBound(to: Int32.self).pointee != 0
}
case MPV_FORMAT_NODE:
if let ptr = property.data {
let node = ptr.assumingMemoryBound(to: mpv_node.self).pointee
value = convertNode(node)
}
case MPV_FORMAT_STRING:
if let ptr = property.data {
let cstr = ptr.assumingMemoryBound(to: UnsafePointer<CChar>?.self).pointee
value = cstr.map { String(cString: $0) }
}
default:
break
}
// Handle sig-peak for HDR/EDR activation
if name == "video-params/sig-peak", let sigPeak = value as? Double {
lastSigPeak = sigPeak
DispatchQueue.main.async {
self.updateEDRMode(sigPeak: sigPeak)
}
}
DispatchQueue.main.async {
self.delegate?.onPropertyChange(name: name, value: value)
}
}
// MARK: - HDR/EDR Support
private func updateEDRMode(sigPeak: Double) {
guard let layer = metalLayer else { return }
// Check if screen supports EDR (iOS 16+)
var edrHeadroom: CGFloat = 1.0
if #available(iOS 16.0, *) {
edrHeadroom = containerView?.window?.screen.potentialEDRHeadroom ?? 1.0
}
let isHDRContent = sigPeak > 1.0
let screenSupportsEDR = edrHeadroom > 1.0
let shouldEnableEDR = hdrEnabled && isHDRContent && screenSupportsEDR
if #available(iOS 16.0, *) {
layer.wantsExtendedDynamicRangeContent = shouldEnableEDR
}
print(
"[MpvPlayerCore] EDR mode: \(shouldEnableEDR) (hdrEnabled: \(hdrEnabled), sigPeak: \(sigPeak), headroom: \(edrHeadroom))"
)
}
private func convertNode(_ node: mpv_node) -> Any? {
switch node.format {
case MPV_FORMAT_STRING:
return node.u.string.map { String(cString: $0) }
case MPV_FORMAT_FLAG:
return node.u.flag != 0
case MPV_FORMAT_INT64:
return node.u.int64
case MPV_FORMAT_DOUBLE:
return node.u.double_
case MPV_FORMAT_NODE_ARRAY:
guard let list = node.u.list?.pointee else { return nil }
var array = [Any]()
for i in 0..<Int(list.num) {
if let item = convertNode(list.values[i]) {
array.append(item)
}
}
return array
case MPV_FORMAT_NODE_MAP:
guard let list = node.u.list?.pointee else { return nil }
var dict = [String: Any]()
for i in 0..<Int(list.num) {
if let key = list.keys?[i].map({ String(cString: $0) }),
let val = convertNode(list.values[i])
{
dict[key] = val
}
}
return dict
default:
return nil
}
}
private func checkError(_ status: CInt) {
if status < 0 {
print("[MpvPlayerCore] MPV error: \(String(cString: mpv_error_string(status)))")
}
}
// MARK: - Cleanup
func dispose() {
NotificationCenter.default.removeObserver(self)
let mpvHandle = mpv
mpv = nil
queue.sync {
if let handle = mpvHandle {
mpv_set_wakeup_callback(handle, nil, nil)
mpv_terminate_destroy(handle)
}
}
metalLayer?.removeFromSuperlayer()
metalLayer = nil
containerView?.removeFromSuperview()
containerView = nil
isInitialized = false
print("[MpvPlayerCore] Disposed")
}
deinit {
dispose()
}
}
+245
View File
@@ -0,0 +1,245 @@
import UIKit
import Flutter
/// Flutter plugin that bridges MPV player to Dart via method and event channels
class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPlayerDelegate {
// MARK: - Properties
private var playerCore: MpvPlayerCore?
private var eventSink: FlutterEventSink?
private weak var registrar: FlutterPluginRegistrar?
// MARK: - FlutterPlugin Registration
static func register(with registrar: FlutterPluginRegistrar) {
// Method channel for commands
let methodChannel = FlutterMethodChannel(
name: "com.plezy/mpv_player",
binaryMessenger: registrar.messenger()
)
// Event channel for state updates
let eventChannel = FlutterEventChannel(
name: "com.plezy/mpv_player/events",
binaryMessenger: registrar.messenger()
)
let instance = MpvPlayerPlugin()
instance.registrar = registrar
registrar.addMethodCallDelegate(instance, channel: methodChannel)
eventChannel.setStreamHandler(instance)
print("[MpvPlayerPlugin] Registered with Flutter")
}
// MARK: - FlutterStreamHandler
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
self.eventSink = events
print("[MpvPlayerPlugin] Event stream connected")
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
self.eventSink = nil
print("[MpvPlayerPlugin] Event stream disconnected")
return nil
}
// MARK: - FlutterPlugin Method Handler
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "initialize":
handleInitialize(result: result)
case "dispose":
handleDispose(result: result)
case "setProperty":
handleSetProperty(call: call, result: result)
case "getProperty":
handleGetProperty(call: call, result: result)
case "observeProperty":
handleObserveProperty(call: call, result: result)
case "command":
handleCommand(call: call, result: result)
case "setVisible":
handleSetVisible(call: call, result: result)
case "isInitialized":
result(playerCore?.isInitialized ?? false)
case "updateFrame":
handleUpdateFrame(result: result)
default:
result(FlutterMethodNotImplemented)
}
}
// MARK: - Method Handlers
private func handleInitialize(result: @escaping FlutterResult) {
DispatchQueue.main.async { [weak self] in
guard let self = self else {
result(FlutterError(code: "ERROR", message: "Plugin deallocated", details: nil))
return
}
// Check if already initialized
if self.playerCore?.isInitialized == true {
print("[MpvPlayerPlugin] Already initialized")
result(true)
return
}
// Find the key window
guard let window = self.findKeyWindow() else {
print("[MpvPlayerPlugin] Failed to find key window")
result(FlutterError(code: "NO_WINDOW", message: "Could not find key window", details: nil))
return
}
// Create and initialize player core
let core = MpvPlayerCore()
core.delegate = self
guard core.initialize(in: window) else {
print("[MpvPlayerPlugin] Failed to initialize MPV")
result(FlutterError(code: "MPV_INIT_FAILED", message: "Failed to initialize MPV", details: nil))
return
}
self.playerCore = core
// Start hidden
core.setVisible(false)
print("[MpvPlayerPlugin] Initialized successfully")
result(true)
}
}
private func handleDispose(result: @escaping FlutterResult) {
DispatchQueue.main.async { [weak self] in
self?.playerCore?.dispose()
self?.playerCore = nil
print("[MpvPlayerPlugin] Disposed")
result(nil)
}
}
private func handleSetProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String,
let value = args["value"] as? String else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'name' or 'value' argument", details: nil))
return
}
playerCore?.setProperty(name, value: value)
result(nil)
}
private func handleGetProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'name' argument", details: nil))
return
}
let value = playerCore?.getProperty(name)
result(value)
}
private func handleObserveProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String,
let format = args["format"] as? String else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'name' or 'format' argument", details: nil))
return
}
playerCore?.observeProperty(name, format: format)
result(nil)
}
private func handleCommand(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let commandArgs = args["args"] as? [String] else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'args' argument", details: nil))
return
}
playerCore?.command(commandArgs)
result(nil)
}
private func handleSetVisible(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let visible = args["visible"] as? Bool else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'visible' argument", details: nil))
return
}
DispatchQueue.main.async { [weak self] in
self?.playerCore?.setVisible(visible)
// Update frame when becoming visible
if visible {
self?.playerCore?.updateFrame()
}
result(nil)
}
}
private func handleUpdateFrame(result: @escaping FlutterResult) {
DispatchQueue.main.async { [weak self] in
self?.playerCore?.updateFrame()
result(nil)
}
}
// MARK: - MpvPlayerDelegate
func onPropertyChange(name: String, value: Any?) {
guard let eventSink = eventSink else { return }
var event: [String: Any] = ["type": "property", "name": name]
if let value = value {
event["value"] = value
}
eventSink(event)
}
func onEvent(name: String, data: [String: Any]?) {
guard let eventSink = eventSink else { return }
var event: [String: Any] = ["type": "event", "name": name]
if let data = data {
event["data"] = data
}
eventSink(event)
}
// MARK: - Helpers
private func findKeyWindow() -> UIWindow? {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first(where: { $0.isKeyWindow }) else {
return nil
}
return window
}
}
+12533 -5827
View File
File diff suppressed because it is too large Load Diff
+47 -4
View File
@@ -44,7 +44,6 @@
},
"screens": {
"licenses": "Licenses",
"selectServer": "Select Server",
"switchProfile": "Switch Profile",
"subtitleStyling": "Subtitle Styling",
"search": "Search",
@@ -133,7 +132,14 @@
"validationErrorEnterNumber": "Please enter a valid number",
"validationErrorDuration": "Duration must be between ${min} and ${max} ${unit}",
"shortcutAlreadyAssigned": "Shortcut already assigned to ${action}",
"shortcutUpdated": "Shortcut updated for ${action}"
"shortcutUpdated": "Shortcut updated for ${action}",
"autoSkip": "Auto Skip",
"autoSkipIntro": "Auto Skip Intro",
"autoSkipIntroDescription": "Automatically skip intro markers after a few seconds",
"autoSkipCredits": "Auto Skip Credits",
"autoSkipCreditsDescription": "Automatically skip credits and play next episode",
"autoSkipDelay": "Auto Skip Delay",
"autoSkipDelayDescription": "Wait ${seconds} seconds before auto-skipping"
},
"search": {
"hint": "Search movies, shows, music...",
@@ -184,6 +190,16 @@
"shufflePlay": "Shuffle Play",
"fileInfo": "File Info"
},
"accessibility": {
"mediaCardMovie": "${title}, movie",
"mediaCardShow": "${title}, TV show",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "watched",
"mediaCardPartiallyWatched": "${percent} percent watched",
"mediaCardUnwatched": "unwatched",
"tapToPlay": "Tap to play"
},
"tooltips": {
"shufflePlay": "Shuffle play",
"markAsWatched": "Mark as watched",
@@ -206,7 +222,30 @@
"sleepTimer": "Sleep Timer",
"timerActive": "Timer Active",
"playbackWillPauseIn": "Playback will pause in ${duration}",
"sleepTimerCompleted": "Sleep timer completed - playback paused"
"sleepTimerCompleted": "Sleep timer completed - playback paused",
"playButton": "Play",
"pauseButton": "Pause",
"seekBackwardButton": "Seek backward ${seconds} seconds",
"seekForwardButton": "Seek forward ${seconds} seconds",
"previousButton": "Previous episode",
"nextButton": "Next episode",
"previousChapterButton": "Previous chapter",
"nextChapterButton": "Next chapter",
"volumeButton": "Volume",
"muteButton": "Mute",
"unmuteButton": "Unmute",
"settingsButton": "Video settings",
"audioTrackButton": "Audio tracks",
"subtitlesButton": "Subtitles",
"chaptersButton": "Chapters",
"versionsButton": "Video versions",
"aspectRatioButton": "Aspect ratio",
"fullscreenButton": "Enter fullscreen",
"exitFullscreenButton": "Exit fullscreen",
"rotationLockButton": "Rotation lock",
"timelineSlider": "Video timeline",
"volumeSlider": "Volume level",
"backButton": "Back"
},
"userStatus": {
"admin": "Admin",
@@ -267,7 +306,6 @@
"discover": {
"title": "Discover",
"switchProfile": "Switch Profile",
"switchServer": "Switch Server",
"logout": "Logout",
"noContentAvailable": "No content available",
"addMediaToLibraries": "Add some media to your libraries",
@@ -366,6 +404,11 @@
},
"serverSelection": {
"connectingToServer": "Connecting to server...",
"connectingToAllServers": "Connecting to all servers...",
"connectToAllServers": "Connect to All Servers",
"allServerConnectionsFailed": "Failed to connect to any servers. Please check your network and try again.",
"foundServers": "Found ${count} server(s)",
"orSelectIndividually": "Or select a server individually:",
"serverDebugCopied": "Server debug data copied to clipboard",
"copyDebugData": "Copy Debug Data",
"noServersFound": "No servers found",
+50 -5
View File
@@ -133,7 +133,14 @@
"validationErrorEnterNumber": "Bitte eine gültige Zahl eingeben",
"validationErrorDuration": "Dauer muss zwischen ${min} und ${max} ${unit} liegen",
"shortcutAlreadyAssigned": "Tastenkürzel bereits zugewiesen an ${action}",
"shortcutUpdated": "Tastenkürzel aktualisiert für ${action}"
"shortcutUpdated": "Tastenkürzel aktualisiert für ${action}",
"autoSkip": "Automatisches Überspringen",
"autoSkipIntro": "Intro automatisch überspringen",
"autoSkipIntroDescription": "Intro-Marker nach wenigen Sekunden automatisch überspringen",
"autoSkipCredits": "Abspann automatisch überspringen",
"autoSkipCreditsDescription": "Abspann automatisch überspringen und nächste Episode abspielen",
"autoSkipDelay": "Verzögerung für automatisches Überspringen",
"autoSkipDelayDescription": "${seconds} Sekunden vor dem automatischen Überspringen warten"
},
"search": {
"hint": "Filme, Serien, Musik suchen...",
@@ -184,6 +191,16 @@
"shufflePlay": "Zufallswiedergabe",
"fileInfo": "Dateiinfo"
},
"accessibility": {
"mediaCardMovie": "${title}, Film",
"mediaCardShow": "${title}, Serie",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "angesehen",
"mediaCardPartiallyWatched": "${percent} Prozent angesehen",
"mediaCardUnwatched": "ungeschaut",
"tapToPlay": "Zum Abspielen tippen"
},
"tooltips": {
"shufflePlay": "Zufallswiedergabe",
"markAsWatched": "Als gesehen markieren",
@@ -203,10 +220,33 @@
"stretch": "Strecken",
"lockRotation": "Rotation sperren",
"unlockRotation": "Rotation entsperren",
"sleepTimer": "Schlaf-Timer",
"timerActive": "Timer aktiv",
"playbackWillPauseIn": "Wiedergabe wird pausiert in ${duration}",
"sleepTimerCompleted": "Schlaf-Timer abgelaufen - Wiedergabe pausiert"
"sleepTimer": "Schlaftimer",
"timerActive": "Schlaftimer aktiv",
"playbackWillPauseIn": "Wiedergabe wird in ${duration} pausiert",
"sleepTimerCompleted": "Schlaftimer abgelaufen – Wiedergabe pausiert",
"playButton": "Wiedergeben",
"pauseButton": "Pause",
"seekBackwardButton": "${seconds} Sekunden zurück",
"seekForwardButton": "${seconds} Sekunden vor",
"previousButton": "Vorherige Episode",
"nextButton": "Nächste Episode",
"previousChapterButton": "Vorheriges Kapitel",
"nextChapterButton": "Nächstes Kapitel",
"volumeButton": "Lautstärke",
"muteButton": "Stumm schalten",
"unmuteButton": "Stummschaltung aufheben",
"settingsButton": "Videoeinstellungen",
"audioTrackButton": "Tonspuren",
"subtitlesButton": "Untertitel",
"chaptersButton": "Kapitel",
"versionsButton": "Videoversionen",
"aspectRatioButton": "Seitenverhältnis",
"fullscreenButton": "Vollbild aktivieren",
"exitFullscreenButton": "Vollbild verlassen",
"rotationLockButton": "Dreh­sperre",
"timelineSlider": "Video-Zeitleiste",
"volumeSlider": "Lautstärkepegel",
"backButton": "Zurück"
},
"userStatus": {
"admin": "Eigentümer",
@@ -366,6 +406,11 @@
},
"serverSelection": {
"connectingToServer": "Verbinde mit Server...",
"connectingToAllServers": "Verbinde mit allen Servern...",
"connectToAllServers": "Mit allen Servern verbinden",
"allServerConnectionsFailed": "Verbindung zu allen Servern fehlgeschlagen. Bitte Netzwerk prüfen und erneut versuchen.",
"foundServers": "${count} Server gefunden",
"orSelectIndividually": "Oder einzelnen Server auswählen:",
"serverDebugCopied": "Server-Debugdaten kopiert",
"copyDebugData": "Debugdaten kopieren",
"noServersFound": "Keine Server gefunden",
+52 -7
View File
@@ -48,7 +48,7 @@
"switchProfile": "Cambia profilo",
"subtitleStyling": "Stile sottotitoli",
"search": "Cerca",
"logs": "Logs"
"logs": "Registro"
},
"update": {
"available": "Aggiornamento disponibile",
@@ -133,7 +133,14 @@
"validationErrorEnterNumber": "Inserisci un numero valido",
"validationErrorDuration": "la durata deve essere compresa tra ${min} e ${max} ${unit}",
"shortcutAlreadyAssigned": "Scorciatoia già assegnata a ${action}",
"shortcutUpdated": "Scorciatoia aggiornata per ${action}"
"shortcutUpdated": "Scorciatoia aggiornata per ${action}",
"autoSkip": "Salto Automatico",
"autoSkipIntro": "Salta Intro Automaticamente",
"autoSkipIntroDescription": "Salta automaticamente i marcatori dell'intro dopo alcuni secondi",
"autoSkipCredits": "Salta Crediti Automaticamente",
"autoSkipCreditsDescription": "Salta automaticamente i crediti e riproduci l'episodio successivo",
"autoSkipDelay": "Ritardo Salto Automatico",
"autoSkipDelayDescription": "Aspetta ${seconds} secondi prima del salto automatico"
},
"search": {
"hint": "Cerca film. spettacoli, musica...",
@@ -184,6 +191,16 @@
"shufflePlay": "Riproduzione casuale",
"fileInfo": "Info sul file"
},
"accessibility": {
"mediaCardMovie": "${title}, film",
"mediaCardShow": "${title}, serie TV",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "visto",
"mediaCardPartiallyWatched": "${percent} percento visto",
"mediaCardUnwatched": "non visto",
"tapToPlay": "Tocca per riprodurre"
},
"tooltips": {
"shufflePlay": "Riproduzione casuale",
"markAsWatched": "Segna come visto",
@@ -197,7 +214,7 @@
"minusTime": "-${amount}${unit}",
"playsLater": "${label} riprodotto dopo",
"playsEarlier": "${label} riprodotto prima",
"noOffset": "No offset",
"noOffset": "Nessun offset",
"letterbox": "Letterbox",
"fillScreen": "Riempi schermo",
"stretch": "Allunga",
@@ -206,7 +223,30 @@
"sleepTimer": "Timer di spegnimento",
"timerActive": "Timer attivo",
"playbackWillPauseIn": "La riproduzione si interromperà tra ${duration}",
"sleepTimerCompleted": "Timer di spegnimento completato - riproduzione in pausa"
"sleepTimerCompleted": "Timer di spegnimento completato - riproduzione in pausa",
"playButton": "Riproduci",
"pauseButton": "Pausa",
"seekBackwardButton": "Riavvolgi di ${seconds} secondi",
"seekForwardButton": "Avanza di ${seconds} secondi",
"previousButton": "Episodio precedente",
"nextButton": "Episodio successivo",
"previousChapterButton": "Capitolo precedente",
"nextChapterButton": "Capitolo successivo",
"volumeButton": "Volume",
"muteButton": "Silenzia",
"unmuteButton": "Riattiva audio",
"settingsButton": "Impostazioni video",
"audioTrackButton": "Tracce audio",
"subtitlesButton": "Sottotitoli",
"chaptersButton": "Capitoli",
"versionsButton": "Versioni video",
"aspectRatioButton": "Proporzioni",
"fullscreenButton": "Attiva schermo intero",
"exitFullscreenButton": "Esci da schermo intero",
"rotationLockButton": "Blocco rotazione",
"timelineSlider": "Timeline video",
"volumeSlider": "Livello volume",
"backButton": "Indietro"
},
"userStatus": {
"admin": "Admin",
@@ -265,7 +305,7 @@
"playNow": "Riproduci ora"
},
"discover": {
"title": "Discover",
"title": "Esplora",
"switchProfile": "Cambia profilo",
"switchServer": "Cambia server",
"logout": "Disconnetti",
@@ -279,7 +319,7 @@
"resumeEpisode": "Riprendi S${season}, E${episode}",
"pause": "Pausa",
"overview": "Panoramica",
"cast": "Cast",
"cast": "Attori",
"seasons": "Stagioni",
"studio": "Studio",
"rating": "Classificazione",
@@ -366,6 +406,11 @@
},
"serverSelection": {
"connectingToServer": "Connessione al server...",
"connectingToAllServers": "Connessione a tutti i server...",
"connectToAllServers": "Connetti a tutti i server",
"allServerConnectionsFailed": "Impossibile connettersi a nessun server. Controlla la tua rete e riprova.",
"foundServers": "Trovati ${count} server",
"orSelectIndividually": "Oppure seleziona un server singolarmente:",
"serverDebugCopied": "Dati di debug del server copiati negli appunti",
"copyDebugData": "Copia dati di debug",
"noServersFound": "Nessun server trovato",
@@ -386,7 +431,7 @@
"noItemsFound": "Nessun elemento trovato"
},
"logs": {
"title": "Log",
"title": "Registro",
"clearLogs": "Cancella log",
"copyLogs": "Copia log",
"exportLogs": "Esporta log",
+55 -10
View File
@@ -10,7 +10,7 @@
"authenticate": "Authenticeren",
"retry": "Opnieuw proberen",
"debugEnterToken": "Debug: Voer Plex Token in",
"plexTokenLabel": "Plex Auth Token",
"plexTokenLabel": "Plex Authenticatietoken",
"plexTokenHint": "Voer je Plex.tv token in",
"authenticationTimeout": "Authenticatie verlopen. Probeer opnieuw.",
"scanQRCodeInstruction": "Scan deze QR-code met een apparaat dat is ingelogd op Plex om te authenticeren.",
@@ -39,7 +39,7 @@
"no": "Nee",
"server": "Server",
"delete": "Verwijderen",
"shuffle": "Shuffle",
"shuffle": "Willekeurig",
"addTo": "Toevoegen aan..."
},
"screens": {
@@ -48,7 +48,7 @@
"switchProfile": "Wissel van profiel",
"subtitleStyling": "Ondertitel opmaak",
"search": "Zoeken",
"logs": "Logs"
"logs": "Logbestanden"
},
"update": {
"available": "Update beschikbaar",
@@ -133,7 +133,14 @@
"validationErrorEnterNumber": "Voer een geldig nummer in",
"validationErrorDuration": "Duur moet tussen ${min} en ${max} ${unit} zijn",
"shortcutAlreadyAssigned": "Sneltoets al toegewezen aan ${action}",
"shortcutUpdated": "Sneltoets bijgewerkt voor ${action}"
"shortcutUpdated": "Sneltoets bijgewerkt voor ${action}",
"autoSkip": "Automatisch Overslaan",
"autoSkipIntro": "Intro Automatisch Overslaan",
"autoSkipIntroDescription": "Intro-markeringen na enkele seconden automatisch overslaan",
"autoSkipCredits": "Credits Automatisch Overslaan",
"autoSkipCreditsDescription": "Credits automatisch overslaan en volgende aflevering afspelen",
"autoSkipDelay": "Vertraging Automatisch Overslaan",
"autoSkipDelayDescription": "${seconds} seconden wachten voor automatisch overslaan"
},
"search": {
"hint": "Zoek films, series, muziek...",
@@ -184,6 +191,16 @@
"shufflePlay": "Willekeurig afspelen",
"fileInfo": "Bestand info"
},
"accessibility": {
"mediaCardMovie": "${title}, film",
"mediaCardShow": "${title}, TV-serie",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "bekeken",
"mediaCardPartiallyWatched": "${percent} procent bekeken",
"mediaCardUnwatched": "niet bekeken",
"tapToPlay": "Tik om af te spelen"
},
"tooltips": {
"shufflePlay": "Willekeurig afspelen",
"markAsWatched": "Markeer als gekeken",
@@ -206,7 +223,30 @@
"sleepTimer": "Slaaptimer",
"timerActive": "Timer actief",
"playbackWillPauseIn": "Afspelen wordt gepauzeerd over ${duration}",
"sleepTimerCompleted": "Slaaptimer voltooid - afspelen gepauzeerd"
"sleepTimerCompleted": "Slaaptimer voltooid - afspelen gepauzeerd",
"playButton": "Afspelen",
"pauseButton": "Pauzeren",
"seekBackwardButton": "Terugspoelen ${seconds} seconden",
"seekForwardButton": "Vooruitspoelen ${seconds} seconden",
"previousButton": "Vorige aflevering",
"nextButton": "Volgende aflevering",
"previousChapterButton": "Vorig hoofdstuk",
"nextChapterButton": "Volgend hoofdstuk",
"volumeButton": "Volume",
"muteButton": "Dempen",
"unmuteButton": "Dempen opheffen",
"settingsButton": "Video-instellingen",
"audioTrackButton": "Audiosporen",
"subtitlesButton": "Ondertitels",
"chaptersButton": "Hoofdstukken",
"versionsButton": "Videoversies",
"aspectRatioButton": "Beeldverhouding",
"fullscreenButton": "Volledig scherm activeren",
"exitFullscreenButton": "Volledig scherm verlaten",
"rotationLockButton": "Rotatievergrendeling",
"timelineSlider": "Videotijdlijn",
"volumeSlider": "Volumeniveau",
"backButton": "Terug"
},
"userStatus": {
"admin": "Beheerder",
@@ -279,7 +319,7 @@
"resumeEpisode": "Hervat S${season}, E${episode}",
"pause": "Pauzeren",
"overview": "Overzicht",
"cast": "Cast",
"cast": "Acteurs",
"seasons": "Seizoenen",
"studio": "Studio",
"rating": "Leeftijd",
@@ -366,6 +406,11 @@
},
"serverSelection": {
"connectingToServer": "Verbinden met server...",
"connectingToAllServers": "Verbinden met alle servers...",
"connectToAllServers": "Verbind met alle servers",
"allServerConnectionsFailed": "Kon niet verbinden met servers. Controleer je netwerk en probeer opnieuw.",
"foundServers": "${count} server(s) gevonden",
"orSelectIndividually": "Of selecteer een server individueel:",
"serverDebugCopied": "Server debug gegevens gekopieerd naar klembord",
"copyDebugData": "Kopieer debug gegevens",
"noServersFound": "Geen servers gevonden",
@@ -386,13 +431,13 @@
"noItemsFound": "Geen items gevonden"
},
"logs": {
"title": "Logs",
"title": "Logbestanden",
"clearLogs": "Wis logs",
"copyLogs": "Kopieer logs",
"exportLogs": "Exporteer logs",
"noLogsToShow": "Geen logs om te tonen",
"error": "Fout:",
"stackTrace": "Stack Trace:"
"stackTrace": "Stacktracering:"
},
"licenses": {
"relatedPackages": "Gerelateerde pakketten",
@@ -401,7 +446,7 @@
"licensesCount": "${count} licenties"
},
"navigation": {
"home": "Home",
"home": "Thuis",
"search": "Zoeken",
"libraries": "Bibliotheken",
"settings": "Instellingen"
@@ -420,7 +465,7 @@
"removeItem": "Verwijderen uit afspeellijst",
"clearPlaylist": "Afspeellijst wissen",
"playAll": "Alles afspelen",
"shuffle": "Shuffle",
"shuffle": "Willekeurig",
"smartPlaylist": "Slimme afspeellijst",
"regularPlaylist": "Normale afspeellijst",
"itemCount": "${count} items",
+47 -2
View File
@@ -133,7 +133,14 @@
"validationErrorEnterNumber": "Vänligen ange ett giltigt nummer",
"validationErrorDuration": "Tiden måste vara mellan ${min} och ${max} ${unit}",
"shortcutAlreadyAssigned": "Genväg redan tilldelad ${action}",
"shortcutUpdated": "Genväg uppdaterad för ${action}"
"shortcutUpdated": "Genväg uppdaterad för ${action}",
"autoSkip": "Auto Hoppa Över",
"autoSkipIntro": "Hoppa Över Intro Automatiskt",
"autoSkipIntroDescription": "Hoppa automatiskt över intro-markörer efter några sekunder",
"autoSkipCredits": "Hoppa Över Credits Automatiskt",
"autoSkipCreditsDescription": "Hoppa automatiskt över credits och spela nästa avsnitt",
"autoSkipDelay": "Fördröjning Auto Hoppa Över",
"autoSkipDelayDescription": "Vänta ${seconds} sekunder innan automatisk överhoppning"
},
"search": {
"hint": "Sök filmer, serier, musik...",
@@ -184,6 +191,16 @@
"shufflePlay": "Blanda uppspelning",
"fileInfo": "Filinformation"
},
"accessibility": {
"mediaCardMovie": "${title}, film",
"mediaCardShow": "${title}, TV-serie",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "sedd",
"mediaCardPartiallyWatched": "${percent} procent sedd",
"mediaCardUnwatched": "osedd",
"tapToPlay": "Tryck för att spela"
},
"tooltips": {
"shufflePlay": "Blanda uppspelning",
"markAsWatched": "Markera som sedd",
@@ -206,7 +223,30 @@
"sleepTimer": "Sovtimer",
"timerActive": "Timer aktiv",
"playbackWillPauseIn": "Uppspelningen pausas om ${duration}",
"sleepTimerCompleted": "Sovtimer slutförd - uppspelning pausad"
"sleepTimerCompleted": "Sovtimer slutförd - uppspelning pausad",
"playButton": "Spela",
"pauseButton": "Pausa",
"seekBackwardButton": "Spola bakåt ${seconds} sekunder",
"seekForwardButton": "Spola framåt ${seconds} sekunder",
"previousButton": "Föregående avsnitt",
"nextButton": "Nästa avsnitt",
"previousChapterButton": "Föregående kapitel",
"nextChapterButton": "Nästa kapitel",
"volumeButton": "Volym",
"muteButton": "Tysta",
"unmuteButton": "Slå på ljud",
"settingsButton": "Videoinställningar",
"audioTrackButton": "Ljudspår",
"subtitlesButton": "Undertexter",
"chaptersButton": "Kapitel",
"versionsButton": "Videoversioner",
"aspectRatioButton": "Bildförhållande",
"fullscreenButton": "Aktivera helskärm",
"exitFullscreenButton": "Avsluta helskärm",
"rotationLockButton": "Rotationslås",
"timelineSlider": "Videotidslinje",
"volumeSlider": "Volymnivå",
"backButton": "Tillbaka"
},
"userStatus": {
"admin": "Admin",
@@ -366,6 +406,11 @@
},
"serverSelection": {
"connectingToServer": "Ansluter till server...",
"connectingToAllServers": "Ansluter till alla servrar...",
"connectToAllServers": "Anslut till alla servrar",
"allServerConnectionsFailed": "Misslyckades att ansluta till servrar. Kontrollera ditt nätverk och försök igen.",
"foundServers": "Hittade ${count} server(ar)",
"orSelectIndividually": "Eller välj en server individuellt:",
"serverDebugCopied": "Server-felsökningsdata kopierad till urklipp",
"copyDebugData": "Kopiera felsökningsdata",
"noServersFound": "Inga servrar hittades",
+47 -2
View File
@@ -133,7 +133,14 @@
"validationErrorEnterNumber": "请输入一个有效的数字",
"validationErrorDuration": "时长必须介于 ${min} 和 ${max} ${unit} 之间",
"shortcutAlreadyAssigned": "快捷键已被分配给 ${action}",
"shortcutUpdated": "快捷键已为 ${action} 更新"
"shortcutUpdated": "快捷键已为 ${action} 更新",
"autoSkip": "自动跳过",
"autoSkipIntro": "自动跳过片头",
"autoSkipIntroDescription": "几秒钟后自动跳过片头标记",
"autoSkipCredits": "自动跳过片尾",
"autoSkipCreditsDescription": "自动跳过片尾并播放下一集",
"autoSkipDelay": "自动跳过延迟",
"autoSkipDelayDescription": "自动跳过前等待 ${seconds} 秒"
},
"search": {
"hint": "搜索电影、系列、音乐...",
@@ -184,6 +191,16 @@
"shufflePlay": "随机播放",
"fileInfo": "文件信息"
},
"accessibility": {
"mediaCardMovie": "${title}, 电影",
"mediaCardShow": "${title}, 电视剧",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "已观看",
"mediaCardPartiallyWatched": "已观看 ${percent} 百分比",
"mediaCardUnwatched": "未观看",
"tapToPlay": "点击播放"
},
"tooltips": {
"shufflePlay": "随机播放",
"markAsWatched": "标记为已观看",
@@ -206,7 +223,30 @@
"sleepTimer": "睡眠定时器",
"timerActive": "定时器已激活",
"playbackWillPauseIn": "播放将在 ${duration} 后暂停",
"sleepTimerCompleted": "睡眠定时器已完成 - 播放已暂停"
"sleepTimerCompleted": "睡眠定时器已完成 - 播放已暂停",
"playButton": "播放",
"pauseButton": "暂停",
"seekBackwardButton": "后退 ${seconds} 秒",
"seekForwardButton": "前进 ${seconds} 秒",
"previousButton": "上一集",
"nextButton": "下一集",
"previousChapterButton": "上一章节",
"nextChapterButton": "下一章节",
"volumeButton": "音量",
"muteButton": "静音",
"unmuteButton": "取消静音",
"settingsButton": "视频设置",
"audioTrackButton": "音轨",
"subtitlesButton": "字幕",
"chaptersButton": "章节",
"versionsButton": "视频版本",
"aspectRatioButton": "宽高比",
"fullscreenButton": "进入全屏",
"exitFullscreenButton": "退出全屏",
"rotationLockButton": "旋转锁定",
"timelineSlider": "视频时间轴",
"volumeSlider": "音量调节",
"backButton": "返回"
},
"userStatus": {
"admin": "管理员",
@@ -366,6 +406,11 @@
},
"serverSelection": {
"connectingToServer": "正在连接服务器...",
"connectingToAllServers": "正在连接所有服务器...",
"connectToAllServers": "连接所有服务器",
"allServerConnectionsFailed": "无法连接到任何服务器。请检查你的网络并重试。",
"foundServers": "找到 ${count} 个服务器",
"orSelectIndividually": "或单独选择一个服务器:",
"serverDebugCopied": "服务器调试数据已复制到剪贴板",
"copyDebugData": "复制调试数据",
"noServersFound": "未找到服务器",
+126 -93
View File
@@ -1,28 +1,29 @@
import 'package:flutter/material.dart';
import 'dart:io' show Platform;
import 'package:media_kit/media_kit.dart';
import 'package:window_manager/window_manager.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'screens/main_screen.dart';
import 'screens/auth_screen.dart';
import 'services/storage_service.dart';
import 'services/plex_auth_service.dart';
import 'services/server_connection_service.dart';
import 'services/macos_titlebar_service.dart';
import 'services/fullscreen_state_manager.dart';
import 'services/update_service.dart';
import 'services/settings_service.dart';
import 'providers/user_profile_provider.dart';
import 'providers/plex_client_provider.dart';
import 'providers/multi_server_provider.dart';
import 'providers/server_state_provider.dart';
import 'providers/theme_provider.dart';
import 'providers/settings_provider.dart';
import 'providers/hidden_libraries_provider.dart';
import 'providers/playback_state_provider.dart';
import 'utils/language_codes.dart';
import 'services/multi_server_manager.dart';
import 'services/data_aggregation_service.dart';
import 'services/server_registry.dart';
import 'utils/app_logger.dart';
import 'utils/provider_extensions.dart';
import 'utils/orientation_helper.dart';
import 'utils/language_codes.dart';
import 'i18n/strings.g.dart';
void main() async {
@@ -36,26 +37,27 @@ void main() async {
LocaleSettings.setLocale(savedLocale);
// Configure image cache for large libraries
PaintingBinding.instance.imageCache.maximumSizeBytes = 500 << 20; // 500MB
PaintingBinding.instance.imageCache.maximumSize = 500; // 500 images
PaintingBinding.instance.imageCache.maximumSizeBytes = 200 << 20; // 200MB
// Initialize services in parallel where possible
final futures = <Future<void>>[];
// Initialize window_manager for desktop platforms
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
await windowManager.ensureInitialized();
futures.add(windowManager.ensureInitialized());
}
// Configure macOS window with custom titlebar
await MacOSTitlebarService.setupCustomTitlebar();
// Configure macOS window with custom titlebar (depends on window manager)
futures.add(MacOSTitlebarService.setupCustomTitlebar());
// Initialize MediaKit
MediaKit.ensureInitialized();
// Note: Orientation will be set dynamically based on device type in MainApp
await StorageService.getInstance();
// Initialize storage service
futures.add(StorageService.getInstance().then((_) {}));
// Initialize language codes for track selection
await LanguageCodes.initialize();
futures.add(LanguageCodes.initialize());
// Wait for all parallel services to complete
await Future.wait(futures);
// Initialize logger level based on debug setting
final debugEnabled = settings.getEnableDebugLogging();
@@ -77,15 +79,31 @@ class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Initialize multi-server infrastructure
final serverManager = MultiServerManager();
final aggregationService = DataAggregationService(serverManager);
return MultiProvider(
providers: [
// Legacy provider for backward compatibility
ChangeNotifierProvider(create: (context) => PlexClientProvider()),
// New multi-server providers
ChangeNotifierProvider(
create: (context) => UserProfileProvider()..initialize(),
create: (context) =>
MultiServerProvider(serverManager, aggregationService),
),
ChangeNotifierProvider(create: (context) => ServerStateProvider()),
// Existing providers
ChangeNotifierProvider(create: (context) => UserProfileProvider()),
ChangeNotifierProvider(create: (context) => ThemeProvider()),
ChangeNotifierProvider(create: (context) => SettingsProvider()),
ChangeNotifierProvider(create: (context) => HiddenLibrariesProvider()),
ChangeNotifierProvider(
create: (context) => SettingsProvider(),
lazy: true,
),
ChangeNotifierProvider(
create: (context) => HiddenLibrariesProvider(),
lazy: true,
),
ChangeNotifierProvider(create: (context) => PlaybackStateProvider()),
],
child: Consumer<ThemeProvider>(
@@ -145,7 +163,7 @@ class _SetupScreenState extends State<SetupScreen> {
_loadSavedCredentials();
}
void _checkForUpdatesOnStartup() async {
Future<void> _checkForUpdatesOnStartup() async {
// Delay slightly to allow UI to settle
await Future.delayed(const Duration(milliseconds: 500));
@@ -219,86 +237,101 @@ class _SetupScreenState extends State<SetupScreen> {
Future<void> _loadSavedCredentials() async {
final storage = await StorageService.getInstance();
final registry = ServerRegistry(storage);
// Check if we have server data
final serverData = storage.getServerData();
final clientId = storage.getClientIdentifier();
final plexToken = storage.getPlexToken();
// Migrate from single-server to multi-server if needed
await registry.migrateFromSingleServer();
// Get current user's server token (prioritize over original server token)
final currentUserToken = storage.getToken();
// Load enabled servers
final servers = await registry.getEnabledServers();
if (serverData != null && clientId != null) {
try {
// Recreate PlexServer from stored data
final server = PlexServer.fromJson(serverData);
// Use current user's token if available, fallback to server's original token
final tokenToUse = currentUserToken ?? server.accessToken;
appLogger.d(
'App startup token selection: currentUserToken=${currentUserToken != null ? 'present' : 'null'}, using=${currentUserToken != null ? 'current user' : 'original server'} token',
if (servers.isEmpty) {
// No servers configured - show auth screen
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const AuthScreen()),
);
// Create updated server with correct token for current user
final serverWithCurrentToken = PlexServer(
name: server.name,
clientIdentifier: server.clientIdentifier,
accessToken: tokenToUse,
connections: server.connections,
owned: server.owned,
product: server.product,
platform: server.platform,
lastSeenAt: server.lastSeenAt,
presence: server.presence,
);
// Connect using the optimized service with current user's token
final result = await ServerConnectionService.connectToServer(
serverWithCurrentToken,
clientIdentifier: clientId,
verifyServer: true,
fetchUserProfile: plexToken != null,
plexToken: plexToken,
);
// Handle result
if (result.isSuccess) {
// Success! Set client in provider
if (mounted) {
context.plexClient.setClient(result.client!);
// Check for updates BEFORE navigation to keep context valid
_checkForUpdatesOnStartup();
// Navigate to main screen after update check is initiated
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: result.client!),
),
);
}
}
return;
} else {
// Connection failed, clear credentials
await storage.clearCredentials();
}
} catch (e) {
// Error loading or testing server
appLogger.e('Error during auto-login', error: e);
await storage.clearCredentials();
}
return;
}
// No saved credentials or auto-login failed - show auth screen
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const AuthScreen()),
// Get multi-server provider
if (!mounted) return;
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
try {
appLogger.i('Connecting to ${servers.length} enabled servers...');
// Get or generate client identifier
final clientId = storage.getClientIdentifier();
// Connect to all servers in parallel
final connectedCount = await multiServerProvider.serverManager
.connectToAllServers(
servers,
clientIdentifier: clientId,
timeout: const Duration(seconds: 10),
onServerConnected: (serverId, client) {
// Set first connected client in legacy provider for backward compatibility
final legacyProvider = Provider.of<PlexClientProvider>(
context,
listen: false,
);
if (legacyProvider.client == null) {
legacyProvider.setClient(client);
}
},
);
if (connectedCount > 0) {
// At least one server connected successfully
appLogger.i('Successfully connected to $connectedCount servers');
if (mounted) {
// Navigate to main screen immediately
// Get first connected client for backward compatibility
final firstClient =
multiServerProvider.serverManager.onlineClients.values.first;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: firstClient),
),
);
// Check for updates in background after navigation
_checkForUpdatesOnStartup();
}
} else {
// All connections failed
appLogger.w('Failed to connect to any servers');
if (mounted) {
// Show auth screen to re-authenticate
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const AuthScreen()),
);
}
}
} catch (e, stackTrace) {
appLogger.e(
'Error during multi-server connection',
error: e,
stackTrace: stackTrace,
);
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const AuthScreen()),
);
}
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../services/plex_client.dart';
import '../models/plex_metadata.dart';
/// Mixin for screens that need to update individual items after watch state changes
+102
View File
@@ -0,0 +1,102 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/keyboard_utils.dart';
/// A mixin that provides keyboard long-press detection for focusable widgets.
///
/// This allows keyboard/gamepad users to access context menus by holding
/// the activation key (Enter, Space, Select, or GameButtonA) for 1 second.
///
/// Usage:
/// ```dart
/// class _MyWidgetState extends State<MyWidget> with KeyboardLongPressMixin {
/// @override
/// void onKeyboardTap() {
/// // Handle short press (normal tap)
/// }
///
/// @override
/// void onKeyboardLongPress() {
/// // Handle long press (show context menu)
/// }
///
/// KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
/// final result = handleKeyboardLongPress(event);
/// if (result == KeyEventResult.handled) return result;
/// // Handle other keys...
/// return KeyEventResult.ignored;
/// }
/// }
/// ```
mixin KeyboardLongPressMixin<T extends StatefulWidget> on State<T> {
Timer? _longPressTimer;
LogicalKeyboardKey? _pressedKey;
bool _longPressTriggered = false;
static const _longPressDuration = Duration(seconds: 1);
/// Override to handle tap action (short press)
void onKeyboardTap();
/// Override to handle long press action (e.g., show context menu)
void onKeyboardLongPress();
/// Call this from your onKeyEvent handler to enable long-press detection.
/// Returns [KeyEventResult.handled] if the event was an activation key,
/// [KeyEventResult.ignored] otherwise.
KeyEventResult handleKeyboardLongPress(KeyEvent event) {
if (!isKeyboardActivationKey(event.logicalKey)) {
return KeyEventResult.ignored;
}
if (event is KeyDownEvent) {
// Only start timer on initial press (not key repeat)
if (_pressedKey == null) {
_pressedKey = event.logicalKey;
_longPressTriggered = false;
_longPressTimer = Timer(_longPressDuration, () {
_longPressTriggered = true;
onKeyboardLongPress();
});
}
return KeyEventResult.handled;
}
// Handle key repeat events (suppress system sound on macOS)
if (event is KeyRepeatEvent) {
return KeyEventResult.handled;
}
if (event is KeyUpEvent && event.logicalKey == _pressedKey) {
_longPressTimer?.cancel();
_longPressTimer = null;
_pressedKey = null;
// Only trigger tap if long press wasn't already triggered
if (!_longPressTriggered) {
onKeyboardTap();
}
_longPressTriggered = false;
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Cancel any pending long-press timer. Call this if focus is lost
/// or the widget is being disposed while a key is held.
void cancelKeyboardLongPress() {
_longPressTimer?.cancel();
_longPressTimer = null;
_pressedKey = null;
_longPressTriggered = false;
}
@override
void dispose() {
_longPressTimer?.cancel();
super.dispose();
}
}
+7 -55
View File
@@ -1,63 +1,15 @@
import 'package:flutter/material.dart';
import '../services/plex_client.dart';
import '../models/plex_library.dart';
import '../models/plex_metadata.dart';
import '../utils/provider_extensions.dart';
/// Mixin providing common state management for library tab screens
/// Standardizes loading, error handling, and lifecycle management
/// Mixin providing common functionality for library tab screens
/// Provides server-specific client resolution for multi-server support
mixin LibraryTabStateMixin<T extends StatefulWidget> on State<T> {
/// The list of items to display
List<PlexMetadata> get items;
set items(List<PlexMetadata> value);
/// Whether data is currently loading
bool get isLoading;
set isLoading(bool value);
/// Error message if loading failed
String? get errorMessage;
set errorMessage(String? value);
/// The library being displayed
PlexLibrary get library;
/// Load or reload the content
Future<void> loadContent();
/// Common lifecycle: reload if library changed
@mustCallSuper
void didUpdateLibrary(PlexLibrary oldLibrary) {
if (oldLibrary.key != library.key) {
loadContent();
}
}
/// Helper to set loading state
void setLoadingState(bool loading) {
if (mounted) {
setState(() {
isLoading = loading;
});
}
}
/// Helper to set error state
void setErrorState(String? error) {
if (mounted) {
setState(() {
errorMessage = error;
isLoading = false;
});
}
}
/// Helper to set success state with items
void setSuccessState(List<PlexMetadata> newItems) {
if (mounted) {
setState(() {
items = newItems;
isLoading = false;
errorMessage = null;
});
}
}
/// Get the correct PlexClient for this library's server
/// Throws an exception if no client is available
PlexClient getClientForLibrary() => context.getClientForLibrary(library);
}
-31
View File
@@ -1,31 +0,0 @@
import 'package:json_annotation/json_annotation.dart';
import 'plex_metadata.dart';
import 'plex_library.dart';
part 'media_container.g.dart';
@JsonSerializable()
class MediaContainer<T> {
final int? size;
final int? totalSize;
final int? offset;
final String? identifier;
@JsonKey(name: 'Directory')
final List<PlexLibrary>? directories;
@JsonKey(name: 'Metadata')
final List<PlexMetadata>? metadata;
MediaContainer({
this.size,
this.totalSize,
this.offset,
this.identifier,
this.directories,
this.metadata,
});
factory MediaContainer.fromJson(Map<String, dynamic> json) =>
_$MediaContainerFromJson(json);
Map<String, dynamic> toJson() => _$MediaContainerToJson(this);
}
-31
View File
@@ -1,31 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'media_container.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
MediaContainer<T> _$MediaContainerFromJson<T>(Map<String, dynamic> json) =>
MediaContainer<T>(
size: (json['size'] as num?)?.toInt(),
totalSize: (json['totalSize'] as num?)?.toInt(),
offset: (json['offset'] as num?)?.toInt(),
identifier: json['identifier'] as String?,
directories: (json['Directory'] as List<dynamic>?)
?.map((e) => PlexLibrary.fromJson(e as Map<String, dynamic>))
.toList(),
metadata: (json['Metadata'] as List<dynamic>?)
?.map((e) => PlexMetadata.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> _$MediaContainerToJson<T>(MediaContainer<T> instance) =>
<String, dynamic>{
'size': instance.size,
'totalSize': instance.totalSize,
'offset': instance.offset,
'identifier': instance.identifier,
'Directory': instance.directories,
'Metadata': instance.metadata,
};
@@ -0,0 +1,15 @@
import 'package:json_annotation/json_annotation.dart';
/// Mixin that provides multi-server support fields for models.
///
/// This mixin adds serverId and serverName fields that are excluded from
/// JSON serialization but can be used to track which server an item belongs to.
mixin MultiServerFields {
/// Server machine identifier (not from API)
@JsonKey(includeFromJson: false, includeToJson: false)
String? get serverId;
/// Server display name (not from API)
@JsonKey(includeFromJson: false, includeToJson: false)
String? get serverName;
}
+30 -2
View File
@@ -49,10 +49,38 @@ class PlayQueueResponse {
this.items,
});
factory PlayQueueResponse.fromJson(Map<String, dynamic> json) {
factory PlayQueueResponse.fromJson(
Map<String, dynamic> json, {
String? serverId,
String? serverName,
}) {
// The API returns data wrapped in MediaContainer
final container = json['MediaContainer'] as Map<String, dynamic>? ?? json;
return _$PlayQueueResponseFromJson(container);
final response = _$PlayQueueResponseFromJson(container);
// Tag all items with server info
if (response.items != null && (serverId != null || serverName != null)) {
final taggedItems = response.items!
.map(
(item) => item.copyWith(serverId: serverId, serverName: serverName),
)
.toList();
return PlayQueueResponse(
playQueueID: response.playQueueID,
playQueueSelectedItemID: response.playQueueSelectedItemID,
playQueueSelectedItemOffset: response.playQueueSelectedItemOffset,
playQueueSelectedMetadataItemID:
response.playQueueSelectedMetadataItemID,
playQueueShuffled: response.playQueueShuffled,
playQueueSourceURI: response.playQueueSourceURI,
playQueueTotalCount: response.playQueueTotalCount,
playQueueVersion: response.playQueueVersion,
size: response.size,
items: taggedItems,
);
}
return response;
}
/// Get the current selected item from the queue
+6
View File
@@ -10,6 +10,10 @@ class PlexHub {
final bool more;
final List<PlexMetadata> items;
// Multi-server support fields
final String? serverId; // Server machine identifier
final String? serverName; // Server display name
PlexHub({
required this.hubKey,
required this.title,
@@ -18,6 +22,8 @@ class PlexHub {
required this.size,
required this.more,
required this.items,
this.serverId,
this.serverName,
});
factory PlexHub.fromJson(Map<String, dynamic> json) {
+47 -1
View File
@@ -1,9 +1,11 @@
import 'package:json_annotation/json_annotation.dart';
import 'mixins/multi_server_fields.dart';
part 'plex_library.g.dart';
@JsonSerializable()
class PlexLibrary {
class PlexLibrary with MultiServerFields {
final String key;
final String title;
final String type;
@@ -15,6 +17,17 @@ class PlexLibrary {
final int? createdAt;
final int? hidden;
// Multi-server support fields (from MultiServerFields mixin)
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverId;
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverName;
/// Global unique identifier across all servers (serverId:key)
String get globalKey => serverId != null ? '$serverId:$key' : key;
PlexLibrary({
required this.key,
required this.title,
@@ -26,10 +39,43 @@ class PlexLibrary {
this.updatedAt,
this.createdAt,
this.hidden,
this.serverId,
this.serverName,
});
factory PlexLibrary.fromJson(Map<String, dynamic> json) =>
_$PlexLibraryFromJson(json);
Map<String, dynamic> toJson() => _$PlexLibraryToJson(this);
/// Create a copy of this library with optional field overrides
PlexLibrary copyWith({
String? key,
String? title,
String? type,
String? agent,
String? scanner,
String? language,
String? uuid,
int? updatedAt,
int? createdAt,
int? hidden,
String? serverId,
String? serverName,
}) {
return PlexLibrary(
key: key ?? this.key,
title: title ?? this.title,
type: type ?? this.type,
agent: agent ?? this.agent,
scanner: scanner ?? this.scanner,
language: language ?? this.language,
uuid: uuid ?? this.uuid,
updatedAt: updatedAt ?? this.updatedAt,
createdAt: createdAt ?? this.createdAt,
hidden: hidden ?? this.hidden,
serverId: serverId ?? this.serverId,
serverName: serverName ?? this.serverName,
);
}
}
+3
View File
@@ -3,13 +3,16 @@ class PlexMediaInfo {
final List<PlexAudioTrack> audioTracks;
final List<PlexSubtitleTrack> subtitleTracks;
final List<PlexChapter> chapters;
final int? partId;
PlexMediaInfo({
required this.videoUrl,
required this.audioTracks,
required this.subtitleTracks,
required this.chapters,
this.partId,
});
int? getPartId() => partId;
}
/// Mixin for building track labels with a consistent pattern
+23 -1
View File
@@ -1,11 +1,12 @@
import 'package:json_annotation/json_annotation.dart';
import 'mixins/multi_server_fields.dart';
import 'plex_role.dart';
part 'plex_metadata.g.dart';
@JsonSerializable()
class PlexMetadata {
class PlexMetadata with MultiServerFields {
final String ratingKey;
final String key;
final String? guid;
@@ -22,6 +23,7 @@ class PlexMetadata {
final int? duration;
final int? addedAt;
final int? updatedAt;
final int? lastViewedAt; // Timestamp when item was last viewed
final String? grandparentTitle; // Show title for episodes
final String? grandparentThumb; // Show poster for episodes
final String? grandparentArt; // Show art for episodes
@@ -45,10 +47,21 @@ class PlexMetadata {
final int? playQueueItemID; // Play queue item ID (unique even for duplicates)
final int? librarySectionID; // Library section ID this item belongs to
// Multi-server support fields (from MultiServerFields mixin)
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverId;
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverName;
// Transient field for clear logo (extracted from Image array)
String? _clearLogo;
String? get clearLogo => _clearLogo;
/// Global unique identifier across all servers (serverId:ratingKey)
String get globalKey => serverId != null ? '$serverId:$ratingKey' : ratingKey;
PlexMetadata({
required this.ratingKey,
required this.key,
@@ -66,6 +79,7 @@ class PlexMetadata {
this.duration,
this.addedAt,
this.updatedAt,
this.lastViewedAt,
this.grandparentTitle,
this.grandparentThumb,
this.grandparentArt,
@@ -87,6 +101,8 @@ class PlexMetadata {
this.playlistItemID,
this.playQueueItemID,
this.librarySectionID,
this.serverId,
this.serverName,
});
/// Create a copy of this metadata with optional field overrides
@@ -107,6 +123,7 @@ class PlexMetadata {
int? duration,
int? addedAt,
int? updatedAt,
int? lastViewedAt,
String? grandparentTitle,
String? grandparentThumb,
String? grandparentArt,
@@ -128,6 +145,8 @@ class PlexMetadata {
int? playlistItemID,
int? playQueueItemID,
int? librarySectionID,
String? serverId,
String? serverName,
}) {
final copy = PlexMetadata(
ratingKey: ratingKey ?? this.ratingKey,
@@ -146,6 +165,7 @@ class PlexMetadata {
duration: duration ?? this.duration,
addedAt: addedAt ?? this.addedAt,
updatedAt: updatedAt ?? this.updatedAt,
lastViewedAt: lastViewedAt ?? this.lastViewedAt,
grandparentTitle: grandparentTitle ?? this.grandparentTitle,
grandparentThumb: grandparentThumb ?? this.grandparentThumb,
grandparentArt: grandparentArt ?? this.grandparentArt,
@@ -167,6 +187,8 @@ class PlexMetadata {
playlistItemID: playlistItemID ?? this.playlistItemID,
playQueueItemID: playQueueItemID ?? this.playQueueItemID,
librarySectionID: librarySectionID ?? this.librarySectionID,
serverId: serverId ?? this.serverId,
serverName: serverName ?? this.serverName,
);
// Preserve clearLogo
copy._clearLogo = _clearLogo;
+2
View File
@@ -23,6 +23,7 @@ PlexMetadata _$PlexMetadataFromJson(Map<String, dynamic> json) => PlexMetadata(
duration: (json['duration'] as num?)?.toInt(),
addedAt: (json['addedAt'] as num?)?.toInt(),
updatedAt: (json['updatedAt'] as num?)?.toInt(),
lastViewedAt: (json['lastViewedAt'] as num?)?.toInt(),
grandparentTitle: json['grandparentTitle'] as String?,
grandparentThumb: json['grandparentThumb'] as String?,
grandparentArt: json['grandparentArt'] as String?,
@@ -66,6 +67,7 @@ Map<String, dynamic> _$PlexMetadataToJson(PlexMetadata instance) =>
'duration': instance.duration,
'addedAt': instance.addedAt,
'updatedAt': instance.updatedAt,
'lastViewedAt': instance.lastViewedAt,
'grandparentTitle': instance.grandparentTitle,
'grandparentThumb': instance.grandparentThumb,
'grandparentArt': instance.grandparentArt,
+92 -1
View File
@@ -1,9 +1,11 @@
import 'package:json_annotation/json_annotation.dart';
import 'mixins/multi_server_fields.dart';
part 'plex_playlist.g.dart';
@JsonSerializable()
class PlexPlaylist {
class PlexPlaylist with MultiServerFields {
final String ratingKey;
final String key;
final String type; // "playlist"
@@ -22,6 +24,14 @@ class PlexPlaylist {
final String? guid;
final String? thumb;
// Multi-server support fields (from MultiServerFields mixin)
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverId;
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverName;
PlexPlaylist({
required this.ratingKey,
required this.key,
@@ -40,16 +50,97 @@ class PlexPlaylist {
this.content,
this.guid,
this.thumb,
this.serverId,
this.serverName,
});
/// Helper to get display image (composite or thumb)
String? get displayImage => composite ?? thumb;
/// Helper to get display title (consistent with PlexMetadata)
String get displayTitle => title;
/// Helper to determine if playlist is editable
bool get isEditable => !smart;
/// Get globally unique key across all servers
String get globalKey => serverId != null ? '$serverId:$ratingKey' : ratingKey;
// Properties for MediaCard compatibility with PlexMetadata interface
/// Playlists are not "watched" in the traditional sense
bool get isWatched => false;
/// Playlists don't have resume positions
int? get viewOffset => null;
/// Playlists don't have parent/episode indices
int? get parentIndex => null;
int? get index => null;
/// Playlists don't have parent titles or subtitles
String? get parentTitle => null;
String? get displaySubtitle => null;
/// Playlists don't have year, rating, or content metadata
int? get year => null;
String? get contentRating => null;
double? get rating => null;
String? get studio => null;
/// Use leafCount as the equivalent of childCount
int? get childCount => leafCount;
/// Playlists don't track viewed leaf count
int? get viewedLeafCount => null;
factory PlexPlaylist.fromJson(Map<String, dynamic> json) =>
_$PlexPlaylistFromJson(json);
Map<String, dynamic> toJson() => _$PlexPlaylistToJson(this);
/// Create a copy with optional field updates
PlexPlaylist copyWith({
String? ratingKey,
String? key,
String? type,
String? title,
String? summary,
bool? smart,
String? playlistType,
int? duration,
int? leafCount,
String? composite,
int? addedAt,
int? updatedAt,
int? lastViewedAt,
int? viewCount,
String? content,
String? guid,
String? thumb,
String? serverId,
String? serverName,
}) {
return PlexPlaylist(
ratingKey: ratingKey ?? this.ratingKey,
key: key ?? this.key,
type: type ?? this.type,
title: title ?? this.title,
summary: summary ?? this.summary,
smart: smart ?? this.smart,
playlistType: playlistType ?? this.playlistType,
duration: duration ?? this.duration,
leafCount: leafCount ?? this.leafCount,
composite: composite ?? this.composite,
addedAt: addedAt ?? this.addedAt,
updatedAt: updatedAt ?? this.updatedAt,
lastViewedAt: lastViewedAt ?? this.lastViewedAt,
viewCount: viewCount ?? this.viewCount,
content: content ?? this.content,
guid: guid ?? this.guid,
thumb: thumb ?? this.thumb,
serverId: serverId ?? this.serverId,
serverName: serverName ?? this.serverName,
);
}
}
-29
View File
@@ -1,29 +0,0 @@
import 'package:json_annotation/json_annotation.dart';
part 'plex_server_info.g.dart';
@JsonSerializable()
class PlexServerInfo {
final String name;
final String? host;
final int? port;
final String? machineIdentifier;
final String version;
final bool? owned;
final bool? https;
PlexServerInfo({
required this.name,
this.host,
this.port,
this.machineIdentifier,
required this.version,
this.owned,
this.https,
});
factory PlexServerInfo.fromJson(Map<String, dynamic> json) =>
_$PlexServerInfoFromJson(json);
Map<String, dynamic> toJson() => _$PlexServerInfoToJson(this);
}
-29
View File
@@ -1,29 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'plex_server_info.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
PlexServerInfo _$PlexServerInfoFromJson(Map<String, dynamic> json) =>
PlexServerInfo(
name: json['name'] as String,
host: json['host'] as String?,
port: (json['port'] as num?)?.toInt(),
machineIdentifier: json['machineIdentifier'] as String?,
version: json['version'] as String,
owned: json['owned'] as bool?,
https: json['https'] as bool?,
);
Map<String, dynamic> _$PlexServerInfoToJson(PlexServerInfo instance) =>
<String, dynamic>{
'name': instance.name,
'host': instance.host,
'port': instance.port,
'machineIdentifier': instance.machineIdentifier,
'version': instance.version,
'owned': instance.owned,
'https': instance.https,
};
+26
View File
@@ -0,0 +1,26 @@
/// Represents an audio output device.
class AudioDevice {
/// Unique identifier for the device.
final String name;
/// Human-readable description of the device.
final String description;
const AudioDevice({required this.name, this.description = ''});
/// Default/auto audio device.
static const auto = AudioDevice(name: 'auto', description: 'Auto');
@override
String toString() => 'AudioDevice($name, $description)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AudioDevice &&
runtimeType == other.runtimeType &&
name == other.name;
@override
int get hashCode => name.hashCode;
}
+68
View File
@@ -0,0 +1,68 @@
/// Represents an audio track in the media.
class AudioTrack {
/// Unique identifier for the track.
final String id;
/// Human-readable title of the track.
final String? title;
/// Language code (e.g., 'eng', 'jpn').
final String? language;
/// Audio codec (e.g., 'aac', 'ac3', 'dts').
final String? codec;
/// Number of audio channels.
final int? channels;
/// Alias for channels (media_kit compatibility).
int? get channelsCount => channels;
/// Sample rate in Hz.
final int? sampleRate;
/// Bitrate in bits per second.
final int? bitrate;
/// Whether this is the default track.
final bool isDefault;
/// Whether this track is forced.
final bool isForced;
const AudioTrack({
required this.id,
this.title,
this.language,
this.codec,
this.channels,
this.sampleRate,
this.bitrate,
this.isDefault = false,
this.isForced = false,
});
/// Auto-select track.
static const auto = AudioTrack(id: 'auto', title: 'Auto');
/// Disable audio.
static const off = AudioTrack(id: 'no', title: 'Off');
/// Returns a display name for the track.
String get displayName {
if (title != null && title!.isNotEmpty) return title!;
if (language != null && language!.isNotEmpty) return language!;
return 'Track $id';
}
@override
String toString() => 'AudioTrack($id, $displayName)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AudioTrack && runtimeType == other.runtimeType && id == other.id;
@override
int get hashCode => id.hashCode;
}
+27
View File
@@ -0,0 +1,27 @@
/// Represents a media source for the player.
class Media {
/// The URI of the media (file path, HTTP URL, etc.).
final String uri;
/// Optional HTTP headers for network requests.
final Map<String, String>? headers;
/// Optional start position for playback.
final Duration? start;
const Media(this.uri, {this.headers, this.start});
@override
String toString() => 'Media($uri)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Media &&
runtimeType == other.runtimeType &&
uri == other.uri &&
start == other.start;
@override
int get hashCode => uri.hashCode ^ start.hashCode;
}
+22
View File
@@ -0,0 +1,22 @@
import 'player_log_level.dart';
/// A log entry from the player.
class PlayerLog {
/// The log level of this message.
final PlayerLogLevel level;
/// The prefix/category of the log message (e.g., 'cplayer', 'ffmpeg').
final String prefix;
/// The log message text.
final String text;
const PlayerLog({
required this.level,
required this.prefix,
required this.text,
});
@override
String toString() => '[$prefix] ${level.name}: $text';
}
+26
View File
@@ -0,0 +1,26 @@
/// Log level for player messages.
enum PlayerLogLevel {
/// No logging.
none,
/// Fatal errors only.
fatal,
/// Errors.
error,
/// Warnings.
warn,
/// Informational messages.
info,
/// Verbose output.
verbose,
/// Debug messages.
debug,
/// Trace-level output (very verbose).
trace,
}
+75
View File
@@ -0,0 +1,75 @@
/// Represents a subtitle track in the media.
class SubtitleTrack {
/// Unique identifier for the track.
final String id;
/// Human-readable title of the track.
final String? title;
/// Language code (e.g., 'eng', 'jpn').
final String? language;
/// Subtitle codec/format (e.g., 'subrip', 'ass', 'pgs').
final String? codec;
/// Whether this is the default track.
final bool isDefault;
/// Whether this track is forced (e.g., for foreign language segments).
final bool isForced;
/// Whether this is an external subtitle file.
final bool isExternal;
/// URI of external subtitle file (if isExternal is true).
final String? uri;
const SubtitleTrack({
required this.id,
this.title,
this.language,
this.codec,
this.isDefault = false,
this.isForced = false,
this.isExternal = false,
this.uri,
});
/// Create a subtitle track from an external URI.
factory SubtitleTrack.uri(String uri, {String? title, String? language}) {
return SubtitleTrack(
id: 'external:$uri',
title: title,
language: language,
isExternal: true,
uri: uri,
);
}
/// Auto-select track.
static const auto = SubtitleTrack(id: 'auto', title: 'Auto');
/// Disable subtitles.
static const off = SubtitleTrack(id: 'no', title: 'Off');
/// Returns a display name for the track.
String get displayName {
if (title != null && title!.isNotEmpty) return title!;
if (language != null && language!.isNotEmpty) return language!;
if (isExternal) return 'External';
return 'Track $id';
}
@override
String toString() => 'SubtitleTrack($id, $displayName)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is SubtitleTrack &&
runtimeType == other.runtimeType &&
id == other.id;
@override
int get hashCode => id.hashCode;
}
+24
View File
@@ -0,0 +1,24 @@
import 'audio_track.dart';
import 'subtitle_track.dart';
/// Represents the currently selected tracks.
class TrackSelection {
/// Currently selected audio track.
final AudioTrack? audio;
/// Currently selected subtitle track.
final SubtitleTrack? subtitle;
const TrackSelection({this.audio, this.subtitle});
/// Creates a copy with the given fields replaced.
TrackSelection copyWith({AudioTrack? audio, SubtitleTrack? subtitle}) {
return TrackSelection(
audio: audio ?? this.audio,
subtitle: subtitle ?? this.subtitle,
);
}
@override
String toString() => 'TrackSelection(audio: $audio, subtitle: $subtitle)';
}
+25
View File
@@ -0,0 +1,25 @@
import 'audio_track.dart';
import 'subtitle_track.dart';
/// Container for all available tracks in the media.
class Tracks {
/// Available audio tracks.
final List<AudioTrack> audio;
/// Available subtitle tracks.
final List<SubtitleTrack> subtitle;
const Tracks({this.audio = const [], this.subtitle = const []});
/// Creates a copy with the given fields replaced.
Tracks copyWith({List<AudioTrack>? audio, List<SubtitleTrack>? subtitle}) {
return Tracks(
audio: audio ?? this.audio,
subtitle: subtitle ?? this.subtitle,
);
}
@override
String toString() =>
'Tracks(audio: ${audio.length}, subtitle: ${subtitle.length})';
}
+62
View File
@@ -0,0 +1,62 @@
/// MPV Player library for Flutter.
///
/// This library provides a platform-agnostic interface for video playback
/// using MPV as the underlying player engine.
///
/// ## Features
///
/// - Stream-based reactive state updates
/// - Audio passthrough support for lossless audio
/// - Subtitle rendering with libass
/// - Hardware-accelerated decoding
/// - Cross-platform support (macOS, iOS, Android, Windows, Linux)
///
/// ## Usage
///
/// ```dart
/// import 'package:flutter_application_1/mpv/mpv.dart';
///
/// // Create a player
/// final player = Player();
///
/// // Configure player properties
/// await player.setProperty('hwdec', 'auto');
/// await player.setProperty('demuxer-max-bytes', '150000000');
/// await player.setAudioPassthrough(true);
///
/// // Open and play media
/// await player.open(Media('https://example.com/video.mp4'));
///
/// // Listen to state changes
/// player.streams.position.listen((position) {
/// print('Position: $position');
/// });
///
/// // Display video
/// Video(
/// player: player,
/// controls: (context) => MyCustomControls(),
/// )
///
/// // Clean up
/// await player.dispose();
/// ```
library;
// Player
export 'player/player.dart';
export 'player/player_state.dart';
export 'player/player_streams.dart';
// Models
export 'models/media.dart';
export 'models/audio_device.dart';
export 'models/audio_track.dart';
export 'models/subtitle_track.dart';
export 'models/tracks.dart';
export 'models/track_selection.dart';
export 'models/player_log.dart';
export 'models/player_log_level.dart';
// Video
export 'video/video.dart';
+29
View File
@@ -0,0 +1,29 @@
import 'package:flutter/services.dart';
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.
class PlayerLinux extends PlayerNative {
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
@override
int? get textureId => null; // Uses GtkGLArea, not Flutter texture
/// Sets the visibility of the video controls overlay.
///
/// On Linux, due to Flutter's lack of transparency support in GtkOverlay,
/// we hide the video layer when controls are visible and show it when
/// controls are hidden. This provides a workaround for the transparency
/// limitation.
@override
Future<void> setControlsVisible(bool visible) async {
await _methodChannel.invokeMethod('setControlsVisible', {
'visible': visible,
});
}
}
@@ -0,0 +1,33 @@
import 'package:flutter/services.dart';
import '../player_native.dart';
import '../video_rect_support.dart';
/// Windows implementation of [Player].
///
/// Uses libmpv via platform channels with native window embedding.
/// The mpv video window is positioned behind the Flutter window,
/// with transparent regions allowing the video to show through.
class PlayerWindows extends PlayerNative with VideoRectSupport {
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
@override
int? get textureId => null; // Uses native window embedding, not Flutter texture
@override
Future<void> setVideoRect({
required int left,
required int top,
required int right,
required int bottom,
required double devicePixelRatio,
}) async {
await _methodChannel.invokeMethod('setVideoRect', {
'left': left,
'top': top,
'right': right,
'bottom': bottom,
'devicePixelRatio': devicePixelRatio,
});
}
}
+219
View File
@@ -0,0 +1,219 @@
import 'dart:io' show Platform;
import '../models/audio_device.dart';
import '../models/media.dart';
import '../models/audio_track.dart';
import '../models/subtitle_track.dart';
import 'player_native.dart';
import 'player_state.dart';
import 'player_streams.dart';
import 'platform/player_linux.dart';
import 'platform/player_windows.dart';
/// Abstract interface for the video player.
///
/// This interface defines all playback control methods, state access,
/// and reactive streams for the video player.
///
/// Example usage:
/// ```dart
/// final player = Player();
/// await player.open(Media('https://example.com/video.mp4'));
/// await player.play();
///
/// // Configure player properties
/// await player.setProperty('hwdec', 'auto');
/// await player.setProperty('demuxer-max-bytes', '150000000');
///
/// // Listen to position updates
/// player.streams.position.listen((position) {
/// print('Position: $position');
/// });
///
/// // Access current state
/// print('Playing: ${player.state.playing}');
/// ```
abstract class Player {
/// Current synchronous state snapshot.
///
/// Use this for immediate state access in UI.
PlayerState get state;
/// Reactive streams for state changes.
///
/// Use these for reactive UI updates.
PlayerStreams get streams;
/// Texture ID for Flutter's Texture widget (video rendering).
///
/// This is set by the platform implementation when video
/// rendering is initialized. Returns null if not ready.
int? get textureId;
// ============================================
// Playback Control
// ============================================
/// Open a media source for playback.
///
/// [media] - The media source to open.
/// [play] - Whether to start playback immediately (default: true).
Future<void> open(Media media, {bool play = true});
/// Start or resume playback.
Future<void> play();
/// Pause playback.
Future<void> pause();
/// Toggle between play and pause.
Future<void> playOrPause();
/// Stop playback and reset position.
Future<void> stop();
/// Seek to a specific position.
Future<void> seek(Duration position);
// ============================================
// Track Selection
// ============================================
/// Select an audio track.
Future<void> selectAudioTrack(AudioTrack track);
/// Select a subtitle track.
///
/// Pass [SubtitleTrack.off] to disable subtitles.
Future<void> selectSubtitleTrack(SubtitleTrack track);
/// Add an external subtitle track.
///
/// [uri] - URL or path to the subtitle file.
/// [title] - Optional display title.
/// [language] - Optional language code.
/// [select] - Whether to select this track immediately.
Future<void> addSubtitleTrack({
required String uri,
String? title,
String? language,
bool select = false,
});
// ============================================
// Volume and Rate
// ============================================
/// Set the playback volume.
///
/// [volume] - Volume level from 0.0 (muted) to 100.0 (max).
Future<void> setVolume(double volume);
/// Set the playback rate/speed.
///
/// [rate] - Playback rate from 0.25 to 4.0 (1.0 = normal speed).
Future<void> setRate(double rate);
/// Set the audio output device.
///
/// [device] - The audio device to use.
Future<void> setAudioDevice(AudioDevice device);
// ============================================
// MPV Properties (Advanced)
// ============================================
/// Set an MPV property by name.
///
/// Common properties:
/// - 'hwdec': Hardware decoding mode ('auto', 'no', 'videotoolbox', etc.)
/// - 'demuxer-max-bytes': Buffer size in bytes
/// - 'audio-delay': Audio sync offset in seconds (e.g., '0.5')
/// - 'sub-delay': Subtitle sync offset in seconds
/// - 'sub-font': Subtitle font name
/// - 'sub-font-size': Subtitle font size
/// - 'sub-color': Subtitle text color
/// - 'sub-back-color': Subtitle background color
/// - 'sub-border-size': Subtitle border size
/// - 'sub-margin-y': Vertical subtitle margin
/// - 'sub-ass': Enable/disable ASS subtitle rendering ('yes'/'no')
/// - 'audio-exclusive': Exclusive audio mode ('yes'/'no')
/// - 'audio-spdif': Audio passthrough formats (e.g., 'ac3,eac3,dts,truehd')
Future<void> setProperty(String name, String value);
/// Get an MPV property value by name.
Future<String?> getProperty(String name);
/// Execute a raw MPV command.
///
/// [args] - Command and arguments as a list of strings.
Future<void> command(List<String> args);
// ============================================
// Passthrough Mode (Audio)
// ============================================
/// Enable or disable audio passthrough mode.
///
/// When enabled, supported audio codecs (AC3, DTS, etc.) will be
/// passed through to the audio device without decoding.
Future<void> setAudioPassthrough(bool enabled);
// ============================================
// Visibility (macOS Metal Layer)
// ============================================
/// Show or hide the video rendering layer.
///
/// On macOS, this controls the Metal layer visibility.
/// On other platforms, this may have no effect.
///
/// Returns true if the operation was successful.
Future<bool> setVisible(bool visible);
/// Notify the player about controls visibility.
///
/// On Linux, due to Flutter's lack of transparency support in GtkOverlay,
/// the video layer is hidden when controls are visible and shown when
/// controls are hidden. On other platforms, this is a no-op.
Future<void> setControlsVisible(bool visible);
/// Update the video frame/surface dimensions.
///
/// On iOS/macOS, this updates the Metal layer's frame to match the current
/// window size. Call this when the layout changes (e.g., device rotation).
/// On other platforms, this is a no-op.
Future<void> updateFrame();
// ============================================
// Lifecycle
// ============================================
/// Dispose of the player and release resources.
///
/// After calling this, the player instance should not be used.
Future<void> dispose();
// ============================================
// Factory
// ============================================
/// Creates a new player instance.
///
/// Returns a platform-specific implementation:
/// - macOS/iOS/Android: [PlayerNative] using MPVKit/libmpv with texture rendering
/// - Windows: [PlayerWindows] using libmpv with native window embedding
/// - Linux: [PlayerLinux] using libmpv with OpenGL rendering via GtkGLArea
factory Player() {
if (Platform.isMacOS || Platform.isIOS || Platform.isAndroid) {
return PlayerNative();
}
if (Platform.isWindows) {
return PlayerWindows();
}
if (Platform.isLinux) {
return PlayerLinux();
}
throw UnsupportedError('Player is not supported on this platform');
}
}
+577
View File
@@ -0,0 +1,577 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter/services.dart';
import '../utils/android_font_loader.dart';
import '../models/audio_device.dart';
import '../models/audio_track.dart';
import '../models/player_log.dart';
import '../models/media.dart';
import '../models/subtitle_track.dart';
import '../models/track_selection.dart';
import '../models/tracks.dart';
import 'player.dart';
import 'player_state.dart';
import 'player_streams.dart';
/// Shared native implementation of [Player] for iOS and macOS.
/// Uses MPVKit via platform channels with Metal rendering.
class PlayerNative implements Player {
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
static const _eventChannel = EventChannel('com.plezy/mpv_player/events');
PlayerState _state = const PlayerState();
@override
PlayerState get state => _state;
late final PlayerStreams _streams;
@override
PlayerStreams get streams => _streams;
@override
int? get textureId => null; // Uses direct Metal layer, not Flutter texture
// Stream controllers
final _playingController = StreamController<bool>.broadcast();
final _completedController = StreamController<bool>.broadcast();
final _bufferingController = StreamController<bool>.broadcast();
final _positionController = StreamController<Duration>.broadcast();
final _durationController = StreamController<Duration>.broadcast();
final _bufferController = StreamController<Duration>.broadcast();
final _volumeController = StreamController<double>.broadcast();
final _rateController = StreamController<double>.broadcast();
final _tracksController = StreamController<Tracks>.broadcast();
final _trackController = StreamController<TrackSelection>.broadcast();
final _logController = StreamController<PlayerLog>.broadcast();
final _errorController = StreamController<String>.broadcast();
final _audioDeviceController = StreamController<AudioDevice>.broadcast();
final _audioDevicesController =
StreamController<List<AudioDevice>>.broadcast();
StreamSubscription? _eventSubscription;
bool _disposed = false;
bool _initialized = false;
PlayerNative() {
_streams = PlayerStreams(
playing: _playingController.stream,
completed: _completedController.stream,
buffering: _bufferingController.stream,
position: _positionController.stream,
duration: _durationController.stream,
buffer: _bufferController.stream,
volume: _volumeController.stream,
rate: _rateController.stream,
tracks: _tracksController.stream,
track: _trackController.stream,
log: _logController.stream,
error: _errorController.stream,
audioDevice: _audioDeviceController.stream,
audioDevices: _audioDevicesController.stream,
);
_setupEventListener();
}
void _setupEventListener() {
_eventSubscription = _eventChannel.receiveBroadcastStream().listen(
_handleEvent,
onError: (error) {
_errorController.add(error.toString());
},
);
}
void _handleEvent(dynamic event) {
if (event is! Map) return;
final type = event['type'] as String?;
final name = event['name'] as String?;
if (type == 'property' && name != null) {
_handlePropertyChange(name, event['value']);
} else if (type == 'event' && name != null) {
_handleMpvEvent(name, event['data'] as Map?);
}
}
void _handlePropertyChange(String name, dynamic value) {
switch (name) {
case 'pause':
final playing = value == false;
_state = _state.copyWith(playing: playing);
_playingController.add(playing);
break;
case 'eof-reached':
final completed = value == true;
_state = _state.copyWith(completed: completed);
_completedController.add(completed);
break;
case 'paused-for-cache':
final buffering = value == true;
_state = _state.copyWith(buffering: buffering);
_bufferingController.add(buffering);
break;
case 'time-pos':
if (value is num) {
final position = Duration(milliseconds: (value * 1000).toInt());
_state = _state.copyWith(position: position);
_positionController.add(position);
}
break;
case 'duration':
if (value is num) {
final duration = Duration(milliseconds: (value * 1000).toInt());
_state = _state.copyWith(duration: duration);
_durationController.add(duration);
}
break;
case 'demuxer-cache-time':
if (value is num) {
final buffer = Duration(milliseconds: (value * 1000).toInt());
_state = _state.copyWith(buffer: buffer);
_bufferController.add(buffer);
}
break;
case 'volume':
if (value is num) {
final volume = value.toDouble();
_state = _state.copyWith(volume: volume);
_volumeController.add(volume);
}
break;
case 'speed':
if (value is num) {
final rate = value.toDouble();
_state = _state.copyWith(rate: rate);
_rateController.add(rate);
}
break;
case 'track-list':
List? trackList;
if (value is List) {
trackList = value;
} else if (value is String) {
// Android - JSON string that needs parsing
try {
final decoded = jsonDecode(value);
if (decoded is List) {
trackList = decoded;
}
} catch (e) {
// Invalid JSON, ignore
break;
}
}
if (trackList != null) {
final tracks = _parseTrackList(trackList);
_state = _state.copyWith(tracks: tracks);
_tracksController.add(tracks);
}
break;
case 'aid':
_updateSelectedAudioTrack(value);
break;
case 'sid':
_updateSelectedSubtitleTrack(value);
break;
}
}
void _handleMpvEvent(String name, Map? data) {
switch (name) {
case 'end-file':
final reason = data?['reason'] as String?;
if (reason == 'eof') {
_state = _state.copyWith(completed: true);
_completedController.add(true);
} else if (reason == 'error') {
_errorController.add('Playback error');
}
break;
case 'file-loaded':
// Reset completed state when new file is loaded
_state = _state.copyWith(completed: false);
_completedController.add(false);
break;
}
}
Tracks _parseTrackList(List trackList) {
final audioTracks = <AudioTrack>[];
final subtitleTracks = <SubtitleTrack>[];
for (final track in trackList) {
if (track is! Map) continue;
final type = track['type'] as String?;
final id = track['id']?.toString() ?? '';
if (type == 'audio') {
audioTracks.add(
AudioTrack(
id: id,
title: track['title'] as String?,
language: track['lang'] as String?,
codec: track['codec'] as String?,
channels: (track['demux-channel-count'] as num?)?.toInt(),
sampleRate: (track['demux-samplerate'] as num?)?.toInt(),
isDefault: track['default'] as bool? ?? false,
),
);
} else if (type == 'sub') {
subtitleTracks.add(
SubtitleTrack(
id: id,
title: track['title'] as String?,
language: track['lang'] as String?,
codec: track['codec'] as String?,
isExternal: track['external'] as bool? ?? false,
uri: track['external-filename'] as String?,
),
);
}
}
return Tracks(audio: audioTracks, subtitle: subtitleTracks);
}
void _updateSelectedAudioTrack(dynamic trackId) {
final id = trackId?.toString();
AudioTrack? selectedTrack;
if (id != null && id != 'no') {
selectedTrack = _state.tracks.audio.cast<AudioTrack?>().firstWhere(
(t) => t?.id == id,
orElse: () => null,
);
}
_state = _state.copyWith(
track: _state.track.copyWith(audio: selectedTrack),
);
_trackController.add(_state.track);
}
void _updateSelectedSubtitleTrack(dynamic trackId) {
final id = trackId?.toString();
SubtitleTrack? selectedTrack;
if (id != null && id != 'no') {
selectedTrack = _state.tracks.subtitle.cast<SubtitleTrack?>().firstWhere(
(t) => t?.id == id,
orElse: () => null,
);
}
_state = _state.copyWith(
track: _state.track.copyWith(subtitle: selectedTrack),
);
_trackController.add(_state.track);
}
Future<void> _ensureInitialized() async {
if (_initialized) return;
try {
final result = await _methodChannel.invokeMethod<bool>('initialize');
_initialized = result == true;
if (!_initialized) {
throw Exception('Failed to initialize player');
}
// Configure subtitle fonts for Android libass support
if (Platform.isAndroid) {
await _configureAndroidSubtitleFonts();
}
// Subscribe to MPV properties
await _observeProperty('time-pos', 'double');
await _observeProperty('duration', 'double');
await _observeProperty('pause', 'flag');
await _observeProperty('paused-for-cache', 'flag');
await _observeProperty(
'track-list',
Platform.isAndroid ? 'string' : 'node',
);
await _observeProperty('eof-reached', 'flag');
await _observeProperty('volume', 'double');
await _observeProperty('aid', 'string');
await _observeProperty('sid', 'string');
} catch (e) {
_errorController.add('Initialization failed: $e');
rethrow;
}
}
Future<void> _observeProperty(String name, String format) async {
await _methodChannel.invokeMethod('observeProperty', {
'name': name,
'format': format,
});
}
/// Configures subtitle fonts for Android libass support.
/// On Android, libass cannot access system fonts, so we need to provide
/// a font file from assets.
Future<void> _configureAndroidSubtitleFonts() async {
try {
final fontDir = await AndroidFontLoader.loadSubtitleFont();
if (fontDir != null) {
// Configure MPV to use the extracted font for libass
await setProperty('config', 'yes');
await setProperty('sub-fonts-dir', fontDir);
await setProperty('sub-font', AndroidFontLoader.fontName);
}
} catch (e) {
// Font configuration is not critical - continue without it
_errorController.add('Failed to configure subtitle fonts: $e');
}
}
void _checkDisposed() {
if (_disposed) {
throw StateError('Player has been disposed');
}
}
// ============================================
// Playback Control
// ============================================
@override
Future<void> open(Media media, {bool play = true}) async {
_checkDisposed();
await _ensureInitialized();
// Show the video layer
await _methodChannel.invokeMethod('setVisible', {'visible': true});
// Set start position if provided (must be set before loading file)
if (media.start != null && media.start!.inSeconds > 0) {
await setProperty('start', media.start!.inSeconds.toString());
} else {
// Reset start position if not resuming
await setProperty('start', 'none');
}
await command(['loadfile', media.uri, 'replace']);
if (!play) {
await setProperty('pause', 'yes');
}
}
@override
Future<void> play() async {
_checkDisposed();
await setProperty('pause', 'no');
}
@override
Future<void> pause() async {
_checkDisposed();
await setProperty('pause', 'yes');
}
@override
Future<void> playOrPause() async {
_checkDisposed();
if (_state.playing) {
await pause();
} else {
await play();
}
}
@override
Future<void> stop() async {
_checkDisposed();
await command(['stop']);
await _methodChannel.invokeMethod('setVisible', {'visible': false});
}
@override
Future<void> seek(Duration position) async {
_checkDisposed();
await command([
'seek',
(position.inMilliseconds / 1000.0).toString(),
'absolute',
]);
}
// ============================================
// Track Selection
// ============================================
@override
Future<void> selectAudioTrack(AudioTrack track) async {
_checkDisposed();
await setProperty('aid', track.id);
}
@override
Future<void> selectSubtitleTrack(SubtitleTrack track) async {
_checkDisposed();
await setProperty('sid', track.id);
}
@override
Future<void> addSubtitleTrack({
required String uri,
String? title,
String? language,
bool select = false,
}) async {
_checkDisposed();
final args = ['sub-add', uri, select ? 'select' : 'auto'];
if (title != null) args.add('title=$title');
if (language != null) args.add('lang=$language');
await command(args);
}
// ============================================
// Volume and Rate
// ============================================
@override
Future<void> setVolume(double volume) async {
_checkDisposed();
await setProperty('volume', volume.toString());
}
@override
Future<void> setRate(double rate) async {
_checkDisposed();
await setProperty('speed', rate.toString());
}
@override
Future<void> setAudioDevice(AudioDevice device) async {
_checkDisposed();
await setProperty('audio-device', device.name);
}
// ============================================
// MPV Properties
// ============================================
@override
Future<void> setProperty(String name, String value) async {
_checkDisposed();
await _ensureInitialized();
await _methodChannel.invokeMethod('setProperty', {
'name': name,
'value': value,
});
}
@override
Future<String?> getProperty(String name) async {
_checkDisposed();
await _ensureInitialized();
return await _methodChannel.invokeMethod<String>('getProperty', {
'name': name,
});
}
@override
Future<void> command(List<String> args) async {
_checkDisposed();
await _ensureInitialized();
await _methodChannel.invokeMethod('command', {'args': args});
}
// ============================================
// Passthrough
// ============================================
@override
Future<void> setAudioPassthrough(bool enabled) async {
_checkDisposed();
if (enabled) {
await setProperty('audio-spdif', 'ac3,eac3,dts,dts-hd,truehd');
await setProperty('audio-exclusive', 'yes');
} else {
await setProperty('audio-spdif', '');
await setProperty('audio-exclusive', 'no');
}
}
// ============================================
// Visibility
// ============================================
@override
Future<bool> setVisible(bool visible) async {
_checkDisposed();
try {
await _methodChannel.invokeMethod('setVisible', {'visible': visible});
return true;
} catch (e) {
_errorController.add('Failed to set visibility: $e');
return false;
}
}
@override
Future<void> setControlsVisible(bool visible) async {
// No-op on most platforms. Override on Linux for transparency workaround.
}
@override
Future<void> updateFrame() async {
_checkDisposed();
if (!_initialized) return;
// Only iOS and macOS use Metal layer that needs frame updates
if (Platform.isIOS || Platform.isMacOS) {
await _methodChannel.invokeMethod('updateFrame');
}
}
// ============================================
// Lifecycle
// ============================================
@override
Future<void> dispose() async {
if (_disposed) return;
_disposed = true;
await _eventSubscription?.cancel();
await _methodChannel.invokeMethod('dispose');
await _playingController.close();
await _completedController.close();
await _bufferingController.close();
await _positionController.close();
await _durationController.close();
await _bufferController.close();
await _volumeController.close();
await _rateController.close();
await _tracksController.close();
await _trackController.close();
await _logController.close();
await _errorController.close();
await _audioDeviceController.close();
await _audioDevicesController.close();
}
}
+113
View File
@@ -0,0 +1,113 @@
import '../models/audio_device.dart';
import '../models/tracks.dart';
import '../models/track_selection.dart';
/// Immutable snapshot of the current player state.
///
/// This class provides synchronous access to the player's current state.
/// For reactive updates, use [PlayerStreams].
class PlayerState {
/// Whether playback is currently active.
final bool playing;
/// Whether the media has completed playback.
final bool completed;
/// Whether the player is currently buffering.
final bool buffering;
/// Current playback position.
final Duration position;
/// Total duration of the media.
final Duration duration;
/// Amount of media buffered ahead of current position.
final Duration buffer;
/// Current volume level (0.0 to 100.0).
final double volume;
/// Current playback rate (1.0 = normal speed).
final double rate;
/// Available tracks in the media.
final Tracks tracks;
/// Currently selected tracks.
final TrackSelection track;
/// Audio delay/sync offset in seconds.
final double audioDelay;
/// Subtitle delay/sync offset in seconds.
final double subtitleDelay;
/// Whether audio passthrough is currently enabled.
final bool audioPassthrough;
/// Current audio output device.
final AudioDevice audioDevice;
/// Available audio output devices.
final List<AudioDevice> audioDevices;
const PlayerState({
this.playing = false,
this.completed = false,
this.buffering = false,
this.position = Duration.zero,
this.duration = Duration.zero,
this.buffer = Duration.zero,
this.volume = 100.0,
this.rate = 1.0,
this.tracks = const Tracks(),
this.track = const TrackSelection(),
this.audioDelay = 0.0,
this.subtitleDelay = 0.0,
this.audioPassthrough = false,
this.audioDevice = AudioDevice.auto,
this.audioDevices = const [],
});
/// Creates a copy with the given fields replaced.
PlayerState copyWith({
bool? playing,
bool? completed,
bool? buffering,
Duration? position,
Duration? duration,
Duration? buffer,
double? volume,
double? rate,
Tracks? tracks,
TrackSelection? track,
double? audioDelay,
double? subtitleDelay,
bool? audioPassthrough,
AudioDevice? audioDevice,
List<AudioDevice>? audioDevices,
}) {
return PlayerState(
playing: playing ?? this.playing,
completed: completed ?? this.completed,
buffering: buffering ?? this.buffering,
position: position ?? this.position,
duration: duration ?? this.duration,
buffer: buffer ?? this.buffer,
volume: volume ?? this.volume,
rate: rate ?? this.rate,
tracks: tracks ?? this.tracks,
track: track ?? this.track,
audioDelay: audioDelay ?? this.audioDelay,
subtitleDelay: subtitleDelay ?? this.subtitleDelay,
audioPassthrough: audioPassthrough ?? this.audioPassthrough,
audioDevice: audioDevice ?? this.audioDevice,
audioDevices: audioDevices ?? this.audioDevices,
);
}
@override
String toString() =>
'PlayerState(playing: $playing, position: $position, duration: $duration)';
}
+69
View File
@@ -0,0 +1,69 @@
import '../models/audio_device.dart';
import '../models/player_log.dart';
import '../models/tracks.dart';
import '../models/track_selection.dart';
/// Reactive streams for player state changes.
///
/// Subscribe to these streams to receive updates when the player state changes.
/// For synchronous state access, use [PlayerState].
class PlayerStreams {
/// Stream of playing state changes.
final Stream<bool> playing;
/// Stream of completion state changes.
final Stream<bool> completed;
/// Stream of buffering state changes.
final Stream<bool> buffering;
/// Stream of position updates.
final Stream<Duration> position;
/// Stream of duration changes (when media is loaded).
final Stream<Duration> duration;
/// Stream of buffer position updates.
final Stream<Duration> buffer;
/// Stream of volume changes.
final Stream<double> volume;
/// Stream of playback rate changes.
final Stream<double> rate;
/// Stream of available tracks updates.
final Stream<Tracks> tracks;
/// Stream of track selection changes.
final Stream<TrackSelection> track;
/// Stream of log messages from the player.
final Stream<PlayerLog> log;
/// Stream of error messages.
final Stream<String> error;
/// Stream of audio device changes.
final Stream<AudioDevice> audioDevice;
/// Stream of available audio devices.
final Stream<List<AudioDevice>> audioDevices;
const PlayerStreams({
required this.playing,
required this.completed,
required this.buffering,
required this.position,
required this.duration,
required this.buffer,
required this.volume,
required this.rate,
required this.tracks,
required this.track,
required this.log,
required this.error,
required this.audioDevice,
required this.audioDevices,
});
}
+20
View File
@@ -0,0 +1,20 @@
/// Mixin for players that support video rect positioning.
///
/// Players that render video behind the Flutter view (e.g., using
/// native window embedding or GtkGLArea) implement this mixin to
/// receive layout updates from the [Video] widget.
mixin VideoRectSupport {
/// Updates the video rendering area.
///
/// Called by the [Video] widget when the layout changes.
///
/// [left], [top], [right], [bottom] define the rect in physical pixels.
/// [devicePixelRatio] is the device's pixel ratio for scaling.
Future<void> setVideoRect({
required int left,
required int top,
required int right,
required int bottom,
required double devicePixelRatio,
});
}
+53
View File
@@ -0,0 +1,53 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
/// Utility class for loading font assets on Android for libass subtitle rendering.
///
/// On Android, libass cannot access system fonts through fontconfig, so we need
/// to extract font files from Flutter assets to the app's cache directory.
class AndroidFontLoader {
static const String _fontAssetPath = 'assets/go-noto-current-regular.ttf';
static const String _fontName = 'Go Noto Current-Regular';
/// Loads the subtitle font from assets to the Android cache directory.
/// Returns the directory path containing the font file.
static Future<String?> loadSubtitleFont() async {
try {
// Get the app's cache directory
final cacheDir = await getTemporaryDirectory();
final fontDir = Directory(path.join(cacheDir.path, 'subtitle_fonts'));
// Create fonts directory if it doesn't exist
if (!await fontDir.exists()) {
await fontDir.create(recursive: true);
}
final fontFile = File(
path.join(fontDir.path, 'go-noto-current-regular.ttf'),
);
// Load font from assets and write to cache if it doesn't exist
if (!await fontFile.exists()) {
final fontData = await rootBundle.load(_fontAssetPath);
await fontFile.writeAsBytes(fontData.buffer.asUint8List());
}
return fontDir.path;
} catch (e) {
// Return null if font loading fails - libass will fall back gracefully
if (kDebugMode) {
debugPrint('Failed to load subtitle font: $e');
}
return null;
}
}
/// Returns the font name to be used with libass.
static String get fontName => _fontName;
/// Returns the font asset path.
static String get fontAssetPath => _fontAssetPath;
}
+117
View File
@@ -0,0 +1,117 @@
import 'package:flutter/material.dart';
import '../player/player.dart';
import '../player/video_rect_support.dart';
/// Video widget for displaying player output.
///
/// This widget displays the video output from a [Player] instance
/// and optionally overlays custom controls.
///
/// Example usage:
/// ```dart
/// final player = Player();
///
/// Video(
/// player: player,
/// fit: BoxFit.contain,
/// controls: (context) => MyCustomControls(),
/// )
/// ```
class Video extends StatefulWidget {
/// The player instance.
final Player player;
/// How the video should be inscribed into the widget's box.
final BoxFit fit;
/// Builder for custom video controls overlay.
final Widget Function(BuildContext context)? controls;
/// Background color shown behind the video.
final Color backgroundColor;
const Video({
super.key,
required this.player,
this.fit = BoxFit.contain,
this.controls,
this.backgroundColor = Colors.black,
});
@override
State<Video> createState() => _VideoState();
}
class _VideoState extends State<Video> {
Rect? _lastRect;
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Stack(
fit: StackFit.expand,
children: [
// Video rendering area
_buildVideoSurface(),
// Controls overlay
if (widget.controls != null) widget.controls!(context),
],
),
);
}
Widget _buildVideoSurface() {
// For players that support video rect positioning (Windows, Linux),
// communicate layout changes to the native side.
if (widget.player is VideoRectSupport) {
return LayoutBuilder(
builder: (context, constraints) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateVideoRect(context, constraints);
});
return const SizedBox.expand();
},
);
}
return const SizedBox.expand();
}
void _updateVideoRect(BuildContext context, BoxConstraints constraints) {
final renderBox = context.findRenderObject() as RenderBox?;
if (renderBox == null || !renderBox.hasSize) return;
final position = renderBox.localToGlobal(Offset.zero);
final size = renderBox.size;
final dpr = MediaQuery.of(context).devicePixelRatio;
final newRect = Rect.fromLTWH(
position.dx,
position.dy,
size.width,
size.height,
);
// Only update if the rect has changed significantly
if (_lastRect != null &&
(newRect.left - _lastRect!.left).abs() < 1 &&
(newRect.top - _lastRect!.top).abs() < 1 &&
(newRect.width - _lastRect!.width).abs() < 1 &&
(newRect.height - _lastRect!.height).abs() < 1) {
return;
}
_lastRect = newRect;
// Update the native video rect
(widget.player as VideoRectSupport).setVideoRect(
left: (position.dx * dpr).toInt(),
top: (position.dy * dpr).toInt(),
right: ((position.dx + size.width) * dpr).toInt(),
bottom: ((position.dy + size.height) * dpr).toInt(),
devicePixelRatio: dpr,
);
}
}
+9 -2
View File
@@ -10,13 +10,17 @@ class HiddenLibrariesProvider extends ChangeNotifier {
bool _isInitialized = false;
/// Get an unmodifiable copy of hidden library keys
Set<String> get hiddenLibraryKeys => Set.unmodifiable(_hiddenLibraryKeys);
Set<String> get hiddenLibraryKeys {
if (!_isInitialized) _initialize();
return Set.unmodifiable(_hiddenLibraryKeys);
}
/// Check if the provider has completed initialization
bool get isInitialized => _isInitialized;
HiddenLibrariesProvider() {
_initialize();
// Don't initialize immediately if lazy-loaded
// _initialize() will be called when first accessed
}
/// Initialize the provider by loading hidden libraries from storage
@@ -30,6 +34,7 @@ class HiddenLibrariesProvider extends ChangeNotifier {
/// Hide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> hideLibrary(String libraryKey) async {
if (!_isInitialized) await _initialize();
if (!_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..add(libraryKey);
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
@@ -40,6 +45,7 @@ class HiddenLibrariesProvider extends ChangeNotifier {
/// Unhide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> unhideLibrary(String libraryKey) async {
if (!_isInitialized) await _initialize();
if (_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..remove(libraryKey);
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
@@ -49,6 +55,7 @@ class HiddenLibrariesProvider extends ChangeNotifier {
/// Check if a specific library is hidden
bool isLibraryHidden(String libraryKey) {
if (!_isInitialized) _initialize();
return _hiddenLibraryKeys.contains(libraryKey);
}
+112
View File
@@ -0,0 +1,112 @@
import 'package:flutter/foundation.dart';
import '../services/plex_client.dart';
import '../services/data_aggregation_service.dart';
import '../services/multi_server_manager.dart';
import '../services/plex_auth_service.dart';
import '../utils/app_logger.dart';
/// Provider for multi-server Plex connections
/// Manages multiple PlexClient instances and provides data aggregation
class MultiServerProvider extends ChangeNotifier {
final MultiServerManager _serverManager;
final DataAggregationService _aggregationService;
MultiServerProvider(this._serverManager, this._aggregationService) {
// Listen to server status changes
_serverManager.statusStream.listen((_) {
notifyListeners();
});
}
/// Get the multi-server manager
MultiServerManager get serverManager => _serverManager;
/// Get the data aggregation service
DataAggregationService get aggregationService => _aggregationService;
/// Get client for specific server
PlexClient? getClientForServer(String serverId) {
return _serverManager.getClient(serverId);
}
/// Get all online server IDs
List<String> get onlineServerIds => _serverManager.onlineServerIds;
/// Get all server IDs
List<String> get serverIds => _serverManager.serverIds;
/// Check if a server is online
bool isServerOnline(String serverId) {
return _serverManager.isServerOnline(serverId);
}
/// Get number of online servers
int get onlineServerCount => _serverManager.onlineServerIds.length;
/// Get number of total servers
int get totalServerCount => _serverManager.serverIds.length;
/// Check if any servers are connected
bool get hasConnectedServers => onlineServerCount > 0;
/// Update token for a specific server
void updateTokenForServer(String serverId, String newToken) {
final client = _serverManager.getClient(serverId);
if (client != null) {
client.updateToken(newToken);
appLogger.d('MultiServerProvider: Token updated for server $serverId');
notifyListeners();
} else {
appLogger.w(
'MultiServerProvider: Cannot update token - server $serverId not found',
);
}
}
/// Clear all server connections
void clearAllConnections() {
_serverManager.disconnectAll();
_aggregationService.clearCache(); // Clear cached data when servers change
appLogger.d('MultiServerProvider: All connections cleared');
notifyListeners();
}
/// Reconnect all servers after a profile switch
/// Clears existing connections and connects to all provided servers
Future<int> reconnectWithServers(
List<PlexServer> servers, {
String? clientIdentifier,
}) async {
// Clear existing connections first
_serverManager.disconnectAll();
_aggregationService.clearCache(); // Clear cached data when servers change
appLogger.d(
'MultiServerProvider: Cleared connections, reconnecting to ${servers.length} servers',
);
// Connect with new server tokens
final connectedCount = await _serverManager.connectToAllServers(
servers,
clientIdentifier: clientIdentifier,
);
appLogger.i(
'MultiServerProvider: Reconnected to $connectedCount/${servers.length} servers after profile switch',
);
notifyListeners();
return connectedCount;
}
/// Check server health for all connected servers
Future<void> checkServerHealth() async {
await _serverManager.checkServerHealth();
// notifyListeners() will be called automatically via status stream
}
@override
void dispose() {
_serverManager.dispose();
super.dispose();
}
}
+17 -35
View File
@@ -1,13 +1,13 @@
import 'package:flutter/foundation.dart';
import '../models/plex_metadata.dart';
import '../models/play_queue_response.dart';
import '../client/plex_client.dart';
import '../services/plex_client.dart';
/// Playback mode types
///
/// All playback now uses Plex play queues.
enum PlaybackMode {
none, // No active playback queue
sequential, // Normal episode-to-episode playback (uses Plex API)
playQueue, // Play queue-based playback (playlists, collections, shuffle)
playQueue, // Play queue-based playback (sequential, shuffle, playlists, collections)
}
/// Result of trying to locate the current queue index.
@@ -38,13 +38,13 @@ class PlaybackStateProvider with ChangeNotifier {
// Legacy state for backward compatibility
String? _contextKey; // The show/season/playlist ratingKey for this session
PlaybackMode _playbackMode = PlaybackMode.none;
PlaybackMode? _playbackMode;
// Client reference for loading more items
PlexClient? _client;
/// Current playback mode
PlaybackMode get playbackMode => _playbackMode;
/// Current playback mode (null if no queue active)
PlaybackMode? get playbackMode => _playbackMode;
/// Whether shuffle mode is currently active
bool get isShuffleActive => _playQueueShuffled;
@@ -92,8 +92,10 @@ class PlaybackStateProvider with ChangeNotifier {
/// Call this after creating a play queue via the API
Future<void> setPlaybackFromPlayQueue(
PlayQueueResponse playQueue,
String? contextKey,
) async {
String? contextKey, {
String? serverId,
String? serverName,
}) async {
_playQueueId = playQueue.playQueueID;
// Use size or items length as fallback if totalCount is null
_playQueueTotalCount =
@@ -102,31 +104,10 @@ class PlaybackStateProvider with ChangeNotifier {
(playQueue.items?.length ?? 0);
_playQueueShuffled = playQueue.playQueueShuffled;
_currentPlayQueueItemID = playQueue.playQueueSelectedItemID;
// Items are already tagged with server info by PlexClient
_loadedItems = playQueue.items ?? [];
_contextKey = contextKey;
_playbackMode = PlaybackMode.playQueue;
notifyListeners();
}
/// Legacy method for backward compatibility with shuffle play
/// This now creates a play queue on the server
@Deprecated('Use createPlayQueueFromUri instead')
void setShuffleQueue(List<PlexMetadata> episodes, String contextKey) {
// This is kept for backward compatibility but should not be used
// New code should use the play queue API
_loadedItems = List.from(episodes);
_contextKey = contextKey;
_playbackMode = PlaybackMode.playQueue;
notifyListeners();
}
/// Legacy method for backward compatibility with playlist playback
/// This now creates a play queue on the server
@Deprecated('Use createPlayQueueFromUri instead')
void setPlaybackQueue(List<PlexMetadata> items, String contextKey) {
// This is kept for backward compatibility but should not be used
// New code should use the play queue API
_loadedItems = List.from(items);
_contextKey = contextKey;
_playbackMode = PlaybackMode.playQueue;
notifyListeners();
@@ -153,6 +134,7 @@ class PlaybackStateProvider with ChangeNotifier {
);
if (response != null && response.items != null) {
// Items are already tagged with server info by PlexClient
_loadedItems = response.items!;
// Use size or items length as fallback if totalCount is null
_playQueueTotalCount =
@@ -245,6 +227,7 @@ class PlaybackStateProvider with ChangeNotifier {
if (response != null &&
response.items != null &&
response.items!.isNotEmpty) {
// Items are already tagged with server info by PlexClient
_loadedItems = response.items!;
final firstItem = _loadedItems.first;
// Don't update _currentPlayQueueItemID here - let setCurrentItem do it when playback starts
@@ -252,8 +235,7 @@ class PlaybackStateProvider with ChangeNotifier {
}
}
}
// Queue has ended - clear it and let sequential playback take over
clearShuffle();
// At end of queue - return null but keep queue active so user can still go back
return null;
}
@@ -318,7 +300,7 @@ class PlaybackStateProvider with ChangeNotifier {
_currentPlayQueueItemID = null;
_loadedItems = [];
_contextKey = null;
_playbackMode = PlaybackMode.none;
_playbackMode = null;
notifyListeners();
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import 'package:flutter/foundation.dart';
import '../client/plex_client.dart';
import '../services/plex_client.dart';
import '../utils/app_logger.dart';
class PlexClientProvider extends ChangeNotifier {
+76
View File
@@ -0,0 +1,76 @@
import 'package:flutter/foundation.dart';
/// Provider for tracking server-specific UI state
/// Manages which server is currently in context for detail views
class ServerStateProvider extends ChangeNotifier {
String? _currentServerId;
final Map<String, bool> _serverConnectionStates = {};
final Map<String, String?> _serverErrors = {};
/// Get the currently selected server ID (for detail views)
String? get currentServerId => _currentServerId;
/// Set the current server context (e.g., when viewing a library from a specific server)
void setCurrentServer(String? serverId) {
if (_currentServerId != serverId) {
_currentServerId = serverId;
notifyListeners();
}
}
/// Clear the current server selection
void clearCurrentServer() {
if (_currentServerId != null) {
_currentServerId = null;
notifyListeners();
}
}
/// Get connection state for a server
bool isServerConnected(String serverId) {
return _serverConnectionStates[serverId] ?? false;
}
/// Update connection state for a server
void updateServerConnectionState(String serverId, bool isConnected) {
if (_serverConnectionStates[serverId] != isConnected) {
_serverConnectionStates[serverId] = isConnected;
notifyListeners();
}
}
/// Get error message for a server (null if no error)
String? getServerError(String serverId) {
return _serverErrors[serverId];
}
/// Set error for a server
void setServerError(String serverId, String? error) {
_serverErrors[serverId] = error;
notifyListeners();
}
/// Clear error for a server
void clearServerError(String serverId) {
if (_serverErrors.containsKey(serverId)) {
_serverErrors.remove(serverId);
notifyListeners();
}
}
/// Clear all server errors
void clearAllServerErrors() {
if (_serverErrors.isNotEmpty) {
_serverErrors.clear();
notifyListeners();
}
}
/// Reset all state
void reset() {
_currentServerId = null;
_serverConnectionStates.clear();
_serverErrors.clear();
notifyListeners();
}
}
+38 -47
View File
@@ -2,91 +2,82 @@ import 'package:flutter/material.dart';
import '../services/settings_service.dart';
class SettingsProvider extends ChangeNotifier {
late SettingsService _settingsService;
SettingsService? _settingsService;
LibraryDensity _libraryDensity = LibraryDensity.normal;
ViewMode _viewMode = ViewMode.grid;
bool _useSeasonPoster = false;
bool _showHeroSection = true;
bool _shuffleUnwatchedOnly = true;
bool _shuffleOrderNavigation = true;
bool _shuffleLoopQueue = false;
bool _isInitialized = false;
SettingsProvider() {
_initializeSettings();
// Don't initialize immediately if lazy-loaded
// _initializeSettings() will be called when first accessed
}
Future<void> _initializeSettings() async {
if (_isInitialized) return;
_settingsService = await SettingsService.getInstance();
_libraryDensity = _settingsService.getLibraryDensity();
_viewMode = _settingsService.getViewMode();
_useSeasonPoster = _settingsService.getUseSeasonPoster();
_showHeroSection = _settingsService.getShowHeroSection();
_shuffleUnwatchedOnly = _settingsService.getShuffleUnwatchedOnly();
_shuffleOrderNavigation = _settingsService.getShuffleOrderNavigation();
_shuffleLoopQueue = _settingsService.getShuffleLoopQueue();
_libraryDensity = _settingsService!.getLibraryDensity();
_viewMode = _settingsService!.getViewMode();
_useSeasonPoster = _settingsService!.getUseSeasonPoster();
_showHeroSection = _settingsService!.getShowHeroSection();
_isInitialized = true;
notifyListeners();
}
LibraryDensity get libraryDensity => _libraryDensity;
ViewMode get viewMode => _viewMode;
bool get useSeasonPoster => _useSeasonPoster;
bool get showHeroSection => _showHeroSection;
bool get shuffleUnwatchedOnly => _shuffleUnwatchedOnly;
bool get shuffleOrderNavigation => _shuffleOrderNavigation;
bool get shuffleLoopQueue => _shuffleLoopQueue;
LibraryDensity get libraryDensity {
if (!_isInitialized) _initializeSettings();
return _libraryDensity;
}
ViewMode get viewMode {
if (!_isInitialized) _initializeSettings();
return _viewMode;
}
bool get useSeasonPoster {
if (!_isInitialized) _initializeSettings();
return _useSeasonPoster;
}
bool get showHeroSection {
if (!_isInitialized) _initializeSettings();
return _showHeroSection;
}
Future<void> setLibraryDensity(LibraryDensity density) async {
if (!_isInitialized) await _initializeSettings();
if (_libraryDensity != density) {
_libraryDensity = density;
await _settingsService.setLibraryDensity(density);
await _settingsService!.setLibraryDensity(density);
notifyListeners();
}
}
Future<void> setViewMode(ViewMode mode) async {
if (!_isInitialized) await _initializeSettings();
if (_viewMode != mode) {
_viewMode = mode;
await _settingsService.setViewMode(mode);
await _settingsService!.setViewMode(mode);
notifyListeners();
}
}
Future<void> setUseSeasonPoster(bool value) async {
if (!_isInitialized) await _initializeSettings();
if (_useSeasonPoster != value) {
_useSeasonPoster = value;
await _settingsService.setUseSeasonPoster(value);
await _settingsService!.setUseSeasonPoster(value);
notifyListeners();
}
}
Future<void> setShowHeroSection(bool value) async {
if (!_isInitialized) await _initializeSettings();
if (_showHeroSection != value) {
_showHeroSection = value;
await _settingsService.setShowHeroSection(value);
notifyListeners();
}
}
Future<void> setShuffleUnwatchedOnly(bool value) async {
if (_shuffleUnwatchedOnly != value) {
_shuffleUnwatchedOnly = value;
await _settingsService.setShuffleUnwatchedOnly(value);
notifyListeners();
}
}
Future<void> setShuffleOrderNavigation(bool value) async {
if (_shuffleOrderNavigation != value) {
_shuffleOrderNavigation = value;
await _settingsService.setShuffleOrderNavigation(value);
notifyListeners();
}
}
Future<void> setShuffleLoopQueue(bool value) async {
if (_shuffleLoopQueue != value) {
_shuffleLoopQueue = value;
await _settingsService.setShuffleLoopQueue(value);
await _settingsService!.setShowHeroSection(value);
notifyListeners();
}
}
+32 -53
View File
@@ -7,7 +7,7 @@ import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../widgets/pin_entry_dialog.dart';
import '../screens/profile/pin_entry_dialog.dart';
import 'plex_client_provider.dart';
class UserProfileProvider extends ChangeNotifier {
@@ -16,6 +16,7 @@ class UserProfileProvider extends ChangeNotifier {
PlexUserProfile? _profileSettings;
bool _isLoading = false;
String? _error;
bool _isInitialized = false;
PlexHome? get home => _home;
PlexHomeUser? get currentUser => _currentUser;
@@ -34,22 +35,34 @@ class UserProfileProvider extends ChangeNotifier {
StorageService? _storageService;
// Callback for data invalidation when switching profiles
VoidCallback? _onDataInvalidationRequested;
// Receives the list of servers with new profile tokens for reconnection
Future<void> Function(List<PlexServer>)? _onDataInvalidationRequested;
/// Set a callback to be called when profile switching requires data invalidation
void setDataInvalidationCallback(VoidCallback? callback) {
/// The callback receives the list of servers with the new profile's access tokens
void setDataInvalidationCallback(
Future<void> Function(List<PlexServer>)? callback,
) {
_onDataInvalidationRequested = callback;
}
/// Trigger data invalidation for all screens
void _invalidateAllData() {
/// Trigger data invalidation for all screens with the new profile's servers
Future<void> _invalidateAllData(List<PlexServer> servers) async {
if (_onDataInvalidationRequested != null) {
_onDataInvalidationRequested!();
appLogger.d('Data invalidation triggered for profile switch');
await _onDataInvalidationRequested!(servers);
appLogger.d(
'Data invalidation triggered for profile switch with ${servers.length} servers',
);
}
}
Future<void> initialize() async {
// Prevent duplicate initialization
if (_isInitialized) {
appLogger.d('UserProfileProvider: Already initialized, skipping');
return;
}
appLogger.d('UserProfileProvider: Initializing...');
try {
_authService = await PlexAuthService.create();
@@ -84,6 +97,7 @@ class UserProfileProvider extends ChangeNotifier {
// Don't set error here, cached profile (if any) was already loaded
}
_isInitialized = true;
appLogger.d('UserProfileProvider: Initialization complete');
} catch (e) {
appLogger.e(
@@ -94,6 +108,7 @@ class UserProfileProvider extends ChangeNotifier {
// Ensure services are null on failure
_authService = null;
_storageService = null;
_isInitialized = false; // Allow retry on failure
}
}
@@ -294,7 +309,7 @@ class UserProfileProvider extends ChangeNotifier {
);
// switchResponse.authToken is the new user's Plex.tv token
// We need to fetch servers with this token to get the proper server access token
// Fetch servers with this token to get the proper server access tokens
appLogger.d('Got new user Plex.tv token, fetching servers...');
final servers = await _authService!.fetchServers(
@@ -304,38 +319,14 @@ class UserProfileProvider extends ChangeNotifier {
throw Exception('No servers available for this user');
}
// Find the current server from storage
final currentServerData = _storageService!.getServerData();
if (currentServerData == null) {
throw Exception('No current server data found');
}
appLogger.d('Fetched ${servers.length} servers for new profile');
// Find matching server by name or client identifier
final currentServerName = currentServerData['name'] as String?;
final currentServerClientId =
currentServerData['clientIdentifier'] as String?;
final matchingServer = servers.firstWhere(
(server) =>
server.name == currentServerName ||
server.clientIdentifier == currentServerClientId,
orElse: () => servers.first, // Fallback to first server
);
appLogger.d(
'Found matching server: ${matchingServer.name}, getting access token',
);
// Update storage with new tokens
await _storageService!.updateCurrentUser(
user.uuid,
matchingServer
.accessToken, // Use server access token, not Plex.tv token
);
// Also save the new Plex.tv token for future profile operations
// Save the new Plex.tv token for future profile operations
await _storageService!.savePlexToken(switchResponse.authToken);
// Update current user UUID in storage
await _storageService!.saveCurrentUserUUID(user.uuid);
// Update current user
_currentUser = user;
@@ -351,26 +342,14 @@ class UserProfileProvider extends ChangeNotifier {
},
);
// Update PlexClient with proper server access token
if (clientProvider != null) {
try {
clientProvider.updateToken(matchingServer.accessToken);
appLogger.d(
'Updated PlexClient with server access token for user: ${user.displayName}',
);
} catch (e) {
appLogger.w('Failed to update PlexClient token', error: e);
}
}
notifyListeners();
// Invalidate all cached data for the new profile
// This will cause screens to refresh and rebuild widgets with the new token
_invalidateAllData();
// Invalidate all cached data and reconnect to all servers with new tokens
// The callback will handle server reconnection using the servers list
await _invalidateAllData(servers);
appLogger.d(
'Profile switch complete, all data and images should refresh with new token',
'Profile switch complete, all servers reconnected with new tokens',
);
appLogger.i('Successfully switched to user: ${user.displayName}');
+151 -60
View File
@@ -1,12 +1,17 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../services/server_registry.dart';
import '../providers/multi_server_provider.dart';
import '../providers/plex_client_provider.dart';
import '../i18n/strings.g.dart';
import 'server_selection_screen.dart';
import '../utils/app_logger.dart';
import 'main_screen.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({super.key});
@@ -33,6 +38,77 @@ class _AuthScreenState extends State<AuthScreen> {
_authService = await PlexAuthService.create();
}
/// Connect to all available servers and navigate to main screen
Future<void> _connectToAllServersAndNavigate(String plexToken) async {
if (!mounted) return;
setState(() {
_isAuthenticating = true;
_errorMessage = null;
});
try {
// Fetch all servers for this user
final servers = await _authService.fetchServers(plexToken);
final storage = await StorageService.getInstance();
if (servers.isEmpty) {
await storage.clearCredentials();
setState(() {
_isAuthenticating = false;
_errorMessage = t.serverSelection.noServersFound;
});
return;
}
// Save all servers to registry and enable them
final registry = ServerRegistry(storage);
await registry.saveServers(servers);
// Enable all servers
final serverIds = servers.map((s) => s.clientIdentifier).toSet();
await registry.saveEnabledServerIds(serverIds);
// Connect to all servers
if (!mounted) return;
final multiServerProvider = context.read<MultiServerProvider>();
final connectedCount = await multiServerProvider.serverManager
.connectToAllServers(servers);
if (connectedCount == 0) {
setState(() {
_isAuthenticating = false;
_errorMessage = t.serverSelection.allServerConnectionsFailed;
});
return;
}
// Get the first connected client for backward compatibility
if (!mounted) return;
final firstClient =
multiServerProvider.serverManager.onlineClients.values.first;
// Set it as the legacy client
final plexClientProvider = context.read<PlexClientProvider>();
plexClientProvider.setClient(firstClient);
// Navigate to main screen
if (!mounted) return;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: firstClient),
),
);
} catch (e) {
appLogger.e('Failed to connect to servers', error: e);
setState(() {
_isAuthenticating = false;
_errorMessage = t.serverSelection.failedToLoadServers(error: e);
});
}
}
Future<void> _startAuthentication() async {
setState(() {
_isAuthenticating = true;
@@ -100,23 +176,16 @@ class _AuthScreenState extends State<AuthScreen> {
final storage = await StorageService.getInstance();
await storage.savePlexToken(token);
// Navigate to server selection
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => ServerSelectionScreen(
authService: _authService,
plexToken: token,
),
),
);
}
// Clear QR URL after successful auth
setState(() {
_qrAuthUrl = null;
_useQrFlow = false;
});
// Connect to all servers and navigate to main screen
if (mounted) {
await _connectToAllServersAndNavigate(token);
}
} catch (e) {
setState(() {
_isAuthenticating = false;
@@ -197,17 +266,10 @@ class _AuthScreenState extends State<AuthScreen> {
final storage = await StorageService.getInstance();
await storage.savePlexToken(token);
// Close dialog and navigate
// Close dialog and connect to all servers
if (mounted) {
navigator.pop();
navigator.pushReplacement(
MaterialPageRoute(
builder: (context) => ServerSelectionScreen(
authService: _authService,
plexToken: token,
),
),
);
await _connectToAllServersAndNavigate(token);
}
} catch (e) {
setDialogState(() {
@@ -287,17 +349,7 @@ class _AuthScreenState extends State<AuthScreen> {
),
),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
_buildRetryButton(),
] else ...[
// Browser auth flow - show spinner and waiting message
const Center(child: CircularProgressIndicator()),
@@ -307,17 +359,7 @@ class _AuthScreenState extends State<AuthScreen> {
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
_buildRetryButton(),
],
] else ...[
// Initial state buttons
@@ -394,24 +436,57 @@ class _AuthScreenState extends State<AuthScreen> {
),
const SizedBox(height: 48),
if (_isAuthenticating) ...[
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
Text(
t.auth.waitingForAuth,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
if (_useQrFlow && _qrAuthUrl != null) ...[
// QR code flow - show QR code and scan instruction
Text(
t.auth.scanQRCodeInstruction,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: QrImageView(
data: _qrAuthUrl!,
size: 200,
version: QrVersions.auto,
backgroundColor: Colors.white,
),
),
),
child: Text(t.auth.retry),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
] else ...[
// Browser auth flow - show spinner and waiting message
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
Text(
t.auth.waitingForAuth,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
],
] else ...[
// add QR button here
ElevatedButton(
@@ -469,4 +544,20 @@ class _AuthScreenState extends State<AuthScreen> {
),
);
}
Widget _buildRetryButton() {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
),
child: Text(t.auth.retry),
),
],
);
}
}
+189 -5
View File
@@ -1,10 +1,14 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import 'package:provider/provider.dart';
import '../../services/plex_client.dart';
import '../models/plex_metadata.dart';
import '../providers/multi_server_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/collection_playlist_play_helper.dart';
import '../utils/app_logger.dart';
import '../mixins/refreshable.dart';
import '../mixins/item_updatable.dart';
import '../i18n/strings.g.dart';
/// Abstract base class for screens displaying media lists (collections/playlists)
/// Provides common state management and playback functionality
@@ -17,7 +21,7 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
String? errorMessage;
@override
PlexClient get client => context.clientSafe;
PlexClient get client => _getClientForMediaItem();
/// The media item being displayed (collection or playlist)
dynamic get mediaItem;
@@ -28,6 +32,42 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
/// Message to show when list is empty
String get emptyMessage;
/// Optional icon to show when list is empty
IconData? get emptyIcon => null;
/// Get the correct PlexClient for this media item's server
PlexClient _getClientForMediaItem() {
// Try to get serverId from the media item
String? serverId;
// Check if mediaItem has serverId property
if (mediaItem is PlexMetadata) {
serverId = (mediaItem as PlexMetadata).serverId;
} else if (mediaItem != null) {
// For playlists or other types, use dynamic access
try {
final dynamic item = mediaItem;
serverId = item.serverId as String?;
} catch (_) {
// Ignore if serverId is not available
}
}
// If serverId is null, fall back to first available server
if (serverId == null) {
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
if (!multiServerProvider.hasConnectedServers) {
throw Exception(t.errors.noClientAvailable);
}
serverId = multiServerProvider.onlineServerIds.first;
}
return context.getClientForServer(serverId);
}
@override
void initState() {
super.initState();
@@ -54,9 +94,7 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
return;
}
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final client = _getClientForMediaItem();
await playCollectionOrPlaylist(
context: context,
@@ -82,4 +120,150 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
void refresh() {
loadItems();
}
/// Build common error/loading/empty state slivers
/// Returns a list of slivers to display based on current state
List<Widget> buildStateSlivers() {
if (errorMessage != null) {
return [
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: loadItems,
child: Text(t.common.retry),
),
],
),
),
),
];
}
if (items.isEmpty && isLoading) {
return [
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
),
];
}
if (items.isEmpty) {
final icon = emptyIcon;
return [
SliverFillRemaining(
child: Center(
child: icon != null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(
emptyMessage,
style: const TextStyle(
fontSize: 16,
color: Colors.grey,
),
),
],
)
: Text(emptyMessage),
),
),
];
}
return [];
}
/// Build standard app bar actions (play, shuffle, delete)
/// Subclasses can override to customize actions
List<Widget> buildAppBarActions({
VoidCallback? onDelete,
String? deleteTooltip,
Color? deleteColor,
bool showDelete = true,
}) {
return [
// Play button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.play_arrow),
tooltip: t.discover.play,
onPressed: playItems,
),
// Shuffle button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.shuffle),
tooltip: t.common.shuffle,
onPressed: shufflePlayItems,
),
// Delete button
if (showDelete && onDelete != null)
IconButton(
icon: const Icon(Icons.delete),
tooltip: deleteTooltip ?? t.common.delete,
onPressed: onDelete,
color: deleteColor ?? Colors.red,
),
];
}
}
/// Mixin that provides standard loadItems implementation for media lists
/// Handles the common pattern of fetching, tagging, and setting items
mixin StandardItemLoader<T extends StatefulWidget>
on BaseMediaListDetailScreen<T> {
/// Fetch items from the API (must be implemented by subclass)
Future<List<PlexMetadata>> fetchItems();
/// Get error message for failed load (can be overridden)
String getLoadErrorMessage(Object error) {
return 'Failed to load items: ${error.toString()}';
}
/// Get log message for successful load (can be overridden)
String getLoadSuccessMessage(int itemCount) {
return 'Loaded $itemCount items';
}
@override
Future<void> loadItems() async {
if (mounted) {
setState(() {
isLoading = true;
errorMessage = null;
});
}
try {
// Items are automatically tagged with server info by PlexClient
final newItems = await fetchItems();
if (mounted) {
setState(() {
items = newItems;
isLoading = false;
});
}
appLogger.d(getLoadSuccessMessage(newItems.length));
} catch (e) {
appLogger.e('Failed to load items', error: e);
if (mounted) {
setState(() {
errorMessage = getLoadErrorMessage(e);
isLoading = false;
});
}
}
}
}
+16 -92
View File
@@ -2,13 +2,12 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/settings_provider.dart';
import '../utils/app_logger.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../i18n/strings.g.dart';
import '../utils/grid_size_calculator.dart';
import '../utils/dialogs.dart';
import '../utils/provider_extensions.dart';
import '../utils/app_logger.dart';
import 'base_media_list_detail_screen.dart';
/// Screen to display the contents of a collection
@@ -22,7 +21,8 @@ class CollectionDetailScreen extends StatefulWidget {
}
class _CollectionDetailScreenState
extends BaseMediaListDetailScreen<CollectionDetailScreen> {
extends BaseMediaListDetailScreen<CollectionDetailScreen>
with StandardItemLoader<CollectionDetailScreen> {
@override
PlexMetadata get mediaItem => widget.collection;
@@ -33,39 +33,18 @@ class _CollectionDetailScreenState
String get emptyMessage => t.collections.empty;
@override
Future<void> loadItems() async {
if (mounted) {
setState(() {
isLoading = true;
errorMessage = null;
});
}
Future<List<PlexMetadata>> fetchItems() async {
return await client.getCollectionItems(widget.collection.ratingKey);
}
try {
final client = this.client;
final newItems = await client.getCollectionItems(
widget.collection.ratingKey,
);
@override
String getLoadErrorMessage(Object error) {
return t.collections.failedToLoadItems(error: error.toString());
}
if (mounted) {
setState(() {
items = newItems;
isLoading = false;
});
}
appLogger.d(
'Loaded ${newItems.length} items for collection: ${widget.collection.title}',
);
} catch (e) {
appLogger.e('Failed to load collection items', error: e);
if (mounted) {
setState(() {
errorMessage = t.collections.failedToLoadItems(error: e.toString());
isLoading = false;
});
}
}
@override
String getLoadSuccessMessage(int itemCount) {
return 'Loaded $itemCount items for collection: ${widget.collection.title}';
}
Future<void> _deleteCollection() async {
@@ -97,10 +76,6 @@ class _CollectionDetailScreenState
if (!mounted) return;
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final success = await client.deleteCollection(
sectionId.toString(),
widget.collection.ratingKey,
@@ -145,61 +120,10 @@ class _CollectionDetailScreenState
CustomAppBar(
title: Text(widget.collection.title),
pinned: true,
actions: [
// Play button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.play_arrow),
tooltip: t.discover.play,
onPressed: playItems,
),
// Shuffle button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.shuffle),
tooltip: t.common.shuffle,
onPressed: shufflePlayItems,
),
// Delete button
IconButton(
icon: const Icon(Icons.delete),
tooltip: t.common.delete,
onPressed: _deleteCollection,
color: Colors.red,
),
],
actions: buildAppBarActions(onDelete: _deleteCollection),
),
if (errorMessage != null)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: Colors.red,
),
const SizedBox(height: 16),
Text(errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: loadItems,
child: Text(t.common.retry),
),
],
),
),
)
else if (items.isEmpty && isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (items.isEmpty)
SliverFillRemaining(
child: Center(child: Text(t.collections.noItems)),
)
else
...buildStateSlivers(),
if (items.isNotEmpty)
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
sliver: Consumer<SettingsProvider>(
File diff suppressed because it is too large Load Diff
+15 -18
View File
@@ -1,6 +1,6 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../../services/plex_client.dart';
import '../models/plex_hub.dart';
import '../models/plex_metadata.dart';
import '../models/plex_sort.dart';
@@ -10,7 +10,7 @@ import '../utils/app_logger.dart';
import '../utils/grid_cross_axis_extent.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/sort_bottom_sheet.dart';
import 'libraries/sort_bottom_sheet.dart';
import '../mixins/refreshable.dart';
import '../i18n/strings.g.dart';
@@ -25,7 +25,7 @@ class HubDetailScreen extends StatefulWidget {
}
class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
PlexClient get client => context.clientSafe;
PlexClient get client => _getClientForHub();
List<PlexMetadata> _items = [];
List<PlexMetadata> _filteredItems = [];
@@ -35,6 +35,11 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
bool _isLoading = false;
String? _errorMessage;
/// Get the correct PlexClient for this hub's server
PlexClient _getClientForHub() {
return context.getClientForServer(widget.hub.serverId!);
}
@override
void initState() {
super.initState();
@@ -51,9 +56,7 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
Future<void> _loadSorts() async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final client = _getClientForHub();
// Get the library key from the hub key
// Hub keys can have various formats:
@@ -197,27 +200,21 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final client = _getClientForHub();
// Fetch more items from the hub using the hubKey
final response = await client.getHubContent(widget.hub.hubKey);
// Fetch items from the hub, tagged with server info at the source
final items = await client.getHubContent(widget.hub.hubKey);
setState(() {
_items = response;
_filteredItems = response;
_items = items;
_filteredItems = items;
_isLoading = false;
});
// Apply any existing sort
_applySort();
appLogger.d(
'Loaded ${response.length} items for hub: ${widget.hub.title}',
);
appLogger.d('Loaded ${items.length} items for hub: ${widget.hub.title}');
} catch (e) {
appLogger.e('Failed to load hub content', error: e);
setState(() {
@@ -0,0 +1,86 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_metadata.dart';
import '../../providers/settings_provider.dart';
import '../../services/settings_service.dart' show ViewMode;
import '../../utils/grid_size_calculator.dart';
import '../../widgets/media_card.dart';
/// A widget that automatically switches between grid and list view
/// based on user settings, providing a consistent layout pattern
/// across all library screens
class AdaptiveMediaGrid extends StatelessWidget {
/// The list of media items to display
final List<PlexMetadata> items;
/// Callback when the list needs to be refreshed
final VoidCallback? onRefresh;
/// Optional padding around the grid/list
final EdgeInsets padding;
/// Child aspect ratio for grid items (width / height)
final double childAspectRatio;
/// Optional focus node for the first item (for keyboard navigation)
final FocusNode? firstItemFocusNode;
const AdaptiveMediaGrid({
super.key,
required this.items,
this.onRefresh,
this.padding = const EdgeInsets.fromLTRB(8, 8, 8, 8),
this.childAspectRatio = 2 / 3.3,
this.firstItemFocusNode,
});
@override
Widget build(BuildContext context) {
return Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return FocusTraversalGroup(
child: ListView.builder(
padding: padding,
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onListRefresh: onRefresh,
focusNode: index == 0 ? firstItemFocusNode : null,
);
},
),
);
} else {
return FocusTraversalGroup(
child: GridView.builder(
padding: padding,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: childAspectRatio,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onListRefresh: onRefresh,
focusNode: index == 0 ? firstItemFocusNode : null,
);
},
),
);
}
},
);
}
}
@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import '../i18n/strings.g.dart';
import '../../i18n/strings.g.dart';
import 'empty_state_widget.dart';
import 'error_state_widget.dart';
/// A widget that handles loading, error, empty, and content states
/// Provides a consistent UI pattern across the app for data-driven screens
@@ -45,36 +47,17 @@ class ContentStateBuilder<T> extends StatelessWidget {
// Error state (only show error if items list is empty)
if (errorMessage != null && items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(
errorMessage!,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white70),
),
const SizedBox(height: 16),
ElevatedButton(onPressed: onRetry, child: Text(t.common.retry)),
],
),
return ErrorStateWidget(
message: errorMessage!,
icon: Icons.error_outline,
onRetry: onRetry,
retryLabel: t.common.retry,
);
}
// Empty state
if (items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(emptyIcon, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(emptyMessage, style: const TextStyle(color: Colors.white70)),
],
),
);
return EmptyStateWidget(message: emptyMessage, icon: emptyIcon);
}
// Content state - delegate to builder
@@ -0,0 +1,22 @@
import 'package:flutter/material.dart';
/// A menu action item for context menus
class ContextMenuItem {
final String value;
final IconData icon;
final String label;
final bool requiresConfirmation;
final String? confirmationTitle;
final String? confirmationMessage;
final bool isDestructive;
const ContextMenuItem({
required this.value,
required this.icon,
required this.label,
this.requiresConfirmation = false,
this.confirmationTitle,
this.confirmationMessage,
this.isDestructive = false,
});
}
@@ -0,0 +1,36 @@
import 'package:flutter/material.dart';
import 'state_message_widget.dart';
/// A reusable widget for displaying empty states throughout the app
class EmptyStateWidget extends StatelessWidget {
/// The message to display
final String message;
/// Optional icon to display above the message
final IconData? icon;
/// Optional callback for action button
final VoidCallback? onAction;
/// Optional label for the action button
final String? actionLabel;
const EmptyStateWidget({
super.key,
required this.message,
this.icon,
this.onAction,
this.actionLabel,
});
@override
Widget build(BuildContext context) {
return StateMessageWidget(
message: message,
icon: icon,
onAction: onAction,
actionLabel: actionLabel,
actionIcon: Icons.add,
);
}
}
@@ -0,0 +1,38 @@
import 'package:flutter/material.dart';
import 'state_message_widget.dart';
/// A reusable widget for displaying error states throughout the app
class ErrorStateWidget extends StatelessWidget {
/// The error message to display
final String message;
/// Optional icon to display above the message
final IconData? icon;
/// Optional callback for retry action
final VoidCallback? onRetry;
/// Optional label for the retry button
final String? retryLabel;
const ErrorStateWidget({
super.key,
required this.message,
this.icon,
this.onRetry,
this.retryLabel,
});
@override
Widget build(BuildContext context) {
return StateMessageWidget(
message: message,
icon: icon,
iconColor: Theme.of(context).colorScheme.error,
textColor: Theme.of(context).colorScheme.error,
onAction: onRetry,
actionLabel: retryLabel ?? 'Retry',
actionIcon: Icons.refresh,
);
}
}
@@ -0,0 +1,320 @@
import 'package:flutter/material.dart';
import '../../models/plex_filter.dart';
import '../../widgets/app_bar_back_button.dart';
import '../../widgets/bottom_sheet_header.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/keyboard_utils.dart';
import '../../i18n/strings.g.dart';
class FiltersBottomSheet extends StatefulWidget {
final List<PlexFilter> filters;
final Map<String, String> selectedFilters;
final Function(Map<String, String>) onFiltersChanged;
final String serverId;
const FiltersBottomSheet({
super.key,
required this.filters,
required this.selectedFilters,
required this.onFiltersChanged,
required this.serverId,
});
@override
State<FiltersBottomSheet> createState() => _FiltersBottomSheetState();
}
class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
PlexFilter? _currentFilter;
List<PlexFilterValue> _filterValues = [];
bool _isLoadingValues = false;
final Map<String, String> _tempSelectedFilters = {};
final Map<String, String> _filterDisplayNames = {}; // Cache for display names
late List<PlexFilter> _sortedFilters;
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'FilterFirstItem',
);
final FocusNode _filterValuesFocusNode = FocusNode(
debugLabel: 'FilterValuesFirstItem',
);
@override
void initState() {
super.initState();
_tempSelectedFilters.addAll(widget.selectedFilters);
_sortFilters();
// Focus the first item after build
WidgetsBinding.instance.addPostFrameCallback((_) {
_firstItemFocusNode.requestFocus();
});
}
@override
void dispose() {
_firstItemFocusNode.dispose();
_filterValuesFocusNode.dispose();
super.dispose();
}
void _sortFilters() {
// Separate boolean filters (toggles) from regular filters
final booleanFilters = widget.filters
.where((f) => f.filterType == 'boolean')
.toList();
final regularFilters = widget.filters
.where((f) => f.filterType != 'boolean')
.toList();
// Combine with boolean filters first
_sortedFilters = [...booleanFilters, ...regularFilters];
}
bool _isBooleanFilter(PlexFilter filter) {
return filter.filterType == 'boolean';
}
Future<void> _loadFilterValues(PlexFilter filter) async {
setState(() {
_currentFilter = filter;
_isLoadingValues = true;
});
try {
final client = context.getClientForServer(widget.serverId);
final values = await client.getFilterValues(filter.key);
setState(() {
_filterValues = values;
_isLoadingValues = false;
});
// Focus the first filter value after loading
WidgetsBinding.instance.addPostFrameCallback((_) {
_filterValuesFocusNode.requestFocus();
});
} catch (e) {
setState(() {
_filterValues = [];
_isLoadingValues = false;
});
}
}
void _goBack() {
setState(() {
_currentFilter = null;
_filterValues = [];
});
}
void _applyFilters() {
widget.onFiltersChanged(_tempSelectedFilters);
Navigator.pop(context);
}
/// Handle back key - go back to main view or close sheet
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
if (_currentFilter != null) {
// Go back to main filters view
_goBack();
} else {
// Close the bottom sheet
Navigator.pop(context);
}
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
String _extractFilterValue(String key, String filterName) {
if (key.contains('?')) {
final queryStart = key.indexOf('?');
final queryString = key.substring(queryStart + 1);
final params = Uri.splitQueryString(queryString);
return params[filterName] ?? key;
} else if (key.startsWith('/')) {
return key.split('/').last;
}
return key;
}
@override
Widget build(BuildContext context) {
return Focus(
autofocus: true,
onKeyEvent: _handleBackKey,
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 ListTile(
focusNode: _filterValuesFocusNode,
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 ListTile(
title: Text(value.title),
selected: isSelected,
onTap: () {
setState(() {
_tempSelectedFilters[_currentFilter!.filter] =
filterValue;
// Cache the display name for this filter value
_filterDisplayNames['${_currentFilter!.filter}:$filterValue'] =
value.title;
});
_applyFilters();
},
);
},
),
),
],
);
}
// Show main filters view
return Column(
children: [
// Header
BottomSheetHeader(
title: t.libraries.filters,
leading: const Icon(Icons.filter_alt),
action: _tempSelectedFilters.isNotEmpty
? TextButton.icon(
onPressed: () {
setState(() {
_tempSelectedFilters.clear();
});
_applyFilters();
},
icon: const Icon(Icons.clear_all),
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 SwitchListTile(
focusNode: index == 0 ? _firstItemFocusNode : 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['${filter.filter}:$selectedValue'] ??
selectedValue;
}
return ListTile(
focusNode: index == 0 ? _firstItemFocusNode : 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 Icon(Icons.chevron_right),
],
),
onTap: () => _loadFilterValues(filter),
);
},
),
),
],
);
},
),
);
}
}
+159
View File
@@ -0,0 +1,159 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../models/plex_metadata.dart';
import '../../utils/keyboard_utils.dart';
/// Individual item in the folder tree
/// Can be either a folder (expandable) or a file (tappable)
class FolderTreeItem extends StatefulWidget {
final PlexMetadata item;
final int depth;
final bool isExpanded;
final bool isFolder;
final void Function({bool isKeyboard})? onTap;
final VoidCallback? onExpand;
final bool isLoading;
const FolderTreeItem({
super.key,
required this.item,
required this.depth,
this.isExpanded = false,
this.isFolder = false,
this.onTap,
this.onExpand,
this.isLoading = false,
});
@override
State<FolderTreeItem> createState() => _FolderTreeItemState();
}
class _FolderTreeItemState extends State<FolderTreeItem> {
bool _isKeyboardActivation = false;
IconData _getIcon() {
if (widget.isFolder) {
return Icons.folder;
}
// File icons based on type
final type = widget.item.type.toLowerCase();
switch (type) {
case 'movie':
return Icons.movie;
case 'show':
return Icons.tv;
case 'season':
return Icons.video_library;
case 'episode':
return Icons.play_circle_outline;
case 'collection':
return Icons.collections;
default:
return Icons.insert_drive_file;
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent && isKeyboardActivationKey(event.logicalKey)) {
_isKeyboardActivation = true;
return KeyEventResult.ignored; // Let InkWell handle the activation
}
return KeyEventResult.ignored;
}
void _handleTap() {
if (widget.isFolder) {
widget.onExpand?.call();
} else {
widget.onTap?.call(isKeyboard: _isKeyboardActivation);
}
_isKeyboardActivation = false;
}
@override
Widget build(BuildContext context) {
final indentation = widget.depth * 24.0;
return Focus(
onKeyEvent: _handleKeyEvent,
child: InkWell(
onTap: _handleTap,
child: Container(
padding: EdgeInsets.only(
left: 16.0 + indentation,
right: 16.0,
top: 12.0,
bottom: 12.0,
),
child: Row(
children: [
// Expand/collapse icon for folders
if (widget.isFolder)
SizedBox(
width: 24,
child: widget.isLoading
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Icon(
widget.isExpanded
? Icons.keyboard_arrow_down
: Icons.keyboard_arrow_right,
size: 20,
),
)
else
const SizedBox(width: 24),
const SizedBox(width: 8),
// File/folder icon
Icon(
_getIcon(),
size: 20,
color: widget.isFolder
? Theme.of(context).colorScheme.primary
: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.7),
),
const SizedBox(width: 12),
// Item title
Expanded(
child: Text(
widget.item.title,
style: TextStyle(
fontSize: 14,
fontWeight: widget.isFolder
? FontWeight.w500
: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
// Additional metadata for files
if (!widget.isFolder && widget.item.year != null)
Text(
widget.item.year.toString(),
style: TextStyle(
fontSize: 12,
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.6),
),
),
],
),
),
),
);
}
}
@@ -1,21 +1,28 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/plex_client_provider.dart';
import '../utils/app_logger.dart';
import '../utils/video_player_navigation.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import '../../models/plex_metadata.dart';
import '../media_detail_screen.dart';
import '../season_detail_screen.dart';
import '../../utils/app_logger.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/video_player_navigation.dart';
import '../../i18n/strings.g.dart';
import 'folder_tree_item.dart';
import '../i18n/strings.g.dart';
import 'empty_state_widget.dart';
import 'error_state_widget.dart';
/// Expandable tree view for browsing library folders
/// Shows a hierarchical file/folder structure
class FolderTreeView extends StatefulWidget {
final String libraryKey;
final String? serverId; // Server this library belongs to
final void Function(String)? onRefresh;
const FolderTreeView({super.key, required this.libraryKey, this.onRefresh});
const FolderTreeView({
super.key,
required this.libraryKey,
this.serverId,
this.onRefresh,
});
@override
State<FolderTreeView> createState() => _FolderTreeViewState();
@@ -42,18 +49,23 @@ class _FolderTreeViewState extends State<FolderTreeView> {
});
try {
final clientProvider = context.read<PlexClientProvider>();
final client = clientProvider.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final client = context.getClientForServer(widget.serverId!);
final folders = await client.getLibraryFolders(widget.libraryKey);
if (!mounted) return;
final taggedFolders = folders
.map(
(folder) => folder.copyWith(
serverId: widget.serverId!,
serverName: null, // server name not required for folders listing
),
)
.toList();
setState(() {
_rootFolders = folders;
_rootFolders = taggedFolders;
_isLoadingRoot = false;
});
@@ -89,12 +101,9 @@ class _FolderTreeViewState extends State<FolderTreeView> {
});
try {
final clientProvider = context.read<PlexClientProvider>();
final client = clientProvider.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final client = context.getClientForServer(widget.serverId!);
// Items are automatically tagged with server info by PlexClient
final children = await client.getFolderChildren(folder.key);
if (!mounted) return;
@@ -141,7 +150,10 @@ class _FolderTreeViewState extends State<FolderTreeView> {
}
}
Future<void> _handleItemTap(PlexMetadata item) async {
Future<void> _handleItemTap(
PlexMetadata item, {
bool isKeyboard = false,
}) async {
final itemType = item.type.toLowerCase();
// For episodes, start playback directly
@@ -154,7 +166,8 @@ class _FolderTreeViewState extends State<FolderTreeView> {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SeasonDetailScreen(season: item),
builder: (context) =>
SeasonDetailScreen(season: item, focusFirstEpisode: isKeyboard),
),
);
widget.onRefresh?.call(item.ratingKey);
@@ -206,7 +219,10 @@ class _FolderTreeViewState extends State<FolderTreeView> {
isExpanded: isExpanded,
isLoading: isLoading,
onExpand: isFolder ? () => _toggleFolder(item) : null,
onTap: !isFolder ? () => _handleItemTap(item) : null,
onTap: !isFolder
? ({bool isKeyboard = false}) =>
_handleItemTap(item, isKeyboard: isKeyboard)
: null,
),
);
@@ -227,33 +243,18 @@ class _FolderTreeViewState extends State<FolderTreeView> {
}
if (_errorMessage != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadRootFolders,
child: Text(t.common.retry),
),
],
),
return ErrorStateWidget(
message: _errorMessage!,
icon: Icons.error_outline,
onRetry: _loadRootFolders,
retryLabel: t.common.retry,
);
}
if (_rootFolders.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.folder_open, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(t.libraries.noFoldersFound),
],
),
return EmptyStateWidget(
message: t.libraries.noFoldersFound,
icon: Icons.folder_open,
);
}
File diff suppressed because it is too large Load Diff
+65
View File
@@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
/// A small badge widget that indicates which server content is from
/// Shows server name or first letter with optional tooltip
class ServerBadge extends StatelessWidget {
final String? serverName;
final Color? backgroundColor;
final Color? textColor;
final double size;
final bool showFullName;
const ServerBadge({
super.key,
required this.serverName,
this.backgroundColor,
this.textColor,
this.size = 20,
this.showFullName = false,
});
@override
Widget build(BuildContext context) {
if (serverName == null || serverName!.isEmpty) {
return const SizedBox.shrink();
}
final theme = Theme.of(context);
final bgColor =
backgroundColor ??
theme.colorScheme.primaryContainer.withValues(alpha: 0.8);
final fgColor = textColor ?? theme.colorScheme.onPrimaryContainer;
final displayText = showFullName
? serverName!
: serverName!.substring(0, 1).toUpperCase();
final badge = Container(
padding: EdgeInsets.symmetric(
horizontal: showFullName ? 6 : 4,
vertical: 2,
),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(4),
),
child: Text(
displayText,
style: TextStyle(
color: fgColor,
fontSize: showFullName ? 10 : 11,
fontWeight: FontWeight.w600,
height: 1.2,
),
),
);
// If showing full name, no need for tooltip
if (showFullName) {
return badge;
}
// Show tooltip with full server name on hover/long press
return Tooltip(message: serverName!, child: badge);
}
}
@@ -0,0 +1,164 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../models/plex_sort.dart';
import '../../widgets/bottom_sheet_header.dart';
import '../../utils/keyboard_utils.dart';
import '../../i18n/strings.g.dart';
class SortBottomSheet extends StatefulWidget {
final List<PlexSort> sortOptions;
final PlexSort? selectedSort;
final bool isSortDescending;
final Function(PlexSort, bool) onSortChanged;
final VoidCallback? onClear;
const SortBottomSheet({
super.key,
required this.sortOptions,
required this.selectedSort,
required this.isSortDescending,
required this.onSortChanged,
this.onClear,
});
@override
State<SortBottomSheet> createState() => _SortBottomSheetState();
}
class _SortBottomSheetState extends State<SortBottomSheet> {
late PlexSort? _currentSort;
late bool _currentDescending;
final FocusNode _firstItemFocusNode = FocusNode(debugLabel: 'SortFirstItem');
@override
void initState() {
super.initState();
_currentSort = widget.selectedSort;
_currentDescending = widget.isSortDescending;
// Focus the first item after build
WidgetsBinding.instance.addPostFrameCallback((_) {
_firstItemFocusNode.requestFocus();
});
}
@override
void dispose() {
_firstItemFocusNode.dispose();
super.dispose();
}
void _handleSortChange(PlexSort sort, bool descending) {
setState(() {
_currentSort = sort;
_currentDescending = descending;
});
widget.onSortChanged(sort, descending);
Navigator.pop(context);
}
void _handleClear() {
setState(() {
_currentSort = null;
_currentDescending = false;
});
widget.onClear?.call();
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
return Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(context);
return KeyEventResult.handled;
}
// Left/right arrows toggle sort direction when a sort is selected
if (event is KeyDownEvent && _currentSort != null) {
if (event.logicalKey == LogicalKeyboardKey.arrowLeft &&
_currentDescending) {
_handleSortChange(_currentSort!, false);
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowRight &&
!_currentDescending) {
_handleSortChange(_currentSort!, true);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
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: FocusTraversalGroup(
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 RadioListTile<PlexSort>(
focusNode: index == 0 ? _firstItemFocusNode : null,
title: Text(sort.title),
value: sort,
groupValue: _currentSort,
onChanged: (value) {
if (value != null) {
_handleSortChange(value, value.isDefaultDescending);
}
},
secondary: isSelected
? ExcludeFocus(
child: SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: Icon(Icons.arrow_upward, size: 16),
),
ButtonSegment(
value: true,
icon: Icon(
Icons.arrow_downward,
size: 16,
),
),
],
selected: {_currentDescending},
onSelectionChanged: (Set<bool> newSelection) {
_handleSortChange(sort, newSelection.first);
},
),
)
: null,
);
},
),
),
),
],
);
},
),
);
}
}
@@ -1,25 +1,38 @@
import 'package:flutter/material.dart';
/// A reusable widget for displaying empty states throughout the app
class EmptyStateWidget extends StatelessWidget {
/// Base widget for displaying state messages (empty, error, etc.)
/// Provides a consistent UI pattern for showing icons, messages, and actions
class StateMessageWidget extends StatelessWidget {
/// The message to display
final String message;
/// Optional icon to display above the message
final IconData? icon;
/// Optional color for the icon
final Color? iconColor;
/// Optional color for the message text
final Color? textColor;
/// Optional callback for action button
final VoidCallback? onAction;
/// Optional label for the action button
final String? actionLabel;
const EmptyStateWidget({
/// Optional icon for the action button
final IconData? actionIcon;
const StateMessageWidget({
super.key,
required this.message,
this.icon,
this.iconColor,
this.textColor,
this.onAction,
this.actionLabel,
this.actionIcon,
});
@override
@@ -34,9 +47,11 @@ class EmptyStateWidget extends StatelessWidget {
Icon(
icon,
size: 64,
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.4),
color:
iconColor ??
Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.4),
),
const SizedBox(height: 16),
],
@@ -44,16 +59,18 @@ class EmptyStateWidget extends StatelessWidget {
message,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.6),
color:
textColor ??
Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.6),
),
),
if (onAction != null && actionLabel != null) ...[
const SizedBox(height: 24),
FilledButton.icon(
onPressed: onAction,
icon: const Icon(Icons.add),
icon: Icon(actionIcon ?? Icons.refresh),
label: Text(actionLabel!),
),
],
@@ -0,0 +1,170 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../../models/plex_library.dart';
import '../../../utils/app_logger.dart';
import '../../../mixins/library_tab_state.dart';
import '../../../mixins/refreshable.dart';
import '../content_state_builder.dart';
/// Base class for library tab screens that provides common state management
/// and lifecycle handling for tabs that display library content.
///
/// Type parameter T: The type of items this tab displays
///
/// Subclasses must implement:
/// - [loadData]: Load data from the Plex API
/// - [buildContent]: Build the UI for displaying loaded items
///
/// Optional overrides:
/// - [emptyIcon]: Icon to show when there are no items
/// - [emptyMessage]: Message to show when there are no items
/// - [errorContext]: Context for error messages (defaults to "content")
/// - [getRefreshStream]: Stream to listen for refresh events
abstract class BaseLibraryTab<T> extends StatefulWidget {
final PlexLibrary library;
final String? viewMode;
final String? density;
const BaseLibraryTab({
super.key,
required this.library,
this.viewMode,
this.density,
});
}
/// State mixin that provides the common implementation for library tabs
/// This preserves AutomaticKeepAliveClientMixin functionality
abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
extends State<W>
with AutomaticKeepAliveClientMixin, Refreshable, LibraryTabStateMixin {
@override
bool get wantKeepAlive => true;
@override
PlexLibrary get library => widget.library;
@override
void refresh() {
loadItems();
}
// State management
List<T> _items = [];
bool _isLoading = false;
String? _errorMessage;
StreamSubscription<void>? _refreshSubscription;
// Getters for subclasses
List<T> get items => _items;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
@override
void initState() {
super.initState();
loadItems();
// Subscribe to refresh stream if provided
final refreshStream = getRefreshStream();
if (refreshStream != null) {
_refreshSubscription = refreshStream.listen((_) {
if (mounted) {
loadItems();
}
});
}
}
@override
void dispose() {
_refreshSubscription?.cancel();
super.dispose();
}
@override
void didUpdateWidget(W oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.globalKey != widget.library.globalKey) {
loadItems();
}
}
/// Load items from the API
/// This is the main data loading function that subclasses must implement
Future<List<T>> loadData();
/// Build the content widget given the loaded items
/// This is called by ContentStateBuilder when items are available
Widget buildContent(List<T> items);
/// Icon to display when there are no items (empty state)
IconData get emptyIcon;
/// Message to display when there are no items (empty state)
String get emptyMessage;
/// Context string for error messages (e.g., "playlists", "collections")
String get errorContext;
/// Optional refresh stream to listen for external refresh events
/// Return null if no refresh stream is needed
Stream<void>? getRefreshStream() => null;
/// Load items with error handling and state management
Future<void> loadItems() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final loadedItems = await loadData();
if (!mounted) return;
setState(() {
_items = loadedItems;
_isLoading = false;
});
} catch (e) {
if (!mounted) return;
appLogger.e('Error loading $errorContext', error: e);
setState(() {
_errorMessage = 'Failed to load $errorContext: ${e.toString()}';
_isLoading = false;
});
}
}
/// Focus the first item in the tab content
/// Subclasses can override this for custom focus behavior
void focusFirstItem() {
// Default implementation: try to focus the first focusable item
if (_items.isNotEmpty && mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
FocusScope.of(context).nextFocus();
}
});
}
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
return ContentStateBuilder<T>(
isLoading: _isLoading,
errorMessage: _errorMessage,
items: _items,
emptyIcon: emptyIcon,
emptyMessage: emptyMessage,
onRetry: loadItems,
builder: (items) =>
RefreshIndicator(onRefresh: loadItems, child: buildContent(items)),
);
}
}
@@ -1,25 +1,28 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:dio/dio.dart';
import '../../client/plex_client.dart';
import '../../models/plex_library.dart';
import '../../models/plex_metadata.dart';
import '../../models/plex_filter.dart';
import '../../models/plex_sort.dart';
import '../../providers/plex_client_provider.dart';
import '../../providers/settings_provider.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/error_message_utils.dart';
import '../../utils/grid_size_calculator.dart';
import '../../widgets/media_card.dart';
import '../../widgets/folder_tree_view.dart';
import '../../widgets/filters_bottom_sheet.dart';
import '../../widgets/sort_bottom_sheet.dart';
import '../../services/storage_service.dart';
import '../../services/settings_service.dart' show ViewMode;
import '../../mixins/item_updatable.dart';
import '../../mixins/refreshable.dart';
import '../../i18n/strings.g.dart';
import '../../../../services/plex_client.dart';
import '../../../models/plex_library.dart';
import '../../../models/plex_metadata.dart';
import '../../../models/plex_filter.dart';
import '../../../models/plex_sort.dart';
import '../../../providers/settings_provider.dart';
import '../../../utils/error_message_utils.dart';
import '../../../utils/grid_size_calculator.dart';
import '../../../utils/keyboard_utils.dart';
import '../../../widgets/media_card.dart';
import '../folder_tree_view.dart';
import '../filters_bottom_sheet.dart';
import '../sort_bottom_sheet.dart';
import '../empty_state_widget.dart';
import '../error_state_widget.dart';
import '../../../services/storage_service.dart';
import '../../../services/settings_service.dart' show ViewMode;
import '../../../mixins/item_updatable.dart';
import '../../../mixins/library_tab_state.dart';
import '../../../mixins/refreshable.dart';
import '../../../i18n/strings.g.dart';
/// Browse tab for library screen
/// Shows library items with grouping, filtering, and sorting
@@ -40,12 +43,19 @@ class LibraryBrowseTab extends StatefulWidget {
}
class _LibraryBrowseTabState extends State<LibraryBrowseTab>
with AutomaticKeepAliveClientMixin, ItemUpdatable, Refreshable {
with
AutomaticKeepAliveClientMixin,
ItemUpdatable,
Refreshable,
LibraryTabStateMixin {
@override
bool get wantKeepAlive => true;
@override
PlexClient get client => context.clientSafe;
PlexLibrary get library => widget.library;
@override
PlexClient get client => getClientForLibrary();
@override
void refresh() {
@@ -79,6 +89,11 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
int _requestId = 0;
static const int _pageSize = 500;
/// Focus node for the first item in the list/grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'BrowseFirstItem',
);
@override
void initState() {
super.initState();
@@ -89,7 +104,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
void didUpdateWidget(LibraryBrowseTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.key != widget.library.key) {
if (oldWidget.library.globalKey != widget.library.globalKey) {
_loadContent();
}
}
@@ -97,17 +112,25 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
@override
void dispose() {
_cancelToken?.cancel();
_firstItemFocusNode.dispose();
super.dispose();
}
/// Focus the first item in the list/grid
void focusFirstItem() {
if (_items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
}
}
Future<void> _loadContent() async {
// Cancel any pending request
_cancelToken?.cancel();
_cancelToken = CancelToken();
final currentRequestId = ++_requestId;
// Extract context dependencies before async gap
final clientProvider = context.plexClient;
// Extract context dependencies before async gap - use server-specific client
final client = getClientForLibrary();
setState(() {
_isLoading = true;
@@ -118,11 +141,6 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
});
try {
final client = clientProvider.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final storage = await StorageService.getInstance();
// Load filters and sorts for this library
@@ -131,10 +149,12 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
// Load saved preferences
final savedFilters = storage.getLibraryFilters(
sectionId: widget.library.key,
sectionId: widget.library.globalKey,
);
final savedSort = storage.getLibrarySort(widget.library.globalKey);
final savedGrouping = storage.getLibraryGrouping(
widget.library.globalKey,
);
final savedSort = storage.getLibrarySort(widget.library.key);
final savedGrouping = storage.getLibraryGrouping(widget.library.key);
// Check if request was cancelled
if (currentRequestId != _requestId) return;
@@ -161,12 +181,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
// Load items
await _loadItems();
} catch (e) {
if (currentRequestId != _requestId) return;
setState(() {
_errorMessage = _getErrorMessage(e);
_isLoading = false;
});
_handleLoadError(e, currentRequestId);
}
}
@@ -192,10 +207,8 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
});
try {
final client = context.read<PlexClientProvider>().client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
// Use server-specific client for this library
final client = getClientForLibrary();
// Build filter params
final filterParams = Map<String, String>.from(_selectedFilters);
@@ -215,6 +228,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
);
}
// Items are automatically tagged with server info by PlexClient
final items = await client.getLibraryContent(
widget.library.key,
start: _currentPage * _pageSize,
@@ -236,15 +250,19 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
_isLoading = false;
});
} catch (e) {
if (currentRequestId != _requestId) return;
setState(() {
_errorMessage = _getErrorMessage(e);
_isLoading = false;
});
_handleLoadError(e, currentRequestId);
}
}
void _handleLoadError(dynamic error, int currentRequestId) {
if (currentRequestId != _requestId) return;
setState(() {
_errorMessage = _getErrorMessage(error);
_isLoading = false;
});
}
String _getDefaultGrouping() {
final type = widget.library.type.toLowerCase();
if (type == 'show') {
@@ -308,33 +326,50 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
void _showGroupingBottomSheet() {
showModalBottomSheet(
context: context,
builder: (context) {
return ListView(
shrinkWrap: true,
children: _getGroupingOptions().map((grouping) {
return RadioListTile<String>(
title: Text(_getGroupingLabel(grouping)),
value: grouping,
// ignore: deprecated_member_use
groupValue: _selectedGrouping,
// ignore: deprecated_member_use
onChanged: (value) async {
if (value != null) {
setState(() {
_selectedGrouping = value;
});
builder: (sheetContext) {
final options = _getGroupingOptions();
return Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(sheetContext);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: FocusTraversalGroup(
child: ListView.builder(
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (context, index) {
final grouping = options[index];
return RadioListTile<String>(
autofocus: index == 0,
title: Text(_getGroupingLabel(grouping)),
value: grouping,
groupValue: _selectedGrouping,
onChanged: (value) async {
if (value != null) {
setState(() {
_selectedGrouping = value;
});
final storage = await StorageService.getInstance();
await storage.saveLibraryGrouping(widget.library.key, value);
final storage = await StorageService.getInstance();
await storage.saveLibraryGrouping(
widget.library.globalKey,
value,
);
if (!mounted) return;
if (!sheetContext.mounted) return;
Navigator.pop(context);
_loadItems();
}
Navigator.pop(sheetContext);
_loadItems();
}
},
);
},
);
}).toList(),
),
),
);
},
);
@@ -347,6 +382,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
builder: (context) => FiltersBottomSheet(
filters: _filters,
selectedFilters: _selectedFilters,
serverId: widget.library.serverId!,
onFiltersChanged: (filters) async {
setState(() {
_selectedFilters.clear();
@@ -357,7 +393,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
final storage = await StorageService.getInstance();
await storage.saveLibraryFilters(
filters,
sectionId: widget.library.key,
sectionId: widget.library.globalKey,
);
_loadItems();
@@ -382,7 +418,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
StorageService.getInstance().then((storage) {
storage.saveLibrarySort(
widget.library.key,
widget.library.globalKey,
sort.key,
descending: descending,
);
@@ -399,32 +435,52 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
required String label,
required VoidCallback onPressed,
}) {
return InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: 16,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(width: 6),
Text(
label,
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
return Focus(
onKeyEvent: (node, event) {
if (event is KeyDownEvent) {
if (isKeyboardActivationKey(event.logicalKey)) {
onPressed();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
child: Builder(
builder: (context) {
final isFocused = Focus.of(context).hasFocus;
final colorScheme = Theme.of(context).colorScheme;
// When focused: inverse colors (white bg + dark text in dark mode, dark bg + light text in light mode)
final backgroundColor = isFocused
? colorScheme.onSurface
: colorScheme.surfaceContainerHighest;
final foregroundColor = isFocused
? colorScheme.surface
: colorScheme.onSurfaceVariant;
return InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 16, color: foregroundColor),
const SizedBox(width: 6),
Text(
label,
style: Theme.of(
context,
).textTheme.labelMedium?.copyWith(color: foregroundColor),
),
],
),
),
],
),
);
},
),
);
}
@@ -487,6 +543,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
if (_selectedGrouping == 'folders') {
return FolderTreeView(
libraryKey: widget.library.key,
serverId: widget.library.serverId,
onRefresh: updateItem,
);
}
@@ -496,33 +553,18 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
}
if (_errorMessage != null && _items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadContent,
child: Text(t.common.retry),
),
],
),
return ErrorStateWidget(
message: _errorMessage!,
icon: Icons.error_outline,
onRetry: _loadContent,
retryLabel: t.common.retry,
);
}
if (_items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.folder_open, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(t.libraries.thisLibraryIsEmpty),
],
),
return EmptyStateWidget(
message: t.libraries.thisLibraryIsEmpty,
icon: Icons.folder_open,
);
}
@@ -539,52 +581,53 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
child: Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
itemCount: _items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) {
if (index >= _items.length) {
return const Padding(
padding: EdgeInsets.all(16.0),
child: Center(child: CircularProgressIndicator()),
);
}
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
},
return ClipRect(
child: ListView.builder(
clipBehavior: Clip.none, // Allow focus indicator to overflow
padding: const EdgeInsets.all(8),
itemCount:
_items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) => _buildMediaCardItem(index),
),
);
} else {
return GridView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
return ClipRect(
child: GridView.builder(
clipBehavior: Clip.none, // Allow focus indicator to overflow
padding: const EdgeInsets.all(8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
itemCount:
_items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) => _buildMediaCardItem(index),
),
itemCount: _items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) {
if (index >= _items.length) {
return const Center(child: CircularProgressIndicator());
}
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
},
);
}
},
),
);
}
Widget _buildMediaCardItem(int index) {
if (index >= _items.length) {
return const Padding(
padding: EdgeInsets.all(16.0),
child: Center(child: CircularProgressIndicator()),
);
}
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
focusNode: index == 0 ? _firstItemFocusNode : null,
);
}
}
@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import '../../../models/plex_metadata.dart';
import '../../../utils/library_refresh_notifier.dart';
import '../../../i18n/strings.g.dart';
import '../adaptive_media_grid.dart';
import 'base_library_tab.dart';
/// Collections tab for library screen
/// Shows collections for the current library
class LibraryCollectionsTab extends BaseLibraryTab<PlexMetadata> {
const LibraryCollectionsTab({
super.key,
required super.library,
super.viewMode,
super.density,
});
@override
State<LibraryCollectionsTab> createState() => _LibraryCollectionsTabState();
}
class _LibraryCollectionsTabState
extends BaseLibraryTabState<PlexMetadata, LibraryCollectionsTab> {
/// Focus node for the first item in the grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'CollectionsFirstItem',
);
@override
void dispose() {
_firstItemFocusNode.dispose();
super.dispose();
}
@override
IconData get emptyIcon => Icons.collections;
@override
String get emptyMessage => t.libraries.noCollections;
@override
String get errorContext => t.collections.title;
@override
Stream<void>? getRefreshStream() =>
LibraryRefreshNotifier().collectionsStream;
@override
Future<List<PlexMetadata>> loadData() async {
// Use server-specific client for this library
final client = getClientForLibrary();
// Collections are automatically tagged with server info by PlexClient
return await client.getLibraryCollections(widget.library.key);
}
@override
void focusFirstItem() {
if (items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
}
}
@override
Widget buildContent(List<PlexMetadata> items) {
return AdaptiveMediaGrid(
items: items,
onRefresh: loadItems,
firstItemFocusNode: _firstItemFocusNode,
);
}
}
@@ -0,0 +1,110 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../models/plex_playlist.dart';
import '../../../providers/settings_provider.dart';
import '../../../utils/library_refresh_notifier.dart';
import '../../../services/settings_service.dart' show ViewMode;
import '../../../utils/grid_size_calculator.dart';
import '../../../widgets/media_card.dart';
import '../../../i18n/strings.g.dart';
import 'base_library_tab.dart';
/// Playlists tab for library screen
/// Shows playlists that contain items from the current library
class LibraryPlaylistsTab extends BaseLibraryTab<PlexPlaylist> {
const LibraryPlaylistsTab({
super.key,
required super.library,
super.viewMode,
super.density,
});
@override
State<LibraryPlaylistsTab> createState() => _LibraryPlaylistsTabState();
}
class _LibraryPlaylistsTabState
extends BaseLibraryTabState<PlexPlaylist, LibraryPlaylistsTab> {
/// Focus node for the first item in the grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'PlaylistsFirstItem',
);
@override
void dispose() {
_firstItemFocusNode.dispose();
super.dispose();
}
@override
IconData get emptyIcon => Icons.playlist_play;
@override
String get emptyMessage => t.playlists.noPlaylists;
@override
String get errorContext => t.playlists.title;
@override
Stream<void>? getRefreshStream() => LibraryRefreshNotifier().playlistsStream;
@override
Future<List<PlexPlaylist>> loadData() async {
// Use server-specific client for this library
final client = getClientForLibrary();
// Playlists are automatically tagged with server info by PlexClient
return await client.getLibraryPlaylists(
sectionId: widget.library.key,
playlistType: 'video',
);
}
@override
void focusFirstItem() {
if (items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
}
}
@override
Widget buildContent(List<PlexPlaylist> items) {
return Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
itemCount: items.length,
itemBuilder: (context, index) =>
_buildPlaylistItem(items[index], index),
);
} else {
return GridView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) =>
_buildPlaylistItem(items[index], index),
);
}
},
);
}
Widget _buildPlaylistItem(PlexPlaylist playlist, int index) {
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: loadItems,
focusNode: index == 0 ? _firstItemFocusNode : null,
);
}
}
@@ -0,0 +1,164 @@
import 'package:flutter/material.dart';
import '../../../../services/plex_client.dart';
import '../../../i18n/strings.g.dart';
import '../../../mixins/item_updatable.dart';
import '../../../models/plex_hub.dart';
import '../../../models/plex_metadata.dart';
import '../../../widgets/hub_navigation_controller.dart';
import '../../../widgets/hub_section.dart';
import 'base_library_tab.dart';
/// Recommended tab for library screen
/// Shows library-specific hubs and recommendations, including dedicated Continue Watching
class LibraryRecommendedTab extends BaseLibraryTab<PlexHub> {
const LibraryRecommendedTab({super.key, required super.library});
@override
State<LibraryRecommendedTab> createState() => _LibraryRecommendedTabState();
}
class _LibraryRecommendedTabState
extends BaseLibraryTabState<PlexHub, LibraryRecommendedTab>
with ItemUpdatable {
final HubNavigationController _hubNavigationController =
HubNavigationController();
@override
void dispose() {
_hubNavigationController.dispose();
super.dispose();
}
/// Focus the first item in the first hub
@override
void focusFirstItem() {
_hubNavigationController.focusHub(0, 0);
}
@override
PlexClient get client => getClientForLibrary();
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
// Update the item in any hub that contains it
for (final hub in items) {
final itemIndex = hub.items.indexWhere(
(item) => item.ratingKey == ratingKey,
);
if (itemIndex != -1) {
hub.items[itemIndex] = updatedMetadata;
}
}
}
@override
IconData get emptyIcon => Icons.recommend;
@override
String get emptyMessage => t.libraries.noRecommendations;
@override
String get errorContext => t.libraries.tabs.recommended;
@override
Future<List<PlexHub>> loadData() async {
// Use server-specific client for this library
final client = getClientForLibrary();
// Load both continue watching items and regular hubs in parallel
final results = await Future.wait([
client.getOnDeckForLibrary(widget.library.key),
client.getLibraryHubs(widget.library.key, limit: 12),
]);
final continueWatchingItems = results[0] as List<PlexMetadata>;
final hubs = results[1] as List<PlexHub>;
// Filter out any existing Continue Watching hubs since we're adding our own
final filteredHubs = hubs.where((hub) {
final title = hub.title.toLowerCase();
final hubId = hub.hubIdentifier?.toLowerCase() ?? '';
return !title.contains('continue watching') &&
!title.contains('on deck') &&
!hubId.contains('ondeck') &&
!hubId.contains('continue');
}).toList();
final finalHubs = <PlexHub>[];
// Add Continue Watching as the first hub if there are items
if (continueWatchingItems.isNotEmpty) {
final continueWatchingHub = PlexHub(
hubKey: 'library_continue_watching_${widget.library.key}',
title: t.discover.continueWatching,
type: 'mixed',
hubIdentifier: '_library_continue_watching_',
size: continueWatchingItems.length,
more: false,
items: continueWatchingItems,
serverId: widget.library.serverId,
serverName: widget.library.serverName,
);
finalHubs.add(continueWatchingHub);
}
// Add the filtered regular hubs
finalHubs.addAll(filteredHubs);
return finalHubs;
}
@override
Widget buildContent(List<PlexHub> items) {
return HubNavigationScope(
controller: _hubNavigationController,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: items.length,
itemBuilder: (context, index) {
final hub = items[index];
final isContinueWatching =
hub.hubIdentifier == '_library_continue_watching_';
return HubSection(
hub: hub,
icon: _getHubIcon(hub),
navigationOrder: index,
isInContinueWatching: isContinueWatching,
onRefresh: updateItem,
onRemoveFromContinueWatching: isContinueWatching
? _refreshContinueWatching
: null,
);
},
),
);
}
/// Refresh the Continue Watching section
void _refreshContinueWatching() {
// Reload all data to refresh the continue watching section
loadItems();
}
IconData _getHubIcon(PlexHub hub) {
final title = hub.title.toLowerCase();
if (title.contains('continue watching') || title.contains('on deck')) {
return Icons.play_circle;
} else if (title.contains('recently') || title.contains('new')) {
return Icons.fiber_new;
} else if (title.contains('popular') || title.contains('trending')) {
return Icons.trending_up;
} else if (title.contains('top') || title.contains('rated')) {
return Icons.star;
} else if (title.contains('recommended')) {
return Icons.thumb_up;
} else if (title.contains('unwatched')) {
return Icons.visibility_off;
} else if (title.contains('genre')) {
return Icons.category;
}
return Icons.movie;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,130 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_library.dart';
import '../../models/plex_metadata.dart';
import '../../providers/plex_client_provider.dart';
import '../../utils/app_logger.dart';
import '../../utils/library_refresh_notifier.dart';
import '../../i18n/strings.g.dart';
import '../../mixins/refreshable.dart';
import '../../widgets/content_state_builder.dart';
import '../../widgets/adaptive_media_grid.dart';
/// Collections tab for library screen
/// Shows collections for the current library
class LibraryCollectionsTab extends StatefulWidget {
final PlexLibrary library;
final String? viewMode;
final String? density;
const LibraryCollectionsTab({
super.key,
required this.library,
this.viewMode,
this.density,
});
@override
State<LibraryCollectionsTab> createState() => _LibraryCollectionsTabState();
}
class _LibraryCollectionsTabState extends State<LibraryCollectionsTab>
with AutomaticKeepAliveClientMixin, Refreshable {
@override
bool get wantKeepAlive => true;
@override
void refresh() {
_loadCollections();
}
List<PlexMetadata> _collections = [];
bool _isLoading = false;
String? _errorMessage;
StreamSubscription<void>? _refreshSubscription;
@override
void initState() {
super.initState();
_loadCollections();
// Listen for refresh notifications
_refreshSubscription = LibraryRefreshNotifier().collectionsStream.listen((
_,
) {
if (mounted) {
_loadCollections();
}
});
}
@override
void dispose() {
_refreshSubscription?.cancel();
super.dispose();
}
@override
void didUpdateWidget(LibraryCollectionsTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.key != widget.library.key) {
_loadCollections();
}
}
Future<void> _loadCollections() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final client = context.read<PlexClientProvider>().client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final collections = await client.getLibraryCollections(
widget.library.key,
);
if (!mounted) return;
setState(() {
_collections = collections;
_isLoading = false;
});
} catch (e) {
if (!mounted) return;
appLogger.e('Error loading collections', error: e);
setState(() {
_errorMessage = t.errors.failedToLoad(
context: t.collections.title,
error: e.toString(),
);
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
return ContentStateBuilder<PlexMetadata>(
isLoading: _isLoading,
errorMessage: _errorMessage,
items: _collections,
emptyIcon: Icons.collections,
emptyMessage: t.libraries.noCollections,
onRetry: _loadCollections,
builder: (items) => RefreshIndicator(
onRefresh: _loadCollections,
child: AdaptiveMediaGrid(items: items, onRefresh: _loadCollections),
),
);
}
}
@@ -1,172 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_library.dart';
import '../../models/plex_playlist.dart';
import '../../providers/plex_client_provider.dart';
import '../../providers/settings_provider.dart';
import '../../utils/app_logger.dart';
import '../../utils/library_refresh_notifier.dart';
import '../../services/settings_service.dart' show ViewMode;
import '../../utils/grid_size_calculator.dart';
import '../../widgets/media_card.dart';
import '../../i18n/strings.g.dart';
import '../../mixins/refreshable.dart';
import '../../widgets/content_state_builder.dart';
/// Playlists tab for library screen
/// Shows playlists that contain items from the current library
class LibraryPlaylistsTab extends StatefulWidget {
final PlexLibrary library;
final String? viewMode;
final String? density;
const LibraryPlaylistsTab({
super.key,
required this.library,
this.viewMode,
this.density,
});
@override
State<LibraryPlaylistsTab> createState() => _LibraryPlaylistsTabState();
}
class _LibraryPlaylistsTabState extends State<LibraryPlaylistsTab>
with AutomaticKeepAliveClientMixin, Refreshable {
@override
bool get wantKeepAlive => true;
@override
void refresh() {
_loadPlaylists();
}
List<PlexPlaylist> _playlists = [];
bool _isLoading = false;
String? _errorMessage;
StreamSubscription<void>? _refreshSubscription;
@override
void initState() {
super.initState();
_loadPlaylists();
// Listen for refresh notifications
_refreshSubscription = LibraryRefreshNotifier().playlistsStream.listen((_) {
if (mounted) {
_loadPlaylists();
}
});
}
@override
void dispose() {
_refreshSubscription?.cancel();
super.dispose();
}
@override
void didUpdateWidget(LibraryPlaylistsTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.key != widget.library.key) {
_loadPlaylists();
}
}
Future<void> _loadPlaylists() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final client = context.read<PlexClientProvider>().client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
// Get playlists for this library
final playlists = await client.getLibraryPlaylists(
sectionId: widget.library.key,
playlistType: 'video',
);
if (!mounted) return;
setState(() {
_playlists = playlists;
_isLoading = false;
});
} catch (e) {
if (!mounted) return;
appLogger.e('Error loading playlists', error: e);
setState(() {
_errorMessage = t.errors.failedToLoad(
context: t.playlists.title,
error: e.toString(),
);
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
return ContentStateBuilder<PlexPlaylist>(
isLoading: _isLoading,
errorMessage: _errorMessage,
items: _playlists,
emptyIcon: Icons.playlist_play,
emptyMessage: t.playlists.noPlaylists,
onRetry: _loadPlaylists,
builder: (items) => RefreshIndicator(
onRefresh: _loadPlaylists,
child: Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
itemCount: items.length,
itemBuilder: (context, index) {
final playlist = items[index];
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: _loadPlaylists,
);
},
);
} else {
return GridView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) {
final playlist = items[index];
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: _loadPlaylists,
);
},
);
}
},
),
),
);
}
}
@@ -1,130 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_library.dart';
import '../../models/plex_hub.dart';
import '../../providers/plex_client_provider.dart';
import '../../utils/app_logger.dart';
import '../../widgets/hub_section.dart';
import '../../i18n/strings.g.dart';
import '../../mixins/refreshable.dart';
import '../../widgets/content_state_builder.dart';
/// Recommended tab for library screen
/// Shows library-specific hubs and recommendations
class LibraryRecommendedTab extends StatefulWidget {
final PlexLibrary library;
const LibraryRecommendedTab({super.key, required this.library});
@override
State<LibraryRecommendedTab> createState() => _LibraryRecommendedTabState();
}
class _LibraryRecommendedTabState extends State<LibraryRecommendedTab>
with AutomaticKeepAliveClientMixin, Refreshable {
@override
bool get wantKeepAlive => true;
@override
void refresh() {
_loadHubs();
}
List<PlexHub> _hubs = [];
bool _isLoading = false;
String? _errorMessage;
@override
void initState() {
super.initState();
_loadHubs();
}
@override
void didUpdateWidget(LibraryRecommendedTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.key != widget.library.key) {
_loadHubs();
}
}
Future<void> _loadHubs() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final client = context.read<PlexClientProvider>().client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final hubs = await client.getLibraryHubs(widget.library.key, limit: 12);
if (!mounted) return;
setState(() {
_hubs = hubs;
_isLoading = false;
});
} catch (e) {
if (!mounted) return;
appLogger.e('Error loading library hubs', error: e);
setState(() {
_errorMessage = t.errors.failedToLoad(
context: t.libraries.tabs.recommended,
error: e.toString(),
);
_isLoading = false;
});
}
}
IconData _getHubIcon(PlexHub hub) {
final title = hub.title.toLowerCase();
if (title.contains('continue watching') || title.contains('on deck')) {
return Icons.play_circle;
} else if (title.contains('recently') || title.contains('new')) {
return Icons.fiber_new;
} else if (title.contains('popular') || title.contains('trending')) {
return Icons.trending_up;
} else if (title.contains('top') || title.contains('rated')) {
return Icons.star;
} else if (title.contains('recommended')) {
return Icons.thumb_up;
} else if (title.contains('unwatched')) {
return Icons.visibility_off;
} else if (title.contains('genre')) {
return Icons.category;
}
return Icons.movie;
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
return ContentStateBuilder<PlexHub>(
isLoading: _isLoading,
errorMessage: _errorMessage,
items: _hubs,
emptyIcon: Icons.recommend,
emptyMessage: t.libraries.noRecommendations,
onRetry: _loadHubs,
builder: (items) => RefreshIndicator(
onRefresh: _loadHubs,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: items.length,
itemBuilder: (context, index) {
final hub = items[index];
return HubSection(hub: hub, icon: _getHubIcon(hub));
},
),
),
);
}
}
+205 -37
View File
@@ -1,14 +1,47 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../services/plex_client.dart';
import '../i18n/strings.g.dart';
import '../utils/app_logger.dart';
import '../utils/keyboard_utils.dart';
import '../utils/provider_extensions.dart';
import '../main.dart';
import '../mixins/refreshable.dart';
import '../providers/multi_server_provider.dart';
import '../providers/server_state_provider.dart';
import '../providers/hidden_libraries_provider.dart';
import '../providers/playback_state_provider.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import 'discover_screen.dart';
import 'libraries_screen.dart';
import 'libraries/libraries_screen.dart';
import 'search_screen.dart';
import 'settings_screen.dart';
import 'settings/settings_screen.dart';
/// InheritedWidget that provides back navigation functionality to child screens
class BackNavigationScope extends InheritedWidget {
final VoidCallback focusBottomNav;
const BackNavigationScope({
super.key,
required this.focusBottomNav,
required super.child,
});
static BackNavigationScope? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<BackNavigationScope>();
}
static BackNavigationScope? maybeOf(BuildContext context) {
return context.getInheritedWidgetOfExactType<BackNavigationScope>();
}
@override
bool updateShouldNotify(BackNavigationScope oldWidget) {
return focusBottomNav != oldWidget.focusBottomNav;
}
}
class MainScreen extends StatefulWidget {
final PlexClient client;
@@ -28,9 +61,18 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
final GlobalKey<State<SearchScreen>> _searchKey = GlobalKey();
final GlobalKey<State<SettingsScreen>> _settingsKey = GlobalKey();
/// Focus scope node for the bottom navigation bar
/// Using FocusScopeNode so requestFocus() focuses the first child
late final FocusScopeNode _bottomNavFocusScopeNode;
/// Focus scope node for the main content area
late final FocusScopeNode _contentFocusScopeNode;
@override
void initState() {
super.initState();
_bottomNavFocusScopeNode = FocusScopeNode(debugLabel: 'BottomNavigation');
_contentFocusScopeNode = FocusScopeNode(debugLabel: 'MainContent');
_screens = [
DiscoverScreen(
@@ -62,9 +104,38 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
@override
void dispose() {
routeObserver.unsubscribe(this);
_bottomNavFocusScopeNode.dispose();
_contentFocusScopeNode.dispose();
super.dispose();
}
/// Focus the bottom navigation bar (called by child screens on back press)
void _focusBottomNav() {
// Request focus on the scope, then navigate to the currently selected tab
_bottomNavFocusScopeNode.requestFocus();
WidgetsBinding.instance.addPostFrameCallback((_) {
// Move to first item, then advance to current index
_bottomNavFocusScopeNode.nextFocus();
for (int i = 0; i < _currentIndex; i++) {
_bottomNavFocusScopeNode.nextFocus();
}
});
}
/// Focus the content area (called when back is pressed in navbar)
void _focusContent() {
_contentFocusScopeNode.requestFocus();
}
/// Handle back key in navbar - focus content area
KeyEventResult _handleNavBarBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
_focusContent();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
void didPush() {
// Called when this route has been pushed (initial navigation)
@@ -91,8 +162,38 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
}
/// Invalidate all cached data across all screens when profile is switched
void _invalidateAllScreens() {
appLogger.d('Invalidating all screen data due to profile switch');
/// Receives the list of servers with new profile tokens for reconnection
Future<void> _invalidateAllScreens(List<PlexServer> servers) async {
appLogger.d(
'Invalidating all screen data due to profile switch with ${servers.length} servers',
);
// Get all providers
final multiServerProvider = context.read<MultiServerProvider>();
final serverStateProvider = context.read<ServerStateProvider>();
final hiddenLibrariesProvider = context.read<HiddenLibrariesProvider>();
final playbackStateProvider = context.read<PlaybackStateProvider>();
// Reconnect to all servers with new profile tokens
if (servers.isNotEmpty) {
final storage = await StorageService.getInstance();
final clientId = storage.getClientIdentifier();
final connectedCount = await multiServerProvider.reconnectWithServers(
servers,
clientIdentifier: clientId,
);
appLogger.d(
'Reconnected to $connectedCount/${servers.length} servers after profile switch',
);
}
// Reset other provider states
serverStateProvider.reset();
hiddenLibrariesProvider.refresh();
playbackStateProvider.clearShuffle();
appLogger.d('Cleared all provider states for profile switch');
// Full refresh discover screen (reload all content for new profile)
final discoverState = _discoverKey.currentState;
@@ -113,44 +214,111 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
}
}
void _selectTab(int index) {
// Check if selection came from keyboard/d-pad (bottom nav has focus)
final isKeyboardNavigation = _bottomNavFocusScopeNode.hasFocus;
setState(() {
_currentIndex = index;
});
// Notify discover screen when it becomes visible via tab switch
if (index == 0) {
_onDiscoverBecameVisible();
// Focus hero when selecting Home tab via keyboard/d-pad
if (isKeyboardNavigation) {
final discoverState = _discoverKey.currentState;
if (discoverState != null) {
(discoverState as dynamic).focusHero();
}
}
}
// Focus first content item when selecting Libraries tab via keyboard/d-pad
if (index == 1 && isKeyboardNavigation) {
final librariesState = _librariesKey.currentState;
if (librariesState != null) {
(librariesState as dynamic).focusFirstContentItem();
}
}
// Focus search input when selecting Search tab (for both click/tap and keyboard)
if (index == 2) {
final searchState = _searchKey.currentState;
if (searchState != null) {
(searchState as dynamic).focusSearchInput();
}
}
// Move focus to the content area when selecting a tab via keyboard
if (isKeyboardNavigation) {
_contentFocusScopeNode.requestFocus();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(index: _currentIndex, children: _screens),
bottomNavigationBar: NavigationBar(
selectedIndex: _currentIndex,
onDestinationSelected: (index) {
setState(() {
_currentIndex = index;
});
// Notify discover screen when it becomes visible via tab switch
if (index == 0) {
_onDiscoverBecameVisible();
}
return Shortcuts(
shortcuts: {
// Number keys 1-4 for quick tab switching
const SingleActivator(LogicalKeyboardKey.digit1): _TabIntent(0),
const SingleActivator(LogicalKeyboardKey.digit2): _TabIntent(1),
const SingleActivator(LogicalKeyboardKey.digit3): _TabIntent(2),
const SingleActivator(LogicalKeyboardKey.digit4): _TabIntent(3),
},
child: Actions(
actions: {
_TabIntent: CallbackAction<_TabIntent>(
onInvoke: (intent) {
_selectTab(intent.tabIndex);
return null;
},
),
},
destinations: [
NavigationDestination(
icon: const Icon(Icons.home_outlined),
selectedIcon: const Icon(Icons.home),
label: t.navigation.home,
child: Scaffold(
body: BackNavigationScope(
focusBottomNav: _focusBottomNav,
child: FocusScope(
node: _contentFocusScopeNode,
child: FocusTraversalGroup(
child: IndexedStack(index: _currentIndex, children: _screens),
),
),
),
NavigationDestination(
icon: const Icon(Icons.video_library_outlined),
selectedIcon: const Icon(Icons.video_library),
label: t.navigation.libraries,
bottomNavigationBar: FocusScope(
node: _bottomNavFocusScopeNode,
onKeyEvent: _handleNavBarBackKey,
child: NavigationBar(
selectedIndex: _currentIndex,
onDestinationSelected: _selectTab,
destinations: [
NavigationDestination(
icon: const Icon(Icons.home_outlined),
selectedIcon: const Icon(Icons.home),
label: t.navigation.home,
),
NavigationDestination(
icon: const Icon(Icons.video_library_outlined),
selectedIcon: const Icon(Icons.video_library),
label: t.navigation.libraries,
),
NavigationDestination(
icon: const Icon(Icons.search),
selectedIcon: const Icon(Icons.search),
label: t.navigation.search,
),
NavigationDestination(
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
label: t.navigation.settings,
),
],
),
),
NavigationDestination(
icon: const Icon(Icons.search),
selectedIcon: const Icon(Icons.search),
label: t.navigation.search,
),
NavigationDestination(
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
label: t.navigation.settings,
),
],
),
),
);
}
}
/// Intent for switching tabs via keyboard shortcuts
class _TabIntent extends Intent {
final int tabIndex;
const _TabIntent(this.tabIndex);
}
File diff suppressed because it is too large Load Diff

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