Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f9602a7f42 | ||
|
|
88588851c9 | ||
|
|
e3fbe6d925 | ||
|
|
27e88207fa | ||
|
|
9c6b7740cf | ||
|
|
109c3ffcfb | ||
|
|
328b978ade | ||
|
|
93cd7369a3 | ||
|
|
9d37443e4e | ||
|
|
0fc2708a51 | ||
|
|
b7ec24c2c1 | ||
|
|
2b9bb54caf | ||
|
|
cb5949fb5b | ||
|
|
09fc856ee6 | ||
|
|
f5dc67573c | ||
|
|
e11c7e3eed | ||
|
|
d31b4ab7a2 | ||
|
|
09f18692e8 | ||
|
|
5e3178e6fe | ||
|
|
54e8e0c621 | ||
|
|
9777344edc | ||
|
|
bafc557370 | ||
|
|
99f3e78a30 | ||
|
|
ec57cd436e | ||
|
|
8c97df6ff5 | ||
|
|
264dcb196d | ||
|
|
e55a2a89dc | ||
|
|
57d4630f26 | ||
|
|
bc9c2f53f2 | ||
|
|
e9b8457a62 | ||
|
|
ffbd504042 | ||
|
|
e77585ca6f | ||
|
|
5e62be3741 | ||
|
|
d755485c98 | ||
|
|
efcbccacf0 | ||
|
|
2101f0e450 | ||
|
|
efe9b86707 | ||
|
|
3a2f2c9c69 | ||
|
|
943f7dab08 | ||
|
|
12c4c389d1 | ||
|
|
0dbe9e99d4 | ||
|
|
d6c305ac46 | ||
|
|
3b7e8ff782 | ||
|
|
fb9105f84e | ||
|
|
19049365cc | ||
|
|
ddf28a0d1e | ||
|
|
bbe4174445 | ||
|
|
e1ae6b185e | ||
|
|
ff5f8d3e2a | ||
|
|
a55b03033f | ||
|
|
737da40bbd | ||
|
|
6720137edc | ||
|
|
a73518d963 | ||
|
|
43494c822e | ||
|
|
0d747554d5 | ||
|
|
aa718c37aa | ||
|
|
85d07a7f72 | ||
|
|
3a6db5d467 | ||
|
|
4af2dd016f | ||
|
|
8b8c249988 | ||
|
|
c4479660e9 | ||
|
|
c23908427e | ||
|
|
1c71e72a3c | ||
|
|
faf2602faa | ||
|
|
d338f69c41 | ||
|
|
0fd6a37800 | ||
|
|
0ffeb20ff9 | ||
|
|
b5726fe4b7 | ||
|
|
3b0c53d7f9 | ||
|
|
9721e6bf3f | ||
|
|
e18a9457dd | ||
|
|
852f778c42 | ||
|
|
45ff3faddb | ||
|
|
86bb43dfc8 | ||
|
|
91b11a5137 | ||
|
|
9d64589c3d | ||
|
|
ca9b6a9ecd | ||
|
|
42a6a85a89 | ||
|
|
aa60ab4412 | ||
|
|
9422979f3a | ||
|
|
ec74aadca7 | ||
|
|
0005d70bde | ||
|
|
9071eab3ae | ||
|
|
0290adcb6d | ||
|
|
103653ea47 | ||
|
|
60c95c58fe | ||
|
|
4edaf3ebea | ||
|
|
ea696b0b63 | ||
|
|
bfb973ab0f | ||
|
|
7755e07fa8 | ||
|
|
e497570aa7 | ||
|
|
045502405d | ||
|
|
09d79417fb | ||
|
|
3d196c76e3 | ||
|
|
a9344781f3 | ||
|
|
4df515f35f | ||
|
|
5cb4f79476 | ||
|
|
67a6bb29bf | ||
|
|
a87aa2968c | ||
|
|
80cae9e220 | ||
|
|
70f6e2142d | ||
|
|
37f025056c | ||
|
|
ea8ea6f059 | ||
|
|
05f4c9e1f6 | ||
|
|
3a18d07593 | ||
|
|
d2eaadb07d | ||
|
|
4db60bc7c2 | ||
|
|
27ff86f822 | ||
|
|
c4789070d0 | ||
|
|
c189bef42c | ||
|
|
aea4cfcf59 | ||
|
|
cffef8671e | ||
|
|
8e5b9de471 | ||
|
|
a91a419ef3 | ||
|
|
c71db8f9eb | ||
|
|
abe0919324 | ||
|
|
f4d3dbd7d8 | ||
|
|
570f1fdc58 | ||
|
|
da1a4e7aa8 | ||
|
|
5ed2532bf1 | ||
|
|
ed98a65c60 | ||
|
|
562b54d1cb | ||
|
|
85b056f3d0 | ||
|
|
da6ba9bd67 | ||
|
|
6bfda5e6d4 | ||
|
|
a10dfcc004 | ||
|
|
08f8d2373a | ||
|
|
ce6686e634 | ||
|
|
c53018b53b | ||
|
|
1191d8a438 | ||
|
|
1d67a5d992 | ||
|
|
e3c1cba600 | ||
|
|
a0f28b1dc7 | ||
|
|
442899eecd | ||
|
|
76db3cb450 | ||
|
|
bea485bddc | ||
|
|
b36e585fd7 | ||
|
|
8b89529ac8 | ||
|
|
8b3b8ad596 | ||
|
|
1d8a5ee23e | ||
|
|
4453eb995e | ||
|
|
9e506d3f68 | ||
|
|
a698ab0930 | ||
|
|
b0d669d93a | ||
|
|
8dafac4ea5 | ||
|
|
ef7fe85d5d |
@@ -84,8 +84,15 @@ body:
|
||||
attributes:
|
||||
label: Logs and Stack Traces
|
||||
description: Please paste any relevant logs or stack traces
|
||||
render: shell
|
||||
placeholder: Paste logs here
|
||||
value: |
|
||||
<details>
|
||||
<summary>Logs</summary>
|
||||
|
||||
```
|
||||
Paste logs here
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
- type: textarea
|
||||
id: screenshots
|
||||
|
||||
@@ -215,7 +215,7 @@ jobs:
|
||||
IDENTITY=$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -1 | grep -o '".*"' | tr -d '"')
|
||||
echo "Signing with identity: $IDENTITY"
|
||||
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
|
||||
# Sign all frameworks and dylibs first (inside-out signing)
|
||||
find "$APP_PATH/Contents/Frameworks" -name "*.framework" -o -name "*.dylib" | while read framework; do
|
||||
@@ -229,7 +229,7 @@ jobs:
|
||||
|
||||
- name: Verify Signature
|
||||
run: |
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
echo "Verifying signature..."
|
||||
codesign -dvvv "$APP_PATH"
|
||||
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
|
||||
@@ -240,7 +240,7 @@ jobs:
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
|
||||
# Create a temporary ZIP for notarization submission
|
||||
echo "Creating ZIP for notarization..."
|
||||
@@ -265,7 +265,7 @@ jobs:
|
||||
- name: Create DMG
|
||||
run: |
|
||||
mkdir -p dmg-staging
|
||||
cp -R build/macos/Build/Products/Release/plezy.app dmg-staging/
|
||||
cp -R build/macos/Build/Products/Release/Plezy.app dmg-staging/
|
||||
ln -s /Applications dmg-staging/Applications
|
||||
hdiutil create -format ULMO -srcfolder dmg-staging -volname "Plezy" plezy-macos.dmg
|
||||
|
||||
|
||||
+2
-2
@@ -57,8 +57,8 @@ This project uses `slang` for internationalization with JSON files.
|
||||
|
||||
### Adding New Languages
|
||||
|
||||
1. Create new JSON file: `lib/i18n/strings_[locale].i18n.json`
|
||||
2. Copy structure from `strings.i18n.json` and translate values
|
||||
1. Create new JSON file: `lib/i18n/[locale].i18n.json`
|
||||
2. Copy structure from `en.i18n.json` and translate values
|
||||
3. Run `dart run slang` to regenerate files
|
||||
|
||||
### Guidelines
|
||||
|
||||
@@ -22,6 +22,7 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
|
||||
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg)
|
||||
- [Linux (x64)](https://github.com/edde746/plezy/releases/latest) - .deb, .rpm, .pkg.tar.zst, and portable tar.gz available
|
||||
- [NixOS/Nix](https://github.com/mio-19/nurpkgs/tree/main/pkgs/plezy) - Community package by [@mio-19](https://github.com/mio-19)
|
||||
- [Homebrew](https://github.com/Tazi0/homebrew-plezy) - Community tap by [@Tazi0](https://github.com/Tazi0)
|
||||
|
||||
## Features
|
||||
|
||||
|
||||
@@ -57,6 +57,13 @@ android {
|
||||
// If key.properties doesn't exist, it will use debug signing for CI builds
|
||||
}
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// Resolve conflict between libass-android and libmpv native libraries
|
||||
pickFirsts.add("lib/*/libc++_shared.so")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flutter {
|
||||
@@ -65,4 +72,16 @@ flutter {
|
||||
|
||||
dependencies {
|
||||
implementation("dev.jdtech.mpv:libmpv:0.5.1")
|
||||
|
||||
// Media3 ExoPlayer for Android
|
||||
implementation("androidx.media3:media3-exoplayer:1.5.1")
|
||||
implementation("androidx.media3:media3-ui:1.5.1")
|
||||
implementation("androidx.media3:media3-common:1.5.1")
|
||||
implementation("androidx.media3:media3-session:1.5.1")
|
||||
|
||||
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
|
||||
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
|
||||
|
||||
// libass-android for ASS/SSA subtitle rendering
|
||||
implementation("io.github.peerless2012:ass-media:0.4.0-beta01")
|
||||
}
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
<!-- Internet access permissions -->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
|
||||
<!-- PIP Permissions -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
||||
|
||||
<!-- Media session permissions for OS media controls -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
||||
@@ -18,16 +22,23 @@
|
||||
<!-- Touchscreen not required for TV -->
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||
|
||||
<!-- Android Automotive OS support -->
|
||||
<uses-feature android:name="android.hardware.type.automotive" android:required="false" />
|
||||
|
||||
<application
|
||||
android:label="Plezy"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/ic_launcher">
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:banner="@drawable/tv_banner"
|
||||
android:appCategory="video"
|
||||
android:usesCleartextTraffic="true">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/LaunchTheme"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
|
||||
android:hardwareAccelerated="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.util.Rational
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.android.RenderMode
|
||||
import io.flutter.embedding.android.TransparencyMode
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import com.edde746.plezy.exoplayer.ExoPlayerPlugin
|
||||
import com.edde746.plezy.mpv.MpvPlayerPlugin
|
||||
|
||||
class MainActivity : FlutterActivity() {
|
||||
|
||||
private val PIP_CHANNEL = "app.plezy/pip"
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
// Disable Android's default focus highlight ring that appears when using
|
||||
// D-pad navigation so the Flutter UI can render its own focus state.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
window.decorView.defaultFocusHighlightEnabled = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun getRenderMode(): RenderMode {
|
||||
// Use TextureView so Flutter doesn't occupy a SurfaceView layer.
|
||||
// This allows the libass subtitle SurfaceView to sit between video and Flutter UI.
|
||||
return RenderMode.texture
|
||||
}
|
||||
|
||||
override fun getTransparencyMode(): TransparencyMode {
|
||||
// Keep Flutter transparent so video/subtitles are visible below.
|
||||
return TransparencyMode.transparent
|
||||
}
|
||||
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
flutterEngine.plugins.add(MpvPlayerPlugin())
|
||||
flutterEngine.plugins.add(ExoPlayerPlugin())
|
||||
|
||||
MethodChannel( flutterEngine.dartExecutor.binaryMessenger, PIP_CHANNEL ).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"isSupported" -> {
|
||||
result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
|
||||
}
|
||||
"enter" -> {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "android_version"))
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
// Check if PiP permission is granted via AppOpsManager
|
||||
val appOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
|
||||
val pipAllowed = appOpsManager.checkOpNoThrow(
|
||||
AppOpsManager.OPSTR_PICTURE_IN_PICTURE,
|
||||
applicationInfo.uid,
|
||||
packageName
|
||||
) == AppOpsManager.MODE_ALLOWED
|
||||
|
||||
if (!pipAllowed) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "permission_disabled"))
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
try {
|
||||
val width = call.argument<Int>("width") ?: 16
|
||||
val height = call.argument<Int>("height") ?: 9
|
||||
|
||||
// Android PiP requires aspect ratio between 0.418410 (5:12) and 2.39 (12:5)
|
||||
val ratio = width.toFloat() / height.toFloat()
|
||||
val clampedWidth: Int
|
||||
val clampedHeight: Int
|
||||
|
||||
when {
|
||||
ratio < 0.42f -> {
|
||||
// Too tall - clamp to minimum ratio (5:12)
|
||||
clampedWidth = 5
|
||||
clampedHeight = 12
|
||||
}
|
||||
ratio > 2.39f -> {
|
||||
// Too wide - clamp to maximum ratio (12:5)
|
||||
clampedWidth = 12
|
||||
clampedHeight = 5
|
||||
}
|
||||
else -> {
|
||||
clampedWidth = width
|
||||
clampedHeight = height
|
||||
}
|
||||
}
|
||||
|
||||
val params = PictureInPictureParams.Builder()
|
||||
.setAspectRatio(Rational(clampedWidth, clampedHeight))
|
||||
.build()
|
||||
val success = enterPictureInPictureMode(params)
|
||||
if (success) {
|
||||
result.success(mapOf("success" to true))
|
||||
} else {
|
||||
result.success(mapOf("success" to false, "errorCode" to "failed"))
|
||||
}
|
||||
} catch (e: IllegalStateException) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "not_supported"))
|
||||
} catch (e: Exception) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "unknown", "errorMessage" to (e.message ?: "Unknown error")))
|
||||
}
|
||||
} else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean,newConfig: Configuration) {
|
||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||
MethodChannel( flutterEngine!!.dartExecutor.binaryMessenger, PIP_CHANNEL ).invokeMethod( "onPipChanged" , isInPictureInPictureMode)
|
||||
|
||||
// Notify ExoPlayer plugin to resize video surface for PiP
|
||||
flutterEngine?.plugins?.get(ExoPlayerPlugin::class.java)?.let { plugin ->
|
||||
(plugin as? ExoPlayerPlugin)?.onPipModeChanged(isInPictureInPictureMode)
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,581 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.app.Activity
|
||||
import android.util.Log
|
||||
import com.edde746.plezy.mpv.MpvPlayerCore
|
||||
import com.edde746.plezy.mpv.MpvPlayerDelegate
|
||||
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 ExoPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
EventChannel.StreamHandler, ActivityAware, ExoPlayerDelegate, MpvPlayerDelegate {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ExoPlayerPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/exo_player"
|
||||
private const val EVENT_CHANNEL = "com.plezy/exo_player/events"
|
||||
}
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private lateinit var eventChannel: EventChannel
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
private var playerCore: ExoPlayerCore? = null
|
||||
private var mpvCore: MpvPlayerCore? = null // MPV fallback player
|
||||
private var usingMpvFallback: Boolean = false
|
||||
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
|
||||
mpvCore?.dispose()
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
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)
|
||||
"open" -> handleOpen(call, result)
|
||||
"play" -> handlePlay(result)
|
||||
"pause" -> handlePause(result)
|
||||
"stop" -> handleStop(result)
|
||||
"seek" -> handleSeek(call, result)
|
||||
"setVolume" -> handleSetVolume(call, result)
|
||||
"setRate" -> handleSetRate(call, result)
|
||||
"selectAudioTrack" -> handleSelectAudioTrack(call, result)
|
||||
"selectSubtitleTrack" -> handleSelectSubtitleTrack(call, result)
|
||||
"addSubtitleTrack" -> handleAddSubtitleTrack(call, result)
|
||||
"setVisible" -> handleSetVisible(call, result)
|
||||
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
|
||||
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
|
||||
"requestAudioFocus" -> handleRequestAudioFocus(result)
|
||||
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
|
||||
"isInitialized" -> result.success(
|
||||
if (usingMpvFallback) mpvCore?.isInitialized ?: false
|
||||
else playerCore?.isInitialized ?: false
|
||||
)
|
||||
"getStats" -> handleGetStats(result)
|
||||
"getPlayerType" -> result.success(if (usingMpvFallback) "mpv" else "exoplayer")
|
||||
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 = ExoPlayerCore(currentActivity).apply {
|
||||
delegate = this@ExoPlayerPlugin
|
||||
}
|
||||
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 {
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.dispose()
|
||||
mpvCore = null
|
||||
} else {
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
}
|
||||
usingMpvFallback = false
|
||||
Log.d(TAG, "Disposed")
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleOpen(call: MethodCall, result: MethodChannel.Result) {
|
||||
val uri = call.argument<String>("uri")
|
||||
val headers = call.argument<Map<String, String>>("headers")
|
||||
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
|
||||
val autoPlay = call.argument<Boolean>("autoPlay") ?: true
|
||||
|
||||
if (uri == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'uri'", null)
|
||||
return
|
||||
}
|
||||
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
// MPV: Build loadfile command with options
|
||||
val startSeconds = startPositionMs / 1000.0
|
||||
val options = mutableListOf<String>()
|
||||
options.add("start=$startSeconds")
|
||||
if (!autoPlay) options.add("pause=yes")
|
||||
headers?.forEach { (key, value) ->
|
||||
options.add("http-header-fields-append=$key: $value")
|
||||
}
|
||||
val optionsStr = options.joinToString(",")
|
||||
mpvCore?.command(arrayOf("loadfile", uri, "replace", "-1", optionsStr))
|
||||
} else {
|
||||
playerCore?.open(uri, headers, startPositionMs, autoPlay)
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
|
||||
private fun handlePlay(result: MethodChannel.Result) {
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.setProperty("pause", "no")
|
||||
} else {
|
||||
playerCore?.play()
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handlePause(result: MethodChannel.Result) {
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.setProperty("pause", "yes")
|
||||
} else {
|
||||
playerCore?.pause()
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleStop(result: MethodChannel.Result) {
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.command(arrayOf("stop"))
|
||||
mpvCore?.setVisible(false)
|
||||
} else {
|
||||
playerCore?.stop()
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSeek(call: MethodCall, result: MethodChannel.Result) {
|
||||
val positionMs = call.argument<Number>("positionMs")?.toLong()
|
||||
|
||||
if (positionMs == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'positionMs'", null)
|
||||
return
|
||||
}
|
||||
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
val positionSeconds = positionMs / 1000.0
|
||||
mpvCore?.command(arrayOf("seek", positionSeconds.toString(), "absolute"))
|
||||
} else {
|
||||
playerCore?.seekTo(positionMs)
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVolume(call: MethodCall, result: MethodChannel.Result) {
|
||||
val volume = call.argument<Number>("volume")?.toFloat()
|
||||
|
||||
if (volume == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'volume'", null)
|
||||
return
|
||||
}
|
||||
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.setProperty("volume", volume.toString())
|
||||
} else {
|
||||
playerCore?.setVolume(volume / 100f) // Convert 0-100 to 0-1
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetRate(call: MethodCall, result: MethodChannel.Result) {
|
||||
val rate = call.argument<Number>("rate")?.toFloat()
|
||||
|
||||
if (rate == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'rate'", null)
|
||||
return
|
||||
}
|
||||
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.setProperty("speed", rate.toString())
|
||||
} else {
|
||||
playerCore?.setPlaybackSpeed(rate)
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSelectAudioTrack(call: MethodCall, result: MethodChannel.Result) {
|
||||
val trackId = call.argument<String>("trackId")
|
||||
|
||||
if (trackId == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'trackId'", null)
|
||||
return
|
||||
}
|
||||
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
// MPV uses numeric track IDs - extract from string format
|
||||
val numericId = trackId.split("_").lastOrNull()?.toIntOrNull() ?: 1
|
||||
mpvCore?.setProperty("aid", numericId.toString())
|
||||
} else {
|
||||
playerCore?.selectAudioTrack(trackId)
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSelectSubtitleTrack(call: MethodCall, result: MethodChannel.Result) {
|
||||
val trackId = call.argument<String>("trackId")
|
||||
|
||||
// trackId can be null or "no" to disable subtitles
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
if (trackId == null || trackId == "no") {
|
||||
mpvCore?.setProperty("sid", "no")
|
||||
} else {
|
||||
val numericId = trackId.split("_").lastOrNull()?.toIntOrNull() ?: 1
|
||||
mpvCore?.setProperty("sid", numericId.toString())
|
||||
}
|
||||
} else {
|
||||
playerCore?.selectSubtitleTrack(trackId)
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleAddSubtitleTrack(call: MethodCall, result: MethodChannel.Result) {
|
||||
val uri = call.argument<String>("uri")
|
||||
val title = call.argument<String>("title")
|
||||
val language = call.argument<String>("language")
|
||||
val mimeType = call.argument<String>("mimeType")
|
||||
val select = call.argument<Boolean>("select") ?: false
|
||||
|
||||
if (uri == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'uri'", null)
|
||||
return
|
||||
}
|
||||
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
val selectFlag = if (select) "select" else "auto"
|
||||
mpvCore?.command(arrayOf("sub-add", uri, selectFlag, title ?: "External"))
|
||||
} else {
|
||||
playerCore?.addSubtitleTrack(uri, title, language, mimeType, select)
|
||||
}
|
||||
result.success(null)
|
||||
} ?: 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
|
||||
}
|
||||
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.setVisible(visible)
|
||||
} else {
|
||||
playerCore?.setVisible(visible)
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVideoFrameRate(call: MethodCall, result: MethodChannel.Result) {
|
||||
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
|
||||
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration")
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.setVideoFrameRate(fps, duration)
|
||||
} else {
|
||||
playerCore?.setVideoFrameRate(fps, duration)
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.clearVideoFrameRate()
|
||||
} else {
|
||||
playerCore?.clearVideoFrameRate()
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "requestAudioFocus")
|
||||
val granted = if (usingMpvFallback) {
|
||||
mpvCore?.requestAudioFocus() ?: false
|
||||
} else {
|
||||
playerCore?.requestAudioFocus() ?: false
|
||||
}
|
||||
result.success(granted)
|
||||
}
|
||||
|
||||
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "abandonAudioFocus")
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.abandonAudioFocus()
|
||||
} else {
|
||||
playerCore?.abandonAudioFocus()
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleGetStats(result: MethodChannel.Result) {
|
||||
activity?.runOnUiThread {
|
||||
val stats = if (usingMpvFallback) {
|
||||
// For MPV fallback, query MPV properties directly
|
||||
getMpvStats()
|
||||
} else {
|
||||
val coreStats = playerCore?.getStats() ?: emptyMap()
|
||||
coreStats + mapOf("playerType" to "exoplayer")
|
||||
}
|
||||
result.success(stats)
|
||||
} ?: result.success(mapOf("playerType" to "unknown"))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get playback stats from MPV when in fallback mode.
|
||||
* Queries relevant MPV properties and returns them in a map format
|
||||
* compatible with the performance overlay.
|
||||
*/
|
||||
private fun getMpvStats(): Map<String, Any?> {
|
||||
val mpv = mpvCore ?: return mapOf("playerType" to "mpv")
|
||||
|
||||
return mapOf(
|
||||
"playerType" to "mpv",
|
||||
// Video metrics
|
||||
"video-codec" to mpv.getProperty("video-codec"),
|
||||
"video-params/w" to mpv.getProperty("video-params/w"),
|
||||
"video-params/h" to mpv.getProperty("video-params/h"),
|
||||
"container-fps" to mpv.getProperty("container-fps"),
|
||||
"estimated-vf-fps" to mpv.getProperty("estimated-vf-fps"),
|
||||
"video-bitrate" to mpv.getProperty("video-bitrate"),
|
||||
"hwdec-current" to mpv.getProperty("hwdec-current"),
|
||||
// Audio metrics
|
||||
"audio-codec-name" to mpv.getProperty("audio-codec-name"),
|
||||
"audio-params/samplerate" to mpv.getProperty("audio-params/samplerate"),
|
||||
"audio-params/hr-channels" to mpv.getProperty("audio-params/hr-channels"),
|
||||
"audio-bitrate" to mpv.getProperty("audio-bitrate"),
|
||||
// Performance metrics
|
||||
"total-avsync-change" to mpv.getProperty("total-avsync-change"),
|
||||
"cache-used" to mpv.getProperty("cache-used"),
|
||||
"cache-speed" to mpv.getProperty("cache-speed"),
|
||||
"display-fps" to mpv.getProperty("display-fps"),
|
||||
"frame-drop-count" to mpv.getProperty("frame-drop-count"),
|
||||
"decoder-frame-drop-count" to mpv.getProperty("decoder-frame-drop-count"),
|
||||
"demuxer-cache-duration" to mpv.getProperty("demuxer-cache-duration"),
|
||||
// Color/Format properties
|
||||
"video-params/pixelformat" to mpv.getProperty("video-params/pixelformat"),
|
||||
"video-params/hw-pixelformat" to mpv.getProperty("video-params/hw-pixelformat"),
|
||||
"video-params/colormatrix" to mpv.getProperty("video-params/colormatrix"),
|
||||
"video-params/primaries" to mpv.getProperty("video-params/primaries"),
|
||||
"video-params/gamma" to mpv.getProperty("video-params/gamma"),
|
||||
// HDR metadata
|
||||
"video-params/max-luma" to mpv.getProperty("video-params/max-luma"),
|
||||
"video-params/min-luma" to mpv.getProperty("video-params/min-luma"),
|
||||
"video-params/max-cll" to mpv.getProperty("video-params/max-cll"),
|
||||
"video-params/max-fall" to mpv.getProperty("video-params/max-fall"),
|
||||
// Other
|
||||
"video-params/aspect-name" to mpv.getProperty("video-params/aspect-name"),
|
||||
"video-params/rotate" to mpv.getProperty("video-params/rotate")
|
||||
)
|
||||
}
|
||||
|
||||
// PiP Mode handling
|
||||
|
||||
fun onPipModeChanged(isInPipMode: Boolean) {
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.onPipModeChanged(isInPipMode)
|
||||
} else {
|
||||
playerCore?.onPipModeChanged(isInPipMode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ExoPlayerDelegate
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
override fun onFormatUnsupported(
|
||||
uri: String,
|
||||
headers: Map<String, String>?,
|
||||
positionMs: Long,
|
||||
errorMessage: String
|
||||
): Boolean {
|
||||
val currentActivity = activity ?: return false
|
||||
|
||||
Log.i(TAG, "Format unsupported, switching to MPV fallback at ${positionMs}ms")
|
||||
|
||||
currentActivity.runOnUiThread {
|
||||
try {
|
||||
// Dispose ExoPlayer
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
|
||||
// Create and initialize MPV
|
||||
mpvCore = MpvPlayerCore(currentActivity).apply {
|
||||
delegate = this@ExoPlayerPlugin
|
||||
}
|
||||
val success = mpvCore?.initialize() ?: false
|
||||
|
||||
if (!success) {
|
||||
Log.e(TAG, "Failed to initialize MPV fallback")
|
||||
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: $errorMessage"))
|
||||
return@runOnUiThread
|
||||
}
|
||||
|
||||
usingMpvFallback = true
|
||||
|
||||
// Configure basic MPV properties for Plex playback
|
||||
mpvCore?.setProperty("hwdec", "auto")
|
||||
mpvCore?.setProperty("vo", "gpu")
|
||||
mpvCore?.setProperty("ao", "audiotrack")
|
||||
|
||||
// Setup property observers
|
||||
mpvCore?.observeProperty("time-pos", "double")
|
||||
mpvCore?.observeProperty("duration", "double")
|
||||
mpvCore?.observeProperty("pause", "flag")
|
||||
mpvCore?.observeProperty("paused-for-cache", "flag")
|
||||
mpvCore?.observeProperty("demuxer-cache-time", "double")
|
||||
mpvCore?.observeProperty("eof-reached", "flag")
|
||||
mpvCore?.observeProperty("track-list", "string")
|
||||
mpvCore?.observeProperty("aid", "string")
|
||||
mpvCore?.observeProperty("sid", "string")
|
||||
mpvCore?.observeProperty("volume", "double")
|
||||
mpvCore?.observeProperty("speed", "double")
|
||||
|
||||
// Show the MPV surface
|
||||
mpvCore?.setVisible(true)
|
||||
|
||||
// Load media at the same position
|
||||
val startSeconds = positionMs / 1000.0
|
||||
val options = mutableListOf<String>()
|
||||
options.add("start=$startSeconds")
|
||||
headers?.forEach { (key, value) ->
|
||||
options.add("http-header-fields-append=$key: $value")
|
||||
}
|
||||
val optionsStr = options.joinToString(",")
|
||||
mpvCore?.command(arrayOf("loadfile", uri, "replace", "-1", optionsStr))
|
||||
|
||||
// Request audio focus
|
||||
mpvCore?.requestAudioFocus()
|
||||
|
||||
// Emit backend-switched event so Flutter can show notification
|
||||
onEvent("backend-switched", null)
|
||||
|
||||
Log.i(TAG, "Successfully switched to MPV fallback")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to switch to MPV fallback", e)
|
||||
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
|
||||
}
|
||||
}
|
||||
|
||||
return true // Fallback is being handled
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,31 @@
|
||||
package com.edde746.plezy.mpv
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.graphics.PixelFormat
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFocusRequest
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
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 android.view.WindowManager
|
||||
import androidx.annotation.RequiresApi
|
||||
import dev.jdtech.mpv.MPVLib
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.math.BigDecimal
|
||||
import java.math.RoundingMode
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
interface MpvPlayerDelegate {
|
||||
fun onPropertyChange(name: String, value: Any?)
|
||||
@@ -24,9 +39,11 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MpvPlayerCore"
|
||||
private const val SHORT_VIDEO_LENGTH_MS = 300000L // 5 minutes
|
||||
}
|
||||
|
||||
private var surfaceView: SurfaceView? = null
|
||||
private var surfaceContainer: android.widget.FrameLayout? = null
|
||||
private var overlayLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? =
|
||||
null
|
||||
private var voInUse: String = "gpu"
|
||||
@@ -34,6 +51,87 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
var isInitialized: Boolean = false
|
||||
private set
|
||||
|
||||
// Executor for running MPV commands off the UI thread to prevent ANR
|
||||
private val commandExecutor = Executors.newSingleThreadExecutor()
|
||||
|
||||
// Frame rate matching
|
||||
private var currentVideoFps: Float = 0f
|
||||
private var displayListener: DisplayManager.DisplayListener? = null
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
// Audio focus
|
||||
private var audioManager: AudioManager? = null
|
||||
private var audioFocusRequest: AudioFocusRequest? = null
|
||||
private var hasAudioFocus: Boolean = false
|
||||
private var wasPlayingBeforeFocusLoss: Boolean = false
|
||||
|
||||
private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
|
||||
when (focusChange) {
|
||||
AudioManager.AUDIOFOCUS_GAIN -> {
|
||||
Log.d(TAG, "Audio focus gained")
|
||||
hasAudioFocus = true
|
||||
// Resume playback if we were playing before focus loss
|
||||
if (wasPlayingBeforeFocusLoss && isInitialized) {
|
||||
try {
|
||||
MPVLib.setPropertyBoolean("pause", false)
|
||||
wasPlayingBeforeFocusLoss = false
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to resume playback after focus gain", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS -> {
|
||||
Log.d(TAG, "Audio focus lost permanently")
|
||||
hasAudioFocus = false
|
||||
// Pause playback on permanent focus loss
|
||||
if (isInitialized) {
|
||||
try {
|
||||
val isPaused = MPVLib.getPropertyBoolean("pause")
|
||||
wasPlayingBeforeFocusLoss = !isPaused
|
||||
if (!isPaused) {
|
||||
MPVLib.setPropertyBoolean("pause", true)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to pause on focus loss", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
|
||||
Log.d(TAG, "Audio focus lost transiently")
|
||||
hasAudioFocus = false
|
||||
// Pause playback, remember to resume
|
||||
if (isInitialized) {
|
||||
try {
|
||||
val isPaused = MPVLib.getPropertyBoolean("pause")
|
||||
wasPlayingBeforeFocusLoss = !isPaused
|
||||
if (!isPaused) {
|
||||
MPVLib.setPropertyBoolean("pause", true)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to pause on transient focus loss", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
|
||||
Log.d(TAG, "Audio focus lost transiently (can duck)")
|
||||
// For video content, we pause instead of ducking
|
||||
// since dialogue is typically important
|
||||
hasAudioFocus = false
|
||||
if (isInitialized) {
|
||||
try {
|
||||
val isPaused = MPVLib.getPropertyBoolean("pause")
|
||||
wasPlayingBeforeFocusLoss = !isPaused
|
||||
if (!isPaused) {
|
||||
MPVLib.setPropertyBoolean("pause", true)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to pause on duck focus loss", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureFlutterOverlayOnTop() {
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
contentView.post {
|
||||
@@ -49,11 +147,11 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
}
|
||||
|
||||
// Fallback for release (FlutterView may be obfuscated): pick the last ViewGroup
|
||||
// that is not our mpv SurfaceView and has children.
|
||||
// that is not our mpv container 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) {
|
||||
if (child is ViewGroup && child != surfaceContainer && child.childCount > 0) {
|
||||
flutterContainer = child
|
||||
break
|
||||
}
|
||||
@@ -86,13 +184,26 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
}
|
||||
|
||||
try {
|
||||
// Create SurfaceView for video rendering
|
||||
surfaceView = SurfaceView(activity).apply {
|
||||
// Initialize AudioManager for audio focus handling
|
||||
audioManager = activity.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
|
||||
// Create FrameLayout container for video (matches ExoPlayer pattern)
|
||||
// Setting visibility on container instead of SurfaceView directly allows
|
||||
// the surface to be created even when hidden (required with RenderMode.texture)
|
||||
surfaceContainer = android.widget.FrameLayout(activity).apply {
|
||||
layoutParams = ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
setBackgroundColor(Color.BLACK)
|
||||
}
|
||||
|
||||
// Create SurfaceView for video rendering
|
||||
surfaceView = SurfaceView(activity).apply {
|
||||
layoutParams = android.widget.FrameLayout.LayoutParams(
|
||||
android.widget.FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
android.widget.FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
// 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
|
||||
@@ -103,9 +214,12 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
setZOrderMediaOverlay(false)
|
||||
}
|
||||
|
||||
// Insert SurfaceView at bottom of view hierarchy (behind Flutter)
|
||||
// Add SurfaceView to container
|
||||
surfaceContainer!!.addView(surfaceView)
|
||||
|
||||
// Insert container at bottom of view hierarchy (behind Flutter)
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
contentView.addView(surfaceView, 0)
|
||||
contentView.addView(surfaceContainer, 0)
|
||||
|
||||
// Find FlutterView and its internal FlutterSurfaceView, set it on top
|
||||
for (i in 0 until contentView.childCount) {
|
||||
@@ -168,6 +282,69 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
MPVLib.setOptionString("ao", "audiotrack")
|
||||
}
|
||||
|
||||
// Audio Focus
|
||||
|
||||
/**
|
||||
* Request audio focus before starting playback.
|
||||
* This will cause other media apps to pause.
|
||||
* @return true if audio focus was granted
|
||||
*/
|
||||
fun requestAudioFocus(): Boolean {
|
||||
val am = audioManager ?: return false
|
||||
|
||||
Log.d(TAG, "Requesting audio focus")
|
||||
|
||||
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
// Android 8.0+ uses AudioFocusRequest
|
||||
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
|
||||
.build()
|
||||
)
|
||||
.setOnAudioFocusChangeListener(audioFocusChangeListener, handler)
|
||||
.setWillPauseWhenDucked(true)
|
||||
.build()
|
||||
|
||||
audioFocusRequest = focusRequest
|
||||
am.requestAudioFocus(focusRequest)
|
||||
} else {
|
||||
// Legacy API for older Android versions
|
||||
@Suppress("DEPRECATION")
|
||||
am.requestAudioFocus(
|
||||
audioFocusChangeListener,
|
||||
AudioManager.STREAM_MUSIC,
|
||||
AudioManager.AUDIOFOCUS_GAIN
|
||||
)
|
||||
}
|
||||
|
||||
hasAudioFocus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
|
||||
Log.d(TAG, "Audio focus request result: $result, granted: $hasAudioFocus")
|
||||
return hasAudioFocus
|
||||
}
|
||||
|
||||
/**
|
||||
* Abandon audio focus when playback stops.
|
||||
* This allows other apps to resume their audio.
|
||||
*/
|
||||
fun abandonAudioFocus() {
|
||||
val am = audioManager ?: return
|
||||
|
||||
Log.d(TAG, "Abandoning audio focus")
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
audioFocusRequest?.let { am.abandonAudioFocusRequest(it) }
|
||||
audioFocusRequest = null
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
am.abandonAudioFocus(audioFocusChangeListener)
|
||||
}
|
||||
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = false
|
||||
}
|
||||
|
||||
// SurfaceHolder.Callback
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
@@ -293,18 +470,250 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
MPVLib.command(args)
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an MPV command asynchronously off the UI thread.
|
||||
* This prevents ANR when commands like loadfile block waiting for network I/O.
|
||||
* The result is called back on the UI thread when the command completes.
|
||||
*/
|
||||
fun commandAsync(args: Array<String>, result: MethodChannel.Result) {
|
||||
if (!isInitialized || args.isEmpty()) {
|
||||
result.success(null)
|
||||
return
|
||||
}
|
||||
|
||||
commandExecutor.execute {
|
||||
try {
|
||||
MPVLib.command(args)
|
||||
activity.runOnUiThread {
|
||||
result.success(null)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Async command failed: ${e.message}", e)
|
||||
activity.runOnUiThread {
|
||||
result.error("COMMAND_FAILED", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setVisible(visible: Boolean) {
|
||||
activity.runOnUiThread {
|
||||
surfaceView?.visibility = if (visible) View.VISIBLE else View.INVISIBLE
|
||||
// Set visibility on the container, not the SurfaceView directly.
|
||||
// This allows the SurfaceView surface to be created even when hidden,
|
||||
// which is required with RenderMode.texture (TextureView mode).
|
||||
surfaceContainer?.visibility = if (visible) View.VISIBLE else View.INVISIBLE
|
||||
Log.d(TAG, "setVisible($visible)")
|
||||
}
|
||||
}
|
||||
|
||||
fun onPipModeChanged(isInPipMode: Boolean) {
|
||||
// MPV handles aspect ratio internally via its own surface management
|
||||
}
|
||||
|
||||
// Frame Rate Matching
|
||||
|
||||
private fun getDisplayManager(): DisplayManager {
|
||||
return activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the video frame rate for display refresh rate matching.
|
||||
* Based on VLC Android's FrameRateManager implementation.
|
||||
*/
|
||||
fun setVideoFrameRate(fps: Float, videoDurationMs: Long) {
|
||||
currentVideoFps = fps
|
||||
if (fps <= 0f) {
|
||||
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
|
||||
return
|
||||
}
|
||||
|
||||
val surface = surfaceView?.holder?.surface
|
||||
if (surface == null) {
|
||||
Log.d(TAG, "setVideoFrameRate: Surface not available")
|
||||
return
|
||||
}
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=${videoDurationMs}ms, API=${Build.VERSION.SDK_INT}")
|
||||
|
||||
when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> setFrameRateS(fps, surface, videoDurationMs)
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> setFrameRateR(fps, surface)
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> setFrameRateM(fps)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear frame rate setting and cleanup display listener.
|
||||
*/
|
||||
fun clearVideoFrameRate() {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
currentVideoFps = 0f
|
||||
displayListener?.let {
|
||||
getDisplayManager().unregisterDisplayListener(it)
|
||||
displayListener = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and register display listener for mode switch completion.
|
||||
* Resumes playback after display mode change (needed for HDMI/projectors).
|
||||
*/
|
||||
private fun registerDisplayListener() {
|
||||
displayListener?.let {
|
||||
getDisplayManager().unregisterDisplayListener(it)
|
||||
}
|
||||
|
||||
displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = Unit
|
||||
override fun onDisplayRemoved(displayId: Int) = Unit
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
// Mode switch may pause playback (HDMI), wait and resume
|
||||
handler.postDelayed({
|
||||
try {
|
||||
val isPaused = MPVLib.getPropertyBoolean("pause")
|
||||
if (isPaused) {
|
||||
Log.d(TAG, "Display changed, resuming playback")
|
||||
MPVLib.setPropertyBoolean("pause", false)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to resume playback after display change", e)
|
||||
}
|
||||
}, 2000L) // Wait 2 seconds for mode switch to complete
|
||||
getDisplayManager().unregisterDisplayListener(this)
|
||||
displayListener = null
|
||||
}
|
||||
}
|
||||
getDisplayManager().registerDisplayListener(displayListener, handler)
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.R)
|
||||
private fun setFrameRateR(fps: Float, surface: Surface) {
|
||||
Log.d(TAG, "setFrameRateR: Setting frame rate to $fps")
|
||||
surface.setFrameRate(fps, Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE)
|
||||
registerDisplayListener()
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.S)
|
||||
private fun setFrameRateS(fps: Float, surface: Surface, videoDurationMs: Long) {
|
||||
Log.d(TAG, "setFrameRateS: fps=$fps, duration=${videoDurationMs}ms")
|
||||
|
||||
// For short videos (<5min), only switch if seamless
|
||||
if (videoDurationMs < SHORT_VIDEO_LENGTH_MS) {
|
||||
Log.d(TAG, "Short video, using seamless-only switching")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// For longer videos, check if switch will be seamless
|
||||
var seamless = false
|
||||
activity.display?.mode?.alternativeRefreshRates?.let { refreshRates ->
|
||||
for (rate in refreshRates) {
|
||||
// Check if rates match or are integer multiples
|
||||
if (fps.toString().startsWith(rate.toString()) ||
|
||||
rate.toString().startsWith(fps.toString()) ||
|
||||
rate % fps == 0f) {
|
||||
seamless = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (seamless) {
|
||||
Log.d(TAG, "Seamless switch available, using CHANGE_FRAME_RATE_ALWAYS")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ALWAYS
|
||||
)
|
||||
registerDisplayListener()
|
||||
} else {
|
||||
// Non-seamless: only switch if user enabled it at OS level
|
||||
val userPreference = getDisplayManager().matchContentFrameRateUserPreference
|
||||
if (userPreference == DisplayManager.MATCH_CONTENT_FRAMERATE_ALWAYS) {
|
||||
Log.d(TAG, "User preference allows non-seamless switch")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ALWAYS
|
||||
)
|
||||
registerDisplayListener()
|
||||
} else {
|
||||
Log.d(TAG, "Non-seamless switch not allowed by user preference, using seamless-only")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setFrameRateM(fps: Float) {
|
||||
Log.d(TAG, "setFrameRateM: fps=$fps")
|
||||
val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
val display = wm.defaultDisplay ?: return
|
||||
|
||||
display.supportedModes?.let { supportedModes ->
|
||||
val currentMode = display.mode
|
||||
var modeToUse = currentMode
|
||||
|
||||
for (mode in supportedModes) {
|
||||
// Skip modes with different resolution
|
||||
if (mode.physicalHeight != currentMode.physicalHeight ||
|
||||
mode.physicalWidth != currentMode.physicalWidth) {
|
||||
continue
|
||||
}
|
||||
|
||||
Log.d(TAG, "Supported mode: ${mode.modeId} - ${mode.refreshRate}Hz")
|
||||
|
||||
// Check for exact match
|
||||
if (BigDecimal(fps.toString()).setScale(1, RoundingMode.FLOOR) ==
|
||||
BigDecimal(mode.refreshRate.toString()).setScale(1, RoundingMode.FLOOR)) {
|
||||
modeToUse = mode
|
||||
Log.d(TAG, "Found exact match: ${mode.refreshRate}Hz")
|
||||
break
|
||||
}
|
||||
// Check for integer multiple (e.g., 48Hz for 24fps)
|
||||
else if (mode.refreshRate % fps == 0f) {
|
||||
modeToUse = mode
|
||||
Log.d(TAG, "Found integer multiple: ${mode.refreshRate}Hz")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (modeToUse != currentMode) {
|
||||
Log.d(TAG, "Switching to mode ${modeToUse.modeId} (${modeToUse.refreshRate}Hz)")
|
||||
activity.window?.attributes?.let { attrs ->
|
||||
attrs.preferredDisplayModeId = modeToUse.modeId
|
||||
activity.window?.attributes = attrs
|
||||
}
|
||||
registerDisplayListener()
|
||||
} else {
|
||||
Log.d(TAG, "No better mode found, staying at ${currentMode.refreshRate}Hz")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
|
||||
fun dispose() {
|
||||
Log.d(TAG, "Disposing")
|
||||
|
||||
// Shutdown command executor
|
||||
commandExecutor.shutdown()
|
||||
|
||||
// Clean up frame rate listener
|
||||
clearVideoFrameRate()
|
||||
|
||||
// Release audio focus
|
||||
abandonAudioFocus()
|
||||
audioManager = null
|
||||
|
||||
MPVLib.removeObserver(this)
|
||||
MPVLib.removeLogObserver(this)
|
||||
|
||||
@@ -315,7 +724,8 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
}
|
||||
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
surfaceView?.let { contentView.removeView(it) }
|
||||
surfaceContainer?.let { contentView.removeView(it) }
|
||||
surfaceContainer = null
|
||||
surfaceView = null
|
||||
|
||||
MPVLib.destroy()
|
||||
|
||||
@@ -94,6 +94,10 @@ class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
"observeProperty" -> handleObserveProperty(call, result)
|
||||
"command" -> handleCommand(call, result)
|
||||
"setVisible" -> handleSetVisible(call, result)
|
||||
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
|
||||
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
|
||||
"requestAudioFocus" -> handleRequestAudioFocus(result)
|
||||
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
|
||||
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
@@ -119,7 +123,8 @@ class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
}
|
||||
val success = playerCore?.initialize() ?: false
|
||||
|
||||
// Start hidden
|
||||
// Start hidden - now safe because setVisible operates on the container,
|
||||
// not the SurfaceView directly (matching ExoPlayer's approach)
|
||||
playerCore?.setVisible(false)
|
||||
|
||||
Log.d(TAG, "Initialized: $success")
|
||||
@@ -186,8 +191,10 @@ class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
return
|
||||
}
|
||||
|
||||
playerCore?.command(args.toTypedArray())
|
||||
result.success(null)
|
||||
// Use async command to prevent ANR - command executes off UI thread
|
||||
// and result is called back when complete
|
||||
playerCore?.commandAsync(args.toTypedArray(), result)
|
||||
?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
|
||||
@@ -202,6 +209,33 @@ class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVideoFrameRate(call: MethodCall, result: MethodChannel.Result) {
|
||||
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
|
||||
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration")
|
||||
playerCore?.setVideoFrameRate(fps, duration)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
playerCore?.clearVideoFrameRate()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "requestAudioFocus")
|
||||
val granted = playerCore?.requestAudioFocus() ?: false
|
||||
result.success(granted)
|
||||
}
|
||||
|
||||
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "abandonAudioFocus")
|
||||
playerCore?.abandonAudioFocus()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
// MpvPlayerDelegate
|
||||
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import com.edde746.plezy.mpv.MpvPlayerPlugin
|
||||
|
||||
class MainActivity : FlutterActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
// Disable Android's default focus highlight ring that appears when using
|
||||
// D-pad navigation so the Flutter UI can render its own focus state.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
window.decorView.defaultFocusHighlightEnabled = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
flutterEngine.plugins.add(MpvPlayerPlugin())
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 70 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 109 KiB |
@@ -49,11 +49,17 @@ class MpvPlayerCore: NSObject {
|
||||
weak var delegate: MpvPlayerDelegate?
|
||||
|
||||
private(set) var isInitialized = false
|
||||
private var isDisposing = false // Flag to prevent race conditions during disposal
|
||||
|
||||
// HDR settings
|
||||
private var hdrEnabled = true // User preference for HDR
|
||||
private var lastSigPeak: Double = 0.0 // Last known sig-peak for re-evaluation
|
||||
|
||||
// Async command tracking to prevent UI blocking
|
||||
private var pendingCommands: [UInt64: (Result<Void, Error>) -> Void] = [:]
|
||||
private var pendingCommandsLock = NSLock()
|
||||
private var nextRequestId: UInt64 = 1
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
func initialize(in window: UIWindow) -> Bool {
|
||||
@@ -147,7 +153,8 @@ class MpvPlayerCore: NSObject {
|
||||
mpv_set_wakeup_callback(
|
||||
mpv,
|
||||
{ ctx in
|
||||
let core = Unmanaged<MpvPlayerCore>.fromOpaque(ctx!).takeUnretainedValue()
|
||||
guard let ctx = ctx else { return } // Safe guard instead of force unwrap
|
||||
let core = Unmanaged<MpvPlayerCore>.fromOpaque(ctx).takeUnretainedValue()
|
||||
core.readEvents()
|
||||
}, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
|
||||
|
||||
@@ -249,6 +256,50 @@ class MpvPlayerCore: NSObject {
|
||||
command(args[0], args: Array(args.dropFirst()))
|
||||
}
|
||||
|
||||
/// Execute an MPV command asynchronously to prevent UI blocking.
|
||||
/// Uses mpv_command_async which returns immediately; the completion is called
|
||||
/// when MPV_EVENT_COMMAND_REPLY is received.
|
||||
func commandAsync(_ args: [String], completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
guard let mpv = mpv, !args.isEmpty else {
|
||||
completion(.success(()))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate unique request ID
|
||||
pendingCommandsLock.lock()
|
||||
let requestId = nextRequestId
|
||||
nextRequestId += 1
|
||||
pendingCommands[requestId] = completion
|
||||
pendingCommandsLock.unlock()
|
||||
|
||||
// Build array of C strings for mpv_command_async
|
||||
var cargs: [UnsafeMutablePointer<CChar>?] = args.map { strdup($0) }
|
||||
cargs.append(nil) // null-terminate
|
||||
|
||||
// mpv_command_async returns immediately
|
||||
cargs.withUnsafeBufferPointer { buffer in
|
||||
var constPtrs = buffer.map { UnsafePointer($0) }
|
||||
let result = mpv_command_async(mpv, requestId, &constPtrs)
|
||||
if result < 0 {
|
||||
// Command submission failed, complete immediately with error
|
||||
pendingCommandsLock.lock()
|
||||
if let pending = pendingCommands.removeValue(forKey: requestId) {
|
||||
pendingCommandsLock.unlock()
|
||||
let error = NSError(domain: "mpv", code: Int(result),
|
||||
userInfo: [NSLocalizedDescriptionKey: String(cString: mpv_error_string(result))])
|
||||
DispatchQueue.main.async { pending(.failure(error)) }
|
||||
} else {
|
||||
pendingCommandsLock.unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Free the C strings
|
||||
for ptr in cargs {
|
||||
free(ptr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Visibility
|
||||
|
||||
func setVisible(_ visible: Bool) {
|
||||
@@ -308,7 +359,7 @@ class MpvPlayerCore: NSObject {
|
||||
|
||||
private func readEvents() {
|
||||
queue.async { [weak self] in
|
||||
guard let self = self, let mpv = self.mpv else { return }
|
||||
guard let self = self, !self.isDisposing, let mpv = self.mpv else { return }
|
||||
|
||||
while true {
|
||||
let event = mpv_wait_event(mpv, 0)
|
||||
@@ -331,6 +382,23 @@ class MpvPlayerCore: NSObject {
|
||||
let name = String(cString: property.name)
|
||||
handlePropertyChange(name: name, property: property)
|
||||
|
||||
case MPV_EVENT_COMMAND_REPLY:
|
||||
// Handle async command completion
|
||||
let requestId = event.reply_userdata
|
||||
pendingCommandsLock.lock()
|
||||
let completion = pendingCommands.removeValue(forKey: requestId)
|
||||
pendingCommandsLock.unlock()
|
||||
|
||||
if let completion = completion {
|
||||
if event.error < 0 {
|
||||
let error = NSError(domain: "mpv", code: Int(event.error),
|
||||
userInfo: [NSLocalizedDescriptionKey: String(cString: mpv_error_string(event.error))])
|
||||
DispatchQueue.main.async { completion(.failure(error)) }
|
||||
} else {
|
||||
DispatchQueue.main.async { completion(.success(())) }
|
||||
}
|
||||
}
|
||||
|
||||
case MPV_EVENT_FILE_LOADED:
|
||||
DispatchQueue.main.async {
|
||||
self.delegate?.onEvent(name: "file-loaded", data: nil)
|
||||
@@ -487,12 +555,29 @@ class MpvPlayerCore: NSObject {
|
||||
// MARK: - Cleanup
|
||||
|
||||
func dispose() {
|
||||
// Set disposing flag first to prevent race conditions with event callbacks
|
||||
isDisposing = true
|
||||
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
|
||||
// Cancel any pending async commands
|
||||
pendingCommandsLock.lock()
|
||||
let pending = pendingCommands
|
||||
pendingCommands.removeAll()
|
||||
pendingCommandsLock.unlock()
|
||||
|
||||
// Complete pending commands with cancellation error
|
||||
let cancelError = NSError(domain: "mpv", code: -1,
|
||||
userInfo: [NSLocalizedDescriptionKey: "Player disposed"])
|
||||
for (_, completion) in pending {
|
||||
DispatchQueue.main.async { completion(.failure(cancelError)) }
|
||||
}
|
||||
|
||||
let mpvHandle = mpv
|
||||
mpv = nil
|
||||
|
||||
queue.sync {
|
||||
// Use async to avoid blocking the main thread (prevents deadlock)
|
||||
queue.async {
|
||||
if let handle = mpvHandle {
|
||||
mpv_set_wakeup_callback(handle, nil, nil)
|
||||
mpv_terminate_destroy(handle)
|
||||
|
||||
@@ -178,8 +178,15 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPlayerD
|
||||
return
|
||||
}
|
||||
|
||||
playerCore?.command(commandArgs)
|
||||
result(nil)
|
||||
// Use async command to prevent UI blocking during network operations
|
||||
playerCore?.commandAsync(commandArgs) { commandResult in
|
||||
switch commandResult {
|
||||
case .success:
|
||||
result(nil)
|
||||
case .failure(let error):
|
||||
result(FlutterError(code: "COMMAND_FAILED", message: error.localizedDescription, details: nil))
|
||||
}
|
||||
} ?? result(nil)
|
||||
}
|
||||
|
||||
private func handleSetVisible(call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
|
||||
@@ -197,8 +197,29 @@ class AppDatabase extends _$AppDatabase {
|
||||
|
||||
LazyDatabase _openConnection() {
|
||||
return LazyDatabase(() async {
|
||||
final dbFolder = await getApplicationDocumentsDirectory();
|
||||
final Directory dbFolder;
|
||||
if (Platform.isAndroid || Platform.isIOS) {
|
||||
dbFolder = await getApplicationDocumentsDirectory();
|
||||
} else {
|
||||
dbFolder = await getApplicationSupportDirectory();
|
||||
}
|
||||
|
||||
final file = File(p.join(dbFolder.path, 'plezy_downloads.db'));
|
||||
|
||||
// Ensure directory exists
|
||||
if (!await file.parent.exists()) {
|
||||
await file.parent.create(recursive: true);
|
||||
}
|
||||
|
||||
// Migrate from old location on desktop (was in Documents subfolder)
|
||||
if (!Platform.isAndroid && !Platform.isIOS && !await file.exists()) {
|
||||
final oldFolder = await getApplicationDocumentsDirectory();
|
||||
final oldFile = File(p.join(oldFolder.path, 'plezy_downloads.db'));
|
||||
if (await oldFile.exists()) {
|
||||
await oldFile.rename(file.path);
|
||||
}
|
||||
}
|
||||
|
||||
return NativeDatabase(file);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -57,3 +57,46 @@ extension DpadKeyExtension on LogicalKeyboardKey {
|
||||
/// Whether this key moves focus down.
|
||||
bool get isDownKey => this == LogicalKeyboardKey.arrowDown;
|
||||
}
|
||||
|
||||
/// Global helper to suppress the next SELECT key-up event.
|
||||
class SelectKeyUpSuppressor {
|
||||
static bool _suppressSelectUntilKeyUp = false;
|
||||
|
||||
static void suppressSelectUntilKeyUp() {
|
||||
_suppressSelectUntilKeyUp = true;
|
||||
}
|
||||
|
||||
static bool consumeIfSuppressed(KeyEvent event) {
|
||||
if (!_suppressSelectUntilKeyUp) return false;
|
||||
if (event.logicalKey.isSelectKey) {
|
||||
if (event is KeyUpEvent) {
|
||||
_suppressSelectUntilKeyUp = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Global helper to suppress the next BACK key-up event.
|
||||
///
|
||||
/// Use this when a modal (bottom sheet, dialog) closes to prevent
|
||||
/// the BACK key-up from propagating to the underlying screen.
|
||||
class BackKeyUpSuppressor {
|
||||
static bool _suppressBackUntilKeyUp = false;
|
||||
|
||||
static void suppressBackUntilKeyUp() {
|
||||
_suppressBackUntilKeyUp = true;
|
||||
}
|
||||
|
||||
static bool consumeIfSuppressed(KeyEvent event) {
|
||||
if (!_suppressBackUntilKeyUp) return false;
|
||||
if (event.logicalKey.isBackKey) {
|
||||
if (event is KeyUpEvent) {
|
||||
_suppressBackUntilKeyUp = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Reusable focus memory tracker for screens with multiple focusable items.
|
||||
/// Tracks which item was last focused and provides focus restoration.
|
||||
class FocusMemoryTracker {
|
||||
final Map<String, FocusNode> _nodes = {};
|
||||
final Set<String> _focused = {};
|
||||
final VoidCallback? _onFocusChanged;
|
||||
final String _debugLabelPrefix;
|
||||
String? _lastFocusedKey;
|
||||
|
||||
FocusMemoryTracker({VoidCallback? onFocusChanged, String debugLabelPrefix = 'focus'})
|
||||
: _onFocusChanged = onFocusChanged,
|
||||
_debugLabelPrefix = debugLabelPrefix;
|
||||
|
||||
/// Get or create a focus node for the given key
|
||||
FocusNode get(String key, {String? debugLabel}) {
|
||||
return _nodes.putIfAbsent(key, () {
|
||||
final node = FocusNode(debugLabel: debugLabel ?? '${_debugLabelPrefix}_$key');
|
||||
node.addListener(() {
|
||||
final wasFocused = _focused.contains(key);
|
||||
if (node.hasFocus && !wasFocused) {
|
||||
_focused.add(key);
|
||||
_lastFocusedKey = key;
|
||||
_onFocusChanged?.call();
|
||||
} else if (!node.hasFocus && wasFocused) {
|
||||
_focused.remove(key);
|
||||
_onFocusChanged?.call();
|
||||
}
|
||||
});
|
||||
return node;
|
||||
});
|
||||
}
|
||||
|
||||
/// Get the last focused key (for focus restoration)
|
||||
String? get lastFocusedKey => _lastFocusedKey;
|
||||
|
||||
/// Check if a key is currently focused
|
||||
bool isFocused(String key) => _focused.contains(key);
|
||||
|
||||
/// Get a node without creating it (returns null if not found)
|
||||
FocusNode? nodeFor(String key) => _nodes[key];
|
||||
|
||||
/// Restore focus to the last focused item, or fallback if provided
|
||||
/// Returns true if focus was successfully restored
|
||||
bool restoreFocus({String? fallbackKey}) {
|
||||
// Try to restore last focused item
|
||||
if (_lastFocusedKey != null) {
|
||||
final node = _nodes[_lastFocusedKey];
|
||||
if (node != null) {
|
||||
node.requestFocus();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// Fallback: focus the provided key if available
|
||||
if (fallbackKey != null) {
|
||||
final node = _nodes[fallbackKey];
|
||||
if (node != null) {
|
||||
node.requestFocus();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Remove nodes not in the given set of valid keys (prunes stale nodes)
|
||||
void pruneExcept(Set<String> validKeys) {
|
||||
final toRemove = _nodes.keys.where((k) => !validKeys.contains(k)).toList();
|
||||
for (final key in toRemove) {
|
||||
_nodes[key]?.dispose();
|
||||
_nodes.remove(key);
|
||||
_focused.remove(key);
|
||||
}
|
||||
// Clear last focused if it was pruned
|
||||
if (_lastFocusedKey != null && !validKeys.contains(_lastFocusedKey)) {
|
||||
_lastFocusedKey = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispose all nodes
|
||||
void dispose() {
|
||||
for (final node in _nodes.values) {
|
||||
node.dispose();
|
||||
}
|
||||
_nodes.clear();
|
||||
_focused.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'dpad_navigator.dart';
|
||||
import 'key_event_utils.dart';
|
||||
|
||||
/// Callbacks for chip key event handling.
|
||||
class ChipKeyCallbacks {
|
||||
@@ -102,27 +103,41 @@ mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
|
||||
/// Returns [KeyEventResult.handled] if the event was consumed,
|
||||
/// [KeyEventResult.ignored] otherwise.
|
||||
KeyEventResult handleChipKeyEvent(FocusNode node, KeyEvent event, ChipKeyCallbacks callbacks) {
|
||||
final key = event.logicalKey;
|
||||
|
||||
if (callbacks.onBack != null) {
|
||||
final backResult = handleBackKeyAction(event, callbacks.onBack!);
|
||||
if (backResult != KeyEventResult.ignored) {
|
||||
return backResult;
|
||||
}
|
||||
}
|
||||
|
||||
if (!event.isActionable) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
final key = event.logicalKey;
|
||||
|
||||
// SELECT key activates the chip
|
||||
if (key.isSelectKey && callbacks.onSelect != null) {
|
||||
callbacks.onSelect!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT arrow
|
||||
if (key.isLeftKey && callbacks.onNavigateLeft != null) {
|
||||
callbacks.onNavigateLeft!();
|
||||
return KeyEventResult.handled;
|
||||
// LEFT arrow - call callback if provided, otherwise propagate to parent
|
||||
if (key.isLeftKey) {
|
||||
if (callbacks.onNavigateLeft != null) {
|
||||
callbacks.onNavigateLeft!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
// No callback - let parent handle (e.g., to focus sidebar)
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
// RIGHT arrow
|
||||
if (key.isRightKey && callbacks.onNavigateRight != null) {
|
||||
callbacks.onNavigateRight!();
|
||||
// RIGHT arrow - call callback if provided, otherwise consume to prevent escape
|
||||
if (key.isRightKey) {
|
||||
if (callbacks.onNavigateRight != null) {
|
||||
callbacks.onNavigateRight!();
|
||||
}
|
||||
// Always consume RIGHT to prevent focus escape
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
@@ -138,12 +153,6 @@ mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// BACK key
|
||||
if (key.isBackKey && callbacks.onBack != null) {
|
||||
callbacks.onBack!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/services.dart';
|
||||
import 'dpad_navigator.dart';
|
||||
import 'focus_theme.dart';
|
||||
import 'input_mode_tracker.dart';
|
||||
import 'key_event_utils.dart';
|
||||
|
||||
/// A wrapper widget that makes its child focusable with D-pad navigation support.
|
||||
///
|
||||
@@ -32,6 +33,12 @@ class FocusableWrapper extends StatefulWidget {
|
||||
/// Called when the user presses UP and there's no focusable item above.
|
||||
final VoidCallback? onNavigateUp;
|
||||
|
||||
/// Called when the user presses LEFT and there's no focusable item to the left.
|
||||
final VoidCallback? onNavigateLeft;
|
||||
|
||||
/// Called when the user presses RIGHT and there's no focusable item to the right.
|
||||
final VoidCallback? onNavigateRight;
|
||||
|
||||
/// Called when the user presses BACK.
|
||||
final VoidCallback? onBack;
|
||||
|
||||
@@ -87,6 +94,8 @@ class FocusableWrapper extends StatefulWidget {
|
||||
this.onLongPress,
|
||||
this.onFocusChange,
|
||||
this.onNavigateUp,
|
||||
this.onNavigateLeft,
|
||||
this.onNavigateRight,
|
||||
this.onBack,
|
||||
this.autofocus = false,
|
||||
this.focusNode,
|
||||
@@ -182,6 +191,12 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
_isFocused = hasFocus;
|
||||
});
|
||||
|
||||
// Reset long press state when focus is lost
|
||||
if (!hasFocus) {
|
||||
_longPressTimer?.cancel();
|
||||
_isSelectKeyDown = false;
|
||||
}
|
||||
|
||||
// Animate scale
|
||||
if (hasFocus) {
|
||||
_animationController.forward();
|
||||
@@ -199,6 +214,10 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
}
|
||||
}
|
||||
|
||||
// Extra padding for focus decoration (scale + border extends beyond item bounds)
|
||||
// Scale 1.02 adds ~1% on each side, plus 2.5px border = ~8px total padding needed
|
||||
static const double _focusDecorationPadding = 8.0;
|
||||
|
||||
void _scrollIntoView() {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted || !_isFocused) return;
|
||||
@@ -206,37 +225,69 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
final renderObject = context.findRenderObject();
|
||||
if (renderObject == null) return;
|
||||
|
||||
final scrollable = Scrollable.maybeOf(context);
|
||||
if (scrollable == null) return;
|
||||
|
||||
final viewport = scrollable.context.findRenderObject() as RenderBox?;
|
||||
if (viewport == null) return;
|
||||
|
||||
// Get item's position relative to viewport
|
||||
final itemBox = renderObject as RenderBox;
|
||||
final itemPosition = itemBox.localToGlobal(Offset.zero, ancestor: viewport);
|
||||
|
||||
final viewportHeight = viewport.size.height;
|
||||
final itemHeight = itemBox.size.height;
|
||||
final itemVerticalCenter = itemPosition.dy + itemHeight / 2;
|
||||
|
||||
// Account for focus decoration when checking item visibility
|
||||
final itemTop = itemPosition.dy - _focusDecorationPadding;
|
||||
final itemBottom = itemPosition.dy + itemHeight + _focusDecorationPadding;
|
||||
|
||||
if (widget.useComfortableZone) {
|
||||
// Check if item is already in the comfortable zone
|
||||
final scrollable = Scrollable.maybeOf(context);
|
||||
if (scrollable == null) return;
|
||||
|
||||
final viewport = scrollable.context.findRenderObject() as RenderBox?;
|
||||
if (viewport == null) return;
|
||||
|
||||
// Get item's position relative to viewport
|
||||
final itemBox = renderObject as RenderBox;
|
||||
final itemPosition = itemBox.localToGlobal(Offset.zero, ancestor: viewport);
|
||||
|
||||
// Check if item is already in the comfortable zone
|
||||
final viewportHeight = viewport.size.height;
|
||||
final itemHeight = itemBox.size.height;
|
||||
final itemVerticalCenter = itemPosition.dy + itemHeight / 2;
|
||||
|
||||
// Define comfortable zone - if item center is within middle 60% of viewport, don't scroll
|
||||
// Define comfortable zone - if item (including focus decoration) is within middle 60% of viewport, don't scroll
|
||||
final comfortZoneTop = viewportHeight * 0.2;
|
||||
final comfortZoneBottom = viewportHeight * 0.8;
|
||||
|
||||
if (itemVerticalCenter >= comfortZoneTop && itemVerticalCenter <= comfortZoneBottom) {
|
||||
if (itemTop >= comfortZoneTop && itemBottom <= comfortZoneBottom) {
|
||||
// Item is in comfortable zone, no need to scroll
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// When not using comfortable zone, still skip scroll if item is already
|
||||
// close to target position (prevents jitter when navigating horizontally)
|
||||
final targetY = viewportHeight * widget.scrollAlignment;
|
||||
final distance = (itemVerticalCenter - targetY).abs();
|
||||
// Skip scroll if within half the item height of target
|
||||
if (distance < itemHeight / 2) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Item is outside comfortable zone or comfortable zone disabled, scroll to alignment
|
||||
Scrollable.ensureVisible(
|
||||
context,
|
||||
alignment: widget.scrollAlignment,
|
||||
// Calculate target scroll offset for the immediate scrollable only.
|
||||
// This avoids Scrollable.ensureVisible which scrolls ALL ancestor scrollables,
|
||||
// which can cause issues with nested scroll views (e.g., chips bar scrolling
|
||||
// out of view when focusing grid items in library browse tab).
|
||||
final position = scrollable.position;
|
||||
final currentOffset = position.pixels;
|
||||
|
||||
// Target: item center should be at scrollAlignment of viewport
|
||||
// Add padding to ensure focus decoration is fully visible
|
||||
final targetViewportY = viewportHeight * widget.scrollAlignment;
|
||||
var scrollDelta = itemVerticalCenter - targetViewportY;
|
||||
|
||||
// If item would be near the top edge, add extra scroll to show focus decoration
|
||||
final projectedItemTop = itemTop - scrollDelta;
|
||||
if (projectedItemTop < _focusDecorationPadding) {
|
||||
scrollDelta -= (_focusDecorationPadding - projectedItemTop);
|
||||
}
|
||||
|
||||
final targetOffset = (currentOffset + scrollDelta).clamp(
|
||||
position.minScrollExtent,
|
||||
position.maxScrollExtent,
|
||||
);
|
||||
|
||||
position.animateTo(
|
||||
targetOffset,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
curve: Curves.easeInOut,
|
||||
);
|
||||
@@ -246,6 +297,10 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
|
||||
if (SelectKeyUpSuppressor.consumeIfSuppressed(event)) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// Call custom key handler first
|
||||
if (widget.onKeyEvent != null) {
|
||||
final result = widget.onKeyEvent!(node, event);
|
||||
@@ -254,6 +309,13 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
}
|
||||
}
|
||||
|
||||
if (widget.onBack != null) {
|
||||
final backResult = handleBackKeyAction(event, widget.onBack!);
|
||||
if (backResult != KeyEventResult.ignored) {
|
||||
return backResult;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle SELECT key with optional long-press detection
|
||||
if (key.isSelectKey) {
|
||||
if (widget.enableLongPress) {
|
||||
@@ -265,6 +327,7 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
_longPressTimer = Timer(widget.longPressDuration, () {
|
||||
// Long press detected
|
||||
if (mounted) {
|
||||
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
|
||||
widget.onLongPress?.call();
|
||||
}
|
||||
});
|
||||
@@ -300,6 +363,7 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
|
||||
// Context menu key
|
||||
if (key.isContextMenuKey) {
|
||||
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
|
||||
widget.onLongPress?.call();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
@@ -310,9 +374,17 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// BACK key
|
||||
if (key.isBackKey && widget.onBack != null) {
|
||||
widget.onBack!();
|
||||
// LEFT arrow - if callback provided, navigate left (caller is responsible
|
||||
// for only providing this callback when the item is at the left edge)
|
||||
if (key == LogicalKeyboardKey.arrowLeft && widget.onNavigateLeft != null) {
|
||||
widget.onNavigateLeft!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// RIGHT arrow - if callback provided, navigate right (caller is responsible
|
||||
// for only providing this callback when the item is at the right edge)
|
||||
if (key == LogicalKeyboardKey.arrowRight && widget.onNavigateRight != null) {
|
||||
widget.onNavigateRight!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,10 +28,55 @@ import 'dpad_navigator.dart';
|
||||
/// child: ...
|
||||
/// )
|
||||
/// ```
|
||||
KeyEventResult handleBackKeyNavigation<T>(BuildContext context, KeyEvent event, {T? result}) {
|
||||
if (event is KeyDownEvent && event.logicalKey.isBackKey) {
|
||||
Navigator.pop(context, result);
|
||||
class BackKeyCoordinator {
|
||||
static bool _handledThisFrame = false;
|
||||
static bool _clearScheduled = false;
|
||||
|
||||
static void markHandled() {
|
||||
_handledThisFrame = true;
|
||||
if (_clearScheduled) return;
|
||||
_clearScheduled = true;
|
||||
// Clear on next frame to avoid blocking unrelated future back presses.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_handledThisFrame = false;
|
||||
_clearScheduled = false;
|
||||
});
|
||||
}
|
||||
|
||||
static bool consumeIfHandled() {
|
||||
if (_handledThisFrame) {
|
||||
_handledThisFrame = false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a BACK key press by running [onBack] on key up.
|
||||
///
|
||||
/// This consumes KeyDown/KeyRepeat to avoid duplicate actions from key repeat.
|
||||
/// Optionally suppresses stray KeyUp events delivered to the next route after a pop.
|
||||
KeyEventResult handleBackKeyAction(KeyEvent event, VoidCallback onBack) {
|
||||
if (!event.logicalKey.isBackKey) return KeyEventResult.ignored;
|
||||
|
||||
// Check if this BACK event should be suppressed (e.g., after modal closed)
|
||||
if (BackKeyUpSuppressor.consumeIfSuppressed(event)) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (event is KeyUpEvent) {
|
||||
BackKeyCoordinator.markHandled();
|
||||
onBack();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (event is KeyDownEvent || event is KeyRepeatEvent) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
KeyEventResult handleBackKeyNavigation<T>(BuildContext context, KeyEvent event, {T? result}) {
|
||||
// Handle on KeyUpEvent to prevent double-pop when returning from child screens
|
||||
// (KeyDownEvent can be received by both the popping screen and the returned-to screen)
|
||||
return handleBackKeyAction(event, () => Navigator.pop(context, result));
|
||||
}
|
||||
|
||||
@@ -60,7 +60,13 @@
|
||||
"appearance": "Darstellung",
|
||||
"videoPlayback": "Videowiedergabe",
|
||||
"advanced": "Erweitert",
|
||||
"useSeasonPostersDescription": "Staffelposter statt Serienposter für Episoden anzeigen",
|
||||
"episodePosterMode": "Episoden-Poster-Stil",
|
||||
"seriesPoster": "Serienposter",
|
||||
"seriesPosterDescription": "Zeige das Serienposter für alle Episoden",
|
||||
"seasonPoster": "Staffelposter",
|
||||
"seasonPosterDescription": "Zeige das staffelspezifische Poster für Episoden",
|
||||
"episodeThumbnail": "Episoden-Miniatur",
|
||||
"episodeThumbnailDescription": "Zeige 16:9 Episoden-Vorschaubilder",
|
||||
"showHeroSectionDescription": "Bereich mit empfohlenen Inhalten auf der Startseite anzeigen",
|
||||
"secondsLabel": "Sekunden",
|
||||
"minutesLabel": "Minuten",
|
||||
@@ -83,8 +89,18 @@
|
||||
"gridViewDescription": "Elemente im Raster anzeigen",
|
||||
"listView": "Liste",
|
||||
"listViewDescription": "Elemente in Listenansicht anzeigen",
|
||||
"useSeasonPosters": "Staffelposter verwenden",
|
||||
"showHeroSection": "Hero-Bereich anzeigen",
|
||||
"useGlobalHubs": "Plex-Startseiten-Layout verwenden",
|
||||
"useGlobalHubsDescription": "Zeigt Startseiten-Hubs wie der offizielle Plex-Client. Wenn deaktiviert, werden stattdessen Empfehlungen pro Bibliothek angezeigt.",
|
||||
"showServerNameOnHubs": "Servername bei Hubs anzeigen",
|
||||
"showServerNameOnHubsDescription": "Zeigt immer den Servernamen in Hub-Titeln an. Wenn deaktiviert, nur bei doppelten Hub-Namen.",
|
||||
"alwaysKeepSidebarOpen": "Seitenleiste immer geöffnet halten",
|
||||
"alwaysKeepSidebarOpenDescription": "Seitenleiste bleibt erweitert und Inhaltsbereich passt sich an",
|
||||
"playerBackend": "Player-Backend",
|
||||
"exoPlayer": "ExoPlayer (Empfohlen)",
|
||||
"exoPlayerDescription": "Android-nativer Player mit besserer Hardware-Unterstützung",
|
||||
"mpv": "MPV",
|
||||
"mpvDescription": "Erweiterter Player mit mehr Funktionen und ASS-Untertitel-Unterstützung",
|
||||
"hardwareDecoding": "Hardware-Decodierung",
|
||||
"hardwareDecodingDescription": "Hardwarebeschleunigung verwenden, sofern verfügbar",
|
||||
"bufferSize": "Puffergröße",
|
||||
@@ -98,6 +114,8 @@
|
||||
"minutesUnit": "${minutes} Minuten",
|
||||
"rememberTrackSelections": "Spurauswahl pro Serie/Film merken",
|
||||
"rememberTrackSelectionsDescription": "Audio- und Untertitelsprache automatisch speichern, wenn während der Wiedergabe geändert",
|
||||
"clickVideoTogglesPlayback": "Klicken Sie auf das Video, um die Wiedergabe zu starten oder zu pausieren.",
|
||||
"clickVideoTogglesPlaybackDescription": "Wenn diese Option aktiviert ist, wird durch Klicken auf den Videoplayer die Wiedergabe gestartet oder pausiert. Andernfalls werden durch Klicken die Wiedergabesteuerungen ein- oder ausgeblendet.",
|
||||
"videoPlayerControls": "Videoplayer-Steuerung",
|
||||
"keyboardShortcuts": "Tastenkürzel",
|
||||
"keyboardShortcutsDescription": "Tastenkürzel anpassen",
|
||||
@@ -149,7 +167,9 @@
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Maximale Lautstärke eingeben (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Zeige auf Discord, was du gerade schaust"
|
||||
"discordRichPresenceDescription": "Zeige auf Discord, was du gerade schaust",
|
||||
"matchContentFrameRate": "Inhalts-Bildrate anpassen",
|
||||
"matchContentFrameRateDescription": "Bildwiederholfrequenz des Displays an den Videoinhalt anpassen, reduziert Ruckeln und spart Akku"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Filme, Serien, Musik suchen...",
|
||||
@@ -159,7 +179,26 @@
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Tastenkürzel festlegen für ${actionName}",
|
||||
"clearShortcut": "Kürzel löschen"
|
||||
"clearShortcut": "Kürzel löschen",
|
||||
"actions": {
|
||||
"playPause": "Wiedergabe/Pause",
|
||||
"volumeUp": "Lauter",
|
||||
"volumeDown": "Leiser",
|
||||
"seekForward": "Vorspulen (${seconds}s)",
|
||||
"seekBackward": "Zurückspulen (${seconds}s)",
|
||||
"fullscreenToggle": "Vollbild umschalten",
|
||||
"muteToggle": "Stumm umschalten",
|
||||
"subtitleToggle": "Untertitel umschalten",
|
||||
"audioTrackNext": "Nächste Audiospur",
|
||||
"subtitleTrackNext": "Nächste Untertitelspur",
|
||||
"chapterNext": "Nächstes Kapitel",
|
||||
"chapterPrevious": "Vorheriges Kapitel",
|
||||
"speedIncrease": "Geschwindigkeit erhöhen",
|
||||
"speedDecrease": "Geschwindigkeit verringern",
|
||||
"speedReset": "Geschwindigkeit zurücksetzen",
|
||||
"subSeekNext": "Zum nächsten Untertitel springen",
|
||||
"subSeekPrev": "Zum vorherigen Untertitel springen"
|
||||
}
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "PIN eingeben",
|
||||
@@ -233,6 +272,8 @@
|
||||
"timerActive": "Schlaftimer aktiv",
|
||||
"playbackWillPauseIn": "Wiedergabe wird in ${duration} pausiert",
|
||||
"sleepTimerCompleted": "Schlaftimer abgelaufen – Wiedergabe pausiert",
|
||||
"autoPlayNext": "Nächstes automatisch abspielen",
|
||||
"playNext": "Nächstes abspielen",
|
||||
"playButton": "Wiedergeben",
|
||||
"pauseButton": "Pause",
|
||||
"seekBackwardButton": "${seconds} Sekunden zurück",
|
||||
@@ -248,6 +289,7 @@
|
||||
"subtitlesButton": "Untertitel",
|
||||
"chaptersButton": "Kapitel",
|
||||
"versionsButton": "Videoversionen",
|
||||
"pipButton": "Bild-in-Bild Modus",
|
||||
"aspectRatioButton": "Seitenverhältnis",
|
||||
"fullscreenButton": "Vollbild aktivieren",
|
||||
"exitFullscreenButton": "Vollbild verlassen",
|
||||
@@ -255,7 +297,15 @@
|
||||
"rotationLockButton": "Drehsperre",
|
||||
"timelineSlider": "Video-Zeitleiste",
|
||||
"volumeSlider": "Lautstärkepegel",
|
||||
"backButton": "Zurück"
|
||||
"backButton": "Zurück",
|
||||
"pipFailed": "Bild-in-Bild konnte nicht gestartet werden",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Erfordert Android 8.0 oder neuer",
|
||||
"permissionDisabled": "Bild-in-Bild-Berechtigung ist deaktiviert. Aktiviere sie unter Einstellungen > Apps > Plezy > Bild-in-Bild",
|
||||
"notSupported": "Dieses Gerät unterstützt den Bild-in-Bild-Modus nicht",
|
||||
"failed": "Bild-in-Bild konnte nicht gestartet werden",
|
||||
"unknown": "Ein Fehler ist aufgetreten: ${error}"
|
||||
}
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "Eigentümer",
|
||||
@@ -293,7 +343,8 @@
|
||||
"noItemsAvailable": "Keine Elemente verfügbar",
|
||||
"failedToCreatePlayQueue": "Wiedergabewarteschlange konnte nicht erstellt werden",
|
||||
"failedToCreatePlayQueueNoItems": "Wiedergabewarteschlange konnte nicht erstellt werden – keine Elemente",
|
||||
"failedPlayback": "Wiedergabe für ${action} fehlgeschlagen: ${error}"
|
||||
"failedPlayback": "Wiedergabe für ${action} fehlgeschlagen: ${error}",
|
||||
"switchingToCompatiblePlayer": "Wechsle zu kompatiblem Player..."
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "Stiloptionen",
|
||||
@@ -572,6 +623,7 @@
|
||||
"codeMustBe8Chars": "Sitzungscode muss 8 Zeichen haben",
|
||||
"joinInstructions": "Gib den vom Host geteilten Sitzungscode ein, um seiner Schausitzung beizutreten.",
|
||||
"failedToCreate": "Sitzung konnte nicht erstellt werden",
|
||||
"failedToJoin": "Sitzung konnte nicht beigetreten werden"
|
||||
"failedToJoin": "Sitzung konnte nicht beigetreten werden",
|
||||
"sessionCodeCopied": "Sitzungscode in Zwischenablage kopiert"
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,13 @@
|
||||
"appearance": "Appearance",
|
||||
"videoPlayback": "Video Playback",
|
||||
"advanced": "Advanced",
|
||||
"useSeasonPostersDescription": "Show season poster instead of series poster for episodes",
|
||||
"episodePosterMode": "Episode Poster Style",
|
||||
"seriesPoster": "Series Poster",
|
||||
"seriesPosterDescription": "Show the series poster for all episodes",
|
||||
"seasonPoster": "Season Poster",
|
||||
"seasonPosterDescription": "Show the season-specific poster for episodes",
|
||||
"episodeThumbnail": "Episode Thumbnail",
|
||||
"episodeThumbnailDescription": "Show 16:9 episode screenshot thumbnails",
|
||||
"showHeroSectionDescription": "Display featured content carousel on home screen",
|
||||
"secondsLabel": "Seconds",
|
||||
"minutesLabel": "Minutes",
|
||||
@@ -82,8 +88,18 @@
|
||||
"gridViewDescription": "Display items in a grid layout",
|
||||
"listView": "List",
|
||||
"listViewDescription": "Display items in a list layout",
|
||||
"useSeasonPosters": "Use Season Posters",
|
||||
"showHeroSection": "Show Hero Section",
|
||||
"useGlobalHubs": "Use Plex Home Layout",
|
||||
"useGlobalHubsDescription": "Show home page hubs like the official Plex client. When off, shows per-library recommendations instead.",
|
||||
"showServerNameOnHubs": "Show Server Name on Hubs",
|
||||
"showServerNameOnHubsDescription": "Always display the server name in hub titles. When off, only shows for duplicate hub names.",
|
||||
"alwaysKeepSidebarOpen": "Always Keep Sidebar Open",
|
||||
"alwaysKeepSidebarOpenDescription": "Sidebar stays expanded and content area adjusts to fit",
|
||||
"playerBackend": "Player Backend",
|
||||
"exoPlayer": "ExoPlayer (Recommended)",
|
||||
"exoPlayerDescription": "Android native player with better hardware support",
|
||||
"mpv": "MPV",
|
||||
"mpvDescription": "Advanced player with more features and ASS subtitle support",
|
||||
"hardwareDecoding": "Hardware Decoding",
|
||||
"hardwareDecodingDescription": "Use hardware acceleration when available",
|
||||
"bufferSize": "Buffer Size",
|
||||
@@ -97,6 +113,8 @@
|
||||
"minutesUnit": "${minutes} minutes",
|
||||
"rememberTrackSelections": "Remember track selections per show/movie",
|
||||
"rememberTrackSelectionsDescription": "Automatically save audio and subtitle language preferences when you change tracks during playback",
|
||||
"clickVideoTogglesPlayback": "Click on video to toggle play/pause",
|
||||
"clickVideoTogglesPlaybackDescription": "If enabled, clicking on the video player will play/pause the video. Otherwise, clicking will show/hide the playback controls.",
|
||||
"videoPlayerControls": "Video Player Controls",
|
||||
"keyboardShortcuts": "Keyboard Shortcuts",
|
||||
"keyboardShortcutsDescription": "Customize keyboard shortcuts",
|
||||
@@ -148,7 +166,9 @@
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Enter max volume (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Show what you're watching on Discord"
|
||||
"discordRichPresenceDescription": "Show what you're watching on Discord",
|
||||
"matchContentFrameRate": "Match Content Frame Rate",
|
||||
"matchContentFrameRateDescription": "Adjust display refresh rate to match video content, reducing judder and saving battery"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Search movies, shows, music...",
|
||||
@@ -158,7 +178,26 @@
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Set Shortcut for ${actionName}",
|
||||
"clearShortcut": "Clear shortcut"
|
||||
"clearShortcut": "Clear shortcut",
|
||||
"actions": {
|
||||
"playPause": "Play/Pause",
|
||||
"volumeUp": "Volume Up",
|
||||
"volumeDown": "Volume Down",
|
||||
"seekForward": "Seek Forward (${seconds}s)",
|
||||
"seekBackward": "Seek Backward (${seconds}s)",
|
||||
"fullscreenToggle": "Toggle Fullscreen",
|
||||
"muteToggle": "Toggle Mute",
|
||||
"subtitleToggle": "Toggle Subtitles",
|
||||
"audioTrackNext": "Next Audio Track",
|
||||
"subtitleTrackNext": "Next Subtitle Track",
|
||||
"chapterNext": "Next Chapter",
|
||||
"chapterPrevious": "Previous Chapter",
|
||||
"speedIncrease": "Increase Speed",
|
||||
"speedDecrease": "Decrease Speed",
|
||||
"speedReset": "Reset Speed",
|
||||
"subSeekNext": "Seek to Next Subtitle",
|
||||
"subSeekPrev": "Seek to Previous Subtitle"
|
||||
}
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "Enter PIN",
|
||||
@@ -232,6 +271,8 @@
|
||||
"timerActive": "Timer Active",
|
||||
"playbackWillPauseIn": "Playback will pause in ${duration}",
|
||||
"sleepTimerCompleted": "Sleep timer completed - playback paused",
|
||||
"autoPlayNext": "Auto-Play Next",
|
||||
"playNext": "Play Next",
|
||||
"playButton": "Play",
|
||||
"pauseButton": "Pause",
|
||||
"seekBackwardButton": "Seek backward ${seconds} seconds",
|
||||
@@ -247,6 +288,7 @@
|
||||
"subtitlesButton": "Subtitles",
|
||||
"chaptersButton": "Chapters",
|
||||
"versionsButton": "Video versions",
|
||||
"pipButton": "Picture-in-Picture mode",
|
||||
"aspectRatioButton": "Aspect ratio",
|
||||
"fullscreenButton": "Enter fullscreen",
|
||||
"exitFullscreenButton": "Exit fullscreen",
|
||||
@@ -254,7 +296,15 @@
|
||||
"rotationLockButton": "Rotation lock",
|
||||
"timelineSlider": "Video timeline",
|
||||
"volumeSlider": "Volume level",
|
||||
"backButton": "Back"
|
||||
"backButton": "Back",
|
||||
"pipFailed": "Picture-in-picture failed to start",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Requires Android 8.0 or newer",
|
||||
"permissionDisabled": "Picture-in-picture permission is disabled. Enable it in Settings > Apps > Plezy > Picture-in-picture",
|
||||
"notSupported": "Device doesn't support picture-in-picture mode",
|
||||
"failed": "Picture-in-picture failed to start",
|
||||
"unknown": "An error occurred: ${error}"
|
||||
}
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "Admin",
|
||||
@@ -292,7 +342,8 @@
|
||||
"noItemsAvailable": "No items available",
|
||||
"failedToCreatePlayQueue": "Failed to create play queue",
|
||||
"failedToCreatePlayQueueNoItems": "Failed to create play queue - no items",
|
||||
"failedPlayback": "Failed to ${action}: ${error}"
|
||||
"failedPlayback": "Failed to ${action}: ${error}",
|
||||
"switchingToCompatiblePlayer": "Switching to compatible player..."
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "Styling Options",
|
||||
@@ -554,7 +605,8 @@
|
||||
"codeMustBe8Chars": "Session code must be 8 characters",
|
||||
"joinInstructions": "Enter the session code shared by the host to join their watch session.",
|
||||
"failedToCreate": "Failed to create session",
|
||||
"failedToJoin": "Failed to join session"
|
||||
"failedToJoin": "Failed to join session",
|
||||
"sessionCodeCopied": "Session code copied to clipboard"
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Downloads",
|
||||
@@ -0,0 +1,627 @@
|
||||
{
|
||||
"app": {
|
||||
"title": "Plezy",
|
||||
"loading": "Chargement..."
|
||||
},
|
||||
"auth": {
|
||||
"signInWithPlex": "S'inscrire avec Plex",
|
||||
"showQRCode": "Afficher le QR Code",
|
||||
"cancel": "Annuler",
|
||||
"authenticate": "S'authentifier",
|
||||
"retry": "Réessayer",
|
||||
"debugEnterToken": "Debug: Entrez votre token Plex",
|
||||
"plexTokenLabel": "Token d'authentification Plex",
|
||||
"plexTokenHint": "Entrez votre token Plex.tv",
|
||||
"authenticationTimeout": "Délai d'authentification expiré. Veuillez réessayer.",
|
||||
"scanQRCodeInstruction": "Scannez ce code QR avec un appareil connecté à Plex pour vous authentifier.",
|
||||
"waitingForAuth": "En attente d'authentification...\nVeuillez vous connecter dans votre navigateur."
|
||||
},
|
||||
"common": {
|
||||
"cancel": "Annuler",
|
||||
"save": "Sauvegarder",
|
||||
"close": "Fermer",
|
||||
"clear": "Nettoyer",
|
||||
"reset": "Réinitialiser",
|
||||
"later": "Plus tard",
|
||||
"submit": "Soumettre",
|
||||
"confirm": "Confirmer",
|
||||
"retry": "Réessayer",
|
||||
"logout": "Se déconnecter",
|
||||
"unknown": "Inconnu",
|
||||
"refresh": "Rafraichir",
|
||||
"yes": "Oui",
|
||||
"no": "Non",
|
||||
"delete": "Supprimer",
|
||||
"shuffle": "Mélanger",
|
||||
"addTo": "Ajouter à..."
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Licenses",
|
||||
"switchProfile": "Changer de profil",
|
||||
"subtitleStyling": "Configuration des sous-titres",
|
||||
"mpvConfig": "Configuration MPV",
|
||||
"search": "Recherche",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"update": {
|
||||
"available": "Mise à jour disponible",
|
||||
"versionAvailable": "Version ${version} disponible",
|
||||
"currentVersion": "Installé: ${version}",
|
||||
"skipVersion": "Ignorer cette version",
|
||||
"viewRelease": "Voir la Release",
|
||||
"latestVersion": "Vous utilisez la dernière version",
|
||||
"checkFailed": "Échec de la vérification des mises à jour"
|
||||
},
|
||||
"settings": {
|
||||
"title": "Paramètres",
|
||||
"language": "Langue",
|
||||
"theme": "Thème",
|
||||
"appearance": "Apparence",
|
||||
"videoPlayback": "Lecture vidéo",
|
||||
"advanced": "Avancé",
|
||||
"episodePosterMode": "Style du Poster d'épisode",
|
||||
"seriesPoster": "Poster de série",
|
||||
"seriesPosterDescription": "Afficher le poster de série pour tous les épisodes",
|
||||
"seasonPoster": "Poster de saison",
|
||||
"seasonPosterDescription": "Afficher le poster spécifique à la saison pour les épisodes",
|
||||
"episodeThumbnail": "Mignature d'épisode",
|
||||
"episodeThumbnailDescription": "Afficher les vignettes des captures d'écran des épisodes au format 16:9",
|
||||
"showHeroSectionDescription": "Afficher le carrousel de contenu en vedette sur l'écran d'accueil",
|
||||
"secondsLabel": "Secondes",
|
||||
"minutesLabel": "Minutes",
|
||||
"secondsShort": "s",
|
||||
"minutesShort": "m",
|
||||
"durationHint": "Entrez la durée (${min}-${max})",
|
||||
"systemTheme": "Système",
|
||||
"systemThemeDescription": "Suivre les paramètres système",
|
||||
"lightTheme": "Light",
|
||||
"darkTheme": "Dark",
|
||||
"libraryDensity": "Densité des bibliothèques",
|
||||
"compact": "Compact",
|
||||
"compactDescription": "Cartes plus petites, plus d'éléments visibles",
|
||||
"normal": "Normal",
|
||||
"normalDescription": "Taille par défaut",
|
||||
"comfortable": "Confortable",
|
||||
"comfortableDescription": "Cartes plus grandes, moins d'éléments visibles",
|
||||
"viewMode": "Mode d'affichage",
|
||||
"gridView": "Grille",
|
||||
"gridViewDescription": "Afficher les éléments dans une disposition en grille",
|
||||
"listView": "Liste",
|
||||
"listViewDescription": "Afficher les éléments dans une liste",
|
||||
"showHeroSection": "Afficher la section Hero",
|
||||
"useGlobalHubs": "Utiliser la disposition Plex Home",
|
||||
"useGlobalHubsDescription": "Afficher les hubs de la page d'accueil comme le client Plex officiel. Lorsque cette option est désactivée, affiche à la place les recommandations par bibliothèque.",
|
||||
"showServerNameOnHubs": "Afficher le nom du serveur sur les hubs",
|
||||
"showServerNameOnHubsDescription": "Toujours afficher le nom du serveur dans les titres des hubs. Lorsque cette option est désactivée, seuls les noms de hubs en double s'affichent.",
|
||||
"alwaysKeepSidebarOpen": "Toujours garder la barre latérale ouverte",
|
||||
"alwaysKeepSidebarOpenDescription": "La barre latérale reste étendue et la zone de contenu s'adapte",
|
||||
"playerBackend": "Moteur de lecture",
|
||||
"exoPlayer": "ExoPlayer (Recommandé)",
|
||||
"exoPlayerDescription": "Lecteur natif Android avec meilleur support matériel",
|
||||
"mpv": "MPV",
|
||||
"mpvDescription": "Lecteur avancé avec plus de fonctionnalités et support des sous-titres ASS",
|
||||
"hardwareDecoding": "Décodage matériel",
|
||||
"hardwareDecodingDescription": "Utilisez l'accélération matérielle lorsqu'elle est disponible.",
|
||||
"bufferSize": "Taille du Buffer",
|
||||
"bufferSizeMB": "${size}MB",
|
||||
"subtitleStyling": "Stylisation des sous-titres",
|
||||
"subtitleStylingDescription": "Personnaliser l'apparence des sous-titres",
|
||||
"smallSkipDuration": "Small Skip Duration",
|
||||
"largeSkipDuration": "Large Skip Duration",
|
||||
"secondsUnit": "${seconds} secondes",
|
||||
"defaultSleepTimer": "Minuterie de mise en veille par défaut",
|
||||
"minutesUnit": "${minutes} minutes",
|
||||
"rememberTrackSelections": "Mémoriser les sélections de pistes par émission/film",
|
||||
"rememberTrackSelectionsDescription": "Enregistrer automatiquement les préférences linguistiques pour l'audio et les sous-titres lorsque vous changez de piste pendant la lecture",
|
||||
"clickVideoTogglesPlayback": "Cliquez sur la vidéo pour basculer entre lecture et pause.",
|
||||
"clickVideoTogglesPlaybackDescription": "Si cette option est activée, cliquer sur le lecteur vidéo lancera ou mettra en pause la vidéo. Sinon, le clic affichera ou masquera les commandes de lecture.",
|
||||
"videoPlayerControls": "Commandes du lecteur vidéo",
|
||||
"keyboardShortcuts": "Raccourcis clavier",
|
||||
"keyboardShortcutsDescription": "Personnaliser les raccourcis clavier",
|
||||
"videoPlayerNavigation": "Navigation dans le lecteur vidéo",
|
||||
"videoPlayerNavigationDescription": "Utilisez les touches fléchées pour naviguer dans les commandes du lecteur vidéo.",
|
||||
"debugLogging": "Journalisation de débogage",
|
||||
"debugLoggingDescription": "Activer la journalisation détaillée pour le dépannage",
|
||||
"viewLogs": "Voir les logs",
|
||||
"viewLogsDescription": "Voir les logs d'application",
|
||||
"clearCache": "Vider le cache",
|
||||
"clearCacheDescription": "Cela effacera toutes les images et données mises en cache. Le chargement du contenu de l'application peut prendre plus de temps après avoir effacé le cache.",
|
||||
"clearCacheSuccess": "Cache effacé avec succès",
|
||||
"resetSettings": "Réinitialiser les paramètres",
|
||||
"resetSettingsDescription": "Cela réinitialisera tous les paramètres à leurs valeurs par défaut. Cette action ne peut pas être annulée.",
|
||||
"resetSettingsSuccess": "Réinitialisation des paramètres réussie",
|
||||
"shortcutsReset": "Raccourcis réinitialisés aux valeurs par défaut",
|
||||
"about": "À propos",
|
||||
"aboutDescription": "Informations sur l'application et licences",
|
||||
"updates": "Mises à jour",
|
||||
"updateAvailable": "Mise à jour disponible",
|
||||
"checkForUpdates": "Vérifier les mises à jour",
|
||||
"validationErrorEnterNumber": "Veuillez saisir un numéro valide",
|
||||
"validationErrorDuration": "La durée doit être comprise entre ${min} et ${max} ${unit}",
|
||||
"shortcutAlreadyAssigned": "Raccourci déjà attribué à ${action}",
|
||||
"shortcutUpdated": "Raccourci mis à jour pour ${action}",
|
||||
"autoSkip": "Skip automatique",
|
||||
"autoSkipIntro": "Skip automatique de l'introduction",
|
||||
"autoSkipIntroDescription": "Skipper automatiquement l'introduction après quelques secondes",
|
||||
"autoSkipCredits": "Skip automatique des crédits",
|
||||
"autoSkipCreditsDescription": "Passer les crédits et passer à l'épisode suivant automatiquement",
|
||||
"autoSkipDelay": "Délai avant skip automatique",
|
||||
"autoSkipDelayDescription": "Attendre ${seconds} secondes avant l'auto-skip",
|
||||
"downloads": "Téléchargement",
|
||||
"downloadLocationDescription": "Choisissez où stocker le contenu téléchargé",
|
||||
"downloadLocationDefault": "Par défaut (stockage de l'application)",
|
||||
"downloadLocationCustom": "Emplacement personnalisé",
|
||||
"selectFolder": "Sélectionner un dossier",
|
||||
"resetToDefault": "Réinitialiser les paramètres par défaut",
|
||||
"currentPath": "Actuel: ${path}",
|
||||
"downloadLocationChanged": "Emplacement de téléchargement modifié",
|
||||
"downloadLocationReset": "Emplacement de téléchargement réinitialisé à la valeur par défaut",
|
||||
"downloadLocationInvalid": "Le dossier sélectionné n'est pas accessible en écriture",
|
||||
"downloadLocationSelectError": "Échec de la sélection du dossier",
|
||||
"downloadOnWifiOnly": "Télécharger uniquement via WiFi",
|
||||
"downloadOnWifiOnlyDescription": "Empêcher les téléchargements lorsque vous utilisez les données cellulaires",
|
||||
"cellularDownloadBlocked": "Les téléchargements sont désactivés sur les données cellulaires. Connectez-vous au Wi-Fi ou modifiez le paramètre.",
|
||||
"maxVolume": "Volume maximal",
|
||||
"maxVolumeDescription": "Autoriser l'augmentation du volume au-delà de 100 % pour les médias silencieux",
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Entrez le volume maximal (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Montrez ce que vous regardez sur Discord",
|
||||
"matchContentFrameRate": "Fréquence d'images du contenu correspondant",
|
||||
"matchContentFrameRateDescription": "Ajustez la fréquence de rafraîchissement de l'écran en fonction du contenu vidéo, ce qui réduit les saccades et économise la batterie"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Rechercher des films, des séries, de la musique...",
|
||||
"tryDifferentTerm": "Essayez un autre terme de recherche",
|
||||
"searchYourMedia": "Rechercher dans vos médias",
|
||||
"enterTitleActorOrKeyword": "Entrez un titre, un acteur ou un mot-clé"
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Définir un raccourci pour ${actionName}",
|
||||
"clearShortcut": "Effacer le raccourci",
|
||||
"actions": {
|
||||
"playPause": "Lecture/Pause",
|
||||
"volumeUp": "Augmenter le volume",
|
||||
"volumeDown": "Baisser le volume",
|
||||
"seekForward": "Avancer (${seconds}s)",
|
||||
"seekBackward": "Reculer (${seconds}s)",
|
||||
"fullscreenToggle": "Basculer en mode plein écran",
|
||||
"muteToggle": "Activer/désactiver le mode silencieux",
|
||||
"subtitleToggle": "Activer/désactiver les sous-titres",
|
||||
"audioTrackNext": "Piste audio suivante",
|
||||
"subtitleTrackNext": "Piste de sous-titres suivante",
|
||||
"chapterNext": "Chapitre suivant",
|
||||
"chapterPrevious": "Chapitre précédent",
|
||||
"speedIncrease": "Augmenter la vitesse",
|
||||
"speedDecrease": "Réduire la vitesse",
|
||||
"speedReset": "Réinitialiser la vitesse",
|
||||
"subSeekNext": "Rechercher le sous-titre suivant",
|
||||
"subSeekPrev": "Rechercher le sous-titre précédent"
|
||||
}
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "Entrer le code PIN",
|
||||
"showPin": "Afficher le code PIN",
|
||||
"hidePin": "Masquer le code PIN"
|
||||
},
|
||||
"fileInfo": {
|
||||
"title": "Informations sur le fichier",
|
||||
"video": "Vidéo",
|
||||
"audio": "Audio",
|
||||
"file": "Fichier",
|
||||
"advanced": "Avancé",
|
||||
"codec": "Codec",
|
||||
"resolution": "Résolution",
|
||||
"bitrate": "Bitrate",
|
||||
"frameRate": "Fréquence d'images",
|
||||
"aspectRatio": "Format d'image",
|
||||
"profile": "Profil",
|
||||
"bitDepth": "Profondeur de bits",
|
||||
"colorSpace": "Espace colorimétrique",
|
||||
"colorRange": "Gamme de couleurs",
|
||||
"colorPrimaries": "Couleurs primaires",
|
||||
"chromaSubsampling": "Sous-échantillonnage chromatique",
|
||||
"channels": "Channels",
|
||||
"path": "Chemin",
|
||||
"size": "Taille",
|
||||
"container": "Conteneur",
|
||||
"duration": "Durée",
|
||||
"optimizedForStreaming": "Optimisé pour le streaming",
|
||||
"has64bitOffsets": "Décalages 64 bits"
|
||||
},
|
||||
"mediaMenu": {
|
||||
"markAsWatched": "Marquer comme vu",
|
||||
"markAsUnwatched": "Marquer comme non visionné",
|
||||
"removeFromContinueWatching": "Supprimer de la liste \"Continuer à regarder\"",
|
||||
"goToSeries": "Aller à la série",
|
||||
"goToSeason": "Aller à la saison",
|
||||
"shufflePlay": "Lecture aléatoire",
|
||||
"fileInfo": "Informations sur le fichier"
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}, film",
|
||||
"mediaCardShow": "${title}, show TV",
|
||||
"mediaCardEpisode": "${title}, ${episodeInfo}",
|
||||
"mediaCardSeason": "${title}, ${seasonInfo}",
|
||||
"mediaCardWatched": "visionné",
|
||||
"mediaCardPartiallyWatched": "${percent} pourcentage visionné",
|
||||
"mediaCardUnwatched": "non visionné",
|
||||
"tapToPlay": "Appuyez pour lire"
|
||||
},
|
||||
"tooltips": {
|
||||
"shufflePlay": "Lecture aléatoire",
|
||||
"markAsWatched": "Marqué comme vu",
|
||||
"markAsUnwatched": "Marqué comme non vu"
|
||||
},
|
||||
"videoControls": {
|
||||
"audioLabel": "Audio",
|
||||
"subtitlesLabel": "Sous-titres",
|
||||
"resetToZero": "Réinitialiser à 0ms",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} lire plus tard",
|
||||
"playsEarlier": "${label} lire plus tôt",
|
||||
"noOffset": "Pas de décalage",
|
||||
"letterbox": "Boîte aux lettres",
|
||||
"fillScreen": "Remplir l'écran",
|
||||
"stretch": "Etirer",
|
||||
"lockRotation": "Verrouillage de la rotation",
|
||||
"unlockRotation": "Déverrouiller la rotation",
|
||||
"sleepTimer": "Minuterie de mise en veille",
|
||||
"timerActive": "Minuterie active",
|
||||
"playbackWillPauseIn": "La lecture sera mise en pause dans ${duration}",
|
||||
"sleepTimerCompleted": "Minuterie de mise en veille terminée - lecture en pause",
|
||||
"autoPlayNext": "Lecture automatique suivante",
|
||||
"playNext": "Lire l'épisode suivant",
|
||||
"playButton": "Lire",
|
||||
"pauseButton": "Pause",
|
||||
"seekBackwardButton": "Reculer de ${seconds} secondes",
|
||||
"seekForwardButton": "Avancer de ${seconds} secondes",
|
||||
"previousButton": "Épisode précédent",
|
||||
"nextButton": "Épisode suivant",
|
||||
"previousChapterButton": "Chapitre précédent",
|
||||
"nextChapterButton": "Chapitre suivant",
|
||||
"muteButton": "Mute",
|
||||
"unmuteButton": "Dé-mute",
|
||||
"settingsButton": "Paramètres vidéo",
|
||||
"audioTrackButton": "Pistes audio",
|
||||
"subtitlesButton": "Sous-titres",
|
||||
"chaptersButton": "Chapitres",
|
||||
"versionsButton": "Versions vidéo",
|
||||
"pipButton": "Mode PiP (Picture-in-Picture)",
|
||||
"aspectRatioButton": "Format d'image",
|
||||
"fullscreenButton": "Passer en mode plein écran",
|
||||
"exitFullscreenButton": "Quitter le mode plein écran",
|
||||
"alwaysOnTopButton": "Always on top",
|
||||
"rotationLockButton": "Verrouillage de rotation",
|
||||
"timelineSlider": "Timeline vidéo",
|
||||
"volumeSlider": "Niveau sonore",
|
||||
"backButton": "Retour",
|
||||
"pipFailed": "Échec du démarrage du mode image dans l'image",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Nécessite Android 8.0 ou plus récent",
|
||||
"permissionDisabled": "L'autorisation Image dans l'image est désactivée. Activez-la dans Paramètres > Applications > Plezy > Image dans l'image",
|
||||
"notSupported": "Cet appareil ne prend pas en charge le mode image dans l'image",
|
||||
"failed": "Échec du démarrage du mode image dans l'image",
|
||||
"unknown": "Une erreur s'est produite : ${error}"
|
||||
}
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "Admin",
|
||||
"restricted": "Restreint",
|
||||
"protected": "Protégé",
|
||||
"current": "ACTUEL"
|
||||
},
|
||||
"messages": {
|
||||
"markedAsWatched": "Marqué comme vu",
|
||||
"markedAsUnwatched": "Marqué comme non vu",
|
||||
"markedAsWatchedOffline": "Marqué comme vu (se synchronisera lorsque vous serez en ligne)",
|
||||
"markedAsUnwatchedOffline": "Marqué comme non vu (sera synchronisé lorsque vous serez en ligne)",
|
||||
"removedFromContinueWatching": "Supprimer de \"Continuer à regarder\"",
|
||||
"errorLoading": "Erreur: ${error}",
|
||||
"fileInfoNotAvailable": "Informations sur le fichier non disponibles",
|
||||
"errorLoadingFileInfo": "Erreur lors du chargement des informations sur le fichier: ${error}",
|
||||
"errorLoadingSeries": "Erreur lors du chargement de la série",
|
||||
"errorLoadingSeason": "Erreur lors du chargement de la saison",
|
||||
"musicNotSupported": "La lecture de musique n'est pas encore prise en charge",
|
||||
"logsCleared": "Logs effacés",
|
||||
"logsCopied": "Logs copiés dans le presse-papier",
|
||||
"noLogsAvailable": "Aucun log disponible",
|
||||
"libraryScanning": "Scan de \"${title}\"...",
|
||||
"libraryScanStarted": "Scan de la bibliothèque démarrée pour \"${title}\"",
|
||||
"libraryScanFailed": "Échec du scan de la bibliothèque: ${error}",
|
||||
"metadataRefreshing": "Actualisation des métadonnées pour \"${title}\"...",
|
||||
"metadataRefreshStarted": "Actualisation des métadonnées lancée pour \"${title}\"",
|
||||
"metadataRefreshFailed": "Échec de l'actualisation des métadonnées: ${error}",
|
||||
"logoutConfirm": "Êtes-vous sûr de vouloir vous déconnecter ?",
|
||||
"noSeasonsFound": "Aucune saison trouvée",
|
||||
"noEpisodesFound": "Aucun épisode trouvé dans la première saison",
|
||||
"noEpisodesFoundGeneral": "Aucun épisode trouvé",
|
||||
"noResultsFound": "Aucun résultat trouvé",
|
||||
"sleepTimerSet": "Minuterie de mise en veille réglée sur ${label}",
|
||||
"noItemsAvailable": "Aucun élément disponible",
|
||||
"failedToCreatePlayQueue": "Échec de la création de la file d'attente de lecture",
|
||||
"failedToCreatePlayQueueNoItems": "Échec de la création de la file d'attente de lecture - aucun élément",
|
||||
"failedPlayback": "Echec de ${action}: ${error}",
|
||||
"switchingToCompatiblePlayer": "Passage au lecteur compatible..."
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "Options de style",
|
||||
"fontSize": "Taille de la police",
|
||||
"textColor": "Couleur du texte",
|
||||
"borderSize": "Taille de la bordure",
|
||||
"borderColor": "Couleur de la bordure",
|
||||
"backgroundOpacity": "Opacité d'arrière-plan",
|
||||
"backgroundColor": "Couleur d'arrière-plan"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "Configuration MPV",
|
||||
"description": "Paramètres avancés du lecteur vidéo",
|
||||
"properties": "Propriétés",
|
||||
"presets": "Préréglages",
|
||||
"noProperties": "Aucune propriété configurée",
|
||||
"noPresets": "Aucun préréglage enregistré",
|
||||
"addProperty": "Ajouter une propriété",
|
||||
"editProperty": "Modifier la propriété",
|
||||
"deleteProperty": "Supprimer la propriété",
|
||||
"propertyKey": "Clé",
|
||||
"propertyKeyHint": "e.g., hwdec, demuxer-max-bytes",
|
||||
"propertyValue": "Valeur",
|
||||
"propertyValueHint": "e.g., auto, 256000000",
|
||||
"saveAsPreset": "Enregistrer comme préréglage...",
|
||||
"presetName": "Nom du préréglage",
|
||||
"presetNameHint": "Entrez un nom pour ce préréglage",
|
||||
"loadPreset": "Charger",
|
||||
"deletePreset": "Supprimer",
|
||||
"presetSaved": "Préréglage enregistré",
|
||||
"presetLoaded": "Préréglage chargé",
|
||||
"presetDeleted": "Préréglage supprimé",
|
||||
"confirmDeletePreset": "Êtes-vous sûr de vouloir supprimer ce préréglage ?",
|
||||
"confirmDeleteProperty": "Êtes-vous sûr de vouloir supprimer cette propriété ?",
|
||||
"entriesCount": "${count} entrées"
|
||||
},
|
||||
"dialog": {
|
||||
"confirmAction": "Confirmer l'action",
|
||||
"cancel": "Annuler",
|
||||
"playNow": "Lire maintenant"
|
||||
},
|
||||
"discover": {
|
||||
"title": "Découvrez",
|
||||
"switchProfile": "Changer de profil",
|
||||
"logout": "Déconnexion",
|
||||
"noContentAvailable": "Aucun contenu disponible",
|
||||
"addMediaToLibraries": "Ajoutez des médias à votre bibliothèque",
|
||||
"continueWatching": "Continuer à regarder",
|
||||
"play": "Lire",
|
||||
"playEpisode": "S${season}E${episode}",
|
||||
"pause": "Pause",
|
||||
"overview": "Aperçu",
|
||||
"cast": "Cast",
|
||||
"seasons": "Saisons",
|
||||
"studio": "Studio",
|
||||
"rating": "Évaluation",
|
||||
"watched": "Vu",
|
||||
"episodeCount": "${count} épisodes",
|
||||
"watchedProgress": "${watched}/${total} vu",
|
||||
"movie": "Film",
|
||||
"tvShow": "Show TV",
|
||||
"minutesLeft": "${minutes} min restantes"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "Recherche échouée: ${error}",
|
||||
"connectionTimeout": "Délai d'attente de connexion dépassé pendant le chargement ${context}",
|
||||
"connectionFailed": "Impossible de se connecter au serveur Plex",
|
||||
"failedToLoad": "Échec du chargement ${context}: ${error}",
|
||||
"noClientAvailable": "Aucun client disponible",
|
||||
"authenticationFailed": "Échec de l'authentification: ${error}",
|
||||
"couldNotLaunchUrl": "Impossible de lancer l'URL d'authentification",
|
||||
"pleaseEnterToken": "Veuillez saisir un token",
|
||||
"invalidToken": "Token invalide",
|
||||
"failedToVerifyToken": "Échec de la vérification du token: ${error}",
|
||||
"failedToSwitchProfile": "Impossible de changer de profil vers ${displayName}"
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Bibliothèques",
|
||||
"scanLibraryFiles": "Scanner les fichiers de la bibliothèque",
|
||||
"scanLibrary": "Scanner la bibliothèque",
|
||||
"analyze": "Analyser",
|
||||
"analyzeLibrary": "Analyser la bibliothèque",
|
||||
"refreshMetadata": "Actualiser les métadonnées",
|
||||
"emptyTrash": "Vider la corbeille",
|
||||
"emptyingTrash": "Vider les poubelles pour \"${title}\"...",
|
||||
"trashEmptied": "Poubelles vidées pour \"${title}\"",
|
||||
"failedToEmptyTrash": "Échec de la suppression des éléments supprimés: ${error}",
|
||||
"analyzing": "Analyse de \"${title}\"...",
|
||||
"analysisStarted": "L'analyse a commencé pour \"${title}\"",
|
||||
"failedToAnalyze": "Échec de l'analyse de la bibliothèque: ${error}",
|
||||
"noLibrariesFound": "Aucune bibliothèque trouvée",
|
||||
"thisLibraryIsEmpty": "Cette bibliothèque est vide",
|
||||
"all": "Tout",
|
||||
"clearAll": "Tout effacer",
|
||||
"scanLibraryConfirm": "Êtes-vous sûr de vouloir lancer le scan de \"${title}\"?",
|
||||
"analyzeLibraryConfirm": "Êtes-vous sûr de vouloir analyser \"${title}\"?",
|
||||
"refreshMetadataConfirm": "Êtes-vous sûr de vouloir actualiser les métadonnées pour \"${title}\"?",
|
||||
"emptyTrashConfirm": "Êtes-vous sûr de vouloir vider la corbeille pour \"${title}\"?",
|
||||
"manageLibraries": "Gérer les bibliothèques",
|
||||
"sort": "Trier",
|
||||
"sortBy": "Trier par",
|
||||
"filters": "Filtres",
|
||||
"confirmActionMessage": "Êtes-vous sûr de vouloir effectuer cette action ?",
|
||||
"showLibrary": "Afficher la bibliothèque",
|
||||
"hideLibrary": "Masquer la bibliothèque",
|
||||
"libraryOptions": "Options de bibliothèque",
|
||||
"content": "contenu de la bibliothèque",
|
||||
"selectLibrary": "Sélectionner la bibliothèque",
|
||||
"filtersWithCount": "Filtres (${count})",
|
||||
"noRecommendations": "Aucune recommandation disponible",
|
||||
"noCollections": "Aucune collection dans cette bibliothèque",
|
||||
"noFoldersFound": "Aucun dossier trouvé",
|
||||
"folders": "dossiers",
|
||||
"tabs": {
|
||||
"recommended": "Recommandé",
|
||||
"browse": "Parcourir",
|
||||
"collections": "Collections",
|
||||
"playlists": "Playlists"
|
||||
},
|
||||
"groupings": {
|
||||
"all": "Tous",
|
||||
"movies": "Films",
|
||||
"shows": "Show TV",
|
||||
"seasons": "Saisons",
|
||||
"episodes": "Épisodes",
|
||||
"folders": "Dossiers"
|
||||
}
|
||||
},
|
||||
"about": {
|
||||
"title": "À propos",
|
||||
"openSourceLicenses": "Licences Open Source",
|
||||
"versionLabel": "Version ${version}",
|
||||
"appDescription": "Un magnifique client Plex pour Flutter",
|
||||
"viewLicensesDescription": "Afficher les licences des bibliothèques tierces"
|
||||
},
|
||||
"serverSelection": {
|
||||
"allServerConnectionsFailed": "Impossible de se connecter à un serveur. Veuillez vérifier votre connexion réseau et réessayer.",
|
||||
"noServersFound": "Aucun serveur trouvé",
|
||||
"noServersFoundForAccount": "Aucun serveur trouvé pour ${username} (${email})",
|
||||
"failedToLoadServers": "Échec du chargement des serveurs: ${error}"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Titre",
|
||||
"releaseYear": "Année de sortie",
|
||||
"dateAdded": "Date d'ajout",
|
||||
"rating": "Évaluation",
|
||||
"noItemsFound": "Aucun élément trouvé"
|
||||
},
|
||||
"logs": {
|
||||
"clearLogs": "Effacer les logs",
|
||||
"copyLogs": "Copier les logs",
|
||||
"error": "Erreur:",
|
||||
"stackTrace": "Liste des appels:"
|
||||
},
|
||||
"licenses": {
|
||||
"relatedPackages": "Package associés",
|
||||
"license": "Licence",
|
||||
"licenseNumber": "Licence ${number}",
|
||||
"licensesCount": "${count} licences"
|
||||
},
|
||||
"navigation": {
|
||||
"home": "Accueil",
|
||||
"search": "Rechercher",
|
||||
"libraries": "Bibliothèques",
|
||||
"settings": "Paramètres",
|
||||
"downloads": "Téléchargements"
|
||||
},
|
||||
"collections": {
|
||||
"title": "Collections",
|
||||
"collection": "Collection",
|
||||
"empty": "La collection est vide",
|
||||
"unknownLibrarySection": "Impossible de supprimer : section de bibliothèque inconnue",
|
||||
"deleteCollection": "Supprimer la collection",
|
||||
"deleteConfirm": "Êtes-vous sûr de vouloir supprimer \"${title}\" ? Cette action ne peut pas être annulée.",
|
||||
"deleted": "Collection supprimée",
|
||||
"deleteFailed": "Échec de la suppression de la collection",
|
||||
"deleteFailedWithError": "Échec de la suppression de la collection: ${error}",
|
||||
"failedToLoadItems": "Échec du chargement des éléments de la collection: ${error}",
|
||||
"selectCollection": "Sélectionner une collection",
|
||||
"createNewCollection": "Créer une nouvelle collection",
|
||||
"collectionName": "Nom de la collection",
|
||||
"enterCollectionName": "Entrez le nom de la collection",
|
||||
"addedToCollection": "Ajouté à la collection",
|
||||
"errorAddingToCollection": "Échec de l'ajout à la collection",
|
||||
"created": "Collection créée",
|
||||
"removeFromCollection": "Supprimer de la collection",
|
||||
"removeFromCollectionConfirm": "Retirer \"${title}\" de cette collection ?",
|
||||
"removedFromCollection": "Retiré de la collection",
|
||||
"removeFromCollectionFailed": "Impossible de supprimer de la collection",
|
||||
"removeFromCollectionError": "Erreur lors de la suppression de la collection: ${error}"
|
||||
},
|
||||
"playlists": {
|
||||
"title": "Playlists",
|
||||
"playlist": "Playlist",
|
||||
"noPlaylists": "Aucune playlist trouvée",
|
||||
"create": "Créer une playlist",
|
||||
"playlistName": "Nom de playlist",
|
||||
"enterPlaylistName": "Entrer le nom de playlist",
|
||||
"delete": "Supprimer la playlist",
|
||||
"removeItem": "Retirer de la playlist",
|
||||
"smartPlaylist": "Smart playlist",
|
||||
"itemCount": "${count} éléments",
|
||||
"oneItem": "1 élément",
|
||||
"emptyPlaylist": "Cette playlist est vide",
|
||||
"deleteConfirm": "Supprimer la playlist ?",
|
||||
"deleteMessage": "Êtes-vous sûr de vouloir supprimer \"${name}\"?",
|
||||
"created": "Playlist créée",
|
||||
"deleted": "Playlist supprimée",
|
||||
"itemAdded": "Ajouté à la playlist",
|
||||
"itemRemoved": "Retiré de la playlist",
|
||||
"selectPlaylist": "Select Playlist",
|
||||
"createNewPlaylist": "Créer une nouvelle playlist",
|
||||
"errorCreating": "Échec de la création de playlist",
|
||||
"errorDeleting": "Échec de suppression de playlist",
|
||||
"errorLoading": "Échec de chargement de playlists",
|
||||
"errorAdding": "Échec d'ajout dans la playlist",
|
||||
"errorReordering": "Échec de réordonnacement d'élément de playlist",
|
||||
"errorRemoving": "Échec de suppression depuis la playlist"
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Regarder ensemble",
|
||||
"description": "Regardez du contenu en synchronisation avec vos amis et votre famille",
|
||||
"createSession": "Créer une session",
|
||||
"creating": "Création...",
|
||||
"joinSession": "Rejoindre la session",
|
||||
"joining": "Rejoindre...",
|
||||
"controlMode": "Mode de contrôle",
|
||||
"controlModeQuestion": "Qui peut contrôler la lecture ?",
|
||||
"hostOnly": "Hôte uniquement",
|
||||
"anyone": "N'importe qui",
|
||||
"hostingSession": "Session d'hébergement",
|
||||
"inSession": "En session",
|
||||
"sessionCode": "Code de session",
|
||||
"hostControlsPlayback": "L'hôte contrôle la lecture",
|
||||
"anyoneCanControl": "Tout le monde peut contrôler la lecture",
|
||||
"hostControls": "Commandes de l'hôte",
|
||||
"anyoneControls": "Tout le monde contrôle",
|
||||
"participants": "Participants",
|
||||
"host": "Hôte",
|
||||
"hostBadge": "HOST",
|
||||
"youAreHost": "Vous êtes l'hôte",
|
||||
"watchingWithOthers": "Regarder avec d'autres personnes",
|
||||
"endSession": "Fin de session",
|
||||
"leaveSession": "Quitter la session",
|
||||
"endSessionQuestion": "Terminer la session ?",
|
||||
"leaveSessionQuestion": "Quitter la session ?",
|
||||
"endSessionConfirm": "Cela mettra fin à la session pour tous les participants.",
|
||||
"leaveSessionConfirm": "Vous allez être déconnecté de la session.",
|
||||
"endSessionConfirmOverlay": "Cela mettra fin à la session de visionnage pour tous les participants.",
|
||||
"leaveSessionConfirmOverlay": "Vous serez déconnecté de la session de visionnage.",
|
||||
"end": "Terminer",
|
||||
"leave": "Fin",
|
||||
"syncing": "Synchronisation...",
|
||||
"participant": "participant",
|
||||
"joinWatchSession": "Rejoindre la session de visionnage",
|
||||
"enterCodeHint": "Entrez le code à 8 caractères",
|
||||
"pasteFromClipboard": "Coller depuis le presse-papiers",
|
||||
"pleaseEnterCode": "Veuillez saisir un code de session",
|
||||
"codeMustBe8Chars": "Le code de session doit comporter 8 caractères",
|
||||
"joinInstructions": "Entrez le code de session partagé par l'hôte pour rejoindre sa session de visionnage.",
|
||||
"failedToCreate": "Échec de la création de la session",
|
||||
"failedToJoin": "Échec de la connexion à la session",
|
||||
"sessionCodeCopied": "Code de session copié dans le presse-papiers"
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Téléchargements",
|
||||
"manage": "Gérer",
|
||||
"tvShows": "Show TV",
|
||||
"movies": "Films",
|
||||
"noDownloads": "Aucun téléchargement pour le moment",
|
||||
"noDownloadsDescription": "Le contenu téléchargé apparaîtra ici pour être consulté hors ligne.",
|
||||
"downloadNow": "Télécharger",
|
||||
"deleteDownload": "Supprimer le téléchargement",
|
||||
"retryDownload": "Réessayer le téléchargement",
|
||||
"downloadQueued": "Téléchargement en attente",
|
||||
"episodesQueued": "${count} épisodes en attente de téléchargement",
|
||||
"downloadDeleted": "Télécharger supprimé",
|
||||
"deleteConfirm": "Êtes-vous sûr de vouloir supprimer \"${title}\" ? Cela supprimera le fichier téléchargé de votre appareil.",
|
||||
"deletingWithProgress": "Suppression de ${title}... (${current} sur ${total})"
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,13 @@
|
||||
"appearance": "Aspetto",
|
||||
"videoPlayback": "Riproduzione video",
|
||||
"advanced": "Avanzate",
|
||||
"useSeasonPostersDescription": "Mostra il poster della stagione invece del poster della serie per gli episodi",
|
||||
"episodePosterMode": "Stile poster episodio",
|
||||
"seriesPoster": "Poster della serie",
|
||||
"seriesPosterDescription": "Mostra il poster della serie per tutti gli episodi",
|
||||
"seasonPoster": "Poster della stagione",
|
||||
"seasonPosterDescription": "Mostra il poster specifico della stagione per gli episodi",
|
||||
"episodeThumbnail": "Miniatura episodio",
|
||||
"episodeThumbnailDescription": "Mostra miniature 16:9 degli episodi",
|
||||
"showHeroSectionDescription": "Visualizza il carosello dei contenuti in primo piano sulla schermata iniziale",
|
||||
"secondsLabel": "Secondi",
|
||||
"minutesLabel": "Minuti",
|
||||
@@ -83,8 +89,18 @@
|
||||
"gridViewDescription": "Visualizza gli elementi in un layout a griglia",
|
||||
"listView": "Elenco",
|
||||
"listViewDescription": "Visualizza gli elementi in un layout a elenco",
|
||||
"useSeasonPosters": "Usa poster delle stagioni",
|
||||
"showHeroSection": "Mostra sezione principale",
|
||||
"useGlobalHubs": "Usa layout Home di Plex",
|
||||
"useGlobalHubsDescription": "Mostra gli hub della home page come il client Plex ufficiale. Se disattivato, mostra invece i suggerimenti per libreria.",
|
||||
"showServerNameOnHubs": "Mostra nome server sugli hub",
|
||||
"showServerNameOnHubsDescription": "Mostra sempre il nome del server nei titoli degli hub. Se disattivato, solo per nomi hub duplicati.",
|
||||
"alwaysKeepSidebarOpen": "Mantieni sempre aperta la barra laterale",
|
||||
"alwaysKeepSidebarOpenDescription": "La barra laterale rimane espansa e l'area del contenuto si adatta",
|
||||
"playerBackend": "Motore di riproduzione",
|
||||
"exoPlayer": "ExoPlayer (Consigliato)",
|
||||
"exoPlayerDescription": "Lettore nativo Android con migliore supporto hardware",
|
||||
"mpv": "MPV",
|
||||
"mpvDescription": "Lettore avanzato con più funzionalità e supporto sottotitoli ASS",
|
||||
"hardwareDecoding": "Decodifica Hardware",
|
||||
"hardwareDecodingDescription": "Utilizza l'accelerazione hardware quando disponibile",
|
||||
"bufferSize": "Dimensione buffer",
|
||||
@@ -98,6 +114,8 @@
|
||||
"minutesUnit": "${minutes} minuti",
|
||||
"rememberTrackSelections": "Ricorda selezioni tracce per serie/film",
|
||||
"rememberTrackSelectionsDescription": "Salva automaticamente le preferenze delle lingue audio e sottotitoli quando cambi tracce durante la riproduzione",
|
||||
"clickVideoTogglesPlayback": "Fai clic sul video per avviare o mettere in pausa la riproduzione.",
|
||||
"clickVideoTogglesPlaybackDescription": "Se questa opzione è abilitata, facendo clic sul lettore video la riproduzione verrà avviata o messa in pausa. In caso contrario, facendo clic verranno mostrati o nascosti i controlli di riproduzione.",
|
||||
"videoPlayerControls": "Controlli del lettore video",
|
||||
"keyboardShortcuts": "Scorciatoie da tastiera",
|
||||
"keyboardShortcutsDescription": "Personalizza le scorciatoie da tastiera",
|
||||
@@ -149,7 +167,9 @@
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Inserisci volume massimo (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Mostra su Discord cosa stai guardando"
|
||||
"discordRichPresenceDescription": "Mostra su Discord cosa stai guardando",
|
||||
"matchContentFrameRate": "Adatta frequenza fotogrammi",
|
||||
"matchContentFrameRateDescription": "Regola la frequenza di aggiornamento del display in base al contenuto video, riducendo i tremolii e risparmiando batteria"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Cerca film. spettacoli, musica...",
|
||||
@@ -159,7 +179,26 @@
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Imposta scorciatoia per ${actionName}",
|
||||
"clearShortcut": "Elimina scorciatoia"
|
||||
"clearShortcut": "Elimina scorciatoia",
|
||||
"actions": {
|
||||
"playPause": "Riproduci/Pausa",
|
||||
"volumeUp": "Alza volume",
|
||||
"volumeDown": "Abbassa volume",
|
||||
"seekForward": "Avanti (${seconds}s)",
|
||||
"seekBackward": "Indietro (${seconds}s)",
|
||||
"fullscreenToggle": "Schermo intero",
|
||||
"muteToggle": "Muto",
|
||||
"subtitleToggle": "Sottotitoli",
|
||||
"audioTrackNext": "Traccia audio successiva",
|
||||
"subtitleTrackNext": "Sottotitoli successivi",
|
||||
"chapterNext": "Capitolo successivo",
|
||||
"chapterPrevious": "Capitolo precedente",
|
||||
"speedIncrease": "Aumenta velocità",
|
||||
"speedDecrease": "Diminuisci velocità",
|
||||
"speedReset": "Ripristina velocità",
|
||||
"subSeekNext": "Vai al sottotitolo successivo",
|
||||
"subSeekPrev": "Vai al sottotitolo precedente"
|
||||
}
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "Inserisci PIN",
|
||||
@@ -233,6 +272,8 @@
|
||||
"timerActive": "Timer attivo",
|
||||
"playbackWillPauseIn": "La riproduzione si interromperà tra ${duration}",
|
||||
"sleepTimerCompleted": "Timer di spegnimento completato - riproduzione in pausa",
|
||||
"autoPlayNext": "Riproduzione automatica successivo",
|
||||
"playNext": "Riproduci successivo",
|
||||
"playButton": "Riproduci",
|
||||
"pauseButton": "Pausa",
|
||||
"seekBackwardButton": "Riavvolgi di ${seconds} secondi",
|
||||
@@ -248,6 +289,7 @@
|
||||
"subtitlesButton": "Sottotitoli",
|
||||
"chaptersButton": "Capitoli",
|
||||
"versionsButton": "Versioni video",
|
||||
"pipButton": "Modalità Picture-in-Picture",
|
||||
"aspectRatioButton": "Proporzioni",
|
||||
"fullscreenButton": "Attiva schermo intero",
|
||||
"exitFullscreenButton": "Esci da schermo intero",
|
||||
@@ -255,7 +297,15 @@
|
||||
"rotationLockButton": "Blocco rotazione",
|
||||
"timelineSlider": "Timeline video",
|
||||
"volumeSlider": "Livello volume",
|
||||
"backButton": "Indietro"
|
||||
"backButton": "Indietro",
|
||||
"pipFailed": "Impossibile avviare la modalità Picture-in-Picture",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Richiede Android 8.0 o versioni successive",
|
||||
"permissionDisabled": "L'autorizzazione Picture-in-Picture è disabilitata. Abilitala in Impostazioni > App > Plezy > Picture-in-Picture",
|
||||
"notSupported": "Questo dispositivo non supporta la modalità Picture-in-Picture",
|
||||
"failed": "Impossibile avviare la modalità Picture-in-Picture",
|
||||
"unknown": "Si è verificato un errore: ${error}"
|
||||
}
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "Admin",
|
||||
@@ -293,7 +343,8 @@
|
||||
"noItemsAvailable": "Nessun elemento disponibile",
|
||||
"failedToCreatePlayQueue": "Impossibile creare la coda di riproduzione",
|
||||
"failedToCreatePlayQueueNoItems": "Impossibile creare la coda di riproduzione - nessun elemento",
|
||||
"failedPlayback": "Impossibile ${action}: ${error}"
|
||||
"failedPlayback": "Impossibile ${action}: ${error}",
|
||||
"switchingToCompatiblePlayer": "Passaggio al lettore compatibile..."
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "Opzioni stile",
|
||||
@@ -572,6 +623,7 @@
|
||||
"codeMustBe8Chars": "Il codice sessione deve essere di 8 caratteri",
|
||||
"joinInstructions": "Inserisci il codice sessione condiviso dall'host per unirti alla loro sessione di visione.",
|
||||
"failedToCreate": "Impossibile creare la sessione",
|
||||
"failedToJoin": "Impossibile unirsi alla sessione"
|
||||
"failedToJoin": "Impossibile unirsi alla sessione",
|
||||
"sessionCodeCopied": "Codice sessione copiato negli appunti"
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,13 @@
|
||||
"appearance": "외관",
|
||||
"videoPlayback": "비디오 재생",
|
||||
"advanced": "고급",
|
||||
"useSeasonPostersDescription": "에피소드에 시리즈 포스터 대신 시즌 포스터 표시",
|
||||
"episodePosterMode": "에피소드 포스터 스타일",
|
||||
"seriesPoster": "시리즈 포스터",
|
||||
"seriesPosterDescription": "모든 에피소드에 시리즈 포스터 표시",
|
||||
"seasonPoster": "시즌 포스터",
|
||||
"seasonPosterDescription": "에피소드에 시즌별 포스터 표시",
|
||||
"episodeThumbnail": "에피소드 썸네일",
|
||||
"episodeThumbnailDescription": "16:9 에피소드 스크린샷 썸네일 표시",
|
||||
"showHeroSectionDescription": "홈 화면에 주요 콘텐츠 캐러셀(슬라이드) 표시",
|
||||
"secondsLabel": "초",
|
||||
"minutesLabel": "분",
|
||||
@@ -83,8 +89,18 @@
|
||||
"gridViewDescription": "항목을 그리드 레이아웃으로 표시합니다",
|
||||
"listView": "목록 보기",
|
||||
"listViewDescription": "항목을 목록 레이아웃으로 표시합니다",
|
||||
"useSeasonPosters": "시즌 포스터 사용",
|
||||
"showHeroSection": "주요 추천 영역 표시",
|
||||
"useGlobalHubs": "Plex 홈 레이아웃 사용",
|
||||
"useGlobalHubsDescription": "공식 Plex 클라이언트처럼 홈 페이지 허브를 표시합니다. 끄면 라이브러리별 추천이 대신 표시됩니다.",
|
||||
"showServerNameOnHubs": "허브에 서버 이름 표시",
|
||||
"showServerNameOnHubsDescription": "허브 제목에 항상 서버 이름을 표시합니다. 끄면 중복된 허브 이름에만 표시됩니다.",
|
||||
"alwaysKeepSidebarOpen": "사이드바 항상 열어두기",
|
||||
"alwaysKeepSidebarOpenDescription": "사이드바가 확장된 상태로 유지되고 콘텐츠 영역이 맞춰집니다",
|
||||
"playerBackend": "플레이어 백엔드",
|
||||
"exoPlayer": "ExoPlayer (권장)",
|
||||
"exoPlayerDescription": "더 나은 하드웨어 지원을 제공하는 Android 네이티브 플레이어",
|
||||
"mpv": "MPV",
|
||||
"mpvDescription": "더 많은 기능과 ASS 자막을 지원하는 고급 플레이어",
|
||||
"hardwareDecoding": "하드웨어 디코딩",
|
||||
"hardwareDecodingDescription": "가능한 경우 하드웨어 가속을 사용합니다",
|
||||
"bufferSize": "버퍼 크기",
|
||||
@@ -98,6 +114,8 @@
|
||||
"minutesUnit": "${minutes}분",
|
||||
"rememberTrackSelections": "에피소드/영화별 트랙 선택 기억",
|
||||
"rememberTrackSelectionsDescription": "재생 중 트랙을 변경할 때 오디오 및 자막 언어 설정을 자동으로 저장합니다",
|
||||
"clickVideoTogglesPlayback": "비디오를 클릭하여 재생/일시정지를 전환하세요.",
|
||||
"clickVideoTogglesPlaybackDescription": "이 옵션이 활성화되어 있으면 비디오 플레이어를 클릭할 때 재생 또는 일시정지가 됩니다. 그렇지 않으면 클릭 시 재생 컨트롤이 표시되거나 숨겨집니다.",
|
||||
"videoPlayerControls": "비디오 플레이어 컨트롤",
|
||||
"keyboardShortcuts": "키보드 단축키",
|
||||
"keyboardShortcutsDescription": "사용자 정의 키보드 단축키",
|
||||
@@ -149,7 +167,9 @@
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "최대 볼륨 입력 (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Discord에서 시청 중인 콘텐츠 표시"
|
||||
"discordRichPresenceDescription": "Discord에서 시청 중인 콘텐츠 표시",
|
||||
"matchContentFrameRate": "콘텐츠 프레임 레이트 맞춤",
|
||||
"matchContentFrameRateDescription": "비디오 콘텐츠에 맞게 디스플레이 주사율을 조정하여 떨림을 줄이고 배터리를 절약합니다"
|
||||
},
|
||||
"search": {
|
||||
"hint": "영화, 시리즈, 음악 등을 검색하세요...",
|
||||
@@ -159,7 +179,26 @@
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "${actionName}에 대한 단축키 설정",
|
||||
"clearShortcut": "단축키 삭제"
|
||||
"clearShortcut": "단축키 삭제",
|
||||
"actions": {
|
||||
"playPause": "재생/일시정지",
|
||||
"volumeUp": "볼륨 높이기",
|
||||
"volumeDown": "볼륨 낮추기",
|
||||
"seekForward": "앞으로 이동 (${seconds}초)",
|
||||
"seekBackward": "뒤로 이동 (${seconds}초)",
|
||||
"fullscreenToggle": "전체 화면 전환",
|
||||
"muteToggle": "음소거 전환",
|
||||
"subtitleToggle": "자막 전환",
|
||||
"audioTrackNext": "다음 오디오 트랙",
|
||||
"subtitleTrackNext": "다음 자막 트랙",
|
||||
"chapterNext": "다음 챕터",
|
||||
"chapterPrevious": "이전 챕터",
|
||||
"speedIncrease": "속도 높이기",
|
||||
"speedDecrease": "속도 낮추기",
|
||||
"speedReset": "속도 초기화",
|
||||
"subSeekNext": "다음 자막으로 이동",
|
||||
"subSeekPrev": "이전 자막으로 이동"
|
||||
}
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "PIN 입력",
|
||||
@@ -233,6 +272,8 @@
|
||||
"timerActive": "타이머 활성화됨",
|
||||
"playbackWillPauseIn": "재생이 ${duration} 후에 일시 중지 됩니다",
|
||||
"sleepTimerCompleted": "수면 타이머 완료됨 - 재생이 일시 중지되었습니다",
|
||||
"autoPlayNext": "다음 자동 재생",
|
||||
"playNext": "다음 재생",
|
||||
"playButton": "재생",
|
||||
"pauseButton": "일시정지",
|
||||
"seekBackwardButton": "${seconds} 초 뒤로",
|
||||
@@ -248,6 +289,7 @@
|
||||
"subtitlesButton": "자막",
|
||||
"chaptersButton": "챕터",
|
||||
"versionsButton": "동영상 버전",
|
||||
"pipButton": "픽처 인 픽처 모드",
|
||||
"aspectRatioButton": "화면비율",
|
||||
"fullscreenButton": "전체화면",
|
||||
"exitFullscreenButton": "전체화면 종료",
|
||||
@@ -255,7 +297,15 @@
|
||||
"rotationLockButton": "회전 잠금",
|
||||
"timelineSlider": "타임라인",
|
||||
"volumeSlider": "볼륨 조절",
|
||||
"backButton": "뒤로 가기"
|
||||
"backButton": "뒤로 가기",
|
||||
"pipFailed": "화면 속 화면 모드를 시작할 수 없습니다",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Android 8.0 이상이 필요합니다",
|
||||
"permissionDisabled": "화면 속 화면 권한이 비활성화되어 있습니다. 설정 > 앱 > Plezy > 화면 속 화면에서 활성화하세요",
|
||||
"notSupported": "이 기기는 화면 속 화면 모드를 지원하지 않습니다",
|
||||
"failed": "화면 속 화면 모드를 시작할 수 없습니다",
|
||||
"unknown": "오류가 발생했습니다: ${error}"
|
||||
}
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "관리자",
|
||||
@@ -293,7 +343,8 @@
|
||||
"noItemsAvailable": "사용 가능한 항목이 없습니다",
|
||||
"failedToCreatePlayQueue": "재생 대기열 생성 실패",
|
||||
"failedToCreatePlayQueueNoItems": "재생 대기열 생성 실패 - 항목 없음",
|
||||
"failedPlayback": "${action}을(를) 수행할 수 없습니다: ${error}"
|
||||
"failedPlayback": "${action}을(를) 수행할 수 없습니다: ${error}",
|
||||
"switchingToCompatiblePlayer": "호환되는 플레이어로 전환 중..."
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "스타일 옵션",
|
||||
@@ -556,7 +607,8 @@
|
||||
"codeMustBe8Chars": "세션 코드는 반드시 8자리여야 합니다",
|
||||
"joinInstructions": "호스트가 공유한 세션 코드를 입력하여 시청 세션에 참여하세요.",
|
||||
"failedToCreate": "세션 생성 실패",
|
||||
"failedToJoin": "세션 참여 실패"
|
||||
"failedToJoin": "세션 참여 실패",
|
||||
"sessionCodeCopied": "세션 코드가 클립보드에 복사되었습니다"
|
||||
},
|
||||
"downloads": {
|
||||
"title": "다운로드",
|
||||
@@ -60,7 +60,13 @@
|
||||
"appearance": "Uiterlijk",
|
||||
"videoPlayback": "Video afspelen",
|
||||
"advanced": "Geavanceerd",
|
||||
"useSeasonPostersDescription": "Toon seizoenposter in plaats van serieposter voor afleveringen",
|
||||
"episodePosterMode": "Aflevering poster stijl",
|
||||
"seriesPoster": "Serie poster",
|
||||
"seriesPosterDescription": "Toon de serie poster voor alle afleveringen",
|
||||
"seasonPoster": "Seizoen poster",
|
||||
"seasonPosterDescription": "Toon de seizoensspecifieke poster voor afleveringen",
|
||||
"episodeThumbnail": "Aflevering miniatuur",
|
||||
"episodeThumbnailDescription": "Toon 16:9 aflevering miniaturen",
|
||||
"showHeroSectionDescription": "Toon uitgelichte inhoud carrousel op startscherm",
|
||||
"secondsLabel": "Seconden",
|
||||
"minutesLabel": "Minuten",
|
||||
@@ -83,8 +89,18 @@
|
||||
"gridViewDescription": "Items weergeven in een rasterindeling",
|
||||
"listView": "Lijst",
|
||||
"listViewDescription": "Items weergeven in een lijstindeling",
|
||||
"useSeasonPosters": "Gebruik seizoenposters",
|
||||
"showHeroSection": "Toon hoofdsectie",
|
||||
"useGlobalHubs": "Plex Home-indeling gebruiken",
|
||||
"useGlobalHubsDescription": "Toon startpagina-hubs zoals de officiële Plex-client. Indien uitgeschakeld, worden in plaats daarvan aanbevelingen per bibliotheek getoond.",
|
||||
"showServerNameOnHubs": "Servernaam tonen bij hubs",
|
||||
"showServerNameOnHubsDescription": "Toon altijd de servernaam in hub-titels. Indien uitgeschakeld, alleen bij dubbele hub-namen.",
|
||||
"alwaysKeepSidebarOpen": "Zijbalk altijd open houden",
|
||||
"alwaysKeepSidebarOpenDescription": "Zijbalk blijft uitgevouwen en inhoudsgebied past zich aan",
|
||||
"playerBackend": "Speler backend",
|
||||
"exoPlayer": "ExoPlayer (Aanbevolen)",
|
||||
"exoPlayerDescription": "Android-native speler met betere hardware-ondersteuning",
|
||||
"mpv": "MPV",
|
||||
"mpvDescription": "Geavanceerde speler met meer functies en ASS-ondertitelondersteuning",
|
||||
"hardwareDecoding": "Hardware decodering",
|
||||
"hardwareDecodingDescription": "Gebruik hardware versnelling indien beschikbaar",
|
||||
"bufferSize": "Buffer grootte",
|
||||
@@ -98,6 +114,8 @@
|
||||
"minutesUnit": "bij ${minutes} minuten",
|
||||
"rememberTrackSelections": "Onthoud track selecties per serie/film",
|
||||
"rememberTrackSelectionsDescription": "Bewaar automatisch audio- en ondertiteltaalvoorkeuren wanneer je tracks wijzigt tijdens afspelen",
|
||||
"clickVideoTogglesPlayback": "Klik op de video om afspelen/pauzeren te wisselen.",
|
||||
"clickVideoTogglesPlaybackDescription": "Als deze optie is ingeschakeld, wordt de video afgespeeld of gepauzeerd wanneer je op de videospeler klikt. Anders worden bij een klik de afspeelbedieningen weergegeven of verborgen.",
|
||||
"videoPlayerControls": "Videospeler bediening",
|
||||
"keyboardShortcuts": "Toetsenbord sneltoetsen",
|
||||
"keyboardShortcutsDescription": "Pas toetsenbord sneltoetsen aan",
|
||||
@@ -149,7 +167,9 @@
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Voer maximaal volume in (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Toon op Discord wat je aan het kijken bent"
|
||||
"discordRichPresenceDescription": "Toon op Discord wat je aan het kijken bent",
|
||||
"matchContentFrameRate": "Inhoudsframesnelheid afstemmen",
|
||||
"matchContentFrameRateDescription": "Pas de schermverversingssnelheid aan op de video-inhoud, vermindert haperingen en bespaart batterij"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Zoek films, series, muziek...",
|
||||
@@ -159,7 +179,26 @@
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Stel sneltoets in voor ${actionName}",
|
||||
"clearShortcut": "Wis sneltoets"
|
||||
"clearShortcut": "Wis sneltoets",
|
||||
"actions": {
|
||||
"playPause": "Afspelen/Pauzeren",
|
||||
"volumeUp": "Volume omhoog",
|
||||
"volumeDown": "Volume omlaag",
|
||||
"seekForward": "Vooruitspoelen (${seconds}s)",
|
||||
"seekBackward": "Terugspoelen (${seconds}s)",
|
||||
"fullscreenToggle": "Volledig scherm",
|
||||
"muteToggle": "Dempen",
|
||||
"subtitleToggle": "Ondertiteling",
|
||||
"audioTrackNext": "Volgende audiotrack",
|
||||
"subtitleTrackNext": "Volgende ondertiteltrack",
|
||||
"chapterNext": "Volgend hoofdstuk",
|
||||
"chapterPrevious": "Vorig hoofdstuk",
|
||||
"speedIncrease": "Snelheid verhogen",
|
||||
"speedDecrease": "Snelheid verlagen",
|
||||
"speedReset": "Snelheid resetten",
|
||||
"subSeekNext": "Naar volgende ondertitel",
|
||||
"subSeekPrev": "Naar vorige ondertitel"
|
||||
}
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "Voer PIN in",
|
||||
@@ -233,6 +272,8 @@
|
||||
"timerActive": "Timer actief",
|
||||
"playbackWillPauseIn": "Afspelen wordt gepauzeerd over ${duration}",
|
||||
"sleepTimerCompleted": "Slaaptimer voltooid - afspelen gepauzeerd",
|
||||
"autoPlayNext": "Automatisch volgende afspelen",
|
||||
"playNext": "Volgende afspelen",
|
||||
"playButton": "Afspelen",
|
||||
"pauseButton": "Pauzeren",
|
||||
"seekBackwardButton": "Terugspoelen ${seconds} seconden",
|
||||
@@ -248,6 +289,7 @@
|
||||
"subtitlesButton": "Ondertitels",
|
||||
"chaptersButton": "Hoofdstukken",
|
||||
"versionsButton": "Videoversies",
|
||||
"pipButton": "Beeld-in-beeld modus",
|
||||
"aspectRatioButton": "Beeldverhouding",
|
||||
"fullscreenButton": "Volledig scherm activeren",
|
||||
"exitFullscreenButton": "Volledig scherm verlaten",
|
||||
@@ -255,7 +297,15 @@
|
||||
"rotationLockButton": "Rotatievergrendeling",
|
||||
"timelineSlider": "Videotijdlijn",
|
||||
"volumeSlider": "Volumeniveau",
|
||||
"backButton": "Terug"
|
||||
"backButton": "Terug",
|
||||
"pipFailed": "Beeld-in-beeld kon niet worden gestart",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Vereist Android 8.0 of nieuwer",
|
||||
"permissionDisabled": "Beeld-in-beeld toestemming is uitgeschakeld. Schakel deze in via Instellingen > Apps > Plezy > Beeld-in-beeld",
|
||||
"notSupported": "Dit apparaat ondersteunt geen beeld-in-beeld modus",
|
||||
"failed": "Beeld-in-beeld kon niet worden gestart",
|
||||
"unknown": "Er is een fout opgetreden: ${error}"
|
||||
}
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "Beheerder",
|
||||
@@ -293,7 +343,8 @@
|
||||
"noItemsAvailable": "Geen items beschikbaar",
|
||||
"failedToCreatePlayQueue": "Kan afspeelwachtrij niet maken",
|
||||
"failedToCreatePlayQueueNoItems": "Kan afspeelwachtrij niet maken - geen items",
|
||||
"failedPlayback": "Afspelen van ${action} mislukt: ${error}"
|
||||
"failedPlayback": "Afspelen van ${action} mislukt: ${error}",
|
||||
"switchingToCompatiblePlayer": "Overschakelen naar compatibele speler..."
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "Opmaak opties",
|
||||
@@ -572,6 +623,7 @@
|
||||
"codeMustBe8Chars": "Sessiecode moet 8 tekens zijn",
|
||||
"joinInstructions": "Voer de sessiecode in die door de host is gedeeld om deel te nemen aan hun kijksessie.",
|
||||
"failedToCreate": "Sessie maken mislukt",
|
||||
"failedToJoin": "Sessie deelnemen mislukt"
|
||||
"failedToJoin": "Sessie deelnemen mislukt",
|
||||
"sessionCodeCopied": "Sessiecode gekopieerd naar klembord"
|
||||
}
|
||||
}
|
||||
+177
-9749
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -60,7 +60,13 @@
|
||||
"appearance": "Utseende",
|
||||
"videoPlayback": "Videouppspelning",
|
||||
"advanced": "Avancerat",
|
||||
"useSeasonPostersDescription": "Visa säsongsaffisch istället för serieaffisch för avsnitt",
|
||||
"episodePosterMode": "Avsnittsaffisch-stil",
|
||||
"seriesPoster": "Serieaffisch",
|
||||
"seriesPosterDescription": "Visa seriens affisch för alla avsnitt",
|
||||
"seasonPoster": "Säsongsaffisch",
|
||||
"seasonPosterDescription": "Visa säsongens affisch för avsnitt",
|
||||
"episodeThumbnail": "Avsnittsminiatyr",
|
||||
"episodeThumbnailDescription": "Visa 16:9 skärmbild från avsnittet",
|
||||
"showHeroSectionDescription": "Visa utvalda innehållskarusell på startsidan",
|
||||
"secondsLabel": "Sekunder",
|
||||
"minutesLabel": "Minuter",
|
||||
@@ -83,8 +89,18 @@
|
||||
"gridViewDescription": "Visa objekt i rutnätslayout",
|
||||
"listView": "Lista",
|
||||
"listViewDescription": "Visa objekt i listlayout",
|
||||
"useSeasonPosters": "Använd säsongsaffischer",
|
||||
"showHeroSection": "Visa hjältesektion",
|
||||
"useGlobalHubs": "Använd Plex hem-layout",
|
||||
"useGlobalHubsDescription": "Visar startsidans hubbar som den officiella Plex-klienten. När av visas rekommendationer per bibliotek istället.",
|
||||
"showServerNameOnHubs": "Visa servernamn på hubbar",
|
||||
"showServerNameOnHubsDescription": "Visa alltid servernamnet i hubbtitlar. När av visas endast för duplicerade hubbnamn.",
|
||||
"alwaysKeepSidebarOpen": "Håll sidofältet alltid öppet",
|
||||
"alwaysKeepSidebarOpenDescription": "Sidofältet förblir expanderat och innehållsytan anpassas",
|
||||
"playerBackend": "Spelarmotor",
|
||||
"exoPlayer": "ExoPlayer (Rekommenderad)",
|
||||
"exoPlayerDescription": "Android-nativ spelare med bättre hårdvarustöd",
|
||||
"mpv": "MPV",
|
||||
"mpvDescription": "Avancerad spelare med fler funktioner och ASS-undertextstöd",
|
||||
"hardwareDecoding": "Hårdvaruavkodning",
|
||||
"hardwareDecodingDescription": "Använd hårdvaruacceleration när tillgängligt",
|
||||
"bufferSize": "Bufferstorlek",
|
||||
@@ -98,6 +114,8 @@
|
||||
"minutesUnit": "${minutes} minuter",
|
||||
"rememberTrackSelections": "Kom ihåg spårval per serie/film",
|
||||
"rememberTrackSelectionsDescription": "Spara automatiskt ljud- och undertextspråkpreferenser när du ändrar spår under uppspelning",
|
||||
"clickVideoTogglesPlayback": "Klicka på videon för att växla mellan spela upp och pausa.",
|
||||
"clickVideoTogglesPlaybackDescription": "Om detta är aktiverat kommer ett klick på videospelaren att starta eller pausa videon. Annars visas eller döljs uppspelningskontrollerna när du klickar.",
|
||||
"videoPlayerControls": "Videospelar-kontroller",
|
||||
"keyboardShortcuts": "Tangentbordsgenvägar",
|
||||
"keyboardShortcutsDescription": "Anpassa tangentbordsgenvägar",
|
||||
@@ -149,7 +167,9 @@
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Ange maximal volym (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Visa vad du tittar på i Discord"
|
||||
"discordRichPresenceDescription": "Visa vad du tittar på i Discord",
|
||||
"matchContentFrameRate": "Matcha innehållets bildfrekvens",
|
||||
"matchContentFrameRateDescription": "Justera skärmens uppdateringsfrekvens för att matcha videoinnehållet, minskar hackighet och sparar batteri"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Sök filmer, serier, musik...",
|
||||
@@ -159,7 +179,26 @@
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Sätt genväg för ${actionName}",
|
||||
"clearShortcut": "Rensa genväg"
|
||||
"clearShortcut": "Rensa genväg",
|
||||
"actions": {
|
||||
"playPause": "Spela/Pausa",
|
||||
"volumeUp": "Höj volym",
|
||||
"volumeDown": "Sänk volym",
|
||||
"seekForward": "Spola framåt (${seconds}s)",
|
||||
"seekBackward": "Spola bakåt (${seconds}s)",
|
||||
"fullscreenToggle": "Växla helskärm",
|
||||
"muteToggle": "Växla ljud av",
|
||||
"subtitleToggle": "Växla undertexter",
|
||||
"audioTrackNext": "Nästa ljudspår",
|
||||
"subtitleTrackNext": "Nästa undertextspår",
|
||||
"chapterNext": "Nästa kapitel",
|
||||
"chapterPrevious": "Föregående kapitel",
|
||||
"speedIncrease": "Öka hastighet",
|
||||
"speedDecrease": "Minska hastighet",
|
||||
"speedReset": "Återställ hastighet",
|
||||
"subSeekNext": "Hoppa till nästa undertext",
|
||||
"subSeekPrev": "Hoppa till föregående undertext"
|
||||
}
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "Ange PIN",
|
||||
@@ -233,6 +272,8 @@
|
||||
"timerActive": "Timer aktiv",
|
||||
"playbackWillPauseIn": "Uppspelningen pausas om ${duration}",
|
||||
"sleepTimerCompleted": "Sovtimer slutförd - uppspelning pausad",
|
||||
"autoPlayNext": "Spela nästa automatiskt",
|
||||
"playNext": "Spela nästa",
|
||||
"playButton": "Spela",
|
||||
"pauseButton": "Pausa",
|
||||
"seekBackwardButton": "Spola bakåt ${seconds} sekunder",
|
||||
@@ -248,6 +289,7 @@
|
||||
"subtitlesButton": "Undertexter",
|
||||
"chaptersButton": "Kapitel",
|
||||
"versionsButton": "Videoversioner",
|
||||
"pipButton": "Bild-i-bild läge",
|
||||
"aspectRatioButton": "Bildförhållande",
|
||||
"fullscreenButton": "Aktivera helskärm",
|
||||
"exitFullscreenButton": "Avsluta helskärm",
|
||||
@@ -255,7 +297,15 @@
|
||||
"rotationLockButton": "Rotationslås",
|
||||
"timelineSlider": "Videotidslinje",
|
||||
"volumeSlider": "Volymnivå",
|
||||
"backButton": "Tillbaka"
|
||||
"backButton": "Tillbaka",
|
||||
"pipFailed": "Bild-i-bild kunde inte starta",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Kräver Android 8.0 eller nyare",
|
||||
"permissionDisabled": "Bild-i-bild-behörighet är inaktiverad. Aktivera den i Inställningar > Appar > Plezy > Bild-i-bild",
|
||||
"notSupported": "Denna enhet stöder inte bild-i-bild-läge",
|
||||
"failed": "Bild-i-bild kunde inte starta",
|
||||
"unknown": "Ett fel uppstod: ${error}"
|
||||
}
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "Admin",
|
||||
@@ -293,7 +343,8 @@
|
||||
"noItemsAvailable": "Inga objekt tillgängliga",
|
||||
"failedToCreatePlayQueue": "Det gick inte att skapa uppspelningskö",
|
||||
"failedToCreatePlayQueueNoItems": "Det gick inte att skapa uppspelningskö – inga objekt",
|
||||
"failedPlayback": "Kunde inte ${action}: ${error}"
|
||||
"failedPlayback": "Kunde inte ${action}: ${error}",
|
||||
"switchingToCompatiblePlayer": "Byter till kompatibel spelare..."
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "Stilalternativ",
|
||||
@@ -572,6 +623,7 @@
|
||||
"codeMustBe8Chars": "Sessionskod måste vara 8 tecken",
|
||||
"joinInstructions": "Ange sessionskoden som delats av värden för att gå med i deras tittarsession.",
|
||||
"failedToCreate": "Det gick inte att skapa session",
|
||||
"failedToJoin": "Det gick inte att gå med i session"
|
||||
"failedToJoin": "Det gick inte att gå med i session",
|
||||
"sessionCodeCopied": "Sessionskod kopierad till urklipp"
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,13 @@
|
||||
"appearance": "外观",
|
||||
"videoPlayback": "视频播放",
|
||||
"advanced": "高级",
|
||||
"useSeasonPostersDescription": "为剧集显示季海报而非剧集海报",
|
||||
"episodePosterMode": "剧集海报样式",
|
||||
"seriesPoster": "剧集海报",
|
||||
"seriesPosterDescription": "为所有剧集显示剧集海报",
|
||||
"seasonPoster": "季海报",
|
||||
"seasonPosterDescription": "为剧集显示特定季的海报",
|
||||
"episodeThumbnail": "剧集缩略图",
|
||||
"episodeThumbnailDescription": "显示16:9剧集截图缩略图",
|
||||
"showHeroSectionDescription": "在主屏幕上显示精选内容轮播区",
|
||||
"secondsLabel": "秒",
|
||||
"minutesLabel": "分钟",
|
||||
@@ -83,8 +89,18 @@
|
||||
"gridViewDescription": "以网格布局显示项目",
|
||||
"listView": "列表视图",
|
||||
"listViewDescription": "以列表布局显示项目",
|
||||
"useSeasonPosters": "使用季海报",
|
||||
"showHeroSection": "显示主要精选区",
|
||||
"useGlobalHubs": "使用 Plex 主页布局",
|
||||
"useGlobalHubsDescription": "显示与官方 Plex 客户端相同的主页推荐。关闭时将显示按媒体库分类的推荐。",
|
||||
"showServerNameOnHubs": "在推荐栏显示服务器名称",
|
||||
"showServerNameOnHubsDescription": "始终在推荐栏标题中显示服务器名称。关闭时仅在推荐栏名称重复时显示。",
|
||||
"alwaysKeepSidebarOpen": "始终保持侧边栏展开",
|
||||
"alwaysKeepSidebarOpenDescription": "侧边栏保持展开状态,内容区域自动调整",
|
||||
"playerBackend": "播放器引擎",
|
||||
"exoPlayer": "ExoPlayer(推荐)",
|
||||
"exoPlayerDescription": "Android 原生播放器,硬件支持更好",
|
||||
"mpv": "MPV",
|
||||
"mpvDescription": "功能更多的高级播放器,支持 ASS 字幕",
|
||||
"hardwareDecoding": "硬件解码",
|
||||
"hardwareDecodingDescription": "如果可用,使用硬件加速",
|
||||
"bufferSize": "缓冲区大小",
|
||||
@@ -98,6 +114,8 @@
|
||||
"minutesUnit": "${minutes} 分钟",
|
||||
"rememberTrackSelections": "记住每个剧集/电影的音轨选择",
|
||||
"rememberTrackSelectionsDescription": "在播放过程中更改音轨时自动保存音频和字幕语言偏好",
|
||||
"clickVideoTogglesPlayback": "点击视频可切换播放/暂停",
|
||||
"clickVideoTogglesPlaybackDescription": "如果启用此选项,点击视频播放器将播放或暂停视频。否则,点击将显示或隐藏播放控件",
|
||||
"videoPlayerControls": "视频播放器控制",
|
||||
"keyboardShortcuts": "键盘快捷键",
|
||||
"keyboardShortcutsDescription": "自定义键盘快捷键",
|
||||
@@ -149,7 +167,9 @@
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "输入最大音量 (100-300)",
|
||||
"discordRichPresence": "Discord 动态状态",
|
||||
"discordRichPresenceDescription": "在 Discord 上显示您正在观看的内容"
|
||||
"discordRichPresenceDescription": "在 Discord 上显示您正在观看的内容",
|
||||
"matchContentFrameRate": "匹配内容帧率",
|
||||
"matchContentFrameRateDescription": "调整显示刷新率以匹配视频内容,减少画面抖动并节省电量"
|
||||
},
|
||||
"search": {
|
||||
"hint": "搜索电影、系列、音乐...",
|
||||
@@ -159,7 +179,26 @@
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "为 ${actionName} 设置快捷键",
|
||||
"clearShortcut": "清除快捷键"
|
||||
"clearShortcut": "清除快捷键",
|
||||
"actions": {
|
||||
"playPause": "播放/暂停",
|
||||
"volumeUp": "增大音量",
|
||||
"volumeDown": "减小音量",
|
||||
"seekForward": "快进 (${seconds}秒)",
|
||||
"seekBackward": "快退 (${seconds}秒)",
|
||||
"fullscreenToggle": "切换全屏",
|
||||
"muteToggle": "切换静音",
|
||||
"subtitleToggle": "切换字幕",
|
||||
"audioTrackNext": "下一音轨",
|
||||
"subtitleTrackNext": "下一字幕轨",
|
||||
"chapterNext": "下一章节",
|
||||
"chapterPrevious": "上一章节",
|
||||
"speedIncrease": "加速",
|
||||
"speedDecrease": "减速",
|
||||
"speedReset": "重置速度",
|
||||
"subSeekNext": "跳转到下一字幕",
|
||||
"subSeekPrev": "跳转到上一字幕"
|
||||
}
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "输入 PIN",
|
||||
@@ -233,6 +272,8 @@
|
||||
"timerActive": "定时器已激活",
|
||||
"playbackWillPauseIn": "播放将在 ${duration} 后暂停",
|
||||
"sleepTimerCompleted": "睡眠定时器已完成 - 播放已暂停",
|
||||
"autoPlayNext": "自动播放下一集",
|
||||
"playNext": "播放下一集",
|
||||
"playButton": "播放",
|
||||
"pauseButton": "暂停",
|
||||
"seekBackwardButton": "后退 ${seconds} 秒",
|
||||
@@ -248,6 +289,7 @@
|
||||
"subtitlesButton": "字幕",
|
||||
"chaptersButton": "章节",
|
||||
"versionsButton": "视频版本",
|
||||
"pipButton": "画中画模式",
|
||||
"aspectRatioButton": "宽高比",
|
||||
"fullscreenButton": "进入全屏",
|
||||
"exitFullscreenButton": "退出全屏",
|
||||
@@ -255,7 +297,15 @@
|
||||
"rotationLockButton": "旋转锁定",
|
||||
"timelineSlider": "视频时间轴",
|
||||
"volumeSlider": "音量调节",
|
||||
"backButton": "返回"
|
||||
"backButton": "返回",
|
||||
"pipFailed": "画中画启动失败",
|
||||
"pipErrors": {
|
||||
"androidVersion": "需要 Android 8.0 或更高版本",
|
||||
"permissionDisabled": "画中画权限已禁用。请在设置 > 应用 > Plezy > 画中画中启用",
|
||||
"notSupported": "此设备不支持画中画模式",
|
||||
"failed": "画中画启动失败",
|
||||
"unknown": "发生错误:${error}"
|
||||
}
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "管理员",
|
||||
@@ -293,7 +343,8 @@
|
||||
"noItemsAvailable": "没有可用的项目",
|
||||
"failedToCreatePlayQueue": "创建播放队列失败",
|
||||
"failedToCreatePlayQueueNoItems": "创建播放队列失败 - 没有项目",
|
||||
"failedPlayback": "无法${action}: ${error}"
|
||||
"failedPlayback": "无法${action}: ${error}",
|
||||
"switchingToCompatiblePlayer": "正在切换到兼容的播放器..."
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "样式选项",
|
||||
@@ -572,6 +623,7 @@
|
||||
"codeMustBe8Chars": "会话代码必须是8个字符",
|
||||
"joinInstructions": "输入主持人分享的会话代码以加入他们的观看会话。",
|
||||
"failedToCreate": "创建会话失败",
|
||||
"failedToJoin": "加入会话失败"
|
||||
"failedToJoin": "加入会话失败",
|
||||
"sessionCodeCopied": "会话代码已复制到剪贴板"
|
||||
}
|
||||
}
|
||||
+34
-78
@@ -1,14 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'screens/main_screen.dart';
|
||||
import 'screens/auth_screen.dart';
|
||||
import 'services/storage_service.dart';
|
||||
import 'services/macos_titlebar_service.dart';
|
||||
import 'services/fullscreen_state_manager.dart';
|
||||
import 'services/update_service.dart';
|
||||
import 'services/settings_service.dart';
|
||||
import 'utils/platform_detector.dart';
|
||||
import 'services/discord_rpc_service.dart';
|
||||
@@ -20,6 +19,7 @@ import 'providers/server_state_provider.dart';
|
||||
import 'providers/theme_provider.dart';
|
||||
import 'providers/settings_provider.dart';
|
||||
import 'providers/hidden_libraries_provider.dart';
|
||||
import 'providers/libraries_provider.dart';
|
||||
import 'providers/playback_state_provider.dart';
|
||||
import 'providers/download_provider.dart';
|
||||
import 'providers/offline_mode_provider.dart';
|
||||
@@ -31,6 +31,7 @@ import 'services/data_aggregation_service.dart';
|
||||
import 'services/in_app_review_service.dart';
|
||||
import 'services/server_registry.dart';
|
||||
import 'services/download_manager_service.dart';
|
||||
import 'services/pip_service.dart';
|
||||
import 'services/download_storage_service.dart';
|
||||
import 'services/plex_api_cache.dart';
|
||||
import 'database/app_database.dart';
|
||||
@@ -39,9 +40,28 @@ import 'utils/orientation_helper.dart';
|
||||
import 'utils/language_codes.dart';
|
||||
import 'i18n/strings.g.dart';
|
||||
import 'focus/input_mode_tracker.dart';
|
||||
import 'package:intl/date_symbol_data_local.dart';
|
||||
|
||||
// Workaround for Flutter bug #177992: iPadOS 26.1+ misinterprets fake touch events
|
||||
// at (0,0) as barrier taps, causing modals to dismiss immediately.
|
||||
// Remove when Flutter PR #179643 is merged.
|
||||
bool _zeroOffsetPointerGuardInstalled = false;
|
||||
|
||||
void _installZeroOffsetPointerGuard() {
|
||||
if (_zeroOffsetPointerGuardInstalled) return;
|
||||
GestureBinding.instance.pointerRouter.addGlobalRoute(_absorbZeroOffsetPointerEvent);
|
||||
_zeroOffsetPointerGuardInstalled = true;
|
||||
}
|
||||
|
||||
void _absorbZeroOffsetPointerEvent(PointerEvent event) {
|
||||
if (event.position == Offset.zero) {
|
||||
GestureBinding.instance.cancelPointer(event.pointer);
|
||||
}
|
||||
}
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
_installZeroOffsetPointerGuard(); // Workaround for iPadOS 26.1+ modal dismissal bug
|
||||
|
||||
// Initialize settings first to get saved locale
|
||||
final settings = await SettingsService.getInstance();
|
||||
@@ -50,6 +70,9 @@ void main() async {
|
||||
// Initialize localization with saved locale
|
||||
LocaleSettings.setLocale(savedLocale);
|
||||
|
||||
// Needed for formatting dates in different locales
|
||||
await initializeDateFormatting(savedLocale.languageCode, null);
|
||||
|
||||
// Configure image cache for large libraries
|
||||
PaintingBinding.instance.imageCache.maximumSizeBytes = 200 << 20; // 200MB
|
||||
|
||||
@@ -61,9 +84,11 @@ void main() async {
|
||||
futures.add(windowManager.ensureInitialized());
|
||||
}
|
||||
|
||||
// Initialize TV detection for Android
|
||||
// Initialize TV detection and PiP service for Android
|
||||
if (Platform.isAndroid) {
|
||||
futures.add(TvDetectionService.getInstance().then((_) {}));
|
||||
// Initialize PiP service to listen for PiP state changes
|
||||
PipService();
|
||||
}
|
||||
|
||||
// Configure macOS window with custom titlebar (depends on window manager)
|
||||
@@ -221,6 +246,7 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
|
||||
ChangeNotifierProvider(create: (context) => ThemeProvider()),
|
||||
ChangeNotifierProvider(create: (context) => SettingsProvider(), lazy: true),
|
||||
ChangeNotifierProvider(create: (context) => HiddenLibrariesProvider(), lazy: true),
|
||||
ChangeNotifierProvider(create: (context) => LibrariesProvider()),
|
||||
ChangeNotifierProvider(create: (context) => PlaybackStateProvider()),
|
||||
ChangeNotifierProvider(create: (context) => WatchTogetherProvider()),
|
||||
],
|
||||
@@ -283,78 +309,6 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
_loadSavedCredentials();
|
||||
}
|
||||
|
||||
Future<void> _checkForUpdatesOnStartup() async {
|
||||
// Delay slightly to allow UI to settle
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
try {
|
||||
final updateInfo = await UpdateService.checkForUpdatesOnStartup();
|
||||
|
||||
if (updateInfo != null && updateInfo['hasUpdate'] == true && mounted) {
|
||||
_showUpdateDialog(updateInfo);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Error checking for updates', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
void _showUpdateDialog(Map<String, dynamic> updateInfo) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext dialogContext) {
|
||||
return AlertDialog(
|
||||
title: Text(t.update.available),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
t.update.versionAvailable(version: updateInfo['latestVersion']),
|
||||
style: Theme.of(dialogContext).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
t.update.currentVersion(version: updateInfo['currentVersion']),
|
||||
style: Theme.of(dialogContext).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(dialogContext);
|
||||
},
|
||||
child: Text(t.common.later),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
await UpdateService.skipVersion(updateInfo['latestVersion']);
|
||||
if (dialogContext.mounted) {
|
||||
Navigator.pop(dialogContext);
|
||||
}
|
||||
},
|
||||
child: Text(t.update.skipVersion),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final url = Uri.parse(updateInfo['releaseUrl']);
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
if (dialogContext.mounted) {
|
||||
Navigator.pop(dialogContext);
|
||||
}
|
||||
},
|
||||
child: Text(t.update.viewRelease),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _loadSavedCredentials() async {
|
||||
final storage = await StorageService.getInstance();
|
||||
final registry = ServerRegistry(storage);
|
||||
@@ -405,6 +359,11 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
appLogger.i('Successfully connected to $connectedCount servers');
|
||||
|
||||
if (mounted) {
|
||||
// Initialize and load libraries
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
librariesProvider.initialize(multiServerProvider.aggregationService);
|
||||
await librariesProvider.loadLibraries();
|
||||
|
||||
// Now that Plex clients are available, trigger initial watch sync
|
||||
context.read<OfflineWatchSyncService>().onServersConnected();
|
||||
|
||||
@@ -413,9 +372,6 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
final firstClient = multiServerProvider.serverManager.onlineClients.values.first;
|
||||
|
||||
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => MainScreen(client: firstClient)));
|
||||
|
||||
// Check for updates in background after navigation
|
||||
_checkForUpdatesOnStartup();
|
||||
}
|
||||
} else {
|
||||
// All connections failed - navigate to offline mode
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
|
||||
/// Mixin for screens that need to react to watch state changes.
|
||||
///
|
||||
/// Provides automatic subscription management and filtering based on
|
||||
/// which items the screen cares about.
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// class _MyScreenState extends State<MyScreen> with WatchStateAware {
|
||||
/// List<PlexMetadata> _items = [];
|
||||
///
|
||||
/// @override
|
||||
/// Set<String>? get watchedRatingKeys =>
|
||||
/// _items.map((e) => e.ratingKey).toSet();
|
||||
///
|
||||
/// @override
|
||||
/// void onWatchStateChanged(WatchStateEvent event) {
|
||||
/// // Refresh affected item
|
||||
/// _refreshItem(event.ratingKey);
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
mixin WatchStateAware<T extends StatefulWidget> on State<T> {
|
||||
StreamSubscription<WatchStateEvent>? _watchStateSubscription;
|
||||
|
||||
/// Override to specify which ratingKeys this screen cares about.
|
||||
///
|
||||
/// Return null to receive ALL events (not recommended for performance).
|
||||
/// Return an empty set to receive no events.
|
||||
///
|
||||
/// The set should include:
|
||||
/// - Direct items displayed (e.g., episode ratingKeys in a season view)
|
||||
/// - Parent items that affect display (e.g., show ratingKey for on-deck)
|
||||
Set<String>? get watchedRatingKeys;
|
||||
|
||||
/// Called when a relevant watch state change occurs.
|
||||
///
|
||||
/// Only called if [watchedRatingKeys] is null or contains an affected key.
|
||||
void onWatchStateChanged(WatchStateEvent event);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_subscribeToWatchState();
|
||||
}
|
||||
|
||||
void _subscribeToWatchState() {
|
||||
_watchStateSubscription = WatchStateNotifier().stream.listen((event) {
|
||||
if (!mounted) return;
|
||||
|
||||
final keys = watchedRatingKeys;
|
||||
// If keys is null, receive all events
|
||||
// Otherwise, filter to events that affect our keys
|
||||
if (keys == null || event.affectsAnyOf(keys)) {
|
||||
onWatchStateChanged(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_watchStateSubscription?.cancel();
|
||||
_watchStateSubscription = null;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -30,11 +30,18 @@ class PlexHub {
|
||||
final metadataList = <PlexMetadata>[];
|
||||
|
||||
// Helper function to parse entries from a JSON list
|
||||
void parseEntries(List? entries) {
|
||||
void parseEntries(List? entries, {bool isDirectory = false}) {
|
||||
if (entries == null) return;
|
||||
for (final item in entries) {
|
||||
try {
|
||||
metadataList.add(PlexMetadata.fromJson(item));
|
||||
if (isDirectory && item is Map && !item.containsKey('type')) {
|
||||
// Directory items often represent shows but might miss the type field
|
||||
// Default to 'show' if it looks like a show (has leafCount or childCount)
|
||||
// or 'folder' as a safe default
|
||||
final String type = (item.containsKey('leafCount') || item.containsKey('childCount')) ? 'show' : 'folder';
|
||||
item['type'] = type;
|
||||
}
|
||||
metadataList.add(PlexMetadata.fromJson(item as Map<String, dynamic>));
|
||||
} catch (e) {
|
||||
// Skip items that fail to parse
|
||||
}
|
||||
@@ -43,7 +50,7 @@ class PlexHub {
|
||||
|
||||
// Hubs can contain either Metadata or Directory entries
|
||||
parseEntries(json['Metadata'] as List?);
|
||||
parseEntries(json['Directory'] as List?);
|
||||
parseEntries(json['Directory'] as List?, isDirectory: true);
|
||||
|
||||
return PlexHub(
|
||||
hubKey: json['key'] as String? ?? '',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
import '../services/settings_service.dart' show EpisodePosterMode;
|
||||
import 'mixins/multi_server_fields.dart';
|
||||
import 'plex_role.dart';
|
||||
|
||||
@@ -46,6 +47,7 @@ class PlexMetadata with MultiServerFields {
|
||||
final double? rating;
|
||||
final double? audienceRating;
|
||||
final int? year;
|
||||
final String? originallyAvailableAt; // Full release date (YYYY-MM-DD)
|
||||
final String? thumb;
|
||||
final String? art;
|
||||
final int? duration;
|
||||
@@ -119,6 +121,7 @@ class PlexMetadata with MultiServerFields {
|
||||
this.rating,
|
||||
this.audienceRating,
|
||||
this.year,
|
||||
this.originallyAvailableAt,
|
||||
this.thumb,
|
||||
this.art,
|
||||
this.duration,
|
||||
@@ -164,6 +167,7 @@ class PlexMetadata with MultiServerFields {
|
||||
double? rating,
|
||||
double? audienceRating,
|
||||
int? year,
|
||||
String? originallyAvailableAt,
|
||||
String? thumb,
|
||||
String? art,
|
||||
int? duration,
|
||||
@@ -207,6 +211,7 @@ class PlexMetadata with MultiServerFields {
|
||||
rating: rating ?? this.rating,
|
||||
audienceRating: audienceRating ?? this.audienceRating,
|
||||
year: year ?? this.year,
|
||||
originallyAvailableAt: originallyAvailableAt ?? this.originallyAvailableAt,
|
||||
thumb: thumb ?? this.thumb,
|
||||
art: art ?? this.art,
|
||||
duration: duration ?? this.duration,
|
||||
@@ -294,27 +299,62 @@ class PlexMetadata with MultiServerFields {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Helper to get the poster (show poster for episodes/seasons, thumb otherwise)
|
||||
// If useSeasonPoster is true, episodes will use season poster instead of series poster
|
||||
String? posterThumb({bool useSeasonPoster = false}) {
|
||||
/// Returns the appropriate image path based on episode poster mode.
|
||||
/// For episodes:
|
||||
/// - seriesPoster: grandparentThumb (series poster)
|
||||
/// - seasonPoster: parentThumb (season poster)
|
||||
/// - episodeThumbnail: thumb (16:9 episode still)
|
||||
/// For seasons: returns grandparentThumb (series poster), or art/thumb in mixed hub context
|
||||
/// For movies/shows/seasons in mixed hub context: returns art (16:9 background)
|
||||
/// For other types: returns thumb
|
||||
String? posterThumb({EpisodePosterMode mode = EpisodePosterMode.seriesPoster, bool mixedHubContext = false}) {
|
||||
final itemType = type.toLowerCase();
|
||||
|
||||
if (itemType == 'episode') {
|
||||
// If season poster is enabled and available, use it
|
||||
if (useSeasonPoster && parentThumb != null) {
|
||||
return parentThumb!;
|
||||
switch (mode) {
|
||||
case EpisodePosterMode.episodeThumbnail:
|
||||
return thumb; // 16:9 episode thumbnail
|
||||
case EpisodePosterMode.seasonPoster:
|
||||
return parentThumb ?? grandparentThumb ?? thumb;
|
||||
case EpisodePosterMode.seriesPoster:
|
||||
return grandparentThumb ?? thumb;
|
||||
}
|
||||
// Otherwise fall back to series poster, then item thumb
|
||||
} else if (itemType == 'season') {
|
||||
// In mixed hub with episode thumbnail mode, use art/thumb (16:9)
|
||||
if (mixedHubContext && mode == EpisodePosterMode.episodeThumbnail) {
|
||||
return art ?? thumb;
|
||||
}
|
||||
// Otherwise use series poster (2:3)
|
||||
if (grandparentThumb != null) {
|
||||
return grandparentThumb!;
|
||||
}
|
||||
} else if (itemType == 'season' && grandparentThumb != null) {
|
||||
// For seasons, always use series poster
|
||||
return grandparentThumb!;
|
||||
}
|
||||
|
||||
// For movies/shows in mixed hub context with episode thumbnail mode, use art (16:9)
|
||||
if (mixedHubContext && mode == EpisodePosterMode.episodeThumbnail && (itemType == 'movie' || itemType == 'show')) {
|
||||
return art ?? thumb;
|
||||
}
|
||||
|
||||
return thumb;
|
||||
}
|
||||
|
||||
/// Returns true if this item should use 16:9 aspect ratio.
|
||||
/// Episodes use 16:9 when in episodeThumbnail mode.
|
||||
/// Movies, shows, and seasons use 16:9 in mixed hub context with episodeThumbnail mode.
|
||||
bool usesWideAspectRatio(EpisodePosterMode mode, {bool mixedHubContext = false}) {
|
||||
final itemType = type.toLowerCase();
|
||||
if (itemType == 'episode' && mode == EpisodePosterMode.episodeThumbnail) {
|
||||
return true;
|
||||
}
|
||||
// Movies, shows, and seasons use 16:9 in mixed hubs with episode thumbnail mode
|
||||
if (mixedHubContext &&
|
||||
mode == EpisodePosterMode.episodeThumbnail &&
|
||||
(itemType == 'movie' || itemType == 'show' || itemType == 'season')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Helper to determine if content is watched
|
||||
bool get isWatched {
|
||||
// For series/seasons, check if all episodes are watched
|
||||
|
||||
@@ -18,6 +18,7 @@ PlexMetadata _$PlexMetadataFromJson(Map<String, dynamic> json) => PlexMetadata(
|
||||
rating: (json['rating'] as num?)?.toDouble(),
|
||||
audienceRating: (json['audienceRating'] as num?)?.toDouble(),
|
||||
year: (json['year'] as num?)?.toInt(),
|
||||
originallyAvailableAt: json['originallyAvailableAt'] as String?,
|
||||
thumb: json['thumb'] as String?,
|
||||
art: json['art'] as String?,
|
||||
duration: (json['duration'] as num?)?.toInt(),
|
||||
@@ -60,6 +61,7 @@ Map<String, dynamic> _$PlexMetadataToJson(PlexMetadata instance) => <String, dyn
|
||||
'rating': instance.rating,
|
||||
'audienceRating': instance.audienceRating,
|
||||
'year': instance.year,
|
||||
'originallyAvailableAt': instance.originallyAvailableAt,
|
||||
'thumb': instance.thumb,
|
||||
'art': instance.art,
|
||||
'duration': instance.duration,
|
||||
|
||||
@@ -13,7 +13,15 @@ class PlexVideoPlaybackData {
|
||||
/// Available media versions/qualities for this content
|
||||
final List<PlexMediaVersion> availableVersions;
|
||||
|
||||
PlexVideoPlaybackData({required this.videoUrl, required this.mediaInfo, required this.availableVersions});
|
||||
/// Markers for intro/credits skip functionality
|
||||
final List<PlexMarker> markers;
|
||||
|
||||
PlexVideoPlaybackData({
|
||||
required this.videoUrl,
|
||||
required this.mediaInfo,
|
||||
required this.availableVersions,
|
||||
this.markers = const [],
|
||||
});
|
||||
|
||||
/// Returns true if this playback data has a valid video URL
|
||||
bool get hasValidVideoUrl => videoUrl != null && videoUrl!.isNotEmpty;
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../player_native.dart';
|
||||
|
||||
/// Linux implementation of [Player].
|
||||
@@ -9,19 +7,6 @@ import '../player_native.dart';
|
||||
/// 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});
|
||||
}
|
||||
}
|
||||
|
||||
+66
-10
@@ -1,12 +1,15 @@
|
||||
import 'dart:io' show Platform;
|
||||
|
||||
import '../models.dart';
|
||||
import 'player_android.dart';
|
||||
import 'player_native.dart';
|
||||
import 'player_state.dart';
|
||||
import 'player_streams.dart';
|
||||
import 'platform/player_linux.dart';
|
||||
import 'platform/player_windows.dart';
|
||||
|
||||
export 'player_base.dart';
|
||||
|
||||
/// Abstract interface for the video player.
|
||||
///
|
||||
/// This interface defines all playback control methods, state access,
|
||||
@@ -47,6 +50,9 @@ abstract class Player {
|
||||
/// rendering is initialized. Returns null if not ready.
|
||||
int? get textureId;
|
||||
|
||||
/// The type of player backend being used (e.g., 'mpv', 'exoplayer').
|
||||
String get playerType;
|
||||
|
||||
// ============================================
|
||||
// Playback Control
|
||||
// ============================================
|
||||
@@ -163,13 +169,6 @@ abstract class Player {
|
||||
/// 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
|
||||
@@ -177,6 +176,49 @@ abstract class Player {
|
||||
/// On other platforms, this is a no-op.
|
||||
Future<void> updateFrame();
|
||||
|
||||
// ============================================
|
||||
// Frame Rate Matching (Android)
|
||||
// ============================================
|
||||
|
||||
/// Set the video frame rate for display refresh rate matching.
|
||||
///
|
||||
/// On Android, this hints the system to adjust the display refresh rate
|
||||
/// to match the video content's frame rate, reducing judder and saving
|
||||
/// battery on LTPO displays.
|
||||
///
|
||||
/// [fps] - The video frame rate (e.g., 23.976, 24, 30, 60).
|
||||
/// [durationMs] - The video duration in milliseconds.
|
||||
///
|
||||
/// On other platforms, this is a no-op.
|
||||
Future<void> setVideoFrameRate(double fps, int durationMs);
|
||||
|
||||
/// Clear the video frame rate hint and restore default display mode.
|
||||
///
|
||||
/// Call this when playback ends to restore the normal display refresh rate.
|
||||
/// On other platforms, this is a no-op.
|
||||
Future<void> clearVideoFrameRate();
|
||||
|
||||
// ============================================
|
||||
// Audio Focus (Android)
|
||||
// ============================================
|
||||
|
||||
/// Request audio focus before starting playback.
|
||||
///
|
||||
/// On Android, this notifies the system that the app wants to play audio,
|
||||
/// causing other media apps (Spotify, podcasts, etc.) to pause.
|
||||
///
|
||||
/// Returns true if audio focus was granted.
|
||||
/// On other platforms, this is a no-op and returns true.
|
||||
Future<bool> requestAudioFocus();
|
||||
|
||||
/// Abandon audio focus when playback stops.
|
||||
///
|
||||
/// On Android, this notifies the system that the app is done playing audio,
|
||||
/// allowing other apps to resume their playback.
|
||||
///
|
||||
/// On other platforms, this is a no-op.
|
||||
Future<void> abandonAudioFocus();
|
||||
|
||||
// ============================================
|
||||
// Lifecycle
|
||||
// ============================================
|
||||
@@ -193,11 +235,25 @@ abstract class Player {
|
||||
/// Creates a new player instance.
|
||||
///
|
||||
/// Returns a platform-specific implementation:
|
||||
/// - macOS/iOS/Android: [PlayerNative] using MPVKit/libmpv with texture rendering
|
||||
/// - macOS/iOS: [PlayerNative] using MPVKit/libmpv with Metal rendering
|
||||
/// - Android: [PlayerAndroid] using ExoPlayer (default) or [PlayerNative] using MPV (fallback)
|
||||
/// - 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) {
|
||||
///
|
||||
/// On Android, pass [useExoPlayer] to override the default:
|
||||
/// - true: Use ExoPlayer (default, better hardware support)
|
||||
/// - false: Use MPV (more features, ASS subtitle rendering)
|
||||
factory Player({bool? useExoPlayer}) {
|
||||
if (Platform.isAndroid) {
|
||||
// Default to ExoPlayer on Android, with MPV as fallback
|
||||
// The caller should pass useExoPlayer based on SettingsService.getUseExoPlayer()
|
||||
final useExo = useExoPlayer ?? true;
|
||||
if (useExo) {
|
||||
return PlayerAndroid(); // ExoPlayer (default)
|
||||
}
|
||||
return PlayerNative(); // MPV fallback
|
||||
}
|
||||
if (Platform.isMacOS || Platform.isIOS) {
|
||||
return PlayerNative();
|
||||
}
|
||||
if (Platform.isWindows) {
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../models.dart';
|
||||
import 'player_base.dart';
|
||||
|
||||
/// Android implementation of [Player] using ExoPlayer.
|
||||
/// Provides hardware-accelerated playback with ASS subtitle support via libass-android.
|
||||
class PlayerAndroid extends PlayerBase {
|
||||
static const _methodChannel = MethodChannel('com.plezy/exo_player');
|
||||
static const _eventChannel = EventChannel('com.plezy/exo_player/events');
|
||||
|
||||
@override
|
||||
MethodChannel get methodChannel => _methodChannel;
|
||||
|
||||
@override
|
||||
EventChannel get eventChannel => _eventChannel;
|
||||
|
||||
@override
|
||||
String get logPrefix => 'ExoPlayer';
|
||||
|
||||
@override
|
||||
String get playerType => 'exoplayer';
|
||||
|
||||
// ============================================
|
||||
// Platform-Specific Event Handling
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
void handlePlayerEvent(String name, Map? data) {
|
||||
// Handle Android-specific events
|
||||
if (name == 'backend-switched') {
|
||||
// Native player switched from ExoPlayer to MPV due to unsupported format
|
||||
backendSwitchedController.add(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Delegate to base class for common events
|
||||
super.handlePlayerEvent(name, data);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Initialization
|
||||
// ============================================
|
||||
|
||||
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 ExoPlayer');
|
||||
}
|
||||
} catch (e) {
|
||||
errorController.add('Initialization failed: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Playback Control
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<void> open(Media media, {bool play = true}) async {
|
||||
checkDisposed();
|
||||
await _ensureInitialized();
|
||||
|
||||
// Show the video layer
|
||||
await setVisible(true);
|
||||
|
||||
await methodChannel.invokeMethod('open', {
|
||||
'uri': media.uri,
|
||||
'headers': media.headers,
|
||||
'startPositionMs': media.start?.inMilliseconds ?? 0,
|
||||
'autoPlay': play,
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> play() async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('play');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pause() async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('pause');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stop() async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('stop');
|
||||
await setVisible(false);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> seek(Duration position) async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('seek', {'positionMs': position.inMilliseconds});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Track Selection
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<void> selectAudioTrack(AudioTrack track) async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('selectAudioTrack', {'trackId': track.id});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> selectSubtitleTrack(SubtitleTrack track) async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('selectSubtitleTrack', {'trackId': track.id});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> addSubtitleTrack({required String uri, String? title, String? language, bool select = false}) async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('addSubtitleTrack', {
|
||||
'uri': uri,
|
||||
'title': title,
|
||||
'language': language,
|
||||
'select': select,
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Volume and Rate
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<void> setVolume(double volume) async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('setVolume', {'volume': volume});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setRate(double rate) async {
|
||||
checkDisposed();
|
||||
await methodChannel.invokeMethod('setRate', {'rate': rate});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// MPV Properties (Compatibility Layer)
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<void> setProperty(String name, String value) async {
|
||||
checkDisposed();
|
||||
// ExoPlayer doesn't use MPV properties, but we handle common ones
|
||||
switch (name) {
|
||||
case 'pause':
|
||||
if (value == 'yes') {
|
||||
await pause();
|
||||
} else {
|
||||
await play();
|
||||
}
|
||||
break;
|
||||
case 'volume':
|
||||
await setVolume(double.tryParse(value) ?? 100);
|
||||
break;
|
||||
case 'speed':
|
||||
await setRate(double.tryParse(value) ?? 1.0);
|
||||
break;
|
||||
// Other properties are no-ops for ExoPlayer
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> getProperty(String name) async {
|
||||
checkDisposed();
|
||||
// Return state-based values for common properties
|
||||
switch (name) {
|
||||
case 'pause':
|
||||
return state.playing ? 'no' : 'yes';
|
||||
case 'volume':
|
||||
return state.volume.toString();
|
||||
case 'speed':
|
||||
return state.rate.toString();
|
||||
case 'time-pos':
|
||||
return (state.position.inMilliseconds / 1000.0).toString();
|
||||
case 'duration':
|
||||
return (state.duration.inMilliseconds / 1000.0).toString();
|
||||
// Video dimensions - query from ExoPlayer stats
|
||||
case 'width':
|
||||
case 'dwidth':
|
||||
final stats = await getStats();
|
||||
final width = stats['videoWidth'];
|
||||
return width?.toString();
|
||||
case 'height':
|
||||
case 'dheight':
|
||||
final stats = await getStats();
|
||||
final height = stats['videoHeight'];
|
||||
return height?.toString();
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all playback stats from ExoPlayer.
|
||||
/// Returns a map with video/audio codec info, buffer state, and performance metrics.
|
||||
Future<Map<String, dynamic>> getStats() async {
|
||||
checkDisposed();
|
||||
try {
|
||||
final result = await methodChannel.invokeMethod<Map>('getStats');
|
||||
return Map<String, dynamic>.from(result ?? {});
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current player type ('exoplayer' or 'mpv' if fallback is active).
|
||||
Future<String> getPlayerType() async {
|
||||
checkDisposed();
|
||||
try {
|
||||
final result = await methodChannel.invokeMethod<String>('getPlayerType');
|
||||
return result ?? 'unknown';
|
||||
} catch (e) {
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> command(List<String> args) async {
|
||||
checkDisposed();
|
||||
// Handle MPV commands by translating to ExoPlayer equivalents
|
||||
if (args.isEmpty) return;
|
||||
|
||||
switch (args[0]) {
|
||||
case 'loadfile':
|
||||
if (args.length > 1) {
|
||||
await open(Media(args[1]));
|
||||
}
|
||||
break;
|
||||
case 'seek':
|
||||
if (args.length > 1) {
|
||||
final seconds = double.tryParse(args[1]) ?? 0;
|
||||
final mode = args.length > 2 ? args[2] : 'relative';
|
||||
if (mode == 'absolute') {
|
||||
await seek(Duration(milliseconds: (seconds * 1000).toInt()));
|
||||
} else {
|
||||
final newPos = state.position + Duration(milliseconds: (seconds * 1000).toInt());
|
||||
await seek(newPos);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'stop':
|
||||
await stop();
|
||||
break;
|
||||
case 'sub-add':
|
||||
if (args.length > 1) {
|
||||
final select = args.length > 2 && args[2] == 'select';
|
||||
await addSubtitleTrack(uri: args[1], select: select);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Frame Rate Matching
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<void> setVideoFrameRate(double fps, int durationMs) async {
|
||||
checkDisposed();
|
||||
if (!initialized) return;
|
||||
|
||||
await methodChannel.invokeMethod('setVideoFrameRate', {'fps': fps, 'duration': durationMs});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearVideoFrameRate() async {
|
||||
checkDisposed();
|
||||
if (!initialized) return;
|
||||
|
||||
await methodChannel.invokeMethod('clearVideoFrameRate');
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Audio Focus
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<bool> requestAudioFocus() async {
|
||||
checkDisposed();
|
||||
if (!initialized) return false;
|
||||
|
||||
final result = await methodChannel.invokeMethod<bool>('requestAudioFocus');
|
||||
return result ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> abandonAudioFocus() async {
|
||||
checkDisposed();
|
||||
if (!initialized) return;
|
||||
|
||||
await methodChannel.invokeMethod('abandonAudioFocus');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart' show protected;
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../models.dart';
|
||||
import 'player.dart';
|
||||
import 'player_state.dart';
|
||||
import 'player_stream_controllers.dart';
|
||||
import 'player_streams.dart';
|
||||
|
||||
/// Abstract base class for player implementations.
|
||||
///
|
||||
/// This class contains shared logic for both [PlayerAndroid] (ExoPlayer)
|
||||
/// and [PlayerNative] (MPV) implementations, including:
|
||||
/// - State management
|
||||
/// - Stream controller setup
|
||||
/// - Event handling infrastructure
|
||||
/// - Property change handlers
|
||||
/// - Track parsing and selection
|
||||
/// - Common lifecycle methods
|
||||
abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
|
||||
PlayerState _state = const PlayerState();
|
||||
|
||||
@override
|
||||
PlayerState get state => _state;
|
||||
|
||||
late final PlayerStreams _streams;
|
||||
|
||||
@override
|
||||
PlayerStreams get streams => _streams;
|
||||
|
||||
@override
|
||||
int? get textureId => null;
|
||||
|
||||
StreamSubscription? _eventSubscription;
|
||||
bool _disposed = false;
|
||||
|
||||
/// Whether the player has been initialized.
|
||||
/// Subclasses should set this to true after initialization.
|
||||
@protected
|
||||
bool initialized = false;
|
||||
|
||||
/// Whether the player has been disposed.
|
||||
bool get disposed => _disposed;
|
||||
|
||||
/// The method channel for platform communication.
|
||||
MethodChannel get methodChannel;
|
||||
|
||||
/// The event channel for receiving platform events.
|
||||
EventChannel get eventChannel;
|
||||
|
||||
/// The log prefix for this player (e.g., 'MPV', 'ExoPlayer').
|
||||
String get logPrefix;
|
||||
|
||||
PlayerBase() {
|
||||
_streams = createStreams();
|
||||
_setupEventListener();
|
||||
logController.stream.listen(_forwardToAppLogger);
|
||||
}
|
||||
|
||||
void _forwardToAppLogger(PlayerLog log) {
|
||||
final message = '[$logPrefix:${log.prefix}] ${log.text}'.trimRight();
|
||||
switch (log.level) {
|
||||
case PlayerLogLevel.fatal:
|
||||
case PlayerLogLevel.error:
|
||||
appLogger.e(message);
|
||||
case PlayerLogLevel.warn:
|
||||
appLogger.w(message);
|
||||
case PlayerLogLevel.info:
|
||||
case PlayerLogLevel.verbose:
|
||||
appLogger.i(message);
|
||||
case PlayerLogLevel.debug:
|
||||
case PlayerLogLevel.trace:
|
||||
appLogger.d(message);
|
||||
case PlayerLogLevel.none:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
handlePlayerEvent(name, event['data'] as Map?);
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a property change event from the platform.
|
||||
/// Subclasses can override this to handle platform-specific properties.
|
||||
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 && value.isNotEmpty) {
|
||||
try {
|
||||
final parsed = jsonDecode(value);
|
||||
if (parsed is List) trackList = parsed;
|
||||
} catch (_) {
|
||||
// Ignore parse errors
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a player event from the platform.
|
||||
/// Subclasses can override this to handle platform-specific events.
|
||||
void handlePlayerEvent(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(data?['message'] as String? ?? 'Playback error');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'file-loaded':
|
||||
_state = _state.copyWith(completed: false);
|
||||
completedController.add(false);
|
||||
break;
|
||||
|
||||
case 'playback-restart':
|
||||
playbackRestartController.add(null);
|
||||
break;
|
||||
|
||||
case 'log-message':
|
||||
final prefix = data?['prefix'] as String? ?? '';
|
||||
final levelStr = data?['level'] as String? ?? 'info';
|
||||
final text = data?['text'] as String? ?? '';
|
||||
final level = parseLogLevel(levelStr);
|
||||
logController.add(PlayerLog(level: level, prefix: prefix, text: text));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a log level string to [PlayerLogLevel].
|
||||
PlayerLogLevel parseLogLevel(String level) {
|
||||
return switch (level) {
|
||||
'fatal' => PlayerLogLevel.fatal,
|
||||
'error' => PlayerLogLevel.error,
|
||||
'warn' => PlayerLogLevel.warn,
|
||||
'info' => PlayerLogLevel.info,
|
||||
'v' || 'verbose' => PlayerLogLevel.verbose,
|
||||
'debug' => PlayerLogLevel.debug,
|
||||
'trace' => PlayerLogLevel.trace,
|
||||
_ => PlayerLogLevel.info,
|
||||
};
|
||||
}
|
||||
|
||||
/// Parse a track list from the platform into [Tracks].
|
||||
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);
|
||||
}
|
||||
|
||||
/// Update the selected audio track.
|
||||
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);
|
||||
}
|
||||
|
||||
/// Update the selected subtitle track.
|
||||
void updateSelectedSubtitleTrack(dynamic trackId) {
|
||||
final id = trackId?.toString();
|
||||
SubtitleTrack? selectedTrack;
|
||||
|
||||
if (id == null || id == 'no') {
|
||||
selectedTrack = SubtitleTrack.off;
|
||||
} else {
|
||||
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);
|
||||
}
|
||||
|
||||
/// Update the internal state.
|
||||
void updateState(PlayerState Function(PlayerState) update) {
|
||||
_state = update(_state);
|
||||
}
|
||||
|
||||
/// Throws if the player has been disposed.
|
||||
void checkDisposed() {
|
||||
if (_disposed) {
|
||||
throw StateError('Player has been disposed');
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Default Implementations
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<void> playOrPause() async {
|
||||
checkDisposed();
|
||||
if (_state.playing) {
|
||||
await pause();
|
||||
} else {
|
||||
await play();
|
||||
}
|
||||
}
|
||||
|
||||
@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> updateFrame() async {
|
||||
// Default no-op, overridden by platforms that need it
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setVideoFrameRate(double fps, int durationMs) async {
|
||||
// Default no-op, overridden by platforms that support it
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearVideoFrameRate() async {
|
||||
// Default no-op, overridden by platforms that support it
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> requestAudioFocus() async {
|
||||
// Default returns true, overridden by Android
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> abandonAudioFocus() async {
|
||||
// Default no-op, overridden by Android
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setAudioDevice(AudioDevice device) async {
|
||||
// Default no-op, overridden by platforms that support it
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setAudioPassthrough(bool enabled) async {
|
||||
// Default no-op, overridden by platforms that support it
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Lifecycle
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
|
||||
await _eventSubscription?.cancel();
|
||||
await methodChannel.invokeMethod('dispose');
|
||||
await closeStreamControllers();
|
||||
}
|
||||
}
|
||||
@@ -1,345 +1,40 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io' show Platform;
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../font_loader.dart';
|
||||
import '../models.dart';
|
||||
import 'player.dart';
|
||||
import 'player_state.dart';
|
||||
import 'player_streams.dart';
|
||||
import 'player_base.dart';
|
||||
|
||||
/// Shared native implementation of [Player] for iOS and macOS.
|
||||
/// Uses MPVKit via platform channels with Metal rendering.
|
||||
class PlayerNative implements Player {
|
||||
/// Shared native implementation of [Player] for iOS, macOS, and Android (MPV fallback).
|
||||
/// Uses MPVKit via platform channels with Metal rendering (Apple) or native window (Android).
|
||||
class PlayerNative extends PlayerBase {
|
||||
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
|
||||
static const _eventChannel = EventChannel('com.plezy/mpv_player/events');
|
||||
|
||||
PlayerState _state = const PlayerState();
|
||||
@override
|
||||
MethodChannel get methodChannel => _methodChannel;
|
||||
|
||||
@override
|
||||
PlayerState get state => _state;
|
||||
|
||||
late final PlayerStreams _streams;
|
||||
EventChannel get eventChannel => _eventChannel;
|
||||
|
||||
@override
|
||||
PlayerStreams get streams => _streams;
|
||||
String get logPrefix => 'MPV';
|
||||
|
||||
@override
|
||||
int? get textureId => null; // Uses direct Metal layer, not Flutter texture
|
||||
String get playerType => 'mpv';
|
||||
|
||||
// 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();
|
||||
final _playbackRestartController = StreamController<void>.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,
|
||||
playbackRestart: _playbackRestartController.stream,
|
||||
);
|
||||
|
||||
_setupEventListener();
|
||||
|
||||
// Forward MPV logs to app logger
|
||||
_logController.stream.listen(_forwardToAppLogger);
|
||||
}
|
||||
|
||||
void _forwardToAppLogger(PlayerLog log) {
|
||||
final message = '[MPV:${log.prefix}] ${log.text}'.trimRight();
|
||||
switch (log.level) {
|
||||
case PlayerLogLevel.fatal:
|
||||
case PlayerLogLevel.error:
|
||||
appLogger.e(message);
|
||||
case PlayerLogLevel.warn:
|
||||
appLogger.w(message);
|
||||
case PlayerLogLevel.info:
|
||||
case PlayerLogLevel.verbose:
|
||||
appLogger.i(message);
|
||||
case PlayerLogLevel.debug:
|
||||
case PlayerLogLevel.trace:
|
||||
appLogger.d(message);
|
||||
case PlayerLogLevel.none:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
PlayerLogLevel _parseLogLevel(String level) {
|
||||
return switch (level) {
|
||||
'fatal' => PlayerLogLevel.fatal,
|
||||
'error' => PlayerLogLevel.error,
|
||||
'warn' => PlayerLogLevel.warn,
|
||||
'info' => PlayerLogLevel.info,
|
||||
'v' || 'verbose' => PlayerLogLevel.verbose,
|
||||
'debug' => PlayerLogLevel.debug,
|
||||
'trace' => PlayerLogLevel.trace,
|
||||
_ => PlayerLogLevel.info,
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
case 'playback-restart':
|
||||
// Playback started/restarted - first frame is ready
|
||||
_playbackRestartController.add(null);
|
||||
break;
|
||||
|
||||
case 'log-message':
|
||||
final prefix = data?['prefix'] as String? ?? '';
|
||||
final levelStr = data?['level'] as String? ?? 'info';
|
||||
final text = data?['text'] as String? ?? '';
|
||||
final level = _parseLogLevel(levelStr);
|
||||
_logController.add(PlayerLog(level: level, prefix: prefix, text: text));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Tracks _parseTrackList(List trackList) {
|
||||
final audioTracks = <AudioTrack>[];
|
||||
final subtitleTracks = <SubtitleTrack>[];
|
||||
|
||||
for (final track in trackList) {
|
||||
if (track is! Map) continue;
|
||||
|
||||
final type = track['type'] as String?;
|
||||
final id = track['id']?.toString() ?? '';
|
||||
|
||||
if (type == 'audio') {
|
||||
audioTracks.add(
|
||||
AudioTrack(
|
||||
id: id,
|
||||
title: track['title'] as String?,
|
||||
language: track['lang'] as String?,
|
||||
codec: track['codec'] as String?,
|
||||
channels: (track['demux-channel-count'] as num?)?.toInt(),
|
||||
sampleRate: (track['demux-samplerate'] as num?)?.toInt(),
|
||||
isDefault: track['default'] as bool? ?? false,
|
||||
),
|
||||
);
|
||||
} else if (type == 'sub') {
|
||||
subtitleTracks.add(
|
||||
SubtitleTrack(
|
||||
id: id,
|
||||
title: track['title'] as String?,
|
||||
language: track['lang'] as String?,
|
||||
codec: track['codec'] as String?,
|
||||
isExternal: track['external'] as bool? ?? false,
|
||||
uri: track['external-filename'] as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return Tracks(audio: audioTracks, subtitle: subtitleTracks);
|
||||
}
|
||||
|
||||
void _updateSelectedAudioTrack(dynamic trackId) {
|
||||
_updateSelectedTrack<AudioTrack>(
|
||||
trackId,
|
||||
_state.tracks.audio.cast<AudioTrack?>().toList(),
|
||||
(selection, track) => selection.copyWith(audio: track),
|
||||
);
|
||||
}
|
||||
|
||||
void _updateSelectedSubtitleTrack(dynamic trackId) {
|
||||
_updateSelectedTrack<SubtitleTrack>(
|
||||
trackId,
|
||||
_state.tracks.subtitle.cast<SubtitleTrack?>().toList(),
|
||||
(selection, track) => selection.copyWith(subtitle: track),
|
||||
);
|
||||
}
|
||||
|
||||
void _updateSelectedTrack<T>(
|
||||
dynamic trackId,
|
||||
List<T?> tracks,
|
||||
TrackSelection Function(TrackSelection, T?) selectionSetter,
|
||||
) {
|
||||
final id = trackId?.toString();
|
||||
T? selectedTrack;
|
||||
|
||||
if (id != null && id != 'no') {
|
||||
selectedTrack = tracks.firstWhere((track) => _getTrackId(track) == id, orElse: () => null);
|
||||
}
|
||||
|
||||
_state = _state.copyWith(track: selectionSetter(_state.track, selectedTrack));
|
||||
_trackController.add(_state.track);
|
||||
}
|
||||
|
||||
String? _getTrackId<T>(T? track) {
|
||||
final dynamic t = track;
|
||||
return t?.id?.toString();
|
||||
}
|
||||
// ============================================
|
||||
// Initialization
|
||||
// ============================================
|
||||
|
||||
Future<void> _ensureInitialized() async {
|
||||
if (_initialized) return;
|
||||
if (initialized) return;
|
||||
|
||||
try {
|
||||
final result = await _methodChannel.invokeMethod<bool>('initialize');
|
||||
_initialized = result == true;
|
||||
if (!_initialized) {
|
||||
final result = await methodChannel.invokeMethod<bool>('initialize');
|
||||
initialized = result == true;
|
||||
if (!initialized) {
|
||||
throw Exception('Failed to initialize player');
|
||||
}
|
||||
|
||||
@@ -358,13 +53,13 @@ class PlayerNative implements Player {
|
||||
await _observeProperty('aid', 'string');
|
||||
await _observeProperty('sid', 'string');
|
||||
} catch (e) {
|
||||
_errorController.add('Initialization failed: $e');
|
||||
errorController.add('Initialization failed: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _observeProperty(String name, String format) async {
|
||||
await _methodChannel.invokeMethod('observeProperty', {'name': name, 'format': format});
|
||||
await methodChannel.invokeMethod('observeProperty', {'name': name, 'format': format});
|
||||
}
|
||||
|
||||
/// Configures subtitle fonts for libass support.
|
||||
@@ -381,13 +76,7 @@ class PlayerNative implements Player {
|
||||
}
|
||||
} 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');
|
||||
errorController.add('Failed to configure subtitle fonts: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,11 +86,11 @@ class PlayerNative implements Player {
|
||||
|
||||
@override
|
||||
Future<void> open(Media media, {bool play = true}) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await _ensureInitialized();
|
||||
|
||||
// Show the video layer
|
||||
await _methodChannel.invokeMethod('setVisible', {'visible': true});
|
||||
await setVisible(true);
|
||||
|
||||
// Set HTTP headers for Plex authentication and profile
|
||||
if (media.headers != null && media.headers!.isNotEmpty) {
|
||||
@@ -417,44 +106,38 @@ class PlayerNative implements Player {
|
||||
await setProperty('start', 'none');
|
||||
}
|
||||
|
||||
await command(['loadfile', media.uri, 'replace']);
|
||||
// Set pause BEFORE loadfile to prevent decoder from starting immediately.
|
||||
// This is important for adding external subtitles before playback begins,
|
||||
// avoiding a race condition that can freeze the video decoder on Android (issue #226).
|
||||
if (!play) {
|
||||
await setProperty('pause', 'yes');
|
||||
}
|
||||
|
||||
await command(['loadfile', media.uri, 'replace']);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> play() async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await setProperty('pause', 'no');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pause() async {
|
||||
_checkDisposed();
|
||||
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();
|
||||
checkDisposed();
|
||||
await command(['stop']);
|
||||
await _methodChannel.invokeMethod('setVisible', {'visible': false});
|
||||
await methodChannel.invokeMethod('setVisible', {'visible': false});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> seek(Duration position) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await command(['seek', (position.inMilliseconds / 1000.0).toString(), 'absolute']);
|
||||
}
|
||||
|
||||
@@ -464,19 +147,19 @@ class PlayerNative implements Player {
|
||||
|
||||
@override
|
||||
Future<void> selectAudioTrack(AudioTrack track) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await setProperty('aid', track.id);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> selectSubtitleTrack(SubtitleTrack track) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await setProperty('sid', track.id);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> addSubtitleTrack({required String uri, String? title, String? language, bool select = false}) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
final args = ['sub-add', uri, select ? 'select' : 'auto'];
|
||||
if (title != null) args.add('title=$title');
|
||||
if (language != null) args.add('lang=$language');
|
||||
@@ -489,19 +172,19 @@ class PlayerNative implements Player {
|
||||
|
||||
@override
|
||||
Future<void> setVolume(double volume) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await setProperty('volume', volume.toString());
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setRate(double rate) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await setProperty('speed', rate.toString());
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setAudioDevice(AudioDevice device) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await setProperty('audio-device', device.name);
|
||||
}
|
||||
|
||||
@@ -511,23 +194,23 @@ class PlayerNative implements Player {
|
||||
|
||||
@override
|
||||
Future<void> setProperty(String name, String value) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await _ensureInitialized();
|
||||
await _methodChannel.invokeMethod('setProperty', {'name': name, 'value': value});
|
||||
await methodChannel.invokeMethod('setProperty', {'name': name, 'value': value});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> getProperty(String name) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await _ensureInitialized();
|
||||
return await _methodChannel.invokeMethod<String>('getProperty', {'name': name});
|
||||
return await methodChannel.invokeMethod<String>('getProperty', {'name': name});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> command(List<String> args) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
await _ensureInitialized();
|
||||
await _methodChannel.invokeMethod('command', {'args': args});
|
||||
await methodChannel.invokeMethod('command', {'args': args});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -536,7 +219,7 @@ class PlayerNative implements Player {
|
||||
|
||||
@override
|
||||
Future<void> setAudioPassthrough(bool enabled) async {
|
||||
_checkDisposed();
|
||||
checkDisposed();
|
||||
if (enabled) {
|
||||
await setProperty('audio-spdif', 'ac3,eac3,dts,dts-hd,truehd');
|
||||
await setProperty('audio-exclusive', 'yes');
|
||||
@@ -547,63 +230,53 @@ class PlayerNative implements Player {
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Visibility
|
||||
// Platform-Specific Overrides
|
||||
// ============================================
|
||||
|
||||
@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;
|
||||
checkDisposed();
|
||||
if (!initialized) return;
|
||||
// Only iOS and macOS use Metal layer that needs frame updates
|
||||
if (Platform.isIOS || Platform.isMacOS) {
|
||||
await _methodChannel.invokeMethod('updateFrame');
|
||||
await methodChannel.invokeMethod('updateFrame');
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Lifecycle
|
||||
// ============================================
|
||||
@override
|
||||
Future<void> setVideoFrameRate(double fps, int durationMs) async {
|
||||
checkDisposed();
|
||||
if (!Platform.isAndroid) return;
|
||||
if (!initialized) return;
|
||||
|
||||
await methodChannel.invokeMethod('setVideoFrameRate', {'fps': fps, 'duration': durationMs});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
Future<void> clearVideoFrameRate() async {
|
||||
checkDisposed();
|
||||
if (!Platform.isAndroid) return;
|
||||
if (!initialized) return;
|
||||
|
||||
await _eventSubscription?.cancel();
|
||||
await _methodChannel.invokeMethod('dispose');
|
||||
await methodChannel.invokeMethod('clearVideoFrameRate');
|
||||
}
|
||||
|
||||
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();
|
||||
await _playbackRestartController.close();
|
||||
@override
|
||||
Future<bool> requestAudioFocus() async {
|
||||
checkDisposed();
|
||||
if (!Platform.isAndroid) return true;
|
||||
if (!initialized) return false;
|
||||
|
||||
final result = await methodChannel.invokeMethod<bool>('requestAudioFocus');
|
||||
return result ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> abandonAudioFocus() async {
|
||||
checkDisposed();
|
||||
if (!Platform.isAndroid) return;
|
||||
if (!initialized) return;
|
||||
|
||||
await methodChannel.invokeMethod('abandonAudioFocus');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../models.dart';
|
||||
import 'player_streams.dart';
|
||||
|
||||
/// Mixin providing stream controllers for player state changes.
|
||||
///
|
||||
/// This mixin contains the 16 stream controllers used by both
|
||||
/// [PlayerAndroid] and [PlayerNative] implementations.
|
||||
mixin PlayerStreamControllersMixin {
|
||||
// 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();
|
||||
final playbackRestartController = StreamController<void>.broadcast();
|
||||
final backendSwitchedController = StreamController<void>.broadcast();
|
||||
|
||||
/// Creates a [PlayerStreams] instance from the stream controllers.
|
||||
PlayerStreams createStreams() {
|
||||
return 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,
|
||||
playbackRestart: playbackRestartController.stream,
|
||||
backendSwitched: backendSwitchedController.stream,
|
||||
);
|
||||
}
|
||||
|
||||
/// Closes all stream controllers.
|
||||
Future<void> closeStreamControllers() async {
|
||||
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();
|
||||
await playbackRestartController.close();
|
||||
await backendSwitchedController.close();
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,10 @@ class PlayerStreams {
|
||||
/// Stream that emits when playback restarts (first frame ready after load/seek).
|
||||
final Stream<void> playbackRestart;
|
||||
|
||||
/// Stream that emits when the native player backend switches (e.g., ExoPlayer to MPV).
|
||||
/// Only emitted on Android when ExoPlayer encounters an unsupported format.
|
||||
final Stream<void> backendSwitched;
|
||||
|
||||
const PlayerStreams({
|
||||
required this.playing,
|
||||
required this.completed,
|
||||
@@ -66,5 +70,6 @@ class PlayerStreams {
|
||||
required this.audioDevice,
|
||||
required this.audioDevices,
|
||||
required this.playbackRestart,
|
||||
required this.backendSwitched,
|
||||
});
|
||||
}
|
||||
|
||||
+21
-1
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'player/player.dart';
|
||||
@@ -35,11 +37,29 @@ class Video extends StatefulWidget {
|
||||
|
||||
class _VideoState extends State<Video> {
|
||||
Rect? _lastRect;
|
||||
bool _hasFirstFrame = false;
|
||||
StreamSubscription<void>? _playbackRestartSubscription;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_playbackRestartSubscription = widget.player.streams.playbackRestart.listen((_) {
|
||||
if (!_hasFirstFrame && mounted) {
|
||||
setState(() => _hasFirstFrame = true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_playbackRestartSubscription?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: Colors.transparent,
|
||||
color: _hasFirstFrame ? Colors.transparent : widget.backgroundColor,
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../models/plex_library.dart';
|
||||
import '../services/data_aggregation_service.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/content_utils.dart';
|
||||
|
||||
/// Load state for the libraries provider
|
||||
enum LibrariesLoadState { initial, loading, loaded, error }
|
||||
|
||||
/// Provider that serves as the single source of truth for library data.
|
||||
/// Both SideNavigationRail and LibrariesScreen consume this provider
|
||||
/// instead of independently fetching library data.
|
||||
class LibrariesProvider extends ChangeNotifier {
|
||||
DataAggregationService? _aggregationService;
|
||||
List<PlexLibrary> _libraries = [];
|
||||
LibrariesLoadState _loadState = LibrariesLoadState.initial;
|
||||
String? _errorMessage;
|
||||
|
||||
/// Unmodifiable list of all libraries (filtered for supported types, ordered)
|
||||
List<PlexLibrary> get libraries => List.unmodifiable(_libraries);
|
||||
|
||||
/// Whether libraries are currently being loaded
|
||||
bool get isLoading => _loadState == LibrariesLoadState.loading;
|
||||
|
||||
/// Whether libraries have been loaded at least once
|
||||
bool get hasLoaded => _loadState == LibrariesLoadState.loaded;
|
||||
|
||||
/// Current load state
|
||||
LibrariesLoadState get loadState => _loadState;
|
||||
|
||||
/// Error message if loading failed
|
||||
String? get errorMessage => _errorMessage;
|
||||
|
||||
/// Whether libraries are available
|
||||
bool get hasLibraries => _libraries.isNotEmpty;
|
||||
|
||||
/// Initialize the provider with the aggregation service.
|
||||
/// This should be called after server connection is established.
|
||||
void initialize(DataAggregationService service) {
|
||||
_aggregationService = service;
|
||||
}
|
||||
|
||||
/// Load libraries from all connected servers.
|
||||
/// Filters out music libraries and applies saved ordering.
|
||||
Future<void> loadLibraries() async {
|
||||
if (_aggregationService == null) {
|
||||
appLogger.w('LibrariesProvider: Cannot load libraries - not initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
_loadState = LibrariesLoadState.loading;
|
||||
_errorMessage = null;
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
// Fetch libraries from all servers
|
||||
final allLibraries = await _aggregationService!.getLibrariesFromAllServers();
|
||||
|
||||
// Filter out music libraries (not supported)
|
||||
final filteredLibraries = allLibraries.where((lib) => !ContentTypeHelper.isMusicLibrary(lib)).toList();
|
||||
|
||||
// Apply saved library order
|
||||
final storage = await StorageService.getInstance();
|
||||
final savedOrder = storage.getLibraryOrder();
|
||||
final orderedLibraries = _applyLibraryOrder(filteredLibraries, savedOrder);
|
||||
|
||||
_libraries = orderedLibraries;
|
||||
_loadState = LibrariesLoadState.loaded;
|
||||
_errorMessage = null;
|
||||
|
||||
appLogger.i('LibrariesProvider: Loaded ${_libraries.length} libraries');
|
||||
notifyListeners();
|
||||
} catch (e, stackTrace) {
|
||||
appLogger.e('LibrariesProvider: Failed to load libraries', error: e, stackTrace: stackTrace);
|
||||
_loadState = LibrariesLoadState.error;
|
||||
_errorMessage = e.toString();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh libraries by clearing cache and reloading.
|
||||
Future<void> refresh() async {
|
||||
if (_aggregationService == null) {
|
||||
appLogger.w('LibrariesProvider: Cannot refresh - not initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear aggregation service cache
|
||||
_aggregationService!.clearCache();
|
||||
|
||||
// Reload libraries
|
||||
await loadLibraries();
|
||||
}
|
||||
|
||||
/// Update the library order and persist it.
|
||||
Future<void> updateLibraryOrder(List<PlexLibrary> orderedLibraries) async {
|
||||
_libraries = List.from(orderedLibraries);
|
||||
notifyListeners();
|
||||
|
||||
// Save the new order
|
||||
final storage = await StorageService.getInstance();
|
||||
final libraryKeys = orderedLibraries.map((lib) => lib.globalKey).toList();
|
||||
await storage.saveLibraryOrder(libraryKeys);
|
||||
|
||||
appLogger.d('LibrariesProvider: Updated library order');
|
||||
}
|
||||
|
||||
/// Clear all library data (for profile switch or logout).
|
||||
void clear() {
|
||||
_libraries = [];
|
||||
_loadState = LibrariesLoadState.initial;
|
||||
_errorMessage = null;
|
||||
notifyListeners();
|
||||
appLogger.d('LibrariesProvider: Cleared library data');
|
||||
}
|
||||
|
||||
/// Apply saved library order to a list of libraries.
|
||||
List<PlexLibrary> _applyLibraryOrder(List<PlexLibrary> libraries, List<String>? savedOrder) {
|
||||
if (savedOrder == null || savedOrder.isEmpty) {
|
||||
return libraries;
|
||||
}
|
||||
|
||||
// Create a map for quick lookup
|
||||
final libraryMap = {for (var lib in libraries) lib.globalKey: lib};
|
||||
|
||||
// Build ordered list based on saved order
|
||||
final orderedLibraries = <PlexLibrary>[];
|
||||
for (final key in savedOrder) {
|
||||
final lib = libraryMap.remove(key);
|
||||
if (lib != null) {
|
||||
orderedLibraries.add(lib);
|
||||
}
|
||||
}
|
||||
|
||||
// Add any new libraries that weren't in the saved order
|
||||
orderedLibraries.addAll(libraryMap.values);
|
||||
|
||||
return orderedLibraries;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../services/offline_watch_sync_service.dart';
|
||||
import '../services/plex_api_cache.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import 'download_provider.dart';
|
||||
|
||||
/// Provider for offline watch status UI state.
|
||||
@@ -166,19 +167,57 @@ class OfflineWatchProvider extends ChangeNotifier {
|
||||
return episodes.first;
|
||||
}
|
||||
|
||||
/// Emit a watch state change event for immediate UI update.
|
||||
void _emitWatchStateChange({
|
||||
required String serverId,
|
||||
required String ratingKey,
|
||||
required bool isNowWatched,
|
||||
required WatchStateChangeType changeType,
|
||||
}) {
|
||||
final globalKey = '$serverId:$ratingKey';
|
||||
final metadata = _downloadProvider.getMetadata(globalKey);
|
||||
if (metadata != null) {
|
||||
WatchStateNotifier().notifyWatched(metadata: metadata, isNowWatched: isNowWatched);
|
||||
} else {
|
||||
// Fallback: emit minimal event without parent chain
|
||||
WatchStateNotifier().notify(
|
||||
WatchStateEvent(
|
||||
ratingKey: ratingKey,
|
||||
serverId: serverId,
|
||||
changeType: changeType,
|
||||
parentChain: [],
|
||||
mediaType: 'unknown',
|
||||
isNowWatched: isNowWatched,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark an item as watched while offline.
|
||||
///
|
||||
/// This queues the action for sync when online.
|
||||
/// This queues the action for sync when online and emits a [WatchStateEvent].
|
||||
Future<void> markAsWatched({required String serverId, required String ratingKey}) async {
|
||||
await _syncService.queueMarkWatched(serverId: serverId, ratingKey: ratingKey);
|
||||
_emitWatchStateChange(
|
||||
serverId: serverId,
|
||||
ratingKey: ratingKey,
|
||||
isNowWatched: true,
|
||||
changeType: WatchStateChangeType.watched,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Mark an item as unwatched while offline.
|
||||
///
|
||||
/// This queues the action for sync when online.
|
||||
/// This queues the action for sync when online and emits a [WatchStateEvent].
|
||||
Future<void> markAsUnwatched({required String serverId, required String ratingKey}) async {
|
||||
await _syncService.queueMarkUnwatched(serverId: serverId, ratingKey: ratingKey);
|
||||
_emitWatchStateChange(
|
||||
serverId: serverId,
|
||||
ratingKey: ratingKey,
|
||||
isNowWatched: false,
|
||||
changeType: WatchStateChangeType.unwatched,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../services/settings_service.dart';
|
||||
|
||||
class SettingsProvider extends ChangeNotifier {
|
||||
SettingsService? _settingsService;
|
||||
LibraryDensity _libraryDensity = LibraryDensity.normal;
|
||||
ViewMode _viewMode = ViewMode.grid;
|
||||
bool _useSeasonPoster = false;
|
||||
EpisodePosterMode _episodePosterMode = EpisodePosterMode.seriesPoster;
|
||||
bool _showHeroSection = true;
|
||||
bool _useGlobalHubs = true;
|
||||
bool _showServerNameOnHubs = false;
|
||||
bool _alwaysKeepSidebarOpen = false;
|
||||
bool _isInitialized = false;
|
||||
Future<void>? _initFuture;
|
||||
|
||||
@@ -25,8 +29,11 @@ class SettingsProvider extends ChangeNotifier {
|
||||
_settingsService = await SettingsService.getInstance();
|
||||
_libraryDensity = _settingsService!.getLibraryDensity();
|
||||
_viewMode = _settingsService!.getViewMode();
|
||||
_useSeasonPoster = _settingsService!.getUseSeasonPoster();
|
||||
_episodePosterMode = _settingsService!.getEpisodePosterMode();
|
||||
_showHeroSection = _settingsService!.getShowHeroSection();
|
||||
_useGlobalHubs = _settingsService!.getUseGlobalHubs();
|
||||
_showServerNameOnHubs = _settingsService!.getShowServerNameOnHubs();
|
||||
_alwaysKeepSidebarOpen = _settingsService!.getAlwaysKeepSidebarOpen();
|
||||
_isInitialized = true;
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -38,10 +45,16 @@ class SettingsProvider extends ChangeNotifier {
|
||||
|
||||
ViewMode get viewMode => _viewMode;
|
||||
|
||||
bool get useSeasonPoster => _useSeasonPoster;
|
||||
EpisodePosterMode get episodePosterMode => _episodePosterMode;
|
||||
|
||||
bool get showHeroSection => _showHeroSection;
|
||||
|
||||
bool get useGlobalHubs => _useGlobalHubs;
|
||||
|
||||
bool get showServerNameOnHubs => _showServerNameOnHubs;
|
||||
|
||||
bool get alwaysKeepSidebarOpen => _alwaysKeepSidebarOpen;
|
||||
|
||||
Future<void> setLibraryDensity(LibraryDensity density) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_libraryDensity != density) {
|
||||
@@ -60,11 +73,11 @@ class SettingsProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setUseSeasonPoster(bool value) async {
|
||||
Future<void> setEpisodePosterMode(EpisodePosterMode mode) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_useSeasonPoster != value) {
|
||||
_useSeasonPoster = value;
|
||||
await _settingsService!.setUseSeasonPoster(value);
|
||||
if (_episodePosterMode != mode) {
|
||||
_episodePosterMode = mode;
|
||||
await _settingsService!.setEpisodePosterMode(mode);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -78,6 +91,33 @@ class SettingsProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setUseGlobalHubs(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_useGlobalHubs != value) {
|
||||
_useGlobalHubs = value;
|
||||
await _settingsService!.setUseGlobalHubs(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setShowServerNameOnHubs(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_showServerNameOnHubs != value) {
|
||||
_showServerNameOnHubs = value;
|
||||
await _settingsService!.setShowServerNameOnHubs(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setAlwaysKeepSidebarOpen(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_alwaysKeepSidebarOpen != value) {
|
||||
_alwaysKeepSidebarOpen = value;
|
||||
await _settingsService!.setAlwaysKeepSidebarOpen(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
String get libraryDensityDisplayName {
|
||||
switch (_libraryDensity) {
|
||||
case LibraryDensity.compact:
|
||||
@@ -88,4 +128,15 @@ class SettingsProvider extends ChangeNotifier {
|
||||
return 'Comfortable';
|
||||
}
|
||||
}
|
||||
|
||||
String get episodePosterModeDisplayName {
|
||||
switch (_episodePosterMode) {
|
||||
case EpisodePosterMode.seriesPoster:
|
||||
return t.settings.seriesPoster;
|
||||
case EpisodePosterMode.seasonPoster:
|
||||
return t.settings.seasonPoster;
|
||||
case EpisodePosterMode.episodeThumbnail:
|
||||
return t.settings.episodeThumbnail;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import '../services/storage_service.dart';
|
||||
import '../services/server_registry.dart';
|
||||
import '../providers/multi_server_provider.dart';
|
||||
import '../providers/plex_client_provider.dart';
|
||||
import '../providers/libraries_provider.dart';
|
||||
import '../services/offline_watch_sync_service.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../theme/mono_tokens.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
@@ -91,6 +93,21 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
final plexClientProvider = context.read<PlexClientProvider>();
|
||||
plexClientProvider.setClient(firstClient);
|
||||
|
||||
// Initialize and load libraries (mirroring SetupScreen behavior)
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
librariesProvider.initialize(multiServerProvider.aggregationService);
|
||||
try {
|
||||
await librariesProvider.loadLibraries();
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to load libraries during sign-in', error: e);
|
||||
// Continue anyway - MainScreen will retry
|
||||
}
|
||||
|
||||
// Trigger initial watch sync now that Plex clients are available
|
||||
if (mounted) {
|
||||
context.read<OfflineWatchSyncService>().onServersConnected();
|
||||
}
|
||||
|
||||
// Navigate to main screen
|
||||
if (!mounted) return;
|
||||
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => MainScreen(client: firstClient)));
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../widgets/media_grid_sliver.dart';
|
||||
import '../widgets/focused_scroll_scaffold.dart';
|
||||
import '../widgets/focusable_media_card.dart';
|
||||
import '../widgets/media_grid_delegate.dart';
|
||||
import '../utils/grid_size_calculator.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../utils/dialogs.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/snackbar_helper.dart';
|
||||
import 'base_media_list_detail_screen.dart';
|
||||
import 'focusable_detail_screen_mixin.dart';
|
||||
import '../focus/key_event_utils.dart';
|
||||
|
||||
/// Screen to display the contents of a collection
|
||||
class CollectionDetailScreen extends StatefulWidget {
|
||||
@@ -19,7 +26,7 @@ class CollectionDetailScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _CollectionDetailScreenState extends BaseMediaListDetailScreen<CollectionDetailScreen>
|
||||
with StandardItemLoader<CollectionDetailScreen> {
|
||||
with StandardItemLoader<CollectionDetailScreen>, FocusableDetailScreenMixin<CollectionDetailScreen> {
|
||||
@override
|
||||
PlexMetadata get mediaItem => widget.collection;
|
||||
|
||||
@@ -29,11 +36,30 @@ class _CollectionDetailScreenState extends BaseMediaListDetailScreen<CollectionD
|
||||
@override
|
||||
String get emptyMessage => t.collections.empty;
|
||||
|
||||
@override
|
||||
bool get hasItems => items.isNotEmpty;
|
||||
|
||||
@override
|
||||
int get appBarButtonCount => items.isNotEmpty ? 3 : 1; // play, shuffle, delete (or just delete if empty)
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
disposeFocusResources();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<PlexMetadata>> fetchItems() async {
|
||||
return await client.getCollectionItems(widget.collection.ratingKey);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> loadItems() async {
|
||||
contentVersion++;
|
||||
await super.loadItems();
|
||||
autoFocusFirstItemAfterLoad();
|
||||
}
|
||||
|
||||
@override
|
||||
String getLoadErrorMessage(Object error) {
|
||||
return t.collections.failedToLoadItems(error: error.toString());
|
||||
@@ -44,11 +70,28 @@ class _CollectionDetailScreenState extends BaseMediaListDetailScreen<CollectionD
|
||||
return 'Loaded $itemCount items for collection: ${widget.collection.title}';
|
||||
}
|
||||
|
||||
Future<void> _deleteCollection() async {
|
||||
// Get library section ID from the collection or its items
|
||||
int? sectionId = widget.collection.librarySectionID;
|
||||
@override
|
||||
List<AppBarButtonConfig> getAppBarButtons() {
|
||||
final buttons = <AppBarButtonConfig>[];
|
||||
if (items.isNotEmpty) {
|
||||
buttons.add(AppBarButtonConfig(icon: Symbols.play_arrow_rounded, tooltip: t.discover.play, onPressed: playItems));
|
||||
buttons.add(
|
||||
AppBarButtonConfig(icon: Symbols.shuffle_rounded, tooltip: t.common.shuffle, onPressed: shufflePlayItems),
|
||||
);
|
||||
}
|
||||
buttons.add(
|
||||
AppBarButtonConfig(
|
||||
icon: Symbols.delete_rounded,
|
||||
tooltip: t.common.delete,
|
||||
onPressed: _deleteCollection,
|
||||
color: Colors.red,
|
||||
),
|
||||
);
|
||||
return buttons;
|
||||
}
|
||||
|
||||
// If collection doesn't have it, try to get it from loaded items
|
||||
Future<void> _deleteCollection() async {
|
||||
int? sectionId = widget.collection.librarySectionID;
|
||||
if (sectionId == null && items.isNotEmpty) {
|
||||
sectionId = items.first.librarySectionID;
|
||||
}
|
||||
@@ -60,7 +103,6 @@ class _CollectionDetailScreenState extends BaseMediaListDetailScreen<CollectionD
|
||||
return;
|
||||
}
|
||||
|
||||
// Show confirmation dialog
|
||||
final confirmed = await showDeleteConfirmation(
|
||||
context,
|
||||
title: t.collections.deleteCollection,
|
||||
@@ -75,13 +117,11 @@ class _CollectionDetailScreenState extends BaseMediaListDetailScreen<CollectionD
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (mounted) {
|
||||
if (success) {
|
||||
showSuccessSnackBar(context, t.collections.deleted);
|
||||
Navigator.pop(context, true); // Return true to indicate refresh needed
|
||||
} else {
|
||||
showErrorSnackBar(context, t.collections.deleteFailed);
|
||||
}
|
||||
if (success) {
|
||||
showSuccessSnackBar(context, t.collections.deleted);
|
||||
Navigator.pop(context, true);
|
||||
} else {
|
||||
showErrorSnackBar(context, t.collections.deleteFailed);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to delete collection', error: e);
|
||||
@@ -93,20 +133,58 @@ class _CollectionDetailScreenState extends BaseMediaListDetailScreen<CollectionD
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FocusedScrollScaffold(
|
||||
title: Text(widget.collection.title),
|
||||
actions: buildAppBarActions(onDelete: _deleteCollection),
|
||||
slivers: [
|
||||
...buildStateSlivers(),
|
||||
if (items.isNotEmpty)
|
||||
MediaGridSliver(
|
||||
items: items,
|
||||
onRefresh: updateItem,
|
||||
collectionId: widget.collection.ratingKey,
|
||||
onListRefresh: loadItems,
|
||||
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
|
||||
return PopScope(
|
||||
canPop: false,
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
if (BackKeyCoordinator.consumeIfHandled()) return;
|
||||
if (didPop) return;
|
||||
final shouldPop = handleBackNavigation();
|
||||
if (shouldPop && mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
},
|
||||
child: Scaffold(
|
||||
body: CustomScrollView(
|
||||
controller: scrollController,
|
||||
slivers: [
|
||||
CustomAppBar(title: Text(widget.collection.title), actions: buildFocusableAppBarActions()),
|
||||
...buildStateSlivers(),
|
||||
if (items.isNotEmpty) _buildFocusableGrid(),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildFocusableGrid() {
|
||||
return Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
final columnCount = GridSizeCalculator.getColumnCount(context, settingsProvider.libraryDensity);
|
||||
return SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
|
||||
sliver: SliverGrid.builder(
|
||||
gridDelegate: MediaGridDelegate.createDelegate(context: context, density: settingsProvider.libraryDensity),
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
final inFirstRow = GridSizeCalculator.isFirstRow(index, columnCount);
|
||||
final focusNode = index == 0 ? firstItemFocusNode : getGridItemFocusNode(index);
|
||||
|
||||
return FocusableMediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
focusNode: focusNode,
|
||||
onRefresh: updateItem,
|
||||
collectionId: widget.collection.ratingKey,
|
||||
onListRefresh: loadItems,
|
||||
onNavigateUp: inFirstRow ? navigateToAppBar : null,
|
||||
onBack: handleBackFromContent,
|
||||
onFocusChange: (hasFocus) => trackGridItemFocus(index, hasFocus),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io' show Platform;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:plezy/widgets/app_icon.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
@@ -22,6 +24,8 @@ import '../providers/settings_provider.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
import '../mixins/watch_state_aware.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/video_player_navigation.dart';
|
||||
@@ -30,6 +34,7 @@ import '../utils/platform_detector.dart';
|
||||
import '../theme/mono_tokens.dart';
|
||||
import 'auth_screen.dart';
|
||||
import 'libraries/state_messages.dart';
|
||||
import 'main_screen.dart';
|
||||
import '../watch_together/watch_together.dart';
|
||||
|
||||
class DiscoverScreen extends StatefulWidget {
|
||||
@@ -42,7 +47,13 @@ class DiscoverScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
with Refreshable, FullRefreshable, ItemUpdatable, SingleTickerProviderStateMixin {
|
||||
with
|
||||
Refreshable,
|
||||
FullRefreshable,
|
||||
ItemUpdatable,
|
||||
WatchStateAware,
|
||||
SingleTickerProviderStateMixin,
|
||||
WidgetsBindingObserver {
|
||||
static const Duration _heroAutoScrollDuration = Duration(seconds: 8);
|
||||
|
||||
@override
|
||||
@@ -66,6 +77,28 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
late AnimationController _indicatorAnimationController;
|
||||
bool _isAutoScrollPaused = false;
|
||||
|
||||
// WatchStateAware: watch on-deck items and their parent shows/seasons
|
||||
@override
|
||||
Set<String>? get watchedRatingKeys {
|
||||
final keys = <String>{};
|
||||
for (final item in _onDeck) {
|
||||
keys.add(item.ratingKey);
|
||||
if (item.parentRatingKey != null) {
|
||||
keys.add(item.parentRatingKey!);
|
||||
}
|
||||
if (item.grandparentRatingKey != null) {
|
||||
keys.add(item.grandparentRatingKey!);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
@override
|
||||
void onWatchStateChanged(WatchStateEvent event) {
|
||||
// Refresh continue watching when any relevant item changes
|
||||
_refreshContinueWatching();
|
||||
}
|
||||
|
||||
// Hub navigation keys
|
||||
GlobalKey<HubSectionState>? _continueWatchingHubKey;
|
||||
final List<GlobalKey<HubSectionState>> _hubKeys = [];
|
||||
@@ -152,9 +185,15 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Navigate focus to the sidebar
|
||||
void _navigateToSidebar() {
|
||||
MainScreenFocusScope.of(context)?.focusSidebar();
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_indicatorAnimationController = AnimationController(vsync: this, duration: _heroAutoScrollDuration);
|
||||
_heroFocusNode = FocusNode(debugLabel: 'hero_section');
|
||||
_refreshButtonFocusNode = FocusNode(debugLabel: 'refresh_button');
|
||||
@@ -214,10 +253,12 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT: Navigate hero carousel to previous
|
||||
// LEFT: Navigate hero carousel to previous, or focus sidebar at index 0
|
||||
if (key.isLeftKey) {
|
||||
if (_currentHeroIndex > 0) {
|
||||
_heroController.previousPage(duration: tokens(context).slow, curve: Curves.easeInOut);
|
||||
} else {
|
||||
_navigateToSidebar();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
@@ -261,8 +302,14 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT/UP: Block at boundary
|
||||
if (key.isLeftKey || key.isUpKey) {
|
||||
// LEFT: Navigate to sidebar
|
||||
if (key.isLeftKey) {
|
||||
_navigateToSidebar();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// UP: Block at boundary
|
||||
if (key.isUpKey) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
@@ -352,6 +399,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_autoScrollTimer?.cancel();
|
||||
_heroController.dispose();
|
||||
_scrollController.dispose();
|
||||
@@ -366,6 +414,16 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
// Refresh continue watching when app resumes on mobile platforms
|
||||
// Skip on desktop to avoid excessive refreshes from window focus changes
|
||||
if (state == AppLifecycleState.resumed && (Platform.isIOS || Platform.isAndroid)) {
|
||||
appLogger.d('App resumed on mobile - refreshing continue watching');
|
||||
_refreshContinueWatching();
|
||||
}
|
||||
}
|
||||
|
||||
void _startAutoScroll() {
|
||||
if (_isAutoScrollPaused) return;
|
||||
|
||||
@@ -455,16 +513,29 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
});
|
||||
|
||||
try {
|
||||
appLogger.d('Fetching onDeck and hubs from all Plex servers');
|
||||
appLogger.d('Fetching onDeck and global hubs from all Plex servers');
|
||||
final multiServerProvider = Provider.of<MultiServerProvider>(context, listen: false);
|
||||
|
||||
if (!multiServerProvider.hasConnectedServers) {
|
||||
throw Exception('No servers available');
|
||||
}
|
||||
|
||||
// Start OnDeck and libraries fetch in parallel
|
||||
final onDeckFuture = multiServerProvider.aggregationService.getOnDeckFromAllServers(limit: 20);
|
||||
final librariesFuture = multiServerProvider.aggregationService.getLibrariesFromAllServersGrouped();
|
||||
// Get hidden libraries for filtering
|
||||
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(context, listen: false);
|
||||
|
||||
// Get settings for hub mode preference (ensure initialized before accessing)
|
||||
final settingsProvider = Provider.of<SettingsProvider>(context, listen: false);
|
||||
await settingsProvider.ensureInitialized();
|
||||
|
||||
// Start OnDeck and hubs fetch in parallel
|
||||
final onDeckFuture = multiServerProvider.aggregationService.getOnDeckFromAllServers(
|
||||
limit: 20,
|
||||
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
|
||||
);
|
||||
final hubsFuture = multiServerProvider.aggregationService.getHubsFromAllServers(
|
||||
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
|
||||
useGlobalHubs: settingsProvider.useGlobalHubs,
|
||||
);
|
||||
|
||||
// Wait for OnDeck to complete and show it immediately
|
||||
final onDeck = await onDeckFuture;
|
||||
@@ -487,32 +558,22 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
_heroController.jumpToPage(0);
|
||||
}
|
||||
|
||||
// Wait for libraries and then fetch hubs
|
||||
final librariesByServer = await librariesFuture;
|
||||
// Wait for global hubs
|
||||
final allHubs = await hubsFuture;
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// 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
|
||||
// Filter out Continue Watching / On Deck hubs (handled separately in hero section)
|
||||
final filteredHubs = allHubs.where((hub) {
|
||||
final hubId = hub.hubIdentifier?.toLowerCase() ?? '';
|
||||
final title = hub.title.toLowerCase();
|
||||
// Skip "Continue Watching" and "On Deck" hubs (we handle these separately)
|
||||
return !hubId.contains('ondeck') &&
|
||||
!hubId.contains('continue') &&
|
||||
!title.contains('continue watching') &&
|
||||
!title.contains('on deck');
|
||||
}).toList();
|
||||
|
||||
appLogger.d('Received ${onDeck.length} on deck items and ${filteredHubs.length} hubs from all servers');
|
||||
appLogger.d('Received ${onDeck.length} on deck items and ${filteredHubs.length} global hubs from all servers');
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_hubs = filteredHubs;
|
||||
@@ -543,7 +604,11 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
return;
|
||||
}
|
||||
|
||||
final onDeck = await multiServerProvider.aggregationService.getOnDeckFromAllServers(limit: 20);
|
||||
final hiddenLibrariesProvider = context.read<HiddenLibrariesProvider>();
|
||||
final onDeck = await multiServerProvider.aggregationService.getOnDeckFromAllServers(
|
||||
limit: 20,
|
||||
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
|
||||
);
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
@@ -675,6 +740,15 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
return Symbols.auto_awesome_rounded;
|
||||
}
|
||||
|
||||
/// Get the set of hub titles that appear more than once (duplicates)
|
||||
Set<String> _getDuplicateHubTitles() {
|
||||
final titleCounts = <String, int>{};
|
||||
for (final hub in _hubs) {
|
||||
titleCounts[hub.title] = (titleCounts[hub.title] ?? 0) + 1;
|
||||
}
|
||||
return titleCounts.entries.where((e) => e.value > 1).map((e) => e.key).toSet();
|
||||
}
|
||||
|
||||
@override
|
||||
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
|
||||
// Check and update in _onDeck list
|
||||
@@ -926,6 +1000,10 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Get settings for server name display
|
||||
final showServerNameOnHubs = context.watch<SettingsProvider>().showServerNameOnHubs;
|
||||
final duplicateHubTitles = _getDuplicateHubTitles();
|
||||
|
||||
return Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
@@ -975,6 +1053,11 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
onRemoveFromContinueWatching: _refreshContinueWatching,
|
||||
isInContinueWatching: true,
|
||||
onVerticalNavigation: (isUp) => _handleVerticalNavigation(0, isUp),
|
||||
onNavigateUp: () {
|
||||
_heroFocusNode.requestFocus();
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
|
||||
},
|
||||
onNavigateToSidebar: _navigateToSidebar,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -985,9 +1068,15 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
key: i < _hubKeys.length ? _hubKeys[i] : null,
|
||||
hub: _hubs[i],
|
||||
icon: _getHubIcon(_hubs[i].title),
|
||||
showServerName: showServerNameOnHubs || duplicateHubTitles.contains(_hubs[i].title),
|
||||
onRefresh: updateItem,
|
||||
// Hub index is i + 1 if continue watching exists, otherwise i
|
||||
onVerticalNavigation: (isUp) => _handleVerticalNavigation(_onDeck.isNotEmpty ? i + 1 : i, isUp),
|
||||
onNavigateUp: (i == 0 && _onDeck.isEmpty) ? () {
|
||||
_heroFocusNode.requestFocus();
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
|
||||
} : null,
|
||||
onNavigateToSidebar: _navigateToSidebar,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1073,6 +1162,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
child: SizedBox(
|
||||
height: heroHeight,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
PageView.builder(
|
||||
controller: _heroController,
|
||||
@@ -1090,6 +1180,30 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
return _buildHeroItem(_onDeck[index]);
|
||||
},
|
||||
),
|
||||
// Bottom gradient that extends past hero bounds to ensure seamless blend
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: -32, // Extend 32px past the hero section bounds
|
||||
height: 80, // Tall enough to cover any gap
|
||||
child: IgnorePointer(
|
||||
child: Builder(
|
||||
builder: (context) {
|
||||
final bgColor = Theme.of(context).scaffoldBackgroundColor;
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [bgColor.withValues(alpha: 0), bgColor],
|
||||
stops: const [0.0, 0.6],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
// Page indicators with animated progress and pause/play button
|
||||
Positioned(
|
||||
bottom: 16,
|
||||
@@ -1207,47 +1321,50 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
},
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// Background Image with fade/zoom animation and parallax
|
||||
if (heroItem.art != null || heroItem.grandparentArt != null)
|
||||
AnimatedBuilder(
|
||||
animation: _scrollController,
|
||||
builder: (context, child) {
|
||||
final scrollOffset = _scrollController.hasClients ? _scrollController.offset : 0.0;
|
||||
return Transform.translate(offset: Offset(0, scrollOffset * 0.3), child: child);
|
||||
},
|
||||
child: TweenAnimationBuilder<double>(
|
||||
tween: Tween(begin: 0.0, end: 1.0),
|
||||
duration: const Duration(milliseconds: 800),
|
||||
curve: Curves.easeOut,
|
||||
builder: (context, value, child) {
|
||||
return Transform.scale(
|
||||
scale: 1.0 + (0.1 * (1 - value)),
|
||||
child: Opacity(opacity: value, child: child),
|
||||
);
|
||||
ClipRect(
|
||||
child: AnimatedBuilder(
|
||||
animation: _scrollController,
|
||||
builder: (context, child) {
|
||||
final scrollOffset = _scrollController.hasClients ? _scrollController.offset : 0.0;
|
||||
return Transform.translate(offset: Offset(0, scrollOffset * 0.3), child: child);
|
||||
},
|
||||
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: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) =>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
errorWidget: (context, url, error) =>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
child: TweenAnimationBuilder<double>(
|
||||
tween: Tween(begin: 0.0, end: 1.0),
|
||||
duration: const Duration(milliseconds: 800),
|
||||
curve: Curves.easeOut,
|
||||
builder: (context, value, child) {
|
||||
return Transform.scale(
|
||||
scale: 1.0 + (0.1 * (1 - value)),
|
||||
child: Opacity(opacity: value, child: child),
|
||||
);
|
||||
},
|
||||
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: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) =>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
errorWidget: (context, url, error) =>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -1255,20 +1372,26 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
|
||||
// Gradient Overlay - blends into scaffold background
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final bgColor = Theme.of(context).scaffoldBackgroundColor;
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Colors.transparent, bgColor.withValues(alpha: 0.9), bgColor],
|
||||
stops: const [0.5, 0.85, 1.0],
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: -4, // Extend past stack bounds to ensure coverage
|
||||
child: Builder(
|
||||
builder: (context) {
|
||||
final bgColor = Theme.of(context).scaffoldBackgroundColor;
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Colors.transparent, bgColor.withValues(alpha: 0.9), bgColor],
|
||||
stops: const [0.5, 0.85, 1.0],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
// Content with responsive alignment
|
||||
|
||||
@@ -6,6 +6,8 @@ import '../../providers/download_provider.dart';
|
||||
import '../../providers/multi_server_provider.dart';
|
||||
import '../../providers/settings_provider.dart';
|
||||
import '../../services/gamepad_service.dart';
|
||||
import '../../utils/grid_size_calculator.dart';
|
||||
import '../../utils/layout_constants.dart';
|
||||
import '../../utils/platform_detector.dart';
|
||||
import '../../widgets/desktop_app_bar.dart';
|
||||
import '../../widgets/focusable_tab_chip.dart';
|
||||
@@ -32,7 +34,7 @@ class DownloadsScreenState extends State<DownloadsScreen> with SingleTickerProvi
|
||||
final _moviesTabChipFocusNode = FocusNode(debugLabel: 'tab_chip_movies');
|
||||
|
||||
/// When true, suppress auto-focus in tabs (used when navigating via tab bar)
|
||||
bool _suppressAutoFocus = false;
|
||||
bool _suppressAutoFocus = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -156,7 +158,7 @@ class DownloadsScreenState extends State<DownloadsScreen> with SingleTickerProvi
|
||||
});
|
||||
_getTabChipFocusNode(newIndex).requestFocus();
|
||||
}
|
||||
: null,
|
||||
: _onTabBarBack,
|
||||
onNavigateRight: index < tabCount - 1
|
||||
? () {
|
||||
final newIndex = index + 1;
|
||||
@@ -257,6 +259,9 @@ class DownloadsScreenState extends State<DownloadsScreen> with SingleTickerProvi
|
||||
},
|
||||
onCancel: downloadProvider.cancelDownload,
|
||||
onDelete: downloadProvider.deleteDownload,
|
||||
onNavigateLeft: () => MainScreenFocusScope.of(context)?.focusSidebar(),
|
||||
onBack: focusTabBar,
|
||||
suppressAutoFocus: _suppressAutoFocus,
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -285,35 +290,90 @@ class DownloadsScreenState extends State<DownloadsScreen> with SingleTickerProvi
|
||||
enum DownloadType { manage, tvShows, movies }
|
||||
|
||||
/// Grid content for TV Shows and Movies tabs
|
||||
class _DownloadsGridContent extends StatelessWidget {
|
||||
class _DownloadsGridContent extends StatefulWidget {
|
||||
final DownloadType type;
|
||||
final bool suppressAutoFocus;
|
||||
final VoidCallback? onBack;
|
||||
|
||||
const _DownloadsGridContent({required this.type, required this.suppressAutoFocus, this.onBack});
|
||||
|
||||
@override
|
||||
State<_DownloadsGridContent> createState() => _DownloadsGridContentState();
|
||||
}
|
||||
|
||||
class _DownloadsGridContentState extends State<_DownloadsGridContent> {
|
||||
final FocusNode _firstItemFocusNode = FocusNode(debugLabel: 'DownloadsGrid_firstItem');
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_firstItemFocusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(_DownloadsGridContent oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// When suppressAutoFocus changes from true to false, focus the first item
|
||||
if (oldWidget.suppressAutoFocus && !widget.suppressAutoFocus) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && _firstItemFocusNode.canRequestFocus) {
|
||||
_firstItemFocusNode.requestFocus();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigate focus to the sidebar
|
||||
void _navigateToSidebar() {
|
||||
MainScreenFocusScope.of(context)?.focusSidebar();
|
||||
}
|
||||
|
||||
/// Calculate column count based on actual available width.
|
||||
int _calculateColumnCount(double availableWidth, double maxCrossAxisExtent, double crossAxisSpacing) {
|
||||
return ((availableWidth + crossAxisSpacing) / (maxCrossAxisExtent + crossAxisSpacing)).ceil().clamp(1, 100);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Consumer2<DownloadProvider, SettingsProvider>(
|
||||
builder: (context, downloadProvider, settingsProvider, _) {
|
||||
final List<PlexMetadata> items = type == DownloadType.tvShows
|
||||
final List<PlexMetadata> items = widget.type == DownloadType.tvShows
|
||||
? downloadProvider.downloadedShows
|
||||
: downloadProvider.downloadedMovies;
|
||||
|
||||
if (items.isEmpty) {
|
||||
return _buildEmptyState(context);
|
||||
return _buildEmptyState();
|
||||
}
|
||||
|
||||
return GridView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
gridDelegate: MediaGridDelegate.createDelegate(context: context, density: settingsProvider.libraryDensity),
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
return FocusableMediaCard(
|
||||
item: item,
|
||||
onBack: onBack,
|
||||
isOffline: true, // Downloaded content works without server
|
||||
// Extra top padding for focus decoration (scale + border extends beyond item bounds)
|
||||
const effectivePadding = EdgeInsets.only(left: 8, right: 8, top: 8);
|
||||
final maxCrossAxisExtent = GridSizeCalculator.getMaxCrossAxisExtent(context, settingsProvider.libraryDensity);
|
||||
const crossAxisSpacing = GridLayoutConstants.crossAxisSpacing;
|
||||
|
||||
// Use LayoutBuilder to get actual available width (accounting for sidebar)
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final availableWidth = constraints.maxWidth - effectivePadding.left - effectivePadding.right;
|
||||
final columnCount = _calculateColumnCount(availableWidth, maxCrossAxisExtent, crossAxisSpacing);
|
||||
|
||||
return GridView.builder(
|
||||
padding: effectivePadding,
|
||||
// Allow focus decoration to render outside scroll bounds
|
||||
clipBehavior: Clip.none,
|
||||
gridDelegate: MediaGridDelegate.createDelegate(context: context, density: settingsProvider.libraryDensity),
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
final isFirstColumn = GridSizeCalculator.isFirstColumn(index, columnCount);
|
||||
final isFirst = index == 0;
|
||||
return FocusableMediaCard(
|
||||
item: item,
|
||||
focusNode: isFirst ? _firstItemFocusNode : null,
|
||||
onBack: widget.onBack,
|
||||
isOffline: true, // Downloaded content works without server
|
||||
onNavigateLeft: isFirstColumn ? _navigateToSidebar : null,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -321,7 +381,7 @@ class _DownloadsGridContent extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEmptyState(BuildContext context) {
|
||||
Widget _buildEmptyState() {
|
||||
return EmptyStateWidget(
|
||||
message: t.downloads.noDownloads,
|
||||
subtitle: t.downloads.noDownloadsDescription,
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import '../focus/dpad_navigator.dart';
|
||||
import '../focus/input_mode_tracker.dart';
|
||||
import '../focus/key_event_utils.dart';
|
||||
import '../widgets/app_icon.dart';
|
||||
|
||||
/// Configuration for app bar buttons
|
||||
class AppBarButtonConfig {
|
||||
final IconData icon;
|
||||
final String tooltip;
|
||||
final VoidCallback onPressed;
|
||||
final Color? color;
|
||||
|
||||
const AppBarButtonConfig({required this.icon, required this.tooltip, required this.onPressed, this.color});
|
||||
}
|
||||
|
||||
/// Mixin that provides common focus navigation functionality for detail screens.
|
||||
/// Handles app bar focus, back navigation, scroll-to-top, and grid item focus management.
|
||||
mixin FocusableDetailScreenMixin<T extends StatefulWidget> on State<T> {
|
||||
// Scroll controller for scrolling to top when app bar is focused
|
||||
final ScrollController scrollController = ScrollController();
|
||||
|
||||
// App bar focus nodes
|
||||
final FocusNode playButtonFocusNode = FocusNode(debugLabel: 'detail_play');
|
||||
final FocusNode shuffleButtonFocusNode = FocusNode(debugLabel: 'detail_shuffle');
|
||||
final FocusNode deleteButtonFocusNode = FocusNode(debugLabel: 'detail_delete');
|
||||
|
||||
// Grid item focus
|
||||
final FocusNode firstItemFocusNode = FocusNode(debugLabel: 'detail_first_item');
|
||||
final Map<int, FocusNode> gridItemFocusNodes = {};
|
||||
|
||||
// Focus restoration
|
||||
int? lastFocusedIndex;
|
||||
int contentVersion = 0;
|
||||
int lastFocusedContentVersion = 0;
|
||||
|
||||
// App bar focus state
|
||||
bool isAppBarFocused = false;
|
||||
int appBarFocusedButton = 0; // 0=play, 1=shuffle, 2=delete (or less if fewer buttons)
|
||||
|
||||
// Flag to prevent PopScope from exiting when BACK was handled by a key handler
|
||||
bool backHandledByKeyEvent = false;
|
||||
|
||||
/// Number of app bar buttons (override if different from 3)
|
||||
int get appBarButtonCount => 3;
|
||||
|
||||
/// Called when items are available and we want to check if focus should be set
|
||||
bool get hasItems;
|
||||
|
||||
/// Called to get the list of app bar button configurations
|
||||
List<AppBarButtonConfig> getAppBarButtons();
|
||||
|
||||
/// Dispose focus-related resources. Call this from your dispose() method.
|
||||
void disposeFocusResources() {
|
||||
scrollController.dispose();
|
||||
playButtonFocusNode.dispose();
|
||||
shuffleButtonFocusNode.dispose();
|
||||
deleteButtonFocusNode.dispose();
|
||||
firstItemFocusNode.dispose();
|
||||
for (final node in gridItemFocusNodes.values) {
|
||||
node.dispose();
|
||||
}
|
||||
gridItemFocusNodes.clear();
|
||||
}
|
||||
|
||||
/// Get or create a focus node for a grid item at the given index
|
||||
FocusNode getGridItemFocusNode(int index) {
|
||||
return gridItemFocusNodes.putIfAbsent(index, () => FocusNode(debugLabel: 'detail_grid_item_$index'));
|
||||
}
|
||||
|
||||
/// Navigate from content to app bar
|
||||
void navigateToAppBar() {
|
||||
setState(() {
|
||||
isAppBarFocused = true;
|
||||
appBarFocusedButton = 0;
|
||||
});
|
||||
_focusAppBarButton(0);
|
||||
// Scroll to top to show the app bar
|
||||
scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
|
||||
}
|
||||
|
||||
/// Handle BACK key from content - navigate to app bar and set flag to prevent PopScope exit
|
||||
void handleBackFromContent() {
|
||||
backHandledByKeyEvent = true;
|
||||
navigateToAppBar();
|
||||
}
|
||||
|
||||
/// Navigate focus from app bar down to the grid
|
||||
void navigateToGrid() {
|
||||
if (!hasItems) return;
|
||||
|
||||
// Check if we should restore focus to the last focused item
|
||||
final shouldRestoreFocus =
|
||||
lastFocusedIndex != null && lastFocusedContentVersion == contentVersion && lastFocusedIndex! >= 0;
|
||||
|
||||
final targetIndex = shouldRestoreFocus ? lastFocusedIndex! : 0;
|
||||
|
||||
setState(() {
|
||||
isAppBarFocused = false;
|
||||
});
|
||||
|
||||
if (targetIndex == 0) {
|
||||
firstItemFocusNode.requestFocus();
|
||||
} else {
|
||||
getGridItemFocusNode(targetIndex).requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle back navigation for PopScope. Returns true if should pop.
|
||||
bool handleBackNavigation() {
|
||||
// If BACK was already handled by a key event, don't pop
|
||||
if (backHandledByKeyEvent) {
|
||||
backHandledByKeyEvent = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isAppBarFocused) {
|
||||
// Already on app bar, allow exit
|
||||
return true;
|
||||
} else {
|
||||
// Focus app bar first
|
||||
navigateToAppBar();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Focus a specific app bar button by index
|
||||
void _focusAppBarButton(int index) {
|
||||
switch (index) {
|
||||
case 0:
|
||||
playButtonFocusNode.requestFocus();
|
||||
break;
|
||||
case 1:
|
||||
shuffleButtonFocusNode.requestFocus();
|
||||
break;
|
||||
case 2:
|
||||
deleteButtonFocusNode.requestFocus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle key events when app bar is focused
|
||||
KeyEventResult handleAppBarKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
final maxButton = appBarButtonCount - 1;
|
||||
|
||||
final backResult = handleBackKeyAction(event, () => Navigator.pop(context));
|
||||
if (backResult != KeyEventResult.ignored) {
|
||||
return backResult;
|
||||
}
|
||||
|
||||
if (event is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
|
||||
if (key.isLeftKey && appBarFocusedButton > 0) {
|
||||
setState(() => appBarFocusedButton--);
|
||||
_focusAppBarButton(appBarFocusedButton);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isRightKey && appBarFocusedButton < maxButton) {
|
||||
setState(() => appBarFocusedButton++);
|
||||
_focusAppBarButton(appBarFocusedButton);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isDownKey) {
|
||||
// Return focus to grid
|
||||
navigateToGrid();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isSelectKey) {
|
||||
final buttons = getAppBarButtons();
|
||||
if (appBarFocusedButton < buttons.length) {
|
||||
buttons[appBarFocusedButton].onPressed();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
/// Build focusable app bar action widgets
|
||||
List<Widget> buildFocusableAppBarActions() {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
final buttons = getAppBarButtons();
|
||||
|
||||
return buttons.asMap().entries.map((entry) {
|
||||
final index = entry.key;
|
||||
final config = entry.value;
|
||||
final isFocused = isKeyboardMode && isAppBarFocused && appBarFocusedButton == index;
|
||||
|
||||
FocusNode focusNode;
|
||||
switch (index) {
|
||||
case 0:
|
||||
focusNode = playButtonFocusNode;
|
||||
break;
|
||||
case 1:
|
||||
focusNode = shuffleButtonFocusNode;
|
||||
break;
|
||||
case 2:
|
||||
focusNode = deleteButtonFocusNode;
|
||||
break;
|
||||
default:
|
||||
focusNode = FocusNode();
|
||||
}
|
||||
|
||||
return Focus(
|
||||
focusNode: focusNode,
|
||||
onKeyEvent: handleAppBarKeyEvent,
|
||||
child: Container(
|
||||
decoration: isFocused
|
||||
? BoxDecoration(color: colorScheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(20))
|
||||
: null,
|
||||
child: IconButton(
|
||||
icon: AppIcon(config.icon, fill: 1),
|
||||
tooltip: config.tooltip,
|
||||
onPressed: config.onPressed,
|
||||
color: config.color,
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
/// Auto-focus first item after load if in keyboard mode.
|
||||
/// Call this from loadItems() after items are loaded.
|
||||
void autoFocusFirstItemAfterLoad() {
|
||||
if (mounted && hasItems) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
if (InputModeTracker.isKeyboardMode(context)) {
|
||||
setState(() {
|
||||
isAppBarFocused = false;
|
||||
});
|
||||
firstItemFocusNode.requestFocus();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Track focus on a grid item. Call from onFocusChange of grid items.
|
||||
void trackGridItemFocus(int index, bool hasFocus) {
|
||||
if (hasFocus) {
|
||||
lastFocusedIndex = index;
|
||||
lastFocusedContentVersion = contentVersion;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:plezy/widgets/app_icon.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../models/plex_hub.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_sort.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../services/settings_service.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../widgets/media_grid_sliver.dart';
|
||||
@@ -245,11 +248,33 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
|
||||
else if (_filteredItems.isEmpty)
|
||||
SliverFillRemaining(child: Center(child: Text(t.hubDetail.noItemsFound)))
|
||||
else
|
||||
MediaGridSliver(
|
||||
items: _filteredItems,
|
||||
onRefresh: _handleItemRefresh,
|
||||
usePaddingAwareExtent: true,
|
||||
horizontalPadding: 16,
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final episodePosterMode = context.watch<SettingsProvider>().episodePosterMode;
|
||||
|
||||
// Determine hub content type for layout decisions
|
||||
final hasEpisodes = _filteredItems.any((item) => item.usesWideAspectRatio(episodePosterMode));
|
||||
final hasNonEpisodes = _filteredItems.any((item) => !item.usesWideAspectRatio(episodePosterMode));
|
||||
|
||||
// Mixed hub = has both episodes AND non-episodes
|
||||
final isMixedHub = hasEpisodes && hasNonEpisodes;
|
||||
|
||||
// Episode-only = all items are episodes with thumbnails
|
||||
final isEpisodeOnlyHub = hasEpisodes && !hasNonEpisodes;
|
||||
|
||||
// Use 16:9 for episode-only hubs OR mixed hubs (with episode thumbnail mode)
|
||||
final useWideLayout =
|
||||
episodePosterMode == EpisodePosterMode.episodeThumbnail && (isEpisodeOnlyHub || isMixedHub);
|
||||
|
||||
return MediaGridSliver(
|
||||
items: _filteredItems,
|
||||
onRefresh: _handleItemRefresh,
|
||||
usePaddingAwareExtent: true,
|
||||
horizontalPadding: 16,
|
||||
useWideAspectRatio: useWideLayout,
|
||||
mixedHubContext: isMixedHub,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -4,6 +4,25 @@ import '../../providers/settings_provider.dart';
|
||||
import '../../services/settings_service.dart' show ViewMode, LibraryDensity;
|
||||
import '../../utils/grid_size_calculator.dart';
|
||||
import '../../utils/layout_constants.dart';
|
||||
import '../main_screen.dart';
|
||||
|
||||
/// Context passed to the item builder with navigation information.
|
||||
class GridItemContext {
|
||||
/// Whether this item is in the first row of the grid.
|
||||
final bool isFirstRow;
|
||||
|
||||
/// Whether this item is in the first column of the grid.
|
||||
final bool isFirstColumn;
|
||||
|
||||
/// Callback to navigate to the sidebar (for first-column items).
|
||||
final VoidCallback? navigateToSidebar;
|
||||
|
||||
const GridItemContext({
|
||||
required this.isFirstRow,
|
||||
required this.isFirstColumn,
|
||||
this.navigateToSidebar,
|
||||
});
|
||||
}
|
||||
|
||||
/// A widget that automatically switches between grid and list view
|
||||
/// based on user settings, providing a consistent layout pattern
|
||||
@@ -14,8 +33,9 @@ class AdaptiveMediaGrid<T> extends StatelessWidget {
|
||||
/// The list of items to display
|
||||
final List<T> items;
|
||||
|
||||
/// Builder function for each item in the grid/list
|
||||
final Widget Function(BuildContext context, T item, int index) itemBuilder;
|
||||
/// Builder function for each item in the grid/list.
|
||||
/// Receives the item, index, and optional grid context with navigation info.
|
||||
final Widget Function(BuildContext context, T item, int index, [GridItemContext? gridContext]) itemBuilder;
|
||||
|
||||
/// Callback when the list needs to be refreshed
|
||||
final VoidCallback? onRefresh;
|
||||
@@ -32,6 +52,9 @@ class AdaptiveMediaGrid<T> extends StatelessWidget {
|
||||
/// Callback when back button is pressed (for hierarchical navigation)
|
||||
final VoidCallback? onBack;
|
||||
|
||||
/// Whether to enable sidebar navigation for first-column items.
|
||||
final bool enableSidebarNavigation;
|
||||
|
||||
const AdaptiveMediaGrid({
|
||||
super.key,
|
||||
required this.items,
|
||||
@@ -41,6 +64,7 @@ class AdaptiveMediaGrid<T> extends StatelessWidget {
|
||||
this.childAspectRatio,
|
||||
this.firstItemFocusNode,
|
||||
this.onBack,
|
||||
this.enableSidebarNavigation = false,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -52,28 +76,79 @@ class AdaptiveMediaGrid<T> extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
// Extra top padding for focus decoration (scale + border extends beyond item bounds)
|
||||
static const double _focusDecorationPadding = 8.0;
|
||||
|
||||
/// Navigate focus to the sidebar
|
||||
void _navigateToSidebar(BuildContext context) {
|
||||
MainScreenFocusScope.of(context)?.focusSidebar();
|
||||
}
|
||||
|
||||
/// Calculate column count based on actual available width.
|
||||
/// Uses the same formula as Flutter's SliverGridDelegateWithMaxCrossAxisExtent.
|
||||
int _calculateColumnCount(double availableWidth, double maxCrossAxisExtent) {
|
||||
final crossAxisSpacing = GridLayoutConstants.crossAxisSpacing;
|
||||
return ((availableWidth + crossAxisSpacing) / (maxCrossAxisExtent + crossAxisSpacing)).ceil().clamp(1, 100);
|
||||
}
|
||||
|
||||
/// Builds either a list or grid view based on the view mode
|
||||
Widget _buildItemsView(BuildContext context, ViewMode viewMode, LibraryDensity density) {
|
||||
final effectivePadding = padding ?? GridLayoutConstants.gridPadding;
|
||||
final basePadding = padding ?? GridLayoutConstants.gridPadding;
|
||||
// Add extra top padding for focus decoration of first row items
|
||||
final effectivePadding = basePadding.copyWith(top: basePadding.top + _focusDecorationPadding);
|
||||
final effectiveAspectRatio = childAspectRatio ?? GridLayoutConstants.posterAspectRatio;
|
||||
|
||||
if (viewMode == ViewMode.list) {
|
||||
// In list view, all items are in a single column (first column)
|
||||
return ListView.builder(
|
||||
padding: effectivePadding,
|
||||
// Allow focus decoration to render outside scroll bounds
|
||||
clipBehavior: Clip.none,
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) => itemBuilder(context, items[index], index),
|
||||
itemBuilder: (ctx, index) {
|
||||
final gridContext = enableSidebarNavigation
|
||||
? GridItemContext(
|
||||
isFirstRow: index == 0,
|
||||
isFirstColumn: true, // List view = single column
|
||||
navigateToSidebar: () => _navigateToSidebar(context),
|
||||
)
|
||||
: null;
|
||||
return itemBuilder(ctx, items[index], index, gridContext);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
return GridView.builder(
|
||||
padding: effectivePadding,
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(context, density),
|
||||
childAspectRatio: effectiveAspectRatio,
|
||||
crossAxisSpacing: GridLayoutConstants.crossAxisSpacing,
|
||||
mainAxisSpacing: GridLayoutConstants.mainAxisSpacing,
|
||||
),
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) => itemBuilder(context, items[index], index),
|
||||
final maxCrossAxisExtent = GridSizeCalculator.getMaxCrossAxisExtent(context, density);
|
||||
final horizontalPadding = effectivePadding.left + effectivePadding.right;
|
||||
|
||||
// Use LayoutBuilder to get the actual available width (accounting for sidebar, etc.)
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final availableWidth = constraints.maxWidth - horizontalPadding;
|
||||
final columnCount = _calculateColumnCount(availableWidth, maxCrossAxisExtent);
|
||||
|
||||
return GridView.builder(
|
||||
padding: effectivePadding,
|
||||
// Allow focus decoration to render outside scroll bounds
|
||||
clipBehavior: Clip.none,
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: maxCrossAxisExtent,
|
||||
childAspectRatio: effectiveAspectRatio,
|
||||
crossAxisSpacing: GridLayoutConstants.crossAxisSpacing,
|
||||
mainAxisSpacing: GridLayoutConstants.mainAxisSpacing,
|
||||
),
|
||||
itemCount: items.length,
|
||||
itemBuilder: (ctx, index) {
|
||||
final gridContext = enableSidebarNavigation
|
||||
? GridItemContext(
|
||||
isFirstRow: GridSizeCalculator.isFirstRow(index, columnCount),
|
||||
isFirstColumn: GridSizeCalculator.isFirstColumn(index, columnCount),
|
||||
navigateToSidebar: () => _navigateToSidebar(context),
|
||||
)
|
||||
: null;
|
||||
return itemBuilder(ctx, items[index], index, gridContext);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,14 @@ import 'package:provider/provider.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import '../../focus/dpad_navigator.dart';
|
||||
import '../../focus/input_mode_tracker.dart';
|
||||
import '../../focus/key_event_utils.dart';
|
||||
import '../../services/gamepad_service.dart';
|
||||
import '../../../services/plex_client.dart';
|
||||
import '../../models/plex_library.dart';
|
||||
import '../../models/plex_metadata.dart';
|
||||
import '../../models/plex_sort.dart';
|
||||
import '../../providers/hidden_libraries_provider.dart';
|
||||
import '../../providers/libraries_provider.dart';
|
||||
import '../../providers/multi_server_provider.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../../utils/platform_detector.dart';
|
||||
@@ -81,8 +83,6 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
final _collectionsTabKey = GlobalKey<State<LibraryCollectionsTab>>();
|
||||
final _playlistsTabKey = GlobalKey<State<LibraryPlaylistsTab>>();
|
||||
|
||||
List<PlexLibrary> _allLibraries = []; // All libraries from API (unfiltered)
|
||||
bool _isLoadingLibraries = true;
|
||||
String? _errorMessage;
|
||||
String? _selectedLibraryGlobalKey;
|
||||
bool _isInitialLoad = true;
|
||||
@@ -115,18 +115,69 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
final _collectionsTabChipFocusNode = FocusNode(debugLabel: 'tab_chip_collections');
|
||||
final _playlistsTabChipFocusNode = FocusNode(debugLabel: 'tab_chip_playlists');
|
||||
|
||||
// Scroll controller for the outer CustomScrollView
|
||||
final ScrollController _outerScrollController = ScrollController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tabController = TabController(length: 4, vsync: this);
|
||||
_tabController.addListener(_onTabChanged);
|
||||
_loadLibraries();
|
||||
|
||||
// Initialize with libraries from the provider
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_initializeWithLibraries();
|
||||
});
|
||||
|
||||
// Register L1/R1 callbacks for tab navigation
|
||||
GamepadService.onL1Pressed = _goToPreviousTab;
|
||||
GamepadService.onR1Pressed = _goToNextTab;
|
||||
}
|
||||
|
||||
/// Initialize the screen with libraries from the provider.
|
||||
/// This handles initial library selection and content loading.
|
||||
Future<void> _initializeWithLibraries() async {
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
final hiddenLibrariesProvider = context.read<HiddenLibrariesProvider>();
|
||||
final allLibraries = librariesProvider.libraries;
|
||||
|
||||
if (allLibraries.isEmpty) {
|
||||
// No libraries available yet
|
||||
return;
|
||||
}
|
||||
|
||||
// Compute visible libraries for initial load
|
||||
final hiddenKeys = hiddenLibrariesProvider.hiddenLibraryKeys;
|
||||
final visibleLibraries = allLibraries.where((lib) => !hiddenKeys.contains(lib.globalKey)).toList();
|
||||
|
||||
// Load saved preferences
|
||||
final storage = await StorageService.getInstance();
|
||||
final savedLibraryKey = storage.getSelectedLibraryKey();
|
||||
|
||||
// Find the library by key in visible libraries
|
||||
String? libraryGlobalKeyToLoad;
|
||||
if (savedLibraryKey != null) {
|
||||
// Check if saved library exists and is visible
|
||||
final libraryExists = visibleLibraries.any((lib) => lib.globalKey == savedLibraryKey);
|
||||
if (libraryExists) {
|
||||
libraryGlobalKeyToLoad = savedLibraryKey;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to first visible library if saved key not found
|
||||
if (libraryGlobalKeyToLoad == null && visibleLibraries.isNotEmpty) {
|
||||
libraryGlobalKeyToLoad = visibleLibraries.first.globalKey;
|
||||
}
|
||||
|
||||
if (libraryGlobalKeyToLoad != null && mounted) {
|
||||
final savedFilters = storage.getLibraryFilters(sectionId: libraryGlobalKeyToLoad);
|
||||
if (savedFilters.isNotEmpty) {
|
||||
_selectedFilters = Map.from(savedFilters);
|
||||
}
|
||||
_loadLibraryContent(libraryGlobalKeyToLoad);
|
||||
}
|
||||
}
|
||||
|
||||
void _goToPreviousTab() {
|
||||
if (_tabController.index > 0) {
|
||||
setState(() {
|
||||
@@ -167,32 +218,27 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
/// Focus the first item in the currently active tab
|
||||
/// Focus the first item in the currently active tab.
|
||||
/// Used for initial load and tab switching - focuses the grid content directly.
|
||||
void _focusCurrentTab() {
|
||||
// Don't focus during tab animations - wait for animation to complete
|
||||
// This prevents race conditions during focus restoration
|
||||
if (_tabController.indexIsChanging) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-enable auto-focus since user is navigating into tab content
|
||||
setState(() {
|
||||
_suppressAutoFocus = false;
|
||||
});
|
||||
// Only call setState if the value actually changes to avoid unnecessary rebuilds
|
||||
if (_suppressAutoFocus) {
|
||||
setState(() {
|
||||
_suppressAutoFocus = false;
|
||||
});
|
||||
}
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
|
||||
State? tabState;
|
||||
switch (_tabController.index) {
|
||||
case 0:
|
||||
tabState = _recommendedTabKey.currentState;
|
||||
break;
|
||||
case 1:
|
||||
tabState = _browseTabKey.currentState;
|
||||
break;
|
||||
case 2:
|
||||
tabState = _collectionsTabKey.currentState;
|
||||
break;
|
||||
case 3:
|
||||
tabState = _playlistsTabKey.currentState;
|
||||
break;
|
||||
}
|
||||
|
||||
final tabState = _getTabState(_tabController.index);
|
||||
if (tabState != null) {
|
||||
(tabState as dynamic).focusFirstItem();
|
||||
} else {
|
||||
@@ -207,27 +253,62 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
|
||||
/// Focus without additional frame delay (used for retry)
|
||||
void _focusCurrentTabImmediate() {
|
||||
State? tabState;
|
||||
switch (_tabController.index) {
|
||||
case 0:
|
||||
tabState = _recommendedTabKey.currentState;
|
||||
break;
|
||||
case 1:
|
||||
tabState = _browseTabKey.currentState;
|
||||
break;
|
||||
case 2:
|
||||
tabState = _collectionsTabKey.currentState;
|
||||
break;
|
||||
case 3:
|
||||
tabState = _playlistsTabKey.currentState;
|
||||
break;
|
||||
}
|
||||
|
||||
final tabState = _getTabState(_tabController.index);
|
||||
if (tabState != null) {
|
||||
(tabState as dynamic).focusFirstItem();
|
||||
}
|
||||
}
|
||||
|
||||
/// Focus tab content when navigating DOWN from the tab bar.
|
||||
/// For browse tab, this focuses the chips bar first so DOWN navigates to grid.
|
||||
/// For other tabs, focuses the first item directly.
|
||||
void _focusCurrentTabFromTabBar() {
|
||||
if (_tabController.indexIsChanging) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_suppressAutoFocus) {
|
||||
setState(() {
|
||||
_suppressAutoFocus = false;
|
||||
});
|
||||
}
|
||||
|
||||
// Scroll outer view to top to ensure tab content (including chips bar) is visible
|
||||
if (_outerScrollController.hasClients && _outerScrollController.offset > 0) {
|
||||
_outerScrollController.jumpTo(0);
|
||||
}
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
|
||||
final tabState = _getTabState(_tabController.index);
|
||||
if (tabState != null) {
|
||||
// Browse tab has a chips bar - focus that first so DOWN navigates to grid
|
||||
if (_tabController.index == 1) {
|
||||
(tabState as dynamic).focusChipsBar();
|
||||
} else {
|
||||
(tabState as dynamic).focusFirstItem();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Get the state for a tab by index
|
||||
State? _getTabState(int index) {
|
||||
switch (index) {
|
||||
case 0:
|
||||
return _recommendedTabKey.currentState;
|
||||
case 1:
|
||||
return _browseTabKey.currentState;
|
||||
case 2:
|
||||
return _collectionsTabKey.currentState;
|
||||
case 3:
|
||||
return _playlistsTabKey.currentState;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle when a tab's data has finished loading
|
||||
void _handleTabDataLoaded(int tabIndex) {
|
||||
// Track that this tab has loaded
|
||||
@@ -294,6 +375,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
_tabController.removeListener(_onTabChanged);
|
||||
_tabController.dispose();
|
||||
_cancelToken?.cancel();
|
||||
_outerScrollController.dispose();
|
||||
_recommendedTabChipFocusNode.dispose();
|
||||
_browseTabChipFocusNode.dispose();
|
||||
_collectionsTabChipFocusNode.dispose();
|
||||
@@ -319,118 +401,13 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
}
|
||||
|
||||
/// Check if libraries come from multiple servers
|
||||
bool get _hasMultipleServers {
|
||||
final uniqueServerIds = _allLibraries.where((lib) => lib.serverId != null).map((lib) => lib.serverId).toSet();
|
||||
bool _hasMultipleServers(List<PlexLibrary> libraries) {
|
||||
final uniqueServerIds = libraries.where((lib) => lib.serverId != null).map((lib) => lib.serverId).toSet();
|
||||
return uniqueServerIds.length > 1;
|
||||
}
|
||||
|
||||
Future<void> _loadLibraries() async {
|
||||
// Extract context dependencies before async gap
|
||||
final multiServerProvider = Provider.of<MultiServerProvider>(context, listen: false);
|
||||
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(context, listen: false);
|
||||
|
||||
setState(() {
|
||||
_isLoadingLibraries = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
// Check if we have any connected servers
|
||||
if (!multiServerProvider.hasConnectedServers) {
|
||||
throw Exception(t.errors.noClientAvailable);
|
||||
}
|
||||
|
||||
final storage = await StorageService.getInstance();
|
||||
|
||||
// Fetch libraries from all servers
|
||||
final allLibraries = await multiServerProvider.aggregationService.getLibrariesFromAllServers();
|
||||
|
||||
// Filter out music libraries (type: 'artist') since music playback is not yet supported
|
||||
// Only show movie and TV show libraries
|
||||
final filteredLibraries = allLibraries.where((lib) => !ContentTypeHelper.isMusicLibrary(lib)).toList();
|
||||
|
||||
// Load saved library order and apply it
|
||||
final savedOrder = storage.getLibraryOrder();
|
||||
final orderedLibraries = _applyLibraryOrder(filteredLibraries, savedOrder);
|
||||
|
||||
_updateState(() {
|
||||
_allLibraries = orderedLibraries; // Store all libraries with ordering applied
|
||||
_isLoadingLibraries = false;
|
||||
});
|
||||
|
||||
if (allLibraries.isNotEmpty) {
|
||||
// Compute visible libraries for initial load
|
||||
final hiddenKeys = hiddenLibrariesProvider.hiddenLibraryKeys;
|
||||
final visibleLibraries = allLibraries.where((lib) => !hiddenKeys.contains(lib.globalKey)).toList();
|
||||
|
||||
// Load saved preferences
|
||||
final savedLibraryKey = storage.getSelectedLibraryKey();
|
||||
|
||||
// Find the library by key in visible libraries
|
||||
String? libraryGlobalKeyToLoad;
|
||||
if (savedLibraryKey != null) {
|
||||
// Check if saved library exists and is visible
|
||||
final libraryExists = visibleLibraries.any((lib) => lib.globalKey == savedLibraryKey);
|
||||
if (libraryExists) {
|
||||
libraryGlobalKeyToLoad = savedLibraryKey;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to first visible library if saved key not found
|
||||
if (libraryGlobalKeyToLoad == null && visibleLibraries.isNotEmpty) {
|
||||
libraryGlobalKeyToLoad = visibleLibraries.first.globalKey;
|
||||
}
|
||||
|
||||
if (libraryGlobalKeyToLoad != null && mounted) {
|
||||
final savedFilters = storage.getLibraryFilters(sectionId: libraryGlobalKeyToLoad);
|
||||
if (savedFilters.isNotEmpty) {
|
||||
_selectedFilters = Map.from(savedFilters);
|
||||
}
|
||||
_loadLibraryContent(libraryGlobalKeyToLoad);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_updateState(() {
|
||||
_errorMessage = _getErrorMessage(e, 'libraries');
|
||||
_isLoadingLibraries = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
List<PlexLibrary> _applyLibraryOrder(List<PlexLibrary> libraries, List<String>? savedOrder) {
|
||||
if (savedOrder == null || savedOrder.isEmpty) {
|
||||
return libraries;
|
||||
}
|
||||
|
||||
// Create a map for quick lookup
|
||||
final libraryMap = {for (var lib in libraries) lib.globalKey: lib};
|
||||
|
||||
// Build ordered list based on saved order
|
||||
final orderedLibraries = <PlexLibrary>[];
|
||||
final addedKeys = <String>{};
|
||||
|
||||
// Add libraries in saved order
|
||||
for (final key in savedOrder) {
|
||||
if (libraryMap.containsKey(key)) {
|
||||
orderedLibraries.add(libraryMap[key]!);
|
||||
addedKeys.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Add any new libraries that weren't in the saved order
|
||||
for (final library in libraries) {
|
||||
if (!addedKeys.contains(library.globalKey)) {
|
||||
orderedLibraries.add(library);
|
||||
}
|
||||
}
|
||||
|
||||
return orderedLibraries;
|
||||
}
|
||||
|
||||
Future<void> _saveLibraryOrder() async {
|
||||
final storage = await StorageService.getInstance();
|
||||
final libraryKeys = _allLibraries.map((lib) => lib.globalKey).toList();
|
||||
await storage.saveLibraryOrder(libraryKeys);
|
||||
/// Notify parent that library order changed
|
||||
void _notifyLibraryOrderChanged() {
|
||||
widget.onLibraryOrderChanged?.call();
|
||||
}
|
||||
|
||||
@@ -441,10 +418,14 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
}
|
||||
|
||||
Future<void> _loadLibraryContent(String libraryGlobalKey) async {
|
||||
// Get libraries from provider
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
final allLibraries = librariesProvider.libraries;
|
||||
|
||||
// Compute visible libraries based on current provider state
|
||||
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(context, listen: false);
|
||||
final hiddenKeys = hiddenLibrariesProvider.hiddenLibraryKeys;
|
||||
final visibleLibraries = _allLibraries.where((lib) => !hiddenKeys.contains(lib.globalKey)).toList();
|
||||
final visibleLibraries = allLibraries.where((lib) => !hiddenKeys.contains(lib.globalKey)).toList();
|
||||
|
||||
// Find the library by key
|
||||
final libraryIndex = visibleLibraries.indexWhere((lib) => lib.globalKey == libraryGlobalKey);
|
||||
@@ -482,13 +463,10 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
if (savedTabIndex != null && savedTabIndex >= 0 && savedTabIndex < 4) {
|
||||
// Set flag to prevent _onTabChanged from triggering focus
|
||||
_isRestoringTab = true;
|
||||
_updateState(() {
|
||||
_tabController.index = savedTabIndex;
|
||||
});
|
||||
// Clear flag after the tab change has been processed
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_isRestoringTab = false;
|
||||
});
|
||||
// Use animateTo with zero duration for instant switch without animation race conditions
|
||||
_tabController.animateTo(savedTabIndex, duration: Duration.zero);
|
||||
// Clear flag synchronously - animateTo with zero duration completes immediately
|
||||
_isRestoringTab = false;
|
||||
}
|
||||
|
||||
// Focus is handled by onDataLoaded callbacks from each tab.
|
||||
@@ -641,7 +619,8 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
// Public method to refresh content (for normal navigation)
|
||||
@override
|
||||
void refresh() {
|
||||
_loadLibraries();
|
||||
// Reinitialize with current libraries
|
||||
_initializeWithLibraries();
|
||||
}
|
||||
|
||||
// Refresh the currently active tab
|
||||
@@ -678,14 +657,19 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
@override
|
||||
void fullRefresh() {
|
||||
appLogger.d('LibrariesScreen.fullRefresh() called - reloading all content');
|
||||
// Reload libraries and clear any selected library/filters
|
||||
// Clear local state
|
||||
_selectedLibraryGlobalKey = null;
|
||||
_selectedFilters.clear();
|
||||
_items.clear();
|
||||
_loadLibraries();
|
||||
_errorMessage = null;
|
||||
setState(() {});
|
||||
|
||||
// Reinitialize with current libraries from provider
|
||||
_initializeWithLibraries();
|
||||
}
|
||||
|
||||
Future<void> _toggleLibraryVisibility(PlexLibrary library) async {
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(context, listen: false);
|
||||
final isHidden = hiddenLibrariesProvider.hiddenLibraryKeys.contains(library.globalKey);
|
||||
|
||||
@@ -700,7 +684,8 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
// If we just hid the selected library, select the first visible one
|
||||
if (isCurrentlySelected) {
|
||||
// Compute visible libraries after hiding
|
||||
final visibleLibraries = _allLibraries
|
||||
final allLibraries = librariesProvider.libraries;
|
||||
final visibleLibraries = allLibraries
|
||||
.where((lib) => !hiddenLibrariesProvider.hiddenLibraryKeys.contains(lib.globalKey))
|
||||
.toList();
|
||||
|
||||
@@ -768,25 +753,43 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
}
|
||||
|
||||
void _showLibraryManagementSheet() {
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(context, listen: false);
|
||||
final allLibraries = librariesProvider.libraries;
|
||||
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => _LibraryManagementSheet(
|
||||
allLibraries: List.from(_allLibraries),
|
||||
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
|
||||
onReorder: (reorderedLibraries) {
|
||||
setState(() {
|
||||
_allLibraries = reorderedLibraries;
|
||||
});
|
||||
_saveLibraryOrder();
|
||||
},
|
||||
onToggleVisibility: _toggleLibraryVisibility,
|
||||
getLibraryMenuItems: _getLibraryMenuItems,
|
||||
onLibraryMenuAction: _handleLibraryMenuAction,
|
||||
),
|
||||
);
|
||||
if (PlatformDetector.isTV()) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => _LibraryManagementSheet(
|
||||
isDialog: true,
|
||||
allLibraries: List.from(allLibraries),
|
||||
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
|
||||
onReorder: (reorderedLibraries) {
|
||||
librariesProvider.updateLibraryOrder(reorderedLibraries);
|
||||
_notifyLibraryOrderChanged();
|
||||
},
|
||||
onToggleVisibility: _toggleLibraryVisibility,
|
||||
getLibraryMenuItems: _getLibraryMenuItems,
|
||||
onLibraryMenuAction: _handleLibraryMenuAction,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => _LibraryManagementSheet(
|
||||
allLibraries: List.from(allLibraries),
|
||||
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
|
||||
onReorder: (reorderedLibraries) {
|
||||
librariesProvider.updateLibraryOrder(reorderedLibraries);
|
||||
_notifyLibraryOrderChanged();
|
||||
},
|
||||
onToggleVisibility: _toggleLibraryVisibility,
|
||||
getLibraryMenuItems: _getLibraryMenuItems,
|
||||
onLibraryMenuAction: _handleLibraryMenuAction,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _performLibraryAction({
|
||||
@@ -942,7 +945,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
});
|
||||
_getTabChipFocusNode(newIndex).requestFocus();
|
||||
}
|
||||
: null,
|
||||
: _onTabBarBack,
|
||||
onNavigateRight: index < tabCount - 1
|
||||
? () {
|
||||
final newIndex = index + 1;
|
||||
@@ -953,7 +956,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
_getTabChipFocusNode(newIndex).requestFocus();
|
||||
}
|
||||
: null,
|
||||
onNavigateDown: _focusCurrentTab,
|
||||
onNavigateDown: _focusCurrentTabFromTabBar,
|
||||
onBack: _onTabBarBack,
|
||||
);
|
||||
}
|
||||
@@ -1006,7 +1009,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
children: [
|
||||
AppIcon(ContentTypeHelper.getLibraryIcon(selectedLibrary.type), fill: 1, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
if (_hasMultipleServers && selectedLibrary.serverName != null)
|
||||
if (_hasMultipleServers(visibleLibraries) && selectedLibrary.serverName != null)
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -1032,26 +1035,31 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Watch libraries provider for updates
|
||||
final librariesProvider = context.watch<LibrariesProvider>();
|
||||
final allLibraries = librariesProvider.libraries;
|
||||
final isLoadingLibraries = librariesProvider.isLoading;
|
||||
|
||||
// Watch for hidden libraries changes to trigger rebuild
|
||||
final hiddenLibrariesProvider = context.watch<HiddenLibrariesProvider>();
|
||||
final hiddenKeys = hiddenLibrariesProvider.hiddenLibraryKeys;
|
||||
|
||||
// Compute visible libraries (filtered from all libraries)
|
||||
final visibleLibraries = _allLibraries.where((lib) => !hiddenKeys.contains(lib.globalKey)).toList();
|
||||
final visibleLibraries = allLibraries.where((lib) => !hiddenKeys.contains(lib.globalKey)).toList();
|
||||
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
controller: _outerScrollController,
|
||||
slivers: [
|
||||
DesktopSliverAppBar(
|
||||
title: _buildAppBarTitle(visibleLibraries),
|
||||
floating: true,
|
||||
pinned: true,
|
||||
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
|
||||
surfaceTintColor: Colors.transparent,
|
||||
shadowColor: Colors.transparent,
|
||||
scrolledUnderElevation: 0,
|
||||
actions: [
|
||||
if (_allLibraries.isNotEmpty)
|
||||
if (allLibraries.isNotEmpty)
|
||||
IconButton(
|
||||
icon: const AppIcon(Symbols.edit_rounded, fill: 1),
|
||||
tooltip: t.libraries.manageLibraries,
|
||||
@@ -1064,14 +1072,17 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_isLoadingLibraries)
|
||||
if (isLoadingLibraries)
|
||||
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
|
||||
else if (_errorMessage != null && visibleLibraries.isEmpty)
|
||||
SliverFillRemaining(
|
||||
child: ErrorStateWidget(
|
||||
message: _errorMessage!,
|
||||
icon: Symbols.error_outline_rounded,
|
||||
onRetry: _loadLibraries,
|
||||
onRetry: () {
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
librariesProvider.refresh();
|
||||
},
|
||||
),
|
||||
)
|
||||
else if (visibleLibraries.isEmpty)
|
||||
@@ -1107,10 +1118,13 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
child: TabBarView(
|
||||
key: ValueKey(_selectedLibraryGlobalKey),
|
||||
controller: _tabController,
|
||||
// Disable swipe on desktop - trackpad scrolling triggers accidental tab switches
|
||||
// See: https://github.com/flutter/flutter/issues/11132
|
||||
physics: PlatformDetector.isDesktop(context) ? const NeverScrollableScrollPhysics() : null,
|
||||
children: [
|
||||
LibraryRecommendedTab(
|
||||
key: _recommendedTabKey,
|
||||
library: _allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
|
||||
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
|
||||
isActive: _tabController.index == 0,
|
||||
suppressAutoFocus: _suppressAutoFocus,
|
||||
onDataLoaded: () => _handleTabDataLoaded(0),
|
||||
@@ -1118,7 +1132,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
),
|
||||
LibraryBrowseTab(
|
||||
key: _browseTabKey,
|
||||
library: _allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
|
||||
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
|
||||
isActive: _tabController.index == 1,
|
||||
suppressAutoFocus: _suppressAutoFocus,
|
||||
onDataLoaded: () => _handleTabDataLoaded(1),
|
||||
@@ -1126,7 +1140,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
),
|
||||
LibraryCollectionsTab(
|
||||
key: _collectionsTabKey,
|
||||
library: _allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
|
||||
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
|
||||
isActive: _tabController.index == 2,
|
||||
suppressAutoFocus: _suppressAutoFocus,
|
||||
onDataLoaded: () => _handleTabDataLoaded(2),
|
||||
@@ -1134,7 +1148,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
),
|
||||
LibraryPlaylistsTab(
|
||||
key: _playlistsTabKey,
|
||||
library: _allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
|
||||
library: allLibraries.firstWhere((lib) => lib.globalKey == _selectedLibraryGlobalKey),
|
||||
isActive: _tabController.index == 3,
|
||||
suppressAutoFocus: _suppressAutoFocus,
|
||||
onDataLoaded: () => _handleTabDataLoaded(3),
|
||||
@@ -1151,6 +1165,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
}
|
||||
|
||||
class _LibraryManagementSheet extends StatefulWidget {
|
||||
final bool isDialog;
|
||||
final List<PlexLibrary> allLibraries;
|
||||
final Set<String> hiddenLibraryKeys;
|
||||
final Function(List<PlexLibrary>) onReorder;
|
||||
@@ -1159,6 +1174,7 @@ class _LibraryManagementSheet extends StatefulWidget {
|
||||
final void Function(String action, PlexLibrary library) onLibraryMenuAction;
|
||||
|
||||
const _LibraryManagementSheet({
|
||||
this.isDialog = false,
|
||||
required this.allLibraries,
|
||||
required this.hiddenLibraryKeys,
|
||||
required this.onReorder,
|
||||
@@ -1181,6 +1197,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
int? _originalIndex; // Original position before move (for cancel)
|
||||
List<PlexLibrary>? _originalOrder; // Original order before move (for cancel)
|
||||
final FocusNode _listFocusNode = FocusNode();
|
||||
final Map<int, GlobalKey> _tileKeys = {}; // For dialog mode scroll-into-view
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -1194,11 +1211,43 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
if (event is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
void _ensureFocusedVisible() {
|
||||
if (!widget.isDialog) return;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
final key = _tileKeys[_focusedIndex];
|
||||
final context = key?.currentContext;
|
||||
if (context != null) {
|
||||
Scrollable.ensureVisible(context, alignment: 0.25, duration: const Duration(milliseconds: 200));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
|
||||
final backResult = handleBackKeyAction(event, () {
|
||||
if (_movingIndex != null) {
|
||||
// Cancel move - restore original position
|
||||
setState(() {
|
||||
if (_originalOrder != null) {
|
||||
_tempLibraries = List.from(_originalOrder!);
|
||||
}
|
||||
_focusedIndex = _originalIndex ?? 0;
|
||||
_movingIndex = null;
|
||||
_originalIndex = null;
|
||||
_originalOrder = null;
|
||||
});
|
||||
} else {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
});
|
||||
if (backResult != KeyEventResult.ignored) {
|
||||
return backResult;
|
||||
}
|
||||
|
||||
if (event is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
|
||||
if (_movingIndex != null) {
|
||||
// Move mode - arrows reorder the item
|
||||
if (key.isUpKey && _movingIndex! > 0) {
|
||||
@@ -1229,19 +1278,6 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
});
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isBackKey) {
|
||||
// Cancel move - restore original position
|
||||
setState(() {
|
||||
if (_originalOrder != null) {
|
||||
_tempLibraries = List.from(_originalOrder!);
|
||||
}
|
||||
_focusedIndex = _originalIndex ?? 0;
|
||||
_movingIndex = null;
|
||||
_originalIndex = null;
|
||||
_originalOrder = null;
|
||||
});
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
} else {
|
||||
// Navigation mode
|
||||
if (key.isUpKey && _focusedIndex > 0) {
|
||||
@@ -1249,6 +1285,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
_focusedIndex--;
|
||||
_focusedColumn = 0; // Reset to row when changing rows
|
||||
});
|
||||
_ensureFocusedVisible();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isDownKey && _focusedIndex < _tempLibraries.length - 1) {
|
||||
@@ -1256,6 +1293,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
_focusedIndex++;
|
||||
_focusedColumn = 0; // Reset to row when changing rows
|
||||
});
|
||||
_ensureFocusedVisible();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isLeftKey && _focusedColumn > 0) {
|
||||
@@ -1285,10 +1323,6 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isBackKey) {
|
||||
Navigator.pop(context);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
@@ -1301,6 +1335,9 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
}
|
||||
final library = _tempLibraries.removeAt(oldIndex);
|
||||
_tempLibraries.insert(newIndex, library);
|
||||
if (widget.isDialog) {
|
||||
_tileKeys.clear();
|
||||
}
|
||||
});
|
||||
// Apply immediately
|
||||
widget.onReorder(_tempLibraries);
|
||||
@@ -1374,6 +1411,32 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
final hiddenLibrariesProvider = context.watch<HiddenLibrariesProvider>();
|
||||
final hiddenLibraryKeys = hiddenLibrariesProvider.hiddenLibraryKeys;
|
||||
|
||||
if (widget.isDialog) {
|
||||
return Dialog(
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Row(
|
||||
children: [
|
||||
const AppIcon(Symbols.edit_rounded, fill: 1),
|
||||
const SizedBox(width: 12),
|
||||
Text(t.libraries.manageLibraries),
|
||||
],
|
||||
),
|
||||
automaticallyImplyLeading: false,
|
||||
actions: [
|
||||
IconButton(icon: const AppIcon(Symbols.close_rounded, fill: 1), onPressed: () => Navigator.pop(context)),
|
||||
],
|
||||
),
|
||||
body: Focus(
|
||||
focusNode: _listFocusNode,
|
||||
autofocus: InputModeTracker.isKeyboardMode(context),
|
||||
onKeyEvent: _handleKeyEvent,
|
||||
child: _buildFlatLibraryListDialog(hiddenLibraryKeys),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.7,
|
||||
minChildSize: 0.5,
|
||||
@@ -1421,6 +1484,38 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Build library list for dialog (TV) using ListView with scroll-into-view support
|
||||
Widget _buildFlatLibraryListDialog(Set<String> hiddenLibraryKeys) {
|
||||
final nonUniqueNames = _getNonUniqueLibraryNames();
|
||||
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
|
||||
return ReorderableListView.builder(
|
||||
onReorder: _reorderLibraries,
|
||||
itemCount: _tempLibraries.length,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
buildDefaultDragHandles: false,
|
||||
itemBuilder: (context, index) {
|
||||
final library = _tempLibraries[index];
|
||||
final showServerName = nonUniqueNames.contains(library.title) && library.serverName != null;
|
||||
final isFocused = isKeyboardMode && index == _focusedIndex;
|
||||
final isMoving = index == _movingIndex;
|
||||
|
||||
_tileKeys.putIfAbsent(index, () => GlobalKey());
|
||||
|
||||
return _buildLibraryTile(
|
||||
library,
|
||||
index,
|
||||
hiddenLibraryKeys,
|
||||
showServerName: showServerName,
|
||||
isFocused: isFocused,
|
||||
isMoving: isMoving,
|
||||
focusedColumn: isFocused ? _focusedColumn : null,
|
||||
tileKey: _tileKeys[index],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Build flat library list with server subtitle for non-unique names
|
||||
Widget _buildFlatLibraryList(ScrollController scrollController, Set<String> hiddenLibraryKeys) {
|
||||
final nonUniqueNames = _getNonUniqueLibraryNames();
|
||||
@@ -1459,6 +1554,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
bool isFocused = false,
|
||||
bool isMoving = false,
|
||||
int? focusedColumn,
|
||||
Key? tileKey,
|
||||
}) {
|
||||
final isHidden = hiddenLibraryKeys.contains(library.globalKey);
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
@@ -1477,7 +1573,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
final isOptionsButtonFocused = isFocused && focusedColumn == 2;
|
||||
|
||||
return Opacity(
|
||||
key: ValueKey(library.globalKey),
|
||||
key: tileKey ?? ValueKey(library.globalKey),
|
||||
opacity: isHidden ? 0.5 : 1.0,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(color: tileColor),
|
||||
|
||||
@@ -18,9 +18,10 @@ import '../filters_bottom_sheet.dart';
|
||||
import '../sort_bottom_sheet.dart';
|
||||
import '../state_messages.dart';
|
||||
import '../../../services/storage_service.dart';
|
||||
import '../../../services/settings_service.dart' show ViewMode;
|
||||
import '../../../services/settings_service.dart' show ViewMode, EpisodePosterMode;
|
||||
import '../../../mixins/item_updatable.dart';
|
||||
import '../../../i18n/strings.g.dart';
|
||||
import '../../main_screen.dart';
|
||||
import 'base_library_tab.dart';
|
||||
|
||||
/// Browse tab for library screen
|
||||
@@ -82,15 +83,44 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
final FocusNode _filtersChipFocusNode = FocusNode(debugLabel: 'filters_chip');
|
||||
final FocusNode _sortChipFocusNode = FocusNode(debugLabel: 'sort_chip');
|
||||
|
||||
// Focus tracking for grid items
|
||||
int? _lastFocusedIndex;
|
||||
int _contentVersion = 0;
|
||||
int _lastFocusedContentVersion = 0;
|
||||
final Map<int, FocusNode> _gridItemFocusNodes = {};
|
||||
|
||||
// Scroll controller for the CustomScrollView
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_cancelToken?.cancel();
|
||||
_scrollController.dispose();
|
||||
_groupingChipFocusNode.dispose();
|
||||
_filtersChipFocusNode.dispose();
|
||||
_sortChipFocusNode.dispose();
|
||||
// Dispose all grid item focus nodes
|
||||
for (final node in _gridItemFocusNodes.values) {
|
||||
node.dispose();
|
||||
}
|
||||
_gridItemFocusNodes.clear();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Get or create a focus node for a grid item at the given index
|
||||
FocusNode _getGridItemFocusNode(int index) {
|
||||
return _gridItemFocusNodes.putIfAbsent(index, () => FocusNode(debugLabel: 'browse_grid_item_$index'));
|
||||
}
|
||||
|
||||
/// Clean up focus nodes for items that no longer exist
|
||||
void _cleanupFocusNodes() {
|
||||
final keysToRemove = _gridItemFocusNodes.keys.where((index) => index >= items.length).toList();
|
||||
for (final key in keysToRemove) {
|
||||
_gridItemFocusNodes[key]?.dispose();
|
||||
_gridItemFocusNodes.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Override loadData to use our custom _loadContent
|
||||
@override
|
||||
Future<List<PlexMetadata>> loadData() async {
|
||||
@@ -136,6 +166,23 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
}
|
||||
}
|
||||
|
||||
/// Height of the chips bar (padding + chip + padding)
|
||||
static const double _chipsBarHeight = 48.0;
|
||||
|
||||
/// Focus the chips bar (for navigating from tab bar to content).
|
||||
/// Called by libraries screen when pressing DOWN on tab bar.
|
||||
void focusChipsBar() {
|
||||
// If in folders mode, no chips to focus - go directly to folder tree
|
||||
if (_selectedGrouping == 'folders') {
|
||||
focusFirstItem();
|
||||
return;
|
||||
}
|
||||
|
||||
// With Stack layout, chips are always visible on top of the grid.
|
||||
// No need to scroll - just focus the chip.
|
||||
_groupingChipFocusNode.requestFocus();
|
||||
}
|
||||
|
||||
Future<void> _loadContent() async {
|
||||
// Cancel any pending request
|
||||
_cancelToken?.cancel();
|
||||
@@ -219,6 +266,10 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
isLoading = true;
|
||||
if (!loadMore) {
|
||||
items = [];
|
||||
// Increment content version when loading fresh content
|
||||
// This invalidates the last focused index
|
||||
_contentVersion++;
|
||||
_cleanupFocusNodes();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -432,10 +483,22 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
);
|
||||
}
|
||||
|
||||
/// Navigate focus from chips down to the first grid item
|
||||
/// Navigate focus from chips down to the grid item.
|
||||
/// Restores focus to the previously focused item if content hasn't changed.
|
||||
void _navigateToGrid() {
|
||||
if (items.isNotEmpty) {
|
||||
if (items.isEmpty) return;
|
||||
|
||||
// Check if we should restore focus to the last focused item
|
||||
final shouldRestoreFocus =
|
||||
_lastFocusedIndex != null && _lastFocusedContentVersion == _contentVersion && _lastFocusedIndex! < items.length;
|
||||
|
||||
final targetIndex = shouldRestoreFocus ? _lastFocusedIndex! : 0;
|
||||
|
||||
// Use firstItemFocusNode for index 0 (matches _buildMediaCardItem)
|
||||
if (targetIndex == 0) {
|
||||
firstItemFocusNode.requestFocus();
|
||||
} else {
|
||||
_getGridItemFocusNode(targetIndex).requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,103 +507,46 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
_groupingChipFocusNode.requestFocus();
|
||||
}
|
||||
|
||||
/// Calculate the number of columns in the current grid based on screen width
|
||||
int _getGridColumnCount(BuildContext context, SettingsProvider settingsProvider) {
|
||||
final screenWidth = MediaQuery.of(context).size.width - 16; // Subtract padding
|
||||
final maxCrossAxisExtent = GridSizeCalculator.getMaxCrossAxisExtent(context, settingsProvider.libraryDensity);
|
||||
return (screenWidth / maxCrossAxisExtent).floor().clamp(1, 100);
|
||||
}
|
||||
|
||||
/// Check if the given index is in the first row of the grid
|
||||
bool _isFirstRow(int index, int columnCount) {
|
||||
return index < columnCount;
|
||||
/// Navigate focus to the sidebar
|
||||
void _navigateToSidebar() {
|
||||
MainScreenFocusScope.of(context)?.focusSidebar();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
super.build(context); // Required for AutomaticKeepAliveClientMixin
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
// Filter bar with chips
|
||||
Container(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
alignment: Alignment.centerLeft,
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Grouping chip
|
||||
FocusableFilterChip(
|
||||
focusNode: _groupingChipFocusNode,
|
||||
icon: Symbols.category_rounded,
|
||||
label: _getGroupingLabel(_selectedGrouping),
|
||||
onPressed: _showGroupingBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Filters chip
|
||||
if (_filters.isNotEmpty && _selectedGrouping != 'folders')
|
||||
FocusableFilterChip(
|
||||
focusNode: _filtersChipFocusNode,
|
||||
icon: Symbols.filter_alt_rounded,
|
||||
label: _selectedFilters.isEmpty
|
||||
? t.libraries.filters
|
||||
: t.libraries.filtersWithCount(count: _selectedFilters.length),
|
||||
onPressed: _showFiltersBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
if (_filters.isNotEmpty && _selectedGrouping != 'folders') const SizedBox(width: 8),
|
||||
// Sort chip
|
||||
if (_sortOptions.isNotEmpty && _selectedGrouping != 'folders')
|
||||
FocusableFilterChip(
|
||||
focusNode: _sortChipFocusNode,
|
||||
icon: Symbols.sort_rounded,
|
||||
label: _selectedSort?.title ?? t.libraries.sort,
|
||||
onPressed: _showSortBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
],
|
||||
// For folders mode, use FolderTreeView instead of grid/list
|
||||
if (_selectedGrouping == 'folders') {
|
||||
return Column(
|
||||
children: [
|
||||
_buildChipsBar(),
|
||||
Expanded(
|
||||
child: FolderTreeView(
|
||||
libraryKey: widget.library.key,
|
||||
serverId: widget.library.serverId,
|
||||
onRefresh: updateItem,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Content
|
||||
Expanded(child: _buildContent()),
|
||||
// For list/grid modes, use Stack with chips layered on top of grid.
|
||||
// This allows the grid to use Clip.none for focus decorations while
|
||||
// the chips bar (with background) covers any overflow at the top.
|
||||
return Stack(
|
||||
children: [
|
||||
// Grid fills the entire area, with top padding for chips bar
|
||||
Positioned.fill(child: _buildScrollableContent()),
|
||||
// Chips bar on top with solid background
|
||||
Positioned(top: 0, left: 0, right: 0, child: _buildChipsBar()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent() {
|
||||
// Show folder tree view when in folders mode
|
||||
if (_selectedGrouping == 'folders') {
|
||||
return FolderTreeView(libraryKey: widget.library.key, serverId: widget.library.serverId, onRefresh: updateItem);
|
||||
}
|
||||
|
||||
if (isLoading && items.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (errorMessage != null && items.isEmpty) {
|
||||
return ErrorStateWidget(
|
||||
message: errorMessage!,
|
||||
icon: Symbols.error_outline_rounded,
|
||||
onRetry: _loadContent,
|
||||
retryLabel: t.common.retry,
|
||||
);
|
||||
}
|
||||
|
||||
if (items.isEmpty) {
|
||||
return EmptyStateWidget(message: t.libraries.thisLibraryIsEmpty, icon: Symbols.folder_open_rounded);
|
||||
}
|
||||
|
||||
/// Builds the scrollable content (grid/list) with pagination support
|
||||
Widget _buildScrollableContent() {
|
||||
return NotificationListener<ScrollNotification>(
|
||||
onNotification: (notification) {
|
||||
if (notification.metrics.pixels >= notification.metrics.maxScrollExtent - 300 && _hasMoreItems && !isLoading) {
|
||||
@@ -548,38 +554,165 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
}
|
||||
return false;
|
||||
},
|
||||
child: Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return _buildItemsView(context, settingsProvider);
|
||||
},
|
||||
child: CustomScrollView(
|
||||
controller: _scrollController,
|
||||
// Allow focus decoration to render outside scroll bounds
|
||||
clipBehavior: Clip.none,
|
||||
slivers: _buildContentSlivers(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds either a list or grid view based on the view mode
|
||||
Widget _buildItemsView(BuildContext context, SettingsProvider settingsProvider) {
|
||||
/// Whether the filters chip is visible
|
||||
bool get _isFiltersChipVisible => _filters.isNotEmpty && _selectedGrouping != 'folders';
|
||||
|
||||
/// Whether the sort chip is visible
|
||||
bool get _isSortChipVisible => _sortOptions.isNotEmpty && _selectedGrouping != 'folders';
|
||||
|
||||
/// Builds the chips bar widget
|
||||
Widget _buildChipsBar() {
|
||||
return Container(
|
||||
color: Theme.of(context).scaffoldBackgroundColor,
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Grouping chip
|
||||
FocusableFilterChip(
|
||||
focusNode: _groupingChipFocusNode,
|
||||
icon: Symbols.category_rounded,
|
||||
label: _getGroupingLabel(_selectedGrouping),
|
||||
onPressed: _showGroupingBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onNavigateLeft: _navigateToSidebar,
|
||||
onNavigateRight: _isFiltersChipVisible
|
||||
? () => _filtersChipFocusNode.requestFocus()
|
||||
: _isSortChipVisible
|
||||
? () => _sortChipFocusNode.requestFocus()
|
||||
: null,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Filters chip
|
||||
if (_isFiltersChipVisible)
|
||||
FocusableFilterChip(
|
||||
focusNode: _filtersChipFocusNode,
|
||||
icon: Symbols.filter_alt_rounded,
|
||||
label: _selectedFilters.isEmpty
|
||||
? t.libraries.filters
|
||||
: t.libraries.filtersWithCount(count: _selectedFilters.length),
|
||||
onPressed: _showFiltersBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onNavigateLeft: () => _groupingChipFocusNode.requestFocus(),
|
||||
onNavigateRight: _isSortChipVisible ? () => _sortChipFocusNode.requestFocus() : null,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
if (_isFiltersChipVisible) const SizedBox(width: 8),
|
||||
// Sort chip
|
||||
if (_isSortChipVisible)
|
||||
FocusableFilterChip(
|
||||
focusNode: _sortChipFocusNode,
|
||||
icon: Symbols.sort_rounded,
|
||||
label: _selectedSort?.title ?? t.libraries.sort,
|
||||
onPressed: _showSortBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onNavigateLeft: _isFiltersChipVisible
|
||||
? () => _filtersChipFocusNode.requestFocus()
|
||||
: () => _groupingChipFocusNode.requestFocus(),
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds content as slivers for the CustomScrollView
|
||||
List<Widget> _buildContentSlivers() {
|
||||
if (isLoading && items.isEmpty) {
|
||||
return [const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))];
|
||||
}
|
||||
|
||||
if (errorMessage != null && items.isEmpty) {
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
child: ErrorStateWidget(
|
||||
message: errorMessage!,
|
||||
icon: Symbols.error_outline_rounded,
|
||||
onRetry: _loadContent,
|
||||
retryLabel: t.common.retry,
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
if (items.isEmpty) {
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
child: EmptyStateWidget(message: t.libraries.thisLibraryIsEmpty, icon: Symbols.folder_open_rounded),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return _buildItemsSliver(context, settingsProvider);
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
// Top padding for grid content = chips bar height + extra space for focus decoration
|
||||
// Chips bar is ~48px, focus ring extends ~6px beyond item bounds
|
||||
static const double _gridTopPadding = _chipsBarHeight + 12.0;
|
||||
|
||||
/// Builds either a sliver list or sliver grid based on the view mode
|
||||
Widget _buildItemsSliver(BuildContext context, SettingsProvider settingsProvider) {
|
||||
final itemCount = items.length + (_hasMoreItems && isLoading ? 1 : 0);
|
||||
|
||||
if (settingsProvider.viewMode == ViewMode.list) {
|
||||
// In list view, only the first item can navigate up to chips
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(8),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(index, isFirstRow: index == 0),
|
||||
// In list view, all items are in a single column (first column)
|
||||
return SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, _gridTopPadding, 8, 8),
|
||||
sliver: SliverList.builder(
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(
|
||||
index,
|
||||
isFirstRow: index == 0,
|
||||
isFirstColumn: true, // List view = single column
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// In grid view, calculate columns and pass to item builder
|
||||
final columnCount = _getGridColumnCount(context, settingsProvider);
|
||||
return GridView.builder(
|
||||
padding: const EdgeInsets.all(8),
|
||||
gridDelegate: MediaGridDelegate.createDelegate(context: context, density: settingsProvider.libraryDensity),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(index, isFirstRow: _isFirstRow(index, columnCount)),
|
||||
final columnCount = GridSizeCalculator.getColumnCount(context, settingsProvider.libraryDensity);
|
||||
// Use 16:9 aspect ratio when browsing episodes with episode thumbnail mode
|
||||
final useWideRatio =
|
||||
_selectedGrouping == 'episodes' && settingsProvider.episodePosterMode == EpisodePosterMode.episodeThumbnail;
|
||||
return SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, _gridTopPadding, 8, 8),
|
||||
sliver: SliverGrid.builder(
|
||||
gridDelegate: MediaGridDelegate.createDelegate(
|
||||
context: context,
|
||||
density: settingsProvider.libraryDensity,
|
||||
useWideAspectRatio: useWideRatio,
|
||||
),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(
|
||||
index,
|
||||
isFirstRow: GridSizeCalculator.isFirstRow(index, columnCount),
|
||||
isFirstColumn: GridSizeCalculator.isFirstColumn(index, columnCount),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildMediaCardItem(int index, {required bool isFirstRow}) {
|
||||
Widget _buildMediaCardItem(int index, {required bool isFirstRow, required bool isFirstColumn}) {
|
||||
if (index >= items.length) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
@@ -587,13 +720,26 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
);
|
||||
}
|
||||
final item = items[index];
|
||||
|
||||
// Use firstItemFocusNode for index 0 to maintain compatibility with base class
|
||||
// All other items get managed focus nodes for restoration
|
||||
final focusNode = index == 0 ? firstItemFocusNode : _getGridItemFocusNode(index);
|
||||
|
||||
return FocusableMediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
focusNode: index == 0 ? firstItemFocusNode : null,
|
||||
focusNode: focusNode,
|
||||
onRefresh: updateItem,
|
||||
onNavigateUp: isFirstRow ? _navigateToChips : null,
|
||||
onNavigateLeft: isFirstColumn ? _navigateToSidebar : null,
|
||||
onBack: widget.onBack,
|
||||
onFocusChange: (hasFocus) {
|
||||
if (hasFocus) {
|
||||
// Track the focused index and current content version
|
||||
_lastFocusedIndex = index;
|
||||
_lastFocusedContentVersion = _contentVersion;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../../../models/plex_metadata.dart';
|
||||
import '../../../utils/library_refresh_notifier.dart';
|
||||
import '../../../widgets/focusable_media_card.dart';
|
||||
import '../../../i18n/strings.g.dart';
|
||||
import '../adaptive_media_grid.dart';
|
||||
import 'base_library_tab.dart';
|
||||
import 'library_grid_tab_state.dart';
|
||||
|
||||
@@ -51,14 +52,14 @@ class _LibraryCollectionsTabState extends LibraryGridTabState<PlexMetadata, Libr
|
||||
}
|
||||
|
||||
@override
|
||||
@override
|
||||
Widget buildGridItem(BuildContext context, PlexMetadata item, int index) {
|
||||
Widget buildGridItem(BuildContext context, PlexMetadata item, int index, [GridItemContext? gridContext]) {
|
||||
return FocusableMediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
focusNode: index == 0 ? firstItemFocusNode : null,
|
||||
onListRefresh: loadItems,
|
||||
onBack: widget.onBack,
|
||||
onNavigateLeft: gridContext?.isFirstColumn == true ? gridContext?.navigateToSidebar : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ import 'base_library_tab.dart';
|
||||
abstract class LibraryGridTabState<T, W extends BaseLibraryTab<T>> extends BaseLibraryTabState<T, W>
|
||||
with LibraryTabFocusMixin {
|
||||
/// Build a single grid item.
|
||||
Widget buildGridItem(BuildContext context, T item, int index);
|
||||
/// [gridContext] provides information about the item's position in the grid
|
||||
/// and callbacks for navigation (e.g., navigating to sidebar from first column).
|
||||
Widget buildGridItem(BuildContext context, T item, int index, [GridItemContext? gridContext]);
|
||||
|
||||
@override
|
||||
int get itemCount => items.length;
|
||||
@@ -20,10 +22,11 @@ abstract class LibraryGridTabState<T, W extends BaseLibraryTab<T>> extends BaseL
|
||||
Widget buildContent(List<T> items) {
|
||||
return AdaptiveMediaGrid<T>(
|
||||
items: items,
|
||||
itemBuilder: (context, item, index) => buildGridItem(context, item, index),
|
||||
itemBuilder: (context, item, index, [gridContext]) => buildGridItem(context, item, index, gridContext),
|
||||
onRefresh: loadItems,
|
||||
firstItemFocusNode: firstItemFocusNode,
|
||||
onBack: widget.onBack,
|
||||
enableSidebarNavigation: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../../../models/plex_playlist.dart';
|
||||
import '../../../utils/library_refresh_notifier.dart';
|
||||
import '../../../widgets/focusable_media_card.dart';
|
||||
import '../../../i18n/strings.g.dart';
|
||||
import '../adaptive_media_grid.dart';
|
||||
import 'base_library_tab.dart';
|
||||
import 'library_grid_tab_state.dart';
|
||||
|
||||
@@ -51,13 +52,14 @@ class _LibraryPlaylistsTabState extends LibraryGridTabState<PlexPlaylist, Librar
|
||||
}
|
||||
|
||||
@override
|
||||
Widget buildGridItem(BuildContext context, PlexPlaylist playlist, int index) {
|
||||
Widget buildGridItem(BuildContext context, PlexPlaylist playlist, int index, [GridItemContext? gridContext]) {
|
||||
return FocusableMediaCard(
|
||||
key: Key(playlist.ratingKey),
|
||||
item: playlist,
|
||||
focusNode: index == 0 ? firstItemFocusNode : null,
|
||||
onListRefresh: loadItems,
|
||||
onBack: widget.onBack,
|
||||
onNavigateLeft: gridContext?.isFirstColumn == true ? gridContext?.navigateToSidebar : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import '../../../mixins/item_updatable.dart';
|
||||
import '../../../models/plex_hub.dart';
|
||||
import '../../../models/plex_metadata.dart';
|
||||
import '../../../widgets/hub_section.dart';
|
||||
import '../../main_screen.dart';
|
||||
import 'base_library_tab.dart';
|
||||
|
||||
/// Recommended tab for library screen
|
||||
@@ -115,8 +116,13 @@ class _LibraryRecommendedTabState extends BaseLibraryTabState<PlexHub, LibraryRe
|
||||
final targetIndex = isUp ? hubIndex - 1 : hubIndex + 1;
|
||||
|
||||
// Check if target is valid
|
||||
if (targetIndex < 0 || targetIndex >= _hubKeys.length) {
|
||||
// At boundary, block navigation
|
||||
if (targetIndex < 0) {
|
||||
// At top boundary - return false to allow onNavigateUp to handle it
|
||||
return false;
|
||||
}
|
||||
|
||||
if (targetIndex >= _hubKeys.length) {
|
||||
// At bottom boundary, block navigation
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -138,12 +144,22 @@ class _LibraryRecommendedTabState extends BaseLibraryTabState<PlexHub, LibraryRe
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigate focus to the sidebar
|
||||
void _navigateToSidebar() {
|
||||
MainScreenFocusScope.of(context)?.focusSidebar();
|
||||
}
|
||||
|
||||
// Extra top padding for focus decoration (scale + border extends beyond item bounds)
|
||||
static const double _focusDecorationPadding = 8.0;
|
||||
|
||||
@override
|
||||
Widget buildContent(List<PlexHub> items) {
|
||||
_ensureHubKeys(items.length);
|
||||
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
padding: const EdgeInsets.fromLTRB(0, 8 + _focusDecorationPadding, 0, 8),
|
||||
// Allow focus decoration to render outside scroll bounds
|
||||
clipBehavior: Clip.none,
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) {
|
||||
final hub = items[index];
|
||||
@@ -158,6 +174,8 @@ class _LibraryRecommendedTabState extends BaseLibraryTabState<PlexHub, LibraryRe
|
||||
onRemoveFromContinueWatching: isContinueWatching ? _refreshContinueWatching : null,
|
||||
onVerticalNavigation: (isUp) => _handleVerticalNavigation(index, isUp),
|
||||
onBack: widget.onBack,
|
||||
onNavigateUp: index == 0 ? widget.onBack : null,
|
||||
onNavigateToSidebar: _navigateToSidebar,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
+209
-79
@@ -1,7 +1,12 @@
|
||||
import 'dart:io' show Platform, exit;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../services/update_service.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/platform_detector.dart';
|
||||
@@ -12,13 +17,16 @@ import '../navigation/navigation_tabs.dart';
|
||||
import '../providers/multi_server_provider.dart';
|
||||
import '../providers/server_state_provider.dart';
|
||||
import '../providers/hidden_libraries_provider.dart';
|
||||
import '../providers/libraries_provider.dart';
|
||||
import '../providers/playback_state_provider.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../services/offline_watch_sync_service.dart';
|
||||
import '../providers/offline_mode_provider.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../utils/desktop_window_padding.dart';
|
||||
import '../widgets/side_navigation_rail.dart';
|
||||
import '../focus/key_event_utils.dart';
|
||||
import 'discover_screen.dart';
|
||||
import 'libraries/libraries_screen.dart';
|
||||
import 'search_screen.dart';
|
||||
@@ -61,7 +69,7 @@ class MainScreen extends StatefulWidget {
|
||||
State<MainScreen> createState() => _MainScreenState();
|
||||
}
|
||||
|
||||
class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener {
|
||||
late int _currentIndex;
|
||||
String? _selectedLibraryGlobalKey;
|
||||
|
||||
@@ -94,6 +102,11 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
super.initState();
|
||||
_isOffline = widget.isOfflineMode;
|
||||
|
||||
if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) {
|
||||
windowManager.addListener(this);
|
||||
windowManager.setPreventClose(true);
|
||||
}
|
||||
|
||||
// Start on Downloads tab when in offline mode
|
||||
// In offline mode: visual index 0 = Downloads (screen 3), 1 = Settings (screen 4)
|
||||
// In online mode: indices match directly
|
||||
@@ -123,9 +136,75 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
if (!_isSidebarFocused) {
|
||||
_contentFocusScope.requestFocus();
|
||||
}
|
||||
|
||||
// Check for updates on startup
|
||||
_checkForUpdatesOnStartup();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _checkForUpdatesOnStartup() async {
|
||||
// Delay slightly to allow UI to settle
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
try {
|
||||
final updateInfo = await UpdateService.checkForUpdatesOnStartup();
|
||||
|
||||
if (updateInfo != null && updateInfo['hasUpdate'] == true && mounted) {
|
||||
_showUpdateDialog(updateInfo);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Error checking for updates', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
void _showUpdateDialog(Map<String, dynamic> updateInfo) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext dialogContext) {
|
||||
return AlertDialog(
|
||||
title: Text(t.update.available),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
t.update.versionAvailable(version: updateInfo['latestVersion']),
|
||||
style: Theme.of(dialogContext).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
t.update.currentVersion(version: updateInfo['currentVersion']),
|
||||
style: Theme.of(dialogContext).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.common.later)),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
await UpdateService.skipVersion(updateInfo['latestVersion']);
|
||||
if (dialogContext.mounted) Navigator.pop(dialogContext);
|
||||
},
|
||||
child: Text(t.update.skipVersion),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final url = Uri.parse(updateInfo['releaseUrl']);
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
if (dialogContext.mounted) Navigator.pop(dialogContext);
|
||||
},
|
||||
child: Text(t.update.viewRelease),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Set up the Watch Together navigation callback for guests
|
||||
void _setupWatchTogetherCallback() {
|
||||
try {
|
||||
@@ -208,12 +287,21 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
@override
|
||||
void dispose() {
|
||||
routeObserver.unsubscribe(this);
|
||||
if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) {
|
||||
windowManager.removeListener(this);
|
||||
windowManager.setPreventClose(false);
|
||||
}
|
||||
_offlineModeProvider?.removeListener(_handleOfflineStatusChanged);
|
||||
_sidebarFocusScope.dispose();
|
||||
_contentFocusScope.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowClose() {
|
||||
exit(0);
|
||||
}
|
||||
|
||||
List<Widget> _buildScreens(bool offline) {
|
||||
// In offline mode, only show Downloads and Settings
|
||||
// In online mode, show all 5 screens
|
||||
@@ -312,35 +400,33 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
setState(() => _isSidebarFocused = false);
|
||||
_contentFocusScope.requestFocus();
|
||||
// When content regains focus while on Libraries, retry focusing the active tab
|
||||
if (_currentIndex == 1) {
|
||||
if (_currentIndex == 1 && !_isOffline) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (_librariesKey.currentState case final FocusableTab focusable) {
|
||||
focusable.focusActiveTabIfReady();
|
||||
}
|
||||
});
|
||||
}
|
||||
// When content regains focus while on Settings, restore focus to last focused setting
|
||||
final settingsIndex = NavigationTab.indexFor(NavigationTabId.settings, isOffline: _isOffline);
|
||||
if (_currentIndex == settingsIndex) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (_settingsKey.currentState case final FocusableTab focusable) {
|
||||
focusable.focusActiveTabIfReady();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
KeyEventResult _handleBackKey(KeyEvent event) {
|
||||
if (event is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
|
||||
// Handle all back keys - this handler is only reached if lower widgets
|
||||
// (e.g., LibrariesScreen tab content/chips) don't handle the back key first
|
||||
final isBackKey =
|
||||
event.logicalKey == LogicalKeyboardKey.escape ||
|
||||
event.logicalKey == LogicalKeyboardKey.goBack ||
|
||||
event.logicalKey == LogicalKeyboardKey.browserBack ||
|
||||
event.logicalKey == LogicalKeyboardKey.gameButtonB;
|
||||
|
||||
if (!isBackKey) return KeyEventResult.ignored;
|
||||
|
||||
// Toggle focus between sidebar and content
|
||||
if (_isSidebarFocused) {
|
||||
_focusContent();
|
||||
} else {
|
||||
_focusSidebar();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
// Toggle focus between sidebar and content on BACK key
|
||||
return handleBackKeyAction(event, () {
|
||||
if (_isSidebarFocused) {
|
||||
_focusContent();
|
||||
} else {
|
||||
_focusSidebar();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -382,8 +468,12 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
final multiServerProvider = context.read<MultiServerProvider>();
|
||||
final serverStateProvider = context.read<ServerStateProvider>();
|
||||
final hiddenLibrariesProvider = context.read<HiddenLibrariesProvider>();
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
final playbackStateProvider = context.read<PlaybackStateProvider>();
|
||||
|
||||
// Clear libraries provider state before reconnecting
|
||||
librariesProvider.clear();
|
||||
|
||||
// Reconnect to all servers with new profile tokens
|
||||
if (servers.isNotEmpty) {
|
||||
final storage = await StorageService.getInstance();
|
||||
@@ -396,6 +486,10 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
if (connectedCount > 0) {
|
||||
if (!mounted) return;
|
||||
context.read<OfflineWatchSyncService>().onServersConnected();
|
||||
|
||||
// Reload libraries after reconnection
|
||||
librariesProvider.initialize(multiServerProvider.aggregationService);
|
||||
await librariesProvider.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,6 +514,8 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
if (_searchKey.currentState case final FullRefreshable refreshable) {
|
||||
refreshable.fullRefresh();
|
||||
}
|
||||
|
||||
// Sidebar automatically updates since it watches LibrariesProvider
|
||||
}
|
||||
|
||||
void _selectTab(int index) {
|
||||
@@ -434,23 +530,33 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
}
|
||||
});
|
||||
|
||||
// Skip screen-specific logic in offline mode (only Downloads and Settings available)
|
||||
if (_isOffline) return;
|
||||
// Handle screen-specific logic
|
||||
final settingsIndex = NavigationTab.indexFor(NavigationTabId.settings, isOffline: _isOffline);
|
||||
|
||||
// Notify discover screen when it becomes visible via tab switch
|
||||
if (index == 0) {
|
||||
_onDiscoverBecameVisible();
|
||||
}
|
||||
// Ensure the libraries screen applies focus when brought into view
|
||||
if (index == 1 && previousIndex != 1) {
|
||||
if (_librariesKey.currentState case final FocusableTab focusable) {
|
||||
focusable.focusActiveTabIfReady();
|
||||
// Skip online-only screen logic in offline mode
|
||||
if (!_isOffline) {
|
||||
// Notify discover screen when it becomes visible via tab switch
|
||||
if (index == 0) {
|
||||
_onDiscoverBecameVisible();
|
||||
}
|
||||
// Ensure the libraries screen applies focus when brought into view
|
||||
if (index == 1 && previousIndex != 1) {
|
||||
if (_librariesKey.currentState case final FocusableTab focusable) {
|
||||
focusable.focusActiveTabIfReady();
|
||||
}
|
||||
}
|
||||
// Focus search input when selecting Search tab
|
||||
if (index == 2) {
|
||||
if (_searchKey.currentState case final SearchInputFocusable searchable) {
|
||||
searchable.focusSearchInput();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Focus search input when selecting Search tab
|
||||
if (index == 2) {
|
||||
if (_searchKey.currentState case final SearchInputFocusable searchable) {
|
||||
searchable.focusSearchInput();
|
||||
|
||||
// Restore focus when switching to Settings tab (works in both online and offline mode)
|
||||
if (index == settingsIndex && previousIndex != settingsIndex) {
|
||||
if (_settingsKey.currentState case final FocusableTab focusable) {
|
||||
focusable.focusActiveTabIfReady();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -496,52 +602,76 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
final useSideNav = PlatformDetector.shouldUseSideNavigation(context);
|
||||
|
||||
if (useSideNav) {
|
||||
return PopScope(
|
||||
canPop: false, // Prevent system back from popping on Android TV
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
// No-op: back key events bubble through widget tree and are handled
|
||||
// by content screens (e.g., LibrariesScreen) or MainScreen's _handleBackKey.
|
||||
// We only use PopScope to prevent the system from popping the route.
|
||||
},
|
||||
child: Focus(
|
||||
onKeyEvent: (node, event) => _handleBackKey(event),
|
||||
child: MainScreenFocusScope(
|
||||
focusSidebar: _focusSidebar,
|
||||
focusContent: _focusContent,
|
||||
isSidebarFocused: _isSidebarFocused,
|
||||
child: SideNavigationScope(
|
||||
child: Row(
|
||||
children: [
|
||||
FocusScope(
|
||||
node: _sidebarFocusScope,
|
||||
child: SideNavigationRail(
|
||||
key: _sideNavKey,
|
||||
selectedIndex: _currentIndex,
|
||||
selectedLibraryKey: _selectedLibraryGlobalKey,
|
||||
isOfflineMode: _isOffline,
|
||||
onDestinationSelected: (index) {
|
||||
_selectTab(index);
|
||||
_focusContent();
|
||||
},
|
||||
onLibrarySelected: (key) {
|
||||
_selectLibrary(key);
|
||||
_focusContent();
|
||||
},
|
||||
),
|
||||
return Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
final alwaysExpanded = settingsProvider.alwaysKeepSidebarOpen;
|
||||
final contentLeftPadding = alwaysExpanded
|
||||
? SideNavigationRailState.expandedWidth
|
||||
: SideNavigationRailState.collapsedWidth;
|
||||
|
||||
return PopScope(
|
||||
canPop: false, // Prevent system back from popping on Android TV
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
// No-op: back key events bubble through widget tree and are handled
|
||||
// by content screens (e.g., LibrariesScreen) or MainScreen's _handleBackKey.
|
||||
// We only use PopScope to prevent the system from popping the route.
|
||||
},
|
||||
child: Focus(
|
||||
onKeyEvent: (node, event) => _handleBackKey(event),
|
||||
child: MainScreenFocusScope(
|
||||
focusSidebar: _focusSidebar,
|
||||
focusContent: _focusContent,
|
||||
isSidebarFocused: _isSidebarFocused,
|
||||
child: SideNavigationScope(
|
||||
child: Stack(
|
||||
children: [
|
||||
// Content with animated left padding based on sidebar state
|
||||
Positioned.fill(
|
||||
child: AnimatedPadding(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
curve: Curves.easeOutCubic,
|
||||
padding: EdgeInsets.only(left: contentLeftPadding),
|
||||
child: FocusScope(
|
||||
node: _contentFocusScope,
|
||||
// No autofocus - we control focus programmatically to prevent
|
||||
// autofocus from stealing focus back after setState() rebuilds
|
||||
child: IndexedStack(index: _currentIndex, children: _screens),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Sidebar overlays content when expanded (unless always expanded)
|
||||
Positioned(
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
child: FocusScope(
|
||||
node: _sidebarFocusScope,
|
||||
child: SideNavigationRail(
|
||||
key: _sideNavKey,
|
||||
selectedIndex: _currentIndex,
|
||||
selectedLibraryKey: _selectedLibraryGlobalKey,
|
||||
isOfflineMode: _isOffline,
|
||||
isSidebarFocused: _isSidebarFocused,
|
||||
alwaysExpanded: alwaysExpanded,
|
||||
onDestinationSelected: (index) {
|
||||
_selectTab(index);
|
||||
_focusContent();
|
||||
},
|
||||
onLibrarySelected: (key) {
|
||||
_selectLibrary(key);
|
||||
_focusContent();
|
||||
},
|
||||
onNavigateToContent: _focusContent,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Expanded(
|
||||
child: FocusScope(
|
||||
node: _contentFocusScope,
|
||||
// No autofocus - we control focus programmatically to prevent
|
||||
// autofocus from stealing focus back after setState() rebuilds
|
||||
child: IndexedStack(index: _currentIndex, children: _screens),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:plezy/widgets/app_icon.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../focus/dpad_navigator.dart';
|
||||
import '../focus/focusable_wrapper.dart';
|
||||
import '../focus/key_event_utils.dart';
|
||||
import '../focus/input_mode_tracker.dart';
|
||||
import '../widgets/focus_builders.dart';
|
||||
import '../widgets/media_card.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../widgets/plex_optimized_image.dart';
|
||||
import '../utils/plex_image_helper.dart';
|
||||
@@ -27,9 +33,10 @@ import '../utils/video_player_navigation.dart';
|
||||
import '../widgets/app_bar_back_button.dart';
|
||||
import '../utils/desktop_window_padding.dart';
|
||||
import '../widgets/horizontal_scroll_with_arrows.dart';
|
||||
import '../widgets/focusable_media_card.dart';
|
||||
import '../widgets/media_context_menu.dart';
|
||||
import '../widgets/placeholder_container.dart';
|
||||
import '../mixins/watch_state_aware.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import 'season_detail_screen.dart';
|
||||
|
||||
class MediaDetailScreen extends StatefulWidget {
|
||||
@@ -42,7 +49,7 @@ class MediaDetailScreen extends StatefulWidget {
|
||||
State<MediaDetailScreen> createState() => _MediaDetailScreenState();
|
||||
}
|
||||
|
||||
class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAware {
|
||||
List<PlexMetadata> _seasons = [];
|
||||
bool _isLoadingSeasons = false;
|
||||
PlexMetadata? _fullMetadata;
|
||||
@@ -53,11 +60,80 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
bool _watchStateChanged = false;
|
||||
double _scrollOffset = 0;
|
||||
|
||||
// Locked focus pattern for seasons
|
||||
int _focusedSeasonIndex = 0;
|
||||
late final FocusNode _seasonsFocusNode;
|
||||
late final FocusNode _playButtonFocusNode;
|
||||
Timer? _selectKeyTimer;
|
||||
bool _isSelectKeyDown = false;
|
||||
bool _longPressTriggered = false;
|
||||
static const _longPressDuration = Duration(milliseconds: 500);
|
||||
|
||||
// GlobalKeys for season cards to access their context menu
|
||||
final Map<int, GlobalKey<MediaCardState>> _seasonCardKeys = {};
|
||||
|
||||
// WatchStateAware: watch the show/movie and all season ratingKeys
|
||||
@override
|
||||
Set<String>? get watchedRatingKeys {
|
||||
final keys = <String>{widget.metadata.ratingKey};
|
||||
for (final season in _seasons) {
|
||||
keys.add(season.ratingKey);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
@override
|
||||
void onWatchStateChanged(WatchStateEvent event) {
|
||||
// Lightweight refresh - no loader, preserves scroll position
|
||||
if (!widget.isOffline) {
|
||||
_refreshWatchState();
|
||||
}
|
||||
}
|
||||
|
||||
/// Lightweight refresh for watch state changes - no loader, preserves scroll
|
||||
Future<void> _refreshWatchState() async {
|
||||
final client = _getClientForMetadata(context);
|
||||
if (client == null) return;
|
||||
|
||||
try {
|
||||
// Fetch updated metadata + on-deck without showing loader
|
||||
final result = await client.getMetadataWithImagesAndOnDeck(widget.metadata.ratingKey);
|
||||
final metadata = result['metadata'] as PlexMetadata?;
|
||||
final onDeckEpisode = result['onDeckEpisode'] as PlexMetadata?;
|
||||
|
||||
if (metadata != null && mounted) {
|
||||
setState(() {
|
||||
_fullMetadata = metadata.copyWith(serverId: widget.metadata.serverId, serverName: widget.metadata.serverName);
|
||||
_onDeckEpisode = onDeckEpisode?.copyWith(
|
||||
serverId: widget.metadata.serverId,
|
||||
serverName: widget.metadata.serverName,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Refresh seasons for updated watched counts (also without loader)
|
||||
if (widget.metadata.isShow) {
|
||||
final seasons = await client.getChildren(widget.metadata.ratingKey);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_seasons = seasons
|
||||
.map((s) => s.copyWith(serverId: widget.metadata.serverId, serverName: widget.metadata.serverName))
|
||||
.toList();
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Silently fail - data will refresh on next navigation
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_scrollController = ScrollController();
|
||||
_scrollController.addListener(_onScroll);
|
||||
_seasonsFocusNode = FocusNode(debugLabel: 'seasons_row');
|
||||
_playButtonFocusNode = FocusNode(debugLabel: 'play_button');
|
||||
_loadFullMetadata();
|
||||
}
|
||||
|
||||
@@ -71,6 +147,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
void dispose() {
|
||||
_scrollController.dispose();
|
||||
_seasonsScrollController.dispose();
|
||||
_seasonsFocusNode.dispose();
|
||||
_playButtonFocusNode.dispose();
|
||||
_selectKeyTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -156,6 +235,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
SizedBox(
|
||||
height: 48,
|
||||
child: FilledButton(
|
||||
focusNode: _playButtonFocusNode,
|
||||
autofocus: InputModeTracker.isKeyboardMode(context),
|
||||
onPressed: onPlayPressed,
|
||||
style: FilledButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 16)),
|
||||
@@ -448,7 +528,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
} else {
|
||||
await offlineWatch.markAsWatched(serverId: metadata.serverId!, ratingKey: metadata.ratingKey);
|
||||
}
|
||||
if (context.mounted) {
|
||||
if (mounted) {
|
||||
showAppSnackBar(
|
||||
context,
|
||||
isWatched ? t.messages.markedAsUnwatchedOffline : t.messages.markedAsWatchedOffline,
|
||||
@@ -466,7 +546,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
} else {
|
||||
await client.markAsWatched(metadata.ratingKey);
|
||||
}
|
||||
if (context.mounted) {
|
||||
if (mounted) {
|
||||
_watchStateChanged = true;
|
||||
showSuccessSnackBar(context, isWatched ? t.messages.markedAsUnwatched : t.messages.markedAsWatched);
|
||||
// Update watch state without full rebuild
|
||||
@@ -474,7 +554,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
if (mounted) {
|
||||
showErrorSnackBar(context, t.messages.errorLoading(error: e.toString()));
|
||||
}
|
||||
}
|
||||
@@ -692,7 +772,119 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Scroll season list to center the item at the given index
|
||||
void _scrollSeasonToIndex(int index, {bool animate = true}) {
|
||||
if (!_seasonsScrollController.hasClients) return;
|
||||
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
final cardWidth = screenWidth >= 1400
|
||||
? 220.0
|
||||
: screenWidth >= 900
|
||||
? 200.0
|
||||
: screenWidth >= 700
|
||||
? 190.0
|
||||
: 160.0;
|
||||
final itemExtent = cardWidth + 4; // card + padding
|
||||
|
||||
final viewport = _seasonsScrollController.position.viewportDimension;
|
||||
final targetCenter = 12 + (index * itemExtent) + (itemExtent / 2); // 12 = leading padding
|
||||
final desiredOffset = (targetCenter - (viewport / 2)).clamp(0.0, _seasonsScrollController.position.maxScrollExtent);
|
||||
|
||||
if (animate) {
|
||||
_seasonsScrollController.animateTo(
|
||||
desiredOffset,
|
||||
duration: const Duration(milliseconds: 150),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
} else {
|
||||
_seasonsScrollController.jumpTo(desiredOffset);
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle key events for the seasons row (locked focus pattern)
|
||||
KeyEventResult _handleSeasonsKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
|
||||
// Let back key propagate to parent Focus handler
|
||||
if (key.isBackKey) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
// Handle SELECT with long-press detection
|
||||
if (key.isSelectKey) {
|
||||
if (event is KeyDownEvent) {
|
||||
// Always reset state on KeyDown to handle cases where KeyUp was
|
||||
// consumed by a modal (e.g., context menu) and we didn't see it
|
||||
_selectKeyTimer?.cancel();
|
||||
_isSelectKeyDown = true;
|
||||
_longPressTriggered = false;
|
||||
_selectKeyTimer = Timer(_longPressDuration, () {
|
||||
if (!mounted) return;
|
||||
if (_isSelectKeyDown) {
|
||||
_longPressTriggered = true;
|
||||
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
|
||||
// Long-press: show context menu for the focused season
|
||||
_seasonCardKeys[_focusedSeasonIndex]?.currentState?.showContextMenu();
|
||||
}
|
||||
});
|
||||
return KeyEventResult.handled;
|
||||
} else if (event is KeyRepeatEvent) {
|
||||
return KeyEventResult.handled;
|
||||
} else if (event is KeyUpEvent) {
|
||||
final timerWasActive = _selectKeyTimer?.isActive ?? false;
|
||||
_selectKeyTimer?.cancel();
|
||||
if (!_longPressTriggered && timerWasActive && _isSelectKeyDown) {
|
||||
// Short tap: navigate to season
|
||||
if (_focusedSeasonIndex < _seasons.length) {
|
||||
_navigateToSeason(_seasons[_focusedSeasonIndex]);
|
||||
}
|
||||
}
|
||||
_isSelectKeyDown = false;
|
||||
_longPressTriggered = false;
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
|
||||
if (!event.isActionable) return KeyEventResult.ignored;
|
||||
if (_seasons.isEmpty) return KeyEventResult.ignored;
|
||||
|
||||
// LEFT: previous season
|
||||
if (key.isLeftKey) {
|
||||
if (_focusedSeasonIndex > 0) {
|
||||
_focusedSeasonIndex--;
|
||||
_scrollSeasonToIndex(_focusedSeasonIndex);
|
||||
setState(() {});
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// RIGHT: next season
|
||||
if (key.isRightKey) {
|
||||
if (_focusedSeasonIndex < _seasons.length - 1) {
|
||||
_focusedSeasonIndex++;
|
||||
_scrollSeasonToIndex(_focusedSeasonIndex);
|
||||
setState(() {});
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// UP: scroll to top and focus play button
|
||||
if (key.isUpKey) {
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
|
||||
_playButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// DOWN: consume (nothing below seasons to focus)
|
||||
if (key.isDownKey) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
/// Build horizontal seasons list for larger screens (>=600px)
|
||||
/// Uses locked focus pattern for D-pad centered scrolling
|
||||
Widget _buildHorizontalSeasons() {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
final cardWidth = screenWidth >= 1400
|
||||
@@ -705,32 +897,48 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
final posterHeight = (cardWidth - 16) * 1.5;
|
||||
final containerHeight = posterHeight + 66;
|
||||
|
||||
return SizedBox(
|
||||
height: containerHeight,
|
||||
child: HorizontalScrollWithArrows(
|
||||
controller: _seasonsScrollController,
|
||||
builder: (scrollController) => ListView.builder(
|
||||
controller: scrollController,
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
itemCount: _seasons.length,
|
||||
itemBuilder: (context, index) {
|
||||
final season = _seasons[index];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 2),
|
||||
child: FocusableMediaCard(
|
||||
item: season,
|
||||
width: cardWidth,
|
||||
height: posterHeight,
|
||||
forceGridMode: true,
|
||||
isOffline: widget.isOffline,
|
||||
onRefresh: (_) {
|
||||
_watchStateChanged = true;
|
||||
_updateWatchState();
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
final hasFocus = _seasonsFocusNode.hasFocus;
|
||||
|
||||
return Focus(
|
||||
focusNode: _seasonsFocusNode,
|
||||
onKeyEvent: _handleSeasonsKeyEvent,
|
||||
child: SizedBox(
|
||||
height: containerHeight,
|
||||
child: HorizontalScrollWithArrows(
|
||||
controller: _seasonsScrollController,
|
||||
builder: (scrollController) => ListView.builder(
|
||||
controller: scrollController,
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 12),
|
||||
itemCount: _seasons.length,
|
||||
itemBuilder: (context, index) {
|
||||
final season = _seasons[index];
|
||||
final isFocused = hasFocus && index == _focusedSeasonIndex;
|
||||
// Get or create a GlobalKey for this season card
|
||||
final cardKey = _seasonCardKeys.putIfAbsent(index, () => GlobalKey<MediaCardState>());
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 2),
|
||||
child: FocusBuilders.buildLockedFocusWrapper(
|
||||
context: context,
|
||||
isFocused: isFocused,
|
||||
onTap: () => _navigateToSeason(season),
|
||||
child: MediaCard(
|
||||
key: cardKey,
|
||||
item: season,
|
||||
width: cardWidth,
|
||||
height: posterHeight,
|
||||
forceGridMode: true,
|
||||
isOffline: widget.isOffline,
|
||||
onRefresh: (_) {
|
||||
_watchStateChanged = true;
|
||||
_updateWatchState();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1000,20 +1208,29 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
|
||||
// Show loading state while fetching full metadata
|
||||
if (_isLoadingMetadata) {
|
||||
return Focus(
|
||||
final loading = Focus(
|
||||
onKeyEvent: handleBack,
|
||||
child: Scaffold(
|
||||
appBar: AppBar(),
|
||||
body: const Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
);
|
||||
final blockSystemBack = Platform.isAndroid && InputModeTracker.isKeyboardMode(context);
|
||||
if (!blockSystemBack) {
|
||||
return loading;
|
||||
}
|
||||
return PopScope(
|
||||
canPop: false, // Prevent system back from double-popping on Android keyboard/TV
|
||||
onPopInvokedWithResult: (didPop, result) {},
|
||||
child: loading,
|
||||
);
|
||||
}
|
||||
|
||||
// Determine header height based on screen size
|
||||
final size = MediaQuery.of(context).size;
|
||||
final headerHeight = size.height * 0.6;
|
||||
|
||||
return Focus(
|
||||
final content = Focus(
|
||||
onKeyEvent: handleBack,
|
||||
child: Scaffold(
|
||||
body: Stack(
|
||||
@@ -1418,6 +1635,17 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final blockSystemBack = Platform.isAndroid && InputModeTracker.isKeyboardMode(context);
|
||||
if (!blockSystemBack) {
|
||||
return content;
|
||||
}
|
||||
|
||||
return PopScope(
|
||||
canPop: false, // Prevent system back from double-popping on Android keyboard/TV
|
||||
onPopInvokedWithResult: (didPop, result) {},
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInfoRow(String label, String value) {
|
||||
@@ -1478,8 +1706,8 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Season card widget
|
||||
class _SeasonCard extends StatelessWidget {
|
||||
/// Season card widget with D-pad long-press support
|
||||
class _SeasonCard extends StatefulWidget {
|
||||
final PlexMetadata season;
|
||||
final PlexClient? client;
|
||||
final VoidCallback onTap;
|
||||
@@ -1497,119 +1725,139 @@ class _SeasonCard extends StatelessWidget {
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: MediaContextMenu(
|
||||
item: season,
|
||||
onRefresh: (ratingKey) => onRefresh(),
|
||||
onTap: onTap,
|
||||
child: Semantics(
|
||||
label: "media-season-${season.ratingKey}",
|
||||
identifier: "media-season-${season.ratingKey}",
|
||||
button: true,
|
||||
hint: "Tap to view ${season.title}",
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
children: [
|
||||
// Season poster
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: isOffline && localPosterPath != null
|
||||
? Image.file(
|
||||
File(localPosterPath!),
|
||||
width: 80,
|
||||
height: 120,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stackTrace) => Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: const AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
)
|
||||
: season.thumb != null
|
||||
? PlexOptimizedImage.poster(
|
||||
client: client,
|
||||
imagePath: season.thumb,
|
||||
width: 80,
|
||||
height: 120,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
errorWidget: (context, url, error) => Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: const AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
)
|
||||
: Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: const AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
State<_SeasonCard> createState() => _SeasonCardState();
|
||||
}
|
||||
|
||||
// Season info
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
season.title,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
if (season.leafCount != null)
|
||||
class _SeasonCardState extends State<_SeasonCard> {
|
||||
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
|
||||
|
||||
void _showContextMenu() {
|
||||
_contextMenuKey.currentState?.showContextMenu(context);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FocusableWrapper(
|
||||
enableLongPress: true,
|
||||
onSelect: widget.onTap,
|
||||
onLongPress: _showContextMenu,
|
||||
borderRadius: 12, // Match card border radius
|
||||
child: Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: MediaContextMenu(
|
||||
key: _contextMenuKey,
|
||||
item: widget.season,
|
||||
onRefresh: (ratingKey) => widget.onRefresh(),
|
||||
onTap: widget.onTap,
|
||||
child: Semantics(
|
||||
label: "media-season-${widget.season.ratingKey}",
|
||||
identifier: "media-season-${widget.season.ratingKey}",
|
||||
button: true,
|
||||
hint: "Tap to view ${widget.season.title}",
|
||||
child: InkWell(
|
||||
onTap: widget.onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
children: [
|
||||
// Season poster
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: widget.isOffline && widget.localPosterPath != null
|
||||
? Image.file(
|
||||
File(widget.localPosterPath!),
|
||||
width: 80,
|
||||
height: 120,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stackTrace) => Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: const AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
)
|
||||
: widget.season.thumb != null
|
||||
? PlexOptimizedImage.poster(
|
||||
client: widget.client,
|
||||
imagePath: widget.season.thumb,
|
||||
width: 80,
|
||||
height: 120,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
errorWidget: (context, url, error) => Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: const AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
)
|
||||
: Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: const AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
|
||||
// Season info
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
t.discover.episodeCount(count: season.leafCount.toString()),
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: Colors.grey),
|
||||
widget.season.title,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
// Hide watch progress when offline (not tracked)
|
||||
if (!isOffline) ...[
|
||||
const SizedBox(height: 8),
|
||||
if (season.viewedLeafCount != null && season.leafCount != null)
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 200,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: LinearProgressIndicator(
|
||||
value: season.viewedLeafCount! / season.leafCount!,
|
||||
backgroundColor: tokens(context).outline,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).colorScheme.primary),
|
||||
minHeight: 6,
|
||||
const SizedBox(height: 4),
|
||||
if (widget.season.leafCount != null)
|
||||
Text(
|
||||
t.discover.episodeCount(count: widget.season.leafCount.toString()),
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: Colors.grey),
|
||||
),
|
||||
// Hide watch progress when offline (not tracked)
|
||||
if (!widget.isOffline) ...[
|
||||
const SizedBox(height: 8),
|
||||
if (widget.season.viewedLeafCount != null && widget.season.leafCount != null)
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 200,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: LinearProgressIndicator(
|
||||
value: widget.season.viewedLeafCount! / widget.season.leafCount!,
|
||||
backgroundColor: tokens(context).outline,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
minHeight: 6,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
t.discover.watchedProgress(
|
||||
watched: season.viewedLeafCount.toString(),
|
||||
total: season.leafCount.toString(),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
t.discover.watchedProgress(
|
||||
watched: widget.season.viewedLeafCount.toString(),
|
||||
total: widget.season.leafCount.toString(),
|
||||
),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey),
|
||||
),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
],
|
||||
const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:plezy/widgets/app_icon.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../../services/play_queue_launcher.dart';
|
||||
import '../../models/plex_playlist.dart';
|
||||
import '../../models/plex_metadata.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../../utils/provider_extensions.dart';
|
||||
import '../../widgets/media_grid_sliver.dart';
|
||||
import '../../widgets/focusable_media_card.dart';
|
||||
import '../../widgets/media_grid_delegate.dart';
|
||||
import '../../utils/grid_size_calculator.dart';
|
||||
import '../../widgets/desktop_app_bar.dart';
|
||||
import '../../providers/settings_provider.dart';
|
||||
import '../../focus/dpad_navigator.dart';
|
||||
import '../../focus/input_mode_tracker.dart';
|
||||
import '../../focus/key_event_utils.dart';
|
||||
import 'playlist_item_card.dart';
|
||||
import '../../widgets/focused_scroll_scaffold.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../../utils/dialogs.dart';
|
||||
import '../base_media_list_detail_screen.dart';
|
||||
@@ -38,11 +46,92 @@ class _PlaylistDetailScreenState extends BaseMediaListDetailScreen<PlaylistDetai
|
||||
@override
|
||||
IconData get emptyIcon => Symbols.playlist_play_rounded;
|
||||
|
||||
// Scroll controller for scrolling to top when app bar is focused
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
|
||||
// Focus management
|
||||
final FocusNode _listFocusNode = FocusNode(debugLabel: 'playlist_list');
|
||||
final FocusNode _playButtonFocusNode = FocusNode(debugLabel: 'playlist_play');
|
||||
final FocusNode _shuffleButtonFocusNode = FocusNode(debugLabel: 'playlist_shuffle');
|
||||
final FocusNode _deleteButtonFocusNode = FocusNode(debugLabel: 'playlist_delete');
|
||||
|
||||
// Navigation state for regular (non-smart) playlists
|
||||
int _focusedIndex = 0;
|
||||
int _focusedColumn = 0; // 0=content, 1=drag handle, 2=remove button
|
||||
|
||||
// Move mode state
|
||||
int? _movingIndex;
|
||||
int? _originalIndex;
|
||||
List<PlexMetadata>? _originalOrder;
|
||||
|
||||
// Scroll-into-view keys
|
||||
final Map<int, GlobalKey> _itemKeys = {};
|
||||
|
||||
// App bar focus state
|
||||
bool _isAppBarFocused = false;
|
||||
int _appBarFocusedButton = 0; // 0=play, 1=shuffle, 2=delete
|
||||
|
||||
// Flag to prevent PopScope from exiting when BACK was handled by a key handler
|
||||
bool _backHandledByKeyEvent = false;
|
||||
|
||||
// Grid focus for smart playlists
|
||||
final FocusNode _firstItemFocusNode = FocusNode(debugLabel: 'playlist_first_item');
|
||||
final Map<int, FocusNode> _gridItemFocusNodes = {};
|
||||
int? _lastFocusedGridIndex;
|
||||
int _contentVersion = 0;
|
||||
int _lastFocusedContentVersion = 0;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController.dispose();
|
||||
_listFocusNode.dispose();
|
||||
_playButtonFocusNode.dispose();
|
||||
_shuffleButtonFocusNode.dispose();
|
||||
_deleteButtonFocusNode.dispose();
|
||||
_firstItemFocusNode.dispose();
|
||||
for (final node in _gridItemFocusNodes.values) {
|
||||
node.dispose();
|
||||
}
|
||||
_gridItemFocusNodes.clear();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Get or create a focus node for a grid item at the given index
|
||||
FocusNode _getGridItemFocusNode(int index) {
|
||||
return _gridItemFocusNodes.putIfAbsent(index, () => FocusNode(debugLabel: 'playlist_grid_item_$index'));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<PlexMetadata>> fetchItems() async {
|
||||
return await client.getPlaylist(widget.playlist.ratingKey);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> loadItems() async {
|
||||
// Increment content version when loading fresh content
|
||||
_contentVersion++;
|
||||
await super.loadItems();
|
||||
|
||||
// Auto-focus after load if in keyboard mode
|
||||
if (mounted && items.isNotEmpty) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
if (InputModeTracker.isKeyboardMode(context)) {
|
||||
setState(() {
|
||||
_isAppBarFocused = false;
|
||||
_focusedIndex = 0;
|
||||
_focusedColumn = 0;
|
||||
});
|
||||
if (widget.playlist.smart) {
|
||||
_firstItemFocusNode.requestFocus();
|
||||
} else {
|
||||
_listFocusNode.requestFocus();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String getLoadSuccessMessage(int itemCount) {
|
||||
return 'Loaded $itemCount items for playlist: ${widget.playlist.title}';
|
||||
@@ -141,6 +230,72 @@ class _PlaylistDetailScreenState extends BaseMediaListDetailScreen<PlaylistDetai
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist a move that was already done in the UI (during move mode).
|
||||
/// The item is already at newIndex in the items list.
|
||||
Future<void> _persistMoveToServer(int originalIndex, int newIndex) async {
|
||||
// Item is already at newIndex in the list
|
||||
final movedItem = items[newIndex];
|
||||
|
||||
// Check if item has playlistItemID (required for reordering)
|
||||
if (movedItem.playlistItemID == null) {
|
||||
appLogger.e('Cannot persist move: item missing playlistItemID');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.playlists.errorReordering)));
|
||||
// Revert the UI change
|
||||
setState(() {
|
||||
final item = items.removeAt(newIndex);
|
||||
items.insert(originalIndex, item);
|
||||
_focusedIndex = originalIndex;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine the "after" item ID based on where the item is now
|
||||
final int afterPlaylistItemId;
|
||||
if (newIndex == 0) {
|
||||
afterPlaylistItemId = 0; // Move to top
|
||||
} else {
|
||||
final afterItem = items[newIndex - 1];
|
||||
if (afterItem.playlistItemID == null) {
|
||||
appLogger.e('Cannot persist move: after item missing playlistItemID');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.playlists.errorReordering)));
|
||||
// Revert the UI change
|
||||
setState(() {
|
||||
final item = items.removeAt(newIndex);
|
||||
items.insert(originalIndex, item);
|
||||
_focusedIndex = originalIndex;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
afterPlaylistItemId = afterItem.playlistItemID!;
|
||||
}
|
||||
|
||||
appLogger.d('Persisting move from $originalIndex to $newIndex (after ID: $afterPlaylistItemId)');
|
||||
|
||||
// Call API to persist the change (UI is already updated)
|
||||
final success = await client.movePlaylistItem(
|
||||
playlistId: widget.playlist.ratingKey,
|
||||
playlistItemId: movedItem.playlistItemID!,
|
||||
afterPlaylistItemId: afterPlaylistItemId,
|
||||
);
|
||||
|
||||
if (!success) {
|
||||
// Revert on failure
|
||||
appLogger.e('Failed to persist move, reverting UI');
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
final item = items.removeAt(newIndex);
|
||||
items.insert(originalIndex, item);
|
||||
_focusedIndex = originalIndex;
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.playlists.errorReordering)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _removeItem(int index) async {
|
||||
final item = items[index];
|
||||
|
||||
@@ -201,57 +356,482 @@ class _PlaylistDetailScreenState extends BaseMediaListDetailScreen<PlaylistDetai
|
||||
);
|
||||
}
|
||||
|
||||
/// Ensure the focused item is visible in the list
|
||||
void _ensureFocusedVisible() {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
final key = _itemKeys[_focusedIndex];
|
||||
final context = key?.currentContext;
|
||||
if (context != null) {
|
||||
Scrollable.ensureVisible(context, alignment: 0.25, duration: const Duration(milliseconds: 200));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Handle key events for list navigation
|
||||
KeyEventResult _handleListKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
|
||||
final backResult = handleBackKeyAction(event, () {
|
||||
if (_movingIndex != null) {
|
||||
// Cancel move mode, set flag to prevent PopScope exit
|
||||
_backHandledByKeyEvent = true;
|
||||
_cancelMoveMode();
|
||||
} else {
|
||||
// Navigate to app bar on BACK, set flag to prevent PopScope exit
|
||||
_handleBackFromContent();
|
||||
}
|
||||
});
|
||||
if (backResult != KeyEventResult.ignored) {
|
||||
return backResult;
|
||||
}
|
||||
|
||||
if (event is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
|
||||
if (_movingIndex != null) {
|
||||
// Move mode - arrows reorder the item
|
||||
if (key.isUpKey && _movingIndex! > 0) {
|
||||
setState(() {
|
||||
final item = items.removeAt(_movingIndex!);
|
||||
items.insert(_movingIndex! - 1, item);
|
||||
_movingIndex = _movingIndex! - 1;
|
||||
_focusedIndex = _movingIndex!;
|
||||
});
|
||||
_ensureFocusedVisible();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isDownKey && _movingIndex! < items.length - 1) {
|
||||
setState(() {
|
||||
final item = items.removeAt(_movingIndex!);
|
||||
items.insert(_movingIndex! + 1, item);
|
||||
_movingIndex = _movingIndex! + 1;
|
||||
_focusedIndex = _movingIndex!;
|
||||
});
|
||||
_ensureFocusedVisible();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isSelectKey) {
|
||||
// Confirm move - persist to server (UI is already updated during move)
|
||||
final oldIndex = _originalIndex!;
|
||||
final newIndex = _movingIndex!;
|
||||
setState(() {
|
||||
_movingIndex = null;
|
||||
_originalIndex = null;
|
||||
_originalOrder = null;
|
||||
// Keep focus on the moved item at its new position
|
||||
_focusedIndex = newIndex;
|
||||
_focusedColumn = 0;
|
||||
});
|
||||
// Persist the change via API (list is already in correct order)
|
||||
_persistMoveToServer(oldIndex, newIndex);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
} else {
|
||||
// Navigation mode
|
||||
if (key.isUpKey) {
|
||||
if (_focusedIndex > 0) {
|
||||
setState(() {
|
||||
_focusedIndex--;
|
||||
_focusedColumn = 0; // Reset to row when changing rows
|
||||
});
|
||||
_ensureFocusedVisible();
|
||||
} else {
|
||||
// First item - navigate to app bar
|
||||
_navigateToAppBar();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isDownKey && _focusedIndex < items.length - 1) {
|
||||
setState(() {
|
||||
_focusedIndex++;
|
||||
_focusedColumn = 0; // Reset to row when changing rows
|
||||
});
|
||||
_ensureFocusedVisible();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isLeftKey) {
|
||||
// Navigate left within columns
|
||||
if (_focusedColumn == 0 && widget.playlist.smart == false) {
|
||||
// Go to drag handle (column 1)
|
||||
setState(() => _focusedColumn = 1);
|
||||
return KeyEventResult.handled;
|
||||
} else if (_focusedColumn == 2) {
|
||||
// Go back to content
|
||||
setState(() => _focusedColumn = 0);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
if (key.isRightKey) {
|
||||
// Navigate right within columns
|
||||
if (_focusedColumn == 0) {
|
||||
// Go to remove button (column 2)
|
||||
setState(() => _focusedColumn = 2);
|
||||
return KeyEventResult.handled;
|
||||
} else if (_focusedColumn == 1) {
|
||||
// Go to content from drag handle
|
||||
setState(() => _focusedColumn = 0);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
if (key.isSelectKey) {
|
||||
if (_focusedColumn == 0) {
|
||||
// Play from this item
|
||||
_playFromItem(_focusedIndex);
|
||||
} else if (_focusedColumn == 1 && !widget.playlist.smart) {
|
||||
// Enter move mode
|
||||
setState(() {
|
||||
_movingIndex = _focusedIndex;
|
||||
_originalIndex = _focusedIndex;
|
||||
_originalOrder = List.from(items);
|
||||
});
|
||||
} else if (_focusedColumn == 2) {
|
||||
// Remove item
|
||||
_removeItem(_focusedIndex);
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
/// Handle key events when app bar is focused
|
||||
KeyEventResult _handleAppBarKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
final hasDelete = !widget.playlist.smart;
|
||||
final maxButton = hasDelete ? 2 : 1;
|
||||
|
||||
final backResult = handleBackKeyAction(event, () => Navigator.pop(context));
|
||||
if (backResult != KeyEventResult.ignored) {
|
||||
return backResult;
|
||||
}
|
||||
|
||||
if (event is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
|
||||
if (key.isLeftKey && _appBarFocusedButton > 0) {
|
||||
setState(() => _appBarFocusedButton--);
|
||||
_focusAppBarButton(_appBarFocusedButton);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isRightKey && _appBarFocusedButton < maxButton) {
|
||||
setState(() => _appBarFocusedButton++);
|
||||
_focusAppBarButton(_appBarFocusedButton);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isDownKey) {
|
||||
// Return focus to list/grid
|
||||
setState(() => _isAppBarFocused = false);
|
||||
if (items.isNotEmpty) {
|
||||
if (widget.playlist.smart) {
|
||||
_navigateToGrid();
|
||||
} else {
|
||||
_listFocusNode.requestFocus();
|
||||
}
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isSelectKey) {
|
||||
_triggerAppBarButton(_appBarFocusedButton);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
void _focusAppBarButton(int index) {
|
||||
switch (index) {
|
||||
case 0:
|
||||
_playButtonFocusNode.requestFocus();
|
||||
break;
|
||||
case 1:
|
||||
_shuffleButtonFocusNode.requestFocus();
|
||||
break;
|
||||
case 2:
|
||||
_deleteButtonFocusNode.requestFocus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _triggerAppBarButton(int index) {
|
||||
switch (index) {
|
||||
case 0:
|
||||
playItems();
|
||||
break;
|
||||
case 1:
|
||||
shufflePlayItems();
|
||||
break;
|
||||
case 2:
|
||||
if (!widget.playlist.smart) _deletePlaylist();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigate focus from app bar down to the grid
|
||||
void _navigateToGrid() {
|
||||
if (items.isEmpty) return;
|
||||
|
||||
// Check if we should restore focus to the last focused item
|
||||
final shouldRestoreFocus =
|
||||
_lastFocusedGridIndex != null &&
|
||||
_lastFocusedContentVersion == _contentVersion &&
|
||||
_lastFocusedGridIndex! < items.length;
|
||||
|
||||
final targetIndex = shouldRestoreFocus ? _lastFocusedGridIndex! : 0;
|
||||
|
||||
if (targetIndex == 0) {
|
||||
_firstItemFocusNode.requestFocus();
|
||||
} else {
|
||||
_getGridItemFocusNode(targetIndex).requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigate from grid to app bar
|
||||
void _navigateToAppBar() {
|
||||
setState(() {
|
||||
_isAppBarFocused = true;
|
||||
_appBarFocusedButton = 0;
|
||||
});
|
||||
_playButtonFocusNode.requestFocus();
|
||||
// Scroll to top to show the app bar
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeOut);
|
||||
}
|
||||
|
||||
/// Handle BACK key from grid/list - navigate to app bar and set flag to prevent PopScope exit
|
||||
void _handleBackFromContent() {
|
||||
_backHandledByKeyEvent = true;
|
||||
_navigateToAppBar();
|
||||
}
|
||||
|
||||
/// Handle back navigation for PopScope
|
||||
bool _handleBackNavigation() {
|
||||
// If BACK was already handled by a key event, don't pop
|
||||
if (_backHandledByKeyEvent) {
|
||||
_backHandledByKeyEvent = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
// If in move mode, cancel move instead of navigating
|
||||
if (_movingIndex != null) {
|
||||
_cancelMoveMode();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_isAppBarFocused) {
|
||||
// Already on app bar, allow exit
|
||||
return true;
|
||||
} else {
|
||||
// Focus app bar first
|
||||
_navigateToAppBar();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Build focusable app bar actions
|
||||
List<Widget> _buildFocusableAppBarActions() {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
|
||||
Widget buildFocusableButton({
|
||||
required FocusNode focusNode,
|
||||
required int buttonIndex,
|
||||
required IconData icon,
|
||||
required String tooltip,
|
||||
required VoidCallback onPressed,
|
||||
Color? color,
|
||||
}) {
|
||||
final isFocused = isKeyboardMode && _isAppBarFocused && _appBarFocusedButton == buttonIndex;
|
||||
return Focus(
|
||||
focusNode: focusNode,
|
||||
onKeyEvent: _handleAppBarKeyEvent,
|
||||
child: Container(
|
||||
decoration: isFocused
|
||||
? BoxDecoration(color: colorScheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(20))
|
||||
: null,
|
||||
child: IconButton(icon: AppIcon(icon, fill: 1), tooltip: tooltip, onPressed: onPressed, color: color),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
if (items.isNotEmpty)
|
||||
buildFocusableButton(
|
||||
focusNode: _playButtonFocusNode,
|
||||
buttonIndex: 0,
|
||||
icon: Symbols.play_arrow_rounded,
|
||||
tooltip: t.discover.play,
|
||||
onPressed: playItems,
|
||||
),
|
||||
if (items.isNotEmpty)
|
||||
buildFocusableButton(
|
||||
focusNode: _shuffleButtonFocusNode,
|
||||
buttonIndex: 1,
|
||||
icon: Symbols.shuffle_rounded,
|
||||
tooltip: t.common.shuffle,
|
||||
onPressed: shufflePlayItems,
|
||||
),
|
||||
if (!widget.playlist.smart)
|
||||
buildFocusableButton(
|
||||
focusNode: _deleteButtonFocusNode,
|
||||
buttonIndex: 2,
|
||||
icon: Symbols.delete_rounded,
|
||||
tooltip: t.playlists.delete,
|
||||
onPressed: _deletePlaylist,
|
||||
color: Colors.red,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// Cancel move mode if active, returns true if cancelled
|
||||
bool _cancelMoveMode() {
|
||||
if (_movingIndex != null) {
|
||||
setState(() {
|
||||
if (_originalOrder != null) {
|
||||
items = List.from(_originalOrder!);
|
||||
}
|
||||
_focusedIndex = _originalIndex ?? 0;
|
||||
_movingIndex = null;
|
||||
_originalIndex = null;
|
||||
_originalOrder = null;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FocusedScrollScaffold(
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(widget.playlist.title, style: const TextStyle(fontSize: 16)),
|
||||
if (widget.playlist.smart)
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
AppIcon(Symbols.auto_awesome_rounded, fill: 1, size: 12, color: Colors.blue[300]),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
t.playlists.smartPlaylist,
|
||||
style: TextStyle(fontSize: 11, color: Colors.blue[300], fontWeight: FontWeight.normal),
|
||||
),
|
||||
],
|
||||
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
|
||||
return PopScope(
|
||||
canPop: false,
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
if (BackKeyCoordinator.consumeIfHandled()) return;
|
||||
if (didPop) return;
|
||||
final shouldPop = _handleBackNavigation();
|
||||
if (shouldPop && mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
},
|
||||
child: Scaffold(
|
||||
body: CustomScrollView(
|
||||
controller: _scrollController,
|
||||
slivers: [
|
||||
CustomAppBar(
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(widget.playlist.title, style: const TextStyle(fontSize: 16)),
|
||||
if (widget.playlist.smart)
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
AppIcon(Symbols.auto_awesome_rounded, fill: 1, size: 12, color: Colors.blue[300]),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
t.playlists.smartPlaylist,
|
||||
style: TextStyle(fontSize: 11, color: Colors.blue[300], fontWeight: FontWeight.normal),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: _buildFocusableAppBarActions(),
|
||||
),
|
||||
],
|
||||
...buildStateSlivers(),
|
||||
if (items.isNotEmpty)
|
||||
if (widget.playlist.smart)
|
||||
// Smart playlists: Use focusable grid view (cannot be reordered)
|
||||
_buildSmartPlaylistGrid(isKeyboardMode)
|
||||
else
|
||||
// Regular playlists: Use reorderable list view with focus
|
||||
_buildReorderableList(isKeyboardMode),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: buildAppBarActions(
|
||||
onDelete: widget.playlist.smart ? null : _deletePlaylist,
|
||||
deleteTooltip: t.playlists.delete,
|
||||
showDelete: !widget.playlist.smart,
|
||||
);
|
||||
}
|
||||
|
||||
/// Build a focusable grid for smart playlists
|
||||
Widget _buildSmartPlaylistGrid(bool isKeyboardMode) {
|
||||
return Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
final columnCount = GridSizeCalculator.getColumnCount(context, settingsProvider.libraryDensity);
|
||||
return SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
|
||||
sliver: SliverGrid.builder(
|
||||
gridDelegate: MediaGridDelegate.createDelegate(context: context, density: settingsProvider.libraryDensity),
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
final isFirstRow = GridSizeCalculator.isFirstRow(index, columnCount);
|
||||
final focusNode = index == 0 ? _firstItemFocusNode : _getGridItemFocusNode(index);
|
||||
|
||||
return FocusableMediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
focusNode: focusNode,
|
||||
onRefresh: updateItem,
|
||||
onNavigateUp: isFirstRow ? _navigateToAppBar : null,
|
||||
onBack: _handleBackFromContent,
|
||||
onFocusChange: (hasFocus) {
|
||||
if (hasFocus) {
|
||||
_lastFocusedGridIndex = index;
|
||||
_lastFocusedContentVersion = _contentVersion;
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Build a reorderable list for regular playlists with focus support
|
||||
Widget _buildReorderableList(bool isKeyboardMode) {
|
||||
return SliverToBoxAdapter(
|
||||
child: Focus(
|
||||
autofocus: isKeyboardMode && items.isNotEmpty && !_isAppBarFocused,
|
||||
focusNode: _listFocusNode,
|
||||
onKeyEvent: _handleListKeyEvent,
|
||||
onFocusChange: (hasFocus) {
|
||||
// Rebuild when focus changes to update visual indicators
|
||||
if (hasFocus && mounted) {
|
||||
setState(() {
|
||||
_isAppBarFocused = false;
|
||||
});
|
||||
}
|
||||
},
|
||||
child: ReorderableListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
onReorder: _onReorder,
|
||||
buildDefaultDragHandles: false,
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
// Check keyboard mode directly to ensure we get latest value
|
||||
final inKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
final isFocused = inKeyboardMode && index == _focusedIndex && !_isAppBarFocused;
|
||||
final isMoving = index == _movingIndex;
|
||||
|
||||
_itemKeys.putIfAbsent(index, () => GlobalKey());
|
||||
|
||||
return PlaylistItemCard(
|
||||
key: _itemKeys[index] ?? ValueKey(item.playlistItemID ?? item.ratingKey),
|
||||
item: item,
|
||||
index: index,
|
||||
onRemove: () => _removeItem(index),
|
||||
onTap: () => _playFromItem(index),
|
||||
onRefresh: updateItem,
|
||||
canReorder: !widget.playlist.smart,
|
||||
isFocused: isFocused,
|
||||
focusedColumn: isFocused ? _focusedColumn : null,
|
||||
isMoving: isMoving,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
slivers: [
|
||||
...buildStateSlivers(),
|
||||
if (items.isNotEmpty)
|
||||
if (widget.playlist.smart)
|
||||
// Smart playlists: Use grid view (cannot be reordered)
|
||||
MediaGridSliver(items: items, onRefresh: updateItem)
|
||||
else
|
||||
// Regular playlists: Use reorderable list view
|
||||
SliverReorderableList(
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
return PlaylistItemCard(
|
||||
key: ValueKey(item.playlistItemID ?? item.ratingKey),
|
||||
item: item,
|
||||
index: index,
|
||||
onRemove: () => _removeItem(index),
|
||||
onTap: () => _playFromItem(index),
|
||||
onRefresh: updateItem,
|
||||
canReorder: !widget.playlist.smart,
|
||||
);
|
||||
},
|
||||
itemCount: items.length,
|
||||
onReorder: _onReorder,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,11 @@ class PlaylistItemCard extends StatefulWidget {
|
||||
final void Function(String ratingKey)? onRefresh;
|
||||
final bool canReorder; // Whether drag handle should be shown
|
||||
|
||||
// Focus state for keyboard/D-pad navigation
|
||||
final bool isFocused;
|
||||
final int? focusedColumn; // 0=row, 1=drag handle, 2=remove button
|
||||
final bool isMoving; // Whether this item is being moved/reordered
|
||||
|
||||
const PlaylistItemCard({
|
||||
super.key,
|
||||
required this.item,
|
||||
@@ -28,6 +33,9 @@ class PlaylistItemCard extends StatefulWidget {
|
||||
this.onTap,
|
||||
this.onRefresh,
|
||||
this.canReorder = true,
|
||||
this.isFocused = false,
|
||||
this.focusedColumn,
|
||||
this.isMoving = false,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -40,6 +48,29 @@ class _PlaylistItemCardState extends State<PlaylistItemCard> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final item = widget.item;
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
// Determine if row is focused (main content area)
|
||||
final isRowFocused = widget.isFocused && widget.focusedColumn == 0;
|
||||
|
||||
// Focus states for individual elements
|
||||
final isDragHandleFocused = widget.isFocused && widget.focusedColumn == 1;
|
||||
final isRemoveButtonFocused = widget.isFocused && widget.focusedColumn == 2;
|
||||
|
||||
// Determine card styling based on focus/move state
|
||||
Color? cardColor;
|
||||
ShapeBorder? cardShape;
|
||||
if (widget.isMoving) {
|
||||
cardColor = colorScheme.primaryContainer;
|
||||
} else if (isRowFocused) {
|
||||
// Row is focused - use visible border like FocusableWrapper
|
||||
cardColor = colorScheme.surfaceContainerHighest;
|
||||
cardShape = RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: BorderSide(color: colorScheme.primary, width: 2.5),
|
||||
);
|
||||
}
|
||||
|
||||
return MediaContextMenu(
|
||||
key: _contextMenuKey,
|
||||
item: item,
|
||||
@@ -47,6 +78,8 @@ class _PlaylistItemCardState extends State<PlaylistItemCard> {
|
||||
onTap: widget.onTap,
|
||||
child: Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
color: cardColor,
|
||||
shape: cardShape,
|
||||
child: InkWell(
|
||||
onTap: widget.onTap,
|
||||
child: Padding(
|
||||
@@ -54,12 +87,27 @@ class _PlaylistItemCardState extends State<PlaylistItemCard> {
|
||||
child: Row(
|
||||
children: [
|
||||
// Drag handle (if reorderable)
|
||||
// Wrapped in GestureDetector to consume long-press and prevent context menu
|
||||
if (widget.canReorder)
|
||||
ReorderableDragStartListener(
|
||||
index: widget.index,
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.only(right: 12),
|
||||
child: AppIcon(Symbols.drag_indicator_rounded, fill: 1, color: Colors.grey),
|
||||
GestureDetector(
|
||||
onLongPress: () {},
|
||||
child: ReorderableDragStartListener(
|
||||
index: widget.index,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
margin: const EdgeInsets.only(right: 4),
|
||||
decoration: isDragHandleFocused
|
||||
? BoxDecoration(
|
||||
color: colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
)
|
||||
: null,
|
||||
child: AppIcon(
|
||||
widget.isMoving ? Symbols.swap_vert_rounded : Symbols.drag_indicator_rounded,
|
||||
fill: 1,
|
||||
color: (widget.isMoving || isDragHandleFocused) ? colorScheme.primary : Colors.grey,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -111,11 +159,19 @@ class _PlaylistItemCardState extends State<PlaylistItemCard> {
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// Remove button
|
||||
IconButton(
|
||||
icon: const AppIcon(Symbols.close_rounded, fill: 1, size: 20),
|
||||
onPressed: widget.onRemove,
|
||||
tooltip: t.playlists.removeItem,
|
||||
color: Colors.grey[400],
|
||||
Container(
|
||||
decoration: isRemoveButtonFocused
|
||||
? BoxDecoration(
|
||||
color: colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
)
|
||||
: null,
|
||||
child: IconButton(
|
||||
icon: const AppIcon(Symbols.close_rounded, fill: 1, size: 20),
|
||||
onPressed: widget.onRemove,
|
||||
tooltip: t.playlists.removeItem,
|
||||
color: isRemoveButtonFocused ? colorScheme.primary : Colors.grey[400],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
+146
-72
@@ -4,18 +4,22 @@ import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:rate_limiter/rate_limiter.dart';
|
||||
|
||||
import '../focus/dpad_navigator.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../providers/multi_server_provider.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../services/settings_service.dart' show ViewMode;
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/grid_size_calculator.dart';
|
||||
import '../utils/sliver_adaptive_media_builder.dart';
|
||||
import '../utils/snackbar_helper.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/media_card.dart';
|
||||
import '../widgets/focusable_media_card.dart';
|
||||
import '../utils/focus_utils.dart';
|
||||
import 'libraries/state_messages.dart';
|
||||
import 'main_screen.dart';
|
||||
|
||||
class SearchScreen extends StatefulWidget {
|
||||
const SearchScreen({super.key});
|
||||
@@ -27,6 +31,7 @@ class SearchScreen extends StatefulWidget {
|
||||
class _SearchScreenState extends State<SearchScreen> with Refreshable, FullRefreshable, SearchInputFocusable {
|
||||
final _searchController = TextEditingController();
|
||||
final _searchFocusNode = FocusNode(debugLabel: 'SearchInput');
|
||||
final _firstResultFocusNode = FocusNode(debugLabel: 'SearchFirstResult');
|
||||
List<PlexMetadata> _searchResults = [];
|
||||
bool _isSearching = false;
|
||||
bool _hasSearched = false;
|
||||
@@ -48,6 +53,7 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable, FullRefre
|
||||
_searchController.removeListener(_onSearchChanged);
|
||||
_searchController.dispose();
|
||||
_searchFocusNode.dispose();
|
||||
_firstResultFocusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -148,88 +154,156 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable, FullRefre
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigate focus to the sidebar
|
||||
void _navigateToSidebar() {
|
||||
MainScreenFocusScope.of(context)?.focusSidebar();
|
||||
}
|
||||
|
||||
/// Handle key events on the search input for D-pad navigation
|
||||
KeyEventResult _handleSearchInputKeyEvent(FocusNode node, KeyEvent event) {
|
||||
if (!event.isActionable) return KeyEventResult.ignored;
|
||||
|
||||
final key = event.logicalKey;
|
||||
|
||||
// DOWN: Focus first result if results exist and not loading
|
||||
if (key.isDownKey && _searchResults.isNotEmpty && !_isSearching) {
|
||||
_firstResultFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT at cursor position 0: Navigate to sidebar
|
||||
if (key.isLeftKey && _searchController.selection.baseOffset == 0) {
|
||||
_navigateToSidebar();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// BACK: Clear search or navigate to sidebar
|
||||
if (key.isBackKey) {
|
||||
if (_searchController.text.isNotEmpty) {
|
||||
_searchController.clear();
|
||||
} else {
|
||||
_navigateToSidebar();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
/// Calculate column count based on available width.
|
||||
int _calculateColumnCount(double availableWidth, double maxCrossAxisExtent, double crossAxisSpacing) {
|
||||
return ((availableWidth + crossAxisSpacing) / (maxCrossAxisExtent + crossAxisSpacing)).ceil().clamp(1, 100);
|
||||
}
|
||||
|
||||
@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.fromLTRB(16, 0, 16, 16),
|
||||
child: TextField(
|
||||
controller: _searchController,
|
||||
focusNode: _searchFocusNode,
|
||||
decoration: InputDecoration(
|
||||
hintText: t.search.hint,
|
||||
prefixIcon: const AppIcon(Symbols.search_rounded, fill: 1),
|
||||
suffixIcon: _searchController.text.isNotEmpty
|
||||
? IconButton(
|
||||
icon: const AppIcon(Symbols.clear_rounded, fill: 1),
|
||||
onPressed: () {
|
||||
_searchController.clear();
|
||||
// State update handled by listener
|
||||
},
|
||||
)
|
||||
: null,
|
||||
filled: true,
|
||||
fillColor: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(100), borderSide: BorderSide.none),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(100),
|
||||
borderSide: BorderSide.none,
|
||||
// Use LayoutBuilder to get the actual available width (accounting for sidebar)
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final availableWidth = constraints.maxWidth;
|
||||
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
DesktopSliverAppBar(title: Text(t.screens.search), floating: true),
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Focus(
|
||||
onKeyEvent: _handleSearchInputKeyEvent,
|
||||
child: TextField(
|
||||
controller: _searchController,
|
||||
focusNode: _searchFocusNode,
|
||||
decoration: InputDecoration(
|
||||
hintText: t.search.hint,
|
||||
prefixIcon: const AppIcon(Symbols.search_rounded, fill: 1),
|
||||
suffixIcon: _searchController.text.isNotEmpty
|
||||
? IconButton(
|
||||
icon: const AppIcon(Symbols.clear_rounded, fill: 1),
|
||||
onPressed: () {
|
||||
_searchController.clear();
|
||||
// State update handled by listener
|
||||
},
|
||||
)
|
||||
: null,
|
||||
filled: true,
|
||||
fillColor: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(100), borderSide: BorderSide.none),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(100),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(100),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(100),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_isSearching)
|
||||
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
|
||||
else if (!_hasSearched)
|
||||
SliverFillRemaining(
|
||||
child: StateMessageWidget(
|
||||
message: t.search.searchYourMedia,
|
||||
subtitle: t.search.enterTitleActorOrKeyword,
|
||||
icon: Symbols.search_rounded,
|
||||
iconSize: 80,
|
||||
),
|
||||
)
|
||||
else if (_searchResults.isEmpty)
|
||||
SliverFillRemaining(
|
||||
child: StateMessageWidget(
|
||||
message: t.messages.noResultsFound,
|
||||
subtitle: t.search.tryDifferentTerm,
|
||||
icon: Symbols.search_off_rounded,
|
||||
iconSize: 80,
|
||||
),
|
||||
)
|
||||
else
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return buildAdaptiveMediaSliverBuilder<PlexMetadata>(
|
||||
context: context,
|
||||
items: _searchResults,
|
||||
itemBuilder: (context, item, index) {
|
||||
return MediaCard(key: Key(item.ratingKey), item: item, onRefresh: updateItem);
|
||||
},
|
||||
if (_isSearching)
|
||||
const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
|
||||
else if (!_hasSearched)
|
||||
SliverFillRemaining(
|
||||
child: StateMessageWidget(
|
||||
message: t.search.searchYourMedia,
|
||||
subtitle: t.search.enterTitleActorOrKeyword,
|
||||
icon: Symbols.search_rounded,
|
||||
iconSize: 80,
|
||||
),
|
||||
)
|
||||
else if (_searchResults.isEmpty)
|
||||
SliverFillRemaining(
|
||||
child: StateMessageWidget(
|
||||
message: t.messages.noResultsFound,
|
||||
subtitle: t.search.tryDifferentTerm,
|
||||
icon: Symbols.search_off_rounded,
|
||||
iconSize: 80,
|
||||
),
|
||||
)
|
||||
else
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
final maxCrossAxisExtent = GridSizeCalculator.getMaxCrossAxisExtent(context, settingsProvider.libraryDensity);
|
||||
const gridPadding = EdgeInsets.all(16);
|
||||
const crossAxisSpacing = 8.0;
|
||||
final gridAvailableWidth = availableWidth - gridPadding.left - gridPadding.right;
|
||||
final columnCount = _calculateColumnCount(gridAvailableWidth, maxCrossAxisExtent, crossAxisSpacing);
|
||||
final isList = settingsProvider.viewMode == ViewMode.list;
|
||||
|
||||
return buildAdaptiveMediaSliverBuilder<PlexMetadata>(
|
||||
context: context,
|
||||
items: _searchResults,
|
||||
itemBuilder: (context, item, index) {
|
||||
// In list view, all items are in the first column
|
||||
final isFirstColumn = isList || GridSizeCalculator.isFirstColumn(index, columnCount);
|
||||
final isFirstRow = isList ? index == 0 : GridSizeCalculator.isFirstRow(index, columnCount);
|
||||
return FocusableMediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
focusNode: index == 0 ? _firstResultFocusNode : null,
|
||||
onListRefresh: () => updateItem(item.ratingKey),
|
||||
onNavigateLeft: isFirstColumn ? _navigateToSidebar : null,
|
||||
onNavigateUp: isFirstRow ? focusSearchInput : null,
|
||||
);
|
||||
},
|
||||
viewMode: settingsProvider.viewMode,
|
||||
density: settingsProvider.libraryDensity,
|
||||
padding: const EdgeInsets.all(16),
|
||||
childAspectRatio: 2 / 3.3,
|
||||
crossAxisSpacing: 8,
|
||||
mainAxisSpacing: 8,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:plezy/widgets/app_icon.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../main.dart';
|
||||
import '../focus/focusable_wrapper.dart';
|
||||
import '../focus/key_event_utils.dart';
|
||||
import '../focus/dpad_navigator.dart';
|
||||
import '../focus/input_mode_tracker.dart';
|
||||
import '../models/download_models.dart';
|
||||
import '../providers/download_provider.dart';
|
||||
@@ -19,6 +23,8 @@ import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/media_context_menu.dart';
|
||||
import '../widgets/placeholder_container.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
import '../mixins/watch_state_aware.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import '../theme/mono_tokens.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
|
||||
@@ -32,7 +38,7 @@ class SeasonDetailScreen extends StatefulWidget {
|
||||
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
|
||||
}
|
||||
|
||||
class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdatable {
|
||||
class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdatable, WatchStateAware, RouteAware {
|
||||
PlexClient? _client;
|
||||
|
||||
@override
|
||||
@@ -41,6 +47,22 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdata
|
||||
List<PlexMetadata> _episodes = [];
|
||||
bool _isLoadingEpisodes = false;
|
||||
bool _watchStateChanged = false;
|
||||
// Capture keyboard mode once at init to avoid rebuild dependency
|
||||
bool _initialKeyboardMode = false;
|
||||
bool _suppressNextBackKeyUp = false;
|
||||
bool _routeSubscribed = false;
|
||||
|
||||
// WatchStateAware: watch all episode ratingKeys
|
||||
@override
|
||||
Set<String>? get watchedRatingKeys => _episodes.map((e) => e.ratingKey).toSet();
|
||||
|
||||
@override
|
||||
void onWatchStateChanged(WatchStateEvent event) {
|
||||
// Update the affected episode
|
||||
if (!widget.isOffline && _client != null) {
|
||||
updateItem(event.ratingKey);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the correct PlexClient for this season's server
|
||||
PlexClient? _getClientForSeason(BuildContext context) {
|
||||
@@ -55,6 +77,8 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdata
|
||||
super.initState();
|
||||
// Initialize the client once in initState
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
// Capture keyboard mode once to avoid rebuild dependency when mode changes
|
||||
_initialKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
_client = _getClientForSeason(context);
|
||||
_loadEpisodes();
|
||||
});
|
||||
@@ -117,10 +141,45 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdata
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
if (_routeSubscribed) return;
|
||||
final route = ModalRoute.of(context);
|
||||
if (route is PageRoute) {
|
||||
routeObserver.subscribe(this, route);
|
||||
_routeSubscribed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_routeSubscribed) {
|
||||
routeObserver.unsubscribe(this);
|
||||
_routeSubscribed = false;
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didPopNext() {
|
||||
// Returning from a child route (e.g., video player).
|
||||
// Suppress the first BACK KeyUp which can otherwise pop this route.
|
||||
_suppressNextBackKeyUp = true;
|
||||
}
|
||||
|
||||
KeyEventResult _handleBackKeyEvent(KeyEvent event) {
|
||||
if (_suppressNextBackKeyUp && event is KeyUpEvent && event.logicalKey.isBackKey) {
|
||||
_suppressNextBackKeyUp = false;
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return handleBackKeyNavigation(context, event, result: _watchStateChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Focus(
|
||||
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event, result: _watchStateChanged),
|
||||
final content = Focus(
|
||||
onKeyEvent: (_, event) => _handleBackKeyEvent(event),
|
||||
child: Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
@@ -165,7 +224,7 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdata
|
||||
client: _client,
|
||||
isOffline: widget.isOffline,
|
||||
localPosterPath: localPosterPath,
|
||||
autofocus: index == 0 && InputModeTracker.isKeyboardMode(context),
|
||||
autofocus: index == 0 && _initialKeyboardMode,
|
||||
onTap: () async {
|
||||
await navigateToVideoPlayerWithRefresh(
|
||||
context,
|
||||
@@ -182,11 +241,22 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdata
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final blockSystemBack = Platform.isAndroid && InputModeTracker.isKeyboardMode(context);
|
||||
if (!blockSystemBack) {
|
||||
return content;
|
||||
}
|
||||
|
||||
return PopScope(
|
||||
canPop: false, // Prevent system back from double-popping on Android keyboard/TV
|
||||
onPopInvokedWithResult: (didPop, result) {},
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Episode card widget
|
||||
class _EpisodeCard extends StatelessWidget {
|
||||
/// Episode card widget with D-pad long-press support
|
||||
class _EpisodeCard extends StatefulWidget {
|
||||
final PlexMetadata episode;
|
||||
final PlexClient? client;
|
||||
final VoidCallback onTap;
|
||||
@@ -205,16 +275,26 @@ class _EpisodeCard extends StatelessWidget {
|
||||
this.localPosterPath,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_EpisodeCard> createState() => _EpisodeCardState();
|
||||
}
|
||||
|
||||
class _EpisodeCardState extends State<_EpisodeCard> {
|
||||
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
|
||||
|
||||
void _showContextMenu() {
|
||||
_contextMenuKey.currentState?.showContextMenu(context);
|
||||
}
|
||||
|
||||
Widget _buildEpisodeMetaRow(BuildContext context) {
|
||||
return Row(
|
||||
children: [
|
||||
if (episode.duration != null)
|
||||
if (widget.episode.duration != null)
|
||||
Text(
|
||||
formatDurationTimestamp(Duration(milliseconds: episode.duration!)),
|
||||
formatDurationTimestamp(Duration(milliseconds: widget.episode.duration!)),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: tokens(context).textMuted, fontSize: 12),
|
||||
),
|
||||
// Hide watch status when offline (not tracked)
|
||||
if (!isOffline && episode.duration != null && episode.isWatched) ...[
|
||||
if (widget.episode.originallyAvailableAt != null) ...[
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6),
|
||||
child: Text(
|
||||
@@ -223,7 +303,7 @@ class _EpisodeCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${t.discover.watched} ✓',
|
||||
formatFullDate(widget.episode.originallyAvailableAt!),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: tokens(context).textMuted, fontSize: 12),
|
||||
),
|
||||
],
|
||||
@@ -234,264 +314,292 @@ class _EpisodeCard extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Hide progress when offline (not tracked)
|
||||
final hasProgress = !isOffline && episode.viewOffset != null && episode.duration != null && episode.viewOffset! > 0;
|
||||
final progress = hasProgress ? episode.viewOffset! / episode.duration! : 0.0;
|
||||
final hasProgress =
|
||||
!widget.isOffline &&
|
||||
widget.episode.viewOffset != null &&
|
||||
widget.episode.duration != null &&
|
||||
widget.episode.viewOffset! > 0;
|
||||
final progress = hasProgress ? widget.episode.viewOffset! / widget.episode.duration! : 0.0;
|
||||
|
||||
return MediaContextMenu(
|
||||
item: episode,
|
||||
onRefresh: onRefresh,
|
||||
onTap: onTap,
|
||||
child: InkWell(
|
||||
key: Key(episode.ratingKey),
|
||||
autofocus: autofocus,
|
||||
onTap: onTap,
|
||||
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: isOffline && localPosterPath != null
|
||||
? Image.file(
|
||||
File(localPosterPath!),
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stackTrace) => const PlaceholderContainer(
|
||||
child: AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
)
|
||||
: episode.thumb != null
|
||||
? PlexOptimizedImage.thumb(
|
||||
client: client,
|
||||
imagePath: episode.thumb,
|
||||
filterQuality: FilterQuality.medium,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => const PlaceholderContainer(),
|
||||
errorWidget: (context, url, error) => const PlaceholderContainer(
|
||||
child: AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
)
|
||||
: const PlaceholderContainer(child: AppIcon(Symbols.movie_rounded, fill: 1, 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)],
|
||||
),
|
||||
return FocusableWrapper(
|
||||
autofocus: widget.autofocus,
|
||||
enableLongPress: true,
|
||||
onSelect: widget.onTap,
|
||||
onLongPress: _showContextMenu,
|
||||
borderRadius: 0, // Episode cards have no border radius
|
||||
useBackgroundFocus: true, // Use background color instead of outline
|
||||
disableScale: true, // No scale animation for list items
|
||||
child: MediaContextMenu(
|
||||
key: _contextMenuKey,
|
||||
item: widget.episode,
|
||||
onRefresh: widget.onRefresh,
|
||||
onTap: widget.onTap,
|
||||
child: InkWell(
|
||||
key: Key(widget.episode.ratingKey),
|
||||
onTap: widget.onTap,
|
||||
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: widget.isOffline && widget.localPosterPath != null
|
||||
? Image.file(
|
||||
File(widget.localPosterPath!),
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stackTrace) => const PlaceholderContainer(
|
||||
child: AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
)
|
||||
: widget.episode.thumb != null
|
||||
? PlexOptimizedImage.thumb(
|
||||
client: widget.client,
|
||||
imagePath: widget.episode.thumb,
|
||||
filterQuality: FilterQuality.medium,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => const PlaceholderContainer(),
|
||||
errorWidget: (context, url, error) => const PlaceholderContainer(
|
||||
child: AppIcon(Symbols.movie_rounded, fill: 1, size: 32),
|
||||
),
|
||||
)
|
||||
: const PlaceholderContainer(child: AppIcon(Symbols.movie_rounded, fill: 1, size: 32)),
|
||||
),
|
||||
child: Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.6),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
|
||||
// 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)],
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.6),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const AppIcon(Symbols.play_arrow_rounded, fill: 1, color: Colors.white, size: 20),
|
||||
),
|
||||
child: const AppIcon(Symbols.play_arrow_rounded, fill: 1, 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,
|
||||
// Progress bar at bottom
|
||||
if (hasProgress && !widget.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,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
if (widget.episode.isWatched)
|
||||
Positioned(
|
||||
top: 4,
|
||||
right: 4,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
color: tokens(context).text,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.3), blurRadius: 4)],
|
||||
),
|
||||
child: AppIcon(Symbols.check_rounded, fill: 1, color: tokens(context).bg, size: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(width: 12),
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Episode info
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Episode number and title with download status
|
||||
Consumer<DownloadProvider>(
|
||||
builder: (context, downloadProvider, _) {
|
||||
// Build download status icon based on state
|
||||
Widget? downloadStatusIcon;
|
||||
// Episode info
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Episode number and title with download status
|
||||
Consumer<DownloadProvider>(
|
||||
builder: (context, downloadProvider, _) {
|
||||
// Build download status icon based on state
|
||||
Widget? downloadStatusIcon;
|
||||
|
||||
// Only show download status in online mode
|
||||
if (!isOffline && episode.serverId != null) {
|
||||
final globalKey = '${episode.serverId}:${episode.ratingKey}';
|
||||
final progress = downloadProvider.getProgress(globalKey);
|
||||
final isQueueing = downloadProvider.isQueueing(globalKey);
|
||||
// Only show download status in online mode
|
||||
if (!widget.isOffline && widget.episode.serverId != null) {
|
||||
final globalKey = '${widget.episode.serverId}:${widget.episode.ratingKey}';
|
||||
final progress = downloadProvider.getProgress(globalKey);
|
||||
final isQueueing = downloadProvider.isQueueing(globalKey);
|
||||
|
||||
// Helper to get status-specific muted color
|
||||
Color getMutedColor(Color baseColor) {
|
||||
return Color.lerp(
|
||||
tokens(context).textMuted,
|
||||
baseColor,
|
||||
0.3, // 30% of the status color, 70% muted
|
||||
)!;
|
||||
// Helper to get status-specific muted color
|
||||
Color getMutedColor(Color baseColor) {
|
||||
return Color.lerp(
|
||||
tokens(context).textMuted,
|
||||
baseColor,
|
||||
0.3, // 30% of the status color, 70% muted
|
||||
)!;
|
||||
}
|
||||
|
||||
if (isQueueing) {
|
||||
// Queueing state - building queue
|
||||
downloadStatusIcon = SizedBox(
|
||||
width: 12,
|
||||
height: 12,
|
||||
child: CircularProgressIndicator(strokeWidth: 1.5, color: tokens(context).textMuted),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.queued) {
|
||||
// Queued state - waiting to download
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.schedule_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.orange),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.downloading) {
|
||||
// Downloading state - active download with radial progress
|
||||
downloadStatusIcon = SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
// Background circle
|
||||
CircularProgressIndicator(
|
||||
value: 1.0,
|
||||
strokeWidth: 1.5,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
getMutedColor(Colors.blue).withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
// Progress circle
|
||||
CircularProgressIndicator(
|
||||
value: progress?.progressPercent,
|
||||
strokeWidth: 1.5,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(getMutedColor(Colors.blue)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.paused) {
|
||||
// Paused state - download paused
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.pause_circle_outline_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.amber),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.failed) {
|
||||
// Failed state - download failed
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.error_outline_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.red),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.cancelled) {
|
||||
// Cancelled state - download cancelled
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.cancel_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.grey),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.completed) {
|
||||
// Completed state - download complete
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.file_download_done_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.green),
|
||||
);
|
||||
}
|
||||
// Note: No icon shown if not downloaded (null)
|
||||
}
|
||||
|
||||
if (isQueueing) {
|
||||
// Queueing state - building queue
|
||||
downloadStatusIcon = SizedBox(
|
||||
width: 12,
|
||||
height: 12,
|
||||
child: CircularProgressIndicator(strokeWidth: 1.5, color: tokens(context).textMuted),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.queued) {
|
||||
// Queued state - waiting to download
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.schedule_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.orange),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.downloading) {
|
||||
// Downloading state - active download with radial progress
|
||||
downloadStatusIcon = SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
// Background circle
|
||||
CircularProgressIndicator(
|
||||
value: 1.0,
|
||||
strokeWidth: 1.5,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
getMutedColor(Colors.blue).withValues(alpha: 0.3),
|
||||
return Row(
|
||||
children: [
|
||||
// Episode number badge
|
||||
if (widget.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${widget.episode.index}',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onPrimaryContainer,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
// Progress circle
|
||||
CircularProgressIndicator(
|
||||
value: progress?.progressPercent,
|
||||
strokeWidth: 1.5,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(getMutedColor(Colors.blue)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.paused) {
|
||||
// Paused state - download paused
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.pause_circle_outline_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.amber),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.failed) {
|
||||
// Failed state - download failed
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.error_outline_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.red),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.cancelled) {
|
||||
// Cancelled state - download cancelled
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.cancel_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.grey),
|
||||
);
|
||||
} else if (progress?.status == DownloadStatus.completed) {
|
||||
// Completed state - download complete
|
||||
downloadStatusIcon = AppIcon(
|
||||
Symbols.file_download_done_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: getMutedColor(Colors.green),
|
||||
);
|
||||
}
|
||||
// Note: No icon shown if not downloaded (null)
|
||||
}
|
||||
|
||||
return Row(
|
||||
children: [
|
||||
// Episode number badge
|
||||
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),
|
||||
),
|
||||
// Download status icon (if present)
|
||||
if (downloadStatusIcon != null) ...[const SizedBox(width: 6), downloadStatusIcon],
|
||||
const SizedBox(width: 8),
|
||||
// Episode title
|
||||
Expanded(
|
||||
child: Text(
|
||||
'E${episode.index}',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onPrimaryContainer,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
widget.episode.title,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
// Download status icon (if present)
|
||||
if (downloadStatusIcon != null) ...[const SizedBox(width: 6), downloadStatusIcon],
|
||||
const SizedBox(width: 8),
|
||||
// Episode title
|
||||
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,
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
|
||||
// Metadata row (duration, watched status)
|
||||
const SizedBox(height: 8),
|
||||
_buildEpisodeMetaRow(context),
|
||||
],
|
||||
// Summary
|
||||
if (widget.episode.summary != null && widget.episode.summary!.isNotEmpty) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
widget.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),
|
||||
_buildEpisodeMetaRow(context),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -74,6 +74,9 @@ class _MpvConfigScreenState extends State<MpvConfigScreen> {
|
||||
|
||||
final keyController = TextEditingController(text: existingEntry?.key ?? '');
|
||||
final valueController = TextEditingController(text: existingEntry?.value ?? '');
|
||||
final keyFocusNode = FocusNode();
|
||||
final valueFocusNode = FocusNode();
|
||||
final saveFocusNode = FocusNode();
|
||||
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
@@ -84,22 +87,29 @@ class _MpvConfigScreenState extends State<MpvConfigScreen> {
|
||||
children: [
|
||||
TextField(
|
||||
controller: keyController,
|
||||
focusNode: keyFocusNode,
|
||||
decoration: InputDecoration(labelText: t.mpvConfig.propertyKey, hintText: t.mpvConfig.propertyKeyHint),
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.next,
|
||||
onSubmitted: (_) => valueFocusNode.requestFocus(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: valueController,
|
||||
focusNode: valueFocusNode,
|
||||
decoration: InputDecoration(
|
||||
labelText: t.mpvConfig.propertyValue,
|
||||
hintText: t.mpvConfig.propertyValueHint,
|
||||
),
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => saveFocusNode.requestFocus(),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
|
||||
TextButton(
|
||||
focusNode: saveFocusNode,
|
||||
onPressed: () {
|
||||
if (keyController.text.isNotEmpty && valueController.text.isNotEmpty) {
|
||||
Navigator.pop(context, true);
|
||||
@@ -127,6 +137,9 @@ class _MpvConfigScreenState extends State<MpvConfigScreen> {
|
||||
|
||||
keyController.dispose();
|
||||
valueController.dispose();
|
||||
keyFocusNode.dispose();
|
||||
valueFocusNode.dispose();
|
||||
saveFocusNode.dispose();
|
||||
}
|
||||
|
||||
Future<bool> _showConfirmDeleteDialog({required String title, required String content}) async {
|
||||
|
||||
@@ -2,13 +2,17 @@ import 'dart:io';
|
||||
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:plezy/widgets/app_icon.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:hotkey_manager/hotkey_manager.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../focus/focus_memory_tracker.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../main_screen.dart';
|
||||
import '../../mixins/refreshable.dart';
|
||||
import '../../services/discord_rpc_service.dart';
|
||||
import '../../services/download_storage_service.dart';
|
||||
import '../../services/saf_storage_service.dart';
|
||||
@@ -43,8 +47,46 @@ class SettingsScreen extends StatefulWidget {
|
||||
State<SettingsScreen> createState() => _SettingsScreenState();
|
||||
}
|
||||
|
||||
class _SettingsScreenState extends State<SettingsScreen> {
|
||||
class _SettingsScreenState extends State<SettingsScreen> with FocusableTab {
|
||||
late settings.SettingsService _settingsService;
|
||||
late final FocusMemoryTracker _focusTracker;
|
||||
|
||||
// Setting keys for focus tracking
|
||||
static const _kTheme = 'theme';
|
||||
static const _kLanguage = 'language';
|
||||
static const _kLibraryDensity = 'library_density';
|
||||
static const _kViewMode = 'view_mode';
|
||||
static const _kEpisodePosterMode = 'episode_poster_mode';
|
||||
static const _kShowHeroSection = 'show_hero_section';
|
||||
static const _kUseGlobalHubs = 'use_global_hubs';
|
||||
static const _kShowServerNameOnHubs = 'show_server_name_on_hubs';
|
||||
static const _kAlwaysKeepSidebarOpen = 'always_keep_sidebar_open';
|
||||
static const _kPlayerBackend = 'player_backend';
|
||||
static const _kHardwareDecoding = 'hardware_decoding';
|
||||
static const _kMatchContentFrameRate = 'match_content_frame_rate';
|
||||
static const _kBufferSize = 'buffer_size';
|
||||
static const _kSubtitleStyling = 'subtitle_styling';
|
||||
static const _kMpvConfig = 'mpv_config';
|
||||
static const _kSmallSkipDuration = 'small_skip_duration';
|
||||
static const _kLargeSkipDuration = 'large_skip_duration';
|
||||
static const _kDefaultSleepTimer = 'default_sleep_timer';
|
||||
static const _kMaxVolume = 'max_volume';
|
||||
static const _kDiscordRichPresence = 'discord_rich_presence';
|
||||
static const _kRememberTrackSelections = 'remember_track_selections';
|
||||
static const _kClickVideoTogglesPlayback = 'click_video_toggles_playback';
|
||||
static const _kAutoSkipIntro = 'auto_skip_intro';
|
||||
static const _kAutoSkipCredits = 'auto_skip_credits';
|
||||
static const _kAutoSkipDelay = 'auto_skip_delay';
|
||||
static const _kDownloadLocation = 'download_location';
|
||||
static const _kDownloadOnWifiOnly = 'download_on_wifi_only';
|
||||
static const _kVideoPlayerControls = 'video_player_controls';
|
||||
static const _kVideoPlayerNavigation = 'video_player_navigation';
|
||||
static const _kDebugLogging = 'debug_logging';
|
||||
static const _kViewLogs = 'view_logs';
|
||||
static const _kClearCache = 'clear_cache';
|
||||
static const _kResetSettings = 'reset_settings';
|
||||
static const _kCheckForUpdates = 'check_for_updates';
|
||||
static const _kAbout = 'about';
|
||||
KeyboardShortcutsService? _keyboardService;
|
||||
late final bool _keyboardShortcutsSupported = KeyboardShortcutsService.isPlatformSupported();
|
||||
bool _isLoading = true;
|
||||
@@ -56,6 +98,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
int _seekTimeLarge = 30;
|
||||
int _sleepTimerDuration = 30;
|
||||
bool _rememberTrackSelections = true;
|
||||
bool _clickVideoTogglesPlayback = false;
|
||||
bool _autoSkipIntro = true;
|
||||
bool _autoSkipCredits = true;
|
||||
int _autoSkipDelay = 5;
|
||||
@@ -63,6 +106,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
bool _videoPlayerNavigationEnabled = false;
|
||||
int _maxVolume = 100;
|
||||
bool _enableDiscordRPC = false;
|
||||
bool _matchContentFrameRate = false;
|
||||
bool _useExoPlayer = true; // Android only: ExoPlayer vs MPV
|
||||
|
||||
// Update checking state
|
||||
bool _isCheckingForUpdate = false;
|
||||
@@ -71,9 +116,40 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_focusTracker = FocusMemoryTracker(
|
||||
onFocusChanged: () {
|
||||
if (mounted) setState(() {});
|
||||
},
|
||||
debugLabelPrefix: 'settings',
|
||||
);
|
||||
_loadSettings();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focusTracker.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void focusActiveTabIfReady() {
|
||||
_focusTracker.restoreFocus(fallbackKey: _kTheme);
|
||||
}
|
||||
|
||||
/// Navigate focus to the sidebar
|
||||
void _navigateToSidebar() {
|
||||
MainScreenFocusScope.of(context)?.focusSidebar();
|
||||
}
|
||||
|
||||
/// Handle key events for LEFT arrow → sidebar navigation
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.arrowLeft) {
|
||||
_navigateToSidebar();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
Future<void> _loadSettings() async {
|
||||
_settingsService = await settings.SettingsService.getInstance();
|
||||
if (_keyboardShortcutsSupported) {
|
||||
@@ -88,6 +164,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_seekTimeLarge = _settingsService.getSeekTimeLarge();
|
||||
_sleepTimerDuration = _settingsService.getSleepTimerDuration();
|
||||
_rememberTrackSelections = _settingsService.getRememberTrackSelections();
|
||||
_clickVideoTogglesPlayback = _settingsService.getClickVideoTogglesPlayback();
|
||||
_autoSkipIntro = _settingsService.getAutoSkipIntro();
|
||||
_autoSkipCredits = _settingsService.getAutoSkipCredits();
|
||||
_autoSkipDelay = _settingsService.getAutoSkipDelay();
|
||||
@@ -95,6 +172,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_videoPlayerNavigationEnabled = _settingsService.getVideoPlayerNavigationEnabled();
|
||||
_maxVolume = _settingsService.getMaxVolume();
|
||||
_enableDiscordRPC = _settingsService.getEnableDiscordRPC();
|
||||
_matchContentFrameRate = _settingsService.getMatchContentFrameRate();
|
||||
_useExoPlayer = _settingsService.getUseExoPlayer();
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
@@ -106,29 +185,32 @@ 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),
|
||||
_buildDownloadsSection(),
|
||||
const SizedBox(height: 24),
|
||||
if (_keyboardShortcutsSupported) ...[_buildKeyboardShortcutsSection(), const SizedBox(height: 24)],
|
||||
_buildAdvancedSection(),
|
||||
const SizedBox(height: 24),
|
||||
if (UpdateService.isUpdateCheckEnabled) ...[_buildUpdateSection(), const SizedBox(height: 24)],
|
||||
_buildAboutSection(),
|
||||
const SizedBox(height: 24),
|
||||
]),
|
||||
body: Focus(
|
||||
onKeyEvent: _handleKeyEvent,
|
||||
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),
|
||||
_buildVideoPlaybackSection(),
|
||||
const SizedBox(height: 24),
|
||||
_buildDownloadsSection(),
|
||||
const SizedBox(height: 24),
|
||||
if (_keyboardShortcutsSupported) ...[_buildKeyboardShortcutsSection(), const SizedBox(height: 24)],
|
||||
_buildAdvancedSection(),
|
||||
const SizedBox(height: 24),
|
||||
if (UpdateService.isUpdateCheckEnabled) ...[_buildUpdateSection(), const SizedBox(height: 24)],
|
||||
_buildAboutSection(),
|
||||
const SizedBox(height: 24),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -148,6 +230,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Consumer<ThemeProvider>(
|
||||
builder: (context, themeProvider, child) {
|
||||
return ListTile(
|
||||
focusNode: _focusTracker.get(_kTheme),
|
||||
leading: AppIcon(themeProvider.themeModeIcon, fill: 1),
|
||||
title: Text(t.settings.theme),
|
||||
subtitle: Text(themeProvider.themeModeDisplayName),
|
||||
@@ -157,6 +240,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kLanguage),
|
||||
leading: const AppIcon(Symbols.language_rounded, fill: 1),
|
||||
title: Text(t.settings.language),
|
||||
subtitle: Text(_getLanguageDisplayName(LocaleSettings.currentLocale)),
|
||||
@@ -166,6 +250,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return ListTile(
|
||||
focusNode: _focusTracker.get(_kLibraryDensity),
|
||||
leading: const AppIcon(Symbols.grid_view_rounded, fill: 1),
|
||||
title: Text(t.settings.libraryDensity),
|
||||
subtitle: Text(settingsProvider.libraryDensityDisplayName),
|
||||
@@ -177,6 +262,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return ListTile(
|
||||
focusNode: _focusTracker.get(_kViewMode),
|
||||
leading: const AppIcon(Symbols.view_list_rounded, fill: 1),
|
||||
title: Text(t.settings.viewMode),
|
||||
subtitle: Text(
|
||||
@@ -189,20 +275,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SwitchListTile(
|
||||
secondary: const AppIcon(Symbols.image_rounded, fill: 1),
|
||||
title: Text(t.settings.useSeasonPosters),
|
||||
subtitle: Text(t.settings.useSeasonPostersDescription),
|
||||
value: settingsProvider.useSeasonPoster,
|
||||
onChanged: (value) async {
|
||||
await settingsProvider.setUseSeasonPoster(value);
|
||||
},
|
||||
return ListTile(
|
||||
focusNode: _focusTracker.get(_kEpisodePosterMode),
|
||||
leading: const AppIcon(Symbols.image_rounded, fill: 1),
|
||||
title: Text(t.settings.episodePosterMode),
|
||||
subtitle: Text(settingsProvider.episodePosterModeDisplayName),
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () => _showEpisodePosterModeDialog(),
|
||||
);
|
||||
},
|
||||
),
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kShowHeroSection),
|
||||
secondary: const AppIcon(Symbols.featured_play_list_rounded, fill: 1),
|
||||
title: Text(t.settings.showHeroSection),
|
||||
subtitle: Text(t.settings.showHeroSectionDescription),
|
||||
@@ -213,12 +299,57 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
},
|
||||
),
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kUseGlobalHubs),
|
||||
secondary: const AppIcon(Symbols.home_rounded, fill: 1),
|
||||
title: Text(t.settings.useGlobalHubs),
|
||||
subtitle: Text(t.settings.useGlobalHubsDescription),
|
||||
value: settingsProvider.useGlobalHubs,
|
||||
onChanged: (value) async {
|
||||
await settingsProvider.setUseGlobalHubs(value);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kShowServerNameOnHubs),
|
||||
secondary: const AppIcon(Symbols.dns_rounded, fill: 1),
|
||||
title: Text(t.settings.showServerNameOnHubs),
|
||||
subtitle: Text(t.settings.showServerNameOnHubsDescription),
|
||||
value: settingsProvider.showServerNameOnHubs,
|
||||
onChanged: (value) async {
|
||||
await settingsProvider.setShowServerNameOnHubs(value);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
if (PlatformDetector.shouldUseSideNavigation(context))
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kAlwaysKeepSidebarOpen),
|
||||
secondary: const AppIcon(Symbols.dock_to_left_rounded, fill: 1),
|
||||
title: Text(t.settings.alwaysKeepSidebarOpen),
|
||||
subtitle: Text(t.settings.alwaysKeepSidebarOpenDescription),
|
||||
value: settingsProvider.alwaysKeepSidebarOpen,
|
||||
onChanged: (value) async {
|
||||
await settingsProvider.setAlwaysKeepSidebarOpen(value);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildVideoPlaybackSection() {
|
||||
final isMobile = PlatformDetector.isMobile(context);
|
||||
|
||||
return Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -230,7 +361,17 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
if (Platform.isAndroid)
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kPlayerBackend),
|
||||
leading: const AppIcon(Symbols.play_circle_rounded, fill: 1),
|
||||
title: Text(t.settings.playerBackend),
|
||||
subtitle: Text(_useExoPlayer ? t.settings.exoPlayerDescription : t.settings.mpvDescription),
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () => _showPlayerBackendDialog(),
|
||||
),
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kHardwareDecoding),
|
||||
secondary: const AppIcon(Symbols.hardware_rounded, fill: 1),
|
||||
title: Text(t.settings.hardwareDecoding),
|
||||
subtitle: Text(t.settings.hardwareDecodingDescription),
|
||||
@@ -242,7 +383,22 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
await _settingsService.setEnableHardwareDecoding(value);
|
||||
},
|
||||
),
|
||||
if (Platform.isAndroid)
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kMatchContentFrameRate),
|
||||
secondary: const AppIcon(Symbols.display_settings_rounded, fill: 1),
|
||||
title: Text(t.settings.matchContentFrameRate),
|
||||
subtitle: Text(t.settings.matchContentFrameRateDescription),
|
||||
value: _matchContentFrameRate,
|
||||
onChanged: (value) async {
|
||||
setState(() {
|
||||
_matchContentFrameRate = value;
|
||||
});
|
||||
await _settingsService.setMatchContentFrameRate(value);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kBufferSize),
|
||||
leading: const AppIcon(Symbols.memory_rounded, fill: 1),
|
||||
title: Text(t.settings.bufferSize),
|
||||
subtitle: Text(t.settings.bufferSizeMB(size: _bufferSize.toString())),
|
||||
@@ -250,6 +406,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
onTap: () => _showBufferSizeDialog(),
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kSubtitleStyling),
|
||||
leading: const AppIcon(Symbols.subtitles_rounded, fill: 1),
|
||||
title: Text(t.settings.subtitleStyling),
|
||||
subtitle: Text(t.settings.subtitleStylingDescription),
|
||||
@@ -258,16 +415,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (context) => const SubtitleStylingScreen()));
|
||||
},
|
||||
),
|
||||
// MPV Config is only available when using MPV player backend
|
||||
if (!Platform.isAndroid || !_useExoPlayer)
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kMpvConfig),
|
||||
leading: const AppIcon(Symbols.tune_rounded, fill: 1),
|
||||
title: Text(t.mpvConfig.title),
|
||||
subtitle: Text(t.mpvConfig.description),
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (context) => const MpvConfigScreen()));
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const AppIcon(Symbols.tune_rounded, fill: 1),
|
||||
title: Text(t.mpvConfig.title),
|
||||
subtitle: Text(t.mpvConfig.description),
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (context) => const MpvConfigScreen()));
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kSmallSkipDuration),
|
||||
leading: const AppIcon(Symbols.replay_10_rounded, fill: 1),
|
||||
title: Text(t.settings.smallSkipDuration),
|
||||
subtitle: Text(t.settings.secondsUnit(seconds: _seekTimeSmall.toString())),
|
||||
@@ -275,6 +436,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
onTap: () => _showSeekTimeSmallDialog(),
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kLargeSkipDuration),
|
||||
leading: const AppIcon(Symbols.replay_30_rounded, fill: 1),
|
||||
title: Text(t.settings.largeSkipDuration),
|
||||
subtitle: Text(t.settings.secondsUnit(seconds: _seekTimeLarge.toString())),
|
||||
@@ -282,6 +444,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
onTap: () => _showSeekTimeLargeDialog(),
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kDefaultSleepTimer),
|
||||
leading: const AppIcon(Symbols.bedtime_rounded, fill: 1),
|
||||
title: Text(t.settings.defaultSleepTimer),
|
||||
subtitle: Text(t.settings.minutesUnit(minutes: _sleepTimerDuration.toString())),
|
||||
@@ -289,6 +452,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
onTap: () => _showSleepTimerDurationDialog(),
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kMaxVolume),
|
||||
leading: const AppIcon(Symbols.volume_up_rounded, fill: 1),
|
||||
title: Text(t.settings.maxVolume),
|
||||
subtitle: Text(t.settings.maxVolumePercent(percent: _maxVolume.toString())),
|
||||
@@ -297,6 +461,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
if (DiscordRPCService.isAvailable)
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kDiscordRichPresence),
|
||||
secondary: const AppIcon(Symbols.chat_rounded, fill: 1),
|
||||
title: Text(t.settings.discordRichPresence),
|
||||
subtitle: Text(t.settings.discordRichPresenceDescription),
|
||||
@@ -308,6 +473,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kRememberTrackSelections),
|
||||
secondary: const AppIcon(Symbols.bookmark_rounded, fill: 1),
|
||||
title: Text(t.settings.rememberTrackSelections),
|
||||
subtitle: Text(t.settings.rememberTrackSelectionsDescription),
|
||||
@@ -319,6 +485,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
await _settingsService.setRememberTrackSelections(value);
|
||||
},
|
||||
),
|
||||
if (!isMobile)
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kClickVideoTogglesPlayback),
|
||||
secondary: const AppIcon(Symbols.play_pause_rounded, fill: 1),
|
||||
title: Text(t.settings.clickVideoTogglesPlayback),
|
||||
subtitle: Text(t.settings.clickVideoTogglesPlaybackDescription),
|
||||
value: _clickVideoTogglesPlayback,
|
||||
onChanged: (value) async {
|
||||
setState(() {
|
||||
_clickVideoTogglesPlayback = value;
|
||||
});
|
||||
await _settingsService.setClickVideoTogglesPlayback(value);
|
||||
},
|
||||
),
|
||||
const Divider(),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
|
||||
@@ -331,6 +511,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
),
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kAutoSkipIntro),
|
||||
secondary: const AppIcon(Symbols.fast_forward_rounded, fill: 1),
|
||||
title: Text(t.settings.autoSkipIntro),
|
||||
subtitle: Text(t.settings.autoSkipIntroDescription),
|
||||
@@ -343,6 +524,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kAutoSkipCredits),
|
||||
secondary: const AppIcon(Symbols.skip_next_rounded, fill: 1),
|
||||
title: Text(t.settings.autoSkipCredits),
|
||||
subtitle: Text(t.settings.autoSkipCreditsDescription),
|
||||
@@ -355,6 +537,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kAutoSkipDelay),
|
||||
leading: const AppIcon(Symbols.timer_rounded, fill: 1),
|
||||
title: Text(t.settings.autoSkipDelay),
|
||||
subtitle: Text(t.settings.autoSkipDelayDescription(seconds: _autoSkipDelay.toString())),
|
||||
@@ -389,6 +572,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
final currentPath = snapshot.data ?? '...';
|
||||
|
||||
return ListTile(
|
||||
focusNode: _focusTracker.get(_kDownloadLocation),
|
||||
leading: const AppIcon(Symbols.folder_rounded, fill: 1),
|
||||
title: Text(isCustom ? t.settings.downloadLocationCustom : t.settings.downloadLocationDefault),
|
||||
subtitle: Text(currentPath, maxLines: 2, overflow: TextOverflow.ellipsis),
|
||||
@@ -398,6 +582,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kDownloadOnWifiOnly),
|
||||
secondary: const AppIcon(Symbols.wifi_rounded, fill: 1),
|
||||
title: Text(t.settings.downloadOnWifiOnly),
|
||||
subtitle: Text(t.settings.downloadOnWifiOnlyDescription),
|
||||
@@ -531,6 +716,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kVideoPlayerControls),
|
||||
leading: const AppIcon(Symbols.keyboard_rounded, fill: 1),
|
||||
title: Text(t.settings.videoPlayerControls),
|
||||
subtitle: Text(t.settings.keyboardShortcutsDescription),
|
||||
@@ -538,6 +724,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
onTap: () => _showKeyboardShortcutsDialog(),
|
||||
),
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kVideoPlayerNavigation),
|
||||
secondary: const AppIcon(Symbols.gamepad_rounded, fill: 1),
|
||||
title: Text(t.settings.videoPlayerNavigation),
|
||||
subtitle: Text(t.settings.videoPlayerNavigationDescription),
|
||||
@@ -567,6 +754,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
),
|
||||
SwitchListTile(
|
||||
focusNode: _focusTracker.get(_kDebugLogging),
|
||||
secondary: const AppIcon(Symbols.bug_report_rounded, fill: 1),
|
||||
title: Text(t.settings.debugLogging),
|
||||
subtitle: Text(t.settings.debugLoggingDescription),
|
||||
@@ -579,6 +767,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kViewLogs),
|
||||
leading: const AppIcon(Symbols.article_rounded, fill: 1),
|
||||
title: Text(t.settings.viewLogs),
|
||||
subtitle: Text(t.settings.viewLogsDescription),
|
||||
@@ -588,6 +777,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kClearCache),
|
||||
leading: const AppIcon(Symbols.cleaning_services_rounded, fill: 1),
|
||||
title: Text(t.settings.clearCache),
|
||||
subtitle: Text(t.settings.clearCacheDescription),
|
||||
@@ -595,6 +785,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
onTap: () => _showClearCacheDialog(),
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kResetSettings),
|
||||
leading: const AppIcon(Symbols.restore_rounded, fill: 1),
|
||||
title: Text(t.settings.resetSettings),
|
||||
subtitle: Text(t.settings.resetSettingsDescription),
|
||||
@@ -621,15 +812,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kCheckForUpdates),
|
||||
leading: AppIcon(
|
||||
hasUpdate ? Symbols.system_update_rounded : Symbols.check_circle_rounded,
|
||||
fill: 1,
|
||||
color: hasUpdate ? Colors.orange : null,
|
||||
),
|
||||
title: Text(hasUpdate ? t.settings.updateAvailable : t.settings.checkForUpdates),
|
||||
subtitle: hasUpdate
|
||||
? Text(t.update.versionAvailable(version: _updateInfo!['latestVersion']))
|
||||
: Text(t.update.checkFailed),
|
||||
subtitle: hasUpdate ? Text(t.update.versionAvailable(version: _updateInfo!['latestVersion'])) : null,
|
||||
trailing: _isCheckingForUpdate
|
||||
? const SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
@@ -651,6 +841,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Widget _buildAboutSection() {
|
||||
return Card(
|
||||
child: ListTile(
|
||||
focusNode: _focusTracker.get(_kAbout),
|
||||
leading: const AppIcon(Symbols.info_rounded, fill: 1),
|
||||
title: Text(t.settings.about),
|
||||
subtitle: Text(t.settings.aboutDescription),
|
||||
@@ -798,6 +989,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
required Future<void> Function(int value) onSave,
|
||||
}) {
|
||||
int spinnerValue = currentValue;
|
||||
final saveFocusNode = FocusNode();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
@@ -820,6 +1012,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
spinnerValue = value;
|
||||
});
|
||||
},
|
||||
onConfirm: () => saveFocusNode.requestFocus(),
|
||||
onCancel: () => Navigator.pop(dialogContext),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
@@ -833,6 +1027,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.common.cancel)),
|
||||
TextButton(
|
||||
focusNode: saveFocusNode,
|
||||
onPressed: () async {
|
||||
await onSave(spinnerValue);
|
||||
if (dialogContext.mounted) {
|
||||
@@ -846,7 +1041,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
).then((_) => saveFocusNode.dispose());
|
||||
}
|
||||
|
||||
/// Standard numeric input dialog with TextField for non-TV platforms.
|
||||
@@ -1005,6 +1200,53 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
void _showPlayerBackendDialog() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Text(t.settings.playerBackend),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ListTile(
|
||||
leading: AppIcon(
|
||||
_useExoPlayer ? Symbols.radio_button_checked_rounded : Symbols.radio_button_unchecked_rounded,
|
||||
fill: 1,
|
||||
),
|
||||
title: Text(t.settings.exoPlayer),
|
||||
subtitle: Text(t.settings.exoPlayerDescription),
|
||||
onTap: () async {
|
||||
setState(() {
|
||||
_useExoPlayer = true;
|
||||
});
|
||||
await _settingsService.setUseExoPlayer(true);
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: AppIcon(
|
||||
!_useExoPlayer ? Symbols.radio_button_checked_rounded : Symbols.radio_button_unchecked_rounded,
|
||||
fill: 1,
|
||||
),
|
||||
title: Text(t.settings.mpv),
|
||||
subtitle: Text(t.settings.mpvDescription),
|
||||
onTap: () async {
|
||||
setState(() {
|
||||
_useExoPlayer = false;
|
||||
});
|
||||
await _settingsService.setUseExoPlayer(false);
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [TextButton(onPressed: () => Navigator.pop(context), child: Text(t.common.cancel))],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _showKeyboardShortcutsDialog() {
|
||||
if (_keyboardService == null) return;
|
||||
|
||||
@@ -1077,6 +1319,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
return 'English';
|
||||
case AppLocale.sv:
|
||||
return 'Svenska';
|
||||
case AppLocale.fr:
|
||||
return 'Français';
|
||||
case AppLocale.it:
|
||||
return 'Italiano';
|
||||
case AppLocale.nl:
|
||||
@@ -1297,6 +1541,31 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
onSelect: (value, provider) => provider.setViewMode(value),
|
||||
);
|
||||
}
|
||||
|
||||
void _showEpisodePosterModeDialog() {
|
||||
_showOptionSelectionDialog<settings.EpisodePosterMode>(
|
||||
title: t.settings.episodePosterMode,
|
||||
options: [
|
||||
_DialogOption(
|
||||
value: settings.EpisodePosterMode.seriesPoster,
|
||||
title: t.settings.seriesPoster,
|
||||
subtitle: t.settings.seriesPosterDescription,
|
||||
),
|
||||
_DialogOption(
|
||||
value: settings.EpisodePosterMode.seasonPoster,
|
||||
title: t.settings.seasonPoster,
|
||||
subtitle: t.settings.seasonPosterDescription,
|
||||
),
|
||||
_DialogOption(
|
||||
value: settings.EpisodePosterMode.episodeThumbnail,
|
||||
title: t.settings.episodeThumbnail,
|
||||
subtitle: t.settings.episodeThumbnailDescription,
|
||||
),
|
||||
],
|
||||
getCurrentValue: (p) => p.episodePosterMode,
|
||||
onSelect: (value, provider) => provider.setEpisodePosterMode(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _KeyboardShortcutsScreen extends StatefulWidget {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -12,27 +12,12 @@ 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)
|
||||
/// Clear any cached data (for compatibility with existing callers)
|
||||
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;
|
||||
// Cache is now managed by LibrariesProvider
|
||||
// This method is kept for compatibility
|
||||
}
|
||||
|
||||
/// Fetch libraries from all online servers
|
||||
@@ -48,7 +33,7 @@ class DataAggregationService {
|
||||
|
||||
/// Fetch "On Deck" (Continue Watching) from all servers and merge by recency
|
||||
/// Items are automatically tagged with server info by PlexClient
|
||||
Future<List<PlexMetadata>> getOnDeckFromAllServers({int? limit}) async {
|
||||
Future<List<PlexMetadata>> getOnDeckFromAllServers({int? limit, Set<String>? hiddenLibraryKeys}) async {
|
||||
final allOnDeck = await _perServer<PlexMetadata>(
|
||||
operationName: 'fetching on deck',
|
||||
operation: (serverId, client, server) async {
|
||||
@@ -56,53 +41,42 @@ class DataAggregationService {
|
||||
},
|
||||
);
|
||||
|
||||
// Filter out items from hidden libraries
|
||||
List<PlexMetadata> filteredOnDeck = allOnDeck;
|
||||
if (hiddenLibraryKeys != null && hiddenLibraryKeys.isNotEmpty) {
|
||||
filteredOnDeck = allOnDeck.where((item) {
|
||||
final librarySectionId = item.librarySectionID;
|
||||
if (librarySectionId == null) return true; // Keep if no section ID
|
||||
final globalKey = '${item.serverId}:$librarySectionId';
|
||||
return !hiddenLibraryKeys.contains(globalKey);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
// Sort by most recently viewed
|
||||
// Use lastViewedAt (when item was last viewed), falling back to updatedAt/addedAt if not available
|
||||
allOnDeck.sort((a, b) {
|
||||
filteredOnDeck.sort((a, b) {
|
||||
final aTime = a.lastViewedAt ?? a.updatedAt ?? a.addedAt ?? 0;
|
||||
final bTime = b.lastViewedAt ?? b.updatedAt ?? b.addedAt ?? 0;
|
||||
return bTime.compareTo(aTime); // Descending (most recent first)
|
||||
});
|
||||
|
||||
// Apply limit if specified
|
||||
final result = limit != null && limit < allOnDeck.length ? allOnDeck.sublist(0, limit) : allOnDeck;
|
||||
final result = limit != null && limit < filteredOnDeck.length ? filteredOnDeck.sublist(0, limit) : filteredOnDeck;
|
||||
|
||||
appLogger.i('Fetched ${result.length} on deck items from all servers');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 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 librariesByServer = await _perServerGrouped<PlexLibrary>(
|
||||
operationName: 'fetching libraries',
|
||||
operation: (serverId, client, server) async {
|
||||
return await client.getLibraries();
|
||||
},
|
||||
);
|
||||
|
||||
// Cache the results
|
||||
_cachedLibrariesByServer = librariesByServer;
|
||||
_librariesCacheTime = DateTime.now();
|
||||
|
||||
final totalLibraries = librariesByServer.values.fold<int>(0, (sum, libs) => sum + libs.length);
|
||||
appLogger.d('Fetched $totalLibraries libraries from ${librariesByServer.length} servers');
|
||||
|
||||
return librariesByServer;
|
||||
}
|
||||
|
||||
/// Fetch recommendation hubs from all servers using pre-fetched libraries
|
||||
/// Fetch recommendation hubs from all servers
|
||||
/// When useGlobalHubs is true (default), uses the global /hubs endpoint
|
||||
/// to get the true home page hubs like "Recently Added Movies", "Recently Added TV"
|
||||
/// When false, uses per-library hubs from /hubs/sections/{sectionId}
|
||||
Future<List<PlexHub>> getHubsFromAllServers({
|
||||
int? limit,
|
||||
Map<String, List<PlexLibrary>>? librariesByServer,
|
||||
Set<String>? hiddenLibraryKeys,
|
||||
Map<String, List<PlexLibrary>>? librariesByServer,
|
||||
bool useGlobalHubs = true,
|
||||
}) async {
|
||||
final clients = _serverManager.onlineClients;
|
||||
|
||||
@@ -111,12 +85,92 @@ class DataAggregationService {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Use pre-fetched libraries or fetch them if not provided
|
||||
final libraries = librariesByServer ?? await getLibrariesFromAllServersGrouped();
|
||||
if (useGlobalHubs) {
|
||||
return _fetchGlobalHubs(clients, limit: limit, hiddenLibraryKeys: hiddenLibraryKeys);
|
||||
} else {
|
||||
return _fetchLibraryHubs(
|
||||
clients,
|
||||
limit: limit,
|
||||
hiddenLibraryKeys: hiddenLibraryKeys,
|
||||
librariesByServer: librariesByServer,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
appLogger.d('Fetching hubs from ${clients.length} servers');
|
||||
/// Fetch global hubs using /hubs endpoint (matches official Plex client)
|
||||
Future<List<PlexHub>> _fetchGlobalHubs(
|
||||
Map<String, PlexClient> clients, {
|
||||
int? limit,
|
||||
Set<String>? hiddenLibraryKeys,
|
||||
}) async {
|
||||
appLogger.d('Fetching global hubs from ${clients.length} servers');
|
||||
|
||||
final allHubs = <PlexHub>[];
|
||||
// Fetch global hubs from all servers in parallel
|
||||
final hubFutures = clients.entries.map((entry) async {
|
||||
final serverId = entry.key;
|
||||
final client = entry.value;
|
||||
|
||||
try {
|
||||
final hubs = await client.getGlobalHubs(limit: limit ?? 10);
|
||||
appLogger.d('Fetched ${hubs.length} global hubs from server $serverId');
|
||||
|
||||
// Filter out items from hidden libraries if specified
|
||||
if (hiddenLibraryKeys != null && hiddenLibraryKeys.isNotEmpty) {
|
||||
return hubs
|
||||
.map((hub) {
|
||||
final filteredItems = hub.items.where((item) {
|
||||
// Build the global key for the item's library section
|
||||
final librarySectionId = item.librarySectionID;
|
||||
if (librarySectionId == null) return true; // Keep if no section ID
|
||||
final globalKey = '$serverId:$librarySectionId';
|
||||
return !hiddenLibraryKeys.contains(globalKey);
|
||||
}).toList();
|
||||
|
||||
if (filteredItems.isEmpty) return null;
|
||||
|
||||
return PlexHub(
|
||||
hubKey: hub.hubKey,
|
||||
title: hub.title,
|
||||
type: hub.type,
|
||||
hubIdentifier: hub.hubIdentifier,
|
||||
size: filteredItems.length,
|
||||
more: hub.more,
|
||||
items: filteredItems,
|
||||
serverId: hub.serverId,
|
||||
serverName: hub.serverName,
|
||||
);
|
||||
})
|
||||
.whereType<PlexHub>()
|
||||
.toList();
|
||||
}
|
||||
|
||||
return hubs;
|
||||
} catch (e, stackTrace) {
|
||||
appLogger.e('Failed to fetch hubs from server $serverId', error: e, stackTrace: stackTrace);
|
||||
_serverManager.updateServerStatus(serverId, false);
|
||||
return <PlexHub>[];
|
||||
}
|
||||
});
|
||||
|
||||
final results = await Future.wait(hubFutures);
|
||||
final result = _collectAndLimitResults(results, limit);
|
||||
|
||||
appLogger.i('Fetched ${result.length} global hubs from all servers');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Fetch per-library hubs using /hubs/sections/{sectionId} endpoint
|
||||
Future<List<PlexHub>> _fetchLibraryHubs(
|
||||
Map<String, PlexClient> clients, {
|
||||
int? limit,
|
||||
Set<String>? hiddenLibraryKeys,
|
||||
Map<String, List<PlexLibrary>>? librariesByServer,
|
||||
}) async {
|
||||
// Use pre-fetched libraries or fetch and group them
|
||||
final libraries = librariesByServer ?? groupLibrariesByServer(await getLibrariesFromAllServers());
|
||||
|
||||
appLogger.d('Fetching per-library hubs from ${clients.length} servers');
|
||||
|
||||
// Fetch from all servers in parallel using cached libraries
|
||||
final hubFutures = clients.entries.map((entry) async {
|
||||
@@ -176,16 +230,9 @@ class DataAggregationService {
|
||||
});
|
||||
|
||||
final results = await Future.wait(hubFutures);
|
||||
final result = _collectAndLimitResults(results, limit);
|
||||
|
||||
// Flatten results
|
||||
for (final hubs in results) {
|
||||
allHubs.addAll(hubs);
|
||||
}
|
||||
|
||||
// Apply limit if specified
|
||||
final result = limit != null && limit < allHubs.length ? allHubs.sublist(0, limit) : allHubs;
|
||||
|
||||
appLogger.i('Fetched ${result.length} hubs from all servers');
|
||||
appLogger.i('Fetched ${result.length} library hubs from all servers');
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -247,6 +294,15 @@ class DataAggregationService {
|
||||
|
||||
// Private helper methods
|
||||
|
||||
/// Collect results from multiple lists and optionally limit the total count.
|
||||
List<T> _collectAndLimitResults<T>(List<List<T>> results, int? limit) {
|
||||
final all = <T>[];
|
||||
for (final items in results) {
|
||||
all.addAll(items);
|
||||
}
|
||||
return limit != null && limit < all.length ? all.sublist(0, limit) : all;
|
||||
}
|
||||
|
||||
/// Base helper for per-server fan-out operations
|
||||
///
|
||||
/// Returns raw results as (serverId, result) tuples.
|
||||
@@ -298,15 +354,4 @@ class DataAggregationService {
|
||||
final results = await _perServerRaw(operationName: operationName, operation: operation);
|
||||
return [for (final (_, items) in results) ...items];
|
||||
}
|
||||
|
||||
/// Higher-order helper for per-server fan-out operations that groups results by server
|
||||
///
|
||||
/// Similar to [_perServer] but returns a Map with results grouped by serverId.
|
||||
Future<Map<String, List<T>>> _perServerGrouped<T>({
|
||||
required String operationName,
|
||||
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
|
||||
}) async {
|
||||
final results = await _perServerRaw(operationName: operationName, operation: operation);
|
||||
return {for (final (id, items) in results) id: items};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ class DiscordRPCService {
|
||||
DateTime? _playbackStartTime;
|
||||
Duration? _mediaDuration;
|
||||
Duration? _currentPosition;
|
||||
double _playbackSpeed = 1.0;
|
||||
Timer? _reconnectTimer;
|
||||
DateTime? _lastPresenceUpdate;
|
||||
StreamSubscription<void>? _readySubscription;
|
||||
@@ -103,11 +104,10 @@ class DiscordRPCService {
|
||||
_currentMetadata = metadata;
|
||||
_currentClient = client;
|
||||
_playbackStartTime = DateTime.now();
|
||||
_mediaDuration = metadata.duration != null
|
||||
? Duration(milliseconds: metadata.duration!)
|
||||
: null;
|
||||
_mediaDuration = metadata.duration != null ? Duration(milliseconds: metadata.duration!) : null;
|
||||
_currentPosition = Duration.zero;
|
||||
_cachedThumbnailUrl = null;
|
||||
_playbackSpeed = 1.0;
|
||||
|
||||
if (_isEnabled && _isConnected) {
|
||||
// Upload thumbnail in background, don't block playback
|
||||
@@ -135,6 +135,15 @@ class DiscordRPCService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update current playback speed (for accurate remaining time calculation)
|
||||
void updatePlaybackSpeed(double speed) {
|
||||
if (_playbackSpeed == speed) return;
|
||||
_playbackSpeed = speed;
|
||||
if (_isEnabled && _isConnected && _playbackStartTime != null) {
|
||||
_updatePresence();
|
||||
}
|
||||
}
|
||||
|
||||
/// Resume playback (restore timestamp)
|
||||
Future<void> resumePlayback() async {
|
||||
if (_currentMetadata == null) return;
|
||||
@@ -163,6 +172,7 @@ class DiscordRPCService {
|
||||
_currentClient = null;
|
||||
_playbackStartTime = null;
|
||||
_cachedThumbnailUrl = null;
|
||||
_playbackSpeed = 1.0;
|
||||
|
||||
if (_isEnabled && _isConnected) {
|
||||
await clearPresence();
|
||||
@@ -359,11 +369,15 @@ class DiscordRPCService {
|
||||
final now = DateTime.now();
|
||||
final position = _currentPosition ?? Duration.zero;
|
||||
|
||||
// Calculate when playback "started" (now minus current position)
|
||||
final effectiveStart = now.subtract(position);
|
||||
// Calculate remaining time accounting for playback speed
|
||||
final remainingDuration = _mediaDuration! - position;
|
||||
final adjustedRemaining = Duration(microseconds: (remainingDuration.inMicroseconds / _playbackSpeed).round());
|
||||
|
||||
// Calculate when playback will "end" (start + total duration)
|
||||
final effectiveEnd = effectiveStart.add(_mediaDuration!);
|
||||
// Calculate total adjusted duration for progress bar
|
||||
final adjustedTotal = Duration(microseconds: (_mediaDuration!.inMicroseconds / _playbackSpeed).round());
|
||||
|
||||
final effectiveEnd = now.add(adjustedRemaining);
|
||||
final effectiveStart = effectiveEnd.subtract(adjustedTotal);
|
||||
|
||||
return DiscordTimestamps.range(effectiveStart, effectiveEnd);
|
||||
}
|
||||
|
||||
@@ -344,16 +344,13 @@ class DownloadManagerService {
|
||||
}
|
||||
final metadata = PlexMetadata.fromJson(firstMetadata).copyWith(serverId: serverId);
|
||||
|
||||
// Get video playback data (includes URL, streams, etc.)
|
||||
// Get video playback data (includes URL, streams, markers, etc.)
|
||||
// This also caches the metadata with chapters/markers for offline use
|
||||
final playbackData = await client.getVideoPlaybackData(metadata.ratingKey);
|
||||
if (playbackData.videoUrl == null) {
|
||||
throw Exception('Could not get video URL');
|
||||
}
|
||||
|
||||
// Cache playback extras (chapters + markers) for offline use
|
||||
// This fetches and caches in one call
|
||||
await client.getPlaybackExtras(metadata.ratingKey);
|
||||
|
||||
// Determine file extension from URL or default to mp4
|
||||
final extension = _getExtensionFromUrl(playbackData.videoUrl!) ?? 'mp4';
|
||||
|
||||
|
||||
@@ -97,7 +97,6 @@ class EpisodeNavigationService {
|
||||
metadata: episode,
|
||||
preferredAudioTrack: currentAudioTrack,
|
||||
preferredSubtitleTrack: currentSubtitleTrack,
|
||||
preferredPlaybackRate: currentPlaybackRate,
|
||||
usePushReplacement: usePushReplacement,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,64 +1,17 @@
|
||||
import 'package:macos_window_utils/macos_window_utils.dart';
|
||||
import 'package:macos_window_utils/macos/ns_window_delegate.dart';
|
||||
import 'package:macos_window_utils/macos/ns_window_button_type.dart';
|
||||
import 'package:flutter/material.dart' show Offset;
|
||||
import 'fullscreen_state_manager.dart';
|
||||
import 'macos_window_delegate.dart';
|
||||
|
||||
/// Custom window delegate that manages titlebar configuration during fullscreen transitions
|
||||
class FullscreenWindowDelegate extends NSWindowDelegate {
|
||||
static const double _customButtonY = 21.0;
|
||||
|
||||
/// Custom window delegate that manages fullscreen state
|
||||
/// Note: Window manipulation (toolbar, titlebar, traffic lights) is now handled
|
||||
/// directly in Swift's WindowDelegate. This class only updates Dart-side state.
|
||||
class FullscreenWindowDelegate extends MacOSWindowDelegate {
|
||||
@override
|
||||
void windowWillEnterFullScreen() {
|
||||
// Notify global state manager
|
||||
FullscreenStateManager().setFullscreen(true);
|
||||
|
||||
// Remove toolbar and restore default titlebar before entering fullscreen
|
||||
_prepareForFullscreen();
|
||||
}
|
||||
|
||||
@override
|
||||
void windowWillExitFullScreen() {
|
||||
// Hide title and make transparent immediately (safe to do before transition)
|
||||
WindowManipulator.hideTitle();
|
||||
WindowManipulator.makeTitlebarTransparent();
|
||||
}
|
||||
|
||||
@override
|
||||
void windowDidExitFullScreen() {
|
||||
// Notify global state manager
|
||||
FullscreenStateManager().setFullscreen(false);
|
||||
|
||||
// Add toolbar and reposition traffic lights after transition completes
|
||||
WindowManipulator.addToolbar();
|
||||
|
||||
// Restore custom traffic light positions
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.closeButton,
|
||||
offset: const Offset(20, _customButtonY),
|
||||
);
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.miniaturizeButton,
|
||||
offset: const Offset(40, _customButtonY),
|
||||
);
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.zoomButton,
|
||||
offset: const Offset(60, _customButtonY),
|
||||
);
|
||||
}
|
||||
|
||||
/// Prepare titlebar for fullscreen mode
|
||||
void _prepareForFullscreen() {
|
||||
WindowManipulator.removeToolbar();
|
||||
WindowManipulator.showTitle();
|
||||
WindowManipulator.makeTitlebarOpaque();
|
||||
|
||||
// Set traffic lights to standard fullscreen positions (null = default)
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(buttonType: NSWindowButtonType.closeButton, offset: null);
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.miniaturizeButton,
|
||||
offset: null,
|
||||
);
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(buttonType: NSWindowButtonType.zoomButton, offset: null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:in_app_review/in_app_review.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
@@ -40,6 +41,8 @@ class InAppReviewService {
|
||||
if (!isEnabled) return;
|
||||
_sessionStartTime = DateTime.now();
|
||||
appLogger.d('In-app review: Session started');
|
||||
// Prompt checks should run while the app is in the foreground.
|
||||
unawaited(maybeRequestReview());
|
||||
}
|
||||
|
||||
/// End the current session and check if it qualifies
|
||||
@@ -53,7 +56,6 @@ class InAppReviewService {
|
||||
if (sessionDuration >= _minimumSessionDuration) {
|
||||
await _incrementQualifyingSessions();
|
||||
appLogger.d('In-app review: Qualifying session ended (${sessionDuration.inMinutes} minutes)');
|
||||
await maybeRequestReview();
|
||||
} else {
|
||||
appLogger.d('In-app review: Session too short (${sessionDuration.inMinutes} minutes)');
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:hotkey_manager/hotkey_manager.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../mpv/mpv.dart';
|
||||
import 'settings_service.dart';
|
||||
import '../utils/player_utils.dart';
|
||||
@@ -305,15 +306,24 @@ class KeyboardShortcutsService {
|
||||
onPreviousChapter?.call();
|
||||
break;
|
||||
case 'speed_increase':
|
||||
final newRate = (player.state.rate + 0.1).clamp(0.1, 3.0);
|
||||
player.setRate(newRate);
|
||||
final newRateUp = (player.state.rate + 0.1).clamp(0.1, 3.0);
|
||||
player.setRate(newRateUp);
|
||||
_settingsService.setDefaultPlaybackSpeed(newRateUp);
|
||||
break;
|
||||
case 'speed_decrease':
|
||||
final newRate = (player.state.rate - 0.1).clamp(0.1, 3.0);
|
||||
player.setRate(newRate);
|
||||
final newRateDown = (player.state.rate - 0.1).clamp(0.1, 3.0);
|
||||
player.setRate(newRateDown);
|
||||
_settingsService.setDefaultPlaybackSpeed(newRateDown);
|
||||
break;
|
||||
case 'speed_reset':
|
||||
player.setRate(1.0);
|
||||
_settingsService.setDefaultPlaybackSpeed(1.0);
|
||||
break;
|
||||
case 'sub_seek_next':
|
||||
player.command(['sub-seek', '1']);
|
||||
break;
|
||||
case 'sub_seek_prev':
|
||||
player.command(['sub-seek', '-1']);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -322,39 +332,43 @@ class KeyboardShortcutsService {
|
||||
String getActionDisplayName(String action) {
|
||||
switch (action) {
|
||||
case 'play_pause':
|
||||
return 'Play/Pause';
|
||||
return t.hotkeys.actions.playPause;
|
||||
case 'volume_up':
|
||||
return 'Volume Up';
|
||||
return t.hotkeys.actions.volumeUp;
|
||||
case 'volume_down':
|
||||
return 'Volume Down';
|
||||
return t.hotkeys.actions.volumeDown;
|
||||
case 'seek_forward':
|
||||
return 'Seek Forward (${_seekTimeSmall}s)';
|
||||
return t.hotkeys.actions.seekForward(seconds: _seekTimeSmall);
|
||||
case 'seek_backward':
|
||||
return 'Seek Backward (${_seekTimeSmall}s)';
|
||||
return t.hotkeys.actions.seekBackward(seconds: _seekTimeSmall);
|
||||
case 'seek_forward_large':
|
||||
return 'Seek Forward (${_seekTimeLarge}s)';
|
||||
return t.hotkeys.actions.seekForward(seconds: _seekTimeLarge);
|
||||
case 'seek_backward_large':
|
||||
return 'Seek Backward (${_seekTimeLarge}s)';
|
||||
return t.hotkeys.actions.seekBackward(seconds: _seekTimeLarge);
|
||||
case 'fullscreen_toggle':
|
||||
return 'Toggle Fullscreen';
|
||||
return t.hotkeys.actions.fullscreenToggle;
|
||||
case 'mute_toggle':
|
||||
return 'Toggle Mute';
|
||||
return t.hotkeys.actions.muteToggle;
|
||||
case 'subtitle_toggle':
|
||||
return 'Toggle Subtitles';
|
||||
return t.hotkeys.actions.subtitleToggle;
|
||||
case 'audio_track_next':
|
||||
return 'Next Audio Track';
|
||||
return t.hotkeys.actions.audioTrackNext;
|
||||
case 'subtitle_track_next':
|
||||
return 'Next Subtitle Track';
|
||||
return t.hotkeys.actions.subtitleTrackNext;
|
||||
case 'chapter_next':
|
||||
return 'Next Chapter';
|
||||
return t.hotkeys.actions.chapterNext;
|
||||
case 'chapter_previous':
|
||||
return 'Previous Chapter';
|
||||
return t.hotkeys.actions.chapterPrevious;
|
||||
case 'speed_increase':
|
||||
return 'Increase Speed';
|
||||
return t.hotkeys.actions.speedIncrease;
|
||||
case 'speed_decrease':
|
||||
return 'Decrease Speed';
|
||||
return t.hotkeys.actions.speedDecrease;
|
||||
case 'speed_reset':
|
||||
return 'Reset Speed';
|
||||
return t.hotkeys.actions.speedReset;
|
||||
case 'sub_seek_next':
|
||||
return t.hotkeys.actions.subSeekNext;
|
||||
case 'sub_seek_prev':
|
||||
return t.hotkeys.actions.subSeekPrev;
|
||||
default:
|
||||
return action;
|
||||
}
|
||||
|
||||
@@ -1,61 +1,25 @@
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:flutter/material.dart' show Offset;
|
||||
import 'package:macos_window_utils/macos_window_utils.dart';
|
||||
import 'package:macos_window_utils/macos/ns_window_button_type.dart';
|
||||
import 'fullscreen_window_delegate.dart';
|
||||
import 'macos_window_service.dart';
|
||||
|
||||
/// Service to manage macOS titlebar configuration
|
||||
class MacOSTitlebarService {
|
||||
// Standard button Y position when using custom toolbar
|
||||
static const double _customButtonY = 21.0;
|
||||
static bool _initialized = false;
|
||||
|
||||
/// Initialize the custom titlebar setup (transparent with toolbar)
|
||||
/// This configuration automatically handles fullscreen mode natively
|
||||
/// Initialize the custom titlebar setup.
|
||||
///
|
||||
/// Note: The initial window configuration (transparent titlebar, toolbar,
|
||||
/// button positions, fullscreen presentation options) is now applied in
|
||||
/// MainFlutterWindow.swift / WindowDelegate.swift BEFORE frame restoration
|
||||
/// to prevent the window from shrinking on launch.
|
||||
///
|
||||
/// This method only sets up the Dart-side callbacks.
|
||||
static Future<void> setupCustomTitlebar() async {
|
||||
if (!Platform.isMacOS) return;
|
||||
if (!Platform.isMacOS || _initialized) return;
|
||||
_initialized = true;
|
||||
|
||||
// Enable window delegate to use presentation options and fullscreen callbacks
|
||||
await WindowManipulator.initialize(enableWindowDelegate: true);
|
||||
|
||||
// Register custom delegate to handle fullscreen transitions
|
||||
await MacOSWindowService.initialize(enableWindowDelegate: true);
|
||||
final delegate = FullscreenWindowDelegate();
|
||||
WindowManipulator.addNSWindowDelegate(delegate);
|
||||
|
||||
// Make titlebar transparent but keep it functional
|
||||
await WindowManipulator.makeTitlebarTransparent();
|
||||
await WindowManipulator.hideTitle();
|
||||
await WindowManipulator.enableFullSizeContentView();
|
||||
|
||||
// Add toolbar to create space for traffic lights in normal mode
|
||||
await WindowManipulator.addToolbar();
|
||||
|
||||
// Set custom traffic light positions for normal mode
|
||||
await _setCustomButtonPositions();
|
||||
|
||||
// Configure fullscreen presentation to auto-hide toolbar and menubar
|
||||
// This tells macOS to automatically hide the toolbar when entering fullscreen
|
||||
final presentationOptions = NSAppPresentationOptions.from({
|
||||
NSAppPresentationOption.fullScreen,
|
||||
NSAppPresentationOption.autoHideToolbar,
|
||||
NSAppPresentationOption.autoHideMenuBar,
|
||||
NSAppPresentationOption.autoHideDock,
|
||||
});
|
||||
presentationOptions.applyAsFullScreenPresentationOptions();
|
||||
}
|
||||
|
||||
/// Set traffic light buttons to custom positions (with toolbar offset)
|
||||
static Future<void> _setCustomButtonPositions() async {
|
||||
await WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.closeButton,
|
||||
offset: const Offset(20, _customButtonY),
|
||||
);
|
||||
await WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.miniaturizeButton,
|
||||
offset: const Offset(40, _customButtonY),
|
||||
);
|
||||
await WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.zoomButton,
|
||||
offset: const Offset(60, _customButtonY),
|
||||
);
|
||||
MacOSWindowService.addWindowDelegate(delegate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/// Abstract class for receiving macOS window delegate callbacks.
|
||||
/// Extend this class and register with MacOSWindowService to receive
|
||||
/// fullscreen transition events.
|
||||
abstract class MacOSWindowDelegate {
|
||||
/// Called when the window is about to enter fullscreen mode.
|
||||
void windowWillEnterFullScreen() {}
|
||||
|
||||
/// Called when the window has entered fullscreen mode.
|
||||
void windowDidEnterFullScreen() {}
|
||||
|
||||
/// Called when the window is about to exit fullscreen mode.
|
||||
void windowWillExitFullScreen() {}
|
||||
|
||||
/// Called when the window has exited fullscreen mode.
|
||||
void windowDidExitFullScreen() {}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:flutter/services.dart';
|
||||
import 'macos_window_delegate.dart';
|
||||
|
||||
/// Service for manipulating macOS window properties.
|
||||
/// This is a native implementation replacing the macos_window_utils package.
|
||||
///
|
||||
/// Note: Titlebar, toolbar, and traffic light position management is now handled
|
||||
/// directly in Swift (WindowDelegate.swift) during fullscreen transitions.
|
||||
/// This service only exposes what's needed externally:
|
||||
/// - Traffic light visibility (for video controls)
|
||||
/// - Fullscreen enter/exit (for video controls)
|
||||
/// - Delegate registration (for FullscreenStateManager updates)
|
||||
class MacOSWindowService {
|
||||
static const _channel = MethodChannel('com.plezy/window_utils');
|
||||
static bool _initialized = false;
|
||||
static bool _delegateEnabled = false;
|
||||
static final List<MacOSWindowDelegate> _delegates = [];
|
||||
|
||||
// MARK: - Private Helpers
|
||||
|
||||
static Future<void> _invoke(String method, [Map<String, dynamic>? args]) async {
|
||||
if (!Platform.isMacOS) return;
|
||||
await _channel.invokeMethod(method, args);
|
||||
}
|
||||
|
||||
static void _notifyDelegates(void Function(MacOSWindowDelegate) callback) {
|
||||
for (final delegate in _delegates) {
|
||||
callback(delegate);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<dynamic> _handleMethodCall(MethodCall call) async {
|
||||
switch (call.method) {
|
||||
case 'windowWillEnterFullScreen':
|
||||
_notifyDelegates((d) => d.windowWillEnterFullScreen());
|
||||
case 'windowDidEnterFullScreen':
|
||||
_notifyDelegates((d) => d.windowDidEnterFullScreen());
|
||||
case 'windowWillExitFullScreen':
|
||||
_notifyDelegates((d) => d.windowWillExitFullScreen());
|
||||
case 'windowDidExitFullScreen':
|
||||
_notifyDelegates((d) => d.windowDidExitFullScreen());
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
/// Initialize the window service.
|
||||
/// Must be called before using other methods.
|
||||
/// Set [enableWindowDelegate] to true to receive fullscreen callbacks.
|
||||
static Future<void> initialize({bool enableWindowDelegate = false}) async {
|
||||
if (!Platform.isMacOS) return;
|
||||
|
||||
if (!_initialized) {
|
||||
await _channel.invokeMethod('initialize', {'enableWindowDelegate': enableWindowDelegate});
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
// Set up handler if not already done and delegate is requested
|
||||
if (enableWindowDelegate && !_delegateEnabled) {
|
||||
_channel.setMethodCallHandler(_handleMethodCall);
|
||||
_delegateEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a delegate to receive window events.
|
||||
static void addWindowDelegate(MacOSWindowDelegate delegate) {
|
||||
if (!_delegates.contains(delegate)) {
|
||||
_delegates.add(delegate);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a previously added delegate.
|
||||
static void removeWindowDelegate(MacOSWindowDelegate delegate) {
|
||||
_delegates.remove(delegate);
|
||||
}
|
||||
|
||||
// MARK: - Traffic Light Buttons
|
||||
|
||||
/// Show or hide all traffic light buttons (close, miniaturize, zoom).
|
||||
static Future<void> setTrafficLightsVisible(bool visible) => _invoke('setTrafficLightsVisible', {'visible': visible});
|
||||
|
||||
// MARK: - Fullscreen
|
||||
|
||||
/// Enter fullscreen mode.
|
||||
static Future<void> enterFullscreen() => _invoke('enterFullscreen');
|
||||
|
||||
/// Exit fullscreen mode.
|
||||
static Future<void> exitFullscreen() => _invoke('exitFullscreen');
|
||||
|
||||
/// Check if the window is in fullscreen mode.
|
||||
static Future<bool> isFullscreen() async {
|
||||
if (!Platform.isMacOS) return false;
|
||||
return await _channel.invokeMethod<bool>('isFullscreen') ?? false;
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,8 @@ class MediaControlsManager {
|
||||
final params = _PlaybackStateParams(isPlaying: isPlaying, position: position, speed: speed);
|
||||
|
||||
if (force) {
|
||||
// Bypass throttling for forced updates
|
||||
// Cancel any pending throttled update to prevent stale state from overwriting
|
||||
_throttledUpdate.cancel();
|
||||
await _doUpdatePlaybackState(params);
|
||||
} else {
|
||||
// Use throttled update
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:io' show Platform;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../database/app_database.dart';
|
||||
@@ -31,8 +33,15 @@ class OfflineWatchSyncService extends ChangeNotifier {
|
||||
/// Watch threshold - mark as watched when progress exceeds this percentage
|
||||
static const double watchedThreshold = 0.90;
|
||||
|
||||
/// Minimum interval between syncs (10 minutes)
|
||||
static const Duration minSyncInterval = Duration(minutes: 10);
|
||||
/// Minimum interval between syncs.
|
||||
/// Mobile: no throttle (always sync on resume for cross-device updates)
|
||||
/// Desktop: 2 minutes (reduced from 10 min to handle tab-switching better)
|
||||
static Duration get minSyncInterval {
|
||||
if (Platform.isIOS || Platform.isAndroid) {
|
||||
return Duration.zero;
|
||||
}
|
||||
return const Duration(minutes: 2);
|
||||
}
|
||||
|
||||
/// Maximum sync attempts before giving up on an item
|
||||
static const int maxSyncAttempts = 5;
|
||||
@@ -107,11 +116,14 @@ class OfflineWatchSyncService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// Called when app becomes active - syncs if interval has passed.
|
||||
/// Called when app becomes active - syncs for cross-device updates.
|
||||
/// On mobile, always syncs immediately (device-switching scenario).
|
||||
/// On desktop, respects the throttle interval.
|
||||
void onAppResumed() {
|
||||
if (_offlineModeProvider?.isOffline != true) {
|
||||
appLogger.d('App resumed - checking if sync needed');
|
||||
_performBidirectionalSync();
|
||||
final isMobile = Platform.isIOS || Platform.isAndroid;
|
||||
appLogger.d('App resumed - ${isMobile ? "forcing" : "checking"} sync');
|
||||
_performBidirectionalSync(force: isMobile);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:plezy/i18n/strings.g.dart';
|
||||
|
||||
class PipService {
|
||||
static const MethodChannel _channel = MethodChannel('app.plezy/pip');
|
||||
|
||||
// Singleton instance
|
||||
static final PipService _instance = PipService._internal();
|
||||
factory PipService() => _instance;
|
||||
|
||||
PipService._internal() {
|
||||
// Listen for callbacks from native Android
|
||||
_channel.setMethodCallHandler(_handleMethodCall);
|
||||
}
|
||||
|
||||
/// ValueNotifier for PiP state - widgets can listen to this
|
||||
final ValueNotifier<bool> isPipActive = ValueNotifier<bool>(false);
|
||||
|
||||
Future<dynamic> _handleMethodCall(MethodCall call) async {
|
||||
switch (call.method) {
|
||||
case 'onPipChanged':
|
||||
final isInPip = call.arguments as bool;
|
||||
isPipActive.value = isInPip;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> isSupported() async {
|
||||
return await _channel.invokeMethod<bool>('isSupported') ?? false;
|
||||
}
|
||||
|
||||
static Future<(bool success, String? error)> enter({int? width, int? height}) async {
|
||||
final result = await _channel.invokeMethod<Map>('enter', {'width': width, 'height': height});
|
||||
if (result == null) {
|
||||
return (false, t.videoControls.pipErrors.unknown(error: 'No response'));
|
||||
}
|
||||
final success = result['success'] as bool? ?? false;
|
||||
final errorCode = result['errorCode'] as String?;
|
||||
final errorMessage = result['errorMessage'] as String?;
|
||||
final error = errorCode != null ? _getLocalizedError(errorCode, errorMessage) : null;
|
||||
return (success, error);
|
||||
}
|
||||
|
||||
static String _getLocalizedError(String errorCode, String? errorMessage) {
|
||||
return switch (errorCode) {
|
||||
'android_version' => t.videoControls.pipErrors.androidVersion,
|
||||
'permission_disabled' => t.videoControls.pipErrors.permissionDisabled,
|
||||
'not_supported' => t.videoControls.pipErrors.notSupported,
|
||||
'failed' => t.videoControls.pipErrors.failed,
|
||||
_ => t.videoControls.pipErrors.unknown(error: errorMessage ?? 'Unknown error'),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import 'plex_client.dart';
|
||||
import 'offline_watch_sync_service.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
|
||||
/// Tracks playback progress and reports it to the Plex server.
|
||||
///
|
||||
@@ -103,6 +104,15 @@ class PlaybackProgressTracker {
|
||||
// Send progress to server immediately
|
||||
await _sendOnlineProgress(state, position, duration);
|
||||
}
|
||||
|
||||
// Emit watch state event on stop for UI updates across screens
|
||||
if (state == 'stopped' && position.inMilliseconds > 0) {
|
||||
WatchStateNotifier().notifyProgress(
|
||||
metadata: metadata,
|
||||
viewOffset: position.inMilliseconds,
|
||||
duration: duration.inMilliseconds,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to send progress update (non-critical)', error: e);
|
||||
}
|
||||
|
||||
+134
-126
@@ -20,6 +20,7 @@ import '../utils/app_logger.dart';
|
||||
import '../utils/log_redaction_manager.dart';
|
||||
import '../utils/plex_cache_parser.dart';
|
||||
import '../utils/plex_url_helper.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import 'plex_api_cache.dart';
|
||||
|
||||
/// Constants for Plex stream types
|
||||
@@ -356,7 +357,10 @@ class PlexClient {
|
||||
/// Uses cache when offline or as fallback on network error
|
||||
/// Note: OnDeck data is not relevant for offline mode
|
||||
/// Always fetches with chapters/markers but caches at base endpoint
|
||||
Future<Map<String, dynamic>> getMetadataWithImagesAndOnDeck(String ratingKey) async {
|
||||
///
|
||||
/// When [forceRefresh] is true, bypasses cache to get fresh OnDeck data.
|
||||
/// Use this when cross-device sync is needed (e.g., after app resume).
|
||||
Future<Map<String, dynamic>> getMetadataWithImagesAndOnDeck(String ratingKey, {bool forceRefresh = false}) async {
|
||||
// Cache key is always the base endpoint (no query params)
|
||||
final cacheKey = '/library/metadata/$ratingKey';
|
||||
|
||||
@@ -397,6 +401,7 @@ class PlexClient {
|
||||
|
||||
return {'metadata': metadata, 'onDeckEpisode': onDeckEpisode};
|
||||
},
|
||||
forceRefresh: forceRefresh,
|
||||
) ??
|
||||
{'metadata': null, 'onDeckEpisode': null};
|
||||
}
|
||||
@@ -443,7 +448,10 @@ class PlexClient {
|
||||
|
||||
// Online: try network first
|
||||
try {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey', queryParameters: queryParams);
|
||||
// Always include markers and chapters to ensure cached data is complete
|
||||
// This prevents cache corruption when different methods fetch the same endpoint
|
||||
final mergedParams = {'includeMarkers': 1, 'includeChapters': 1, ...?queryParams};
|
||||
final response = await _dio.get('/library/metadata/$ratingKey', queryParameters: mergedParams);
|
||||
|
||||
// Cache at base endpoint
|
||||
if (response.data != null) {
|
||||
@@ -466,12 +474,17 @@ class PlexClient {
|
||||
/// 3. If network succeeds and cacheResponse is true, cache the response
|
||||
/// 4. If network fails, fall back to cached data
|
||||
/// 5. If no cached data available, rethrow the network error
|
||||
/// Fetch data with cache fallback for offline mode and network errors.
|
||||
///
|
||||
/// When [forceRefresh] is true, skips reading from cache (still writes to cache).
|
||||
/// Use this to get fresh data when cross-device sync is needed.
|
||||
Future<T?> _fetchWithCacheFallback<T>({
|
||||
required String cacheKey,
|
||||
required Future<Response> Function() networkCall,
|
||||
required T? Function(dynamic cachedData) parseCache,
|
||||
required T? Function(Response response) parseResponse,
|
||||
bool cacheResponse = true,
|
||||
bool forceRefresh = false,
|
||||
}) async {
|
||||
if (_offlineMode) {
|
||||
final cached = await _cache.get(serverId, cacheKey);
|
||||
@@ -485,6 +498,7 @@ class PlexClient {
|
||||
}
|
||||
return parseResponse(response);
|
||||
} catch (e) {
|
||||
// On forceRefresh, still try cache as last resort on network error
|
||||
appLogger.w('Network request failed for $cacheKey, trying cache', error: e);
|
||||
final cached = await _cache.get(serverId, cacheKey);
|
||||
if (cached != null) return parseCache(cached);
|
||||
@@ -780,36 +794,6 @@ class PlexClient {
|
||||
return '${config.baseUrl}/$path'.withPlexToken(config.token);
|
||||
}
|
||||
|
||||
/// Get video URL for direct playback
|
||||
/// [mediaIndex] specifies which Media item to use (defaults to 0 - first version)
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<String?> getVideoUrl(String ratingKey, {int mediaIndex = 0}) async {
|
||||
final data = await _fetchMetadataWithCache(ratingKey);
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
|
||||
if (metadataJson != null && metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
}
|
||||
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
if (partKey != null) {
|
||||
// Return direct play URL
|
||||
return '${config.baseUrl}$partKey'.withPlexToken(config.token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Get chapters for a media item
|
||||
Future<List<PlexChapter>> getChapters(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey', queryParameters: {'includeChapters': 1});
|
||||
@@ -951,63 +935,8 @@ class PlexClient {
|
||||
return PlaybackExtras(chapters: chapters, markers: markers);
|
||||
}
|
||||
|
||||
/// Get detailed media info including chapters and tracks
|
||||
/// [mediaIndex] specifies which Media item to use (defaults to 0 - first version)
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<PlexMediaInfo?> getMediaInfo(String ratingKey, {int mediaIndex = 0}) async {
|
||||
final data = await _fetchMetadataWithCache(ratingKey);
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
|
||||
if (metadataJson != null && metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
}
|
||||
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
if (partKey != null) {
|
||||
// Parse streams using helper
|
||||
final streams = _parseStreams(part['Stream'] as List<dynamic>?);
|
||||
// Parse chapters using helper
|
||||
final chapters = _parseChapters(metadataJson);
|
||||
|
||||
return PlexMediaInfo(
|
||||
videoUrl: '${config.baseUrl}$partKey'.withPlexToken(config.token),
|
||||
audioTracks: streams.audio,
|
||||
subtitleTracks: streams.subtitles,
|
||||
chapters: chapters,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Get all available media versions for a media item
|
||||
/// Returns a list of PlexMediaVersion objects representing different quality/format options
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<List<PlexMediaVersion>> getMediaVersions(String ratingKey) async {
|
||||
final data = await _fetchMetadataWithCache(ratingKey);
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
|
||||
if (metadataJson != null && metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
return mediaList.map((media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>)).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get consolidated video playback data (URL, media info, and versions) in a single API call
|
||||
/// This method combines the functionality of getVideoUrl(), getMediaInfo(), and getMediaVersions()
|
||||
/// to reduce redundant API calls during video playback initialization.
|
||||
/// Get consolidated video playback data (URL, media info, versions, and markers) in a single API call.
|
||||
/// This is the primary method for playback initialization.
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<PlexVideoPlaybackData> getVideoPlaybackData(String ratingKey, {int mediaIndex = 0}) async {
|
||||
final data = await _fetchMetadataWithCache(ratingKey);
|
||||
@@ -1016,45 +945,68 @@ class PlexClient {
|
||||
String? videoUrl;
|
||||
PlexMediaInfo? mediaInfo;
|
||||
List<PlexMediaVersion> availableVersions = [];
|
||||
List<PlexMarker> markers = [];
|
||||
|
||||
if (metadataJson != null && metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
// Parse available media versions first
|
||||
availableVersions = mediaList.map((media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>)).toList();
|
||||
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
if (metadataJson != null) {
|
||||
// Parse markers (for auto-skip functionality)
|
||||
if (metadataJson['Marker'] != null) {
|
||||
final markerList = metadataJson['Marker'] as List;
|
||||
for (var marker in markerList) {
|
||||
markers.add(
|
||||
PlexMarker(
|
||||
id: marker['id'] as int,
|
||||
type: marker['type'] as String,
|
||||
startTimeOffset: marker['startTimeOffset'] as int,
|
||||
endTimeOffset: marker['endTimeOffset'] as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
if (metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
if (partKey != null) {
|
||||
// Get video URL
|
||||
videoUrl = '${config.baseUrl}$partKey'.withPlexToken(config.token);
|
||||
// Parse available media versions first
|
||||
availableVersions = mediaList.map((media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>)).toList();
|
||||
|
||||
// Parse streams using helper
|
||||
final streams = _parseStreams(part['Stream'] as List<dynamic>?);
|
||||
// Parse chapters using helper
|
||||
final chapters = _parseChapters(metadataJson);
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
}
|
||||
|
||||
// Create media info
|
||||
mediaInfo = PlexMediaInfo(
|
||||
videoUrl: videoUrl,
|
||||
audioTracks: streams.audio,
|
||||
subtitleTracks: streams.subtitles,
|
||||
chapters: chapters,
|
||||
partId: part['id'] as int?,
|
||||
);
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
if (partKey != null) {
|
||||
// Get video URL
|
||||
videoUrl = '${config.baseUrl}$partKey'.withPlexToken(config.token);
|
||||
|
||||
// Parse streams using helper
|
||||
final streams = _parseStreams(part['Stream'] as List<dynamic>?);
|
||||
// Parse chapters using helper
|
||||
final chapters = _parseChapters(metadataJson);
|
||||
|
||||
// Create media info
|
||||
mediaInfo = PlexMediaInfo(
|
||||
videoUrl: videoUrl,
|
||||
audioTracks: streams.audio,
|
||||
subtitleTracks: streams.subtitles,
|
||||
chapters: chapters,
|
||||
partId: part['id'] as int?,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PlexVideoPlaybackData(videoUrl: videoUrl, mediaInfo: mediaInfo, availableVersions: availableVersions);
|
||||
return PlexVideoPlaybackData(
|
||||
videoUrl: videoUrl,
|
||||
mediaInfo: mediaInfo,
|
||||
availableVersions: availableVersions,
|
||||
markers: markers,
|
||||
);
|
||||
}
|
||||
|
||||
/// Get file information for a media item
|
||||
@@ -1123,13 +1075,23 @@ class PlexClient {
|
||||
}
|
||||
|
||||
/// Mark media as watched
|
||||
Future<void> markAsWatched(String ratingKey) async {
|
||||
///
|
||||
/// If [metadata] is provided, emits a [WatchStateEvent] for UI updates.
|
||||
Future<void> markAsWatched(String ratingKey, {PlexMetadata? metadata}) async {
|
||||
await _dio.get('/:/scrobble', queryParameters: {'key': ratingKey, 'identifier': 'com.plexapp.plugins.library'});
|
||||
if (metadata != null) {
|
||||
WatchStateNotifier().notifyWatched(metadata: metadata, isNowWatched: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark media as unwatched
|
||||
Future<void> markAsUnwatched(String ratingKey) async {
|
||||
///
|
||||
/// If [metadata] is provided, emits a [WatchStateEvent] for UI updates.
|
||||
Future<void> markAsUnwatched(String ratingKey, {PlexMetadata? metadata}) async {
|
||||
await _dio.get('/:/unscrobble', queryParameters: {'key': ratingKey, 'identifier': 'com.plexapp.plugins.library'});
|
||||
if (metadata != null) {
|
||||
WatchStateNotifier().notifyWatched(metadata: metadata, isNowWatched: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Update playback progress
|
||||
@@ -1261,11 +1223,9 @@ class PlexClient {
|
||||
final hub = PlexHub.fromJson(hubJson);
|
||||
// Only include hubs that have items and are movie/show content
|
||||
if (hub.items.isNotEmpty) {
|
||||
// Filter out non-video content types and tag with server info
|
||||
// Filter to only video content (movies, shows, seasons, episodes) and tag with server info
|
||||
final videoItems = hub.items
|
||||
.where((item) {
|
||||
return item.isMovie || item.isShow;
|
||||
})
|
||||
.where((item) => item.isVideoContent)
|
||||
.map((item) => item.copyWith(serverId: serverId, serverName: serverName))
|
||||
.toList();
|
||||
|
||||
@@ -1297,14 +1257,62 @@ class PlexClient {
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get global hubs (home page recommendations)
|
||||
/// Returns actual home page hubs like "Recently Added Movies", "Recently Added TV", etc.
|
||||
/// This matches the official Plex client's home page layout.
|
||||
Future<List<PlexHub>> getGlobalHubs({int limit = 10}) async {
|
||||
try {
|
||||
final response = await _dio.get('/hubs', queryParameters: {'count': limit, 'includeGuids': 1});
|
||||
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Hub'] != null) {
|
||||
final hubs = <PlexHub>[];
|
||||
for (final hubJson in container['Hub'] as List) {
|
||||
try {
|
||||
final hub = PlexHub.fromJson(hubJson);
|
||||
if (hub.items.isEmpty) continue;
|
||||
|
||||
// Filter to only video content (movies, shows, seasons, episodes) and tag with server info
|
||||
final videoItems = hub.items
|
||||
.where((item) => item.isVideoContent)
|
||||
.map((item) => item.copyWith(serverId: serverId, serverName: serverName))
|
||||
.toList();
|
||||
|
||||
if (videoItems.isNotEmpty) {
|
||||
hubs.add(
|
||||
PlexHub(
|
||||
hubKey: hub.hubKey,
|
||||
title: hub.title,
|
||||
type: hub.type,
|
||||
hubIdentifier: hub.hubIdentifier,
|
||||
size: hub.size,
|
||||
more: hub.more,
|
||||
items: videoItems,
|
||||
serverId: serverId,
|
||||
serverName: serverName,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to parse global hub', error: e);
|
||||
}
|
||||
}
|
||||
return hubs;
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to get global hubs: $e');
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get full content from a hub using its hub key
|
||||
/// Returns the complete list of metadata items in the hub
|
||||
Future<List<PlexMetadata>> getHubContent(String hubKey) async {
|
||||
return _wrapListApiCall<PlexMetadata>(() => _dio.get(hubKey), (response) {
|
||||
final allItems = _extractMetadataList(response);
|
||||
// Filter out non-video content types
|
||||
// Filter to only video content (movies, shows, seasons, episodes)
|
||||
return allItems.where((item) {
|
||||
return item.isMovie || item.isShow;
|
||||
return item.isVideoContent;
|
||||
}).toList();
|
||||
}, 'Failed to get hub content');
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ enum LibraryDensity { compact, normal, comfortable }
|
||||
|
||||
enum ViewMode { grid, list }
|
||||
|
||||
enum EpisodePosterMode { seriesPoster, seasonPoster, episodeThumbnail }
|
||||
|
||||
class SettingsService extends BaseSharedPreferencesService {
|
||||
static const String _keyThemeMode = 'theme_mode';
|
||||
static const String _keyEnableDebugLogging = 'enable_debug_logging';
|
||||
@@ -25,11 +27,14 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
static const String _keyPreferredAudioCodec = 'preferred_audio_codec';
|
||||
static const String _keyLibraryDensity = 'library_density';
|
||||
static const String _keyViewMode = 'view_mode';
|
||||
static const String _keyUseSeasonPoster = 'use_season_poster';
|
||||
static const String _keyUseSeasonPoster = 'use_season_poster'; // Legacy key for migration
|
||||
static const String _keyEpisodePosterMode = 'episode_poster_mode';
|
||||
static const String _keySeekTimeSmall = 'seek_time_small';
|
||||
static const String _keySeekTimeLarge = 'seek_time_large';
|
||||
static const String _keyMediaVersionPreferences = 'media_version_preferences';
|
||||
static const String _keyShowHeroSection = 'show_hero_section';
|
||||
static const String _keyUseGlobalHubs = 'use_global_hubs';
|
||||
static const String _keyShowServerNameOnHubs = 'show_server_name_on_hubs';
|
||||
static const String _keySleepTimerDuration = 'sleep_timer_duration';
|
||||
static const String _keyAudioSyncOffset = 'audio_sync_offset';
|
||||
static const String _keySubtitleSyncOffset = 'subtitle_sync_offset';
|
||||
@@ -43,6 +48,7 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
static const String _keySubtitleBackgroundOpacity = 'subtitle_background_opacity';
|
||||
static const String _keyAppLocale = 'app_locale';
|
||||
static const String _keyRememberTrackSelections = 'remember_track_selections';
|
||||
static const String _keyClickVideoTogglesPlayback = 'click_video_toggles_playback';
|
||||
static const String _keyAutoSkipIntro = 'auto_skip_intro';
|
||||
static const String _keyAutoSkipCredits = 'auto_skip_credits';
|
||||
static const String _keyAutoSkipDelay = 'auto_skip_delay';
|
||||
@@ -55,6 +61,11 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
static const String _keyMpvConfigPresets = 'mpv_config_presets';
|
||||
static const String _keyMaxVolume = 'max_volume';
|
||||
static const String _keyEnableDiscordRPC = 'enable_discord_rpc';
|
||||
static const String _keyMatchContentFrameRate = 'match_content_frame_rate';
|
||||
static const String _keyDefaultPlaybackSpeed = 'default_playback_speed';
|
||||
static const String _keyAutoPlayNextEpisode = 'auto_play_next_episode';
|
||||
static const String _keyUseExoPlayer = 'use_exoplayer';
|
||||
static const String _keyAlwaysKeepSidebarOpen = 'always_keep_sidebar_open';
|
||||
|
||||
SettingsService._();
|
||||
|
||||
@@ -152,13 +163,23 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return _getEnumValue(_keyViewMode, ViewMode.values, ViewMode.grid);
|
||||
}
|
||||
|
||||
// Use Season Poster
|
||||
Future<void> setUseSeasonPoster(bool enabled) async {
|
||||
await prefs.setBool(_keyUseSeasonPoster, enabled);
|
||||
// Episode Poster Mode
|
||||
Future<void> setEpisodePosterMode(EpisodePosterMode mode) async {
|
||||
await prefs.setString(_keyEpisodePosterMode, mode.name);
|
||||
}
|
||||
|
||||
bool getUseSeasonPoster() {
|
||||
return prefs.getBool(_keyUseSeasonPoster) ?? false; // Default: false (use series poster)
|
||||
EpisodePosterMode getEpisodePosterMode() {
|
||||
// Migration: check old boolean key first
|
||||
final legacyValue = prefs.getBool(_keyUseSeasonPoster);
|
||||
if (legacyValue != null) {
|
||||
// Migrate old setting: true = seasonPoster, false = seriesPoster
|
||||
final migratedMode = legacyValue ? EpisodePosterMode.seasonPoster : EpisodePosterMode.seriesPoster;
|
||||
// Clear old key and save new format (fire and forget)
|
||||
prefs.remove(_keyUseSeasonPoster);
|
||||
prefs.setString(_keyEpisodePosterMode, migratedMode.name);
|
||||
return migratedMode;
|
||||
}
|
||||
return _getEnumValue(_keyEpisodePosterMode, EpisodePosterMode.values, EpisodePosterMode.episodeThumbnail);
|
||||
}
|
||||
|
||||
// Show Hero Section
|
||||
@@ -170,6 +191,24 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return prefs.getBool(_keyShowHeroSection) ?? true; // Default: true (show hero section)
|
||||
}
|
||||
|
||||
// Use Global Hubs (true = global /hubs endpoint, false = per-library hubs)
|
||||
Future<void> setUseGlobalHubs(bool enabled) async {
|
||||
await prefs.setBool(_keyUseGlobalHubs, enabled);
|
||||
}
|
||||
|
||||
bool getUseGlobalHubs() {
|
||||
return prefs.getBool(_keyUseGlobalHubs) ?? true; // Default: true (use global hubs like official Plex)
|
||||
}
|
||||
|
||||
// Show Server Name on Hubs (false = only on duplicates, true = always)
|
||||
Future<void> setShowServerNameOnHubs(bool enabled) async {
|
||||
await prefs.setBool(_keyShowServerNameOnHubs, enabled);
|
||||
}
|
||||
|
||||
bool getShowServerNameOnHubs() {
|
||||
return prefs.getBool(_keyShowServerNameOnHubs) ?? false; // Default: false (only show on duplicates)
|
||||
}
|
||||
|
||||
// Seek Time Small (in seconds)
|
||||
Future<void> setSeekTimeSmall(int seconds) async {
|
||||
await prefs.setInt(_keySeekTimeSmall, seconds);
|
||||
@@ -318,6 +357,8 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
'speed_increase': 'Plus',
|
||||
'speed_decrease': 'Minus',
|
||||
'speed_reset': 'R',
|
||||
'sub_seek_next': 'Ctrl+Right',
|
||||
'sub_seek_prev': 'Ctrl+Left',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -341,6 +382,8 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
'speed_increase': HotKey(key: PhysicalKeyboardKey.equal),
|
||||
'speed_decrease': HotKey(key: PhysicalKeyboardKey.minus),
|
||||
'speed_reset': HotKey(key: PhysicalKeyboardKey.keyR),
|
||||
'sub_seek_next': HotKey(key: PhysicalKeyboardKey.arrowRight, modifiers: [HotKeyModifier.control]),
|
||||
'sub_seek_prev': HotKey(key: PhysicalKeyboardKey.arrowLeft, modifiers: [HotKeyModifier.control]),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -764,6 +807,15 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return prefs.getBool(_keyRememberTrackSelections) ?? true;
|
||||
}
|
||||
|
||||
// Click on Video Player Settings
|
||||
Future<void> setClickVideoTogglesPlayback(bool value) async {
|
||||
await prefs.setBool(_keyClickVideoTogglesPlayback, value);
|
||||
}
|
||||
|
||||
bool getClickVideoTogglesPlayback() {
|
||||
return prefs.getBool(_keyClickVideoTogglesPlayback) ?? false;
|
||||
}
|
||||
|
||||
// Auto Skip Intro
|
||||
Future<void> setAutoSkipIntro(bool value) async {
|
||||
await prefs.setBool(_keyAutoSkipIntro, value);
|
||||
@@ -904,6 +956,52 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return prefs.getBool(_keyEnableDiscordRPC) ?? false; // Default disabled
|
||||
}
|
||||
|
||||
// Match Content Frame Rate (Android only)
|
||||
Future<void> setMatchContentFrameRate(bool enabled) async {
|
||||
await prefs.setBool(_keyMatchContentFrameRate, enabled);
|
||||
}
|
||||
|
||||
bool getMatchContentFrameRate() {
|
||||
return prefs.getBool(_keyMatchContentFrameRate) ?? false; // Default disabled
|
||||
}
|
||||
|
||||
// Default Playback Speed (0.5 to 3.0)
|
||||
Future<void> setDefaultPlaybackSpeed(double speed) async {
|
||||
await prefs.setDouble(_keyDefaultPlaybackSpeed, speed.clamp(0.5, 3.0));
|
||||
}
|
||||
|
||||
double getDefaultPlaybackSpeed() {
|
||||
return prefs.getDouble(_keyDefaultPlaybackSpeed) ?? 1.0; // Default: normal speed
|
||||
}
|
||||
|
||||
// Auto-Play Next Episode
|
||||
Future<void> setAutoPlayNextEpisode(bool enabled) async {
|
||||
await prefs.setBool(_keyAutoPlayNextEpisode, enabled);
|
||||
}
|
||||
|
||||
bool getAutoPlayNextEpisode() {
|
||||
return prefs.getBool(_keyAutoPlayNextEpisode) ?? true; // Default enabled
|
||||
}
|
||||
|
||||
// Use ExoPlayer on Android (default: true)
|
||||
// When false, uses MPV as the player backend
|
||||
Future<void> setUseExoPlayer(bool enabled) async {
|
||||
await prefs.setBool(_keyUseExoPlayer, enabled);
|
||||
}
|
||||
|
||||
bool getUseExoPlayer() {
|
||||
return prefs.getBool(_keyUseExoPlayer) ?? true; // Default: ExoPlayer
|
||||
}
|
||||
|
||||
// Always Keep Sidebar Open (Desktop/TV only)
|
||||
Future<void> setAlwaysKeepSidebarOpen(bool enabled) async {
|
||||
await prefs.setBool(_keyAlwaysKeepSidebarOpen, enabled);
|
||||
}
|
||||
|
||||
bool getAlwaysKeepSidebarOpen() {
|
||||
return prefs.getBool(_keyAlwaysKeepSidebarOpen) ?? false; // Default: collapsed
|
||||
}
|
||||
|
||||
// Reset all settings to defaults
|
||||
Future<void> resetAllSettings() async {
|
||||
await Future.wait([
|
||||
@@ -918,7 +1016,8 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
prefs.remove(_keyPreferredAudioCodec),
|
||||
prefs.remove(_keyLibraryDensity),
|
||||
prefs.remove(_keyViewMode),
|
||||
prefs.remove(_keyUseSeasonPoster),
|
||||
prefs.remove(_keyUseSeasonPoster), // Legacy key
|
||||
prefs.remove(_keyEpisodePosterMode),
|
||||
prefs.remove(_keyShowHeroSection),
|
||||
prefs.remove(_keySeekTimeSmall),
|
||||
prefs.remove(_keySeekTimeLarge),
|
||||
@@ -944,6 +1043,11 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
prefs.remove(_keyMpvConfigEntries),
|
||||
prefs.remove(_keyMpvConfigPresets),
|
||||
prefs.remove(_keyEnableDiscordRPC),
|
||||
prefs.remove(_keyMatchContentFrameRate),
|
||||
prefs.remove(_keyDefaultPlaybackSpeed),
|
||||
prefs.remove(_keyAutoPlayNextEpisode),
|
||||
prefs.remove(_keyUseExoPlayer),
|
||||
prefs.remove(_keyAlwaysKeepSidebarOpen),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -968,12 +1072,13 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
'preferredAudioCodec': getPreferredAudioCodec(),
|
||||
'libraryDensity': getLibraryDensity().name,
|
||||
'viewMode': getViewMode().name,
|
||||
'useSeasonPoster': getUseSeasonPoster(),
|
||||
'episodePosterMode': getEpisodePosterMode().name,
|
||||
'seekTimeSmall': getSeekTimeSmall(),
|
||||
'seekTimeLarge': getSeekTimeLarge(),
|
||||
'keyboardShortcuts': getKeyboardShortcuts(),
|
||||
'keyboardHotkeys': hotkeys.map((key, value) => MapEntry(key, _serializeHotKey(value))),
|
||||
'rememberTrackSelections': getRememberTrackSelections(),
|
||||
'clickVideoTogglesPlayback': getClickVideoTogglesPlayback(),
|
||||
'autoSkipIntro': getAutoSkipIntro(),
|
||||
'autoSkipCredits': getAutoSkipCredits(),
|
||||
'autoSkipDelay': getAutoSkipDelay(),
|
||||
|
||||
@@ -6,6 +6,305 @@ import '../models/plex_user_profile.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/language_codes.dart';
|
||||
|
||||
// ============================================================================
|
||||
// Track Matching Utilities
|
||||
// ============================================================================
|
||||
// These functions match MPV tracks to Plex tracks by properties (language,
|
||||
// codec, title, etc.) instead of list index, since the two may be ordered
|
||||
// differently.
|
||||
|
||||
/// Find the MPV subtitle track that matches a Plex subtitle track
|
||||
SubtitleTrack? findMpvTrackForPlexSubtitle(PlexSubtitleTrack plexTrack, List<SubtitleTrack> mpvTracks) {
|
||||
if (mpvTracks.isEmpty) return null;
|
||||
|
||||
// For external subtitles, match by URI containing the Plex key
|
||||
if (plexTrack.isExternal && plexTrack.key != null) {
|
||||
for (final mpvTrack in mpvTracks) {
|
||||
if (mpvTrack.isExternal && mpvTrack.uri != null) {
|
||||
// Check if the MPV URI contains the Plex key path
|
||||
if (mpvTrack.uri!.contains(plexTrack.key!)) {
|
||||
return mpvTrack;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For internal subtitles, use scoring based on properties
|
||||
SubtitleTrack? bestMatch;
|
||||
int bestScore = 0;
|
||||
|
||||
for (final mpvTrack in mpvTracks) {
|
||||
// Skip external tracks when matching internal Plex tracks
|
||||
if (!plexTrack.isExternal && mpvTrack.isExternal) continue;
|
||||
|
||||
int score = 0;
|
||||
|
||||
// Language match is most important (+10)
|
||||
if (_languagesMatch(mpvTrack.language, plexTrack.languageCode)) {
|
||||
score += 10;
|
||||
}
|
||||
|
||||
// Codec match (+5)
|
||||
if (_subtitleCodecsMatch(mpvTrack.codec, plexTrack.codec)) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
// Title match (+3)
|
||||
if (_titlesMatch(mpvTrack.title, plexTrack.title, plexTrack.displayTitle)) {
|
||||
score += 3;
|
||||
}
|
||||
|
||||
// Forced flag match (+2)
|
||||
if (mpvTrack.isForced == plexTrack.forced) {
|
||||
score += 2;
|
||||
}
|
||||
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestMatch = mpvTrack;
|
||||
}
|
||||
}
|
||||
|
||||
// Require at least language match for a valid match
|
||||
return bestScore >= 10 ? bestMatch : null;
|
||||
}
|
||||
|
||||
/// Find the Plex subtitle track that matches an MPV subtitle track
|
||||
PlexSubtitleTrack? findPlexTrackForMpvSubtitle(SubtitleTrack mpvTrack, List<PlexSubtitleTrack> plexTracks) {
|
||||
if (plexTracks.isEmpty) return null;
|
||||
|
||||
// For external subtitles, match by URI containing the Plex key
|
||||
if (mpvTrack.isExternal && mpvTrack.uri != null) {
|
||||
for (final plexTrack in plexTracks) {
|
||||
if (plexTrack.isExternal && plexTrack.key != null) {
|
||||
if (mpvTrack.uri!.contains(plexTrack.key!)) {
|
||||
return plexTrack;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For internal subtitles, use scoring based on properties
|
||||
PlexSubtitleTrack? bestMatch;
|
||||
int bestScore = 0;
|
||||
|
||||
for (final plexTrack in plexTracks) {
|
||||
// Skip external Plex tracks when matching internal MPV tracks
|
||||
if (!mpvTrack.isExternal && plexTrack.isExternal) continue;
|
||||
|
||||
int score = 0;
|
||||
|
||||
// Language match is most important (+10)
|
||||
if (_languagesMatch(mpvTrack.language, plexTrack.languageCode)) {
|
||||
score += 10;
|
||||
}
|
||||
|
||||
// Codec match (+5)
|
||||
if (_subtitleCodecsMatch(mpvTrack.codec, plexTrack.codec)) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
// Title match (+3)
|
||||
if (_titlesMatch(mpvTrack.title, plexTrack.title, plexTrack.displayTitle)) {
|
||||
score += 3;
|
||||
}
|
||||
|
||||
// Forced flag match (+2)
|
||||
if (mpvTrack.isForced == plexTrack.forced) {
|
||||
score += 2;
|
||||
}
|
||||
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestMatch = plexTrack;
|
||||
}
|
||||
}
|
||||
|
||||
// Require at least language match for a valid match
|
||||
return bestScore >= 10 ? bestMatch : null;
|
||||
}
|
||||
|
||||
/// Find the MPV audio track that matches a Plex audio track
|
||||
AudioTrack? findMpvTrackForPlexAudio(PlexAudioTrack plexTrack, List<AudioTrack> mpvTracks) {
|
||||
if (mpvTracks.isEmpty) return null;
|
||||
|
||||
AudioTrack? bestMatch;
|
||||
int bestScore = 0;
|
||||
|
||||
for (final mpvTrack in mpvTracks) {
|
||||
int score = 0;
|
||||
|
||||
// Language match is most important (+10)
|
||||
if (_languagesMatch(mpvTrack.language, plexTrack.languageCode)) {
|
||||
score += 10;
|
||||
}
|
||||
|
||||
// Codec match (+5)
|
||||
if (_audioCodecsMatch(mpvTrack.codec, plexTrack.codec)) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
// Channel count match (+3)
|
||||
if (mpvTrack.channels != null && plexTrack.channels != null) {
|
||||
if (mpvTrack.channels == plexTrack.channels) {
|
||||
score += 3;
|
||||
}
|
||||
}
|
||||
|
||||
// Title match (+2)
|
||||
if (_titlesMatch(mpvTrack.title, plexTrack.title, plexTrack.displayTitle)) {
|
||||
score += 2;
|
||||
}
|
||||
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestMatch = mpvTrack;
|
||||
}
|
||||
}
|
||||
|
||||
// Require at least language match for a valid match
|
||||
return bestScore >= 10 ? bestMatch : null;
|
||||
}
|
||||
|
||||
/// Find the Plex audio track that matches an MPV audio track
|
||||
PlexAudioTrack? findPlexTrackForMpvAudio(AudioTrack mpvTrack, List<PlexAudioTrack> plexTracks) {
|
||||
if (plexTracks.isEmpty) return null;
|
||||
|
||||
PlexAudioTrack? bestMatch;
|
||||
int bestScore = 0;
|
||||
|
||||
for (final plexTrack in plexTracks) {
|
||||
int score = 0;
|
||||
|
||||
// Language match is most important (+10)
|
||||
if (_languagesMatch(mpvTrack.language, plexTrack.languageCode)) {
|
||||
score += 10;
|
||||
}
|
||||
|
||||
// Codec match (+5)
|
||||
if (_audioCodecsMatch(mpvTrack.codec, plexTrack.codec)) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
// Channel count match (+3)
|
||||
if (mpvTrack.channels != null && plexTrack.channels != null) {
|
||||
if (mpvTrack.channels == plexTrack.channels) {
|
||||
score += 3;
|
||||
}
|
||||
}
|
||||
|
||||
// Title match (+2)
|
||||
if (_titlesMatch(mpvTrack.title, plexTrack.title, plexTrack.displayTitle)) {
|
||||
score += 2;
|
||||
}
|
||||
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestMatch = plexTrack;
|
||||
}
|
||||
}
|
||||
|
||||
// Require at least language match for a valid match
|
||||
return bestScore >= 10 ? bestMatch : null;
|
||||
}
|
||||
|
||||
/// Check if two language codes refer to the same language
|
||||
/// Handles both ISO 639-1 (2-letter) and ISO 639-2 (3-letter) codes
|
||||
bool _languagesMatch(String? mpvLang, String? plexLang) {
|
||||
if (mpvLang == null || plexLang == null) return false;
|
||||
|
||||
final mpvNormalized = mpvLang.toLowerCase().split('-').first;
|
||||
final plexNormalized = plexLang.toLowerCase().split('-').first;
|
||||
|
||||
// Direct match
|
||||
if (mpvNormalized == plexNormalized) return true;
|
||||
|
||||
// Use LanguageCodes to get all variations and check for overlap
|
||||
try {
|
||||
final mpvVariations = LanguageCodes.getVariations(mpvNormalized);
|
||||
return mpvVariations.contains(plexNormalized);
|
||||
} catch (_) {
|
||||
// LanguageCodes not initialized, fall back to direct comparison
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if two subtitle codec strings match
|
||||
/// Handles common aliases (e.g., subrip/srt, ass/ssa)
|
||||
bool _subtitleCodecsMatch(String? mpvCodec, String? plexCodec) {
|
||||
if (mpvCodec == null || plexCodec == null) return false;
|
||||
|
||||
final mpvNorm = mpvCodec.toLowerCase();
|
||||
final plexNorm = plexCodec.toLowerCase();
|
||||
|
||||
if (mpvNorm == plexNorm) return true;
|
||||
|
||||
// Common subtitle codec aliases
|
||||
const aliases = {
|
||||
'subrip': ['srt', 'subrip'],
|
||||
'srt': ['srt', 'subrip'],
|
||||
'ass': ['ass', 'ssa'],
|
||||
'ssa': ['ass', 'ssa'],
|
||||
'pgs': ['pgs', 'hdmv_pgs_subtitle'],
|
||||
'hdmv_pgs_subtitle': ['pgs', 'hdmv_pgs_subtitle'],
|
||||
'vobsub': ['vobsub', 'dvd_subtitle'],
|
||||
'dvd_subtitle': ['vobsub', 'dvd_subtitle'],
|
||||
'webvtt': ['webvtt', 'vtt'],
|
||||
'vtt': ['webvtt', 'vtt'],
|
||||
};
|
||||
|
||||
final mpvAliases = aliases[mpvNorm] ?? [mpvNorm];
|
||||
return mpvAliases.contains(plexNorm);
|
||||
}
|
||||
|
||||
/// Check if two audio codec strings match
|
||||
/// Handles common aliases (e.g., ac3/a52, dts variants)
|
||||
bool _audioCodecsMatch(String? mpvCodec, String? plexCodec) {
|
||||
if (mpvCodec == null || plexCodec == null) return false;
|
||||
|
||||
final mpvNorm = mpvCodec.toLowerCase();
|
||||
final plexNorm = plexCodec.toLowerCase();
|
||||
|
||||
if (mpvNorm == plexNorm) return true;
|
||||
|
||||
// Common audio codec aliases
|
||||
const aliases = {
|
||||
'ac3': ['ac3', 'a52', 'eac3', 'dolby digital'],
|
||||
'a52': ['ac3', 'a52'],
|
||||
'eac3': ['eac3', 'e-ac-3', 'dolby digital plus', 'ac3'],
|
||||
'dts': ['dts', 'dca'],
|
||||
'dca': ['dts', 'dca'],
|
||||
'aac': ['aac', 'mp4a'],
|
||||
'mp4a': ['aac', 'mp4a'],
|
||||
'truehd': ['truehd', 'mlp'],
|
||||
'mlp': ['truehd', 'mlp'],
|
||||
'flac': ['flac'],
|
||||
'opus': ['opus'],
|
||||
'vorbis': ['vorbis', 'ogg'],
|
||||
'mp3': ['mp3', 'mp3float'],
|
||||
};
|
||||
|
||||
final mpvAliases = aliases[mpvNorm] ?? [mpvNorm];
|
||||
return mpvAliases.contains(plexNorm);
|
||||
}
|
||||
|
||||
/// Check if titles match (fuzzy comparison)
|
||||
bool _titlesMatch(String? mpvTitle, String? plexTitle, String? plexDisplayTitle) {
|
||||
if (mpvTitle == null || mpvTitle.isEmpty) return true; // No title to match against
|
||||
|
||||
final mpvNorm = mpvTitle.toLowerCase().trim();
|
||||
|
||||
// Check exact match with either Plex title
|
||||
if (plexTitle != null && plexTitle.toLowerCase().trim() == mpvNorm) return true;
|
||||
if (plexDisplayTitle != null && plexDisplayTitle.toLowerCase().trim() == mpvNorm) return true;
|
||||
|
||||
// Check if one contains the other (partial match)
|
||||
if (plexTitle != null && plexTitle.toLowerCase().contains(mpvNorm)) return true;
|
||||
if (plexDisplayTitle != null && plexDisplayTitle.toLowerCase().contains(mpvNorm)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Priority levels for track selection
|
||||
enum TrackSelectionPriority {
|
||||
navigation, // Priority 1: User's manual selection from previous episode
|
||||
@@ -336,11 +635,15 @@ class TrackSelectionService {
|
||||
}
|
||||
|
||||
// Priority 2: Check Plex-selected track from media info
|
||||
if (plexMediaInfo != null) {
|
||||
final plexAudioTracks = plexMediaInfo!.audioTracks;
|
||||
final plexSelectedIndex = plexAudioTracks.indexWhere((t) => t.selected);
|
||||
if (plexSelectedIndex >= 0 && plexSelectedIndex < availableTracks.length) {
|
||||
return TrackSelectionResult(availableTracks[plexSelectedIndex], TrackSelectionPriority.plexSelected);
|
||||
if (plexMediaInfo != null && availableTracks.isNotEmpty) {
|
||||
final plexSelectedTrack = plexMediaInfo!.audioTracks.where((t) => t.selected).firstOrNull;
|
||||
|
||||
if (plexSelectedTrack != null) {
|
||||
final matchedMpvTrack = findMpvTrackForPlexAudio(plexSelectedTrack, availableTracks);
|
||||
|
||||
if (matchedMpvTrack != null) {
|
||||
return TrackSelectionResult(matchedMpvTrack, TrackSelectionPriority.plexSelected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,10 +699,14 @@ class TrackSelectionService {
|
||||
|
||||
// Priority 2: Check Plex-selected track from media info
|
||||
if (plexMediaInfo != null && availableTracks.isNotEmpty) {
|
||||
final plexSubtitleTracks = plexMediaInfo!.subtitleTracks;
|
||||
final plexSelectedIndex = plexSubtitleTracks.indexWhere((t) => t.selected);
|
||||
if (plexSelectedIndex >= 0 && plexSelectedIndex < availableTracks.length) {
|
||||
return TrackSelectionResult(availableTracks[plexSelectedIndex], TrackSelectionPriority.plexSelected);
|
||||
final plexSelectedTrack = plexMediaInfo!.subtitleTracks.where((t) => t.selected).firstOrNull;
|
||||
|
||||
if (plexSelectedTrack != null) {
|
||||
final matchedMpvTrack = findMpvTrackForPlexSubtitle(plexSelectedTrack, availableTracks);
|
||||
|
||||
if (matchedMpvTrack != null) {
|
||||
return TrackSelectionResult(matchedMpvTrack, TrackSelectionPriority.plexSelected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,7 +753,7 @@ class TrackSelectionService {
|
||||
Future<void> selectAndApplyTracks({
|
||||
AudioTrack? preferredAudioTrack,
|
||||
SubtitleTrack? preferredSubtitleTrack,
|
||||
double? preferredPlaybackRate,
|
||||
double? defaultPlaybackSpeed,
|
||||
Function(AudioTrack)? onAudioTrackChanged,
|
||||
Function(SubtitleTrack)? onSubtitleTrackChanged,
|
||||
}) async {
|
||||
@@ -491,9 +798,9 @@ class TrackSelectionService {
|
||||
onSubtitleTrackChanged(selectedSubtitleTrack);
|
||||
}
|
||||
|
||||
// Set playback rate if preferred rate was provided
|
||||
if (preferredPlaybackRate != null) {
|
||||
player.setRate(preferredPlaybackRate);
|
||||
// Apply default playback speed from settings
|
||||
if (defaultPlaybackSpeed != null && defaultPlaybackSpeed != 1.0) {
|
||||
player.setRate(defaultPlaybackSpeed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,9 @@ class VideoFilterManager {
|
||||
/// BoxFit mode state: 0=contain (letterbox), 1=cover (fill screen), 2=fill (stretch)
|
||||
int _boxFitMode = 0;
|
||||
|
||||
/// Store the boxFitMode before entering PiP so it can be restored
|
||||
int? _prePipBoxFitMode;
|
||||
|
||||
/// Track if a pinch gesture is occurring (public for gesture tracking)
|
||||
bool isPinching = false;
|
||||
|
||||
@@ -57,6 +60,24 @@ class VideoFilterManager {
|
||||
updateVideoFilter();
|
||||
}
|
||||
|
||||
/// Force contain mode for PiP (no cropping/stretching)
|
||||
void enterPipMode() {
|
||||
if (_boxFitMode != 0) {
|
||||
_prePipBoxFitMode = _boxFitMode;
|
||||
_boxFitMode = 0; // Contain mode
|
||||
updateVideoFilter();
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore previous mode when exiting PiP
|
||||
void exitPipMode() {
|
||||
if (_prePipBoxFitMode != null) {
|
||||
_boxFitMode = _prePipBoxFitMode!;
|
||||
_prePipBoxFitMode = null;
|
||||
updateVideoFilter();
|
||||
}
|
||||
}
|
||||
|
||||
/// Update player size when layout changes
|
||||
void updatePlayerSize(Size size) {
|
||||
// Check if size actually changed to avoid unnecessary updates
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../mpv/mpv.dart';
|
||||
import '../services/pip_service.dart';
|
||||
|
||||
/// Manages video Picture-in-Picture mode
|
||||
class VideoPIPManager {
|
||||
final Player player;
|
||||
|
||||
VideoPIPManager({required this.player});
|
||||
|
||||
Size? _playerSize;
|
||||
Size? get playerSize => _playerSize;
|
||||
|
||||
/// Callback to prepare video filter before entering PiP
|
||||
VoidCallback? onBeforeEnterPip;
|
||||
|
||||
/// Update player size for PiP aspect ratio calculation
|
||||
void updatePlayerSize(Size size) {
|
||||
_playerSize = size;
|
||||
}
|
||||
|
||||
/// Access PiP state from the service
|
||||
ValueNotifier<bool> get isPipActive => PipService().isPipActive;
|
||||
|
||||
/// Toggle native PiP
|
||||
/// Returns a tuple of (success, error message) for error handling
|
||||
Future<(bool success, String? error)> togglePIP() async {
|
||||
final supported = await PipService.isSupported();
|
||||
if (!supported) return (false, 'PiP not supported on this device');
|
||||
|
||||
// Reset video filter to contain mode BEFORE entering PiP
|
||||
// This prevents the zoomed/cropped view from being shown in PiP
|
||||
onBeforeEnterPip?.call();
|
||||
|
||||
// Wait a frame for the filter change to take effect
|
||||
await Future.delayed(const Duration(milliseconds: 50));
|
||||
|
||||
// Get display dimensions for correct aspect ratio (accounts for pixel aspect ratio)
|
||||
int? width;
|
||||
int? height;
|
||||
|
||||
try {
|
||||
final dwidth = await player.getProperty('dwidth');
|
||||
final dheight = await player.getProperty('dheight');
|
||||
if (dwidth != null && dheight != null) {
|
||||
width = int.tryParse(dwidth);
|
||||
height = int.tryParse(dheight);
|
||||
}
|
||||
} catch (_) {
|
||||
// Fall through to storage dimensions
|
||||
}
|
||||
|
||||
// Fallback to storage dimensions (less accurate for anamorphic content)
|
||||
if (width == null || height == null) {
|
||||
try {
|
||||
final videoWidth = await player.getProperty('width');
|
||||
final videoHeight = await player.getProperty('height');
|
||||
if (videoWidth != null && videoHeight != null) {
|
||||
width = int.tryParse(videoWidth);
|
||||
height = int.tryParse(videoHeight);
|
||||
}
|
||||
} catch (_) {
|
||||
// Fall through to viewport size
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to viewport size if video dimensions unavailable
|
||||
width ??= _playerSize?.width.toInt();
|
||||
height ??= _playerSize?.height.toInt();
|
||||
|
||||
return await PipService.enter(width: width, height: height);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:duration/duration.dart';
|
||||
import 'package:duration/locale.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
|
||||
/// Formats a number with a minimum number of digits using leading zeros.
|
||||
@@ -121,24 +122,44 @@ String formatDurationWithSeconds(Duration duration) {
|
||||
///
|
||||
/// Used for: video controls, chapters, episode durations.
|
||||
String formatDurationTimestamp(Duration duration) {
|
||||
final hours = duration.inHours;
|
||||
final minutes = duration.inMinutes.remainder(60);
|
||||
final seconds = duration.inSeconds.remainder(60);
|
||||
// Handle negative durations
|
||||
final isNegative = duration.isNegative;
|
||||
final absoluteDuration = duration.abs();
|
||||
|
||||
final hours = absoluteDuration.inHours;
|
||||
final minutes = absoluteDuration.inMinutes.remainder(60);
|
||||
final seconds = absoluteDuration.inSeconds.remainder(60);
|
||||
|
||||
final String result;
|
||||
|
||||
if (hours > 0) {
|
||||
return '$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
|
||||
result = '$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
|
||||
} else {
|
||||
return '$minutes:${seconds.toString().padLeft(2, '0')}';
|
||||
result = '$minutes:${seconds.toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
return isNegative ? '-$result' : result;
|
||||
}
|
||||
|
||||
/// Formats a sync offset in milliseconds with sign indicator (e.g., "+150ms", "-250ms").
|
||||
/// This format is used for audio/subtitle synchronization adjustments.
|
||||
/// Formats a sync offset in milliseconds with sign indicator (e.g., "+150ms", "-15.1s").
|
||||
/// Shows milliseconds for values < 10s, decimal seconds for larger values.
|
||||
///
|
||||
/// Used for: audio sync sheet, sync offset controls.
|
||||
String formatSyncOffset(double offsetMs) {
|
||||
final sign = offsetMs >= 0 ? '+' : '';
|
||||
return '$sign${offsetMs.round()}ms';
|
||||
final sign = offsetMs >= 0 ? '+' : '-';
|
||||
final absMs = offsetMs.abs().round();
|
||||
final durationLocale = _getDurationLocale();
|
||||
|
||||
if (absMs >= 10000) {
|
||||
// For values >= 10s, show decimal seconds (e.g., "+15.1s")
|
||||
final seconds = (offsetMs.abs() / 1000).toStringAsFixed(1);
|
||||
final unit = durationLocale.second(1, true);
|
||||
return '$sign$seconds$unit';
|
||||
}
|
||||
|
||||
// For values < 10s, show milliseconds (e.g., "+7300ms")
|
||||
final unit = durationLocale.millisecond(1, true);
|
||||
return '$sign$absMs$unit';
|
||||
}
|
||||
|
||||
/// Gets the duration package locale based on the current app locale.
|
||||
@@ -158,3 +179,24 @@ DurationLocale _getDurationLocale() {
|
||||
return const EnglishDurationLocale();
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes a list of strings and returns one long string with each item in the list concatenated by a bullet
|
||||
String toBulletedString(List<String> parts) {
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
/// Takes a date string in the format "YYYY-MM-DD" and returns a localized full date string
|
||||
/// If there is any error, `dateString` is returned as is
|
||||
String formatFullDate(String dateString) {
|
||||
try {
|
||||
// Parse the date
|
||||
final date = DateTime.parse(dateString);
|
||||
|
||||
// Create a DateFormat with the full date pattern for the current locale
|
||||
final formatter = DateFormat.yMMMMd(LocaleSettings.currentLocale.languageCode);
|
||||
|
||||
return formatter.format(date);
|
||||
} catch (e) {
|
||||
return dateString;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../services/settings_service.dart' show LibraryDensity;
|
||||
import 'layout_constants.dart';
|
||||
import 'platform_detector.dart';
|
||||
|
||||
/// Utility class for calculating consistent grid sizes across the app
|
||||
class GridSizeCalculator {
|
||||
@@ -13,19 +14,23 @@ class GridSizeCalculator {
|
||||
/// Calculates the maximum cross-axis extent for grid items based on screen size and density
|
||||
static double getMaxCrossAxisExtent(BuildContext context, LibraryDensity density) {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
final isTV = PlatformDetector.isTV();
|
||||
final isDesktop = screenWidth > desktopBreakpoint;
|
||||
final isTablet = screenWidth > tabletBreakpoint && screenWidth <= desktopBreakpoint;
|
||||
|
||||
switch (density) {
|
||||
case LibraryDensity.comfortable:
|
||||
if (isTV) return GridLayoutConstants.comfortableTV;
|
||||
if (isDesktop) return GridLayoutConstants.comfortableDesktop;
|
||||
if (isTablet) return GridLayoutConstants.comfortableTablet;
|
||||
return GridLayoutConstants.comfortableMobile;
|
||||
case LibraryDensity.compact:
|
||||
if (isTV) return GridLayoutConstants.compactTV;
|
||||
if (isDesktop) return GridLayoutConstants.compactDesktop;
|
||||
if (isTablet) return GridLayoutConstants.compactTablet;
|
||||
return GridLayoutConstants.compactMobile;
|
||||
case LibraryDensity.normal:
|
||||
if (isTV) return GridLayoutConstants.normalTV;
|
||||
if (isDesktop) return GridLayoutConstants.normalDesktop;
|
||||
if (isTablet) return GridLayoutConstants.normalTablet;
|
||||
return GridLayoutConstants.normalMobile;
|
||||
@@ -46,6 +51,24 @@ class GridSizeCalculator {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
final availableWidth = screenWidth - horizontalPadding;
|
||||
|
||||
// TV-specific sizing for 10ft viewing distance
|
||||
if (PlatformDetector.isTV()) {
|
||||
double divisor;
|
||||
double maxItemWidth;
|
||||
switch (density) {
|
||||
case LibraryDensity.comfortable:
|
||||
divisor = 7.0;
|
||||
maxItemWidth = 220;
|
||||
case LibraryDensity.normal:
|
||||
divisor = 9.0;
|
||||
maxItemWidth = 190;
|
||||
case LibraryDensity.compact:
|
||||
divisor = 11.0;
|
||||
maxItemWidth = 160;
|
||||
}
|
||||
return (availableWidth / divisor).clamp(0, maxItemWidth);
|
||||
}
|
||||
|
||||
if (ScreenBreakpoints.isWideTabletOrLarger(screenWidth)) {
|
||||
// Wide screens (desktop/large tablet landscape): Responsive division
|
||||
double divisor;
|
||||
@@ -53,31 +76,31 @@ class GridSizeCalculator {
|
||||
|
||||
switch (density) {
|
||||
case LibraryDensity.comfortable:
|
||||
divisor = 6.5;
|
||||
maxItemWidth = 280;
|
||||
divisor = 5.0;
|
||||
maxItemWidth = 320;
|
||||
case LibraryDensity.normal:
|
||||
divisor = 8.0;
|
||||
maxItemWidth = 200;
|
||||
divisor = 6.0;
|
||||
maxItemWidth = 260;
|
||||
case LibraryDensity.compact:
|
||||
divisor = 10.0;
|
||||
maxItemWidth = 160;
|
||||
divisor = 7.5;
|
||||
maxItemWidth = 200;
|
||||
}
|
||||
|
||||
return (availableWidth / divisor).clamp(0, maxItemWidth);
|
||||
} else if (ScreenBreakpoints.isTablet(screenWidth)) {
|
||||
// Medium screens (tablets): Fixed 4-5-6 items
|
||||
// Medium screens (tablets): Fixed 3-4-5 items
|
||||
int targetItemCount = switch (density) {
|
||||
LibraryDensity.comfortable => 4,
|
||||
LibraryDensity.normal => 5,
|
||||
LibraryDensity.compact => 6,
|
||||
LibraryDensity.comfortable => 3,
|
||||
LibraryDensity.normal => 4,
|
||||
LibraryDensity.compact => 5,
|
||||
};
|
||||
return availableWidth / targetItemCount;
|
||||
} else {
|
||||
// Small screens (phones): Fixed 2-3-4 items
|
||||
// Small screens (phones): Fixed 2-3-3 items
|
||||
int targetItemCount = switch (density) {
|
||||
LibraryDensity.comfortable => 2,
|
||||
LibraryDensity.normal => 3,
|
||||
LibraryDensity.compact => 4,
|
||||
LibraryDensity.compact => 3,
|
||||
};
|
||||
return availableWidth / targetItemCount;
|
||||
}
|
||||
@@ -98,4 +121,28 @@ class GridSizeCalculator {
|
||||
static bool isMobile(BuildContext context) {
|
||||
return MediaQuery.of(context).size.width <= tabletBreakpoint;
|
||||
}
|
||||
|
||||
/// Calculates the number of columns in a grid based on screen width and density.
|
||||
///
|
||||
/// Uses the same formula as Flutter's SliverGridDelegateWithMaxCrossAxisExtent:
|
||||
/// `((crossAxisExtent + crossAxisSpacing) / (maxCrossAxisExtent + crossAxisSpacing)).ceil()`
|
||||
///
|
||||
/// [horizontalPadding] should match the grid's total horizontal padding.
|
||||
static int getColumnCount(BuildContext context, LibraryDensity density, {double horizontalPadding = 16}) {
|
||||
final screenWidth = MediaQuery.of(context).size.width - horizontalPadding;
|
||||
final maxCrossAxisExtent = getMaxCrossAxisExtent(context, density);
|
||||
final crossAxisSpacing = GridLayoutConstants.crossAxisSpacing;
|
||||
// Match Flutter's grid delegate calculation
|
||||
return ((screenWidth + crossAxisSpacing) / (maxCrossAxisExtent + crossAxisSpacing)).ceil().clamp(1, 100);
|
||||
}
|
||||
|
||||
/// Check if the given index is in the first row of a grid with given column count.
|
||||
static bool isFirstRow(int index, int columnCount) {
|
||||
return index < columnCount;
|
||||
}
|
||||
|
||||
/// Check if the given index is in the first column of a grid with given column count.
|
||||
static bool isFirstColumn(int index, int columnCount) {
|
||||
return index % columnCount == 0;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user