Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f31ef704a3 | ||
|
|
e53ba988aa | ||
|
|
471c913ee3 | ||
|
|
8b3024b71a | ||
|
|
3eedb615ef | ||
|
|
ac3f7a0b1d | ||
|
|
32dab8953b | ||
|
|
c6f41398a9 | ||
|
|
65811cd0b2 | ||
|
|
851d74e418 | ||
|
|
e804a2a3cc | ||
|
|
c9003e0a03 | ||
|
|
12969eeff9 | ||
|
|
f24bb9dc85 | ||
|
|
4d65607e59 | ||
|
|
80d60077d7 | ||
|
|
d9ea099727 | ||
|
|
223065cab0 | ||
|
|
a373477105 | ||
|
|
7b0aa12c38 | ||
|
|
888d232819 | ||
|
|
6c45706ea3 | ||
|
|
2a15126119 | ||
|
|
392ee575d0 | ||
|
|
6db21d93bb | ||
|
|
4eed2aa3d2 | ||
|
|
cc9cdc8f26 | ||
|
|
20933d3543 | ||
|
|
dc01c5af2f | ||
|
|
aa1a05f207 | ||
|
|
b3c64d62ab | ||
|
|
ac154082cd | ||
|
|
01e5648e28 | ||
|
|
1d50763d9b | ||
|
|
074a6e7e7d | ||
|
|
252da585e3 | ||
|
|
7d75f6e749 | ||
|
|
6b150f7304 | ||
|
|
e73bcd7e4b | ||
|
|
8f817815e6 | ||
|
|
ac7b867f54 | ||
|
|
87dd16d322 | ||
|
|
04b8396d13 | ||
|
|
a4dccb0198 | ||
|
|
74b34bcc77 | ||
|
|
6efc3638d4 | ||
|
|
7f23979e03 | ||
|
|
d214ade2c6 | ||
|
|
a71354d9c5 | ||
|
|
b1dd33ad7a | ||
|
|
2231f42f55 | ||
|
|
4339e00fe2 | ||
|
|
a7a4c641a7 | ||
|
|
cd8592e7e3 | ||
|
|
8a9d889311 | ||
|
|
8b88862a10 | ||
|
|
09860f81c8 | ||
|
|
dff51ca888 | ||
|
|
ecf046a92d | ||
|
|
aaf3e3651b | ||
|
|
78a5ff0fe0 | ||
|
|
a6f0a0b6c0 | ||
|
|
865cba5f9a | ||
|
|
58fd282100 | ||
|
|
75007a6f42 | ||
|
|
6154480c99 | ||
|
|
7c6a121752 | ||
|
|
73eda7c918 | ||
|
|
6d9a56fa73 | ||
|
|
08f92da41b | ||
|
|
a122fb048e | ||
|
|
4cc2426bff | ||
|
|
8a826f0035 | ||
|
|
ae4673bde7 | ||
|
|
920658485f | ||
|
|
e0fd77d7de | ||
|
|
1daded6ec6 | ||
|
|
d9cdde66d8 | ||
|
|
0a6f7c358e | ||
|
|
bc6ee79aef | ||
|
|
bf7e10b1cb | ||
|
|
e30d20e6d1 | ||
|
|
055765ead7 | ||
|
|
26fc38a5ba | ||
|
|
5cbec2398a | ||
|
|
e69644a98e | ||
|
|
c21c5396cd | ||
|
|
01bb1126ef | ||
|
|
0d0388f7a8 | ||
|
|
6ae64e6057 | ||
|
|
44dcdccb2c | ||
|
|
10d4b3088f | ||
|
|
a7f1c8a13c | ||
|
|
516bf3a689 | ||
|
|
141deb8da0 | ||
|
|
4bcdb01029 | ||
|
|
3b51249341 | ||
|
|
0585c9da21 | ||
|
|
7ab8dfa3c3 |
@@ -0,0 +1 @@
|
||||
github: edde746
|
||||
@@ -54,16 +54,10 @@ jobs:
|
||||
- name: Analyze code
|
||||
run: |
|
||||
# Run flutter analyze
|
||||
# Fails on any errors or warnings (info messages are allowed)
|
||||
flutter analyze 2>&1 | tee analyze_output.txt
|
||||
# Fails on errors or warnings only (info messages are allowed)
|
||||
flutter analyze 2>&1 | tee analyze_output.txt || true
|
||||
|
||||
# Check the exit status
|
||||
if [ ${PIPESTATUS[0]} -ne 0 ]; then
|
||||
echo "❌ Analysis failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Also verify no warnings or errors in output
|
||||
# Check output for errors or warnings
|
||||
if grep -q "error •" analyze_output.txt; then
|
||||
echo "❌ Analysis failed with errors"
|
||||
exit 1
|
||||
@@ -71,7 +65,7 @@ jobs:
|
||||
echo "⚠️ Analysis completed with warnings"
|
||||
exit 1
|
||||
else
|
||||
echo "✅ Analysis passed - no issues found!"
|
||||
echo "✅ Analysis passed!"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ jobs:
|
||||
- name: Commit version bump
|
||||
run: |
|
||||
git add pubspec.yaml
|
||||
git commit -m "chore: bump version to ${{ inputs.version }}+${{ steps.get_build.outputs.new_build }}"
|
||||
git commit -m "chore: bump version to ${{ inputs.version }}"
|
||||
|
||||
- name: Create Git tag
|
||||
run: |
|
||||
@@ -67,7 +67,7 @@ jobs:
|
||||
- name: Push changes and tag
|
||||
run: |
|
||||
git push origin main
|
||||
git push origin "${{ inputs.version }}"
|
||||
git push origin --tags
|
||||
|
||||
- name: Trigger build workflow
|
||||
run: |
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
|
||||
|
||||
<!-- Android TV support (not required, but allow detection) -->
|
||||
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||
<!-- Touchscreen not required for TV -->
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||
|
||||
<application
|
||||
android:label="Plezy"
|
||||
android:name="${applicationName}"
|
||||
@@ -37,6 +42,8 @@
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
<!-- Allow app to appear in Android TV launcher -->
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<!-- Don't delete the meta-data below.
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
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")
|
||||
MPVLib.setOptionString("opengl-es", "yes")
|
||||
// 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())
|
||||
}
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 4.6 KiB After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 6.4 KiB After Width: | Height: | Size: 2.5 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 6.1 KiB |
@@ -1,11 +1,9 @@
|
||||
PODS:
|
||||
- connectivity_plus (0.0.1):
|
||||
- Flutter
|
||||
- device_info_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 +19,25 @@ 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`)
|
||||
- device_info_plus (from `.symlinks/plugins/device_info_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"
|
||||
device_info_plus:
|
||||
:path: ".symlinks/plugins/device_info_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 +50,17 @@ 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
|
||||
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
|
||||
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
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// Extension methods for checking D-pad related keys.
|
||||
extension DpadKeyExtension on LogicalKeyboardKey {
|
||||
/// Whether this key is a D-pad directional key.
|
||||
bool get isDpadDirection {
|
||||
return this == LogicalKeyboardKey.arrowUp ||
|
||||
this == LogicalKeyboardKey.arrowDown ||
|
||||
this == LogicalKeyboardKey.arrowLeft ||
|
||||
this == LogicalKeyboardKey.arrowRight;
|
||||
}
|
||||
|
||||
/// Whether this key is a select/activate key.
|
||||
bool get isSelectKey {
|
||||
return this == LogicalKeyboardKey.select ||
|
||||
this == LogicalKeyboardKey.enter ||
|
||||
this == LogicalKeyboardKey.numpadEnter ||
|
||||
this == LogicalKeyboardKey.gameButtonA;
|
||||
}
|
||||
|
||||
/// Whether this key is a back/cancel key.
|
||||
bool get isBackKey {
|
||||
return this == LogicalKeyboardKey.escape ||
|
||||
this == LogicalKeyboardKey.goBack ||
|
||||
this == LogicalKeyboardKey.browserBack ||
|
||||
this == LogicalKeyboardKey.gameButtonB;
|
||||
}
|
||||
|
||||
/// Whether this key is a context menu key.
|
||||
bool get isContextMenuKey {
|
||||
return this == LogicalKeyboardKey.contextMenu ||
|
||||
this == LogicalKeyboardKey.gameButtonX;
|
||||
}
|
||||
|
||||
/// Whether this key moves focus left.
|
||||
bool get isLeftKey {
|
||||
return this == LogicalKeyboardKey.arrowLeft;
|
||||
}
|
||||
|
||||
/// Whether this key moves focus right.
|
||||
bool get isRightKey {
|
||||
return this == LogicalKeyboardKey.arrowRight;
|
||||
}
|
||||
|
||||
/// Whether this key moves focus up.
|
||||
bool get isUpKey {
|
||||
return this == LogicalKeyboardKey.arrowUp;
|
||||
}
|
||||
|
||||
/// Whether this key moves focus down.
|
||||
bool get isDownKey {
|
||||
return this == LogicalKeyboardKey.arrowDown;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme/mono_tokens.dart';
|
||||
|
||||
/// Focus styling constants for D-pad navigation.
|
||||
class FocusTheme {
|
||||
FocusTheme._();
|
||||
|
||||
/// Scale factor when an item is focused.
|
||||
static const double focusScale = 1.02;
|
||||
|
||||
/// Border width for the focus indicator.
|
||||
static const double focusBorderWidth = 2.5;
|
||||
|
||||
/// Default border radius (matches MonoTokens.radiusSm).
|
||||
static const double defaultBorderRadius = 8.0;
|
||||
|
||||
/// Get the focus border color from the theme.
|
||||
static Color getFocusBorderColor(BuildContext context) {
|
||||
return Theme.of(context).colorScheme.primary;
|
||||
}
|
||||
|
||||
/// Get the animation duration from MonoTokens.
|
||||
static Duration getAnimationDuration(BuildContext context) {
|
||||
return Theme.of(context).extension<MonoTokens>()?.fast ??
|
||||
const Duration(milliseconds: 150);
|
||||
}
|
||||
|
||||
/// Build the focus border decoration.
|
||||
static BoxDecoration focusDecoration(
|
||||
BuildContext context, {
|
||||
required bool isFocused,
|
||||
double borderRadius = defaultBorderRadius,
|
||||
}) {
|
||||
final focusColor = getFocusBorderColor(context);
|
||||
|
||||
return BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
border: Border.all(
|
||||
color: isFocused ? focusColor : Colors.transparent,
|
||||
width: focusBorderWidth,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Build focus decoration with background color instead of border.
|
||||
/// Useful for video controls where it should match the native hover style.
|
||||
static BoxDecoration focusBackgroundDecoration({
|
||||
required bool isFocused,
|
||||
double borderRadius = defaultBorderRadius,
|
||||
}) {
|
||||
return BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
color: isFocused
|
||||
? Colors.white.withValues(alpha: 0.2)
|
||||
: Colors.transparent,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// A mixin that provides common FocusNode lifecycle management for chip widgets.
|
||||
///
|
||||
/// This mixin handles:
|
||||
/// - Internal/external FocusNode pattern
|
||||
/// - `_isFocused` state tracking
|
||||
/// - Listener setup in `initState`
|
||||
/// - Listener handoff in `didUpdateWidget`
|
||||
/// - Cleanup in `dispose`
|
||||
///
|
||||
/// To use this mixin:
|
||||
/// 1. Add `with FocusableChipStateMixin<YourWidget>` to your State class
|
||||
/// 2. Implement [widgetFocusNode] to return the widget's optional focusNode
|
||||
/// 3. Implement [debugLabel] to return a debug label for the internal node
|
||||
/// 4. Call [initFocusNode] in your `initState`
|
||||
/// 5. Call [updateFocusNode] in your `didUpdateWidget`
|
||||
/// 6. Call [disposeFocusNode] in your `dispose`
|
||||
/// 7. Use [focusNode] and [isFocused] in your build method
|
||||
mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
|
||||
FocusNode? _internalFocusNode;
|
||||
bool _isFocused = false;
|
||||
|
||||
/// Override to return the widget's optional external focus node.
|
||||
FocusNode? get widgetFocusNode;
|
||||
|
||||
/// Override to return a debug label for the internal focus node.
|
||||
String get debugLabel;
|
||||
|
||||
/// The active focus node (external if provided, otherwise internal).
|
||||
FocusNode get focusNode {
|
||||
return widgetFocusNode ??
|
||||
(_internalFocusNode ??= FocusNode(debugLabel: debugLabel));
|
||||
}
|
||||
|
||||
/// Whether this widget is currently focused.
|
||||
bool get isFocused => _isFocused;
|
||||
|
||||
/// Call this in your `initState` to set up the focus listener.
|
||||
void initFocusNode() {
|
||||
focusNode.addListener(_onFocusChange);
|
||||
}
|
||||
|
||||
/// Call this in your `didUpdateWidget` with the old widget's focusNode.
|
||||
void updateFocusNode(FocusNode? oldFocusNode) {
|
||||
if (oldFocusNode != widgetFocusNode) {
|
||||
oldFocusNode?.removeListener(_onFocusChange);
|
||||
focusNode.addListener(_onFocusChange);
|
||||
}
|
||||
}
|
||||
|
||||
/// Call this in your `dispose` to clean up the focus listener.
|
||||
void disposeFocusNode() {
|
||||
focusNode.removeListener(_onFocusChange);
|
||||
_internalFocusNode?.dispose();
|
||||
}
|
||||
|
||||
void _onFocusChange() {
|
||||
if (mounted) {
|
||||
setState(() => _isFocused = focusNode.hasFocus);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'focus_theme.dart';
|
||||
import 'input_mode_tracker.dart';
|
||||
|
||||
/// A wrapper widget that makes its child focusable with D-pad navigation support.
|
||||
///
|
||||
/// Provides:
|
||||
/// - Visual focus indicator (border + scale animation)
|
||||
/// - Keyboard/D-pad event handling (Enter/Select to activate)
|
||||
/// - Optional auto-scroll to keep focused item visible
|
||||
/// - Long-press detection for SELECT key
|
||||
/// - Navigation callbacks (UP, BACK)
|
||||
class FocusableWrapper extends StatefulWidget {
|
||||
/// The child widget to wrap.
|
||||
final Widget child;
|
||||
|
||||
/// Called when the item is selected (Enter/Select/GamepadA).
|
||||
/// For short press when [enableLongPress] is true.
|
||||
final VoidCallback? onSelect;
|
||||
|
||||
/// Called when long press is triggered (hold SELECT key or context menu key).
|
||||
/// Only triggered if [enableLongPress] is true.
|
||||
final VoidCallback? onLongPress;
|
||||
|
||||
/// Called when focus changes.
|
||||
final ValueChanged<bool>? onFocusChange;
|
||||
|
||||
/// Called when the user presses UP and there's no focusable item above.
|
||||
final VoidCallback? onNavigateUp;
|
||||
|
||||
/// Called when the user presses BACK.
|
||||
final VoidCallback? onBack;
|
||||
|
||||
/// Whether this widget should request focus when first built.
|
||||
final bool autofocus;
|
||||
|
||||
/// Optional external FocusNode for programmatic focus control.
|
||||
final FocusNode? focusNode;
|
||||
|
||||
/// Border radius for the focus indicator.
|
||||
final double borderRadius;
|
||||
|
||||
/// Whether to scroll the widget into view when focused.
|
||||
final bool autoScroll;
|
||||
|
||||
/// Alignment for auto-scroll (0.0 = start, 0.5 = center, 1.0 = end).
|
||||
final double scrollAlignment;
|
||||
|
||||
/// Whether to use comfortable zone scrolling (only scroll if item is outside middle 60%).
|
||||
/// If false, always scrolls to [scrollAlignment].
|
||||
final bool useComfortableZone;
|
||||
|
||||
/// Optional semantic label for accessibility.
|
||||
final String? semanticLabel;
|
||||
|
||||
/// Whether the wrapper can receive focus.
|
||||
final bool canRequestFocus;
|
||||
|
||||
/// Custom key event handler. Return KeyEventResult.handled to consume the event.
|
||||
/// This is called before the default key handling.
|
||||
final KeyEventResult Function(FocusNode node, KeyEvent event)? onKeyEvent;
|
||||
|
||||
/// Whether to enable long-press detection for SELECT key.
|
||||
/// When enabled, holding SELECT triggers [onLongPress] after 500ms.
|
||||
/// Short press triggers [onSelect].
|
||||
final bool enableLongPress;
|
||||
|
||||
/// Duration for long-press detection.
|
||||
final Duration longPressDuration;
|
||||
|
||||
/// Whether to use background color instead of border for focus indicator.
|
||||
/// Useful for video controls where outline doesn't look good.
|
||||
final bool useBackgroundFocus;
|
||||
|
||||
/// Whether to disable the scale animation on focus.
|
||||
/// Useful for elements like sliders where scaling looks odd.
|
||||
final bool disableScale;
|
||||
|
||||
const FocusableWrapper({
|
||||
super.key,
|
||||
required this.child,
|
||||
this.onSelect,
|
||||
this.onLongPress,
|
||||
this.onFocusChange,
|
||||
this.onNavigateUp,
|
||||
this.onBack,
|
||||
this.autofocus = false,
|
||||
this.focusNode,
|
||||
this.borderRadius = FocusTheme.defaultBorderRadius,
|
||||
this.autoScroll = true,
|
||||
this.scrollAlignment = 0.5,
|
||||
this.useComfortableZone = false,
|
||||
this.semanticLabel,
|
||||
this.canRequestFocus = true,
|
||||
this.onKeyEvent,
|
||||
this.enableLongPress = false,
|
||||
this.longPressDuration = const Duration(milliseconds: 500),
|
||||
this.useBackgroundFocus = false,
|
||||
this.disableScale = false,
|
||||
});
|
||||
|
||||
@override
|
||||
State<FocusableWrapper> createState() => _FocusableWrapperState();
|
||||
}
|
||||
|
||||
class _FocusableWrapperState extends State<FocusableWrapper>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late FocusNode _focusNode;
|
||||
bool _ownsNode = false;
|
||||
bool _isFocused = false;
|
||||
|
||||
late AnimationController _animationController;
|
||||
late Animation<double> _scaleAnimation;
|
||||
|
||||
// Long-press detection for SELECT key
|
||||
Timer? _longPressTimer;
|
||||
bool _isSelectKeyDown = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initFocusNode();
|
||||
_initAnimations();
|
||||
}
|
||||
|
||||
void _initFocusNode() {
|
||||
if (widget.focusNode != null) {
|
||||
_focusNode = widget.focusNode!;
|
||||
_ownsNode = false;
|
||||
} else {
|
||||
_focusNode = FocusNode(
|
||||
debugLabel: widget.semanticLabel ?? 'FocusableWrapper',
|
||||
canRequestFocus: widget.canRequestFocus,
|
||||
);
|
||||
_ownsNode = true;
|
||||
}
|
||||
}
|
||||
|
||||
void _initAnimations() {
|
||||
_animationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 150),
|
||||
);
|
||||
|
||||
_scaleAnimation = Tween<double>(begin: 1.0, end: FocusTheme.focusScale)
|
||||
.animate(
|
||||
CurvedAnimation(
|
||||
parent: _animationController,
|
||||
curve: Curves.easeOutCubic,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(FocusableWrapper oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
|
||||
// Handle focusNode changes
|
||||
if (widget.focusNode != oldWidget.focusNode) {
|
||||
if (_ownsNode) {
|
||||
_focusNode.dispose();
|
||||
}
|
||||
_initFocusNode();
|
||||
}
|
||||
|
||||
// Update canRequestFocus
|
||||
if (widget.canRequestFocus != oldWidget.canRequestFocus) {
|
||||
_focusNode.canRequestFocus = widget.canRequestFocus;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_longPressTimer?.cancel();
|
||||
_animationController.dispose();
|
||||
if (_ownsNode) {
|
||||
_focusNode.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _handleFocusChange(bool hasFocus) {
|
||||
if (_isFocused != hasFocus) {
|
||||
setState(() {
|
||||
_isFocused = hasFocus;
|
||||
});
|
||||
|
||||
// Animate scale
|
||||
if (hasFocus) {
|
||||
_animationController.forward();
|
||||
} else {
|
||||
_animationController.reverse();
|
||||
}
|
||||
|
||||
// Auto-scroll into view
|
||||
if (hasFocus && widget.autoScroll) {
|
||||
_scrollIntoView();
|
||||
}
|
||||
|
||||
// Notify listener
|
||||
widget.onFocusChange?.call(hasFocus);
|
||||
}
|
||||
}
|
||||
|
||||
void _scrollIntoView() {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted || !_isFocused) return;
|
||||
|
||||
final renderObject = context.findRenderObject();
|
||||
if (renderObject == null) return;
|
||||
|
||||
if (widget.useComfortableZone) {
|
||||
// Check if item is already in the comfortable zone
|
||||
final scrollable = Scrollable.maybeOf(context);
|
||||
if (scrollable == null) return;
|
||||
|
||||
final viewport = scrollable.context.findRenderObject() as RenderBox?;
|
||||
if (viewport == null) return;
|
||||
|
||||
// Get item's position relative to viewport
|
||||
final itemBox = renderObject as RenderBox;
|
||||
final itemPosition = itemBox.localToGlobal(
|
||||
Offset.zero,
|
||||
ancestor: viewport,
|
||||
);
|
||||
|
||||
// Check if item is already in the comfortable zone
|
||||
final viewportHeight = viewport.size.height;
|
||||
final itemHeight = itemBox.size.height;
|
||||
final itemVerticalCenter = itemPosition.dy + itemHeight / 2;
|
||||
|
||||
// Define comfortable zone - if item center is within middle 60% of viewport, don't scroll
|
||||
final comfortZoneTop = viewportHeight * 0.2;
|
||||
final comfortZoneBottom = viewportHeight * 0.8;
|
||||
|
||||
if (itemVerticalCenter >= comfortZoneTop &&
|
||||
itemVerticalCenter <= comfortZoneBottom) {
|
||||
// Item is in comfortable zone, no need to scroll
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Item is outside comfortable zone or comfortable zone disabled, scroll to alignment
|
||||
Scrollable.ensureVisible(
|
||||
context,
|
||||
alignment: widget.scrollAlignment,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
curve: Curves.easeInOut,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
|
||||
// Call custom key handler first
|
||||
if (widget.onKeyEvent != null) {
|
||||
final result = widget.onKeyEvent!(node, event);
|
||||
if (result == KeyEventResult.handled) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle SELECT key with optional long-press detection
|
||||
if (_isSelectKey(key)) {
|
||||
if (widget.enableLongPress) {
|
||||
if (event is KeyDownEvent) {
|
||||
// Only start timer on initial press, not repeats
|
||||
if (!_isSelectKeyDown) {
|
||||
_isSelectKeyDown = true;
|
||||
_longPressTimer?.cancel();
|
||||
_longPressTimer = Timer(widget.longPressDuration, () {
|
||||
// Long press detected
|
||||
if (mounted) {
|
||||
widget.onLongPress?.call();
|
||||
}
|
||||
});
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
} else if (event is KeyRepeatEvent) {
|
||||
// Consume repeat events to prevent system sounds
|
||||
return KeyEventResult.handled;
|
||||
} else if (event is KeyUpEvent) {
|
||||
final timerWasActive = _longPressTimer?.isActive ?? false;
|
||||
_longPressTimer?.cancel();
|
||||
if (timerWasActive && _isSelectKeyDown) {
|
||||
// Timer still active - short press
|
||||
widget.onSelect?.call();
|
||||
}
|
||||
// If timer already fired, long press was triggered - do nothing on key up
|
||||
_isSelectKeyDown = false;
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
} else {
|
||||
// Simple select handling without long-press
|
||||
if (event is KeyDownEvent) {
|
||||
widget.onSelect?.call();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ignore key repeat events for other keys
|
||||
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
// Context menu key
|
||||
if (_isContextMenuKey(key)) {
|
||||
widget.onLongPress?.call();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// UP arrow - if callback provided, navigate up
|
||||
if (key == LogicalKeyboardKey.arrowUp && widget.onNavigateUp != null) {
|
||||
widget.onNavigateUp!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// BACK key
|
||||
if (_isBackKey(key) && widget.onBack != null) {
|
||||
widget.onBack!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
bool _isSelectKey(LogicalKeyboardKey key) {
|
||||
return key == LogicalKeyboardKey.select ||
|
||||
key == LogicalKeyboardKey.enter ||
|
||||
key == LogicalKeyboardKey.numpadEnter ||
|
||||
key == LogicalKeyboardKey.gameButtonA;
|
||||
}
|
||||
|
||||
bool _isContextMenuKey(LogicalKeyboardKey key) {
|
||||
return key == LogicalKeyboardKey.contextMenu ||
|
||||
key == LogicalKeyboardKey.gameButtonX;
|
||||
}
|
||||
|
||||
bool _isBackKey(LogicalKeyboardKey key) {
|
||||
return key == LogicalKeyboardKey.escape ||
|
||||
key == LogicalKeyboardKey.goBack ||
|
||||
key == LogicalKeyboardKey.browserBack ||
|
||||
key == LogicalKeyboardKey.gameButtonB;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final duration = FocusTheme.getAnimationDuration(context);
|
||||
// Only show focus effects during keyboard/d-pad navigation
|
||||
final showFocus = _isFocused && InputModeTracker.isKeyboardMode(context);
|
||||
|
||||
// Update animation duration if theme changes
|
||||
if (_animationController.duration != duration) {
|
||||
_animationController.duration = duration;
|
||||
}
|
||||
|
||||
// Choose decoration based on useBackgroundFocus
|
||||
final decoration = widget.useBackgroundFocus
|
||||
? FocusTheme.focusBackgroundDecoration(
|
||||
isFocused: showFocus,
|
||||
borderRadius: widget.borderRadius,
|
||||
)
|
||||
: FocusTheme.focusDecoration(
|
||||
context,
|
||||
isFocused: showFocus,
|
||||
borderRadius: widget.borderRadius,
|
||||
);
|
||||
|
||||
Widget result = Focus(
|
||||
focusNode: _focusNode,
|
||||
autofocus: widget.autofocus,
|
||||
onFocusChange: _handleFocusChange,
|
||||
onKeyEvent: _handleKeyEvent,
|
||||
child: AnimatedBuilder(
|
||||
animation: _scaleAnimation,
|
||||
builder: (context, child) {
|
||||
final shouldScale = showFocus && !widget.disableScale;
|
||||
return Transform.scale(
|
||||
scale: shouldScale ? _scaleAnimation.value : 1.0,
|
||||
child: AnimatedContainer(
|
||||
duration: duration,
|
||||
curve: Curves.easeOutCubic,
|
||||
decoration: decoration,
|
||||
child: widget.child,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Add semantics if label provided
|
||||
if (widget.semanticLabel != null) {
|
||||
result = Semantics(
|
||||
label: widget.semanticLabel,
|
||||
button: widget.onSelect != null,
|
||||
child: result,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../services/tv_detection_service.dart';
|
||||
import '../services/gamepad_service.dart';
|
||||
|
||||
/// Tracks whether the user is navigating via keyboard/d-pad or pointer (mouse/touch).
|
||||
///
|
||||
/// Focus effects should only be shown during keyboard navigation.
|
||||
enum InputMode { keyboard, pointer }
|
||||
|
||||
/// Provides input mode tracking to descendant widgets.
|
||||
///
|
||||
/// Wrap your app with this widget to enable input mode detection:
|
||||
/// ```dart
|
||||
/// InputModeTracker(
|
||||
/// child: MaterialApp(...),
|
||||
/// )
|
||||
/// ```
|
||||
///
|
||||
/// Then check the mode in focusable widgets:
|
||||
/// ```dart
|
||||
/// final showFocus = _isFocused && InputModeTracker.isKeyboardMode(context);
|
||||
/// ```
|
||||
class InputModeTracker extends StatefulWidget {
|
||||
final Widget child;
|
||||
|
||||
const InputModeTracker({super.key, required this.child});
|
||||
|
||||
/// Get the current input mode.
|
||||
static InputMode of(BuildContext context) {
|
||||
final provider = context
|
||||
.dependOnInheritedWidgetOfExactType<_InputModeProvider>();
|
||||
return provider?.mode ?? InputMode.pointer;
|
||||
}
|
||||
|
||||
/// Convenience method to check if we're in keyboard mode.
|
||||
static bool isKeyboardMode(BuildContext context) {
|
||||
return of(context) == InputMode.keyboard;
|
||||
}
|
||||
|
||||
@override
|
||||
State<InputModeTracker> createState() => _InputModeTrackerState();
|
||||
}
|
||||
|
||||
class _InputModeTrackerState extends State<InputModeTracker> {
|
||||
// Default to keyboard mode on Android TV, pointer mode elsewhere
|
||||
InputMode _mode = TvDetectionService.isTVSync()
|
||||
? InputMode.keyboard
|
||||
: InputMode.pointer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Initialize focus highlight strategy based on starting mode
|
||||
_updateFocusHighlightStrategy(_mode);
|
||||
// Listen to hardware keyboard events globally
|
||||
HardwareKeyboard.instance.addHandler(_handleKeyEvent);
|
||||
RawKeyboard.instance.addListener(_handleRawKeyEvent);
|
||||
|
||||
// Register callback for gamepad input to switch to keyboard mode
|
||||
GamepadService.onGamepadInput = () => _setMode(InputMode.keyboard);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
HardwareKeyboard.instance.removeHandler(_handleKeyEvent);
|
||||
RawKeyboard.instance.removeListener(_handleRawKeyEvent);
|
||||
GamepadService.onGamepadInput = null;
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool _handleKeyEvent(KeyEvent event) {
|
||||
// Only switch to keyboard mode on key down (not repeats or releases)
|
||||
if (event is KeyDownEvent) {
|
||||
_setMode(InputMode.keyboard);
|
||||
}
|
||||
// Return false to let the event continue propagating
|
||||
return false;
|
||||
}
|
||||
|
||||
void _handleRawKeyEvent(RawKeyEvent event) {
|
||||
if (event is RawKeyDownEvent) {
|
||||
_setMode(InputMode.keyboard);
|
||||
}
|
||||
}
|
||||
|
||||
void _setMode(InputMode mode) {
|
||||
if (_mode != mode) {
|
||||
setState(() => _mode = mode);
|
||||
}
|
||||
_updateFocusHighlightStrategy(mode);
|
||||
}
|
||||
|
||||
// Keep Material focus highlights in sync with our input mode so keyboard/gamepad
|
||||
// navigation immediately shows focus without waiting for a real keypress.
|
||||
void _updateFocusHighlightStrategy(InputMode mode) {
|
||||
final desiredStrategy = mode == InputMode.keyboard
|
||||
? FocusHighlightStrategy.alwaysTraditional
|
||||
: FocusHighlightStrategy.automatic;
|
||||
|
||||
if (FocusManager.instance.highlightStrategy != desiredStrategy) {
|
||||
FocusManager.instance.highlightStrategy = desiredStrategy;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Listener(
|
||||
// Switch to pointer mode on mouse activity
|
||||
onPointerDown: (_) => _setMode(InputMode.pointer),
|
||||
onPointerHover: (_) => _setMode(InputMode.pointer),
|
||||
behavior: HitTestBehavior.translucent,
|
||||
child: _InputModeProvider(mode: _mode, child: widget.child),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// InheritedWidget that provides the current input mode.
|
||||
class _InputModeProvider extends InheritedWidget {
|
||||
final InputMode mode;
|
||||
|
||||
const _InputModeProvider({required this.mode, required super.child});
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(_InputModeProvider oldWidget) {
|
||||
return mode != oldWidget.mode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'dpad_navigator.dart';
|
||||
|
||||
/// Handles back key events by popping the current route.
|
||||
///
|
||||
/// Optionally pass a [result] to return to the previous route.
|
||||
///
|
||||
/// Use this as an `onKeyEvent` callback for Focus widgets that need
|
||||
/// simple back navigation behavior:
|
||||
///
|
||||
/// ```dart
|
||||
/// Focus(
|
||||
/// onKeyEvent: (node, event) => handleBackKeyNavigation(context, event),
|
||||
/// child: ...
|
||||
/// )
|
||||
/// ```
|
||||
///
|
||||
/// With a result value:
|
||||
/// ```dart
|
||||
/// Focus(
|
||||
/// onKeyEvent: (node, event) => handleBackKeyNavigation(
|
||||
/// context,
|
||||
/// event,
|
||||
/// result: _hasChanges,
|
||||
/// ),
|
||||
/// child: ...
|
||||
/// )
|
||||
/// ```
|
||||
KeyEventResult handleBackKeyNavigation<T>(
|
||||
BuildContext context,
|
||||
KeyEvent event, {
|
||||
T? result,
|
||||
}) {
|
||||
if (event is KeyDownEvent && event.logicalKey.isBackKey) {
|
||||
Navigator.pop(context, result);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/// Manages focus memory for hub navigation.
|
||||
///
|
||||
/// Tracks two things:
|
||||
/// 1. Per-hub memory: Each hub remembers which item was last focused
|
||||
/// 2. Global column hint: When entering a hub that hasn't been visited,
|
||||
/// we use the column position from the last focused hub as a hint
|
||||
class HubFocusMemory {
|
||||
static final Map<String, int> _perHubMemory = {};
|
||||
static int _lastColumnHint = 0;
|
||||
|
||||
/// Remember the focused index for a specific hub
|
||||
static void setForHub(String hubKey, int index) {
|
||||
_perHubMemory[hubKey] = index;
|
||||
_lastColumnHint = index;
|
||||
}
|
||||
|
||||
/// Get the remembered index for a hub, or fall back to column hint
|
||||
static int getForHub(String hubKey, int itemCount) {
|
||||
if (itemCount <= 0) return 0;
|
||||
|
||||
// If this hub has memory, use it
|
||||
if (_perHubMemory.containsKey(hubKey)) {
|
||||
return _perHubMemory[hubKey]!.clamp(0, itemCount - 1);
|
||||
}
|
||||
|
||||
// Otherwise use the last column hint (clamped to this hub's item count)
|
||||
return _lastColumnHint.clamp(0, itemCount - 1);
|
||||
}
|
||||
|
||||
/// Clear all memory (e.g., when leaving a screen)
|
||||
static void clear() {
|
||||
_perHubMemory.clear();
|
||||
_lastColumnHint = 0;
|
||||
}
|
||||
}
|
||||
@@ -132,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...",
|
||||
@@ -405,6 +412,7 @@
|
||||
"serverDebugCopied": "Server debug data copied to clipboard",
|
||||
"copyDebugData": "Copy Debug Data",
|
||||
"noServersFound": "No servers found",
|
||||
"noServersFoundForAccount": "No servers found for ${username} (${email})",
|
||||
"malformedServerData": "Found ${count} server(s) with malformed data. No valid servers available.",
|
||||
"incompleteServerInfo": "Some servers have incomplete information and were skipped. Please check your Plex.tv account.",
|
||||
"incompleteConnectionInfo": "Server connection information is incomplete. Please try again.",
|
||||
|
||||
@@ -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...",
|
||||
@@ -407,6 +414,7 @@
|
||||
"serverDebugCopied": "Server-Debugdaten kopiert",
|
||||
"copyDebugData": "Debugdaten kopieren",
|
||||
"noServersFound": "Keine Server gefunden",
|
||||
"noServersFoundForAccount": "Keine Server gefunden für ${username} (${email})",
|
||||
"malformedServerData": "${count} Server mit fehlerhaften Daten gefunden. Keine gültigen Server verfügbar.",
|
||||
"incompleteServerInfo": "Einige Serverinformationen sind unvollständig und wurden übersprungen. Plex.tv-Konto prüfen.",
|
||||
"incompleteConnectionInfo": "Serververbindungsinformationen unvollständig. Bitte erneut versuchen.",
|
||||
|
||||
@@ -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...",
|
||||
@@ -407,6 +414,7 @@
|
||||
"serverDebugCopied": "Dati di debug del server copiati negli appunti",
|
||||
"copyDebugData": "Copia dati di debug",
|
||||
"noServersFound": "Nessun server trovato",
|
||||
"noServersFoundForAccount": "Nessun server trovato per ${username} (${email})",
|
||||
"malformedServerData": "Trovato ${count} server con dati difettosi. Nessun server valido disponibile.",
|
||||
"incompleteServerInfo": "Alcuni server presentano informazioni incomplete e sono stati ignorati. Controlla il tuo account Plex.tv.",
|
||||
"incompleteConnectionInfo": "Le informazioni di connessione al server sono incomplete. Riprova.",
|
||||
|
||||
@@ -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...",
|
||||
@@ -407,6 +414,7 @@
|
||||
"serverDebugCopied": "Server debug gegevens gekopieerd naar klembord",
|
||||
"copyDebugData": "Kopieer debug gegevens",
|
||||
"noServersFound": "Geen servers gevonden",
|
||||
"noServersFoundForAccount": "Geen servers gevonden voor ${username} (${email})",
|
||||
"malformedServerData": "${count} server(s) gevonden met verkeerde data. Geen geldige servers beschikbaar.",
|
||||
"incompleteServerInfo": "Sommige servers hebben incomplete informatie en zijn overgeslagen. Controleer je Plex.tv account.",
|
||||
"incompleteConnectionInfo": "Server verbinding informatie is incompleet. Probeer opnieuw.",
|
||||
|
||||
@@ -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...",
|
||||
@@ -407,6 +414,7 @@
|
||||
"serverDebugCopied": "Server-felsökningsdata kopierad till urklipp",
|
||||
"copyDebugData": "Kopiera felsökningsdata",
|
||||
"noServersFound": "Inga servrar hittades",
|
||||
"noServersFoundForAccount": "Inga servrar hittades för ${username} (${email})",
|
||||
"malformedServerData": "Hittade ${count} server(ar) med felformaterad data. Inga giltiga servrar tillgängliga.",
|
||||
"incompleteServerInfo": "Vissa servrar har ofullständig information och hoppades över. Vänligen kontrollera ditt Plex.tv-konto.",
|
||||
"incompleteConnectionInfo": "Server-anslutningsinformation är ofullständig. Försök igen.",
|
||||
|
||||
@@ -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": "搜索电影、系列、音乐...",
|
||||
@@ -407,6 +414,7 @@
|
||||
"serverDebugCopied": "服务器调试数据已复制到剪贴板",
|
||||
"copyDebugData": "复制调试数据",
|
||||
"noServersFound": "未找到服务器",
|
||||
"noServersFoundForAccount": "未找到 ${username} (${email}) 的服务器",
|
||||
"malformedServerData": "找到 ${count} 个数据格式错误的服务器。没有可用的有效服务器。",
|
||||
"incompleteServerInfo": "某些服务器信息不完整,已被跳过。请检查你的 Plex.tv 账户。",
|
||||
"incompleteConnectionInfo": "服务器连接信息不完整。请重试。",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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';
|
||||
@@ -11,6 +10,8 @@ import 'services/macos_titlebar_service.dart';
|
||||
import 'services/fullscreen_state_manager.dart';
|
||||
import 'services/update_service.dart';
|
||||
import 'services/settings_service.dart';
|
||||
import 'services/tv_detection_service.dart';
|
||||
import 'services/gamepad_service.dart';
|
||||
import 'providers/user_profile_provider.dart';
|
||||
import 'providers/plex_client_provider.dart';
|
||||
import 'providers/multi_server_provider.dart';
|
||||
@@ -22,10 +23,11 @@ import 'providers/playback_state_provider.dart';
|
||||
import 'services/multi_server_manager.dart';
|
||||
import 'services/data_aggregation_service.dart';
|
||||
import 'services/server_registry.dart';
|
||||
import 'utils/language_codes.dart';
|
||||
import 'utils/app_logger.dart';
|
||||
import 'utils/orientation_helper.dart';
|
||||
import 'utils/language_codes.dart';
|
||||
import 'i18n/strings.g.dart';
|
||||
import 'focus/input_mode_tracker.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
@@ -38,26 +40,32 @@ 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();
|
||||
// Initialize TV detection for Android
|
||||
if (Platform.isAndroid) {
|
||||
futures.add(TvDetectionService.getInstance().then((_) {}));
|
||||
}
|
||||
|
||||
// Initialize MediaKit
|
||||
MediaKit.ensureInitialized();
|
||||
// Configure macOS window with custom titlebar (depends on window manager)
|
||||
futures.add(MacOSTitlebarService.setupCustomTitlebar());
|
||||
|
||||
// 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();
|
||||
@@ -66,6 +74,11 @@ void main() async {
|
||||
// Start global fullscreen state monitoring
|
||||
FullscreenStateManager().startMonitoring();
|
||||
|
||||
// Initialize gamepad service for desktop platforms
|
||||
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
|
||||
GamepadService.instance.start();
|
||||
}
|
||||
|
||||
// DTD service is available for MCP tooling connection if needed
|
||||
|
||||
runApp(const MainApp());
|
||||
@@ -94,25 +107,31 @@ class MainApp extends StatelessWidget {
|
||||
),
|
||||
ChangeNotifierProvider(create: (context) => ServerStateProvider()),
|
||||
// Existing providers
|
||||
ChangeNotifierProvider(
|
||||
create: (context) => UserProfileProvider()..initialize(),
|
||||
),
|
||||
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>(
|
||||
builder: (context, themeProvider, child) {
|
||||
return TranslationProvider(
|
||||
child: MaterialApp(
|
||||
title: t.app.title,
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: themeProvider.lightTheme,
|
||||
darkTheme: themeProvider.darkTheme,
|
||||
themeMode: themeProvider.materialThemeMode,
|
||||
navigatorObservers: [routeObserver],
|
||||
home: const OrientationAwareSetup(),
|
||||
child: InputModeTracker(
|
||||
child: MaterialApp(
|
||||
title: t.app.title,
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: themeProvider.lightTheme,
|
||||
darkTheme: themeProvider.darkTheme,
|
||||
themeMode: themeProvider.materialThemeMode,
|
||||
navigatorObservers: [routeObserver],
|
||||
home: const OrientationAwareSetup(),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -159,7 +178,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));
|
||||
|
||||
@@ -288,10 +307,7 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
appLogger.i('Successfully connected to $connectedCount servers');
|
||||
|
||||
if (mounted) {
|
||||
// Check for updates BEFORE navigation
|
||||
_checkForUpdatesOnStartup();
|
||||
|
||||
// Navigate to main screen
|
||||
// Navigate to main screen immediately
|
||||
// Get first connected client for backward compatibility
|
||||
final firstClient =
|
||||
multiServerProvider.serverManager.onlineClients.values.first;
|
||||
@@ -302,6 +318,9 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
builder: (context) => MainScreen(client: firstClient),
|
||||
),
|
||||
);
|
||||
|
||||
// Check for updates in background after navigation
|
||||
_checkForUpdatesOnStartup();
|
||||
}
|
||||
} else {
|
||||
// All connections failed
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Mixin that provides focus management for library tabs.
|
||||
/// Handles the lifecycle of a focus node for the first item and provides
|
||||
/// a method to request focus on that item.
|
||||
mixin LibraryTabFocusMixin<T extends StatefulWidget> on State<T> {
|
||||
/// Focus node for the first item (for programmatic focus)
|
||||
late final FocusNode firstItemFocusNode;
|
||||
|
||||
/// Debug label for the focus node
|
||||
String get focusNodeDebugLabel;
|
||||
|
||||
/// Number of items in the list/grid
|
||||
int get itemCount;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
firstItemFocusNode = FocusNode(debugLabel: focusNodeDebugLabel);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
firstItemFocusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Focus the first item in the grid/list (for tab activation)
|
||||
void focusFirstItem() {
|
||||
if (itemCount > 0) {
|
||||
firstItemFocusNode.requestFocus();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../services/plex_client.dart';
|
||||
import '../models/plex_library.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
|
||||
|
||||
@@ -47,4 +47,35 @@ class PlexLibrary with MultiServerFields {
|
||||
_$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,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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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)';
|
||||
}
|
||||
@@ -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})';
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,585 @@
|
||||
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) {
|
||||
_updateSelectedTrack<AudioTrack>(
|
||||
trackId,
|
||||
_state.tracks.audio.cast<AudioTrack?>().toList(),
|
||||
(selection, track) => selection.copyWith(audio: track),
|
||||
);
|
||||
}
|
||||
|
||||
void _updateSelectedSubtitleTrack(dynamic trackId) {
|
||||
_updateSelectedTrack<SubtitleTrack>(
|
||||
trackId,
|
||||
_state.tracks.subtitle.cast<SubtitleTrack?>().toList(),
|
||||
(selection, track) => selection.copyWith(subtitle: track),
|
||||
);
|
||||
}
|
||||
|
||||
void _updateSelectedTrack<T>(
|
||||
dynamic trackId,
|
||||
List<T?> tracks,
|
||||
TrackSelection Function(TrackSelection, T?) selectionSetter,
|
||||
) {
|
||||
final id = trackId?.toString();
|
||||
T? selectedTrack;
|
||||
|
||||
if (id != null && id != 'no') {
|
||||
selectedTrack = tracks.firstWhere(
|
||||
(track) => _getTrackId(track) == id,
|
||||
orElse: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
_state = _state.copyWith(
|
||||
track: selectionSetter(_state.track, selectedTrack),
|
||||
);
|
||||
_trackController.add(_state.track);
|
||||
}
|
||||
|
||||
String? _getTrackId<T>(T? track) {
|
||||
final dynamic t = track;
|
||||
return t?.id?.toString();
|
||||
}
|
||||
|
||||
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 || Platform.isWindows) ? '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();
|
||||
}
|
||||
}
|
||||
@@ -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)';
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
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,
|
||||
/// controls: (context) => MyCustomControls(),
|
||||
/// )
|
||||
/// ```
|
||||
class Video extends StatefulWidget {
|
||||
/// The player instance.
|
||||
final Player player;
|
||||
|
||||
/// 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.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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../client/plex_client.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
|
||||
@@ -66,10 +67,37 @@ class MultiServerProvider extends ChangeNotifier {
|
||||
/// 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();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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
|
||||
///
|
||||
@@ -105,10 +105,8 @@ class PlaybackStateProvider with ChangeNotifier {
|
||||
_playQueueShuffled = playQueue.playQueueShuffled;
|
||||
_currentPlayQueueItemID = playQueue.playQueueSelectedItemID;
|
||||
|
||||
// Preserve serverId/serverName on all items
|
||||
_loadedItems = (playQueue.items ?? []).map((item) {
|
||||
return item.copyWith(serverId: serverId, serverName: serverName);
|
||||
}).toList();
|
||||
// Items are already tagged with server info by PlexClient
|
||||
_loadedItems = playQueue.items ?? [];
|
||||
|
||||
_contextKey = contextKey;
|
||||
_playbackMode = PlaybackMode.playQueue;
|
||||
@@ -136,17 +134,8 @@ class PlaybackStateProvider with ChangeNotifier {
|
||||
);
|
||||
|
||||
if (response != null && response.items != null) {
|
||||
// Preserve serverId from existing items
|
||||
final serverId = _loadedItems.isNotEmpty
|
||||
? _loadedItems.first.serverId
|
||||
: null;
|
||||
final serverName = _loadedItems.isNotEmpty
|
||||
? _loadedItems.first.serverName
|
||||
: null;
|
||||
|
||||
_loadedItems = response.items!.map((item) {
|
||||
return item.copyWith(serverId: serverId, serverName: serverName);
|
||||
}).toList();
|
||||
// Items are already tagged with server info by PlexClient
|
||||
_loadedItems = response.items!;
|
||||
// Use size or items length as fallback if totalCount is null
|
||||
_playQueueTotalCount =
|
||||
response.playQueueTotalCount ??
|
||||
@@ -238,25 +227,15 @@ class PlaybackStateProvider with ChangeNotifier {
|
||||
if (response != null &&
|
||||
response.items != null &&
|
||||
response.items!.isNotEmpty) {
|
||||
// Preserve serverId when looping
|
||||
final serverId = _loadedItems.isNotEmpty
|
||||
? _loadedItems.first.serverId
|
||||
: null;
|
||||
final serverName = _loadedItems.isNotEmpty
|
||||
? _loadedItems.first.serverName
|
||||
: null;
|
||||
|
||||
_loadedItems = response.items!.map((item) {
|
||||
return item.copyWith(serverId: serverId, serverName: serverName);
|
||||
}).toList();
|
||||
// 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
|
||||
return firstItem;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -2,58 +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 _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();
|
||||
_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;
|
||||
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);
|
||||
await _settingsService!.setShowHeroSection(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}');
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import 'licenses_screen.dart';
|
||||
|
||||
class AboutScreen extends StatefulWidget {
|
||||
const AboutScreen({super.key});
|
||||
|
||||
@override
|
||||
State<AboutScreen> createState() => _AboutScreenState();
|
||||
}
|
||||
|
||||
class _AboutScreenState extends State<AboutScreen> {
|
||||
String _appName = '';
|
||||
String _appVersion = '';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadPackageInfo();
|
||||
}
|
||||
|
||||
Future<void> _loadPackageInfo() async {
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
setState(() {
|
||||
_appName = t.app.title;
|
||||
_appVersion = packageInfo.version;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final appName = _appName;
|
||||
final appVersion = _appVersion;
|
||||
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(title: Text(t.about.title), pinned: true),
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate([
|
||||
// App Icon and Name
|
||||
Center(
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 24),
|
||||
Image.asset('assets/plezy.png', width: 80, height: 80),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
appName,
|
||||
style: Theme.of(context).textTheme.headlineMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
t.about.versionLabel(version: appVersion),
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
t.about.appDescription,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// Open Source Licenses
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.description),
|
||||
title: Text(t.about.openSourceLicenses),
|
||||
subtitle: Text(t.about.viewLicensesDescription),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const LicensesScreen(),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -48,19 +48,27 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
});
|
||||
|
||||
try {
|
||||
// Fetch all servers for this user
|
||||
// Fetch user info and servers for this user
|
||||
final userInfo = await _authService.getUserInfo(plexToken);
|
||||
final username = userInfo['username'] as String? ?? '';
|
||||
final email = userInfo['email'] as String? ?? '';
|
||||
|
||||
final servers = await _authService.fetchServers(plexToken);
|
||||
final storage = await StorageService.getInstance();
|
||||
|
||||
if (servers.isEmpty) {
|
||||
await storage.clearCredentials();
|
||||
setState(() {
|
||||
_isAuthenticating = false;
|
||||
_errorMessage = t.serverSelection.noServersFound;
|
||||
_errorMessage = t.serverSelection.noServersFoundForAccount(
|
||||
username: username,
|
||||
email: email,
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Save all servers to registry and enable them
|
||||
final storage = await StorageService.getInstance();
|
||||
final registry = ServerRegistry(storage);
|
||||
await registry.saveServers(servers);
|
||||
|
||||
@@ -329,57 +337,10 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (_isAuthenticating) ...[
|
||||
if (_useQrFlow && _qrAuthUrl != null) ...[
|
||||
// QR code flow - hint text above QR code
|
||||
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: 300,
|
||||
version: QrVersions.auto,
|
||||
backgroundColor: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
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),
|
||||
),
|
||||
],
|
||||
if (_useQrFlow && _qrAuthUrl != null)
|
||||
_buildQrAuthWidget(qrSize: 300)
|
||||
else
|
||||
_buildBrowserAuthWidget(),
|
||||
] else ...[
|
||||
// Initial state buttons
|
||||
ElevatedButton(
|
||||
@@ -455,24 +416,10 @@ 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,
|
||||
),
|
||||
),
|
||||
child: Text(t.auth.retry),
|
||||
),
|
||||
if (_useQrFlow && _qrAuthUrl != null)
|
||||
_buildQrAuthWidget(qrSize: 200)
|
||||
else
|
||||
_buildBrowserAuthWidget(),
|
||||
] else ...[
|
||||
// add QR button here
|
||||
ElevatedButton(
|
||||
@@ -530,4 +477,64 @@ 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),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds the QR code authentication widget
|
||||
Widget _buildQrAuthWidget({required double qrSize}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
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: qrSize,
|
||||
version: QrVersions.auto,
|
||||
backgroundColor: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
_buildRetryButton(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds the browser authentication waiting widget
|
||||
Widget _buildBrowserAuthWidget() {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Center(child: CircularProgressIndicator()),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
t.auth.waitingForAuth,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: Colors.grey),
|
||||
),
|
||||
_buildRetryButton(),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
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';
|
||||
@@ -51,6 +53,18 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -231,21 +245,12 @@ mixin StandardItemLoader<T extends StatefulWidget>
|
||||
}
|
||||
|
||||
try {
|
||||
// Items are automatically tagged with server info by PlexClient
|
||||
final newItems = await fetchItems();
|
||||
|
||||
// Tag items with server info for correct client resolution
|
||||
final serverId = (mediaItem as dynamic).serverId as String?;
|
||||
final serverName = (mediaItem as dynamic).serverName as String?;
|
||||
|
||||
final taggedItems = newItems
|
||||
.map(
|
||||
(item) => item.copyWith(serverId: serverId, serverName: serverName),
|
||||
)
|
||||
.toList();
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
items = taggedItems;
|
||||
items = newItems;
|
||||
isLoading = false;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../widgets/media_card.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/media_grid_sliver.dart';
|
||||
import '../widgets/focused_scroll_scaffold.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../utils/grid_size_calculator.dart';
|
||||
import '../utils/dialogs.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'base_media_list_detail_screen.dart';
|
||||
@@ -114,47 +111,20 @@ class _CollectionDetailScreenState
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(
|
||||
title: Text(widget.collection.title),
|
||||
pinned: true,
|
||||
actions: buildAppBarActions(onDelete: _deleteCollection),
|
||||
return FocusedScrollScaffold(
|
||||
title: Text(widget.collection.title),
|
||||
actions: buildAppBarActions(onDelete: _deleteCollection),
|
||||
slivers: [
|
||||
...buildStateSlivers(),
|
||||
if (items.isNotEmpty)
|
||||
MediaGridSliver(
|
||||
items: items,
|
||||
onRefresh: updateItem,
|
||||
collectionId: widget.collection.ratingKey,
|
||||
onListRefresh: loadItems,
|
||||
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
|
||||
),
|
||||
...buildStateSlivers(),
|
||||
if (items.isNotEmpty)
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
|
||||
sliver: Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SliverGrid(
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent:
|
||||
GridSizeCalculator.getMaxCrossAxisExtent(
|
||||
context,
|
||||
settingsProvider.libraryDensity,
|
||||
),
|
||||
childAspectRatio: 2 / 3.3,
|
||||
crossAxisSpacing: 0,
|
||||
mainAxisSpacing: 0,
|
||||
),
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
final item = items[index];
|
||||
return MediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
onRefresh: updateItem,
|
||||
collectionId: widget.collection.ratingKey,
|
||||
onListRefresh: loadItems,
|
||||
);
|
||||
}, childCount: items.length),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
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';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
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 '../widgets/media_grid_sliver.dart';
|
||||
import '../widgets/focused_scroll_scaffold.dart';
|
||||
import 'libraries/sort_bottom_sheet.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
|
||||
@@ -37,7 +34,7 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
|
||||
|
||||
/// Get the correct PlexClient for this hub's server
|
||||
PlexClient _getClientForHub() {
|
||||
return context.getClientForServer(widget.hub.serverId);
|
||||
return context.getClientForServer(widget.hub.serverId!);
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -242,73 +239,49 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(
|
||||
title: Text(widget.hub.title),
|
||||
pinned: true,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: Icon(Icons.swap_vert, semanticLabel: t.libraries.sort),
|
||||
onPressed: _showSortBottomSheet,
|
||||
),
|
||||
],
|
||||
),
|
||||
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: _loadMoreItems,
|
||||
child: Text(t.common.retry),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (_filteredItems.isEmpty && _isLoading)
|
||||
const SliverFillRemaining(
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
else if (_filteredItems.isEmpty)
|
||||
SliverFillRemaining(
|
||||
child: Center(child: Text(t.hubDetail.noItemsFound)),
|
||||
)
|
||||
else
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
sliver: SliverGrid(
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: getMaxCrossAxisExtentWithPadding(
|
||||
context,
|
||||
context.watch<SettingsProvider>().libraryDensity,
|
||||
16,
|
||||
return FocusedScrollScaffold(
|
||||
title: Text(widget.hub.title),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: Icon(Icons.swap_vert, semanticLabel: t.libraries.sort),
|
||||
onPressed: _showSortBottomSheet,
|
||||
),
|
||||
],
|
||||
slivers: [
|
||||
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: _loadMoreItems,
|
||||
child: Text(t.common.retry),
|
||||
),
|
||||
childAspectRatio: 2 / 3.3,
|
||||
crossAxisSpacing: 0,
|
||||
mainAxisSpacing: 0,
|
||||
),
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
return MediaCard(
|
||||
item: _filteredItems[index],
|
||||
onRefresh: _handleItemRefresh,
|
||||
);
|
||||
}, childCount: _filteredItems.length),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else if (_filteredItems.isEmpty && _isLoading)
|
||||
const SliverFillRemaining(
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
else if (_filteredItems.isEmpty)
|
||||
SliverFillRemaining(
|
||||
child: Center(child: Text(t.hubDetail.noItemsFound)),
|
||||
)
|
||||
else
|
||||
MediaGridSliver(
|
||||
items: _filteredItems,
|
||||
onRefresh: _handleItemRefresh,
|
||||
usePaddingAwareExtent: true,
|
||||
horizontalPadding: 16,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../providers/settings_provider.dart';
|
||||
import '../../services/settings_service.dart' show ViewMode, LibraryDensity;
|
||||
import '../../utils/grid_size_calculator.dart';
|
||||
|
||||
/// A widget that automatically switches between grid and list view
|
||||
/// based on user settings, providing a consistent layout pattern
|
||||
/// across all library screens.
|
||||
///
|
||||
/// Generic type T: The type of items being displayed
|
||||
class AdaptiveMediaGrid<T> extends StatelessWidget {
|
||||
/// The list of items to display
|
||||
final List<T> items;
|
||||
|
||||
/// Builder function for each item in the grid/list
|
||||
final Widget Function(BuildContext context, T item, int index) itemBuilder;
|
||||
|
||||
/// 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 programmatic focus)
|
||||
final FocusNode? firstItemFocusNode;
|
||||
|
||||
/// Callback when back button is pressed (for hierarchical navigation)
|
||||
final VoidCallback? onBack;
|
||||
|
||||
const AdaptiveMediaGrid({
|
||||
super.key,
|
||||
required this.items,
|
||||
required this.itemBuilder,
|
||||
this.onRefresh,
|
||||
this.padding = const EdgeInsets.fromLTRB(8, 8, 8, 8),
|
||||
this.childAspectRatio = 2 / 3.3,
|
||||
this.firstItemFocusNode,
|
||||
this.onBack,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return _buildItemsView(
|
||||
context,
|
||||
settingsProvider.viewMode,
|
||||
settingsProvider.libraryDensity,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds either a list or grid view based on the view mode
|
||||
Widget _buildItemsView(
|
||||
BuildContext context,
|
||||
ViewMode viewMode,
|
||||
LibraryDensity density,
|
||||
) {
|
||||
if (viewMode == ViewMode.list) {
|
||||
return ListView.builder(
|
||||
padding: padding,
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) =>
|
||||
itemBuilder(context, items[index], index),
|
||||
);
|
||||
} else {
|
||||
return GridView.builder(
|
||||
padding: padding,
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
|
||||
context,
|
||||
density,
|
||||
),
|
||||
childAspectRatio: childAspectRatio,
|
||||
crossAxisSpacing: 0,
|
||||
mainAxisSpacing: 0,
|
||||
),
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) =>
|
||||
itemBuilder(context, items[index], index),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
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';
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../models/plex_filter.dart';
|
||||
import '../../widgets/app_bar_back_button.dart';
|
||||
import '../../widgets/bottom_sheet_header.dart';
|
||||
import '../../widgets/focusable_bottom_sheet.dart';
|
||||
import '../../widgets/focusable_list_tile.dart';
|
||||
import '../../utils/provider_extensions.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;
|
||||
late final FocusNode _initialFocusNode;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tempSelectedFilters.addAll(widget.selectedFilters);
|
||||
_sortFilters();
|
||||
_initialFocusNode = FocusNode(debugLabel: 'FiltersBottomSheetInitialFocus');
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_initialFocusNode.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;
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_filterValues = [];
|
||||
_isLoadingValues = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _goBack() {
|
||||
setState(() {
|
||||
_currentFilter = null;
|
||||
_filterValues = [];
|
||||
});
|
||||
}
|
||||
|
||||
void _applyFilters() {
|
||||
widget.onFiltersChanged(_tempSelectedFilters);
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
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 FocusableBottomSheet(
|
||||
initialFocusNode: _initialFocusNode,
|
||||
child: DraggableScrollableSheet(
|
||||
initialChildSize: 0.7,
|
||||
minChildSize: 0.5,
|
||||
maxChildSize: 0.95,
|
||||
expand: false,
|
||||
builder: (context, scrollController) {
|
||||
if (_currentFilter != null) {
|
||||
// Show filter options view
|
||||
return Column(
|
||||
children: [
|
||||
// Header with back button
|
||||
BottomSheetHeader(
|
||||
title: _currentFilter!.title,
|
||||
leading: AppBarBackButton(
|
||||
style: BackButtonStyle.plain,
|
||||
onPressed: _goBack,
|
||||
),
|
||||
),
|
||||
|
||||
// Filter options list
|
||||
if (_isLoadingValues)
|
||||
const Expanded(
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
else
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: _filterValues.length + 1,
|
||||
itemBuilder: (context, index) {
|
||||
if (index == 0) {
|
||||
final isSelected = !_tempSelectedFilters.containsKey(
|
||||
_currentFilter!.filter,
|
||||
);
|
||||
return FocusableListTile(
|
||||
focusNode: _initialFocusNode,
|
||||
title: Text(t.libraries.all),
|
||||
selected: isSelected,
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_tempSelectedFilters.remove(
|
||||
_currentFilter!.filter,
|
||||
);
|
||||
});
|
||||
_applyFilters();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
final value = _filterValues[index - 1];
|
||||
final filterValue = _extractFilterValue(
|
||||
value.key,
|
||||
_currentFilter!.filter,
|
||||
);
|
||||
final isSelected =
|
||||
_tempSelectedFilters[_currentFilter!.filter] ==
|
||||
filterValue;
|
||||
|
||||
return FocusableListTile(
|
||||
title: Text(value.title),
|
||||
selected: isSelected,
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_tempSelectedFilters[_currentFilter!.filter] =
|
||||
filterValue;
|
||||
// Cache the display name for this filter value
|
||||
_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 FocusableSwitchListTile(
|
||||
focusNode: index == 0 ? _initialFocusNode : null,
|
||||
value: isActive,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
if (value) {
|
||||
_tempSelectedFilters[filter.filter] = '1';
|
||||
} else {
|
||||
_tempSelectedFilters.remove(filter.filter);
|
||||
}
|
||||
});
|
||||
_applyFilters();
|
||||
},
|
||||
title: Text(filter.title),
|
||||
);
|
||||
}
|
||||
|
||||
// Regular navigable filters - show selected value instead of checkmark
|
||||
final selectedValue = _tempSelectedFilters[filter.filter];
|
||||
String? displayValue;
|
||||
if (selectedValue != null) {
|
||||
// Try to get the cached display name, fall back to the value itself
|
||||
displayValue =
|
||||
_filterDisplayNames['${filter.filter}:$selectedValue'] ??
|
||||
selectedValue;
|
||||
}
|
||||
|
||||
return FocusableListTile(
|
||||
focusNode: index == 0 ? _initialFocusNode : null,
|
||||
title: Text(filter.title),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (displayValue != null)
|
||||
Flexible(
|
||||
child: Text(
|
||||
displayValue,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
if (displayValue != null) const SizedBox(width: 8),
|
||||
const Icon(Icons.chevron_right),
|
||||
],
|
||||
),
|
||||
onTap: () => _loadFilterValues(filter),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../../models/plex_metadata.dart';
|
||||
|
||||
/// Individual item in the folder tree
|
||||
/// Can be either a folder (expandable) or a file (tappable)
|
||||
@@ -46,12 +46,20 @@ class FolderTreeItem extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
void _handleTap() {
|
||||
if (isFolder) {
|
||||
onExpand?.call();
|
||||
} else {
|
||||
onTap?.call();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final indentation = depth * 24.0;
|
||||
|
||||
return InkWell(
|
||||
onTap: isFolder ? onExpand : onTap,
|
||||
onTap: _handleTap,
|
||||
child: Container(
|
||||
padding: EdgeInsets.only(
|
||||
left: 16.0 + indentation,
|
||||
@@ -1,11 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../screens/media_detail_screen.dart';
|
||||
import '../screens/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 '../../models/plex_metadata.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../../utils/media_navigation_helper.dart';
|
||||
import '../../utils/provider_extensions.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import 'folder_tree_item.dart';
|
||||
import 'empty_state_widget.dart';
|
||||
import 'error_state_widget.dart';
|
||||
@@ -49,7 +47,7 @@ class _FolderTreeViewState extends State<FolderTreeView> {
|
||||
});
|
||||
|
||||
try {
|
||||
final client = context.getClientForServer(widget.serverId);
|
||||
final client = context.getClientForServer(widget.serverId!);
|
||||
|
||||
final folders = await client.getLibraryFolders(widget.libraryKey);
|
||||
|
||||
@@ -58,7 +56,7 @@ class _FolderTreeViewState extends State<FolderTreeView> {
|
||||
final taggedFolders = folders
|
||||
.map(
|
||||
(folder) => folder.copyWith(
|
||||
serverId: widget.serverId,
|
||||
serverId: widget.serverId!,
|
||||
serverName: null, // server name not required for folders listing
|
||||
),
|
||||
)
|
||||
@@ -101,21 +99,15 @@ class _FolderTreeViewState extends State<FolderTreeView> {
|
||||
});
|
||||
|
||||
try {
|
||||
final client = context.getClientForServer(widget.serverId);
|
||||
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;
|
||||
|
||||
final taggedChildren = children
|
||||
.map(
|
||||
(child) =>
|
||||
child.copyWith(serverId: widget.serverId, serverName: null),
|
||||
)
|
||||
.toList();
|
||||
|
||||
setState(() {
|
||||
_childrenCache[folder.key] = taggedChildren;
|
||||
_childrenCache[folder.key] = children;
|
||||
_expandedFolders.add(folder.key);
|
||||
_loadingFolders.remove(folder.key);
|
||||
});
|
||||
@@ -157,34 +149,7 @@ class _FolderTreeViewState extends State<FolderTreeView> {
|
||||
}
|
||||
|
||||
Future<void> _handleItemTap(PlexMetadata item) async {
|
||||
final itemType = item.type.toLowerCase();
|
||||
|
||||
// For episodes, start playback directly
|
||||
if (itemType == 'episode') {
|
||||
final result = await navigateToVideoPlayer(context, metadata: item);
|
||||
if (result == true) {
|
||||
widget.onRefresh?.call(item.ratingKey);
|
||||
}
|
||||
} else if (itemType == 'season') {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => SeasonDetailScreen(season: item),
|
||||
),
|
||||
);
|
||||
widget.onRefresh?.call(item.ratingKey);
|
||||
} else {
|
||||
// For all other types (shows, movies), show detail screen
|
||||
final result = await Navigator.push<bool>(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MediaDetailScreen(metadata: item),
|
||||
),
|
||||
);
|
||||
if (result == true) {
|
||||
widget.onRefresh?.call(item.ratingKey);
|
||||
}
|
||||
}
|
||||
await navigateToMediaItem(context, item, onRefresh: widget.onRefresh);
|
||||
}
|
||||
|
||||
bool _isFolder(PlexMetadata item) {
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../models/plex_sort.dart';
|
||||
import '../../widgets/bottom_sheet_header.dart';
|
||||
import '../../widgets/focusable_bottom_sheet.dart';
|
||||
import '../../widgets/focusable_list_tile.dart';
|
||||
import '../../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;
|
||||
late final FocusNode _initialFocusNode;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_currentSort = widget.selectedSort;
|
||||
_currentDescending = widget.isSortDescending;
|
||||
_initialFocusNode = FocusNode(debugLabel: 'SortBottomSheetInitialFocus');
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_initialFocusNode.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 FocusableBottomSheet(
|
||||
initialFocusNode: _initialFocusNode,
|
||||
child: DraggableScrollableSheet(
|
||||
initialChildSize: 0.6,
|
||||
minChildSize: 0.4,
|
||||
maxChildSize: 0.9,
|
||||
expand: false,
|
||||
builder: (context, scrollController) {
|
||||
return Column(
|
||||
children: [
|
||||
BottomSheetHeader(
|
||||
title: t.libraries.sortBy,
|
||||
action: widget.onClear != null
|
||||
? TextButton(
|
||||
onPressed: _handleClear,
|
||||
child: Text(t.common.clear),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: widget.sortOptions.length,
|
||||
itemBuilder: (context, index) {
|
||||
final sort = widget.sortOptions[index];
|
||||
final isSelected = _currentSort?.key == sort.key;
|
||||
|
||||
return FocusableRadioListTile<PlexSort>(
|
||||
focusNode: index == 0 ? _initialFocusNode : null,
|
||||
title: Text(sort.title),
|
||||
value: sort,
|
||||
groupValue: _currentSort,
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
_handleSortChange(value, value.isDefaultDescending);
|
||||
}
|
||||
},
|
||||
secondary: isSelected
|
||||
? 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,10 +1,10 @@
|
||||
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 '../../widgets/content_state_builder.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.
|
||||
@@ -25,11 +25,31 @@ abstract class BaseLibraryTab<T> extends StatefulWidget {
|
||||
final String? viewMode;
|
||||
final String? density;
|
||||
|
||||
/// Callback invoked when data has finished loading successfully.
|
||||
/// Used by parent to trigger focus on the first item.
|
||||
final VoidCallback? onDataLoaded;
|
||||
|
||||
/// Whether this tab is currently the active/visible tab.
|
||||
/// Used for internal focus management.
|
||||
final bool isActive;
|
||||
|
||||
/// Whether to suppress auto-focus when tab becomes active.
|
||||
/// Used when navigating via tab bar to keep focus on the tab chips.
|
||||
final bool suppressAutoFocus;
|
||||
|
||||
/// Called when the user presses BACK in the tab content.
|
||||
/// Used to navigate focus back to the tab bar.
|
||||
final VoidCallback? onBack;
|
||||
|
||||
const BaseLibraryTab({
|
||||
super.key,
|
||||
required this.library,
|
||||
this.viewMode,
|
||||
this.density,
|
||||
this.onDataLoaded,
|
||||
this.isActive = false,
|
||||
this.suppressAutoFocus = false,
|
||||
this.onBack,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -55,10 +75,25 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
|
||||
String? _errorMessage;
|
||||
StreamSubscription<void>? _refreshSubscription;
|
||||
|
||||
// Focus management
|
||||
bool _hasLoadedData = false;
|
||||
bool _hasFocused = false;
|
||||
|
||||
// Getters for subclasses
|
||||
List<T> get items => _items;
|
||||
bool get isLoading => _isLoading;
|
||||
String? get errorMessage => _errorMessage;
|
||||
bool get hasLoadedData => _hasLoadedData;
|
||||
|
||||
// Setters for subclasses that override loadItems with custom logic
|
||||
@protected
|
||||
set items(List<T> value) => _items = value;
|
||||
@protected
|
||||
set isLoading(bool value) => _isLoading = value;
|
||||
@protected
|
||||
set errorMessage(String? value) => _errorMessage = value;
|
||||
@protected
|
||||
set hasLoadedData(bool value) => _hasLoadedData = value;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -87,8 +122,22 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// Reload if library changed
|
||||
if (oldWidget.library.globalKey != widget.library.globalKey) {
|
||||
// Reset focus state for new library
|
||||
_hasFocused = false;
|
||||
_hasLoadedData = false;
|
||||
// Immediately clear stale data before async load
|
||||
setState(() {
|
||||
_items = [];
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
loadItems();
|
||||
}
|
||||
|
||||
// Check if we should focus (became active after data loaded)
|
||||
if (widget.isActive && !oldWidget.isActive) {
|
||||
tryFocus();
|
||||
}
|
||||
}
|
||||
|
||||
/// Load items from the API
|
||||
@@ -112,11 +161,36 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
|
||||
/// Return null if no refresh stream is needed
|
||||
Stream<void>? getRefreshStream() => null;
|
||||
|
||||
/// Try to focus the first item if conditions are met (active + loaded + not yet focused)
|
||||
@protected
|
||||
void tryFocus() {
|
||||
// Don't auto-focus if suppressed (e.g., when navigating via tab bar)
|
||||
if (widget.suppressAutoFocus) return;
|
||||
|
||||
if (widget.isActive &&
|
||||
_hasLoadedData &&
|
||||
!_hasFocused &&
|
||||
_items.isNotEmpty) {
|
||||
_hasFocused = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) {
|
||||
focusFirstItem();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Focus the first item in the tab. Subclasses should override this.
|
||||
void focusFirstItem() {
|
||||
// Default implementation - subclasses should override
|
||||
}
|
||||
|
||||
/// Load items with error handling and state management
|
||||
Future<void> loadItems() async {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
_items = []; // Clear items to prevent showing stale data during load
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -128,6 +202,17 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
|
||||
_items = loadedItems;
|
||||
_isLoading = false;
|
||||
});
|
||||
|
||||
// Mark data as loaded and try to focus
|
||||
_hasLoadedData = true;
|
||||
tryFocus();
|
||||
|
||||
// Notify parent that data has loaded
|
||||
if (widget.onDataLoaded != null) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
widget.onDataLoaded!();
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
|
||||
@@ -1,81 +1,72 @@
|
||||
import 'package:flutter/material.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/settings_provider.dart';
|
||||
import '../../utils/error_message_utils.dart';
|
||||
import '../../utils/grid_size_calculator.dart';
|
||||
import '../../utils/server_tagging_extensions.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 '../../widgets/empty_state_widget.dart';
|
||||
import '../../widgets/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';
|
||||
import '../../../../services/plex_client.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 '../../../widgets/focusable_media_card.dart';
|
||||
import '../../../widgets/focusable_filter_chip.dart';
|
||||
import '../../../widgets/media_grid_delegate.dart';
|
||||
import '../../../mixins/library_tab_focus_mixin.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 '../../../i18n/strings.g.dart';
|
||||
import 'base_library_tab.dart';
|
||||
|
||||
/// Browse tab for library screen
|
||||
/// Shows library items with grouping, filtering, and sorting
|
||||
class LibraryBrowseTab extends StatefulWidget {
|
||||
final PlexLibrary library;
|
||||
final String? viewMode;
|
||||
final String? density;
|
||||
|
||||
class LibraryBrowseTab extends BaseLibraryTab<PlexMetadata> {
|
||||
const LibraryBrowseTab({
|
||||
super.key,
|
||||
required this.library,
|
||||
this.viewMode,
|
||||
this.density,
|
||||
required super.library,
|
||||
super.viewMode,
|
||||
super.density,
|
||||
super.onDataLoaded,
|
||||
super.isActive,
|
||||
super.suppressAutoFocus,
|
||||
super.onBack,
|
||||
});
|
||||
|
||||
@override
|
||||
State<LibraryBrowseTab> createState() => _LibraryBrowseTabState();
|
||||
}
|
||||
|
||||
class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
with
|
||||
AutomaticKeepAliveClientMixin,
|
||||
ItemUpdatable,
|
||||
Refreshable,
|
||||
LibraryTabStateMixin {
|
||||
@override
|
||||
bool get wantKeepAlive => true;
|
||||
|
||||
@override
|
||||
PlexLibrary get library => widget.library;
|
||||
|
||||
class _LibraryBrowseTabState
|
||||
extends BaseLibraryTabState<PlexMetadata, LibraryBrowseTab>
|
||||
with ItemUpdatable, LibraryTabStateMixin, LibraryTabFocusMixin {
|
||||
@override
|
||||
PlexClient get client => getClientForLibrary();
|
||||
|
||||
@override
|
||||
void refresh() {
|
||||
_loadContent();
|
||||
}
|
||||
String get focusNodeDebugLabel => 'browse_first_item';
|
||||
|
||||
@override
|
||||
int get itemCount => items.length;
|
||||
|
||||
@override
|
||||
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
|
||||
setState(() {
|
||||
final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
|
||||
final index = items.indexWhere((item) => item.ratingKey == ratingKey);
|
||||
if (index != -1) {
|
||||
_items[index] = updatedMetadata;
|
||||
items[index] = updatedMetadata;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
List<PlexMetadata> _items = [];
|
||||
// Browse-specific state (not in base class)
|
||||
List<PlexFilter> _filters = [];
|
||||
List<PlexSort> _sortOptions = [];
|
||||
bool _isLoading = false;
|
||||
String? _errorMessage;
|
||||
Map<String, String> _selectedFilters = {};
|
||||
PlexSort? _selectedSort;
|
||||
bool _isSortDescending = false;
|
||||
@@ -88,27 +79,67 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
int _requestId = 0;
|
||||
static const int _pageSize = 500;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadContent();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(LibraryBrowseTab oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// Reload if library changed
|
||||
if (oldWidget.library.globalKey != widget.library.globalKey) {
|
||||
_loadContent();
|
||||
}
|
||||
}
|
||||
// Focus nodes for filter chips
|
||||
final FocusNode _groupingChipFocusNode = FocusNode(
|
||||
debugLabel: 'grouping_chip',
|
||||
);
|
||||
final FocusNode _filtersChipFocusNode = FocusNode(debugLabel: 'filters_chip');
|
||||
final FocusNode _sortChipFocusNode = FocusNode(debugLabel: 'sort_chip');
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_cancelToken?.cancel();
|
||||
_groupingChipFocusNode.dispose();
|
||||
_filtersChipFocusNode.dispose();
|
||||
_sortChipFocusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// Override loadData to use our custom _loadContent
|
||||
@override
|
||||
Future<List<PlexMetadata>> loadData() async {
|
||||
// This is called by base class loadItems(), but we override loadItems() entirely
|
||||
// So this just returns empty - actual loading is done in _loadContent
|
||||
return [];
|
||||
}
|
||||
|
||||
// Override loadItems to use our custom loading with pagination
|
||||
@override
|
||||
Future<void> loadItems() async {
|
||||
await _loadContent();
|
||||
}
|
||||
|
||||
// Required abstract implementations from base class
|
||||
@override
|
||||
IconData get emptyIcon => Icons.folder_open;
|
||||
|
||||
@override
|
||||
String get emptyMessage => t.libraries.thisLibraryIsEmpty;
|
||||
|
||||
@override
|
||||
String get errorContext => t.libraries.content;
|
||||
|
||||
// Override buildContent - not used since we override build()
|
||||
@override
|
||||
Widget buildContent(List<PlexMetadata> items) => const SizedBox.shrink();
|
||||
|
||||
/// Focus the first item in the grid/list (for tab activation)
|
||||
@override
|
||||
void focusFirstItem() {
|
||||
if (items.isNotEmpty) {
|
||||
// Request immediately, then once more on the next frame to handle cases
|
||||
// where the grid/list attaches after the initial focus attempt.
|
||||
void request() {
|
||||
if (mounted && items.isNotEmpty && !firstItemFocusNode.hasFocus) {
|
||||
firstItemFocusNode.requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
request();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => request());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadContent() async {
|
||||
// Cancel any pending request
|
||||
_cancelToken?.cancel();
|
||||
@@ -119,11 +150,18 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
final client = getClientForLibrary();
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
_items = [];
|
||||
isLoading = true;
|
||||
errorMessage = null;
|
||||
items = [];
|
||||
_currentPage = 0;
|
||||
_hasMoreItems = true;
|
||||
// Clear filter/sort state while loading to prevent showing stale options
|
||||
_filters = [];
|
||||
_sortOptions = [];
|
||||
_selectedFilters = {};
|
||||
_selectedSort = null;
|
||||
_isSortDescending = false;
|
||||
_selectedGrouping = _getDefaultGrouping();
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -167,17 +205,12 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
// Load items
|
||||
await _loadItems();
|
||||
} catch (e) {
|
||||
if (currentRequestId != _requestId) return;
|
||||
|
||||
setState(() {
|
||||
_errorMessage = _getErrorMessage(e);
|
||||
_isLoading = false;
|
||||
});
|
||||
_handleLoadError(e, currentRequestId);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadItems({bool loadMore = false}) async {
|
||||
if (loadMore && _isLoading) return;
|
||||
if (loadMore && isLoading) return;
|
||||
|
||||
if (!loadMore) {
|
||||
_currentPage = 0;
|
||||
@@ -191,9 +224,9 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
_cancelToken = CancelToken();
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
isLoading = true;
|
||||
if (!loadMore) {
|
||||
_items = [];
|
||||
items = [];
|
||||
}
|
||||
});
|
||||
|
||||
@@ -219,7 +252,8 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
);
|
||||
}
|
||||
|
||||
final items = await client.getLibraryContent(
|
||||
// Items are automatically tagged with server info by PlexClient
|
||||
final loadedItems = await client.getLibraryContent(
|
||||
widget.library.key,
|
||||
start: _currentPage * _pageSize,
|
||||
size: _pageSize,
|
||||
@@ -227,31 +261,45 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
cancelToken: _cancelToken,
|
||||
);
|
||||
|
||||
// Tag items with server info for multi-server support
|
||||
final taggedItems = items.tagWithLibrary(widget.library);
|
||||
|
||||
if (currentRequestId != _requestId) return;
|
||||
|
||||
setState(() {
|
||||
if (loadMore) {
|
||||
_items.addAll(taggedItems);
|
||||
items.addAll(loadedItems);
|
||||
} else {
|
||||
_items = taggedItems;
|
||||
items = loadedItems;
|
||||
}
|
||||
_hasMoreItems = taggedItems.length >= _pageSize;
|
||||
_hasMoreItems = loadedItems.length >= _pageSize;
|
||||
_currentPage++;
|
||||
_isLoading = false;
|
||||
isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (currentRequestId != _requestId) return;
|
||||
|
||||
setState(() {
|
||||
_errorMessage = _getErrorMessage(e);
|
||||
_isLoading = false;
|
||||
});
|
||||
// On initial load (not pagination), mark data as loaded and try to focus
|
||||
if (!loadMore) {
|
||||
hasLoadedData = true;
|
||||
tryFocus();
|
||||
|
||||
// Notify parent
|
||||
if (widget.onDataLoaded != null) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
widget.onDataLoaded!();
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_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') {
|
||||
@@ -315,16 +363,17 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
void _showGroupingBottomSheet() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return ListView(
|
||||
builder: (sheetContext) {
|
||||
final options = _getGroupingOptions();
|
||||
return ListView.builder(
|
||||
shrinkWrap: true,
|
||||
children: _getGroupingOptions().map((grouping) {
|
||||
itemCount: options.length,
|
||||
itemBuilder: (context, index) {
|
||||
final grouping = options[index];
|
||||
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(() {
|
||||
@@ -337,14 +386,14 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
value,
|
||||
);
|
||||
|
||||
if (!context.mounted) return;
|
||||
if (!sheetContext.mounted) return;
|
||||
|
||||
Navigator.pop(context);
|
||||
Navigator.pop(sheetContext);
|
||||
_loadItems();
|
||||
}
|
||||
},
|
||||
);
|
||||
}).toList(),
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -357,6 +406,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
builder: (context) => FiltersBottomSheet(
|
||||
filters: _filters,
|
||||
selectedFilters: _selectedFilters,
|
||||
serverId: widget.library.serverId!,
|
||||
onFiltersChanged: (filters) async {
|
||||
setState(() {
|
||||
_selectedFilters.clear();
|
||||
@@ -404,39 +454,35 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildFilterChip({
|
||||
required IconData icon,
|
||||
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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
/// Navigate focus from chips down to the first grid item
|
||||
void _navigateToGrid() {
|
||||
if (items.isNotEmpty) {
|
||||
firstItemFocusNode.requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigate focus from grid up to the grouping chip
|
||||
void _navigateToChips() {
|
||||
_groupingChipFocusNode.requestFocus();
|
||||
}
|
||||
|
||||
/// Calculate the number of columns in the current grid based on screen width
|
||||
int _getGridColumnCount(
|
||||
BuildContext context,
|
||||
SettingsProvider settingsProvider,
|
||||
) {
|
||||
final screenWidth =
|
||||
MediaQuery.of(context).size.width - 16; // Subtract padding
|
||||
final maxCrossAxisExtent = GridSizeCalculator.getMaxCrossAxisExtent(
|
||||
context,
|
||||
settingsProvider.libraryDensity,
|
||||
);
|
||||
return (screenWidth / maxCrossAxisExtent).floor().clamp(1, 100);
|
||||
}
|
||||
|
||||
/// Check if the given index is in the first row of the grid
|
||||
bool _isFirstRow(int index, int columnCount) {
|
||||
return index < columnCount;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -455,15 +501,20 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Grouping chip
|
||||
_buildFilterChip(
|
||||
FocusableFilterChip(
|
||||
focusNode: _groupingChipFocusNode,
|
||||
icon: Icons.category,
|
||||
label: _getGroupingLabel(_selectedGrouping),
|
||||
onPressed: _showGroupingBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Filters chip
|
||||
if (_filters.isNotEmpty && _selectedGrouping != 'folders')
|
||||
_buildFilterChip(
|
||||
FocusableFilterChip(
|
||||
focusNode: _filtersChipFocusNode,
|
||||
icon: Icons.filter_alt,
|
||||
label: _selectedFilters.isEmpty
|
||||
? t.libraries.filters
|
||||
@@ -471,15 +522,22 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
count: _selectedFilters.length,
|
||||
),
|
||||
onPressed: _showFiltersBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
if (_filters.isNotEmpty && _selectedGrouping != 'folders')
|
||||
const SizedBox(width: 8),
|
||||
// Sort chip
|
||||
if (_sortOptions.isNotEmpty && _selectedGrouping != 'folders')
|
||||
_buildFilterChip(
|
||||
FocusableFilterChip(
|
||||
focusNode: _sortChipFocusNode,
|
||||
icon: Icons.sort,
|
||||
label: _selectedSort?.title ?? t.libraries.sort,
|
||||
onPressed: _showSortBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -502,20 +560,20 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
);
|
||||
}
|
||||
|
||||
if (_isLoading && _items.isEmpty) {
|
||||
if (isLoading && items.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (_errorMessage != null && _items.isEmpty) {
|
||||
if (errorMessage != null && items.isEmpty) {
|
||||
return ErrorStateWidget(
|
||||
message: _errorMessage!,
|
||||
message: errorMessage!,
|
||||
icon: Icons.error_outline,
|
||||
onRetry: _loadContent,
|
||||
retryLabel: t.common.retry,
|
||||
);
|
||||
}
|
||||
|
||||
if (_items.isEmpty) {
|
||||
if (items.isEmpty) {
|
||||
return EmptyStateWidget(
|
||||
message: t.libraries.thisLibraryIsEmpty,
|
||||
icon: Icons.folder_open,
|
||||
@@ -527,60 +585,67 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
|
||||
if (notification.metrics.pixels >=
|
||||
notification.metrics.maxScrollExtent - 300 &&
|
||||
_hasMoreItems &&
|
||||
!_isLoading) {
|
||||
!isLoading) {
|
||||
_loadItems(loadMore: true);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
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,
|
||||
);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
return GridView.builder(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
|
||||
context,
|
||||
settingsProvider.libraryDensity,
|
||||
),
|
||||
childAspectRatio: 2 / 3.3,
|
||||
crossAxisSpacing: 0,
|
||||
mainAxisSpacing: 0,
|
||||
),
|
||||
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,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
return _buildItemsView(context, settingsProvider);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds either a list or grid view based on the view mode
|
||||
Widget _buildItemsView(
|
||||
BuildContext context,
|
||||
SettingsProvider settingsProvider,
|
||||
) {
|
||||
final itemCount = items.length + (_hasMoreItems && isLoading ? 1 : 0);
|
||||
|
||||
if (settingsProvider.viewMode == ViewMode.list) {
|
||||
// In list view, only the first item can navigate up to chips
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(8),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) =>
|
||||
_buildMediaCardItem(index, isFirstRow: index == 0),
|
||||
);
|
||||
} else {
|
||||
// In grid view, calculate columns and pass to item builder
|
||||
final columnCount = _getGridColumnCount(context, settingsProvider);
|
||||
return GridView.builder(
|
||||
padding: const EdgeInsets.all(8),
|
||||
gridDelegate: MediaGridDelegate.createDelegate(
|
||||
context: context,
|
||||
density: settingsProvider.libraryDensity,
|
||||
),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(
|
||||
index,
|
||||
isFirstRow: _isFirstRow(index, columnCount),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildMediaCardItem(int index, {required bool isFirstRow}) {
|
||||
if (index >= items.length) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
final item = items[index];
|
||||
return FocusableMediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
focusNode: index == 0 ? firstItemFocusNode : null,
|
||||
onRefresh: updateItem,
|
||||
onNavigateUp: isFirstRow ? _navigateToChips : null,
|
||||
onBack: widget.onBack,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../models/plex_metadata.dart';
|
||||
import '../../utils/library_refresh_notifier.dart';
|
||||
import '../../utils/server_tagging_extensions.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../../widgets/adaptive_media_grid.dart';
|
||||
import '../../../models/plex_metadata.dart';
|
||||
import '../../../utils/library_refresh_notifier.dart';
|
||||
import '../../../widgets/focusable_media_card.dart';
|
||||
import '../../../i18n/strings.g.dart';
|
||||
import 'base_library_tab.dart';
|
||||
import 'library_grid_tab_state.dart';
|
||||
|
||||
/// Collections tab for library screen
|
||||
/// Shows collections for the current library
|
||||
@@ -14,6 +14,10 @@ class LibraryCollectionsTab extends BaseLibraryTab<PlexMetadata> {
|
||||
required super.library,
|
||||
super.viewMode,
|
||||
super.density,
|
||||
super.onDataLoaded,
|
||||
super.isActive,
|
||||
super.suppressAutoFocus,
|
||||
super.onBack,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -21,7 +25,10 @@ class LibraryCollectionsTab extends BaseLibraryTab<PlexMetadata> {
|
||||
}
|
||||
|
||||
class _LibraryCollectionsTabState
|
||||
extends BaseLibraryTabState<PlexMetadata, LibraryCollectionsTab> {
|
||||
extends LibraryGridTabState<PlexMetadata, LibraryCollectionsTab> {
|
||||
@override
|
||||
String get focusNodeDebugLabel => 'collections_first_item';
|
||||
|
||||
@override
|
||||
IconData get emptyIcon => Icons.collections;
|
||||
|
||||
@@ -40,14 +47,19 @@ class _LibraryCollectionsTabState
|
||||
// Use server-specific client for this library
|
||||
final client = getClientForLibrary();
|
||||
|
||||
final collections = await client.getLibraryCollections(widget.library.key);
|
||||
|
||||
// Tag collections with server info
|
||||
return collections.tagWithLibrary(widget.library);
|
||||
// Collections are automatically tagged with server info by PlexClient
|
||||
return await client.getLibraryCollections(widget.library.key);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget buildContent(List<PlexMetadata> items) {
|
||||
return AdaptiveMediaGrid(items: items, onRefresh: loadItems);
|
||||
@override
|
||||
Widget buildGridItem(BuildContext context, PlexMetadata item, int index) {
|
||||
return FocusableMediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
focusNode: index == 0 ? firstItemFocusNode : null,
|
||||
onListRefresh: loadItems,
|
||||
onBack: widget.onBack,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../adaptive_media_grid.dart';
|
||||
import '../../../mixins/library_tab_focus_mixin.dart';
|
||||
import 'base_library_tab.dart';
|
||||
|
||||
/// Shared state implementation for simple grid-based library tabs.
|
||||
///
|
||||
/// Handles focus, item counting, and grid wiring so individual tabs only
|
||||
/// implement data loading and per-item rendering.
|
||||
abstract class LibraryGridTabState<T, W extends BaseLibraryTab<T>>
|
||||
extends BaseLibraryTabState<T, W>
|
||||
with LibraryTabFocusMixin {
|
||||
/// Build a single grid item.
|
||||
Widget buildGridItem(BuildContext context, T item, int index);
|
||||
|
||||
@override
|
||||
int get itemCount => items.length;
|
||||
|
||||
@override
|
||||
Widget buildContent(List<T> items) {
|
||||
return AdaptiveMediaGrid<T>(
|
||||
items: items,
|
||||
itemBuilder: (context, item, index) =>
|
||||
buildGridItem(context, item, index),
|
||||
onRefresh: loadItems,
|
||||
firstItemFocusNode: firstItemFocusNode,
|
||||
onBack: widget.onBack,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../models/plex_playlist.dart';
|
||||
import '../../../utils/library_refresh_notifier.dart';
|
||||
import '../../../widgets/focusable_media_card.dart';
|
||||
import '../../../i18n/strings.g.dart';
|
||||
import 'base_library_tab.dart';
|
||||
import 'library_grid_tab_state.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,
|
||||
super.onDataLoaded,
|
||||
super.isActive,
|
||||
super.suppressAutoFocus,
|
||||
super.onBack,
|
||||
});
|
||||
|
||||
@override
|
||||
State<LibraryPlaylistsTab> createState() => _LibraryPlaylistsTabState();
|
||||
}
|
||||
|
||||
class _LibraryPlaylistsTabState
|
||||
extends LibraryGridTabState<PlexPlaylist, LibraryPlaylistsTab> {
|
||||
@override
|
||||
String get focusNodeDebugLabel => 'playlists_first_item';
|
||||
|
||||
@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
|
||||
Widget buildGridItem(BuildContext context, PlexPlaylist playlist, int index) {
|
||||
return FocusableMediaCard(
|
||||
key: Key(playlist.ratingKey),
|
||||
item: playlist,
|
||||
focusNode: index == 0 ? firstItemFocusNode : null,
|
||||
onListRefresh: loadItems,
|
||||
onBack: widget.onBack,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
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_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,
|
||||
super.onDataLoaded,
|
||||
super.isActive,
|
||||
super.suppressAutoFocus,
|
||||
super.onBack,
|
||||
});
|
||||
|
||||
@override
|
||||
State<LibraryRecommendedTab> createState() => _LibraryRecommendedTabState();
|
||||
}
|
||||
|
||||
class _LibraryRecommendedTabState
|
||||
extends BaseLibraryTabState<PlexHub, LibraryRecommendedTab>
|
||||
with ItemUpdatable {
|
||||
/// GlobalKeys for each hub section to enable vertical navigation
|
||||
final List<GlobalKey<HubSectionState>> _hubKeys = [];
|
||||
|
||||
@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 {
|
||||
// Clear hub keys before loading new hubs to prevent stale references
|
||||
_hubKeys.clear();
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/// Ensure we have enough GlobalKeys for all hubs
|
||||
void _ensureHubKeys(int count) {
|
||||
while (_hubKeys.length < count) {
|
||||
_hubKeys.add(GlobalKey<HubSectionState>());
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle vertical navigation between hubs
|
||||
bool _handleVerticalNavigation(int hubIndex, bool isUp) {
|
||||
final targetIndex = isUp ? hubIndex - 1 : hubIndex + 1;
|
||||
|
||||
// Check if target is valid
|
||||
if (targetIndex < 0 || targetIndex >= _hubKeys.length) {
|
||||
// At boundary, block navigation
|
||||
return true;
|
||||
}
|
||||
|
||||
// Navigate to target hub with column memory
|
||||
final targetState = _hubKeys[targetIndex].currentState;
|
||||
if (targetState != null) {
|
||||
targetState.requestFocusFromMemory();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Focus the first item in the first hub (for tab activation)
|
||||
@override
|
||||
void focusFirstItem() {
|
||||
if (_hubKeys.isNotEmpty && items.isNotEmpty) {
|
||||
_hubKeys[0].currentState?.requestFocusAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget buildContent(List<PlexHub> items) {
|
||||
_ensureHubKeys(items.length);
|
||||
|
||||
return 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(
|
||||
key: index < _hubKeys.length ? _hubKeys[index] : null,
|
||||
hub: hub,
|
||||
icon: _getHubIcon(hub),
|
||||
isInContinueWatching: isContinueWatching,
|
||||
onRefresh: updateItem,
|
||||
onRemoveFromContinueWatching: isContinueWatching
|
||||
? _refreshContinueWatching
|
||||
: null,
|
||||
onVerticalNavigation: (isUp) =>
|
||||
_handleVerticalNavigation(index, isUp),
|
||||
onBack: widget.onBack,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
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 '../../utils/server_tagging_extensions.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> {
|
||||
@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();
|
||||
|
||||
// Get playlists for this library
|
||||
final playlists = await client.getLibraryPlaylists(
|
||||
sectionId: widget.library.key,
|
||||
playlistType: 'video',
|
||||
);
|
||||
|
||||
// Tag playlists with server info
|
||||
return playlists.tagWithLibrary(widget.library);
|
||||
}
|
||||
|
||||
@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) {
|
||||
final playlist = items[index];
|
||||
return MediaCard(
|
||||
key: Key(playlist.ratingKey),
|
||||
item: playlist,
|
||||
onListRefresh: loadItems,
|
||||
);
|
||||
},
|
||||
);
|
||||
} 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: loadItems,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../models/plex_hub.dart';
|
||||
import '../../widgets/hub_section.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import 'base_library_tab.dart';
|
||||
|
||||
/// Recommended tab for library screen
|
||||
/// Shows library-specific hubs and recommendations
|
||||
class LibraryRecommendedTab extends BaseLibraryTab<PlexHub> {
|
||||
const LibraryRecommendedTab({super.key, required super.library});
|
||||
|
||||
@override
|
||||
State<LibraryRecommendedTab> createState() => _LibraryRecommendedTabState();
|
||||
}
|
||||
|
||||
class _LibraryRecommendedTabState
|
||||
extends BaseLibraryTabState<PlexHub, LibraryRecommendedTab> {
|
||||
@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();
|
||||
|
||||
// Hubs are now tagged with server info at the source
|
||||
return await client.getLibraryHubs(widget.library.key, limit: 12);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget buildContent(List<PlexHub> items) {
|
||||
return 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));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
|
||||
class MergedLicenseEntry {
|
||||
final String packageName;
|
||||
final List<LicenseEntry> licenseEntries;
|
||||
final Set<String> allPackageNames;
|
||||
|
||||
MergedLicenseEntry({
|
||||
required this.packageName,
|
||||
required this.licenseEntries,
|
||||
required this.allPackageNames,
|
||||
});
|
||||
}
|
||||
|
||||
class LicensesScreen extends StatefulWidget {
|
||||
const LicensesScreen({super.key});
|
||||
|
||||
@override
|
||||
State<LicensesScreen> createState() => _LicensesScreenState();
|
||||
}
|
||||
|
||||
class _LicensesScreenState extends State<LicensesScreen> {
|
||||
List<MergedLicenseEntry> _mergedLicenses = [];
|
||||
bool _isLoading = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadLicenses();
|
||||
}
|
||||
|
||||
Future<void> _loadLicenses() async {
|
||||
final licenseMap = <String, List<LicenseEntry>>{};
|
||||
final allPackageNames = <String, Set<String>>{};
|
||||
|
||||
await for (final license in LicenseRegistry.licenses) {
|
||||
for (final packageName in license.packages) {
|
||||
if (!licenseMap.containsKey(packageName)) {
|
||||
licenseMap[packageName] = [];
|
||||
allPackageNames[packageName] = <String>{};
|
||||
}
|
||||
licenseMap[packageName]!.add(license);
|
||||
allPackageNames[packageName]!.addAll(license.packages);
|
||||
}
|
||||
}
|
||||
|
||||
final mergedLicenses = licenseMap.entries.map((entry) {
|
||||
return MergedLicenseEntry(
|
||||
packageName: entry.key,
|
||||
licenseEntries: entry.value,
|
||||
allPackageNames: allPackageNames[entry.key]!,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
mergedLicenses.sort((a, b) => a.packageName.compareTo(b.packageName));
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_mergedLicenses = mergedLicenses;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_isLoading) {
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(title: Text(t.screens.licenses), pinned: true),
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
final mergedLicense = _mergedLicenses[index];
|
||||
final packageName = mergedLicense.packageName;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
child: ListTile(
|
||||
title: Text(
|
||||
packageName,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
subtitle: mergedLicense.licenseEntries.length > 1
|
||||
? Text(
|
||||
t.licenses.licensesCount(
|
||||
count: mergedLicense.licenseEntries.length,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => _showLicenseDetail(mergedLicense),
|
||||
),
|
||||
);
|
||||
}, childCount: _mergedLicenses.length),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showLicenseDetail(MergedLicenseEntry mergedLicense) {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) =>
|
||||
_LicenseDetailScreen(mergedLicense: mergedLicense),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LicenseDetailScreen extends StatelessWidget {
|
||||
final MergedLicenseEntry mergedLicense;
|
||||
|
||||
const _LicenseDetailScreen({required this.mergedLicense});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final packageName = mergedLicense.packageName;
|
||||
final licenseEntries = mergedLicense.licenseEntries;
|
||||
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(title: Text(packageName), pinned: true),
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate([
|
||||
// Package info card
|
||||
if (mergedLicense.allPackageNames.length > 1)
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
t.licenses.relatedPackages,
|
||||
style: Theme.of(context).textTheme.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
mergedLicense.allPackageNames.join(', '),
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (mergedLicense.allPackageNames.length > 1)
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// License cards
|
||||
...licenseEntries.asMap().entries.map((entry) {
|
||||
final index = entry.key;
|
||||
final license = entry.value;
|
||||
final isMultipleLicenses = licenseEntries.length > 1;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
isMultipleLicenses
|
||||
? t.licenses.licenseNumber(
|
||||
number: index + 1,
|
||||
)
|
||||
: t.licenses.license,
|
||||
style: Theme.of(context).textTheme.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
...license.paragraphs.map((paragraph) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: SelectableText(
|
||||
paragraph.text,
|
||||
style: TextStyle(
|
||||
fontFamily: paragraph.indent > 0
|
||||
? 'monospace'
|
||||
: null,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (index < licenseEntries.length - 1)
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
);
|
||||
}),
|
||||
]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,49 @@
|
||||
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/provider_extensions.dart';
|
||||
import '../utils/platform_detector.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 '../utils/desktop_window_padding.dart';
|
||||
import '../widgets/side_navigation_rail.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';
|
||||
|
||||
/// Provides access to the main screen's focus control.
|
||||
class MainScreenFocusScope extends InheritedWidget {
|
||||
final VoidCallback focusSidebar;
|
||||
final VoidCallback focusContent;
|
||||
final bool isSidebarFocused;
|
||||
|
||||
const MainScreenFocusScope({
|
||||
super.key,
|
||||
required this.focusSidebar,
|
||||
required this.focusContent,
|
||||
required this.isSidebarFocused,
|
||||
required super.child,
|
||||
});
|
||||
|
||||
static MainScreenFocusScope? of(BuildContext context) {
|
||||
return context.dependOnInheritedWidgetOfExactType<MainScreenFocusScope>();
|
||||
}
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(MainScreenFocusScope oldWidget) {
|
||||
return isSidebarFocused != oldWidget.isSidebarFocused;
|
||||
}
|
||||
}
|
||||
|
||||
class MainScreen extends StatefulWidget {
|
||||
final PlexClient client;
|
||||
@@ -21,12 +56,23 @@ class MainScreen extends StatefulWidget {
|
||||
|
||||
class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
int _currentIndex = 0;
|
||||
String? _selectedLibraryGlobalKey;
|
||||
|
||||
late final List<Widget> _screens;
|
||||
final GlobalKey<State<DiscoverScreen>> _discoverKey = GlobalKey();
|
||||
final GlobalKey<State<LibrariesScreen>> _librariesKey = GlobalKey();
|
||||
final GlobalKey<State<SearchScreen>> _searchKey = GlobalKey();
|
||||
final GlobalKey<State<SettingsScreen>> _settingsKey = GlobalKey();
|
||||
final GlobalKey<SideNavigationRailState> _sideNavKey = GlobalKey();
|
||||
|
||||
// Focus management for sidebar/content switching
|
||||
final FocusScopeNode _sidebarFocusScope = FocusScopeNode(
|
||||
debugLabel: 'Sidebar',
|
||||
);
|
||||
final FocusScopeNode _contentFocusScope = FocusScopeNode(
|
||||
debugLabel: 'Content',
|
||||
);
|
||||
bool _isSidebarFocused = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -37,7 +83,10 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
key: _discoverKey,
|
||||
onBecameVisible: _onDiscoverBecameVisible,
|
||||
),
|
||||
LibrariesScreen(key: _librariesKey),
|
||||
LibrariesScreen(
|
||||
key: _librariesKey,
|
||||
onLibraryOrderChanged: _onLibraryOrderChanged,
|
||||
),
|
||||
SearchScreen(key: _searchKey),
|
||||
SettingsScreen(key: _settingsKey),
|
||||
];
|
||||
@@ -50,6 +99,11 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
|
||||
// Set up data invalidation callback for profile switching
|
||||
userProfileProvider.setDataInvalidationCallback(_invalidateAllScreens);
|
||||
|
||||
// Focus content initially (replaces autofocus which caused focus stealing issues)
|
||||
if (!_isSidebarFocused) {
|
||||
_contentFocusScope.requestFocus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -62,9 +116,56 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
@override
|
||||
void dispose() {
|
||||
routeObserver.unsubscribe(this);
|
||||
_sidebarFocusScope.dispose();
|
||||
_contentFocusScope.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _focusSidebar() {
|
||||
setState(() => _isSidebarFocused = true);
|
||||
_sidebarFocusScope.requestFocus();
|
||||
// Focus the active item after the focus scope has focus
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_sideNavKey.currentState?.focusActiveItem();
|
||||
});
|
||||
}
|
||||
|
||||
void _focusContent() {
|
||||
setState(() => _isSidebarFocused = false);
|
||||
_contentFocusScope.requestFocus();
|
||||
// When content regains focus while on Libraries, retry focusing the active tab
|
||||
if (_currentIndex == 1) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final librariesState = _librariesKey.currentState;
|
||||
if (librariesState != null) {
|
||||
(librariesState as dynamic).focusActiveTabIfReady();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
KeyEventResult _handleBackKey(KeyEvent event) {
|
||||
if (event is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
|
||||
// Handle all back keys - this handler is only reached if lower widgets
|
||||
// (e.g., LibrariesScreen tab content/chips) don't handle the back key first
|
||||
final isBackKey =
|
||||
event.logicalKey == LogicalKeyboardKey.escape ||
|
||||
event.logicalKey == LogicalKeyboardKey.goBack ||
|
||||
event.logicalKey == LogicalKeyboardKey.browserBack ||
|
||||
event.logicalKey == LogicalKeyboardKey.gameButtonB;
|
||||
|
||||
if (!isBackKey) return KeyEventResult.ignored;
|
||||
|
||||
// Toggle focus between sidebar and content
|
||||
if (_isSidebarFocused) {
|
||||
_focusContent();
|
||||
} else {
|
||||
_focusSidebar();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
@override
|
||||
void didPush() {
|
||||
// Called when this route has been pushed (initial navigation)
|
||||
@@ -90,9 +191,44 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
}
|
||||
}
|
||||
|
||||
void _onLibraryOrderChanged() {
|
||||
// Refresh side navigation when library order changes
|
||||
_sideNavKey.currentState?.reloadLibraries();
|
||||
}
|
||||
|
||||
/// 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,21 +249,106 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
}
|
||||
}
|
||||
|
||||
void _selectTab(int index) {
|
||||
final previousIndex = _currentIndex;
|
||||
setState(() {
|
||||
_currentIndex = index;
|
||||
});
|
||||
// Notify discover screen when it becomes visible via tab switch
|
||||
if (index == 0) {
|
||||
_onDiscoverBecameVisible();
|
||||
}
|
||||
// Ensure the libraries screen applies focus when brought into view
|
||||
if (index == 1 && previousIndex != 1) {
|
||||
final librariesState = _librariesKey.currentState;
|
||||
if (librariesState != null) {
|
||||
(librariesState as dynamic).focusActiveTabIfReady();
|
||||
}
|
||||
}
|
||||
// Focus search input when selecting Search tab
|
||||
if (index == 2) {
|
||||
final searchState = _searchKey.currentState;
|
||||
if (searchState != null) {
|
||||
(searchState as dynamic).focusSearchInput();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle library selection from side navigation rail
|
||||
void _selectLibrary(String libraryGlobalKey) {
|
||||
setState(() {
|
||||
_selectedLibraryGlobalKey = libraryGlobalKey;
|
||||
_currentIndex = 1; // Switch to Libraries tab
|
||||
});
|
||||
// Tell LibrariesScreen to load this library
|
||||
final librariesState = _librariesKey.currentState;
|
||||
if (librariesState != null) {
|
||||
(librariesState as dynamic).loadLibraryByKey(libraryGlobalKey);
|
||||
(librariesState as dynamic).focusActiveTabIfReady();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final useSideNav = PlatformDetector.shouldUseSideNavigation(context);
|
||||
|
||||
if (useSideNav) {
|
||||
return PopScope(
|
||||
canPop: false, // Prevent system back from popping on Android TV
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
// No-op: back key events bubble through widget tree and are handled
|
||||
// by content screens (e.g., LibrariesScreen) or MainScreen's _handleBackKey.
|
||||
// We only use PopScope to prevent the system from popping the route.
|
||||
},
|
||||
child: Focus(
|
||||
onKeyEvent: (node, event) => _handleBackKey(event),
|
||||
child: MainScreenFocusScope(
|
||||
focusSidebar: _focusSidebar,
|
||||
focusContent: _focusContent,
|
||||
isSidebarFocused: _isSidebarFocused,
|
||||
child: SideNavigationScope(
|
||||
child: Row(
|
||||
children: [
|
||||
FocusScope(
|
||||
node: _sidebarFocusScope,
|
||||
child: SideNavigationRail(
|
||||
key: _sideNavKey,
|
||||
selectedIndex: _currentIndex,
|
||||
selectedLibraryKey: _selectedLibraryGlobalKey,
|
||||
onDestinationSelected: (index) {
|
||||
_selectTab(index);
|
||||
_focusContent();
|
||||
},
|
||||
onLibrarySelected: (key) {
|
||||
_selectLibrary(key);
|
||||
_focusContent();
|
||||
},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: FocusScope(
|
||||
node: _contentFocusScope,
|
||||
// No autofocus - we control focus programmatically to prevent
|
||||
// autofocus from stealing focus back after setState() rebuilds
|
||||
child: IndexedStack(
|
||||
index: _currentIndex,
|
||||
children: _screens,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
},
|
||||
onDestinationSelected: _selectTab,
|
||||
destinations: [
|
||||
NavigationDestination(
|
||||
icon: const Icon(Icons.home_outlined),
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../models/plex_playlist.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../providers/playback_state_provider.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/video_player_navigation.dart';
|
||||
import '../utils/grid_size_calculator.dart';
|
||||
import '../widgets/media_card.dart';
|
||||
import '../widgets/playlist_item_card.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../utils/dialogs.dart';
|
||||
import 'base_media_list_detail_screen.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../../services/play_queue_launcher.dart';
|
||||
import '../../models/plex_playlist.dart';
|
||||
import '../../models/plex_metadata.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../../utils/provider_extensions.dart';
|
||||
import '../../widgets/media_grid_sliver.dart';
|
||||
import 'playlist_item_card.dart';
|
||||
import '../../widgets/focused_scroll_scaffold.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../../utils/dialogs.dart';
|
||||
import '../base_media_list_detail_screen.dart';
|
||||
|
||||
/// Screen to display the contents of a playlist
|
||||
class PlaylistDetailScreen extends StatefulWidget {
|
||||
@@ -53,7 +49,7 @@ class _PlaylistDetailScreenState
|
||||
|
||||
/// Get the correct PlexClient for this playlist's server
|
||||
PlexClient _getClientForPlaylist() {
|
||||
return context.getClientForServer(widget.playlist.serverId);
|
||||
return context.getClientForServer(widget.playlist.serverId!);
|
||||
}
|
||||
|
||||
Future<void> _deletePlaylist() async {
|
||||
@@ -207,143 +203,78 @@ class _PlaylistDetailScreenState
|
||||
Future<void> _playFromItem(int index) async {
|
||||
if (items.isEmpty || index < 0 || index >= items.length) return;
|
||||
|
||||
try {
|
||||
final client = _getClientForPlaylist();
|
||||
final plexClient = _getClientForPlaylist();
|
||||
final selectedItem = items[index];
|
||||
|
||||
final selectedItem = items[index];
|
||||
final launcher = PlayQueueLauncher(
|
||||
context: context,
|
||||
client: plexClient,
|
||||
serverId: widget.playlist.serverId,
|
||||
serverName: widget.playlist.serverName,
|
||||
);
|
||||
|
||||
// Create play queue from playlist, starting at the selected item
|
||||
final playQueue = await client.createPlayQueue(
|
||||
playlistID: int.parse(widget.playlist.ratingKey),
|
||||
type: 'video',
|
||||
key: selectedItem.key,
|
||||
);
|
||||
|
||||
if (playQueue == null ||
|
||||
playQueue.items == null ||
|
||||
playQueue.items!.isEmpty) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(t.messages.failedToCreatePlayQueue)),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// Set play queue in provider
|
||||
final playbackState = context.read<PlaybackStateProvider>();
|
||||
playbackState.setClient(client);
|
||||
await playbackState.setPlaybackFromPlayQueue(
|
||||
playQueue,
|
||||
widget.playlist.ratingKey,
|
||||
);
|
||||
|
||||
// Navigate to selected item (should be first in the queue response)
|
||||
if (mounted) {
|
||||
await navigateToVideoPlayer(context, metadata: playQueue.items!.first);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to play from item', error: e);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
t.messages.failedPlayback(
|
||||
action: t.discover.play,
|
||||
error: e.toString(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
await launcher.launchFromPlaylistItem(
|
||||
playlist: widget.playlist,
|
||||
selectedItem: selectedItem,
|
||||
showLoadingIndicator: true,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
return FocusedScrollScaffold(
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(widget.playlist.title, style: const TextStyle(fontSize: 16)),
|
||||
if (widget.playlist.smart)
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.auto_awesome, size: 12, color: Colors.blue[300]),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
widget.playlist.title,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
if (widget.playlist.smart)
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.auto_awesome,
|
||||
size: 12,
|
||||
color: Colors.blue[300],
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
t.playlists.smartPlaylist,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: Colors.blue[300],
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
t.playlists.smartPlaylist,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: Colors.blue[300],
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
pinned: true,
|
||||
actions: buildAppBarActions(
|
||||
onDelete: widget.playlist.smart ? null : _deletePlaylist,
|
||||
deleteTooltip: t.playlists.delete,
|
||||
showDelete: !widget.playlist.smart,
|
||||
),
|
||||
),
|
||||
...buildStateSlivers(),
|
||||
if (items.isNotEmpty)
|
||||
if (widget.playlist.smart)
|
||||
// Smart playlists: Use grid view (cannot be reordered)
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
sliver: SliverGrid(
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent:
|
||||
GridSizeCalculator.getMaxCrossAxisExtent(
|
||||
context,
|
||||
context.watch<SettingsProvider>().libraryDensity,
|
||||
),
|
||||
childAspectRatio: 2 / 3.3,
|
||||
crossAxisSpacing: 0,
|
||||
mainAxisSpacing: 0,
|
||||
),
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
return MediaCard(item: items[index], onRefresh: updateItem);
|
||||
}, childCount: items.length),
|
||||
),
|
||||
)
|
||||
else
|
||||
// Regular playlists: Use reorderable list view
|
||||
SliverReorderableList(
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
return PlaylistItemCard(
|
||||
key: ValueKey(item.playlistItemID ?? item.ratingKey),
|
||||
item: item,
|
||||
index: index,
|
||||
onRemove: () => _removeItem(index),
|
||||
onTap: () => _playFromItem(index),
|
||||
canReorder: !widget.playlist.smart,
|
||||
);
|
||||
},
|
||||
itemCount: items.length,
|
||||
onReorder: _onReorder,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: buildAppBarActions(
|
||||
onDelete: widget.playlist.smart ? null : _deletePlaylist,
|
||||
deleteTooltip: t.playlists.delete,
|
||||
showDelete: !widget.playlist.smart,
|
||||
),
|
||||
slivers: [
|
||||
...buildStateSlivers(),
|
||||
if (items.isNotEmpty)
|
||||
if (widget.playlist.smart)
|
||||
// Smart playlists: Use grid view (cannot be reordered)
|
||||
MediaGridSliver(items: items, onRefresh: updateItem)
|
||||
else
|
||||
// Regular playlists: Use reorderable list view
|
||||
SliverReorderableList(
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
return PlaylistItemCard(
|
||||
key: ValueKey(item.playlistItemID ?? item.ratingKey),
|
||||
item: item,
|
||||
index: index,
|
||||
onRemove: () => _removeItem(index),
|
||||
onTap: () => _playFromItem(index),
|
||||
onRefresh: updateItem,
|
||||
canReorder: !widget.playlist.smart,
|
||||
);
|
||||
},
|
||||
itemCount: items.length,
|
||||
onReorder: _onReorder,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../../models/plex_metadata.dart';
|
||||
import '../../utils/duration_formatter.dart';
|
||||
import '../../utils/provider_extensions.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../../widgets/media_context_menu.dart';
|
||||
import '../../widgets/plex_optimized_image.dart';
|
||||
|
||||
/// Custom list item widget for playlist items
|
||||
/// Shows drag handle, poster, title/metadata, duration, and remove button
|
||||
class PlaylistItemCard extends StatefulWidget {
|
||||
final PlexMetadata item;
|
||||
final int index;
|
||||
final VoidCallback onRemove;
|
||||
final VoidCallback? onTap;
|
||||
final void Function(String ratingKey)? onRefresh;
|
||||
final bool canReorder; // Whether drag handle should be shown
|
||||
|
||||
const PlaylistItemCard({
|
||||
super.key,
|
||||
required this.item,
|
||||
required this.index,
|
||||
required this.onRemove,
|
||||
this.onTap,
|
||||
this.onRefresh,
|
||||
this.canReorder = true,
|
||||
});
|
||||
|
||||
@override
|
||||
State<PlaylistItemCard> createState() => _PlaylistItemCardState();
|
||||
}
|
||||
|
||||
class _PlaylistItemCardState extends State<PlaylistItemCard> {
|
||||
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final item = widget.item;
|
||||
return MediaContextMenu(
|
||||
key: _contextMenuKey,
|
||||
item: item,
|
||||
onRefresh: widget.onRefresh,
|
||||
onTap: widget.onTap,
|
||||
child: Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
child: InkWell(
|
||||
onTap: widget.onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Row(
|
||||
children: [
|
||||
// Drag handle (if reorderable)
|
||||
if (widget.canReorder)
|
||||
ReorderableDragStartListener(
|
||||
index: widget.index,
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.only(right: 12),
|
||||
child: Icon(Icons.drag_indicator, color: Colors.grey),
|
||||
),
|
||||
),
|
||||
|
||||
// Poster thumbnail
|
||||
_buildPosterImage(context),
|
||||
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Title and metadata
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Title
|
||||
Text(
|
||||
item.displayTitle,
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
|
||||
const SizedBox(height: 4),
|
||||
|
||||
// Subtitle (episode info or type)
|
||||
Text(
|
||||
_buildSubtitle(),
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey[400]),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
|
||||
// Progress indicator if partially watched
|
||||
if (item.viewOffset != null && item.duration != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: LinearProgressIndicator(
|
||||
value: item.viewOffset! / item.duration!,
|
||||
backgroundColor: Colors.grey[800],
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
minHeight: 3,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Duration
|
||||
if (item.duration != null)
|
||||
Text(
|
||||
formatDurationTextual(item.duration!),
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey[400]),
|
||||
),
|
||||
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// Remove button
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close, size: 20),
|
||||
onPressed: widget.onRemove,
|
||||
tooltip: t.playlists.removeItem,
|
||||
color: Colors.grey[400],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Get the correct PlexClient for this item's server
|
||||
PlexClient _getClientForItem(BuildContext context) {
|
||||
return context.getClientForServer(widget.item.serverId!);
|
||||
}
|
||||
|
||||
Widget _buildPosterImage(BuildContext context) {
|
||||
final posterUrl = widget.item.posterThumb();
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: PlexOptimizedImage.poster(
|
||||
client: _getClientForItem(context),
|
||||
imagePath: posterUrl,
|
||||
width: 60,
|
||||
height: 90,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => _buildPlaceholder(),
|
||||
errorWidget: (context, url, error) => _buildPlaceholder(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPlaceholder() {
|
||||
return Container(
|
||||
width: 60,
|
||||
height: 90,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[850],
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: const Icon(Icons.movie, color: Colors.grey, size: 24),
|
||||
);
|
||||
}
|
||||
|
||||
String _buildSubtitle() {
|
||||
final item = widget.item;
|
||||
final itemType = item.type.toLowerCase();
|
||||
|
||||
if (itemType == 'episode') {
|
||||
// For episodes, show "S#E# - Episode Title"
|
||||
final season = item.parentIndex;
|
||||
final episode = item.index;
|
||||
if (season != null && episode != null) {
|
||||
return 'S${season}E$episode${item.displaySubtitle != null ? ' - ${item.displaySubtitle}' : ''}';
|
||||
}
|
||||
return item.displaySubtitle ?? t.discover.tvShow;
|
||||
} else if (itemType == 'movie') {
|
||||
// For movies, show year
|
||||
return item.year?.toString() ?? t.discover.movie;
|
||||
}
|
||||
|
||||
// Default to type
|
||||
return item.type;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
|
||||
/// Dialog for entering a PIN to access a protected profile
|
||||
class PinEntryDialog extends StatefulWidget {
|
||||
@@ -1,6 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../models/plex_home_user.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../../models/plex_home_user.dart';
|
||||
import 'user_avatar_widget.dart';
|
||||
|
||||
enum UserAttribute { admin, restricted, protected }
|
||||