Compare commits

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

android_adaptive_icon_fix

android_adaptive_icon_fix

android_adaptive_icon_fix
2025-11-27 23:23:34 +01:00
edde746andGitHub 26fc38a5ba Merge pull request #133 from Doezer/bug/fix-subtitle-saving
fix:  save stream selection per media for audio and subtitles
2025-11-27 05:20:37 +01:00
Doezer 5cbec2398a fix: return explicit boolean value in stream selection logic 2025-11-26 22:39:25 +01:00
Doezer e69644a98e fix: fix missing update in playback init & translate french comments 2025-11-26 22:39:25 +01:00
Doezer c21c5396cd fix: save stream selection per media for audio and subtitles (not just language pref) 2025-11-26 22:39:25 +01:00
edde746 01bb1126ef feat: keyboard navigation 2025-11-26 13:51:25 +01:00
edde746 0d0388f7a8 fix: change android subtitle font
close #131
2025-11-25 22:44:59 +01:00
edde746 6ae64e6057 fix: don't sign in with no servers 2025-11-25 09:43:54 +01:00
edde746 44dcdccb2c refactor: simplify rate limits 2025-11-25 05:04:35 +01:00
181 changed files with 15064 additions and 4598 deletions
+1
View File
@@ -0,0 +1 @@
github: edde746
+4 -10
View File
@@ -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
+4 -38
View File
@@ -17,8 +17,6 @@ Plezy is a modern Plex media client that provides a seamless streaming experienc
<a href='https://apps.apple.com/us/app/id6754315964'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
> Google Play version is in closed testing ([required by Google](https://support.google.com/googleplay/android-developer/answer/14151465#overview)). Join the [Google Group](https://groups.google.com/g/plezy-testers-2) to get access.
### Desktop
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.zip)
@@ -41,6 +39,7 @@ Plezy is a modern Plex media client that provides a seamless streaming experienc
### 🎬 Video Playback
- Wide codec support including HEVC, AV1, VP9, and more
- HDR and Dolby Vision support (iOS, macOS & Windows)
- Advanced subtitle rendering with full ASS/SSA support
- Audio and subtitle track selection with user profile preferences
- Playback progress sync and resume functionality
@@ -77,25 +76,6 @@ flutter run
## Development
### Code Quality
Before submitting changes, ensure your code passes all quality checks:
```bash
# Format code (including generated files)
dart format .
# Analyze code for issues
flutter analyze
# Run tests (if available)
flutter test
```
**Note**: CI checks exclude generated files (`.g.dart`, `.freezed.dart`) from formatting and analysis checks. You can run `dart format .` locally to format everything, but only your hand-written code will be validated in CI.
These checks are automatically run in CI for all pull requests.
### Code Generation
The project uses code generation for JSON serialization. After modifying model classes, run:
@@ -104,24 +84,10 @@ The project uses code generation for JSON serialization. After modifying model c
dart run build_runner build --delete-conflicting-outputs
```
## Building for Production
### Android
```bash
flutter build apk --release
# or
flutter build appbundle --release
```
### Desktop
```bash
flutter build macos --release
flutter build windows --release
flutter build linux --release
```
## Acknowledgments
- Built with [Flutter](https://flutter.dev)
- Media playback powered by [MediaKit](https://github.com/media-kit/media-kit)
- Designed for [Plex Media Server](https://www.plex.tv)
- Playback powered by [mpv](https://mpv.io)
- [MPVKit](https://github.com/mpvkit/MPVKit)
- [mpv-android](https://github.com/mpv-android/mpv-android)
+5 -1
View File
@@ -26,7 +26,7 @@ android {
applicationId = "com.edde746.plezy"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
minSdk = 26 // Required by libmpv-android
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
@@ -62,3 +62,7 @@ android {
flutter {
source = "../.."
}
dependencies {
implementation("dev.jdtech.mpv:libmpv:0.5.1")
}
@@ -0,0 +1,300 @@
package com.edde746.plezy.mpv
import android.app.Activity
import android.graphics.Color
import android.graphics.PixelFormat
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.TextureView
import dev.jdtech.mpv.MPVLib
interface MpvPlayerDelegate {
fun onPropertyChange(name: String, value: Any?)
fun onEvent(name: String, data: Map<String, Any>?)
}
class MpvPlayerCore(private val activity: Activity) :
SurfaceHolder.Callback,
MPVLib.EventObserver {
companion object {
private const val TAG = "MpvPlayerCore"
}
private var surfaceView: SurfaceView? = null
private var overlayLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? =
null
private var voInUse: String = "gpu"
var delegate: MpvPlayerDelegate? = null
var isInitialized: Boolean = false
private set
private fun ensureFlutterOverlayOnTop() {
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.post {
var flutterContainer: ViewGroup? = null
// First pass: look for FlutterView by name (debug builds)
for (i in 0 until contentView.childCount) {
val child = contentView.getChildAt(i)
if (child is ViewGroup && child.javaClass.name.contains("FlutterView")) {
flutterContainer = child
break
}
}
// Fallback for release (FlutterView may be obfuscated): pick the last ViewGroup
// that is not our mpv SurfaceView and has children.
if (flutterContainer == null) {
for (i in contentView.childCount - 1 downTo 0) {
val child = contentView.getChildAt(i)
if (child is ViewGroup && child != surfaceView?.parent && child.childCount > 0) {
flutterContainer = child
break
}
}
}
flutterContainer?.let { container ->
contentView.bringChildToFront(container)
for (j in 0 until container.childCount) {
val flutterChild = container.getChildAt(j)
if (flutterChild is SurfaceView) {
flutterChild.setZOrderOnTop(true)
flutterChild.setZOrderMediaOverlay(true)
flutterChild.holder.setFormat(PixelFormat.TRANSLUCENT)
break
} else if (flutterChild is TextureView) {
// TextureView uses alpha composition; ensure it stays above.
flutterChild.isOpaque = false
break
}
}
}
}
}
fun initialize(): Boolean {
if (isInitialized) {
Log.d(TAG, "Already initialized")
return true
}
try {
// Create SurfaceView for video rendering
surfaceView = SurfaceView(activity).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setBackgroundColor(Color.BLACK)
// Keep video composited in the normal view hierarchy (avoid hardware overlay promotion)
// so Flutter controls reliably draw above it in release builds.
alpha = 0.999f
holder.addCallback(this@MpvPlayerCore)
// Critical: Ensure SurfaceView renders BEHIND Flutter's view
setZOrderOnTop(false)
setZOrderMediaOverlay(false)
}
// Insert SurfaceView at bottom of view hierarchy (behind Flutter)
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.addView(surfaceView, 0)
// Find FlutterView and its internal FlutterSurfaceView, set it on top
for (i in 0 until contentView.childCount) {
val child = contentView.getChildAt(i)
if (child is ViewGroup && child.javaClass.name.contains("FlutterView")) {
contentView.bringChildToFront(child)
// Look inside FlutterView for FlutterSurfaceView
for (j in 0 until child.childCount) {
val flutterChild = child.getChildAt(j)
if (flutterChild is SurfaceView) {
// Put Flutter in media overlay layer (above our video which is in normal layer)
flutterChild.setZOrderOnTop(true)
flutterChild.setZOrderMediaOverlay(true)
flutterChild.holder.setFormat(PixelFormat.TRANSLUCENT)
break
}
}
break
}
}
// Repeat after layout settles to catch late-added Flutter surfaces (release builds)
ensureFlutterOverlayOnTop()
overlayLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
ensureFlutterOverlayOnTop()
}
contentView.viewTreeObserver.addOnGlobalLayoutListener(overlayLayoutListener)
Log.d(TAG, "SurfaceView added to content view")
// Initialize MPVLib
MPVLib.create(activity.applicationContext)
// Configure MPV defaults
setupMpvDefaults()
// Initialize MPV
MPVLib.init()
// Register event observer
MPVLib.addObserver(this)
isInitialized = true
Log.d(TAG, "Initialized successfully")
return true
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize: ${e.message}", e)
return false
}
}
private fun setupMpvDefaults() {
// Video output configuration
MPVLib.setOptionString("vo", "gpu")
MPVLib.setOptionString("gpu-context", "android")
// hwdec is set from Flutter via setProperty based on user preference
// Audio configuration
MPVLib.setOptionString("ao", "audiotrack")
}
// SurfaceHolder.Callback
override fun surfaceCreated(holder: SurfaceHolder) {
Log.d(TAG, "Surface created")
MPVLib.attachSurface(holder.surface)
MPVLib.setOptionString("force-window", "yes")
// Restore video output after surface is available
MPVLib.setPropertyString("vo", voInUse)
// Reassert overlay order whenever the surface is recreated
ensureFlutterOverlayOnTop()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
Log.d(TAG, "Surface changed: ${width}x${height}")
MPVLib.setPropertyString("android-surface-size", "${width}x${height}")
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
Log.d(TAG, "Surface destroyed")
// Disable video output before detaching (like mpv-android)
MPVLib.setPropertyString("vo", "null")
MPVLib.setOptionString("force-window", "no")
MPVLib.detachSurface()
}
// MPVLib.EventObserver
override fun eventProperty(property: String) {
// No value provided
}
override fun eventProperty(property: String, value: Long) {
activity.runOnUiThread {
delegate?.onPropertyChange(property, value)
}
}
override fun eventProperty(property: String, value: Double) {
activity.runOnUiThread {
delegate?.onPropertyChange(property, value)
}
}
override fun eventProperty(property: String, value: Boolean) {
activity.runOnUiThread {
delegate?.onPropertyChange(property, value)
}
}
override fun eventProperty(property: String, value: String) {
activity.runOnUiThread {
delegate?.onPropertyChange(property, value)
}
}
override fun event(eventId: Int) {
val eventName = when (eventId) {
MPVLib.MPV_EVENT_FILE_LOADED -> "file-loaded"
MPVLib.MPV_EVENT_END_FILE -> "end-file"
MPVLib.MPV_EVENT_PLAYBACK_RESTART -> "playback-restart"
else -> null
}
eventName?.let { name ->
activity.runOnUiThread {
delegate?.onEvent(name, null)
}
}
}
// Public API
fun setProperty(name: String, value: String) {
if (!isInitialized) return
MPVLib.setPropertyString(name, value)
}
fun getProperty(name: String): String? {
if (!isInitialized) return null
return try {
MPVLib.getPropertyString(name)
} catch (e: Exception) {
null
}
}
fun observeProperty(name: String, format: String) {
if (!isInitialized) return
val mpvFormat = when (format) {
"double" -> MPVLib.MPV_FORMAT_DOUBLE
"flag" -> MPVLib.MPV_FORMAT_FLAG
"string" -> MPVLib.MPV_FORMAT_STRING
"node" -> MPVLib.MPV_FORMAT_NODE
else -> MPVLib.MPV_FORMAT_NONE
}
MPVLib.observeProperty(name, mpvFormat)
}
fun command(args: Array<String>) {
if (!isInitialized || args.isEmpty()) return
MPVLib.command(args)
}
fun setVisible(visible: Boolean) {
activity.runOnUiThread {
surfaceView?.visibility = if (visible) View.VISIBLE else View.INVISIBLE
Log.d(TAG, "setVisible($visible)")
}
}
// Cleanup
fun dispose() {
Log.d(TAG, "Disposing")
MPVLib.removeObserver(this)
surfaceView?.holder?.removeCallback(this)
overlayLayoutListener?.let { listener ->
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
surfaceView?.let { contentView.removeView(it) }
surfaceView = null
MPVLib.destroy()
isInitialized = false
Log.d(TAG, "Disposed")
}
}
@@ -0,0 +1,225 @@
package com.edde746.plezy.mpv
import android.app.Activity
import android.util.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
EventChannel.StreamHandler, ActivityAware, MpvPlayerDelegate {
companion object {
private const val TAG = "MpvPlayerPlugin"
private const val METHOD_CHANNEL = "com.plezy/mpv_player"
private const val EVENT_CHANNEL = "com.plezy/mpv_player/events"
}
private lateinit var methodChannel: MethodChannel
private lateinit var eventChannel: EventChannel
private var eventSink: EventChannel.EventSink? = null
private var playerCore: MpvPlayerCore? = null
private var activity: Activity? = null
private var activityBinding: ActivityPluginBinding? = null
// FlutterPlugin
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
methodChannel.setMethodCallHandler(this)
eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
eventChannel.setStreamHandler(this)
Log.d(TAG, "Attached to engine")
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
Log.d(TAG, "Detached from engine")
}
// ActivityAware
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
Log.d(TAG, "Attached to activity")
}
override fun onDetachedFromActivity() {
playerCore?.dispose()
playerCore = null
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity")
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
Log.d(TAG, "Reattached to activity for config changes")
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity for config changes")
}
// EventChannel.StreamHandler
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events
Log.d(TAG, "Event stream connected")
}
override fun onCancel(arguments: Any?) {
eventSink = null
Log.d(TAG, "Event stream disconnected")
}
// MethodChannel.MethodCallHandler
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> handleInitialize(result)
"dispose" -> handleDispose(result)
"setProperty" -> handleSetProperty(call, result)
"getProperty" -> handleGetProperty(call, result)
"observeProperty" -> handleObserveProperty(call, result)
"command" -> handleCommand(call, result)
"setVisible" -> handleSetVisible(call, result)
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
else -> result.notImplemented()
}
}
private fun handleInitialize(result: MethodChannel.Result) {
val currentActivity = activity
if (currentActivity == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
return
}
if (playerCore?.isInitialized == true) {
Log.d(TAG, "Already initialized")
result.success(true)
return
}
currentActivity.runOnUiThread {
try {
playerCore = MpvPlayerCore(currentActivity).apply {
delegate = this@MpvPlayerPlugin
}
val success = playerCore?.initialize() ?: false
// Start hidden
playerCore?.setVisible(false)
Log.d(TAG, "Initialized: $success")
result.success(success)
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize: ${e.message}", e)
result.error("INIT_FAILED", e.message, null)
}
}
}
private fun handleDispose(result: MethodChannel.Result) {
activity?.runOnUiThread {
playerCore?.dispose()
playerCore = null
Log.d(TAG, "Disposed")
result.success(null)
} ?: result.success(null)
}
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val value = call.argument<String>("value")
if (name == null || value == null) {
result.error("INVALID_ARGS", "Missing 'name' or 'value'", null)
return
}
playerCore?.setProperty(name, value)
result.success(null)
}
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
if (name == null) {
result.error("INVALID_ARGS", "Missing 'name'", null)
return
}
val value = playerCore?.getProperty(name)
result.success(value)
}
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val format = call.argument<String>("format")
if (name == null || format == null) {
result.error("INVALID_ARGS", "Missing 'name' or 'format'", null)
return
}
playerCore?.observeProperty(name, format)
result.success(null)
}
private fun handleCommand(call: MethodCall, result: MethodChannel.Result) {
val args = call.argument<List<String>>("args")
if (args == null) {
result.error("INVALID_ARGS", "Missing 'args'", null)
return
}
playerCore?.command(args.toTypedArray())
result.success(null)
}
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
val visible = call.argument<Boolean>("visible")
if (visible == null) {
result.error("INVALID_ARGS", "Missing 'visible'", null)
return
}
playerCore?.setVisible(visible)
result.success(null)
}
// MpvPlayerDelegate
override fun onPropertyChange(name: String, value: Any?) {
eventSink?.success(
mapOf(
"type" to "property",
"name" to name,
"value" to value
)
)
}
override fun onEvent(name: String, data: Map<String, Any>?) {
val event = mutableMapOf<String, Any>(
"type" to "event",
"name" to name
)
data?.let { event["data"] = it }
eventSink?.success(event)
}
}
@@ -1,5 +1,12 @@
package com.edde746.plezy
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import com.edde746.plezy.mpv.MpvPlayerPlugin
class MainActivity : FlutterActivity()
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine.plugins.add(MpvPlayerPlugin())
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.
Binary file not shown.
-24
View File
@@ -2,10 +2,6 @@ PODS:
- connectivity_plus (0.0.1):
- Flutter
- Flutter (1.0.0)
- media_kit_libs_ios_video (1.0.4):
- Flutter
- media_kit_video (0.0.1):
- Flutter
- os_media_controls (0.0.1):
- Flutter
- package_info_plus (0.4.5):
@@ -21,34 +17,22 @@ PODS:
- FlutterMacOS
- url_launcher_ios (0.0.1):
- Flutter
- volume_controller (0.0.1):
- Flutter
- wakelock_plus (0.0.1):
- Flutter
DEPENDENCIES:
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
- Flutter (from `Flutter`)
- media_kit_libs_ios_video (from `.symlinks/plugins/media_kit_libs_ios_video/ios`)
- media_kit_video (from `.symlinks/plugins/media_kit_video/ios`)
- os_media_controls (from `.symlinks/plugins/os_media_controls/ios`)
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
- sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`)
- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)
- volume_controller (from `.symlinks/plugins/volume_controller/ios`)
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
EXTERNAL SOURCES:
connectivity_plus:
:path: ".symlinks/plugins/connectivity_plus/ios"
Flutter:
:path: Flutter
media_kit_libs_ios_video:
:path: ".symlinks/plugins/media_kit_libs_ios_video/ios"
media_kit_video:
:path: ".symlinks/plugins/media_kit_video/ios"
os_media_controls:
:path: ".symlinks/plugins/os_media_controls/ios"
package_info_plus:
@@ -61,24 +45,16 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/sqflite_darwin/darwin"
url_launcher_ios:
:path: ".symlinks/plugins/url_launcher_ios/ios"
volume_controller:
:path: ".symlinks/plugins/volume_controller/ios"
wakelock_plus:
:path: ".symlinks/plugins/wakelock_plus/ios"
SPEC CHECKSUMS:
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854
media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
volume_controller: 3657a1f65bedb98fa41ff7dc5793537919f31b12
wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
PODFILE CHECKSUM: 3c63482e143d1b91d2d2560aee9fb04ecc74ac7e
+40
View File
@@ -12,6 +12,9 @@
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
50DEEA8E23D1B433DE5341D6 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C12D873DE8572579684A82C /* Pods_Runner.framework */; };
6A48DFB02EA70C7100C1F7CD /* plezy.icon in Resources */ = {isa = PBXBuildFile; fileRef = 6A48DFAF2EA70C7100C1F7CD /* plezy.icon */; };
6A8A46212EDB320D0057B88C /* MPVKit-GPL in Frameworks */ = {isa = PBXBuildFile; productRef = 6A8A46202EDB320D0057B88C /* MPVKit-GPL */; };
6A8A46252EDB370C0057B88C /* MpvPlayerPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */; };
6A8A46262EDB370C0057B88C /* MpvPlayerCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
@@ -52,6 +55,8 @@
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
5B81FA7048BFA976F49D555E /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = "<group>"; };
6A48DFAF2EA70C7100C1F7CD /* plezy.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = plezy.icon; sourceTree = "<group>"; };
6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MpvPlayerCore.swift; sourceTree = "<group>"; };
6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MpvPlayerPlugin.swift; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
@@ -81,6 +86,7 @@
buildActionMask = 2147483647;
files = (
50DEEA8E23D1B433DE5341D6 /* Pods_Runner.framework in Frameworks */,
6A8A46212EDB320D0057B88C /* MPVKit-GPL in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -104,6 +110,15 @@
name = Frameworks;
sourceTree = "<group>";
};
6A8A46242EDB370C0057B88C /* MpvPlayer */ = {
isa = PBXGroup;
children = (
6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */,
6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */,
);
path = MpvPlayer;
sourceTree = "<group>";
};
875C8AEFBBA3759A1849D674 /* Pods */ = {
isa = PBXGroup;
children = (
@@ -153,6 +168,7 @@
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
6A8A46242EDB370C0057B88C /* MpvPlayer */,
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
97C147021CF9000F007C117D /* Info.plist */,
@@ -237,6 +253,9 @@
Base,
);
mainGroup = 97C146E51CF9000F007C117D;
packageReferences = (
6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */,
);
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
projectDirPath = "";
projectRoot = "";
@@ -376,6 +395,8 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
6A8A46252EDB370C0057B88C /* MpvPlayerPlugin.swift in Sources */,
6A8A46262EDB370C0057B88C /* MpvPlayerCore.swift in Sources */,
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
);
@@ -734,6 +755,25 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/edde746/MPVKit";
requirement = {
kind = revision;
revision = 0d0931fbbb25a3483a7edb46babd3f2f55abeefc;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
6A8A46202EDB320D0057B88C /* MPVKit-GPL */ = {
isa = XCSwiftPackageProductDependency;
package = 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */;
productName = "MPVKit-GPL";
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;
}
@@ -0,0 +1,14 @@
{
"originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee",
"pins" : [
{
"identity" : "mpvkit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "0d0931fbbb25a3483a7edb46babd3f2f55abeefc"
}
}
],
"version" : 3
}
@@ -0,0 +1,14 @@
{
"originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee",
"pins" : [
{
"identity" : "mpvkit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "0d0931fbbb25a3483a7edb46babd3f2f55abeefc"
}
}
],
"version" : 3
}
+5
View File
@@ -10,6 +10,11 @@ import AVFoundation
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
// Register MPV player plugin
if let registrar = self.registrar(forPlugin: "MpvPlayerPlugin") {
MpvPlayerPlugin.register(with: registrar)
}
// Configure audio session for media playback
do {
let session = AVAudioSession.sharedInstance()
+501
View File
@@ -0,0 +1,501 @@
import Libmpv
import UIKit
/// Protocol for receiving player events
protocol MpvPlayerDelegate: AnyObject {
func onPropertyChange(name: String, value: Any?)
func onEvent(name: String, data: [String: Any]?)
}
// Workaround for MoltenVK problems that cause flicker
// https://github.com/mpv-player/mpv/pull/13651
private class MetalLayer: CAMetalLayer {
override var drawableSize: CGSize {
get { return super.drawableSize }
set {
if Int(newValue.width) > 1 && Int(newValue.height) > 1 {
super.drawableSize = newValue
}
}
}
// Fix for target-colorspace-hint - needs main thread for EDR
@available(iOS 16.0, *)
override var wantsExtendedDynamicRangeContent: Bool {
get { return super.wantsExtendedDynamicRangeContent }
set {
if Thread.isMainThread {
super.wantsExtendedDynamicRangeContent = newValue
} else {
DispatchQueue.main.sync {
super.wantsExtendedDynamicRangeContent = newValue
}
}
}
}
}
/// Core MPV player using Metal rendering for iOS
class MpvPlayerCore: NSObject {
// MARK: - Properties
private var metalLayer: MetalLayer?
private var containerView: UIView? // Container for proper EDR activation
private var mpv: OpaquePointer?
private weak var window: UIWindow?
private lazy var queue = DispatchQueue(label: "mpv", qos: .userInitiated)
weak var delegate: MpvPlayerDelegate?
private(set) var isInitialized = false
// HDR settings
private var hdrEnabled = true // User preference for HDR
private var lastSigPeak: Double = 0.0 // Last known sig-peak for re-evaluation
// MARK: - Initialization
func initialize(in window: UIWindow) -> Bool {
guard !isInitialized else {
print("[MpvPlayerCore] Already initialized")
return true
}
self.window = window
// Create container view for proper EDR activation
// EDR requires the CAMetalLayer to be in a UIView hierarchy, not just window.layer
let container = UIView(frame: window.bounds)
container.backgroundColor = .clear
container.isUserInteractionEnabled = false
// Create Metal layer for video rendering
let layer = MetalLayer()
layer.frame = container.bounds
layer.contentsScale = UIScreen.main.nativeScale
layer.framebufferOnly = true
layer.backgroundColor = UIColor.black.cgColor
container.layer.addSublayer(layer)
containerView = container
metalLayer = layer
// Add container view to window (behind Flutter's root view controller)
window.insertSubview(container, at: 0)
print(
"[MpvPlayerCore] Metal layer added to window via container view, frame: \(layer.frame)")
// Initialize MPV with this Metal layer
guard setupMpv() else {
print("[MpvPlayerCore] Failed to setup MPV")
layer.removeFromSuperlayer()
container.removeFromSuperview()
metalLayer = nil
containerView = nil
return false
}
// Setup background/foreground notifications
setupNotifications()
isInitialized = true
print("[MpvPlayerCore] Initialized successfully with MPV")
return true
}
private func setupMpv() -> Bool {
guard let metalLayer = metalLayer else { return false }
mpv = mpv_create()
guard mpv != nil else {
print("[MpvPlayerCore] Failed to create MPV context")
return false
}
// Logging
#if DEBUG
checkError(mpv_request_log_messages(mpv, "info"))
#else
checkError(mpv_request_log_messages(mpv, "warn"))
#endif
// Set the Metal layer as the render target (must use local var for &)
var layer = metalLayer
checkError(mpv_set_option(mpv, "wid", MPV_FORMAT_INT64, &layer))
// Video output settings for Metal/Vulkan
checkError(mpv_set_option_string(mpv, "vo", "gpu-next"))
checkError(mpv_set_option_string(mpv, "gpu-api", "vulkan"))
checkError(mpv_set_option_string(mpv, "gpu-context", "moltenvk"))
checkError(mpv_set_option_string(mpv, "hwdec", "videotoolbox"))
checkError(mpv_set_option_string(mpv, "target-colorspace-hint", "yes"))
// Initialize MPV
let initResult = mpv_initialize(mpv)
if initResult < 0 {
print(
"[MpvPlayerCore] mpv_initialize failed: \(String(cString: mpv_error_string(initResult)))"
)
mpv_terminate_destroy(mpv)
mpv = nil
return false
}
// Set up wakeup callback for event handling
mpv_set_wakeup_callback(
mpv,
{ ctx in
let core = Unmanaged<MpvPlayerCore>.fromOpaque(ctx!).takeUnretainedValue()
core.readEvents()
}, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
// Observe video-params/sig-peak for HDR detection
mpv_observe_property(mpv, 0, "video-params/sig-peak", MPV_FORMAT_DOUBLE)
print("[MpvPlayerCore] MPV initialized successfully")
return true
}
// MARK: - Background/Foreground Handling
private func setupNotifications() {
NotificationCenter.default.addObserver(
self,
selector: #selector(enterBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(enterForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil
)
}
@objc private func enterBackground() {
// Disable video output to fix black screen when returning from background
print("[MpvPlayerCore] Entering background - disabling video")
if mpv != nil {
mpv_set_option_string(mpv, "vid", "no")
}
}
@objc private func enterForeground() {
// Re-enable video output
print("[MpvPlayerCore] Entering foreground - enabling video")
if mpv != nil {
mpv_set_option_string(mpv, "vid", "auto")
}
}
// MARK: - MPV Properties and Commands
func setProperty(_ name: String, value: String) {
guard mpv != nil else { return }
// Handle custom HDR toggle property
if name == "hdr-enabled" {
let enabled = value == "yes" || value == "true" || value == "1"
setHDREnabled(enabled)
return
}
mpv_set_property_string(mpv, name, value)
}
/// Enable or disable HDR mode
func setHDREnabled(_ enabled: Bool) {
hdrEnabled = enabled
print("[MpvPlayerCore] HDR enabled: \(enabled)")
// Update MPV's target-colorspace-hint
if mpv != nil {
mpv_set_property_string(mpv, "target-colorspace-hint", enabled ? "yes" : "no")
}
// Re-evaluate EDR mode with current sig-peak
DispatchQueue.main.async {
self.updateEDRMode(sigPeak: self.lastSigPeak)
}
}
func getProperty(_ name: String) -> String? {
guard mpv != nil else { return nil }
let cstr = mpv_get_property_string(mpv, name)
defer { mpv_free(cstr) }
return cstr.map { String(cString: $0) }
}
func observeProperty(_ name: String, format: String) {
guard mpv != nil else { return }
let mpvFormat: mpv_format
switch format {
case "double": mpvFormat = MPV_FORMAT_DOUBLE
case "flag": mpvFormat = MPV_FORMAT_FLAG
case "node": mpvFormat = MPV_FORMAT_NODE
case "string": mpvFormat = MPV_FORMAT_STRING
default: return
}
mpv_observe_property(mpv, 0, name, mpvFormat)
}
func command(_ args: [String]) {
guard mpv != nil, !args.isEmpty else { return }
command(args[0], args: Array(args.dropFirst()))
}
// MARK: - Visibility
func setVisible(_ visible: Bool) {
guard let container = containerView else { return }
if visible {
// Re-insert at the bottom of the window view stack
container.removeFromSuperview()
window?.insertSubview(container, at: 0)
}
container.isHidden = !visible
print("[MpvPlayerCore] setVisible(\(visible))")
}
func updateFrame(_ frame: CGRect? = nil) {
guard let metalLayer = metalLayer, let container = containerView else { return }
if let frame = frame {
container.frame = frame
metalLayer.frame = container.bounds
} else if let window = window {
container.frame = window.bounds
metalLayer.frame = container.bounds
}
// Update drawable size for proper scaling
let scale = UIScreen.main.nativeScale
metalLayer.drawableSize = CGSize(
width: metalLayer.frame.width * scale,
height: metalLayer.frame.height * scale
)
print("[MpvPlayerCore] updateFrame: \(container.frame)")
}
// MARK: - Private Helpers
private func command(_ cmd: String, args: [String] = []) {
guard mpv != nil else { return }
// Build array of C strings for mpv_command
var cargs: [UnsafeMutablePointer<CChar>?] = ([cmd] + args).map { strdup($0) }
cargs.append(nil) // null-terminate
defer {
for ptr in cargs {
free(ptr)
}
}
// mpv_command expects UnsafePointer, use withUnsafeBufferPointer for the conversion
cargs.withUnsafeBufferPointer { buffer in
var constPtrs = buffer.map { UnsafePointer($0) }
_ = mpv_command(mpv, &constPtrs)
}
}
private func readEvents() {
queue.async { [weak self] in
guard let self = self, let mpv = self.mpv else { return }
while true {
let event = mpv_wait_event(mpv, 0)
guard let eventPtr = event else { break }
if eventPtr.pointee.event_id == MPV_EVENT_NONE {
break
}
self.handleEvent(eventPtr.pointee)
}
}
}
private func handleEvent(_ event: mpv_event) {
switch event.event_id {
case MPV_EVENT_PROPERTY_CHANGE:
guard let data = event.data else { break }
let property = data.assumingMemoryBound(to: mpv_event_property.self).pointee
let name = String(cString: property.name)
handlePropertyChange(name: name, property: property)
case MPV_EVENT_FILE_LOADED:
DispatchQueue.main.async {
self.delegate?.onEvent(name: "file-loaded", data: nil)
}
case MPV_EVENT_END_FILE:
DispatchQueue.main.async {
self.delegate?.onEvent(name: "end-file", data: nil)
}
case MPV_EVENT_SHUTDOWN:
print("[MpvPlayerCore] MPV shutdown event")
case MPV_EVENT_LOG_MESSAGE:
if let msgPtr = event.data?.assumingMemoryBound(to: mpv_event_log_message.self) {
let msg = msgPtr.pointee
if let prefix = msg.prefix, let level = msg.level, let text = msg.text {
print(
"[MPV:\(String(cString: prefix))] \(String(cString: level)): \(String(cString: text))",
terminator: "")
}
}
default:
break
}
}
private func handlePropertyChange(name: String, property: mpv_event_property) {
var value: Any?
switch property.format {
case MPV_FORMAT_DOUBLE:
if let ptr = property.data {
value = ptr.assumingMemoryBound(to: Double.self).pointee
}
case MPV_FORMAT_FLAG:
if let ptr = property.data {
value = ptr.assumingMemoryBound(to: Int32.self).pointee != 0
}
case MPV_FORMAT_NODE:
if let ptr = property.data {
let node = ptr.assumingMemoryBound(to: mpv_node.self).pointee
value = convertNode(node)
}
case MPV_FORMAT_STRING:
if let ptr = property.data {
let cstr = ptr.assumingMemoryBound(to: UnsafePointer<CChar>?.self).pointee
value = cstr.map { String(cString: $0) }
}
default:
break
}
// Handle sig-peak for HDR/EDR activation
if name == "video-params/sig-peak", let sigPeak = value as? Double {
lastSigPeak = sigPeak
DispatchQueue.main.async {
self.updateEDRMode(sigPeak: sigPeak)
}
}
DispatchQueue.main.async {
self.delegate?.onPropertyChange(name: name, value: value)
}
}
// MARK: - HDR/EDR Support
private func updateEDRMode(sigPeak: Double) {
guard let layer = metalLayer else { return }
// Check if screen supports EDR (iOS 16+)
var edrHeadroom: CGFloat = 1.0
if #available(iOS 16.0, *) {
edrHeadroom = containerView?.window?.screen.potentialEDRHeadroom ?? 1.0
}
let isHDRContent = sigPeak > 1.0
let screenSupportsEDR = edrHeadroom > 1.0
let shouldEnableEDR = hdrEnabled && isHDRContent && screenSupportsEDR
if #available(iOS 16.0, *) {
layer.wantsExtendedDynamicRangeContent = shouldEnableEDR
}
print(
"[MpvPlayerCore] EDR mode: \(shouldEnableEDR) (hdrEnabled: \(hdrEnabled), sigPeak: \(sigPeak), headroom: \(edrHeadroom))"
)
}
private func convertNode(_ node: mpv_node) -> Any? {
switch node.format {
case MPV_FORMAT_STRING:
return node.u.string.map { String(cString: $0) }
case MPV_FORMAT_FLAG:
return node.u.flag != 0
case MPV_FORMAT_INT64:
return node.u.int64
case MPV_FORMAT_DOUBLE:
return node.u.double_
case MPV_FORMAT_NODE_ARRAY:
guard let list = node.u.list?.pointee else { return nil }
var array = [Any]()
for i in 0..<Int(list.num) {
if let item = convertNode(list.values[i]) {
array.append(item)
}
}
return array
case MPV_FORMAT_NODE_MAP:
guard let list = node.u.list?.pointee else { return nil }
var dict = [String: Any]()
for i in 0..<Int(list.num) {
if let key = list.keys?[i].map({ String(cString: $0) }),
let val = convertNode(list.values[i])
{
dict[key] = val
}
}
return dict
default:
return nil
}
}
private func checkError(_ status: CInt) {
if status < 0 {
print("[MpvPlayerCore] MPV error: \(String(cString: mpv_error_string(status)))")
}
}
// MARK: - Cleanup
func dispose() {
NotificationCenter.default.removeObserver(self)
let mpvHandle = mpv
mpv = nil
queue.sync {
if let handle = mpvHandle {
mpv_set_wakeup_callback(handle, nil, nil)
mpv_terminate_destroy(handle)
}
}
metalLayer?.removeFromSuperlayer()
metalLayer = nil
containerView?.removeFromSuperview()
containerView = nil
isInitialized = false
print("[MpvPlayerCore] Disposed")
}
deinit {
dispose()
}
}
+245
View File
@@ -0,0 +1,245 @@
import UIKit
import Flutter
/// Flutter plugin that bridges MPV player to Dart via method and event channels
class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPlayerDelegate {
// MARK: - Properties
private var playerCore: MpvPlayerCore?
private var eventSink: FlutterEventSink?
private weak var registrar: FlutterPluginRegistrar?
// MARK: - FlutterPlugin Registration
static func register(with registrar: FlutterPluginRegistrar) {
// Method channel for commands
let methodChannel = FlutterMethodChannel(
name: "com.plezy/mpv_player",
binaryMessenger: registrar.messenger()
)
// Event channel for state updates
let eventChannel = FlutterEventChannel(
name: "com.plezy/mpv_player/events",
binaryMessenger: registrar.messenger()
)
let instance = MpvPlayerPlugin()
instance.registrar = registrar
registrar.addMethodCallDelegate(instance, channel: methodChannel)
eventChannel.setStreamHandler(instance)
print("[MpvPlayerPlugin] Registered with Flutter")
}
// MARK: - FlutterStreamHandler
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
self.eventSink = events
print("[MpvPlayerPlugin] Event stream connected")
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
self.eventSink = nil
print("[MpvPlayerPlugin] Event stream disconnected")
return nil
}
// MARK: - FlutterPlugin Method Handler
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "initialize":
handleInitialize(result: result)
case "dispose":
handleDispose(result: result)
case "setProperty":
handleSetProperty(call: call, result: result)
case "getProperty":
handleGetProperty(call: call, result: result)
case "observeProperty":
handleObserveProperty(call: call, result: result)
case "command":
handleCommand(call: call, result: result)
case "setVisible":
handleSetVisible(call: call, result: result)
case "isInitialized":
result(playerCore?.isInitialized ?? false)
case "updateFrame":
handleUpdateFrame(result: result)
default:
result(FlutterMethodNotImplemented)
}
}
// MARK: - Method Handlers
private func handleInitialize(result: @escaping FlutterResult) {
DispatchQueue.main.async { [weak self] in
guard let self = self else {
result(FlutterError(code: "ERROR", message: "Plugin deallocated", details: nil))
return
}
// Check if already initialized
if self.playerCore?.isInitialized == true {
print("[MpvPlayerPlugin] Already initialized")
result(true)
return
}
// Find the key window
guard let window = self.findKeyWindow() else {
print("[MpvPlayerPlugin] Failed to find key window")
result(FlutterError(code: "NO_WINDOW", message: "Could not find key window", details: nil))
return
}
// Create and initialize player core
let core = MpvPlayerCore()
core.delegate = self
guard core.initialize(in: window) else {
print("[MpvPlayerPlugin] Failed to initialize MPV")
result(FlutterError(code: "MPV_INIT_FAILED", message: "Failed to initialize MPV", details: nil))
return
}
self.playerCore = core
// Start hidden
core.setVisible(false)
print("[MpvPlayerPlugin] Initialized successfully")
result(true)
}
}
private func handleDispose(result: @escaping FlutterResult) {
DispatchQueue.main.async { [weak self] in
self?.playerCore?.dispose()
self?.playerCore = nil
print("[MpvPlayerPlugin] Disposed")
result(nil)
}
}
private func handleSetProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String,
let value = args["value"] as? String else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'name' or 'value' argument", details: nil))
return
}
playerCore?.setProperty(name, value: value)
result(nil)
}
private func handleGetProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'name' argument", details: nil))
return
}
let value = playerCore?.getProperty(name)
result(value)
}
private func handleObserveProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String,
let format = args["format"] as? String else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'name' or 'format' argument", details: nil))
return
}
playerCore?.observeProperty(name, format: format)
result(nil)
}
private func handleCommand(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let commandArgs = args["args"] as? [String] else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'args' argument", details: nil))
return
}
playerCore?.command(commandArgs)
result(nil)
}
private func handleSetVisible(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let visible = args["visible"] as? Bool else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'visible' argument", details: nil))
return
}
DispatchQueue.main.async { [weak self] in
self?.playerCore?.setVisible(visible)
// Update frame when becoming visible
if visible {
self?.playerCore?.updateFrame()
}
result(nil)
}
}
private func handleUpdateFrame(result: @escaping FlutterResult) {
DispatchQueue.main.async { [weak self] in
self?.playerCore?.updateFrame()
result(nil)
}
}
// MARK: - MpvPlayerDelegate
func onPropertyChange(name: String, value: Any?) {
guard let eventSink = eventSink else { return }
var event: [String: Any] = ["type": "property", "name": name]
if let value = value {
event["value"] = value
}
eventSink(event)
}
func onEvent(name: String, data: [String: Any]?) {
guard let eventSink = eventSink else { return }
var event: [String: Any] = ["type": "event", "name": name]
if let data = data {
event["data"] = data
}
eventSink(event)
}
// MARK: - Helpers
private func findKeyWindow() -> UIWindow? {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first(where: { $0.isKeyWindow }) else {
return nil
}
return window
}
}
+184 -2
View File
@@ -4,9 +4,9 @@
/// To regenerate, run: `dart run slang`
///
/// Locales: 6
/// Strings: 2662 (443 per locale)
/// Strings: 2704 (450 per locale)
///
/// Built on 2025-11-21 at 22:35 UTC
/// Built on 2025-12-01 at 09:54 UTC
// coverage:ignore-file
// ignore_for_file: type=lint
@@ -435,6 +435,16 @@ class _StringsSettingsEn {
'Shortcut already assigned to ${action}';
String shortcutUpdated({required Object action}) =>
'Shortcut updated for ${action}';
String get autoSkip => 'Auto Skip';
String get autoSkipIntro => 'Auto Skip Intro';
String get autoSkipIntroDescription =>
'Automatically skip intro markers after a few seconds';
String get autoSkipCredits => 'Auto Skip Credits';
String get autoSkipCreditsDescription =>
'Automatically skip credits and play next episode';
String get autoSkipDelay => 'Auto Skip Delay';
String autoSkipDelayDescription({required Object seconds}) =>
'Wait ${seconds} seconds before auto-skipping';
}
// Path: search
@@ -1478,6 +1488,23 @@ class _StringsSettingsDe implements _StringsSettingsEn {
@override
String shortcutUpdated({required Object action}) =>
'Tastenkürzel aktualisiert für ${action}';
@override
String get autoSkip => 'Automatisches Überspringen';
@override
String get autoSkipIntro => 'Intro automatisch überspringen';
@override
String get autoSkipIntroDescription =>
'Intro-Marker nach wenigen Sekunden automatisch überspringen';
@override
String get autoSkipCredits => 'Abspann automatisch überspringen';
@override
String get autoSkipCreditsDescription =>
'Abspann automatisch überspringen und nächste Episode abspielen';
@override
String get autoSkipDelay => 'Verzögerung für automatisches Überspringen';
@override
String autoSkipDelayDescription({required Object seconds}) =>
'${seconds} Sekunden vor dem automatischen Überspringen warten';
}
// Path: search
@@ -2883,6 +2910,23 @@ class _StringsSettingsIt implements _StringsSettingsEn {
@override
String shortcutUpdated({required Object action}) =>
'Scorciatoia aggiornata per ${action}';
@override
String get autoSkip => 'Salto Automatico';
@override
String get autoSkipIntro => 'Salta Intro Automaticamente';
@override
String get autoSkipIntroDescription =>
'Salta automaticamente i marcatori dell\'intro dopo alcuni secondi';
@override
String get autoSkipCredits => 'Salta Crediti Automaticamente';
@override
String get autoSkipCreditsDescription =>
'Salta automaticamente i crediti e riproduci l\'episodio successivo';
@override
String get autoSkipDelay => 'Ritardo Salto Automatico';
@override
String autoSkipDelayDescription({required Object seconds}) =>
'Aspetta ${seconds} secondi prima del salto automatico';
}
// Path: search
@@ -4287,6 +4331,23 @@ class _StringsSettingsNl implements _StringsSettingsEn {
@override
String shortcutUpdated({required Object action}) =>
'Sneltoets bijgewerkt voor ${action}';
@override
String get autoSkip => 'Automatisch Overslaan';
@override
String get autoSkipIntro => 'Intro Automatisch Overslaan';
@override
String get autoSkipIntroDescription =>
'Intro-markeringen na enkele seconden automatisch overslaan';
@override
String get autoSkipCredits => 'Credits Automatisch Overslaan';
@override
String get autoSkipCreditsDescription =>
'Credits automatisch overslaan en volgende aflevering afspelen';
@override
String get autoSkipDelay => 'Vertraging Automatisch Overslaan';
@override
String autoSkipDelayDescription({required Object seconds}) =>
'${seconds} seconden wachten voor automatisch overslaan';
}
// Path: search
@@ -5680,6 +5741,23 @@ class _StringsSettingsSv implements _StringsSettingsEn {
@override
String shortcutUpdated({required Object action}) =>
'Genväg uppdaterad för ${action}';
@override
String get autoSkip => 'Auto Hoppa Över';
@override
String get autoSkipIntro => 'Hoppa Över Intro Automatiskt';
@override
String get autoSkipIntroDescription =>
'Hoppa automatiskt över intro-markörer efter några sekunder';
@override
String get autoSkipCredits => 'Hoppa Över Credits Automatiskt';
@override
String get autoSkipCreditsDescription =>
'Hoppa automatiskt över credits och spela nästa avsnitt';
@override
String get autoSkipDelay => 'Fördröjning Auto Hoppa Över';
@override
String autoSkipDelayDescription({required Object seconds}) =>
'Vänta ${seconds} sekunder innan automatisk överhoppning';
}
// Path: search
@@ -7062,6 +7140,21 @@ class _StringsSettingsZh implements _StringsSettingsEn {
'快捷键已被分配给 ${action}';
@override
String shortcutUpdated({required Object action}) => '快捷键已为 ${action} 更新';
@override
String get autoSkip => '自动跳过';
@override
String get autoSkipIntro => '自动跳过片头';
@override
String get autoSkipIntroDescription => '几秒钟后自动跳过片头标记';
@override
String get autoSkipCredits => '自动跳过片尾';
@override
String get autoSkipCreditsDescription => '自动跳过片尾并播放下一集';
@override
String get autoSkipDelay => '自动跳过延迟';
@override
String autoSkipDelayDescription({required Object seconds}) =>
'自动跳过前等待 ${seconds} 秒';
}
// Path: search
@@ -8253,6 +8346,21 @@ extension on Translations {
'Shortcut already assigned to ${action}';
case 'settings.shortcutUpdated':
return ({required Object action}) => 'Shortcut updated for ${action}';
case 'settings.autoSkip':
return 'Auto Skip';
case 'settings.autoSkipIntro':
return 'Auto Skip Intro';
case 'settings.autoSkipIntroDescription':
return 'Automatically skip intro markers after a few seconds';
case 'settings.autoSkipCredits':
return 'Auto Skip Credits';
case 'settings.autoSkipCreditsDescription':
return 'Automatically skip credits and play next episode';
case 'settings.autoSkipDelay':
return 'Auto Skip Delay';
case 'settings.autoSkipDelayDescription':
return ({required Object seconds}) =>
'Wait ${seconds} seconds before auto-skipping';
case 'search.hint':
return 'Search movies, shows, music...';
case 'search.tryDifferentTerm':
@@ -9189,6 +9297,21 @@ extension on _StringsDe {
case 'settings.shortcutUpdated':
return ({required Object action}) =>
'Tastenkürzel aktualisiert für ${action}';
case 'settings.autoSkip':
return 'Automatisches Überspringen';
case 'settings.autoSkipIntro':
return 'Intro automatisch überspringen';
case 'settings.autoSkipIntroDescription':
return 'Intro-Marker nach wenigen Sekunden automatisch überspringen';
case 'settings.autoSkipCredits':
return 'Abspann automatisch überspringen';
case 'settings.autoSkipCreditsDescription':
return 'Abspann automatisch überspringen und nächste Episode abspielen';
case 'settings.autoSkipDelay':
return 'Verzögerung für automatisches Überspringen';
case 'settings.autoSkipDelayDescription':
return ({required Object seconds}) =>
'${seconds} Sekunden vor dem automatischen Überspringen warten';
case 'search.hint':
return 'Filme, Serien, Musik suchen...';
case 'search.tryDifferentTerm':
@@ -10130,6 +10253,21 @@ extension on _StringsIt {
case 'settings.shortcutUpdated':
return ({required Object action}) =>
'Scorciatoia aggiornata per ${action}';
case 'settings.autoSkip':
return 'Salto Automatico';
case 'settings.autoSkipIntro':
return 'Salta Intro Automaticamente';
case 'settings.autoSkipIntroDescription':
return 'Salta automaticamente i marcatori dell\'intro dopo alcuni secondi';
case 'settings.autoSkipCredits':
return 'Salta Crediti Automaticamente';
case 'settings.autoSkipCreditsDescription':
return 'Salta automaticamente i crediti e riproduci l\'episodio successivo';
case 'settings.autoSkipDelay':
return 'Ritardo Salto Automatico';
case 'settings.autoSkipDelayDescription':
return ({required Object seconds}) =>
'Aspetta ${seconds} secondi prima del salto automatico';
case 'search.hint':
return 'Cerca film. spettacoli, musica...';
case 'search.tryDifferentTerm':
@@ -11073,6 +11211,21 @@ extension on _StringsNl {
case 'settings.shortcutUpdated':
return ({required Object action}) =>
'Sneltoets bijgewerkt voor ${action}';
case 'settings.autoSkip':
return 'Automatisch Overslaan';
case 'settings.autoSkipIntro':
return 'Intro Automatisch Overslaan';
case 'settings.autoSkipIntroDescription':
return 'Intro-markeringen na enkele seconden automatisch overslaan';
case 'settings.autoSkipCredits':
return 'Credits Automatisch Overslaan';
case 'settings.autoSkipCreditsDescription':
return 'Credits automatisch overslaan en volgende aflevering afspelen';
case 'settings.autoSkipDelay':
return 'Vertraging Automatisch Overslaan';
case 'settings.autoSkipDelayDescription':
return ({required Object seconds}) =>
'${seconds} seconden wachten voor automatisch overslaan';
case 'search.hint':
return 'Zoek films, series, muziek...';
case 'search.tryDifferentTerm':
@@ -12017,6 +12170,21 @@ extension on _StringsSv {
return ({required Object action}) => 'Genväg redan tilldelad ${action}';
case 'settings.shortcutUpdated':
return ({required Object action}) => 'Genväg uppdaterad för ${action}';
case 'settings.autoSkip':
return 'Auto Hoppa Över';
case 'settings.autoSkipIntro':
return 'Hoppa Över Intro Automatiskt';
case 'settings.autoSkipIntroDescription':
return 'Hoppa automatiskt över intro-markörer efter några sekunder';
case 'settings.autoSkipCredits':
return 'Hoppa Över Credits Automatiskt';
case 'settings.autoSkipCreditsDescription':
return 'Hoppa automatiskt över credits och spela nästa avsnitt';
case 'settings.autoSkipDelay':
return 'Fördröjning Auto Hoppa Över';
case 'settings.autoSkipDelayDescription':
return ({required Object seconds}) =>
'Vänta ${seconds} sekunder innan automatisk överhoppning';
case 'search.hint':
return 'Sök filmer, serier, musik...';
case 'search.tryDifferentTerm':
@@ -12959,6 +13127,20 @@ extension on _StringsZh {
return ({required Object action}) => '快捷键已被分配给 ${action}';
case 'settings.shortcutUpdated':
return ({required Object action}) => '快捷键已为 ${action} 更新';
case 'settings.autoSkip':
return '自动跳过';
case 'settings.autoSkipIntro':
return '自动跳过片头';
case 'settings.autoSkipIntroDescription':
return '几秒钟后自动跳过片头标记';
case 'settings.autoSkipCredits':
return '自动跳过片尾';
case 'settings.autoSkipCreditsDescription':
return '自动跳过片尾并播放下一集';
case 'settings.autoSkipDelay':
return '自动跳过延迟';
case 'settings.autoSkipDelayDescription':
return ({required Object seconds}) => '自动跳过前等待 ${seconds} 秒';
case 'search.hint':
return '搜索电影、系列、音乐...';
case 'search.tryDifferentTerm':
+8 -1
View File
@@ -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...",
+8 -1
View File
@@ -133,7 +133,14 @@
"validationErrorEnterNumber": "Bitte eine gültige Zahl eingeben",
"validationErrorDuration": "Dauer muss zwischen ${min} und ${max} ${unit} liegen",
"shortcutAlreadyAssigned": "Tastenkürzel bereits zugewiesen an ${action}",
"shortcutUpdated": "Tastenkürzel aktualisiert für ${action}"
"shortcutUpdated": "Tastenkürzel aktualisiert für ${action}",
"autoSkip": "Automatisches Überspringen",
"autoSkipIntro": "Intro automatisch überspringen",
"autoSkipIntroDescription": "Intro-Marker nach wenigen Sekunden automatisch überspringen",
"autoSkipCredits": "Abspann automatisch überspringen",
"autoSkipCreditsDescription": "Abspann automatisch überspringen und nächste Episode abspielen",
"autoSkipDelay": "Verzögerung für automatisches Überspringen",
"autoSkipDelayDescription": "${seconds} Sekunden vor dem automatischen Überspringen warten"
},
"search": {
"hint": "Filme, Serien, Musik suchen...",
+8 -1
View File
@@ -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...",
+8 -1
View File
@@ -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...",
+8 -1
View File
@@ -133,7 +133,14 @@
"validationErrorEnterNumber": "Vänligen ange ett giltigt nummer",
"validationErrorDuration": "Tiden måste vara mellan ${min} och ${max} ${unit}",
"shortcutAlreadyAssigned": "Genväg redan tilldelad ${action}",
"shortcutUpdated": "Genväg uppdaterad för ${action}"
"shortcutUpdated": "Genväg uppdaterad för ${action}",
"autoSkip": "Auto Hoppa Över",
"autoSkipIntro": "Hoppa Över Intro Automatiskt",
"autoSkipIntroDescription": "Hoppa automatiskt över intro-markörer efter några sekunder",
"autoSkipCredits": "Hoppa Över Credits Automatiskt",
"autoSkipCreditsDescription": "Hoppa automatiskt över credits och spela nästa avsnitt",
"autoSkipDelay": "Fördröjning Auto Hoppa Över",
"autoSkipDelayDescription": "Vänta ${seconds} sekunder innan automatisk överhoppning"
},
"search": {
"hint": "Sök filmer, serier, musik...",
+8 -1
View File
@@ -133,7 +133,14 @@
"validationErrorEnterNumber": "请输入一个有效的数字",
"validationErrorDuration": "时长必须介于 ${min} 和 ${max} ${unit} 之间",
"shortcutAlreadyAssigned": "快捷键已被分配给 ${action}",
"shortcutUpdated": "快捷键已为 ${action} 更新"
"shortcutUpdated": "快捷键已为 ${action} 更新",
"autoSkip": "自动跳过",
"autoSkipIntro": "自动跳过片头",
"autoSkipIntroDescription": "几秒钟后自动跳过片头标记",
"autoSkipCredits": "自动跳过片尾",
"autoSkipCreditsDescription": "自动跳过片尾并播放下一集",
"autoSkipDelay": "自动跳过延迟",
"autoSkipDelayDescription": "自动跳过前等待 ${seconds} 秒"
},
"search": {
"hint": "搜索电影、系列、音乐...",
+28 -24
View File
@@ -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';
@@ -22,9 +21,9 @@ 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';
void main() async {
@@ -38,26 +37,27 @@ void main() async {
LocaleSettings.setLocale(savedLocale);
// Configure image cache for large libraries
PaintingBinding.instance.imageCache.maximumSizeBytes = 500 << 20; // 500MB
PaintingBinding.instance.imageCache.maximumSize = 500; // 500 images
PaintingBinding.instance.imageCache.maximumSizeBytes = 200 << 20; // 200MB
// Initialize services in parallel where possible
final futures = <Future<void>>[];
// Initialize window_manager for desktop platforms
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
await windowManager.ensureInitialized();
futures.add(windowManager.ensureInitialized());
}
// Configure macOS window with custom titlebar
await MacOSTitlebarService.setupCustomTitlebar();
// Configure macOS window with custom titlebar (depends on window manager)
futures.add(MacOSTitlebarService.setupCustomTitlebar());
// Initialize MediaKit
MediaKit.ensureInitialized();
// Note: Orientation will be set dynamically based on device type in MainApp
await StorageService.getInstance();
// Initialize storage service
futures.add(StorageService.getInstance().then((_) {}));
// Initialize language codes for track selection
await LanguageCodes.initialize();
futures.add(LanguageCodes.initialize());
// Wait for all parallel services to complete
await Future.wait(futures);
// Initialize logger level based on debug setting
final debugEnabled = settings.getEnableDebugLogging();
@@ -94,12 +94,16 @@ 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>(
@@ -159,7 +163,7 @@ class _SetupScreenState extends State<SetupScreen> {
_loadSavedCredentials();
}
void _checkForUpdatesOnStartup() async {
Future<void> _checkForUpdatesOnStartup() async {
// Delay slightly to allow UI to settle
await Future.delayed(const Duration(milliseconds: 500));
@@ -288,10 +292,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 +303,9 @@ class _SetupScreenState extends State<SetupScreen> {
builder: (context) => MainScreen(client: firstClient),
),
);
// Check for updates in background after navigation
_checkForUpdatesOnStartup();
}
} else {
// All connections failed
+1 -1
View File
@@ -1,5 +1,5 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../services/plex_client.dart';
import '../models/plex_metadata.dart';
/// Mixin for screens that need to update individual items after watch state changes
+102
View File
@@ -0,0 +1,102 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/keyboard_utils.dart';
/// A mixin that provides keyboard long-press detection for focusable widgets.
///
/// This allows keyboard/gamepad users to access context menus by holding
/// the activation key (Enter, Space, Select, or GameButtonA) for 1 second.
///
/// Usage:
/// ```dart
/// class _MyWidgetState extends State<MyWidget> with KeyboardLongPressMixin {
/// @override
/// void onKeyboardTap() {
/// // Handle short press (normal tap)
/// }
///
/// @override
/// void onKeyboardLongPress() {
/// // Handle long press (show context menu)
/// }
///
/// KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
/// final result = handleKeyboardLongPress(event);
/// if (result == KeyEventResult.handled) return result;
/// // Handle other keys...
/// return KeyEventResult.ignored;
/// }
/// }
/// ```
mixin KeyboardLongPressMixin<T extends StatefulWidget> on State<T> {
Timer? _longPressTimer;
LogicalKeyboardKey? _pressedKey;
bool _longPressTriggered = false;
static const _longPressDuration = Duration(seconds: 1);
/// Override to handle tap action (short press)
void onKeyboardTap();
/// Override to handle long press action (e.g., show context menu)
void onKeyboardLongPress();
/// Call this from your onKeyEvent handler to enable long-press detection.
/// Returns [KeyEventResult.handled] if the event was an activation key,
/// [KeyEventResult.ignored] otherwise.
KeyEventResult handleKeyboardLongPress(KeyEvent event) {
if (!isKeyboardActivationKey(event.logicalKey)) {
return KeyEventResult.ignored;
}
if (event is KeyDownEvent) {
// Only start timer on initial press (not key repeat)
if (_pressedKey == null) {
_pressedKey = event.logicalKey;
_longPressTriggered = false;
_longPressTimer = Timer(_longPressDuration, () {
_longPressTriggered = true;
onKeyboardLongPress();
});
}
return KeyEventResult.handled;
}
// Handle key repeat events (suppress system sound on macOS)
if (event is KeyRepeatEvent) {
return KeyEventResult.handled;
}
if (event is KeyUpEvent && event.logicalKey == _pressedKey) {
_longPressTimer?.cancel();
_longPressTimer = null;
_pressedKey = null;
// Only trigger tap if long press wasn't already triggered
if (!_longPressTriggered) {
onKeyboardTap();
}
_longPressTriggered = false;
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Cancel any pending long-press timer. Call this if focus is lost
/// or the widget is being disposed while a key is held.
void cancelKeyboardLongPress() {
_longPressTimer?.cancel();
_longPressTimer = null;
_pressedKey = null;
_longPressTriggered = false;
}
@override
void dispose() {
_longPressTimer?.cancel();
super.dispose();
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../services/plex_client.dart';
import '../models/plex_library.dart';
import '../utils/provider_extensions.dart';
+3
View File
@@ -3,13 +3,16 @@ class PlexMediaInfo {
final List<PlexAudioTrack> audioTracks;
final List<PlexSubtitleTrack> subtitleTracks;
final List<PlexChapter> chapters;
final int? partId;
PlexMediaInfo({
required this.videoUrl,
required this.audioTracks,
required this.subtitleTracks,
required this.chapters,
this.partId,
});
int? getPartId() => partId;
}
/// Mixin for building track labels with a consistent pattern
+26
View File
@@ -0,0 +1,26 @@
/// Represents an audio output device.
class AudioDevice {
/// Unique identifier for the device.
final String name;
/// Human-readable description of the device.
final String description;
const AudioDevice({required this.name, this.description = ''});
/// Default/auto audio device.
static const auto = AudioDevice(name: 'auto', description: 'Auto');
@override
String toString() => 'AudioDevice($name, $description)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AudioDevice &&
runtimeType == other.runtimeType &&
name == other.name;
@override
int get hashCode => name.hashCode;
}
+68
View File
@@ -0,0 +1,68 @@
/// Represents an audio track in the media.
class AudioTrack {
/// Unique identifier for the track.
final String id;
/// Human-readable title of the track.
final String? title;
/// Language code (e.g., 'eng', 'jpn').
final String? language;
/// Audio codec (e.g., 'aac', 'ac3', 'dts').
final String? codec;
/// Number of audio channels.
final int? channels;
/// Alias for channels (media_kit compatibility).
int? get channelsCount => channels;
/// Sample rate in Hz.
final int? sampleRate;
/// Bitrate in bits per second.
final int? bitrate;
/// Whether this is the default track.
final bool isDefault;
/// Whether this track is forced.
final bool isForced;
const AudioTrack({
required this.id,
this.title,
this.language,
this.codec,
this.channels,
this.sampleRate,
this.bitrate,
this.isDefault = false,
this.isForced = false,
});
/// Auto-select track.
static const auto = AudioTrack(id: 'auto', title: 'Auto');
/// Disable audio.
static const off = AudioTrack(id: 'no', title: 'Off');
/// Returns a display name for the track.
String get displayName {
if (title != null && title!.isNotEmpty) return title!;
if (language != null && language!.isNotEmpty) return language!;
return 'Track $id';
}
@override
String toString() => 'AudioTrack($id, $displayName)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AudioTrack && runtimeType == other.runtimeType && id == other.id;
@override
int get hashCode => id.hashCode;
}
+27
View File
@@ -0,0 +1,27 @@
/// Represents a media source for the player.
class Media {
/// The URI of the media (file path, HTTP URL, etc.).
final String uri;
/// Optional HTTP headers for network requests.
final Map<String, String>? headers;
/// Optional start position for playback.
final Duration? start;
const Media(this.uri, {this.headers, this.start});
@override
String toString() => 'Media($uri)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Media &&
runtimeType == other.runtimeType &&
uri == other.uri &&
start == other.start;
@override
int get hashCode => uri.hashCode ^ start.hashCode;
}
+22
View File
@@ -0,0 +1,22 @@
import 'player_log_level.dart';
/// A log entry from the player.
class PlayerLog {
/// The log level of this message.
final PlayerLogLevel level;
/// The prefix/category of the log message (e.g., 'cplayer', 'ffmpeg').
final String prefix;
/// The log message text.
final String text;
const PlayerLog({
required this.level,
required this.prefix,
required this.text,
});
@override
String toString() => '[$prefix] ${level.name}: $text';
}
+26
View File
@@ -0,0 +1,26 @@
/// Log level for player messages.
enum PlayerLogLevel {
/// No logging.
none,
/// Fatal errors only.
fatal,
/// Errors.
error,
/// Warnings.
warn,
/// Informational messages.
info,
/// Verbose output.
verbose,
/// Debug messages.
debug,
/// Trace-level output (very verbose).
trace,
}
+75
View File
@@ -0,0 +1,75 @@
/// Represents a subtitle track in the media.
class SubtitleTrack {
/// Unique identifier for the track.
final String id;
/// Human-readable title of the track.
final String? title;
/// Language code (e.g., 'eng', 'jpn').
final String? language;
/// Subtitle codec/format (e.g., 'subrip', 'ass', 'pgs').
final String? codec;
/// Whether this is the default track.
final bool isDefault;
/// Whether this track is forced (e.g., for foreign language segments).
final bool isForced;
/// Whether this is an external subtitle file.
final bool isExternal;
/// URI of external subtitle file (if isExternal is true).
final String? uri;
const SubtitleTrack({
required this.id,
this.title,
this.language,
this.codec,
this.isDefault = false,
this.isForced = false,
this.isExternal = false,
this.uri,
});
/// Create a subtitle track from an external URI.
factory SubtitleTrack.uri(String uri, {String? title, String? language}) {
return SubtitleTrack(
id: 'external:$uri',
title: title,
language: language,
isExternal: true,
uri: uri,
);
}
/// Auto-select track.
static const auto = SubtitleTrack(id: 'auto', title: 'Auto');
/// Disable subtitles.
static const off = SubtitleTrack(id: 'no', title: 'Off');
/// Returns a display name for the track.
String get displayName {
if (title != null && title!.isNotEmpty) return title!;
if (language != null && language!.isNotEmpty) return language!;
if (isExternal) return 'External';
return 'Track $id';
}
@override
String toString() => 'SubtitleTrack($id, $displayName)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is SubtitleTrack &&
runtimeType == other.runtimeType &&
id == other.id;
@override
int get hashCode => id.hashCode;
}
+24
View File
@@ -0,0 +1,24 @@
import 'audio_track.dart';
import 'subtitle_track.dart';
/// Represents the currently selected tracks.
class TrackSelection {
/// Currently selected audio track.
final AudioTrack? audio;
/// Currently selected subtitle track.
final SubtitleTrack? subtitle;
const TrackSelection({this.audio, this.subtitle});
/// Creates a copy with the given fields replaced.
TrackSelection copyWith({AudioTrack? audio, SubtitleTrack? subtitle}) {
return TrackSelection(
audio: audio ?? this.audio,
subtitle: subtitle ?? this.subtitle,
);
}
@override
String toString() => 'TrackSelection(audio: $audio, subtitle: $subtitle)';
}
+25
View File
@@ -0,0 +1,25 @@
import 'audio_track.dart';
import 'subtitle_track.dart';
/// Container for all available tracks in the media.
class Tracks {
/// Available audio tracks.
final List<AudioTrack> audio;
/// Available subtitle tracks.
final List<SubtitleTrack> subtitle;
const Tracks({this.audio = const [], this.subtitle = const []});
/// Creates a copy with the given fields replaced.
Tracks copyWith({List<AudioTrack>? audio, List<SubtitleTrack>? subtitle}) {
return Tracks(
audio: audio ?? this.audio,
subtitle: subtitle ?? this.subtitle,
);
}
@override
String toString() =>
'Tracks(audio: ${audio.length}, subtitle: ${subtitle.length})';
}
+62
View File
@@ -0,0 +1,62 @@
/// MPV Player library for Flutter.
///
/// This library provides a platform-agnostic interface for video playback
/// using MPV as the underlying player engine.
///
/// ## Features
///
/// - Stream-based reactive state updates
/// - Audio passthrough support for lossless audio
/// - Subtitle rendering with libass
/// - Hardware-accelerated decoding
/// - Cross-platform support (macOS, iOS, Android, Windows, Linux)
///
/// ## Usage
///
/// ```dart
/// import 'package:flutter_application_1/mpv/mpv.dart';
///
/// // Create a player
/// final player = Player();
///
/// // Configure player properties
/// await player.setProperty('hwdec', 'auto');
/// await player.setProperty('demuxer-max-bytes', '150000000');
/// await player.setAudioPassthrough(true);
///
/// // Open and play media
/// await player.open(Media('https://example.com/video.mp4'));
///
/// // Listen to state changes
/// player.streams.position.listen((position) {
/// print('Position: $position');
/// });
///
/// // Display video
/// Video(
/// player: player,
/// controls: (context) => MyCustomControls(),
/// )
///
/// // Clean up
/// await player.dispose();
/// ```
library;
// Player
export 'player/player.dart';
export 'player/player_state.dart';
export 'player/player_streams.dart';
// Models
export 'models/media.dart';
export 'models/audio_device.dart';
export 'models/audio_track.dart';
export 'models/subtitle_track.dart';
export 'models/tracks.dart';
export 'models/track_selection.dart';
export 'models/player_log.dart';
export 'models/player_log_level.dart';
// Video
export 'video/video.dart';
+29
View File
@@ -0,0 +1,29 @@
import 'package:flutter/services.dart';
import '../player_native.dart';
/// Linux implementation of [Player].
///
/// Uses libmpv with OpenGL rendering via GtkGLArea.
/// The mpv video is rendered to a GtkGLArea positioned behind
/// the Flutter view using a GtkOverlay, with transparent regions
/// in the Flutter UI allowing the video to show through.
class PlayerLinux extends PlayerNative {
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
@override
int? get textureId => null; // Uses GtkGLArea, not Flutter texture
/// Sets the visibility of the video controls overlay.
///
/// On Linux, due to Flutter's lack of transparency support in GtkOverlay,
/// we hide the video layer when controls are visible and show it when
/// controls are hidden. This provides a workaround for the transparency
/// limitation.
@override
Future<void> setControlsVisible(bool visible) async {
await _methodChannel.invokeMethod('setControlsVisible', {
'visible': visible,
});
}
}
@@ -0,0 +1,33 @@
import 'package:flutter/services.dart';
import '../player_native.dart';
import '../video_rect_support.dart';
/// Windows implementation of [Player].
///
/// Uses libmpv via platform channels with native window embedding.
/// The mpv video window is positioned behind the Flutter window,
/// with transparent regions allowing the video to show through.
class PlayerWindows extends PlayerNative with VideoRectSupport {
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
@override
int? get textureId => null; // Uses native window embedding, not Flutter texture
@override
Future<void> setVideoRect({
required int left,
required int top,
required int right,
required int bottom,
required double devicePixelRatio,
}) async {
await _methodChannel.invokeMethod('setVideoRect', {
'left': left,
'top': top,
'right': right,
'bottom': bottom,
'devicePixelRatio': devicePixelRatio,
});
}
}
+219
View File
@@ -0,0 +1,219 @@
import 'dart:io' show Platform;
import '../models/audio_device.dart';
import '../models/media.dart';
import '../models/audio_track.dart';
import '../models/subtitle_track.dart';
import 'player_native.dart';
import 'player_state.dart';
import 'player_streams.dart';
import 'platform/player_linux.dart';
import 'platform/player_windows.dart';
/// Abstract interface for the video player.
///
/// This interface defines all playback control methods, state access,
/// and reactive streams for the video player.
///
/// Example usage:
/// ```dart
/// final player = Player();
/// await player.open(Media('https://example.com/video.mp4'));
/// await player.play();
///
/// // Configure player properties
/// await player.setProperty('hwdec', 'auto');
/// await player.setProperty('demuxer-max-bytes', '150000000');
///
/// // Listen to position updates
/// player.streams.position.listen((position) {
/// print('Position: $position');
/// });
///
/// // Access current state
/// print('Playing: ${player.state.playing}');
/// ```
abstract class Player {
/// Current synchronous state snapshot.
///
/// Use this for immediate state access in UI.
PlayerState get state;
/// Reactive streams for state changes.
///
/// Use these for reactive UI updates.
PlayerStreams get streams;
/// Texture ID for Flutter's Texture widget (video rendering).
///
/// This is set by the platform implementation when video
/// rendering is initialized. Returns null if not ready.
int? get textureId;
// ============================================
// Playback Control
// ============================================
/// Open a media source for playback.
///
/// [media] - The media source to open.
/// [play] - Whether to start playback immediately (default: true).
Future<void> open(Media media, {bool play = true});
/// Start or resume playback.
Future<void> play();
/// Pause playback.
Future<void> pause();
/// Toggle between play and pause.
Future<void> playOrPause();
/// Stop playback and reset position.
Future<void> stop();
/// Seek to a specific position.
Future<void> seek(Duration position);
// ============================================
// Track Selection
// ============================================
/// Select an audio track.
Future<void> selectAudioTrack(AudioTrack track);
/// Select a subtitle track.
///
/// Pass [SubtitleTrack.off] to disable subtitles.
Future<void> selectSubtitleTrack(SubtitleTrack track);
/// Add an external subtitle track.
///
/// [uri] - URL or path to the subtitle file.
/// [title] - Optional display title.
/// [language] - Optional language code.
/// [select] - Whether to select this track immediately.
Future<void> addSubtitleTrack({
required String uri,
String? title,
String? language,
bool select = false,
});
// ============================================
// Volume and Rate
// ============================================
/// Set the playback volume.
///
/// [volume] - Volume level from 0.0 (muted) to 100.0 (max).
Future<void> setVolume(double volume);
/// Set the playback rate/speed.
///
/// [rate] - Playback rate from 0.25 to 4.0 (1.0 = normal speed).
Future<void> setRate(double rate);
/// Set the audio output device.
///
/// [device] - The audio device to use.
Future<void> setAudioDevice(AudioDevice device);
// ============================================
// MPV Properties (Advanced)
// ============================================
/// Set an MPV property by name.
///
/// Common properties:
/// - 'hwdec': Hardware decoding mode ('auto', 'no', 'videotoolbox', etc.)
/// - 'demuxer-max-bytes': Buffer size in bytes
/// - 'audio-delay': Audio sync offset in seconds (e.g., '0.5')
/// - 'sub-delay': Subtitle sync offset in seconds
/// - 'sub-font': Subtitle font name
/// - 'sub-font-size': Subtitle font size
/// - 'sub-color': Subtitle text color
/// - 'sub-back-color': Subtitle background color
/// - 'sub-border-size': Subtitle border size
/// - 'sub-margin-y': Vertical subtitle margin
/// - 'sub-ass': Enable/disable ASS subtitle rendering ('yes'/'no')
/// - 'audio-exclusive': Exclusive audio mode ('yes'/'no')
/// - 'audio-spdif': Audio passthrough formats (e.g., 'ac3,eac3,dts,truehd')
Future<void> setProperty(String name, String value);
/// Get an MPV property value by name.
Future<String?> getProperty(String name);
/// Execute a raw MPV command.
///
/// [args] - Command and arguments as a list of strings.
Future<void> command(List<String> args);
// ============================================
// Passthrough Mode (Audio)
// ============================================
/// Enable or disable audio passthrough mode.
///
/// When enabled, supported audio codecs (AC3, DTS, etc.) will be
/// passed through to the audio device without decoding.
Future<void> setAudioPassthrough(bool enabled);
// ============================================
// Visibility (macOS Metal Layer)
// ============================================
/// Show or hide the video rendering layer.
///
/// On macOS, this controls the Metal layer visibility.
/// On other platforms, this may have no effect.
///
/// Returns true if the operation was successful.
Future<bool> setVisible(bool visible);
/// Notify the player about controls visibility.
///
/// On Linux, due to Flutter's lack of transparency support in GtkOverlay,
/// the video layer is hidden when controls are visible and shown when
/// controls are hidden. On other platforms, this is a no-op.
Future<void> setControlsVisible(bool visible);
/// Update the video frame/surface dimensions.
///
/// On iOS/macOS, this updates the Metal layer's frame to match the current
/// window size. Call this when the layout changes (e.g., device rotation).
/// On other platforms, this is a no-op.
Future<void> updateFrame();
// ============================================
// Lifecycle
// ============================================
/// Dispose of the player and release resources.
///
/// After calling this, the player instance should not be used.
Future<void> dispose();
// ============================================
// Factory
// ============================================
/// Creates a new player instance.
///
/// Returns a platform-specific implementation:
/// - macOS/iOS/Android: [PlayerNative] using MPVKit/libmpv with texture rendering
/// - Windows: [PlayerWindows] using libmpv with native window embedding
/// - Linux: [PlayerLinux] using libmpv with OpenGL rendering via GtkGLArea
factory Player() {
if (Platform.isMacOS || Platform.isIOS || Platform.isAndroid) {
return PlayerNative();
}
if (Platform.isWindows) {
return PlayerWindows();
}
if (Platform.isLinux) {
return PlayerLinux();
}
throw UnsupportedError('Player is not supported on this platform');
}
}
+577
View File
@@ -0,0 +1,577 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter/services.dart';
import '../utils/android_font_loader.dart';
import '../models/audio_device.dart';
import '../models/audio_track.dart';
import '../models/player_log.dart';
import '../models/media.dart';
import '../models/subtitle_track.dart';
import '../models/track_selection.dart';
import '../models/tracks.dart';
import 'player.dart';
import 'player_state.dart';
import 'player_streams.dart';
/// Shared native implementation of [Player] for iOS and macOS.
/// Uses MPVKit via platform channels with Metal rendering.
class PlayerNative implements Player {
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
static const _eventChannel = EventChannel('com.plezy/mpv_player/events');
PlayerState _state = const PlayerState();
@override
PlayerState get state => _state;
late final PlayerStreams _streams;
@override
PlayerStreams get streams => _streams;
@override
int? get textureId => null; // Uses direct Metal layer, not Flutter texture
// Stream controllers
final _playingController = StreamController<bool>.broadcast();
final _completedController = StreamController<bool>.broadcast();
final _bufferingController = StreamController<bool>.broadcast();
final _positionController = StreamController<Duration>.broadcast();
final _durationController = StreamController<Duration>.broadcast();
final _bufferController = StreamController<Duration>.broadcast();
final _volumeController = StreamController<double>.broadcast();
final _rateController = StreamController<double>.broadcast();
final _tracksController = StreamController<Tracks>.broadcast();
final _trackController = StreamController<TrackSelection>.broadcast();
final _logController = StreamController<PlayerLog>.broadcast();
final _errorController = StreamController<String>.broadcast();
final _audioDeviceController = StreamController<AudioDevice>.broadcast();
final _audioDevicesController =
StreamController<List<AudioDevice>>.broadcast();
StreamSubscription? _eventSubscription;
bool _disposed = false;
bool _initialized = false;
PlayerNative() {
_streams = PlayerStreams(
playing: _playingController.stream,
completed: _completedController.stream,
buffering: _bufferingController.stream,
position: _positionController.stream,
duration: _durationController.stream,
buffer: _bufferController.stream,
volume: _volumeController.stream,
rate: _rateController.stream,
tracks: _tracksController.stream,
track: _trackController.stream,
log: _logController.stream,
error: _errorController.stream,
audioDevice: _audioDeviceController.stream,
audioDevices: _audioDevicesController.stream,
);
_setupEventListener();
}
void _setupEventListener() {
_eventSubscription = _eventChannel.receiveBroadcastStream().listen(
_handleEvent,
onError: (error) {
_errorController.add(error.toString());
},
);
}
void _handleEvent(dynamic event) {
if (event is! Map) return;
final type = event['type'] as String?;
final name = event['name'] as String?;
if (type == 'property' && name != null) {
_handlePropertyChange(name, event['value']);
} else if (type == 'event' && name != null) {
_handleMpvEvent(name, event['data'] as Map?);
}
}
void _handlePropertyChange(String name, dynamic value) {
switch (name) {
case 'pause':
final playing = value == false;
_state = _state.copyWith(playing: playing);
_playingController.add(playing);
break;
case 'eof-reached':
final completed = value == true;
_state = _state.copyWith(completed: completed);
_completedController.add(completed);
break;
case 'paused-for-cache':
final buffering = value == true;
_state = _state.copyWith(buffering: buffering);
_bufferingController.add(buffering);
break;
case 'time-pos':
if (value is num) {
final position = Duration(milliseconds: (value * 1000).toInt());
_state = _state.copyWith(position: position);
_positionController.add(position);
}
break;
case 'duration':
if (value is num) {
final duration = Duration(milliseconds: (value * 1000).toInt());
_state = _state.copyWith(duration: duration);
_durationController.add(duration);
}
break;
case 'demuxer-cache-time':
if (value is num) {
final buffer = Duration(milliseconds: (value * 1000).toInt());
_state = _state.copyWith(buffer: buffer);
_bufferController.add(buffer);
}
break;
case 'volume':
if (value is num) {
final volume = value.toDouble();
_state = _state.copyWith(volume: volume);
_volumeController.add(volume);
}
break;
case 'speed':
if (value is num) {
final rate = value.toDouble();
_state = _state.copyWith(rate: rate);
_rateController.add(rate);
}
break;
case 'track-list':
List? trackList;
if (value is List) {
trackList = value;
} else if (value is String) {
// Android - JSON string that needs parsing
try {
final decoded = jsonDecode(value);
if (decoded is List) {
trackList = decoded;
}
} catch (e) {
// Invalid JSON, ignore
break;
}
}
if (trackList != null) {
final tracks = _parseTrackList(trackList);
_state = _state.copyWith(tracks: tracks);
_tracksController.add(tracks);
}
break;
case 'aid':
_updateSelectedAudioTrack(value);
break;
case 'sid':
_updateSelectedSubtitleTrack(value);
break;
}
}
void _handleMpvEvent(String name, Map? data) {
switch (name) {
case 'end-file':
final reason = data?['reason'] as String?;
if (reason == 'eof') {
_state = _state.copyWith(completed: true);
_completedController.add(true);
} else if (reason == 'error') {
_errorController.add('Playback error');
}
break;
case 'file-loaded':
// Reset completed state when new file is loaded
_state = _state.copyWith(completed: false);
_completedController.add(false);
break;
}
}
Tracks _parseTrackList(List trackList) {
final audioTracks = <AudioTrack>[];
final subtitleTracks = <SubtitleTrack>[];
for (final track in trackList) {
if (track is! Map) continue;
final type = track['type'] as String?;
final id = track['id']?.toString() ?? '';
if (type == 'audio') {
audioTracks.add(
AudioTrack(
id: id,
title: track['title'] as String?,
language: track['lang'] as String?,
codec: track['codec'] as String?,
channels: (track['demux-channel-count'] as num?)?.toInt(),
sampleRate: (track['demux-samplerate'] as num?)?.toInt(),
isDefault: track['default'] as bool? ?? false,
),
);
} else if (type == 'sub') {
subtitleTracks.add(
SubtitleTrack(
id: id,
title: track['title'] as String?,
language: track['lang'] as String?,
codec: track['codec'] as String?,
isExternal: track['external'] as bool? ?? false,
uri: track['external-filename'] as String?,
),
);
}
}
return Tracks(audio: audioTracks, subtitle: subtitleTracks);
}
void _updateSelectedAudioTrack(dynamic trackId) {
final id = trackId?.toString();
AudioTrack? selectedTrack;
if (id != null && id != 'no') {
selectedTrack = _state.tracks.audio.cast<AudioTrack?>().firstWhere(
(t) => t?.id == id,
orElse: () => null,
);
}
_state = _state.copyWith(
track: _state.track.copyWith(audio: selectedTrack),
);
_trackController.add(_state.track);
}
void _updateSelectedSubtitleTrack(dynamic trackId) {
final id = trackId?.toString();
SubtitleTrack? selectedTrack;
if (id != null && id != 'no') {
selectedTrack = _state.tracks.subtitle.cast<SubtitleTrack?>().firstWhere(
(t) => t?.id == id,
orElse: () => null,
);
}
_state = _state.copyWith(
track: _state.track.copyWith(subtitle: selectedTrack),
);
_trackController.add(_state.track);
}
Future<void> _ensureInitialized() async {
if (_initialized) return;
try {
final result = await _methodChannel.invokeMethod<bool>('initialize');
_initialized = result == true;
if (!_initialized) {
throw Exception('Failed to initialize player');
}
// Configure subtitle fonts for Android libass support
if (Platform.isAndroid) {
await _configureAndroidSubtitleFonts();
}
// Subscribe to MPV properties
await _observeProperty('time-pos', 'double');
await _observeProperty('duration', 'double');
await _observeProperty('pause', 'flag');
await _observeProperty('paused-for-cache', 'flag');
await _observeProperty(
'track-list',
Platform.isAndroid ? 'string' : 'node',
);
await _observeProperty('eof-reached', 'flag');
await _observeProperty('volume', 'double');
await _observeProperty('aid', 'string');
await _observeProperty('sid', 'string');
} catch (e) {
_errorController.add('Initialization failed: $e');
rethrow;
}
}
Future<void> _observeProperty(String name, String format) async {
await _methodChannel.invokeMethod('observeProperty', {
'name': name,
'format': format,
});
}
/// Configures subtitle fonts for Android libass support.
/// On Android, libass cannot access system fonts, so we need to provide
/// a font file from assets.
Future<void> _configureAndroidSubtitleFonts() async {
try {
final fontDir = await AndroidFontLoader.loadSubtitleFont();
if (fontDir != null) {
// Configure MPV to use the extracted font for libass
await setProperty('config', 'yes');
await setProperty('sub-fonts-dir', fontDir);
await setProperty('sub-font', AndroidFontLoader.fontName);
}
} catch (e) {
// Font configuration is not critical - continue without it
_errorController.add('Failed to configure subtitle fonts: $e');
}
}
void _checkDisposed() {
if (_disposed) {
throw StateError('Player has been disposed');
}
}
// ============================================
// Playback Control
// ============================================
@override
Future<void> open(Media media, {bool play = true}) async {
_checkDisposed();
await _ensureInitialized();
// Show the video layer
await _methodChannel.invokeMethod('setVisible', {'visible': true});
// Set start position if provided (must be set before loading file)
if (media.start != null && media.start!.inSeconds > 0) {
await setProperty('start', media.start!.inSeconds.toString());
} else {
// Reset start position if not resuming
await setProperty('start', 'none');
}
await command(['loadfile', media.uri, 'replace']);
if (!play) {
await setProperty('pause', 'yes');
}
}
@override
Future<void> play() async {
_checkDisposed();
await setProperty('pause', 'no');
}
@override
Future<void> pause() async {
_checkDisposed();
await setProperty('pause', 'yes');
}
@override
Future<void> playOrPause() async {
_checkDisposed();
if (_state.playing) {
await pause();
} else {
await play();
}
}
@override
Future<void> stop() async {
_checkDisposed();
await command(['stop']);
await _methodChannel.invokeMethod('setVisible', {'visible': false});
}
@override
Future<void> seek(Duration position) async {
_checkDisposed();
await command([
'seek',
(position.inMilliseconds / 1000.0).toString(),
'absolute',
]);
}
// ============================================
// Track Selection
// ============================================
@override
Future<void> selectAudioTrack(AudioTrack track) async {
_checkDisposed();
await setProperty('aid', track.id);
}
@override
Future<void> selectSubtitleTrack(SubtitleTrack track) async {
_checkDisposed();
await setProperty('sid', track.id);
}
@override
Future<void> addSubtitleTrack({
required String uri,
String? title,
String? language,
bool select = false,
}) async {
_checkDisposed();
final args = ['sub-add', uri, select ? 'select' : 'auto'];
if (title != null) args.add('title=$title');
if (language != null) args.add('lang=$language');
await command(args);
}
// ============================================
// Volume and Rate
// ============================================
@override
Future<void> setVolume(double volume) async {
_checkDisposed();
await setProperty('volume', volume.toString());
}
@override
Future<void> setRate(double rate) async {
_checkDisposed();
await setProperty('speed', rate.toString());
}
@override
Future<void> setAudioDevice(AudioDevice device) async {
_checkDisposed();
await setProperty('audio-device', device.name);
}
// ============================================
// MPV Properties
// ============================================
@override
Future<void> setProperty(String name, String value) async {
_checkDisposed();
await _ensureInitialized();
await _methodChannel.invokeMethod('setProperty', {
'name': name,
'value': value,
});
}
@override
Future<String?> getProperty(String name) async {
_checkDisposed();
await _ensureInitialized();
return await _methodChannel.invokeMethod<String>('getProperty', {
'name': name,
});
}
@override
Future<void> command(List<String> args) async {
_checkDisposed();
await _ensureInitialized();
await _methodChannel.invokeMethod('command', {'args': args});
}
// ============================================
// Passthrough
// ============================================
@override
Future<void> setAudioPassthrough(bool enabled) async {
_checkDisposed();
if (enabled) {
await setProperty('audio-spdif', 'ac3,eac3,dts,dts-hd,truehd');
await setProperty('audio-exclusive', 'yes');
} else {
await setProperty('audio-spdif', '');
await setProperty('audio-exclusive', 'no');
}
}
// ============================================
// Visibility
// ============================================
@override
Future<bool> setVisible(bool visible) async {
_checkDisposed();
try {
await _methodChannel.invokeMethod('setVisible', {'visible': visible});
return true;
} catch (e) {
_errorController.add('Failed to set visibility: $e');
return false;
}
}
@override
Future<void> setControlsVisible(bool visible) async {
// No-op on most platforms. Override on Linux for transparency workaround.
}
@override
Future<void> updateFrame() async {
_checkDisposed();
if (!_initialized) return;
// Only iOS and macOS use Metal layer that needs frame updates
if (Platform.isIOS || Platform.isMacOS) {
await _methodChannel.invokeMethod('updateFrame');
}
}
// ============================================
// Lifecycle
// ============================================
@override
Future<void> dispose() async {
if (_disposed) return;
_disposed = true;
await _eventSubscription?.cancel();
await _methodChannel.invokeMethod('dispose');
await _playingController.close();
await _completedController.close();
await _bufferingController.close();
await _positionController.close();
await _durationController.close();
await _bufferController.close();
await _volumeController.close();
await _rateController.close();
await _tracksController.close();
await _trackController.close();
await _logController.close();
await _errorController.close();
await _audioDeviceController.close();
await _audioDevicesController.close();
}
}
+113
View File
@@ -0,0 +1,113 @@
import '../models/audio_device.dart';
import '../models/tracks.dart';
import '../models/track_selection.dart';
/// Immutable snapshot of the current player state.
///
/// This class provides synchronous access to the player's current state.
/// For reactive updates, use [PlayerStreams].
class PlayerState {
/// Whether playback is currently active.
final bool playing;
/// Whether the media has completed playback.
final bool completed;
/// Whether the player is currently buffering.
final bool buffering;
/// Current playback position.
final Duration position;
/// Total duration of the media.
final Duration duration;
/// Amount of media buffered ahead of current position.
final Duration buffer;
/// Current volume level (0.0 to 100.0).
final double volume;
/// Current playback rate (1.0 = normal speed).
final double rate;
/// Available tracks in the media.
final Tracks tracks;
/// Currently selected tracks.
final TrackSelection track;
/// Audio delay/sync offset in seconds.
final double audioDelay;
/// Subtitle delay/sync offset in seconds.
final double subtitleDelay;
/// Whether audio passthrough is currently enabled.
final bool audioPassthrough;
/// Current audio output device.
final AudioDevice audioDevice;
/// Available audio output devices.
final List<AudioDevice> audioDevices;
const PlayerState({
this.playing = false,
this.completed = false,
this.buffering = false,
this.position = Duration.zero,
this.duration = Duration.zero,
this.buffer = Duration.zero,
this.volume = 100.0,
this.rate = 1.0,
this.tracks = const Tracks(),
this.track = const TrackSelection(),
this.audioDelay = 0.0,
this.subtitleDelay = 0.0,
this.audioPassthrough = false,
this.audioDevice = AudioDevice.auto,
this.audioDevices = const [],
});
/// Creates a copy with the given fields replaced.
PlayerState copyWith({
bool? playing,
bool? completed,
bool? buffering,
Duration? position,
Duration? duration,
Duration? buffer,
double? volume,
double? rate,
Tracks? tracks,
TrackSelection? track,
double? audioDelay,
double? subtitleDelay,
bool? audioPassthrough,
AudioDevice? audioDevice,
List<AudioDevice>? audioDevices,
}) {
return PlayerState(
playing: playing ?? this.playing,
completed: completed ?? this.completed,
buffering: buffering ?? this.buffering,
position: position ?? this.position,
duration: duration ?? this.duration,
buffer: buffer ?? this.buffer,
volume: volume ?? this.volume,
rate: rate ?? this.rate,
tracks: tracks ?? this.tracks,
track: track ?? this.track,
audioDelay: audioDelay ?? this.audioDelay,
subtitleDelay: subtitleDelay ?? this.subtitleDelay,
audioPassthrough: audioPassthrough ?? this.audioPassthrough,
audioDevice: audioDevice ?? this.audioDevice,
audioDevices: audioDevices ?? this.audioDevices,
);
}
@override
String toString() =>
'PlayerState(playing: $playing, position: $position, duration: $duration)';
}
+69
View File
@@ -0,0 +1,69 @@
import '../models/audio_device.dart';
import '../models/player_log.dart';
import '../models/tracks.dart';
import '../models/track_selection.dart';
/// Reactive streams for player state changes.
///
/// Subscribe to these streams to receive updates when the player state changes.
/// For synchronous state access, use [PlayerState].
class PlayerStreams {
/// Stream of playing state changes.
final Stream<bool> playing;
/// Stream of completion state changes.
final Stream<bool> completed;
/// Stream of buffering state changes.
final Stream<bool> buffering;
/// Stream of position updates.
final Stream<Duration> position;
/// Stream of duration changes (when media is loaded).
final Stream<Duration> duration;
/// Stream of buffer position updates.
final Stream<Duration> buffer;
/// Stream of volume changes.
final Stream<double> volume;
/// Stream of playback rate changes.
final Stream<double> rate;
/// Stream of available tracks updates.
final Stream<Tracks> tracks;
/// Stream of track selection changes.
final Stream<TrackSelection> track;
/// Stream of log messages from the player.
final Stream<PlayerLog> log;
/// Stream of error messages.
final Stream<String> error;
/// Stream of audio device changes.
final Stream<AudioDevice> audioDevice;
/// Stream of available audio devices.
final Stream<List<AudioDevice>> audioDevices;
const PlayerStreams({
required this.playing,
required this.completed,
required this.buffering,
required this.position,
required this.duration,
required this.buffer,
required this.volume,
required this.rate,
required this.tracks,
required this.track,
required this.log,
required this.error,
required this.audioDevice,
required this.audioDevices,
});
}
+20
View File
@@ -0,0 +1,20 @@
/// Mixin for players that support video rect positioning.
///
/// Players that render video behind the Flutter view (e.g., using
/// native window embedding or GtkGLArea) implement this mixin to
/// receive layout updates from the [Video] widget.
mixin VideoRectSupport {
/// Updates the video rendering area.
///
/// Called by the [Video] widget when the layout changes.
///
/// [left], [top], [right], [bottom] define the rect in physical pixels.
/// [devicePixelRatio] is the device's pixel ratio for scaling.
Future<void> setVideoRect({
required int left,
required int top,
required int right,
required int bottom,
required double devicePixelRatio,
});
}
+53
View File
@@ -0,0 +1,53 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
/// Utility class for loading font assets on Android for libass subtitle rendering.
///
/// On Android, libass cannot access system fonts through fontconfig, so we need
/// to extract font files from Flutter assets to the app's cache directory.
class AndroidFontLoader {
static const String _fontAssetPath = 'assets/go-noto-current-regular.ttf';
static const String _fontName = 'Go Noto Current-Regular';
/// Loads the subtitle font from assets to the Android cache directory.
/// Returns the directory path containing the font file.
static Future<String?> loadSubtitleFont() async {
try {
// Get the app's cache directory
final cacheDir = await getTemporaryDirectory();
final fontDir = Directory(path.join(cacheDir.path, 'subtitle_fonts'));
// Create fonts directory if it doesn't exist
if (!await fontDir.exists()) {
await fontDir.create(recursive: true);
}
final fontFile = File(
path.join(fontDir.path, 'go-noto-current-regular.ttf'),
);
// Load font from assets and write to cache if it doesn't exist
if (!await fontFile.exists()) {
final fontData = await rootBundle.load(_fontAssetPath);
await fontFile.writeAsBytes(fontData.buffer.asUint8List());
}
return fontDir.path;
} catch (e) {
// Return null if font loading fails - libass will fall back gracefully
if (kDebugMode) {
debugPrint('Failed to load subtitle font: $e');
}
return null;
}
}
/// Returns the font name to be used with libass.
static String get fontName => _fontName;
/// Returns the font asset path.
static String get fontAssetPath => _fontAssetPath;
}
+117
View File
@@ -0,0 +1,117 @@
import 'package:flutter/material.dart';
import '../player/player.dart';
import '../player/video_rect_support.dart';
/// Video widget for displaying player output.
///
/// This widget displays the video output from a [Player] instance
/// and optionally overlays custom controls.
///
/// Example usage:
/// ```dart
/// final player = Player();
///
/// Video(
/// player: player,
/// fit: BoxFit.contain,
/// controls: (context) => MyCustomControls(),
/// )
/// ```
class Video extends StatefulWidget {
/// The player instance.
final Player player;
/// How the video should be inscribed into the widget's box.
final BoxFit fit;
/// Builder for custom video controls overlay.
final Widget Function(BuildContext context)? controls;
/// Background color shown behind the video.
final Color backgroundColor;
const Video({
super.key,
required this.player,
this.fit = BoxFit.contain,
this.controls,
this.backgroundColor = Colors.black,
});
@override
State<Video> createState() => _VideoState();
}
class _VideoState extends State<Video> {
Rect? _lastRect;
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Stack(
fit: StackFit.expand,
children: [
// Video rendering area
_buildVideoSurface(),
// Controls overlay
if (widget.controls != null) widget.controls!(context),
],
),
);
}
Widget _buildVideoSurface() {
// For players that support video rect positioning (Windows, Linux),
// communicate layout changes to the native side.
if (widget.player is VideoRectSupport) {
return LayoutBuilder(
builder: (context, constraints) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateVideoRect(context, constraints);
});
return const SizedBox.expand();
},
);
}
return const SizedBox.expand();
}
void _updateVideoRect(BuildContext context, BoxConstraints constraints) {
final renderBox = context.findRenderObject() as RenderBox?;
if (renderBox == null || !renderBox.hasSize) return;
final position = renderBox.localToGlobal(Offset.zero);
final size = renderBox.size;
final dpr = MediaQuery.of(context).devicePixelRatio;
final newRect = Rect.fromLTWH(
position.dx,
position.dy,
size.width,
size.height,
);
// Only update if the rect has changed significantly
if (_lastRect != null &&
(newRect.left - _lastRect!.left).abs() < 1 &&
(newRect.top - _lastRect!.top).abs() < 1 &&
(newRect.width - _lastRect!.width).abs() < 1 &&
(newRect.height - _lastRect!.height).abs() < 1) {
return;
}
_lastRect = newRect;
// Update the native video rect
(widget.player as VideoRectSupport).setVideoRect(
left: (position.dx * dpr).toInt(),
top: (position.dy * dpr).toInt(),
right: ((position.dx + size.width) * dpr).toInt(),
bottom: ((position.dy + size.height) * dpr).toInt(),
devicePixelRatio: dpr,
);
}
}
+9 -2
View File
@@ -10,13 +10,17 @@ class HiddenLibrariesProvider extends ChangeNotifier {
bool _isInitialized = false;
/// Get an unmodifiable copy of hidden library keys
Set<String> get hiddenLibraryKeys => Set.unmodifiable(_hiddenLibraryKeys);
Set<String> get hiddenLibraryKeys {
if (!_isInitialized) _initialize();
return Set.unmodifiable(_hiddenLibraryKeys);
}
/// Check if the provider has completed initialization
bool get isInitialized => _isInitialized;
HiddenLibrariesProvider() {
_initialize();
// Don't initialize immediately if lazy-loaded
// _initialize() will be called when first accessed
}
/// Initialize the provider by loading hidden libraries from storage
@@ -30,6 +34,7 @@ class HiddenLibrariesProvider extends ChangeNotifier {
/// Hide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> hideLibrary(String libraryKey) async {
if (!_isInitialized) await _initialize();
if (!_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..add(libraryKey);
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
@@ -40,6 +45,7 @@ class HiddenLibrariesProvider extends ChangeNotifier {
/// Unhide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> unhideLibrary(String libraryKey) async {
if (!_isInitialized) await _initialize();
if (_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..remove(libraryKey);
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
@@ -49,6 +55,7 @@ class HiddenLibrariesProvider extends ChangeNotifier {
/// Check if a specific library is hidden
bool isLibraryHidden(String libraryKey) {
if (!_isInitialized) _initialize();
return _hiddenLibraryKeys.contains(libraryKey);
}
+3 -1
View File
@@ -1,6 +1,6 @@
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';
@@ -67,6 +67,7 @@ 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();
}
@@ -79,6 +80,7 @@ class MultiServerProvider extends ChangeNotifier {
}) 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',
);
+1 -1
View File
@@ -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
///
+1 -1
View File
@@ -1,5 +1,5 @@
import 'package:flutter/foundation.dart';
import '../client/plex_client.dart';
import '../services/plex_client.dart';
import '../utils/app_logger.dart';
class PlexClientProvider extends ChangeNotifier {
+38 -14
View File
@@ -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();
}
}
+10 -1
View File
@@ -7,7 +7,7 @@ import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../widgets/pin_entry_dialog.dart';
import '../screens/profile/pin_entry_dialog.dart';
import 'plex_client_provider.dart';
class UserProfileProvider extends ChangeNotifier {
@@ -16,6 +16,7 @@ class UserProfileProvider extends ChangeNotifier {
PlexUserProfile? _profileSettings;
bool _isLoading = false;
String? _error;
bool _isInitialized = false;
PlexHome? get home => _home;
PlexHomeUser? get currentUser => _currentUser;
@@ -56,6 +57,12 @@ class UserProfileProvider extends ChangeNotifier {
}
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();
@@ -90,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(
@@ -100,6 +108,7 @@ class UserProfileProvider extends ChangeNotifier {
// Ensure services are null on failure
_authService = null;
_storageService = null;
_isInitialized = false; // Allow retry on failure
}
}
+69 -39
View File
@@ -50,8 +50,10 @@ class _AuthScreenState extends State<AuthScreen> {
try {
// Fetch all servers for this user
final servers = await _authService.fetchServers(plexToken);
final storage = await StorageService.getInstance();
if (servers.isEmpty) {
await storage.clearCredentials();
setState(() {
_isAuthenticating = false;
_errorMessage = t.serverSelection.noServersFound;
@@ -60,7 +62,6 @@ class _AuthScreenState extends State<AuthScreen> {
}
// Save all servers to registry and enable them
final storage = await StorageService.getInstance();
final registry = ServerRegistry(storage);
await registry.saveServers(servers);
@@ -348,17 +349,7 @@ class _AuthScreenState extends State<AuthScreen> {
),
),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
_buildRetryButton(),
] else ...[
// Browser auth flow - show spinner and waiting message
const Center(child: CircularProgressIndicator()),
@@ -368,17 +359,7 @@ class _AuthScreenState extends State<AuthScreen> {
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
_buildRetryButton(),
],
] else ...[
// Initial state buttons
@@ -455,24 +436,57 @@ class _AuthScreenState extends State<AuthScreen> {
),
const SizedBox(height: 48),
if (_isAuthenticating) ...[
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
Text(
t.auth.waitingForAuth,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
if (_useQrFlow && _qrAuthUrl != null) ...[
// QR code flow - show QR code and scan instruction
Text(
t.auth.scanQRCodeInstruction,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: QrImageView(
data: _qrAuthUrl!,
size: 200,
version: QrVersions.auto,
backgroundColor: Colors.white,
),
),
),
child: Text(t.auth.retry),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
] else ...[
// Browser auth flow - show spinner and waiting message
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
Text(
t.auth.waitingForAuth,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
],
] else ...[
// add QR button here
ElevatedButton(
@@ -530,4 +544,20 @@ class _AuthScreenState extends State<AuthScreen> {
),
);
}
Widget _buildRetryButton() {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
),
child: Text(t.auth.retry),
),
],
);
}
}
@@ -1,6 +1,6 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../../services/plex_client.dart';
import '../models/plex_metadata.dart';
import '../providers/multi_server_provider.dart';
import '../utils/provider_extensions.dart';
+506 -358
View File
@@ -1,30 +1,33 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../services/plex_client.dart';
import '../utils/plex_image_helper.dart';
import '../models/plex_metadata.dart';
import '../models/plex_hub.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 '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/user_avatar_widget.dart';
import '../widgets/horizontal_scroll_with_arrows.dart';
import 'profile/user_avatar_widget.dart';
import '../widgets/hub_section.dart';
import 'profile_switch_screen.dart';
import '../widgets/hub_navigation_controller.dart';
import 'profile/profile_switch_screen.dart';
import '../providers/user_profile_provider.dart';
import '../providers/settings_provider.dart';
import '../mixins/refreshable.dart';
import '../i18n/strings.g.dart';
import '../mixins/item_updatable.dart';
import '../utils/app_logger.dart';
import '../utils/keyboard_utils.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/content_rating_formatter.dart';
import 'auth_screen.dart';
import 'main_screen.dart';
class DiscoverScreen extends StatefulWidget {
final VoidCallback? onBecameVisible;
@@ -56,6 +59,8 @@ class _DiscoverScreenState extends State<DiscoverScreen>
List<PlexMetadata> _onDeck = [];
List<PlexHub> _hubs = [];
bool _isLoading = true;
bool _isInitialLoad = true;
bool _areHubsLoading = true;
String? _errorMessage;
final PageController _heroController = PageController();
final ScrollController _scrollController = ScrollController();
@@ -63,6 +68,10 @@ class _DiscoverScreenState extends State<DiscoverScreen>
Timer? _autoScrollTimer;
late AnimationController _indicatorAnimationController;
bool _isAutoScrollPaused = false;
final HubNavigationController _hubNavigationController =
HubNavigationController();
late final FocusNode _heroFocusNode;
bool _heroIsFocused = false;
/// Get the correct PlexClient for an item's server
PlexClient _getClientForItem(PlexMetadata? item) {
@@ -90,16 +99,89 @@ class _DiscoverScreenState extends State<DiscoverScreen>
vsync: this,
duration: _heroAutoScrollDuration,
);
_heroFocusNode = FocusNode(debugLabel: 'HeroSection');
_heroFocusNode.addListener(_handleHeroFocusChange);
_loadContent();
_startAutoScroll();
}
void _handleHeroFocusChange() {
if (_heroIsFocused != _heroFocusNode.hasFocus) {
setState(() {
_heroIsFocused = _heroFocusNode.hasFocus;
});
if (_heroFocusNode.hasFocus) {
// Scroll to the very top when hero is focused
_scrollController.animateTo(
0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
}
}
}
/// Handle back key press - focus bottom navigation
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
BackNavigationScope.of(context)?.focusBottomNav();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
KeyEventResult _handleHeroKeyEvent(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent) {
// Enter/Space to play current hero item
if (isKeyboardActivationKey(event.logicalKey)) {
if (_onDeck.isNotEmpty && _currentHeroIndex < _onDeck.length) {
navigateToVideoPlayer(context, metadata: _onDeck[_currentHeroIndex]);
return KeyEventResult.handled;
}
}
// Left arrow to go to previous hero item
if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
if (_onDeck.isNotEmpty && _currentHeroIndex > 0) {
_heroController.previousPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
return KeyEventResult.handled;
}
}
// Right arrow to go to next hero item
if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
if (_onDeck.isNotEmpty && _currentHeroIndex < _onDeck.length - 1) {
_heroController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
return KeyEventResult.handled;
}
}
// Down arrow to navigate to first hub section
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
// Try to navigate to the first hub section
if (_hubNavigationController.navigateToAdjacentHub('_hero_', 1)) {
return KeyEventResult.handled;
}
}
}
return KeyEventResult.ignored;
}
@override
void dispose() {
_autoScrollTimer?.cancel();
_heroController.dispose();
_scrollController.dispose();
_indicatorAnimationController.dispose();
_hubNavigationController.dispose();
_heroFocusNode.removeListener(_handleHeroFocusChange);
_heroFocusNode.dispose();
super.dispose();
}
@@ -193,6 +275,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
appLogger.d('Loading discover content from all servers');
setState(() {
_isLoading = true;
_areHubsLoading = true;
_errorMessage = null;
});
@@ -207,16 +290,53 @@ class _DiscoverScreenState extends State<DiscoverScreen>
throw Exception('No servers available');
}
// Fetch on deck and hubs from all servers in parallel for optimal performance
final results = await Future.wait([
multiServerProvider.aggregationService.getOnDeckFromAllServers(
limit: 20,
),
multiServerProvider.aggregationService.getHubsFromAllServers(),
]);
// Start OnDeck and libraries fetch in parallel
final onDeckFuture = multiServerProvider.aggregationService
.getOnDeckFromAllServers(limit: 20);
final librariesFuture = multiServerProvider.aggregationService
.getLibrariesFromAllServersGrouped();
final onDeck = results[0] as List<PlexMetadata>;
final allHubs = results[1] as List<PlexHub>;
// Wait for OnDeck to complete and show it immediately
final onDeck = await onDeckFuture;
setState(() {
_onDeck = onDeck;
_isLoading = false; // Show content, but hubs still loading
// Reset hero index to avoid sync issues
_currentHeroIndex = 0;
});
// Focus the hero on initial load
if (_isInitialLoad && onDeck.isNotEmpty) {
_isInitialLoad = false;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
_heroFocusNode.requestFocus();
}
});
}
// Sync PageController to first page after OnDeck loads
if (_heroController.hasClients && onDeck.isNotEmpty) {
_heroController.jumpToPage(0);
}
// Wait for libraries and then fetch hubs
final librariesByServer = await librariesFuture;
// Get hidden libraries to filter from hubs
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(
context,
listen: false,
);
// Fetch hubs using the pre-fetched libraries and hidden keys
final allHubs = await multiServerProvider.aggregationService
.getHubsFromAllServers(
librariesByServer: librariesByServer,
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
);
// Filter out duplicate hubs that we already fetch separately
final filteredHubs = allHubs.where((hub) {
@@ -233,25 +353,17 @@ class _DiscoverScreenState extends State<DiscoverScreen>
'Received ${onDeck.length} on deck items and ${filteredHubs.length} hubs from all servers',
);
setState(() {
_onDeck = onDeck;
_hubs = filteredHubs;
_isLoading = false;
// Reset hero index to avoid sync issues
_currentHeroIndex = 0;
_areHubsLoading = false;
});
// Sync PageController to first page after data loads
if (_heroController.hasClients && onDeck.isNotEmpty) {
_heroController.jumpToPage(0);
}
appLogger.d('Discover content loaded successfully');
} catch (e) {
appLogger.e('Failed to load discover content', error: e);
setState(() {
_errorMessage = 'Failed to load content: $e';
_isLoading = false;
_areHubsLoading = false;
});
}
}
@@ -305,6 +417,13 @@ class _DiscoverScreenState extends State<DiscoverScreen>
_loadContent();
}
/// Focus the hero section (for keyboard navigation)
void focusHero() {
if (_onDeck.isNotEmpty) {
_heroFocusNode.requestFocus();
}
}
/// Get icon for hub based on its title
IconData _getHubIcon(String title) {
final lowerTitle = title.toLowerCase();
@@ -485,291 +604,360 @@ class _DiscoverScreenState extends State<DiscoverScreen>
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: CustomScrollView(
controller: _scrollController,
slivers: [
DesktopSliverAppBar(
title: Text(t.discover.title),
floating: true,
pinned: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
surfaceTintColor: Colors.transparent,
shadowColor: Colors.transparent,
scrolledUnderElevation: 0,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadContent,
),
Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
return PopupMenuButton<String>(
icon: userProvider.currentUser?.thumb != null
? UserAvatarWidget(
user: userProvider.currentUser!,
size: 32,
showIndicators: false,
)
: const Icon(Icons.account_circle, size: 32),
onSelected: (value) {
if (value == 'switch_profile') {
_handleSwitchProfile(context);
} else if (value == 'logout') {
_handleLogout();
}
},
itemBuilder: (context) => [
// Only show Switch Profile if multiple users available
if (userProvider.hasMultipleUsers)
PopupMenuItem(
value: 'switch_profile',
child: Row(
children: [
Icon(Icons.people),
SizedBox(width: 8),
Text(t.discover.switchProfile),
],
child: Focus(
onKeyEvent: _handleBackKey,
child: HubNavigationScope(
controller: _hubNavigationController,
child: CustomScrollView(
controller: _scrollController,
slivers: [
DesktopSliverAppBar(
title: Text(t.discover.title),
floating: true,
pinned: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
surfaceTintColor: Colors.transparent,
shadowColor: Colors.transparent,
scrolledUnderElevation: 0,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadContent,
),
Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
return PopupMenuButton<String>(
icon: userProvider.currentUser?.thumb != null
? UserAvatarWidget(
user: userProvider.currentUser!,
size: 32,
showIndicators: false,
)
: const Icon(Icons.account_circle, size: 32),
onSelected: (value) {
if (value == 'switch_profile') {
_handleSwitchProfile(context);
} else if (value == 'logout') {
_handleLogout();
}
},
itemBuilder: (context) => [
// Only show Switch Profile if multiple users available
if (userProvider.hasMultipleUsers)
PopupMenuItem(
value: 'switch_profile',
child: Row(
children: [
Icon(Icons.people),
SizedBox(width: 8),
Text(t.discover.switchProfile),
],
),
),
PopupMenuItem(
value: 'logout',
child: Row(
children: [
Icon(Icons.logout),
SizedBox(width: 8),
Text(t.discover.logout),
],
),
),
],
);
},
),
],
),
if (_isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
),
if (_errorMessage != null)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: Colors.red,
),
PopupMenuItem(
value: 'logout',
child: Row(
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadContent,
child: Text(t.common.retry),
),
],
),
),
),
if (!_isLoading && _errorMessage == null) ...[
// Hero Section (Continue Watching)
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (_onDeck.isNotEmpty &&
settingsProvider.showHeroSection) {
return _buildHeroSection();
}
return const SliverToBoxAdapter(child: SizedBox.shrink());
},
),
// On Deck / Continue Watching
if (_onDeck.isNotEmpty)
SliverToBoxAdapter(
child: HubSection(
hub: PlexHub(
hubKey: 'continue_watching',
title: t.discover.continueWatching,
type: 'mixed',
hubIdentifier: '_continue_watching_',
size: _onDeck.length,
more: false,
items: _onDeck,
),
icon: Icons.play_circle_outline,
onRefresh: updateItem,
onRemoveFromContinueWatching: _refreshContinueWatching,
isInContinueWatching: true,
navigationOrder: 1, // After hero
),
),
// Recommendation Hubs (Trending, Top in Genre, etc.)
for (int i = 0; i < _hubs.length; i++)
SliverToBoxAdapter(
child: HubSection(
hub: _hubs[i],
icon: _getHubIcon(_hubs[i].title),
onRefresh: updateItem,
navigationOrder: 2 + i, // After continue watching
),
),
// Show loading skeleton for hubs while they're loading
if (_areHubsLoading && _hubs.isEmpty)
for (int i = 0; i < 3; i++)
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.logout),
SizedBox(width: 8),
Text(t.discover.logout),
// Hub title skeleton
Container(
width: 200,
height: 24,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(height: 16),
// Hub items skeleton
SizedBox(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 5,
itemBuilder: (context, index) {
return Container(
margin: const EdgeInsets.only(right: 12),
width: 140,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
);
},
),
),
],
),
),
],
);
},
),
),
if (_onDeck.isEmpty && _hubs.isEmpty && !_areHubsLoading)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.movie_outlined,
size: 64,
color: Colors.grey,
),
SizedBox(height: 16),
Text(t.discover.noContentAvailable),
SizedBox(height: 8),
Text(
t.discover.addMediaToLibraries,
style: TextStyle(color: Colors.grey),
),
],
),
),
),
const SliverToBoxAdapter(child: SizedBox(height: 24)),
],
],
),
if (_isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
),
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: _loadContent,
child: Text(t.common.retry),
),
],
),
),
),
if (!_isLoading && _errorMessage == null) ...[
// Hero Section (Continue Watching)
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (_onDeck.isNotEmpty && settingsProvider.showHeroSection) {
return _buildHeroSection();
}
return const SliverToBoxAdapter(child: SizedBox.shrink());
},
),
// On Deck / Continue Watching
if (_onDeck.isNotEmpty) ...[
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 24, 16, 8),
child: Row(
children: [
const Icon(Icons.play_circle_outline),
const SizedBox(width: 8),
Text(
t.discover.continueWatching,
style: Theme.of(context).textTheme.titleLarge,
),
],
),
),
),
_buildHorizontalList(
_onDeck,
isLarge: false,
isInContinueWatching: true,
),
],
// Recommendation Hubs (Trending, Top in Genre, etc.)
for (final hub in _hubs)
SliverToBoxAdapter(
child: HubSection(
hub: hub,
icon: _getHubIcon(hub.title),
onRefresh: updateItem,
),
),
if (_onDeck.isEmpty && _hubs.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.movie_outlined,
size: 64,
color: Colors.grey,
),
SizedBox(height: 16),
Text(t.discover.noContentAvailable),
SizedBox(height: 8),
Text(
t.discover.addMediaToLibraries,
style: TextStyle(color: Colors.grey),
),
],
),
),
),
const SliverToBoxAdapter(child: SizedBox(height: 24)),
],
],
),
),
),
);
}
Widget _buildHeroSection() {
return SliverToBoxAdapter(
child: SizedBox(
height: 500,
child: Stack(
children: [
PageView.builder(
controller: _heroController,
itemCount: _onDeck.length,
onPageChanged: (index) {
// Validate index is within bounds before updating
if (index >= 0 && index < _onDeck.length) {
setState(() {
_currentHeroIndex = index;
});
_resetAutoScrollTimer();
}
},
itemBuilder: (context, index) {
return _buildHeroItem(_onDeck[index]);
},
),
// Page indicators with animated progress and pause/play button
Positioned(
bottom: 16,
left: -26,
right: 0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Pause/Play button
GestureDetector(
onTap: () {
if (_isAutoScrollPaused) {
_resumeAutoScroll();
} else {
_pauseAutoScroll();
}
},
child: Icon(
_isAutoScrollPaused ? Icons.play_arrow : Icons.pause,
color: Colors.white,
size: 18,
semanticLabel:
'${_isAutoScrollPaused ? t.discover.play : t.discover.pause} auto-scroll',
),
),
// Spacer to separate indicators from button
const SizedBox(width: 8),
// Page indicators (limited to 5 dots)
...() {
final range = _getVisibleDotRange();
return List.generate(range.end - range.start + 1, (i) {
final index = range.start + i;
final isActive = _currentHeroIndex == index;
final dotSize = _getDotSize(
index,
range.start,
range.end,
);
// Register hero section with navigation controller
// This allows pressing up from first hub to return to hero
_hubNavigationController.register(
HubSectionRegistration(
hubId: '_hero_',
itemCount: 1,
focusItem: (_) => _heroFocusNode.requestFocus(),
order: 0, // Hero is first
),
);
if (isActive) {
// Animated progress indicator for active page
return AnimatedBuilder(
animation: _indicatorAnimationController,
builder: (context, child) {
// Fill width animates based on dot size
final maxWidth =
dotSize * 3; // 24px for normal, 15px for small
final fillWidth =
dotSize +
((maxWidth - dotSize) *
_indicatorAnimationController.value);
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
margin: const EdgeInsets.symmetric(horizontal: 4),
width: maxWidth,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(
dotSize / 2,
return SliverToBoxAdapter(
child: Focus(
focusNode: _heroFocusNode,
onKeyEvent: _handleHeroKeyEvent,
child: SizedBox(
height: 500,
child: Stack(
children: [
PageView.builder(
controller: _heroController,
itemCount: _onDeck.length,
onPageChanged: (index) {
// Validate index is within bounds before updating
if (index >= 0 && index < _onDeck.length) {
setState(() {
_currentHeroIndex = index;
});
_resetAutoScrollTimer();
}
},
itemBuilder: (context, index) {
return _buildHeroItem(_onDeck[index]);
},
),
// Page indicators with animated progress and pause/play button
Positioned(
bottom: 16,
left: -26,
right: 0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Pause/Play button
GestureDetector(
onTap: () {
if (_isAutoScrollPaused) {
_resumeAutoScroll();
} else {
_pauseAutoScroll();
}
},
child: Icon(
_isAutoScrollPaused ? Icons.play_arrow : Icons.pause,
color: Colors.white,
size: 18,
semanticLabel:
'${_isAutoScrollPaused ? t.discover.play : t.discover.pause} auto-scroll',
),
),
// Spacer to separate indicators from button
const SizedBox(width: 8),
// Page indicators (limited to 5 dots)
...() {
final range = _getVisibleDotRange();
return List.generate(range.end - range.start + 1, (i) {
final index = range.start + i;
final isActive = _currentHeroIndex == index;
final dotSize = _getDotSize(
index,
range.start,
range.end,
);
if (isActive) {
// Animated progress indicator for active page
return AnimatedBuilder(
animation: _indicatorAnimationController,
builder: (context, child) {
// Fill width animates based on dot size
final maxWidth =
dotSize *
3; // 24px for normal, 15px for small
final fillWidth =
dotSize +
((maxWidth - dotSize) *
_indicatorAnimationController.value);
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
margin: const EdgeInsets.symmetric(
horizontal: 4,
),
),
child: Align(
alignment: Alignment.centerLeft,
child: Container(
width: fillWidth,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(
dotSize / 2,
width: maxWidth,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(
dotSize / 2,
),
),
child: Align(
alignment: Alignment.centerLeft,
child: Container(
width: fillWidth,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(
dotSize / 2,
),
),
),
),
),
);
},
);
} else {
// Static indicator for inactive pages
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
margin: const EdgeInsets.symmetric(horizontal: 4),
width: dotSize,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(dotSize / 2),
),
);
}
});
}(),
],
);
},
);
} else {
// Static indicator for inactive pages
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
margin: const EdgeInsets.symmetric(horizontal: 4),
width: dotSize,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(dotSize / 2),
),
);
}
});
}(),
],
),
),
),
],
],
),
),
),
);
@@ -843,10 +1031,18 @@ class _DiscoverScreenState extends State<DiscoverScreen>
child: Builder(
builder: (context) {
final client = _getClientForItem(heroItem);
final mediaQuery = MediaQuery.of(context);
final imageUrl = PlexImageHelper.getOptimizedImageUrl(
client: client,
thumbPath: heroItem.art ?? heroItem.grandparentArt,
maxWidth: mediaQuery.size.width,
maxHeight: mediaQuery.size.height * 0.7,
devicePixelRatio: mediaQuery.devicePixelRatio,
imageType: ImageType.art,
);
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
heroItem.art ?? heroItem.grandparentArt,
),
imageUrl: imageUrl,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
@@ -909,12 +1105,26 @@ class _DiscoverScreenState extends State<DiscoverScreen>
child: Builder(
builder: (context) {
final client = _getClientForItem(heroItem);
final dpr = MediaQuery.of(
context,
).devicePixelRatio;
final logoUrl =
PlexImageHelper.getOptimizedImageUrl(
client: client,
thumbPath: heroItem.clearLogo,
maxWidth: 400,
maxHeight: 120,
devicePixelRatio: dpr,
imageType: ImageType.logo,
);
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
heroItem.clearLogo,
),
imageUrl: logoUrl,
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
memCacheWidth: (400 * dpr)
.clamp(200, 800)
.round(),
alignment: isLargeScreen
? Alignment.bottomLeft
: Alignment.bottomCenter,
@@ -1166,66 +1376,4 @@ class _DiscoverScreenState extends State<DiscoverScreen>
),
);
}
Widget _buildHorizontalList(
List<PlexMetadata> items, {
bool isLarge = false,
bool isInContinueWatching = false,
}) {
return SliverToBoxAdapter(
child: LayoutBuilder(
builder: (context, constraints) {
// Responsive card width based on screen size
// Match Libraries screen sizing (190px baseline)
final screenWidth = constraints.maxWidth;
final cardWidth = screenWidth > 1600
? 220.0
: screenWidth > 1200
? 200.0
: screenWidth > 800
? 190.0
: 160.0;
// MediaCard has 8px padding on all sides (16px total horizontally)
// So actual poster width is cardWidth - 16
final posterWidth = cardWidth - 16;
// 2:3 poster aspect ratio (height is 1.5x width)
final posterHeight = posterWidth * 1.5;
// Container height = poster + padding + spacing + text
// 8px top padding + posterHeight + 4px spacing + ~26px text + 8px bottom padding
final containerHeight = posterHeight + 46;
return SizedBox(
height: containerHeight,
child: HorizontalScrollWithArrows(
builder: (scrollController) => ListView.builder(
controller: scrollController,
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 12),
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
child: MediaCard(
key: Key(item.ratingKey),
item: item,
width: cardWidth,
height: posterHeight,
onRefresh: updateItem,
onRemoveFromContinueWatching: isInContinueWatching
? _refreshContinueWatching
: null,
forceGridMode: true,
isInContinueWatching: isInContinueWatching,
),
);
},
),
),
);
},
),
);
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../../services/plex_client.dart';
import '../models/plex_hub.dart';
import '../models/plex_metadata.dart';
import '../models/plex_sort.dart';
@@ -10,7 +10,7 @@ import '../utils/app_logger.dart';
import '../utils/grid_cross_axis_extent.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/sort_bottom_sheet.dart';
import 'libraries/sort_bottom_sheet.dart';
import '../mixins/refreshable.dart';
import '../i18n/strings.g.dart';
@@ -0,0 +1,86 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_metadata.dart';
import '../../providers/settings_provider.dart';
import '../../services/settings_service.dart' show ViewMode;
import '../../utils/grid_size_calculator.dart';
import '../../widgets/media_card.dart';
/// A widget that automatically switches between grid and list view
/// based on user settings, providing a consistent layout pattern
/// across all library screens
class AdaptiveMediaGrid extends StatelessWidget {
/// The list of media items to display
final List<PlexMetadata> items;
/// Callback when the list needs to be refreshed
final VoidCallback? onRefresh;
/// Optional padding around the grid/list
final EdgeInsets padding;
/// Child aspect ratio for grid items (width / height)
final double childAspectRatio;
/// Optional focus node for the first item (for keyboard navigation)
final FocusNode? firstItemFocusNode;
const AdaptiveMediaGrid({
super.key,
required this.items,
this.onRefresh,
this.padding = const EdgeInsets.fromLTRB(8, 8, 8, 8),
this.childAspectRatio = 2 / 3.3,
this.firstItemFocusNode,
});
@override
Widget build(BuildContext context) {
return Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return FocusTraversalGroup(
child: ListView.builder(
padding: padding,
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onListRefresh: onRefresh,
focusNode: index == 0 ? firstItemFocusNode : null,
);
},
),
);
} else {
return FocusTraversalGroup(
child: GridView.builder(
padding: padding,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: childAspectRatio,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onListRefresh: onRefresh,
focusNode: index == 0 ? firstItemFocusNode : null,
);
},
),
);
}
},
);
}
}
@@ -1,5 +1,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,320 @@
import 'package:flutter/material.dart';
import '../../models/plex_filter.dart';
import '../../widgets/app_bar_back_button.dart';
import '../../widgets/bottom_sheet_header.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/keyboard_utils.dart';
import '../../i18n/strings.g.dart';
class FiltersBottomSheet extends StatefulWidget {
final List<PlexFilter> filters;
final Map<String, String> selectedFilters;
final Function(Map<String, String>) onFiltersChanged;
final String serverId;
const FiltersBottomSheet({
super.key,
required this.filters,
required this.selectedFilters,
required this.onFiltersChanged,
required this.serverId,
});
@override
State<FiltersBottomSheet> createState() => _FiltersBottomSheetState();
}
class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
PlexFilter? _currentFilter;
List<PlexFilterValue> _filterValues = [];
bool _isLoadingValues = false;
final Map<String, String> _tempSelectedFilters = {};
final Map<String, String> _filterDisplayNames = {}; // Cache for display names
late List<PlexFilter> _sortedFilters;
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'FilterFirstItem',
);
final FocusNode _filterValuesFocusNode = FocusNode(
debugLabel: 'FilterValuesFirstItem',
);
@override
void initState() {
super.initState();
_tempSelectedFilters.addAll(widget.selectedFilters);
_sortFilters();
// Focus the first item after build
WidgetsBinding.instance.addPostFrameCallback((_) {
_firstItemFocusNode.requestFocus();
});
}
@override
void dispose() {
_firstItemFocusNode.dispose();
_filterValuesFocusNode.dispose();
super.dispose();
}
void _sortFilters() {
// Separate boolean filters (toggles) from regular filters
final booleanFilters = widget.filters
.where((f) => f.filterType == 'boolean')
.toList();
final regularFilters = widget.filters
.where((f) => f.filterType != 'boolean')
.toList();
// Combine with boolean filters first
_sortedFilters = [...booleanFilters, ...regularFilters];
}
bool _isBooleanFilter(PlexFilter filter) {
return filter.filterType == 'boolean';
}
Future<void> _loadFilterValues(PlexFilter filter) async {
setState(() {
_currentFilter = filter;
_isLoadingValues = true;
});
try {
final client = context.getClientForServer(widget.serverId);
final values = await client.getFilterValues(filter.key);
setState(() {
_filterValues = values;
_isLoadingValues = false;
});
// Focus the first filter value after loading
WidgetsBinding.instance.addPostFrameCallback((_) {
_filterValuesFocusNode.requestFocus();
});
} catch (e) {
setState(() {
_filterValues = [];
_isLoadingValues = false;
});
}
}
void _goBack() {
setState(() {
_currentFilter = null;
_filterValues = [];
});
}
void _applyFilters() {
widget.onFiltersChanged(_tempSelectedFilters);
Navigator.pop(context);
}
/// Handle back key - go back to main view or close sheet
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
if (_currentFilter != null) {
// Go back to main filters view
_goBack();
} else {
// Close the bottom sheet
Navigator.pop(context);
}
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
String _extractFilterValue(String key, String filterName) {
if (key.contains('?')) {
final queryStart = key.indexOf('?');
final queryString = key.substring(queryStart + 1);
final params = Uri.splitQueryString(queryString);
return params[filterName] ?? key;
} else if (key.startsWith('/')) {
return key.split('/').last;
}
return key;
}
@override
Widget build(BuildContext context) {
return Focus(
autofocus: true,
onKeyEvent: _handleBackKey,
child: DraggableScrollableSheet(
initialChildSize: 0.7,
minChildSize: 0.5,
maxChildSize: 0.95,
expand: false,
builder: (context, scrollController) {
if (_currentFilter != null) {
// Show filter options view
return Column(
children: [
// Header with back button
BottomSheetHeader(
title: _currentFilter!.title,
leading: AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: _goBack,
),
),
// Filter options list
if (_isLoadingValues)
const Expanded(
child: Center(child: CircularProgressIndicator()),
)
else
Expanded(
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: _filterValues.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
final isSelected = !_tempSelectedFilters.containsKey(
_currentFilter!.filter,
);
return ListTile(
focusNode: _filterValuesFocusNode,
title: Text(t.libraries.all),
selected: isSelected,
onTap: () {
setState(() {
_tempSelectedFilters.remove(
_currentFilter!.filter,
);
});
_applyFilters();
},
);
}
final value = _filterValues[index - 1];
final filterValue = _extractFilterValue(
value.key,
_currentFilter!.filter,
);
final isSelected =
_tempSelectedFilters[_currentFilter!.filter] ==
filterValue;
return ListTile(
title: Text(value.title),
selected: isSelected,
onTap: () {
setState(() {
_tempSelectedFilters[_currentFilter!.filter] =
filterValue;
// Cache the display name for this filter value
_filterDisplayNames['${_currentFilter!.filter}:$filterValue'] =
value.title;
});
_applyFilters();
},
);
},
),
),
],
);
}
// Show main filters view
return Column(
children: [
// Header
BottomSheetHeader(
title: t.libraries.filters,
leading: const Icon(Icons.filter_alt),
action: _tempSelectedFilters.isNotEmpty
? TextButton.icon(
onPressed: () {
setState(() {
_tempSelectedFilters.clear();
});
_applyFilters();
},
icon: const Icon(Icons.clear_all),
label: Text(t.libraries.clearAll),
)
: null,
),
// All Filters (boolean toggles first, then regular filters)
Expanded(
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: _sortedFilters.length,
itemBuilder: (context, index) {
final filter = _sortedFilters[index];
// Handle boolean filters as switches (unwatched, inProgress, unmatched, hdr, etc.)
if (_isBooleanFilter(filter)) {
final isActive =
_tempSelectedFilters.containsKey(filter.filter) &&
_tempSelectedFilters[filter.filter] == '1';
return SwitchListTile(
focusNode: index == 0 ? _firstItemFocusNode : null,
value: isActive,
onChanged: (value) {
setState(() {
if (value) {
_tempSelectedFilters[filter.filter] = '1';
} else {
_tempSelectedFilters.remove(filter.filter);
}
});
_applyFilters();
},
title: Text(filter.title),
);
}
// Regular navigable filters - show selected value instead of checkmark
final selectedValue = _tempSelectedFilters[filter.filter];
String? displayValue;
if (selectedValue != null) {
// Try to get the cached display name, fall back to the value itself
displayValue =
_filterDisplayNames['${filter.filter}:$selectedValue'] ??
selectedValue;
}
return ListTile(
focusNode: index == 0 ? _firstItemFocusNode : null,
title: Text(filter.title),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (displayValue != null)
Flexible(
child: Text(
displayValue,
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w500,
),
overflow: TextOverflow.ellipsis,
),
),
if (displayValue != null) const SizedBox(width: 8),
const Icon(Icons.chevron_right),
],
),
onTap: () => _loadFilterValues(filter),
);
},
),
),
],
);
},
),
);
}
}
+159
View File
@@ -0,0 +1,159 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../models/plex_metadata.dart';
import '../../utils/keyboard_utils.dart';
/// Individual item in the folder tree
/// Can be either a folder (expandable) or a file (tappable)
class FolderTreeItem extends StatefulWidget {
final PlexMetadata item;
final int depth;
final bool isExpanded;
final bool isFolder;
final void Function({bool isKeyboard})? onTap;
final VoidCallback? onExpand;
final bool isLoading;
const FolderTreeItem({
super.key,
required this.item,
required this.depth,
this.isExpanded = false,
this.isFolder = false,
this.onTap,
this.onExpand,
this.isLoading = false,
});
@override
State<FolderTreeItem> createState() => _FolderTreeItemState();
}
class _FolderTreeItemState extends State<FolderTreeItem> {
bool _isKeyboardActivation = false;
IconData _getIcon() {
if (widget.isFolder) {
return Icons.folder;
}
// File icons based on type
final type = widget.item.type.toLowerCase();
switch (type) {
case 'movie':
return Icons.movie;
case 'show':
return Icons.tv;
case 'season':
return Icons.video_library;
case 'episode':
return Icons.play_circle_outline;
case 'collection':
return Icons.collections;
default:
return Icons.insert_drive_file;
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent && isKeyboardActivationKey(event.logicalKey)) {
_isKeyboardActivation = true;
return KeyEventResult.ignored; // Let InkWell handle the activation
}
return KeyEventResult.ignored;
}
void _handleTap() {
if (widget.isFolder) {
widget.onExpand?.call();
} else {
widget.onTap?.call(isKeyboard: _isKeyboardActivation);
}
_isKeyboardActivation = false;
}
@override
Widget build(BuildContext context) {
final indentation = widget.depth * 24.0;
return Focus(
onKeyEvent: _handleKeyEvent,
child: InkWell(
onTap: _handleTap,
child: Container(
padding: EdgeInsets.only(
left: 16.0 + indentation,
right: 16.0,
top: 12.0,
bottom: 12.0,
),
child: Row(
children: [
// Expand/collapse icon for folders
if (widget.isFolder)
SizedBox(
width: 24,
child: widget.isLoading
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Icon(
widget.isExpanded
? Icons.keyboard_arrow_down
: Icons.keyboard_arrow_right,
size: 20,
),
)
else
const SizedBox(width: 24),
const SizedBox(width: 8),
// File/folder icon
Icon(
_getIcon(),
size: 20,
color: widget.isFolder
? Theme.of(context).colorScheme.primary
: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.7),
),
const SizedBox(width: 12),
// Item title
Expanded(
child: Text(
widget.item.title,
style: TextStyle(
fontSize: 14,
fontWeight: widget.isFolder
? FontWeight.w500
: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
// Additional metadata for files
if (!widget.isFolder && widget.item.year != null)
Text(
widget.item.year.toString(),
style: TextStyle(
fontSize: 12,
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.6),
),
),
],
),
),
),
);
}
}
@@ -1,11 +1,11 @@
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 '../media_detail_screen.dart';
import '../season_detail_screen.dart';
import '../../utils/app_logger.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/video_player_navigation.dart';
import '../../i18n/strings.g.dart';
import 'folder_tree_item.dart';
import 'empty_state_widget.dart';
import 'error_state_widget.dart';
@@ -150,7 +150,10 @@ class _FolderTreeViewState extends State<FolderTreeView> {
}
}
Future<void> _handleItemTap(PlexMetadata item) async {
Future<void> _handleItemTap(
PlexMetadata item, {
bool isKeyboard = false,
}) async {
final itemType = item.type.toLowerCase();
// For episodes, start playback directly
@@ -163,7 +166,8 @@ class _FolderTreeViewState extends State<FolderTreeView> {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SeasonDetailScreen(season: item),
builder: (context) =>
SeasonDetailScreen(season: item, focusFirstEpisode: isKeyboard),
),
);
widget.onRefresh?.call(item.ratingKey);
@@ -215,7 +219,10 @@ class _FolderTreeViewState extends State<FolderTreeView> {
isExpanded: isExpanded,
isLoading: isLoading,
onExpand: isFolder ? () => _toggleFolder(item) : null,
onTap: !isFolder ? () => _handleItemTap(item) : null,
onTap: !isFolder
? ({bool isKeyboard = false}) =>
_handleItemTap(item, isKeyboard: isKeyboard)
: null,
),
);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,164 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../models/plex_sort.dart';
import '../../widgets/bottom_sheet_header.dart';
import '../../utils/keyboard_utils.dart';
import '../../i18n/strings.g.dart';
class SortBottomSheet extends StatefulWidget {
final List<PlexSort> sortOptions;
final PlexSort? selectedSort;
final bool isSortDescending;
final Function(PlexSort, bool) onSortChanged;
final VoidCallback? onClear;
const SortBottomSheet({
super.key,
required this.sortOptions,
required this.selectedSort,
required this.isSortDescending,
required this.onSortChanged,
this.onClear,
});
@override
State<SortBottomSheet> createState() => _SortBottomSheetState();
}
class _SortBottomSheetState extends State<SortBottomSheet> {
late PlexSort? _currentSort;
late bool _currentDescending;
final FocusNode _firstItemFocusNode = FocusNode(debugLabel: 'SortFirstItem');
@override
void initState() {
super.initState();
_currentSort = widget.selectedSort;
_currentDescending = widget.isSortDescending;
// Focus the first item after build
WidgetsBinding.instance.addPostFrameCallback((_) {
_firstItemFocusNode.requestFocus();
});
}
@override
void dispose() {
_firstItemFocusNode.dispose();
super.dispose();
}
void _handleSortChange(PlexSort sort, bool descending) {
setState(() {
_currentSort = sort;
_currentDescending = descending;
});
widget.onSortChanged(sort, descending);
Navigator.pop(context);
}
void _handleClear() {
setState(() {
_currentSort = null;
_currentDescending = false;
});
widget.onClear?.call();
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
return Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(context);
return KeyEventResult.handled;
}
// Left/right arrows toggle sort direction when a sort is selected
if (event is KeyDownEvent && _currentSort != null) {
if (event.logicalKey == LogicalKeyboardKey.arrowLeft &&
_currentDescending) {
_handleSortChange(_currentSort!, false);
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowRight &&
!_currentDescending) {
_handleSortChange(_currentSort!, true);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
child: DraggableScrollableSheet(
initialChildSize: 0.6,
minChildSize: 0.4,
maxChildSize: 0.9,
expand: false,
builder: (context, scrollController) {
return Column(
children: [
BottomSheetHeader(
title: t.libraries.sortBy,
action: widget.onClear != null
? TextButton(
onPressed: _handleClear,
child: Text(t.common.clear),
)
: null,
),
Expanded(
child: FocusTraversalGroup(
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: widget.sortOptions.length,
itemBuilder: (context, index) {
final sort = widget.sortOptions[index];
final isSelected = _currentSort?.key == sort.key;
return RadioListTile<PlexSort>(
focusNode: index == 0 ? _firstItemFocusNode : null,
title: Text(sort.title),
value: sort,
groupValue: _currentSort,
onChanged: (value) {
if (value != null) {
_handleSortChange(value, value.isDefaultDescending);
}
},
secondary: isSelected
? ExcludeFocus(
child: SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: Icon(Icons.arrow_upward, size: 16),
),
ButtonSegment(
value: true,
icon: Icon(
Icons.arrow_downward,
size: 16,
),
),
],
selected: {_currentDescending},
onSelectionChanged: (Set<bool> newSelection) {
_handleSortChange(sort, newSelection.first);
},
),
)
: null,
);
},
),
),
),
],
);
},
),
);
}
}
@@ -1,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.
@@ -139,6 +139,19 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
}
}
/// Focus the first item in the tab content
/// Subclasses can override this for custom focus behavior
void focusFirstItem() {
// Default implementation: try to focus the first focusable item
if (_items.isNotEmpty && mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
FocusScope.of(context).nextFocus();
}
});
}
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
@@ -1,26 +1,28 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:dio/dio.dart';
import '../../client/plex_client.dart';
import '../../models/plex_library.dart';
import '../../models/plex_metadata.dart';
import '../../models/plex_filter.dart';
import '../../models/plex_sort.dart';
import '../../providers/settings_provider.dart';
import '../../utils/error_message_utils.dart';
import '../../utils/grid_size_calculator.dart';
import '../../widgets/media_card.dart';
import '../../widgets/folder_tree_view.dart';
import '../../widgets/filters_bottom_sheet.dart';
import '../../widgets/sort_bottom_sheet.dart';
import '../../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_library.dart';
import '../../../models/plex_metadata.dart';
import '../../../models/plex_filter.dart';
import '../../../models/plex_sort.dart';
import '../../../providers/settings_provider.dart';
import '../../../utils/error_message_utils.dart';
import '../../../utils/grid_size_calculator.dart';
import '../../../utils/keyboard_utils.dart';
import '../../../widgets/media_card.dart';
import '../folder_tree_view.dart';
import '../filters_bottom_sheet.dart';
import '../sort_bottom_sheet.dart';
import '../empty_state_widget.dart';
import '../error_state_widget.dart';
import '../../../services/storage_service.dart';
import '../../../services/settings_service.dart' show ViewMode;
import '../../../mixins/item_updatable.dart';
import '../../../mixins/library_tab_state.dart';
import '../../../mixins/refreshable.dart';
import '../../../i18n/strings.g.dart';
/// Browse tab for library screen
/// Shows library items with grouping, filtering, and sorting
@@ -87,6 +89,11 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
int _requestId = 0;
static const int _pageSize = 500;
/// Focus node for the first item in the list/grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'BrowseFirstItem',
);
@override
void initState() {
super.initState();
@@ -105,9 +112,17 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
@override
void dispose() {
_cancelToken?.cancel();
_firstItemFocusNode.dispose();
super.dispose();
}
/// Focus the first item in the list/grid
void focusFirstItem() {
if (_items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
}
}
Future<void> _loadContent() async {
// Cancel any pending request
_cancelToken?.cancel();
@@ -166,12 +181,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
// Load items
await _loadItems();
} catch (e) {
if (currentRequestId != _requestId) return;
setState(() {
_errorMessage = _getErrorMessage(e);
_isLoading = false;
});
_handleLoadError(e, currentRequestId);
}
}
@@ -240,15 +250,19 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
_isLoading = false;
});
} catch (e) {
if (currentRequestId != _requestId) return;
setState(() {
_errorMessage = _getErrorMessage(e);
_isLoading = false;
});
_handleLoadError(e, currentRequestId);
}
}
void _handleLoadError(dynamic error, int currentRequestId) {
if (currentRequestId != _requestId) return;
setState(() {
_errorMessage = _getErrorMessage(error);
_isLoading = false;
});
}
String _getDefaultGrouping() {
final type = widget.library.type.toLowerCase();
if (type == 'show') {
@@ -312,36 +326,50 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
void _showGroupingBottomSheet() {
showModalBottomSheet(
context: context,
builder: (context) {
return ListView(
shrinkWrap: true,
children: _getGroupingOptions().map((grouping) {
return RadioListTile<String>(
title: Text(_getGroupingLabel(grouping)),
value: grouping,
// ignore: deprecated_member_use
groupValue: _selectedGrouping,
// ignore: deprecated_member_use
onChanged: (value) async {
if (value != null) {
setState(() {
_selectedGrouping = value;
});
builder: (sheetContext) {
final options = _getGroupingOptions();
return Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(sheetContext);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: FocusTraversalGroup(
child: ListView.builder(
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (context, index) {
final grouping = options[index];
return RadioListTile<String>(
autofocus: index == 0,
title: Text(_getGroupingLabel(grouping)),
value: grouping,
groupValue: _selectedGrouping,
onChanged: (value) async {
if (value != null) {
setState(() {
_selectedGrouping = value;
});
final storage = await StorageService.getInstance();
await storage.saveLibraryGrouping(
widget.library.globalKey,
value,
);
final storage = await StorageService.getInstance();
await storage.saveLibraryGrouping(
widget.library.globalKey,
value,
);
if (!context.mounted) return;
if (!sheetContext.mounted) return;
Navigator.pop(context);
_loadItems();
}
Navigator.pop(sheetContext);
_loadItems();
}
},
);
},
);
}).toList(),
),
),
);
},
);
@@ -407,32 +435,52 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
required String label,
required VoidCallback onPressed,
}) {
return InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: 16,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(width: 6),
Text(
label,
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
return Focus(
onKeyEvent: (node, event) {
if (event is KeyDownEvent) {
if (isKeyboardActivationKey(event.logicalKey)) {
onPressed();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
child: Builder(
builder: (context) {
final isFocused = Focus.of(context).hasFocus;
final colorScheme = Theme.of(context).colorScheme;
// When focused: inverse colors (white bg + dark text in dark mode, dark bg + light text in light mode)
final backgroundColor = isFocused
? colorScheme.onSurface
: colorScheme.surfaceContainerHighest;
final foregroundColor = isFocused
? colorScheme.surface
: colorScheme.onSurfaceVariant;
return InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 16, color: foregroundColor),
const SizedBox(width: 6),
Text(
label,
style: Theme.of(
context,
).textTheme.labelMedium?.copyWith(color: foregroundColor),
),
],
),
),
],
),
);
},
),
);
}
@@ -533,52 +581,53 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
child: Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
itemCount: _items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) {
if (index >= _items.length) {
return const Padding(
padding: EdgeInsets.all(16.0),
child: Center(child: CircularProgressIndicator()),
);
}
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
},
return ClipRect(
child: ListView.builder(
clipBehavior: Clip.none, // Allow focus indicator to overflow
padding: const EdgeInsets.all(8),
itemCount:
_items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) => _buildMediaCardItem(index),
),
);
} else {
return GridView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
return ClipRect(
child: GridView.builder(
clipBehavior: Clip.none, // Allow focus indicator to overflow
padding: const EdgeInsets.all(8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
itemCount:
_items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) => _buildMediaCardItem(index),
),
itemCount: _items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) {
if (index >= _items.length) {
return const Center(child: CircularProgressIndicator());
}
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
},
);
}
},
),
);
}
Widget _buildMediaCardItem(int index) {
if (index >= _items.length) {
return const Padding(
padding: EdgeInsets.all(16.0),
child: Center(child: CircularProgressIndicator()),
);
}
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
focusNode: index == 0 ? _firstItemFocusNode : null,
);
}
}
@@ -1,8 +1,8 @@
import 'package:flutter/material.dart';
import '../../models/plex_metadata.dart';
import '../../utils/library_refresh_notifier.dart';
import '../../i18n/strings.g.dart';
import '../../widgets/adaptive_media_grid.dart';
import '../../../models/plex_metadata.dart';
import '../../../utils/library_refresh_notifier.dart';
import '../../../i18n/strings.g.dart';
import '../adaptive_media_grid.dart';
import 'base_library_tab.dart';
/// Collections tab for library screen
@@ -21,6 +21,17 @@ class LibraryCollectionsTab extends BaseLibraryTab<PlexMetadata> {
class _LibraryCollectionsTabState
extends BaseLibraryTabState<PlexMetadata, LibraryCollectionsTab> {
/// Focus node for the first item in the grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'CollectionsFirstItem',
);
@override
void dispose() {
_firstItemFocusNode.dispose();
super.dispose();
}
@override
IconData get emptyIcon => Icons.collections;
@@ -43,8 +54,19 @@ class _LibraryCollectionsTabState
return await client.getLibraryCollections(widget.library.key);
}
@override
void focusFirstItem() {
if (items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
}
}
@override
Widget buildContent(List<PlexMetadata> items) {
return AdaptiveMediaGrid(items: items, onRefresh: loadItems);
return AdaptiveMediaGrid(
items: items,
onRefresh: loadItems,
firstItemFocusNode: _firstItemFocusNode,
);
}
}
@@ -1,12 +1,12 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_playlist.dart';
import '../../providers/settings_provider.dart';
import '../../utils/library_refresh_notifier.dart';
import '../../services/settings_service.dart' show ViewMode;
import '../../utils/grid_size_calculator.dart';
import '../../widgets/media_card.dart';
import '../../i18n/strings.g.dart';
import '../../../models/plex_playlist.dart';
import '../../../providers/settings_provider.dart';
import '../../../utils/library_refresh_notifier.dart';
import '../../../services/settings_service.dart' show ViewMode;
import '../../../utils/grid_size_calculator.dart';
import '../../../widgets/media_card.dart';
import '../../../i18n/strings.g.dart';
import 'base_library_tab.dart';
/// Playlists tab for library screen
@@ -25,6 +25,17 @@ class LibraryPlaylistsTab extends BaseLibraryTab<PlexPlaylist> {
class _LibraryPlaylistsTabState
extends BaseLibraryTabState<PlexPlaylist, LibraryPlaylistsTab> {
/// Focus node for the first item in the grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'PlaylistsFirstItem',
);
@override
void dispose() {
_firstItemFocusNode.dispose();
super.dispose();
}
@override
IconData get emptyIcon => Icons.playlist_play;
@@ -49,6 +60,13 @@ class _LibraryPlaylistsTabState
);
}
@override
void focusFirstItem() {
if (items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
}
}
@override
Widget buildContent(List<PlexPlaylist> items) {
return Consumer<SettingsProvider>(
@@ -57,14 +75,8 @@ class _LibraryPlaylistsTabState
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,
);
},
itemBuilder: (context, index) =>
_buildPlaylistItem(items[index], index),
);
} else {
return GridView.builder(
@@ -79,17 +91,20 @@ class _LibraryPlaylistsTabState
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) {
final playlist = items[index];
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: loadItems,
);
},
itemBuilder: (context, index) =>
_buildPlaylistItem(items[index], index),
);
}
},
);
}
Widget _buildPlaylistItem(PlexPlaylist playlist, int index) {
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: loadItems,
focusNode: index == 0 ? _firstItemFocusNode : null,
);
}
}
@@ -0,0 +1,164 @@
import 'package:flutter/material.dart';
import '../../../../services/plex_client.dart';
import '../../../i18n/strings.g.dart';
import '../../../mixins/item_updatable.dart';
import '../../../models/plex_hub.dart';
import '../../../models/plex_metadata.dart';
import '../../../widgets/hub_navigation_controller.dart';
import '../../../widgets/hub_section.dart';
import 'base_library_tab.dart';
/// Recommended tab for library screen
/// Shows library-specific hubs and recommendations, including dedicated Continue Watching
class LibraryRecommendedTab extends BaseLibraryTab<PlexHub> {
const LibraryRecommendedTab({super.key, required super.library});
@override
State<LibraryRecommendedTab> createState() => _LibraryRecommendedTabState();
}
class _LibraryRecommendedTabState
extends BaseLibraryTabState<PlexHub, LibraryRecommendedTab>
with ItemUpdatable {
final HubNavigationController _hubNavigationController =
HubNavigationController();
@override
void dispose() {
_hubNavigationController.dispose();
super.dispose();
}
/// Focus the first item in the first hub
@override
void focusFirstItem() {
_hubNavigationController.focusHub(0, 0);
}
@override
PlexClient get client => getClientForLibrary();
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
// Update the item in any hub that contains it
for (final hub in items) {
final itemIndex = hub.items.indexWhere(
(item) => item.ratingKey == ratingKey,
);
if (itemIndex != -1) {
hub.items[itemIndex] = updatedMetadata;
}
}
}
@override
IconData get emptyIcon => Icons.recommend;
@override
String get emptyMessage => t.libraries.noRecommendations;
@override
String get errorContext => t.libraries.tabs.recommended;
@override
Future<List<PlexHub>> loadData() async {
// Use server-specific client for this library
final client = getClientForLibrary();
// Load both continue watching items and regular hubs in parallel
final results = await Future.wait([
client.getOnDeckForLibrary(widget.library.key),
client.getLibraryHubs(widget.library.key, limit: 12),
]);
final continueWatchingItems = results[0] as List<PlexMetadata>;
final hubs = results[1] as List<PlexHub>;
// Filter out any existing Continue Watching hubs since we're adding our own
final filteredHubs = hubs.where((hub) {
final title = hub.title.toLowerCase();
final hubId = hub.hubIdentifier?.toLowerCase() ?? '';
return !title.contains('continue watching') &&
!title.contains('on deck') &&
!hubId.contains('ondeck') &&
!hubId.contains('continue');
}).toList();
final finalHubs = <PlexHub>[];
// Add Continue Watching as the first hub if there are items
if (continueWatchingItems.isNotEmpty) {
final continueWatchingHub = PlexHub(
hubKey: 'library_continue_watching_${widget.library.key}',
title: t.discover.continueWatching,
type: 'mixed',
hubIdentifier: '_library_continue_watching_',
size: continueWatchingItems.length,
more: false,
items: continueWatchingItems,
serverId: widget.library.serverId,
serverName: widget.library.serverName,
);
finalHubs.add(continueWatchingHub);
}
// Add the filtered regular hubs
finalHubs.addAll(filteredHubs);
return finalHubs;
}
@override
Widget buildContent(List<PlexHub> items) {
return HubNavigationScope(
controller: _hubNavigationController,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: items.length,
itemBuilder: (context, index) {
final hub = items[index];
final isContinueWatching =
hub.hubIdentifier == '_library_continue_watching_';
return HubSection(
hub: hub,
icon: _getHubIcon(hub),
navigationOrder: index,
isInContinueWatching: isContinueWatching,
onRefresh: updateItem,
onRemoveFromContinueWatching: isContinueWatching
? _refreshContinueWatching
: null,
);
},
),
);
}
/// Refresh the Continue Watching section
void _refreshContinueWatching() {
// Reload all data to refresh the continue watching section
loadItems();
}
IconData _getHubIcon(PlexHub hub) {
final title = hub.title.toLowerCase();
if (title.contains('continue watching') || title.contains('on deck')) {
return Icons.play_circle;
} else if (title.contains('recently') || title.contains('new')) {
return Icons.fiber_new;
} else if (title.contains('popular') || title.contains('trending')) {
return Icons.trending_up;
} else if (title.contains('top') || title.contains('rated')) {
return Icons.star;
} else if (title.contains('recommended')) {
return Icons.thumb_up;
} else if (title.contains('unwatched')) {
return Icons.visibility_off;
} else if (title.contains('genre')) {
return Icons.category;
}
return Icons.movie;
}
}
@@ -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;
}
}
+166 -35
View File
@@ -1,8 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../../services/plex_client.dart';
import '../i18n/strings.g.dart';
import '../utils/app_logger.dart';
import '../utils/keyboard_utils.dart';
import '../utils/provider_extensions.dart';
import '../main.dart';
import '../mixins/refreshable.dart';
@@ -13,9 +15,33 @@ import '../providers/playback_state_provider.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import 'discover_screen.dart';
import 'libraries_screen.dart';
import 'libraries/libraries_screen.dart';
import 'search_screen.dart';
import 'settings_screen.dart';
import 'settings/settings_screen.dart';
/// InheritedWidget that provides back navigation functionality to child screens
class BackNavigationScope extends InheritedWidget {
final VoidCallback focusBottomNav;
const BackNavigationScope({
super.key,
required this.focusBottomNav,
required super.child,
});
static BackNavigationScope? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<BackNavigationScope>();
}
static BackNavigationScope? maybeOf(BuildContext context) {
return context.getInheritedWidgetOfExactType<BackNavigationScope>();
}
@override
bool updateShouldNotify(BackNavigationScope oldWidget) {
return focusBottomNav != oldWidget.focusBottomNav;
}
}
class MainScreen extends StatefulWidget {
final PlexClient client;
@@ -35,9 +61,18 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
final GlobalKey<State<SearchScreen>> _searchKey = GlobalKey();
final GlobalKey<State<SettingsScreen>> _settingsKey = GlobalKey();
/// Focus scope node for the bottom navigation bar
/// Using FocusScopeNode so requestFocus() focuses the first child
late final FocusScopeNode _bottomNavFocusScopeNode;
/// Focus scope node for the main content area
late final FocusScopeNode _contentFocusScopeNode;
@override
void initState() {
super.initState();
_bottomNavFocusScopeNode = FocusScopeNode(debugLabel: 'BottomNavigation');
_contentFocusScopeNode = FocusScopeNode(debugLabel: 'MainContent');
_screens = [
DiscoverScreen(
@@ -69,9 +104,38 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
@override
void dispose() {
routeObserver.unsubscribe(this);
_bottomNavFocusScopeNode.dispose();
_contentFocusScopeNode.dispose();
super.dispose();
}
/// Focus the bottom navigation bar (called by child screens on back press)
void _focusBottomNav() {
// Request focus on the scope, then navigate to the currently selected tab
_bottomNavFocusScopeNode.requestFocus();
WidgetsBinding.instance.addPostFrameCallback((_) {
// Move to first item, then advance to current index
_bottomNavFocusScopeNode.nextFocus();
for (int i = 0; i < _currentIndex; i++) {
_bottomNavFocusScopeNode.nextFocus();
}
});
}
/// Focus the content area (called when back is pressed in navbar)
void _focusContent() {
_contentFocusScopeNode.requestFocus();
}
/// Handle back key in navbar - focus content area
KeyEventResult _handleNavBarBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
_focusContent();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
void didPush() {
// Called when this route has been pushed (initial navigation)
@@ -150,44 +214,111 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
}
}
void _selectTab(int index) {
// Check if selection came from keyboard/d-pad (bottom nav has focus)
final isKeyboardNavigation = _bottomNavFocusScopeNode.hasFocus;
setState(() {
_currentIndex = index;
});
// Notify discover screen when it becomes visible via tab switch
if (index == 0) {
_onDiscoverBecameVisible();
// Focus hero when selecting Home tab via keyboard/d-pad
if (isKeyboardNavigation) {
final discoverState = _discoverKey.currentState;
if (discoverState != null) {
(discoverState as dynamic).focusHero();
}
}
}
// Focus first content item when selecting Libraries tab via keyboard/d-pad
if (index == 1 && isKeyboardNavigation) {
final librariesState = _librariesKey.currentState;
if (librariesState != null) {
(librariesState as dynamic).focusFirstContentItem();
}
}
// Focus search input when selecting Search tab (for both click/tap and keyboard)
if (index == 2) {
final searchState = _searchKey.currentState;
if (searchState != null) {
(searchState as dynamic).focusSearchInput();
}
}
// Move focus to the content area when selecting a tab via keyboard
if (isKeyboardNavigation) {
_contentFocusScopeNode.requestFocus();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(index: _currentIndex, children: _screens),
bottomNavigationBar: NavigationBar(
selectedIndex: _currentIndex,
onDestinationSelected: (index) {
setState(() {
_currentIndex = index;
});
// Notify discover screen when it becomes visible via tab switch
if (index == 0) {
_onDiscoverBecameVisible();
}
return Shortcuts(
shortcuts: {
// Number keys 1-4 for quick tab switching
const SingleActivator(LogicalKeyboardKey.digit1): _TabIntent(0),
const SingleActivator(LogicalKeyboardKey.digit2): _TabIntent(1),
const SingleActivator(LogicalKeyboardKey.digit3): _TabIntent(2),
const SingleActivator(LogicalKeyboardKey.digit4): _TabIntent(3),
},
child: Actions(
actions: {
_TabIntent: CallbackAction<_TabIntent>(
onInvoke: (intent) {
_selectTab(intent.tabIndex);
return null;
},
),
},
destinations: [
NavigationDestination(
icon: const Icon(Icons.home_outlined),
selectedIcon: const Icon(Icons.home),
label: t.navigation.home,
child: Scaffold(
body: BackNavigationScope(
focusBottomNav: _focusBottomNav,
child: FocusScope(
node: _contentFocusScopeNode,
child: FocusTraversalGroup(
child: IndexedStack(index: _currentIndex, children: _screens),
),
),
),
NavigationDestination(
icon: const Icon(Icons.video_library_outlined),
selectedIcon: const Icon(Icons.video_library),
label: t.navigation.libraries,
bottomNavigationBar: FocusScope(
node: _bottomNavFocusScopeNode,
onKeyEvent: _handleNavBarBackKey,
child: NavigationBar(
selectedIndex: _currentIndex,
onDestinationSelected: _selectTab,
destinations: [
NavigationDestination(
icon: const Icon(Icons.home_outlined),
selectedIcon: const Icon(Icons.home),
label: t.navigation.home,
),
NavigationDestination(
icon: const Icon(Icons.video_library_outlined),
selectedIcon: const Icon(Icons.video_library),
label: t.navigation.libraries,
),
NavigationDestination(
icon: const Icon(Icons.search),
selectedIcon: const Icon(Icons.search),
label: t.navigation.search,
),
NavigationDestination(
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
label: t.navigation.settings,
),
],
),
),
NavigationDestination(
icon: const Icon(Icons.search),
selectedIcon: const Icon(Icons.search),
label: t.navigation.search,
),
NavigationDestination(
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
label: t.navigation.settings,
),
],
),
),
);
}
}
/// Intent for switching tabs via keyboard shortcuts
class _TabIntent extends Intent {
final int tabIndex;
const _TabIntent(this.tabIndex);
}
File diff suppressed because it is too large Load Diff
@@ -1,20 +1,20 @@
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 '../../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 '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';
/// Screen to display the contents of a playlist
class PlaylistDetailScreen extends StatefulWidget {
@@ -240,9 +240,12 @@ class _PlaylistDetailScreenState
widget.playlist.ratingKey,
);
// Navigate to selected item (should be first in the queue response)
// Navigate to selected item
if (mounted) {
await navigateToVideoPlayer(context, metadata: playQueue.items!.first);
await navigateToVideoPlayer(
context,
metadata: playQueue.selectedItem ?? playQueue.items!.first,
);
}
} catch (e) {
appLogger.e('Failed to play from item', error: e);
@@ -336,6 +339,7 @@ class _PlaylistDetailScreenState
index: index,
onRemove: () => _removeItem(index),
onTap: () => _playFromItem(index),
onRefresh: updateItem,
canReorder: !widget.playlist.smart,
);
},
@@ -0,0 +1,213 @@
import 'package:flutter/material.dart';
import '../../services/plex_client.dart';
import '../../mixins/keyboard_long_press_mixin.dart';
import '../../models/plex_metadata.dart';
import '../../utils/duration_formatter.dart';
import '../../utils/provider_extensions.dart';
import '../../i18n/strings.g.dart';
import '../../widgets/focus/focus_indicator.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>
with KeyboardLongPressMixin {
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
@override
void onKeyboardTap() => widget.onTap?.call();
@override
void onKeyboardLongPress() {
_contextMenuKey.currentState?.showContextMenu(context);
}
@override
Widget build(BuildContext context) {
final item = widget.item;
return MediaContextMenu(
key: _contextMenuKey,
item: item,
onRefresh: widget.onRefresh,
onTap: widget.onTap,
child: FocusableWrapper(
onKeyEvent: (node, event) => handleKeyboardLongPress(event),
builder: (context, isFocused) => FocusIndicator(
isFocused: isFocused,
borderRadius: 12,
child: Card(
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: InkWell(
onTap: widget.onTap,
focusColor: Colors.transparent,
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: PlexPosterImage(
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 }
@@ -1,11 +1,11 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/profile_list_tile.dart';
import '../widgets/desktop_app_bar.dart';
import '../i18n/strings.g.dart';
import '../../models/plex_home_user.dart';
import '../../providers/user_profile_provider.dart';
import '../../utils/provider_extensions.dart';
import 'profile_list_tile.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../i18n/strings.g.dart';
class ProfileSwitchScreen extends StatelessWidget {
const ProfileSwitchScreen({super.key});
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../models/plex_home_user.dart';
import '../i18n/strings.g.dart';
import '../../models/plex_home_user.dart';
import '../../i18n/strings.g.dart';
class UserAvatarWidget extends StatelessWidget {
final PlexHomeUser user;
+185 -126
View File
@@ -1,9 +1,10 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:rate_limiter/rate_limiter.dart';
import '../i18n/strings.g.dart';
import 'main_screen.dart';
import '../mixins/refreshable.dart';
import '../models/plex_metadata.dart';
import '../providers/multi_server_provider.dart';
@@ -11,6 +12,7 @@ import '../providers/settings_provider.dart';
import '../services/settings_service.dart';
import '../utils/app_logger.dart';
import '../utils/grid_cross_axis_extent.dart';
import '../utils/keyboard_utils.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/media_card.dart';
@@ -23,33 +25,41 @@ class SearchScreen extends StatefulWidget {
class _SearchScreenState extends State<SearchScreen> with Refreshable {
final _searchController = TextEditingController();
final _searchFocusNode = FocusNode(debugLabel: 'SearchInput');
List<PlexMetadata> _searchResults = [];
bool _isSearching = false;
bool _hasSearched = false;
Timer? _debounceTimer;
late final Debounce _searchDebounce;
String _lastSearchedQuery = '';
@override
void initState() {
super.initState();
_searchDebounce = debounce(
_performSearch,
const Duration(milliseconds: 500),
);
_searchController.addListener(_onSearchChanged);
// Focus the search input when the screen is shown
WidgetsBinding.instance.addPostFrameCallback((_) {
_searchFocusNode.requestFocus();
});
}
@override
void dispose() {
_debounceTimer?.cancel();
_searchDebounce.cancel();
_searchController.removeListener(_onSearchChanged);
_searchController.dispose();
_searchFocusNode.dispose();
super.dispose();
}
void _onSearchChanged() {
// Cancel previous timer
_debounceTimer?.cancel();
final query = _searchController.text;
if (query.trim().isEmpty) {
_searchDebounce.cancel();
setState(() {
_searchResults = [];
_hasSearched = false;
@@ -64,10 +74,7 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
return;
}
// Start new timer
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
_performSearch(query);
});
_searchDebounce([query]);
}
Future<void> _performSearch(String query) async {
@@ -124,6 +131,13 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
}
}
/// Focus the search input field
void focusSearchInput() {
WidgetsBinding.instance.addPostFrameCallback((_) {
_searchFocusNode.requestFocus();
});
}
// Public method to fully reload all content (for profile switches)
void fullRefresh() {
appLogger.d(
@@ -146,133 +160,178 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
}
}
/// Handle back key press - focus bottom navigation
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
// Allow backspace to work normally in search field when it has content
if (event.logicalKey == LogicalKeyboardKey.backspace &&
_searchFocusNode.hasFocus &&
_searchController.text.isNotEmpty) {
return KeyEventResult.ignored;
}
BackNavigationScope.of(context)?.focusBottomNav();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: CustomScrollView(
slivers: [
DesktopSliverAppBar(title: Text(t.screens.search), floating: true),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: SearchBar(
controller: _searchController,
hintText: t.search.hint,
leading: const Icon(Icons.search),
trailing: [
if (_searchController.text.isNotEmpty)
IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.clear();
// State update handled by listener
},
child: Focus(
onKeyEvent: _handleBackKey,
child: CustomScrollView(
slivers: [
DesktopSliverAppBar(
title: Text(t.screens.search),
floating: true,
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: _searchController,
focusNode: _searchFocusNode,
decoration: InputDecoration(
hintText: t.search.hint,
prefixIcon: const Icon(Icons.search),
suffixIcon: _searchController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.clear();
// State update handled by listener
},
)
: null,
filled: true,
fillColor: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(28),
borderSide: BorderSide.none,
),
],
autoFocus: false,
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
),
),
),
),
),
if (_isSearching)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (!_hasSearched)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.search, size: 80, color: Colors.grey.shade400),
const SizedBox(height: 16),
Text(
t.search.searchYourMedia,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.grey.shade600,
if (_isSearching)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (!_hasSearched)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.search,
size: 80,
color: Colors.grey.shade400,
),
),
const SizedBox(height: 8),
Text(
t.search.enterTitleActorOrKeyword,
style: TextStyle(color: Colors.grey.shade600),
),
],
),
),
)
else if (_searchResults.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.search_off,
size: 80,
color: Colors.grey.shade400,
),
const SizedBox(height: 16),
Text(
t.messages.noResultsFound,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.grey.shade600,
const SizedBox(height: 16),
Text(
t.search.searchYourMedia,
style: Theme.of(context).textTheme.titleLarge
?.copyWith(color: Colors.grey.shade600),
),
),
const SizedBox(height: 8),
Text(
t.search.tryDifferentTerm,
style: TextStyle(color: Colors.grey.shade600),
),
],
const SizedBox(height: 8),
Text(
t.search.enterTitleActorOrKeyword,
style: TextStyle(color: Colors.grey.shade600),
),
],
),
),
),
)
else
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _searchResults.length),
),
);
} else {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: getMaxCrossAxisExtentWithPadding(
)
else if (_searchResults.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.search_off,
size: 80,
color: Colors.grey.shade400,
),
const SizedBox(height: 16),
Text(
t.messages.noResultsFound,
style: Theme.of(context).textTheme.titleLarge
?.copyWith(color: Colors.grey.shade600),
),
const SizedBox(height: 8),
Text(
t.search.tryDifferentTerm,
style: TextStyle(color: Colors.grey.shade600),
),
],
),
),
)
else
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((
context,
settingsProvider.libraryDensity,
32,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
index,
) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _searchResults.length),
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _searchResults.length),
),
);
}
},
),
],
);
} else {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate:
SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
getMaxCrossAxisExtentWithPadding(
context,
settingsProvider.libraryDensity,
32,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
delegate: SliverChildBuilderDelegate((
context,
index,
) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _searchResults.length),
),
);
}
},
),
],
),
),
),
);
+362 -232
View File
@@ -1,20 +1,31 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../client/plex_client.dart';
import '../../services/plex_client.dart';
import '../widgets/plex_optimized_image.dart';
import '../widgets/focus/focus_indicator.dart';
import '../models/plex_metadata.dart';
import '../utils/keyboard_utils.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/duration_formatter.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/media_context_menu.dart';
import '../mixins/item_updatable.dart';
import '../mixins/keyboard_long_press_mixin.dart';
import '../theme/theme_helper.dart';
import '../i18n/strings.g.dart';
class SeasonDetailScreen extends StatefulWidget {
final PlexMetadata season;
const SeasonDetailScreen({super.key, required this.season});
/// Whether to focus the first episode after loading.
/// Should be true when navigating via keyboard, false for mouse/tap.
final bool focusFirstEpisode;
const SeasonDetailScreen({
super.key,
required this.season,
this.focusFirstEpisode = false,
});
@override
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
@@ -30,6 +41,9 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
List<PlexMetadata> _episodes = [];
bool _isLoadingEpisodes = false;
bool _watchStateChanged = false;
final FocusNode _firstEpisodeFocusNode = FocusNode(
debugLabel: 'FirstEpisode',
);
/// Get the correct PlexClient for this season's server
PlexClient _getClientForSeason(BuildContext context) {
@@ -46,6 +60,12 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
});
}
@override
void dispose() {
_firstEpisodeFocusNode.dispose();
super.dispose();
}
Future<void> _loadEpisodes() async {
setState(() {
_isLoadingEpisodes = true;
@@ -59,6 +79,13 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
_episodes = episodes;
_isLoadingEpisodes = false;
});
// Focus the first episode after loading (only if keyboard navigation)
if (episodes.isNotEmpty && widget.focusFirstEpisode) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_firstEpisodeFocusNode.requestFocus();
});
}
} catch (e) {
setState(() {
_isLoadingEpisodes = false;
@@ -83,52 +110,145 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(widget.season.title),
pinned: true,
onBackPressed: () => Navigator.pop(context, _watchStateChanged),
),
if (_isLoadingEpisodes)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (_episodes.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.movie_outlined,
size: 64,
color: tokens(context).textMuted,
),
const SizedBox(height: 16),
Text(
t.messages.noEpisodesFoundGeneral,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
body: Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(context, _watchStateChanged);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(widget.season.title),
pinned: true,
onBackPressed: () => Navigator.pop(context, _watchStateChanged),
),
if (_isLoadingEpisodes)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (_episodes.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.movie_outlined,
size: 64,
color: tokens(context).textMuted,
),
),
],
const SizedBox(height: 16),
Text(
t.messages.noEpisodesFoundGeneral,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: tokens(context).textMuted,
),
),
],
),
),
)
else
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final episode = _episodes[index];
return _EpisodeCard(
episode: episode,
client: _client,
focusNode: index == 0 ? _firstEpisodeFocusNode : null,
onTap: () async {
await navigateToVideoPlayer(context, metadata: episode);
// Refresh episodes when returning from video player
_loadEpisodes();
},
onRefresh: updateItem,
);
}, childCount: _episodes.length),
),
)
else
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final episode = _episodes[index];
return _buildEpisodeCard(episode);
}, childCount: _episodes.length),
),
],
],
),
),
);
}
}
Widget _buildEpisodeCard(PlexMetadata episode) {
/// Focusable episode card widget
class _EpisodeCard extends StatefulWidget {
final PlexMetadata episode;
final PlexClient client;
final VoidCallback onTap;
final Future<void> Function(String) onRefresh;
final FocusNode? focusNode;
const _EpisodeCard({
required this.episode,
required this.client,
required this.onTap,
required this.onRefresh,
this.focusNode,
});
@override
State<_EpisodeCard> createState() => _EpisodeCardState();
}
class _EpisodeCardState extends State<_EpisodeCard>
with KeyboardLongPressMixin {
FocusNode? _internalFocusNode;
FocusNode get _focusNode =>
widget.focusNode ?? (_internalFocusNode ??= FocusNode());
bool _isFocused = false;
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
@override
void onKeyboardTap() => widget.onTap();
@override
void onKeyboardLongPress() {
_contextMenuKey.currentState?.showContextMenu(context);
}
@override
void initState() {
super.initState();
_focusNode.addListener(_handleFocusChange);
}
@override
void dispose() {
_focusNode.removeListener(_handleFocusChange);
_internalFocusNode?.dispose();
super.dispose();
}
void _handleFocusChange() {
if (_isFocused != _focusNode.hasFocus) {
setState(() {
_isFocused = _focusNode.hasFocus;
});
if (_focusNode.hasFocus) {
Scrollable.ensureVisible(
context,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
}
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
// Handle long-press detection for activation keys
return handleKeyboardLongPress(event);
}
@override
Widget build(BuildContext context) {
final episode = widget.episode;
final hasProgress =
episode.viewOffset != null &&
episode.duration != null &&
@@ -138,44 +258,50 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
: 0.0;
return MediaContextMenu(
key: _contextMenuKey,
item: episode,
onRefresh: updateItem,
onTap: () async {
await navigateToVideoPlayer(context, metadata: episode);
// Refresh episodes when returning from video player
_loadEpisodes();
},
child: InkWell(
key: Key(episode.ratingKey),
hoverColor: Theme.of(
context,
).colorScheme.surface.withValues(alpha: 0.05),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: tokens(context).outline, width: 0.5),
),
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Episode thumbnail (16:9 aspect ratio, fixed width)
SizedBox(
width: 160,
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: AspectRatio(
aspectRatio: 16 / 9,
child: episode.thumb != null
? Builder(
builder: (context) {
return CachedNetworkImage(
imageUrl: _client.getThumbnailUrl(
episode.thumb,
),
onRefresh: widget.onRefresh,
onTap: widget.onTap,
child: Focus(
focusNode: _focusNode,
onKeyEvent: _handleKeyEvent,
child: FocusIndicator(
isFocused: _isFocused,
borderRadius: 0,
scale: 1.0, // No scale for full-width items to avoid clipping
child: InkWell(
key: Key(episode.ratingKey),
onTap: widget.onTap,
hoverColor: Theme.of(
context,
).colorScheme.surface.withValues(alpha: 0.05),
focusColor: Colors.transparent,
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: tokens(context).outline,
width: 0.5,
),
),
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Episode thumbnail (16:9 aspect ratio, fixed width)
SizedBox(
width: 160,
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: AspectRatio(
aspectRatio: 16 / 9,
child: episode.thumb != null
? PlexThumbImage(
client: widget.client,
imagePath: episode.thumb,
filterQuality: FilterQuality.medium,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
@@ -193,174 +319,178 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
size: 32,
),
),
);
},
)
: Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
),
),
// Play overlay
Positioned.fill(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black.withValues(alpha: 0.2),
],
)
: Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
),
),
child: Center(
// Play overlay
Positioned.fill(
child: Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.6),
shape: BoxShape.circle,
borderRadius: BorderRadius.circular(6),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black.withValues(alpha: 0.2),
],
),
),
child: const Icon(
Icons.play_arrow,
color: Colors.white,
size: 20,
),
),
),
),
),
// Progress bar at bottom
if (hasProgress && !episode.isWatched)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: ClipRRect(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(6),
bottomRight: Radius.circular(6),
),
child: LinearProgressIndicator(
value: progress,
backgroundColor: tokens(context).outline,
minHeight: 3,
),
),
),
],
),
),
const SizedBox(width: 12),
// Episode info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Episode number and title
Row(
children: [
if (episode.index != null)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 3,
),
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(3),
),
child: Text(
'E${episode.index}',
style: TextStyle(
color: Theme.of(
context,
).colorScheme.onPrimaryContainer,
fontSize: 11,
fontWeight: FontWeight.w600,
child: Center(
child: Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.6),
shape: BoxShape.circle,
),
child: const Icon(
Icons.play_arrow,
color: Colors.white,
size: 20,
),
),
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
episode.title,
style: Theme.of(context).textTheme.titleSmall
?.copyWith(fontWeight: FontWeight.bold),
maxLines: 2,
),
// Progress bar at bottom
if (hasProgress && !episode.isWatched)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: ClipRRect(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(6),
bottomRight: Radius.circular(6),
),
child: LinearProgressIndicator(
value: progress,
backgroundColor: tokens(context).outline,
minHeight: 3,
),
),
),
],
),
),
const SizedBox(width: 12),
// Episode info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Episode number and title
Row(
children: [
if (episode.index != null)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 3,
),
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(3),
),
child: Text(
'E${episode.index}',
style: TextStyle(
color: Theme.of(
context,
).colorScheme.onPrimaryContainer,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
episode.title,
style: Theme.of(context).textTheme.titleSmall
?.copyWith(fontWeight: FontWeight.bold),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
],
),
// Summary
if (episode.summary != null &&
episode.summary!.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
episode.summary!,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
height: 1.3,
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
],
),
// Summary
if (episode.summary != null &&
episode.summary!.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
episode.summary!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
height: 1.3,
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
],
// Metadata row (duration, watched status)
const SizedBox(height: 8),
Row(
children: [
if (episode.duration != null)
Text(
formatDurationTimestamp(
Duration(milliseconds: episode.duration!),
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
if (episode.duration != null && episode.isWatched) ...[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Text(
'•',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
),
Text(
'${t.discover.watched} ✓',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
],
// Metadata row (duration, watched status)
const SizedBox(height: 8),
Row(
children: [
if (episode.duration != null)
Text(
formatDurationTimestamp(
Duration(milliseconds: episode.duration!),
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
if (episode.duration != null &&
episode.isWatched) ...[
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 6,
),
child: Text(
'•',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
),
Text(
'${t.discover.watched} ✓',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
],
],
),
],
),
],
),
),
],
),
],
),
),
),
),
@@ -1,7 +1,7 @@
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 '../../widgets/desktop_app_bar.dart';
import '../../i18n/strings.g.dart';
import 'licenses_screen.dart';
class AboutScreen extends StatefulWidget {
@@ -1,6 +1,6 @@
import 'package:flutter/material.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import '../i18n/strings.g.dart';
import '../../i18n/strings.g.dart';
class HotKeyRecorderWidget extends StatefulWidget {
final String actionName;
@@ -1,7 +1,7 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../widgets/desktop_app_bar.dart';
import '../i18n/strings.g.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../i18n/strings.g.dart';
class MergedLicenseEntry {
final String packageName;
@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import '../i18n/strings.g.dart';
import '../utils/app_logger.dart';
import '../widgets/desktop_app_bar.dart';
import '../../i18n/strings.g.dart';
import '../../utils/app_logger.dart';
import '../../widgets/desktop_app_bar.dart';
class LogsScreen extends StatefulWidget {
const LogsScreen({super.key});
@@ -245,55 +245,16 @@ class _LogEntryCardState extends State<_LogEntryCard> {
const SizedBox(height: 12),
const Divider(),
const SizedBox(height: 8),
if (widget.log.error != null) ...[
Text(
t.logs.error,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: widget.levelColor,
fontWeight: FontWeight.bold,
),
if (widget.log.error != null)
_buildDetailSection(
title: t.logs.error,
content: widget.log.error.toString(),
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? Colors.grey[900]
: Colors.grey[200],
borderRadius: BorderRadius.circular(4),
),
child: SelectableText(
widget.log.error.toString(),
style: Theme.of(
context,
).textTheme.bodySmall?.copyWith(fontFamily: 'monospace'),
),
),
],
if (widget.log.stackTrace != null) ...[
const SizedBox(height: 12),
Text(
t.logs.stackTrace,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: widget.levelColor,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? Colors.grey[900]
: Colors.grey[200],
borderRadius: BorderRadius.circular(4),
),
child: SelectableText(
widget.log.stackTrace.toString(),
style: Theme.of(
context,
).textTheme.bodySmall?.copyWith(fontFamily: 'monospace'),
),
_buildDetailSection(
title: t.logs.stackTrace,
content: widget.log.stackTrace.toString(),
),
],
],
@@ -303,4 +264,35 @@ class _LogEntryCardState extends State<_LogEntryCard> {
),
);
}
Widget _buildDetailSection({required String title, required String content}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: widget.levelColor,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? Colors.grey[900]
: Colors.grey[200],
borderRadius: BorderRadius.circular(4),
),
child: SelectableText(
content,
style: Theme.of(
context,
).textTheme.bodySmall?.copyWith(fontFamily: 'monospace'),
),
),
],
);
}
}
@@ -3,14 +3,16 @@ import 'package:hotkey_manager/hotkey_manager.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../i18n/strings.g.dart';
import '../providers/settings_provider.dart';
import '../providers/theme_provider.dart';
import '../services/keyboard_shortcuts_service.dart';
import '../services/settings_service.dart' as settings;
import '../services/update_service.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/hotkey_recorder_widget.dart';
import '../../i18n/strings.g.dart';
import '../main_screen.dart';
import '../../providers/settings_provider.dart';
import '../../providers/theme_provider.dart';
import '../../services/keyboard_shortcuts_service.dart';
import '../../services/settings_service.dart' as settings;
import '../../services/update_service.dart';
import '../../utils/keyboard_utils.dart';
import '../../widgets/desktop_app_bar.dart';
import 'hotkey_recorder_widget.dart';
import 'about_screen.dart';
import 'logs_screen.dart';
import 'subtitle_styling_screen.dart';
@@ -34,6 +36,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
int _seekTimeLarge = 30;
int _sleepTimerDuration = 30;
bool _rememberTrackSelections = true;
bool _autoSkipIntro = true;
bool _autoSkipCredits = true;
int _autoSkipDelay = 5;
// Update checking state
bool _isCheckingForUpdate = false;
@@ -57,10 +62,22 @@ class _SettingsScreenState extends State<SettingsScreen> {
_seekTimeLarge = _settingsService.getSeekTimeLarge();
_sleepTimerDuration = _settingsService.getSleepTimerDuration();
_rememberTrackSelections = _settingsService.getRememberTrackSelections();
_autoSkipIntro = _settingsService.getAutoSkipIntro();
_autoSkipCredits = _settingsService.getAutoSkipCredits();
_autoSkipDelay = _settingsService.getAutoSkipDelay();
_isLoading = false;
});
}
/// Handle back key press - focus bottom navigation
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
BackNavigationScope.of(context)?.focusBottomNav();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
@@ -68,31 +85,34 @@ class _SettingsScreenState extends State<SettingsScreen> {
}
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.settings.title), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildAppearanceSection(),
const SizedBox(height: 24),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
const SizedBox(height: 24),
if (UpdateService.isUpdateCheckEnabled) ...[
_buildUpdateSection(),
body: Focus(
onKeyEvent: _handleBackKey,
child: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.settings.title), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildAppearanceSection(),
const SizedBox(height: 24),
],
_buildAboutSection(),
const SizedBox(height: 24),
]),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
const SizedBox(height: 24),
if (UpdateService.isUpdateCheckEnabled) ...[
_buildUpdateSection(),
const SizedBox(height: 24),
],
_buildAboutSection(),
const SizedBox(height: 24),
]),
),
),
),
],
],
),
),
);
}
@@ -276,6 +296,52 @@ class _SettingsScreenState extends State<SettingsScreen> {
await _settingsService.setRememberTrackSelections(value);
},
),
const Divider(),
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Text(
t.settings.autoSkip,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.primary,
),
),
),
SwitchListTile(
secondary: const Icon(Icons.fast_forward),
title: Text(t.settings.autoSkipIntro),
subtitle: Text(t.settings.autoSkipIntroDescription),
value: _autoSkipIntro,
onChanged: (value) async {
setState(() {
_autoSkipIntro = value;
});
await _settingsService.setAutoSkipIntro(value);
},
),
SwitchListTile(
secondary: const Icon(Icons.skip_next),
title: Text(t.settings.autoSkipCredits),
subtitle: Text(t.settings.autoSkipCreditsDescription),
value: _autoSkipCredits,
onChanged: (value) async {
setState(() {
_autoSkipCredits = value;
});
await _settingsService.setAutoSkipCredits(value);
},
),
ListTile(
leading: const Icon(Icons.timer),
title: Text(t.settings.autoSkipDelay),
subtitle: Text(
t.settings.autoSkipDelayDescription(
seconds: _autoSkipDelay.toString(),
),
),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showAutoSkipDelayDialog(),
),
],
),
);
@@ -688,7 +754,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: t.settings.minutesLabel,
hintText: t.settings.durationHint(min: 5, max: 180),
hintText: t.settings.durationHint(min: 5, max: 240),
errorText: errorText,
suffixText: t.settings.minutesShort,
),
@@ -698,10 +764,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
setDialogState(() {
if (parsed == null) {
errorText = t.settings.validationErrorEnterNumber;
} else if (parsed < 5 || parsed > 180) {
} else if (parsed < 5 || parsed > 240) {
errorText = t.settings.validationErrorDuration(
min: 5,
max: 180,
max: 240,
unit: t.settings.minutesLabel.toLowerCase(),
);
} else {
@@ -718,11 +784,77 @@ class _SettingsScreenState extends State<SettingsScreen> {
TextButton(
onPressed: () async {
final parsed = int.tryParse(controller.text);
if (parsed != null && parsed >= 5 && parsed <= 180) {
if (parsed != null && parsed >= 5 && parsed <= 240) {
setState(() {
_sleepTimerDuration = parsed;
_settingsService.setSleepTimerDuration(parsed);
});
await _settingsService.setSleepTimerDuration(parsed);
if (dialogContext.mounted) {
Navigator.pop(dialogContext);
}
}
},
child: Text(t.common.save),
),
],
);
},
);
},
);
}
void _showAutoSkipDelayDialog() {
final controller = TextEditingController(text: _autoSkipDelay.toString());
String? errorText;
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
title: Text(t.settings.autoSkipDelay),
content: TextField(
controller: controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: t.settings.secondsLabel,
hintText: t.settings.durationHint(min: 1, max: 30),
errorText: errorText,
suffixText: t.settings.secondsShort,
),
autofocus: true,
onChanged: (value) {
final parsed = int.tryParse(value);
setDialogState(() {
if (parsed == null) {
errorText = t.settings.validationErrorEnterNumber;
} else if (parsed < 1 || parsed > 30) {
errorText = t.settings.validationErrorDuration(
min: 1,
max: 30,
unit: t.settings.secondsLabel.toLowerCase(),
);
} else {
errorText = null;
}
});
},
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(t.common.cancel),
),
TextButton(
onPressed: () async {
final parsed = int.tryParse(controller.text);
if (parsed != null && parsed >= 1 && parsed <= 30) {
setState(() {
_autoSkipDelay = parsed;
});
await _settingsService.setAutoSkipDelay(parsed);
if (dialogContext.mounted) {
Navigator.pop(dialogContext);
}
@@ -1,8 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flex_color_picker/flex_color_picker.dart';
import '../i18n/strings.g.dart';
import '../services/settings_service.dart';
import '../widgets/desktop_app_bar.dart';
import '../../i18n/strings.g.dart';
import '../../services/settings_service.dart';
import '../../widgets/desktop_app_bar.dart';
class SubtitleStylingScreen extends StatefulWidget {
const SubtitleStylingScreen({super.key});
+428 -133
View File
@@ -3,25 +3,29 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:os_media_controls/os_media_controls.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../mpv/mpv.dart';
import '../../services/plex_client.dart';
import '../models/plex_media_version.dart';
import '../models/plex_metadata.dart';
import '../models/plex_media_info.dart';
import '../providers/playback_state_provider.dart';
import '../services/episode_navigation_service.dart';
import '../services/media_controls_manager.dart';
import '../services/playback_initialization_service.dart';
import '../services/playback_progress_tracker.dart';
import '../services/settings_service.dart';
import '../services/track_selection_service.dart';
import '../services/video_filter_manager.dart';
import '../providers/user_profile_provider.dart';
import '../utils/app_logger.dart';
import '../utils/orientation_helper.dart';
import '../utils/platform_detector.dart';
import '../utils/provider_extensions.dart';
import '../utils/language_codes.dart';
import '../utils/video_player_navigation.dart';
import '../widgets/video_controls/video_controls.dart';
import '../i18n/strings.g.dart';
@@ -49,7 +53,6 @@ class VideoPlayerScreen extends StatefulWidget {
class VideoPlayerScreenState extends State<VideoPlayerScreen>
with WidgetsBindingObserver {
Player? player;
VideoController? controller;
bool _isPlayerInitialized = false;
PlexMetadata? _nextEpisode;
PlexMetadata? _previousEpisode;
@@ -57,6 +60,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
bool _showPlayNextDialog = false;
bool _isPhone = false;
List<PlexMediaVersion> _availableVersions = [];
PlexMediaInfo? _currentMediaInfo;
StreamSubscription<PlayerLog>? _logSubscription;
StreamSubscription<String>? _errorSubscription;
StreamSubscription<bool>? _playingSubscription;
@@ -66,6 +70,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
StreamSubscription<Tracks>? _trackLoadingSubscription;
bool _isReplacingWithVideo =
false; // Flag to skip orientation restoration during video-to-video navigation
bool _isDisposingForNavigation = false;
// App lifecycle state tracking
bool _wasPlayingBeforeInactive = false;
@@ -212,6 +217,29 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
}
}
/// Converts a 2-letter code like "fr", "nl", "ca" to a Plex 3-letter code, or returns null if unknown
String? _iso6391ToPlex6392(String? code) {
if (code == null || code.isEmpty) return null;
// Takes the base "fr" from "fr-FR"
final lang = code.split('-').first.toLowerCase();
// Use LanguageCodes utility to get variations and find the 639-2 code
try {
final variations = LanguageCodes.getVariations(lang);
// The getVariations method returns all variations including 639-2 codes
// We need to find the 3-letter code from the variations
for (final variation in variations) {
if (variation.length == 3) {
return variation;
}
}
return null;
} catch (e) {
// If LanguageCodes is not initialized or fails, return null
return null;
}
}
Future<void> _initializePlayer() async {
try {
// Load buffer size from settings
@@ -222,57 +250,75 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
.getEnableHardwareDecoding();
final debugLoggingEnabled = settingsService.getEnableDebugLogging();
// Build MPV configuration
final config = <String, String>{
'sub-font-size': settingsService.getSubtitleFontSize().toString(),
'sub-color': settingsService.getSubtitleTextColor(),
'sub-border-size': settingsService.getSubtitleBorderSize().toString(),
'sub-border-color': settingsService.getSubtitleBorderColor(),
'sub-back-color':
'#${(settingsService.getSubtitleBackgroundOpacity() * 255 / 100).toInt().toRadixString(16).padLeft(2, '0').toUpperCase()}${settingsService.getSubtitleBackgroundColor().replaceFirst('#', '')}',
'sub-ass-override': 'no',
};
// Create player
player = Player();
await player!.setProperty('sub-ass', 'yes'); // Enable libass
await player!.setProperty(
'demuxer-max-bytes',
bufferSizeBytes.toString(),
);
await player!.setProperty(
'msg-level',
debugLoggingEnabled ? 'all=debug' : 'all=error',
);
await player!.setProperty(
'hwdec',
_getHwdecValue(enableHardwareDecoding),
);
// Subtitle styling
await player!.setProperty(
'sub-font-size',
settingsService.getSubtitleFontSize().toString(),
);
await player!.setProperty(
'sub-color',
settingsService.getSubtitleTextColor(),
);
await player!.setProperty(
'sub-border-size',
settingsService.getSubtitleBorderSize().toString(),
);
await player!.setProperty(
'sub-border-color',
settingsService.getSubtitleBorderColor(),
);
final bgOpacity =
(settingsService.getSubtitleBackgroundOpacity() * 255 / 100).toInt();
final bgColor = settingsService.getSubtitleBackgroundColor().replaceFirst(
'#',
'',
);
await player!.setProperty(
'sub-back-color',
'#${bgOpacity.toRadixString(16).padLeft(2, '0').toUpperCase()}$bgColor',
);
await player!.setProperty('sub-ass-override', 'no');
// Platform-specific settings
if (Platform.isIOS) {
config['audio-exclusive'] = 'yes';
await player!.setProperty('audio-exclusive', 'yes');
}
// Create player with configuration
player = Player(
configuration: PlayerConfiguration(
libass: true,
libassAndroidFont: 'assets/droid-sans.ttf',
libassAndroidFontName: 'Droid Sans Fallback',
bufferSize: bufferSizeBytes,
logLevel: debugLoggingEnabled ? MPVLogLevel.debug : MPVLogLevel.error,
mpvConfiguration: config,
),
);
controller = VideoController(
player!,
configuration: VideoControllerConfiguration(
enableHardwareAcceleration: enableHardwareDecoding,
),
);
// HDR is controlled via custom hdr-enabled property on iOS/macOS/Windows
if (Platform.isIOS || Platform.isMacOS || Platform.isWindows) {
final enableHDR = settingsService.getEnableHDR();
await player!.setProperty('hdr-enabled', enableHDR ? 'yes' : 'no');
}
// Apply audio sync offset
final audioSyncOffset = settingsService.getAudioSyncOffset();
if (audioSyncOffset != 0) {
final offsetSeconds = audioSyncOffset / 1000.0;
await (player!.platform as dynamic).setProperty(
'audio-delay',
offsetSeconds.toString(),
);
await player!.setProperty('audio-delay', offsetSeconds.toString());
}
// Apply subtitle sync offset
final subtitleSyncOffset = settingsService.getSubtitleSyncOffset();
if (subtitleSyncOffset != 0) {
final offsetSeconds = subtitleSyncOffset / 1000.0;
await (player!.platform as dynamic).setProperty(
'sub-delay',
offsetSeconds.toString(),
);
await player!.setProperty('sub-delay', offsetSeconds.toString());
}
// Apply saved volume
@@ -310,23 +356,23 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
}
// Listen to playback state changes
_playingSubscription = player!.stream.playing.listen(
_playingSubscription = player!.streams.playing.listen(
_onPlayingStateChanged,
);
// Listen to completion
_completedSubscription = player!.stream.completed.listen(
_completedSubscription = player!.streams.completed.listen(
_onVideoCompleted,
);
// Listen to MPV logs
_logSubscription = player!.stream.log.listen(_onPlayerLog);
_logSubscription = player!.streams.log.listen(_onPlayerLog);
// Listen to MPV errors
_errorSubscription = player!.stream.error.listen(_onPlayerError);
_errorSubscription = player!.streams.error.listen(_onPlayerError);
// Listen to buffering state
_bufferingSubscription = player!.stream.buffering.listen((isBuffering) {
_bufferingSubscription = player!.streams.buffering.listen((isBuffering) {
_isBuffering.value = isBuffering;
});
@@ -348,6 +394,56 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
}
}
/// Add external subtitle tracks to the player
Future<void> _addExternalSubtitles(
List<SubtitleTrack> externalSubtitles,
) async {
if (player == null || externalSubtitles.isEmpty) return;
appLogger.d(
'Adding ${externalSubtitles.length} external subtitle(s) to player',
);
// Wait for media to be ready
await _waitForMediaReady();
for (final subtitleTrack in externalSubtitles) {
if (subtitleTrack.uri == null) continue;
try {
await player!.addSubtitleTrack(
uri: subtitleTrack.uri!,
title: subtitleTrack.title,
language: subtitleTrack.language,
select: false, // Don't auto-select
);
appLogger.d(
'Added external subtitle: ${subtitleTrack.title ?? subtitleTrack.uri}',
);
} catch (e) {
appLogger.w(
'Failed to add external subtitle: ${subtitleTrack.title ?? subtitleTrack.uri}',
error: e,
);
}
}
}
/// Wait for media to be ready (duration > 0)
Future<void> _waitForMediaReady() async {
if (player == null) return;
int attempts = 0;
while (player!.state.duration.inMilliseconds == 0 && attempts < 100) {
await Future.delayed(const Duration(milliseconds: 100));
attempts++;
}
if (attempts >= 100) {
appLogger.w('Media ready timeout - proceeding anyway');
}
}
/// Initialize the service layer
Future<void> _initializeServices() async {
if (!mounted || player == null) return;
@@ -424,12 +520,12 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
);
// Listen to playing state and update media controls
player!.stream.playing.listen((isPlaying) {
player!.streams.playing.listen((isPlaying) {
_updateMediaControlsPlaybackState();
});
// Listen to position updates for media controls
player!.stream.position.listen((position) {
player!.streams.position.listen((position) {
_mediaControlsManager?.updatePlaybackState(
isPlaying: player!.state.playing,
position: position,
@@ -542,30 +638,29 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
// Use server-specific client for this metadata
final client = _getClientForMetadata(context);
// Capture profile settings before async gap
final profileSettings = context.profileSettings;
// Initialize playback service
final playbackService = PlaybackInitializationService(
player: player!,
client: client,
context: context,
);
final playbackService = PlaybackInitializationService(client: client);
// Start playback and get available versions
final result = await playbackService.startPlayback(
// Get playback data (video URL and available versions)
final result = await playbackService.getPlaybackData(
metadata: widget.metadata,
selectedMediaIndex: widget.selectedMediaIndex,
profileSettings: profileSettings,
preferredAudioTrack: widget.preferredAudioTrack,
preferredSubtitleTrack: widget.preferredSubtitleTrack,
preferredPlaybackRate: widget.preferredPlaybackRate,
);
// Open video through Player
if (result.videoUrl != null) {
// Pass resume position if available
final resumePosition = widget.metadata.viewOffset != null
? Duration(milliseconds: widget.metadata.viewOffset!)
: null;
await player!.open(Media(result.videoUrl!, start: resumePosition));
}
// Update available versions from the playback data
if (mounted) {
setState(() {
_availableVersions = result.availableVersions.cast();
_currentMediaInfo = result.mediaInfo;
});
// Initialize video filter manager with player and available versions
@@ -578,10 +673,26 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
// Update video filter once dimensions are available
_videoFilterManager!.updateVideoFilter();
}
// Add external subtitles to the player
if (result.externalSubtitles.isNotEmpty) {
await _addExternalSubtitles(result.externalSubtitles);
}
}
// Track selection is now handled inside PlaybackInitializationService
// to ensure tracks are selected BEFORE seeking to resume position
// Set up track loading subscription to apply track selection when tracks are loaded
_trackLoadingSubscription?.cancel();
_trackLoadingSubscription = player!.streams.tracks.listen((tracks) {
// Only process when we have actual tracks loaded
if (tracks.audio.isEmpty && tracks.subtitle.isEmpty) return;
// Cancel subscription after first load to avoid re-applying on every track change
_trackLoadingSubscription?.cancel();
_trackLoadingSubscription = null;
// Apply track selection using the service
_applyTrackSelection();
});
} on PlaybackException catch (e) {
if (mounted) {
ScaffoldMessenger.of(
@@ -640,20 +751,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
_mediaControlsManager?.clear();
_mediaControlsManager?.dispose();
// Clear video filter and reset subtitle margins before disposing player
try {
if (player != null) {
final nativePlayer = player!.platform as dynamic;
nativePlayer.setProperty('vf', '');
nativePlayer.setProperty('sub-margin-x', '0');
nativePlayer.setProperty('sub-margin-y', '0');
nativePlayer.setProperty('sub-scale', '1.0');
}
} catch (e) {
// Non-critical: Cleanup operations during disposal
appLogger.d('Error during player cleanup in dispose', error: e);
}
// Restore system UI and orientation preferences (skip if navigating to another video)
if (!_isReplacingWithVideo) {
OrientationHelper.restoreSystemUI();
@@ -702,24 +799,24 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
void _onPlayerLog(PlayerLog log) {
// Map MPV log levels to app logger levels
switch (log.level.toLowerCase()) {
case 'fatal':
case 'error':
switch (log.level) {
case PlayerLogLevel.fatal:
case PlayerLogLevel.error:
appLogger.e('[MPV:${log.prefix}] ${log.text}');
break;
case 'warn':
case PlayerLogLevel.warn:
appLogger.w('[MPV:${log.prefix}] ${log.text}');
break;
case 'info':
case PlayerLogLevel.info:
appLogger.i('[MPV:${log.prefix}] ${log.text}');
break;
case 'debug':
case 'trace':
case 'v':
case PlayerLogLevel.debug:
case PlayerLogLevel.trace:
case PlayerLogLevel.verbose:
appLogger.d('[MPV:${log.prefix}] ${log.text}');
break;
default:
appLogger.d('[MPV:${log.prefix}:${log.level}] ${log.text}');
appLogger.d('[MPV:${log.prefix}:${log.level.name}] ${log.text}');
}
}
@@ -757,7 +854,26 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
await _navigateToEpisode(_previousEpisode!);
}
/// Handle audio track changes from the user - save as per-media preference if enabled
/// Apply track selection using the TrackSelectionService
Future<void> _applyTrackSelection() async {
if (!mounted || player == null) return;
final profileSettings = context.read<UserProfileProvider>().profileSettings;
final trackService = TrackSelectionService(
player: player!,
profileSettings: profileSettings,
metadata: widget.metadata,
);
await trackService.selectAndApplyTracks(
preferredAudioTrack: widget.preferredAudioTrack,
preferredSubtitleTrack: widget.preferredSubtitleTrack,
preferredPlaybackRate: widget.preferredPlaybackRate,
);
}
/// Handle audio track changes from the user - save both stream selection and language preference
Future<void> _onAudioTrackChanged(AudioTrack track) async {
final settings = await SettingsService.getInstance();
@@ -765,41 +881,101 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
if (!settings.getRememberTrackSelections()) {
return;
}
// Extract language code from the track
final languageCode = track.language;
if (languageCode == null || languageCode.isEmpty) {
appLogger.d('Audio track has no language code, not saving preference');
if (_currentMediaInfo == null) {
appLogger.w('No media info available, cannot save stream selection');
return;
}
final partId = _currentMediaInfo!.getPartId();
if (partId == null) {
appLogger.w('No part ID available, cannot save stream selection');
return;
}
// Determine which ratingKey to use
// For TV shows: use grandparentRatingKey (series level)
// For movies: use ratingKey (movie level)
final languageCode = track.language;
int? streamID;
// === Matching by attributes ===
PlexAudioTrack? matched;
final normalizedTrackLang = _iso6391ToPlex6392(track.language);
appLogger.d(
'Normalized media_kit language: ${track.language} -> $normalizedTrackLang',
);
for (final plexTrack in _currentMediaInfo!.audioTracks) {
final matchLang = plexTrack.languageCode == normalizedTrackLang;
final matchTitle = (track.title == null || track.title!.isEmpty)
? true
: (plexTrack.displayTitle == track.title ||
plexTrack.title == track.title);
if (matchLang && matchTitle) {
matched = plexTrack;
appLogger.d('Matched audio by lang/title: streamID ${matched.id}');
break;
}
}
if (matched != null) {
streamID = matched.id;
appLogger.d('Matched audio by lang/title: streamID $streamID');
} else {
appLogger.w('Could not match audio track, using fallback index');
// Fallback - normally no offset for audio
try {
final trackIndex = int.parse(track.id);
if (trackIndex >= 0 &&
trackIndex < _currentMediaInfo!.audioTracks.length) {
streamID = _currentMediaInfo!.audioTracks[trackIndex].id;
appLogger.d(
'Using fallback: audio index $trackIndex -> streamID $streamID',
);
} else {
appLogger.e(
'Fallback index $trackIndex out of bounds (total: ${_currentMediaInfo!.audioTracks.length})',
);
}
} catch (e) {
appLogger.e('Failed to parse track index', error: e);
}
}
final isEpisode = widget.metadata.type.toLowerCase() == 'episode';
final targetRatingKey = isEpisode
final languagePrefRatingKey = isEpisode
? (widget.metadata.grandparentRatingKey ?? widget.metadata.ratingKey)
: widget.metadata.ratingKey;
appLogger.i(
'Saving audio language preference: $languageCode for ${isEpisode ? "series" : "movie"} (ratingKey: $targetRatingKey)',
);
try {
if (!mounted) return;
// Use server-specific client for this metadata
final client = _getClientForMetadata(context);
await client.setMetadataPreferences(
targetRatingKey,
audioLanguage: languageCode,
);
appLogger.d('Successfully saved audio language preference');
final futures = <Future>[];
// 1. Language preference (series/movie level)
if (languageCode != null && languageCode.isNotEmpty) {
futures.add(
client.setMetadataPreferences(
languagePrefRatingKey,
audioLanguage: languageCode,
),
);
}
// 2. Exact stream selection (part level)
if (streamID != null) {
futures.add(
client.selectStreams(partId, audioStreamID: streamID, allParts: true),
);
}
await Future.wait(futures);
appLogger.d('Successfully saved audio preferences (language + stream)');
} catch (e) {
appLogger.e('Failed to save audio language preference', error: e);
appLogger.e('Failed to save audio preferences', error: e);
}
}
/// Handle subtitle track changes from the user - save as per-media preference if enabled
/// Handle subtitle track changes from the user - save both stream selection and language preference
Future<void> _onSubtitleTrackChanged(SubtitleTrack track) async {
final settings = await SettingsService.getInstance();
@@ -808,42 +984,127 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
return;
}
// Handle "Off" selection
if (_currentMediaInfo == null) {
appLogger.w('No media info available, cannot save stream selection');
return;
}
final partId = _currentMediaInfo!.getPartId();
if (partId == null) {
appLogger.w('No part ID available, cannot save stream selection');
return;
}
String? languageCode;
int? streamID;
if (track.id == 'no') {
languageCode = 'none';
streamID = 0;
appLogger.i('User turned subtitles off, saving preference');
} else {
languageCode = track.language;
if (languageCode == null || languageCode.isEmpty) {
// === Matching by attributes ===
PlexSubtitleTrack? matched;
final normalizedTrackLang = _iso6391ToPlex6392(track.language);
appLogger.d(
'Normalized media_kit language: ${track.language} -> $normalizedTrackLang',
);
for (final plexTrack in _currentMediaInfo!.subtitleTracks) {
final matchLang = plexTrack.languageCode == normalizedTrackLang;
final matchTitle = (track.title == null || track.title!.isEmpty)
? true
: (plexTrack.displayTitle == track.title ||
plexTrack.title == track.title);
appLogger.d('Comparing with streamID ${plexTrack.id}:');
appLogger.d(
'Subtitle track has no language code, not saving preference',
' matchLang: $matchLang (${plexTrack.languageCode} == $normalizedTrackLang)',
);
return;
appLogger.d(' matchTitle: $matchTitle');
if (matchLang && matchTitle) {
matched = plexTrack;
appLogger.d(' ✅ MATCHED!');
break;
}
}
if (matched != null) {
streamID = matched.id;
appLogger.d('Matched subtitle by lang/title: streamID $streamID');
} else {
appLogger.w('Could not match subtitle track, using fallback index');
// Fallback with offset correction
try {
final trackIndex = int.parse(track.id);
// media kit has a "no" (off) at index 0, so real subtitles start at 1
// We need to subtract 1 to get the actual index in PlexMediaInfo
final plexIndex = trackIndex > 0 ? trackIndex - 1 : 0;
if (plexIndex >= 0 &&
plexIndex < _currentMediaInfo!.subtitleTracks.length) {
streamID = _currentMediaInfo!.subtitleTracks[plexIndex].id;
appLogger.d(
'Using fallback: media_kit index $trackIndex -> Plex index $plexIndex -> streamID $streamID',
);
} else {
appLogger.e(
'Fallback index $plexIndex out of bounds (total: ${_currentMediaInfo!.subtitleTracks.length})',
);
}
} catch (e) {
appLogger.e('Failed to parse track index', error: e);
}
}
}
// Determine which ratingKey to use
// Determine ratingKeys
final isEpisode = widget.metadata.type.toLowerCase() == 'episode';
final targetRatingKey = isEpisode
final languagePrefRatingKey = isEpisode
? (widget.metadata.grandparentRatingKey ?? widget.metadata.ratingKey)
: widget.metadata.ratingKey;
appLogger.i(
'Saving subtitle language preference: $languageCode for ${isEpisode ? "series" : "movie"} (ratingKey: $targetRatingKey)',
'Saving subtitle preference: language=$languageCode (ratingKey: $languagePrefRatingKey), streamID=$streamID (partId: $partId)',
);
try {
if (!mounted) return;
// Use server-specific client for this metadata
final client = _getClientForMetadata(context);
await client.setMetadataPreferences(
targetRatingKey,
subtitleLanguage: languageCode,
final futures = <Future>[];
// 1. Save language preference at series/movie level
if (languageCode != null) {
futures.add(
client.setMetadataPreferences(
languagePrefRatingKey,
subtitleLanguage: languageCode,
),
);
}
// 2. Save exact stream selection using part ID
if (streamID != null) {
futures.add(
client.selectStreams(
partId,
subtitleStreamID: streamID,
allParts: true,
),
);
}
await Future.wait(futures);
appLogger.d(
'Successfully saved subtitle preferences (language + stream)',
);
appLogger.d('Successfully saved subtitle language preference');
} catch (e) {
appLogger.e('Failed to save subtitle language preference', error: e);
appLogger.e('Failed to save subtitle preferences', error: e);
}
}
@@ -892,6 +1153,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
_progressTracker?.sendProgress('stopped');
_progressTracker?.stopTracking();
// Ensure the native player is fully disposed before creating the next one
await disposePlayerForNavigation();
// Navigate to the episode using pushReplacement to destroy current player
if (mounted) {
navigateToVideoPlayer(
@@ -905,10 +1169,27 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
}
}
/// Dispose the player before replacing the video to avoid race conditions
Future<void> disposePlayerForNavigation() async {
if (_isDisposingForNavigation) return;
_isDisposingForNavigation = true;
try {
_progressTracker?.sendProgress('stopped');
_progressTracker?.stopTracking();
await player?.dispose();
} catch (e) {
appLogger.d('Error disposing player before navigation', error: e);
} finally {
player = null;
_isPlayerInitialized = false;
}
}
@override
Widget build(BuildContext context) {
// Show loading indicator while player initializes
if (!_isPlayerInitialized || controller == null || player == null) {
if (!_isPlayerInitialized || player == null) {
return const Scaffold(
backgroundColor: Colors.black,
body: Center(child: CircularProgressIndicator(color: Colors.white)),
@@ -928,7 +1209,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
}
},
child: Scaffold(
backgroundColor: Colors.black,
// Use transparent background on macOS when native video layer is active
backgroundColor: Colors.transparent,
body: GestureDetector(
behavior: HitTestBehavior
.translucent, // Allow taps to pass through to controls
@@ -967,19 +1249,19 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
constraints.maxHeight,
);
// Update player size in video filter manager
if (_videoFilterManager != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
_videoFilterManager!.updatePlayerSize(newSize);
}
});
}
// Update player size in video filter manager and native layer
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && player != null) {
_videoFilterManager?.updatePlayerSize(newSize);
// Update Metal layer frame on iOS/macOS for rotation
player!.updateFrame();
}
});
return Video(
controller: controller!,
player: player!,
fit: _videoFilterManager?.currentBoxFit ?? BoxFit.contain,
controls: (state) => plexVideoControlsBuilder(
controls: (context) => plexVideoControlsBuilder(
player!,
widget.metadata,
onNext: _nextEpisode != null ? _playNext : null,
@@ -1137,3 +1419,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
);
}
}
/// Returns the appropriate hwdec value based on platform and user preference.
String _getHwdecValue(bool enabled) {
if (!enabled) return 'no';
if (Platform.isMacOS || Platform.isIOS) {
return 'videotoolbox';
} else if (Platform.isAndroid) {
return 'mediacodec-copy';
} else {
return 'auto'; // Windows, Linux
}
}
+115 -9
View File
@@ -1,6 +1,6 @@
import 'dart:async';
import '../client/plex_client.dart';
import 'plex_client.dart';
import '../models/plex_hub.dart';
import '../models/plex_library.dart';
import '../models/plex_metadata.dart';
@@ -12,8 +12,29 @@ import 'plex_auth_service.dart';
class DataAggregationService {
final MultiServerManager _serverManager;
// Cache for libraries with TTL
Map<String, List<PlexLibrary>>? _cachedLibrariesByServer;
DateTime? _librariesCacheTime;
static const Duration _librariesCacheTTL = Duration(hours: 1);
DataAggregationService(this._serverManager);
/// Clear the libraries cache (useful for server changes or logout)
void clearCache() {
_cachedLibrariesByServer = null;
_librariesCacheTime = null;
}
/// Check if libraries cache is still valid
bool get _isLibrariesCacheValid {
if (_cachedLibrariesByServer == null || _librariesCacheTime == null) {
return false;
}
final cacheAge = DateTime.now().difference(_librariesCacheTime!);
return cacheAge < _librariesCacheTTL;
}
/// Fetch libraries from all online servers
/// Libraries are automatically tagged with server info by PlexClient
Future<List<PlexLibrary>> getLibrariesFromAllServers() async {
@@ -53,8 +74,68 @@ class DataAggregationService {
return result;
}
/// Fetch recommendation hubs from all servers
Future<List<PlexHub>> getHubsFromAllServers({int? limit}) async {
/// Fetch libraries from all servers and cache them for hub fetching
/// This allows libraries to be fetched in parallel with other operations
Future<Map<String, List<PlexLibrary>>> getLibrariesFromAllServersGrouped({
bool forceRefresh = false,
}) async {
// Return cached libraries if still valid and not forcing refresh
if (!forceRefresh && _isLibrariesCacheValid) {
appLogger.d('Using cached libraries data');
return _cachedLibrariesByServer!;
}
final clients = _serverManager.onlineClients;
if (clients.isEmpty) {
appLogger.w('No online servers available for fetching libraries');
return {};
}
appLogger.d('Fetching libraries from ${clients.length} servers');
final libraryFutures = clients.entries.map((entry) async {
final serverId = entry.key;
final client = entry.value;
try {
final libraries = await client.getLibraries();
appLogger.d(
'Fetched ${libraries.length} libraries for server $serverId',
);
return MapEntry(serverId, libraries);
} catch (e) {
appLogger.e(
'Failed to fetch libraries from server $serverId',
error: e,
);
return MapEntry(serverId, <PlexLibrary>[]);
}
});
final libraryResults = await Future.wait(libraryFutures);
final librariesByServer = Map.fromEntries(libraryResults);
final totalLibraries = libraryResults.fold<int>(
0,
(sum, entry) => sum + entry.value.length,
);
// Cache the results
_cachedLibrariesByServer = librariesByServer;
_librariesCacheTime = DateTime.now();
appLogger.d(
'Fetched $totalLibraries libraries from ${clients.length} servers',
);
return librariesByServer;
}
/// Fetch recommendation hubs from all servers using pre-fetched libraries
Future<List<PlexHub>> getHubsFromAllServers({
int? limit,
Map<String, List<PlexLibrary>>? librariesByServer,
Set<String>? hiddenLibraryKeys,
}) async {
final clients = _serverManager.onlineClients;
if (clients.isEmpty) {
@@ -62,27 +143,40 @@ class DataAggregationService {
return [];
}
// Use pre-fetched libraries or fetch them if not provided
final libraries =
librariesByServer ?? await getLibrariesFromAllServersGrouped();
appLogger.d('Fetching hubs from ${clients.length} servers');
final allHubs = <PlexHub>[];
// Fetch from all servers in parallel
// Fetch from all servers in parallel using cached libraries
final hubFutures = clients.entries.map((entry) async {
final serverId = entry.key;
final client = entry.value;
try {
// Get libraries for this server
final libraries = await client.getLibraries();
// Use pre-fetched libraries for this server
final serverLibraries = libraries[serverId] ?? <PlexLibrary>[];
if (serverLibraries.isEmpty) {
appLogger.w('No libraries available for server $serverId');
return <PlexHub>[];
}
// Filter to only visible movie/show libraries
final visibleLibraries = libraries.where((library) {
final visibleLibraries = serverLibraries.where((library) {
if (library.type != 'movie' && library.type != 'show') {
return false;
}
if (library.hidden != null && library.hidden != 0) {
return false;
}
// Check app-level hidden libraries
if (hiddenLibraryKeys != null &&
hiddenLibraryKeys.contains(library.globalKey)) {
return false;
}
return true;
}).toList();
@@ -90,7 +184,11 @@ class DataAggregationService {
final libraryHubFutures = visibleLibraries.map((library) async {
try {
// Hubs are now tagged with server info at the source
return await client.getLibraryHubs(library.key);
final hubs = await client.getLibraryHubs(library.key);
appLogger.d(
'Fetched ${hubs.length} hubs for ${library.title} on $serverId',
);
return hubs;
} catch (e) {
appLogger.w(
'Failed to fetch hubs for library ${library.title}: $e',
@@ -239,9 +337,14 @@ class DataAggregationService {
final serverId = entry.key;
final client = entry.value;
final server = _serverManager.getServer(serverId);
final sw = Stopwatch()..start();
try {
return await operation(serverId, client, server);
final result = await operation(serverId, client, server);
appLogger.d(
'$operationName for server $serverId completed in ${sw.elapsedMilliseconds}ms with ${result.length} items',
);
return result;
} catch (e, stackTrace) {
appLogger.e(
'Failed $operationName from server $serverId',
@@ -249,6 +352,9 @@ class DataAggregationService {
stackTrace: stackTrace,
);
_serverManager.updateServerStatus(serverId, false);
appLogger.d(
'$operationName for server $serverId failed after ${sw.elapsedMilliseconds}ms',
);
return <T>[];
}
});
+3 -3
View File
@@ -1,8 +1,8 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../mpv/mpv.dart';
import 'plex_client.dart';
import '../models/plex_metadata.dart';
import '../providers/playback_state_provider.dart';
import '../utils/app_logger.dart';
@@ -93,7 +93,7 @@ class EpisodeNavigationService {
currentPlaybackRate = player.state.rate;
appLogger.d(
'Navigating to episode with preserved settings - Audio: ${currentAudioTrack.id}, Subtitle: ${currentSubtitleTrack.id}, Rate: ${currentPlaybackRate}x',
'Navigating to episode with preserved settings - Audio: ${currentAudioTrack?.id}, Subtitle: ${currentSubtitleTrack?.id}, Rate: ${currentPlaybackRate}x',
);
}
+11 -3
View File
@@ -1,8 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import '../mpv/mpv.dart';
import 'settings_service.dart';
import '../utils/keyboard_utils.dart';
import '../utils/player_utils.dart';
class KeyboardShortcutsService {
@@ -153,10 +154,17 @@ class KeyboardShortcutsService {
VoidCallback? onNextAudioTrack,
VoidCallback? onNextSubtitleTrack,
VoidCallback? onNextChapter,
VoidCallback? onPreviousChapter,
) {
VoidCallback? onPreviousChapter, {
VoidCallback? onBack,
}) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
// Handle back navigation keys first
if (isBackKey(event.logicalKey)) {
onBack?.call();
return KeyEventResult.handled;
}
final physicalKey = event.physicalKey;
final isShiftPressed = HardwareKeyboard.instance.isShiftPressed;
final isControlPressed = HardwareKeyboard.instance.isControlPressed;

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