Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e8bb9909d | ||
|
|
eea98e0cc9 | ||
|
|
6af3a2974e | ||
|
|
da64c69724 | ||
|
|
d044ae902c | ||
|
|
350102e3cb | ||
|
|
6674ee3551 | ||
|
|
eda7f6515e | ||
|
|
145ff88ccf | ||
|
|
070c8e336d | ||
|
|
78049c981b | ||
|
|
490066318c | ||
|
|
4083837c3b | ||
|
|
3fc1540f41 | ||
|
|
403df31907 | ||
|
|
d1d5b808bb | ||
|
|
9528b8f61a | ||
|
|
2276750704 | ||
|
|
a1a030a130 | ||
|
|
3d9c6b203f | ||
|
|
e23f472d78 | ||
|
|
ef2c464dd4 | ||
|
|
778ac50116 | ||
|
|
8f50da4a75 | ||
|
|
8918bdc93e | ||
|
|
a599920ab4 | ||
|
|
4095cc27e1 | ||
|
|
1eb88e23f5 | ||
|
|
edbe2a06be | ||
|
|
e9307c87f0 | ||
|
|
964b89aa67 | ||
|
|
3670383fde |
+152
-8
@@ -217,11 +217,19 @@ jobs:
|
||||
|
||||
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
|
||||
echo "Signing: $framework"
|
||||
codesign --force --sign "$IDENTITY" --timestamp --options runtime "$framework"
|
||||
done
|
||||
# Deep sign everything inside-out: executables, dylibs, XPC services, app bundles, frameworks
|
||||
find "$APP_PATH/Contents/Frameworks" \( -name "*.xpc" -o -name "*.app" -o -name "*.framework" -o -name "*.dylib" \) -print0 \
|
||||
| sort -zr \
|
||||
| while IFS= read -r -d '' item; do
|
||||
echo "Signing: $item"
|
||||
codesign --force --sign "$IDENTITY" --timestamp --options runtime "$item"
|
||||
done
|
||||
|
||||
# Sign any remaining bare executables (e.g. Sparkle's Autoupdate)
|
||||
find "$APP_PATH/Contents/Frameworks" -type f -perm +111 ! -name "*.dylib" ! -path "*/Headers/*" ! -path "*/Modules/*" -print0 \
|
||||
| while IFS= read -r -d '' exe; do
|
||||
codesign --force --sign "$IDENTITY" --timestamp --options runtime "$exe" 2>/dev/null || true
|
||||
done
|
||||
|
||||
# Sign the app bundle itself
|
||||
echo "Signing app bundle: $APP_PATH"
|
||||
@@ -269,16 +277,37 @@ jobs:
|
||||
ln -s /Applications dmg-staging/Applications
|
||||
hdiutil create -format ULMO -srcfolder dmg-staging -volname "Plezy" plezy-macos.dmg
|
||||
|
||||
- name: Sign DMG for Sparkle (EdDSA)
|
||||
if: env.SPARKLE_PRIVATE_KEY != ''
|
||||
env:
|
||||
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
|
||||
run: |
|
||||
printf -- "-----BEGIN ED25519 PRIVATE KEY-----\n%s\n-----END ED25519 PRIVATE KEY-----\n" "$SPARKLE_PRIVATE_KEY" > ed25519_key.pem
|
||||
OUTPUT=$(dart run auto_updater:sign_update plezy-macos.dmg ed25519_key.pem)
|
||||
rm ed25519_key.pem
|
||||
# Extract edSignature value from output like: sparkle:edSignature="..." length="..."
|
||||
SIGNATURE=$(echo "$OUTPUT" | grep -o 'edSignature="[^"]*"' | sed 's/edSignature="//;s/"//')
|
||||
echo "MACOS_ED_SIGNATURE=$SIGNATURE" >> $GITHUB_ENV
|
||||
echo "MACOS_DMG_SIZE=$(stat -f%z plezy-macos.dmg)" >> $GITHUB_ENV
|
||||
|
||||
- name: Attest macOS DMG
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: plezy-macos.dmg
|
||||
|
||||
- name: Write macOS signature metadata
|
||||
run: |
|
||||
echo "${{ env.MACOS_ED_SIGNATURE }}" > macos-ed-signature.txt
|
||||
echo "${{ env.MACOS_DMG_SIZE }}" > macos-dmg-size.txt
|
||||
|
||||
- name: Upload macOS DMG
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: macos-dmg
|
||||
path: plezy-macos.dmg
|
||||
path: |
|
||||
plezy-macos.dmg
|
||||
macos-ed-signature.txt
|
||||
macos-dmg-size.txt
|
||||
|
||||
build-windows-x64:
|
||||
runs-on: windows-latest
|
||||
@@ -361,6 +390,9 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Dart
|
||||
uses: dart-lang/setup-dart@v1
|
||||
|
||||
- name: Download x64 build
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
@@ -373,8 +405,34 @@ jobs:
|
||||
name: windows-arm64-build
|
||||
path: build-arm64
|
||||
|
||||
- name: Read version from pubspec
|
||||
id: version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$v = (Select-String -Path pubspec.yaml -Pattern '^version:\s*(\S+)').Matches[0].Groups[1].Value -replace '\+.*'
|
||||
echo "version=$v" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: Build installer and portables
|
||||
run: .\windows\build-installer.ps1 -X64BuildDir "build-x64" -Arm64BuildDir "build-arm64"
|
||||
run: .\windows\build-installer.ps1 -X64BuildDir "build-x64" -Arm64BuildDir "build-arm64" -Version "${{ steps.version.outputs.version }}"
|
||||
|
||||
- name: Sign installer for WinSparkle (EdDSA)
|
||||
if: env.SPARKLE_PRIVATE_KEY != ''
|
||||
env:
|
||||
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
mkdir _signer | Out-Null
|
||||
@{name="signer"; environment=@{sdk=">=3.0.0 <4.0.0"}; dependencies=@{cryptography="^2.7.0"}} | ConvertTo-Json -Depth 3 | Out-File _signer/pubspec.yaml
|
||||
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/edde746/auto_updater/main/packages/auto_updater/bin/sign_update.dart" -OutFile _signer/sign.dart
|
||||
Push-Location _signer
|
||||
dart pub get
|
||||
Set-Content -Path ed25519_key.pem -Value $env:SPARKLE_PRIVATE_KEY -Encoding ascii -NoNewline
|
||||
$output = dart run sign.dart ../plezy-windows-installer.exe ed25519_key.pem
|
||||
Pop-Location
|
||||
Remove-Item _signer -Recurse -Force
|
||||
$sig = [regex]::Match($output, 'edSignature="([^"]*)"').Groups[1].Value
|
||||
Set-Content -Path win-ed-signature.txt -Value $sig -Encoding ascii -NoNewline
|
||||
Set-Content -Path win-installer-size.txt -Value (Get-Item plezy-windows-installer.exe).Length.ToString() -Encoding ascii -NoNewline
|
||||
|
||||
- name: Attest Windows artifacts
|
||||
uses: actions/attest-build-provenance@v2
|
||||
@@ -400,7 +458,10 @@ jobs:
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-installer
|
||||
path: plezy-windows-installer.exe
|
||||
path: |
|
||||
plezy-windows-installer.exe
|
||||
win-ed-signature.txt
|
||||
win-installer-size.txt
|
||||
|
||||
build-linux-x64:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -634,6 +695,11 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: pubspec.yaml
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
@@ -642,6 +708,83 @@ jobs:
|
||||
- name: Display structure of downloaded files
|
||||
run: ls -R artifacts
|
||||
|
||||
- name: Read version from pubspec.yaml
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //' | sed 's/+.*//')
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Generate appcast.xml
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
|
||||
# Read macOS signature metadata (may be empty if secrets not configured)
|
||||
MACOS_ED_SIG=""
|
||||
MACOS_DMG_SIZE="0"
|
||||
if [ -f artifacts/macos-dmg/macos-ed-signature.txt ]; then
|
||||
MACOS_ED_SIG=$(cat artifacts/macos-dmg/macos-ed-signature.txt)
|
||||
fi
|
||||
if [ -f artifacts/macos-dmg/macos-dmg-size.txt ]; then
|
||||
MACOS_DMG_SIZE=$(cat artifacts/macos-dmg/macos-dmg-size.txt)
|
||||
fi
|
||||
|
||||
# Read Windows signature metadata (may be empty if secrets not configured)
|
||||
WIN_ED_SIG=""
|
||||
WIN_INSTALLER_SIZE="0"
|
||||
if [ -f artifacts/windows-installer/win-ed-signature.txt ]; then
|
||||
WIN_ED_SIG=$(cat artifacts/windows-installer/win-ed-signature.txt)
|
||||
fi
|
||||
if [ -f artifacts/windows-installer/win-installer-size.txt ]; then
|
||||
WIN_INSTALLER_SIZE=$(cat artifacts/windows-installer/win-installer-size.txt)
|
||||
fi
|
||||
|
||||
cat > appcast.xml << 'XMLEOF'
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
|
||||
<channel>
|
||||
<title>Plezy Updates</title>
|
||||
XMLEOF
|
||||
|
||||
# macOS entry
|
||||
if [ -n "$MACOS_ED_SIG" ]; then
|
||||
cat >> appcast.xml << XMLEOF
|
||||
<item>
|
||||
<title>Version ${VERSION}</title>
|
||||
<sparkle:version>${VERSION}</sparkle:version>
|
||||
<sparkle:os>macos</sparkle:os>
|
||||
<enclosure url="https://github.com/edde746/plezy/releases/download/${VERSION}/plezy-macos.dmg"
|
||||
length="${MACOS_DMG_SIZE}" type="application/octet-stream"
|
||||
sparkle:edSignature="${MACOS_ED_SIG}" />
|
||||
</item>
|
||||
XMLEOF
|
||||
fi
|
||||
|
||||
# Windows entry
|
||||
if [ -n "$WIN_ED_SIG" ]; then
|
||||
cat >> appcast.xml << XMLEOF
|
||||
<item>
|
||||
<title>Version ${VERSION}</title>
|
||||
<sparkle:version>${VERSION}</sparkle:version>
|
||||
<sparkle:os>windows</sparkle:os>
|
||||
<enclosure url="https://github.com/edde746/plezy/releases/download/${VERSION}/plezy-windows-installer.exe"
|
||||
length="${WIN_INSTALLER_SIZE}" type="application/octet-stream"
|
||||
sparkle:edSignature="${WIN_ED_SIG}"
|
||||
sparkle:installerArguments="/SILENT /SP-" />
|
||||
</item>
|
||||
XMLEOF
|
||||
fi
|
||||
|
||||
cat >> appcast.xml << 'XMLEOF'
|
||||
</channel>
|
||||
</rss>
|
||||
XMLEOF
|
||||
|
||||
# Clean up leading whitespace from heredoc indentation
|
||||
sed -i 's/^ //' appcast.xml
|
||||
|
||||
echo "Generated appcast.xml:"
|
||||
cat appcast.xml
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
@@ -656,6 +799,7 @@ jobs:
|
||||
artifacts/windows-installer/plezy-windows-installer.exe
|
||||
artifacts/linux-x64/*
|
||||
artifacts/linux-arm64/*
|
||||
appcast.xml
|
||||
draft: true
|
||||
prerelease: false
|
||||
generate_release_notes: true
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
cask "plezy" do
|
||||
version "1.18.2"
|
||||
sha256 "83739e8c298e19eefc1e54b1c3d054da99ad03874dbf07e069fcad0f5f264fb6"
|
||||
version "1.20.0"
|
||||
sha256 "f75b2d8bface31f42820746d8aca0aa56a9b160ff458fb68c80bacf525e34936"
|
||||
|
||||
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
|
||||
name "Plezy"
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.ActivityManager
|
||||
import android.content.ComponentCallbacks2
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Color
|
||||
import android.graphics.PixelFormat
|
||||
import android.hardware.display.DisplayManager
|
||||
@@ -102,6 +105,9 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
|
||||
private var hasAudioFocus: Boolean = false
|
||||
private var wasPlayingBeforeFocusLoss: Boolean = false
|
||||
|
||||
// Memory pressure detection
|
||||
private var memoryCallback: ComponentCallbacks2? = null
|
||||
|
||||
// Track state for event emission
|
||||
private var lastPosition: Long = 0
|
||||
private var lastDuration: Long = 0
|
||||
@@ -339,15 +345,29 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
|
||||
|
||||
val wrappedRenderersFactory = AssRenderersFactory(handler, renderersFactory)
|
||||
|
||||
val loadControl = DefaultLoadControl.Builder().apply {
|
||||
if (bufferSizeBytes != null && bufferSizeBytes > 0) {
|
||||
setTargetBufferBytes(bufferSizeBytes)
|
||||
setPrioritizeTimeOverSizeThresholds(false)
|
||||
Log.d(TAG, "Buffer byte limit set to ${bufferSizeBytes / 1024 / 1024}MB")
|
||||
} else {
|
||||
Log.d(TAG, "Buffer in auto mode (time-based thresholds)")
|
||||
// Compute memory-aware buffer limits to prevent CCodec OOM crashes
|
||||
val activityManager = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
val memoryInfo = ActivityManager.MemoryInfo()
|
||||
activityManager.getMemoryInfo(memoryInfo)
|
||||
val availableMB = memoryInfo.availMem / (1024 * 1024)
|
||||
|
||||
val targetBufferBytes = if (bufferSizeBytes != null && bufferSizeBytes > 0) {
|
||||
bufferSizeBytes
|
||||
} else {
|
||||
// Scale buffer to available memory to reduce hardware decoder pressure
|
||||
when {
|
||||
availableMB < 512 -> 50 * 1024 * 1024
|
||||
availableMB < 1024 -> 75 * 1024 * 1024
|
||||
else -> 150 * 1024 * 1024
|
||||
}
|
||||
}
|
||||
|
||||
val loadControl = DefaultLoadControl.Builder().apply {
|
||||
setTargetBufferBytes(targetBufferBytes)
|
||||
setPrioritizeTimeOverSizeThresholds(false)
|
||||
setBufferDurationsMs(15_000, 30_000, 2_500, 5_000)
|
||||
}.build()
|
||||
Log.d(TAG, "Buffer: ${targetBufferBytes / 1024 / 1024}MB limit, available=${availableMB}MB")
|
||||
|
||||
exoPlayer = ExoPlayer.Builder(activity)
|
||||
.setTrackSelector(trackSelector!!)
|
||||
@@ -381,6 +401,22 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
|
||||
}
|
||||
}
|
||||
|
||||
// Register memory pressure listener to detect impending OOM
|
||||
memoryCallback = object : ComponentCallbacks2 {
|
||||
override fun onTrimMemory(level: Int) {
|
||||
if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) {
|
||||
Log.w(TAG, "TRIM_MEMORY level $level - critical memory pressure")
|
||||
delegate?.onEvent("memory-pressure", mapOf("level" to "critical"))
|
||||
}
|
||||
}
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {}
|
||||
override fun onLowMemory() {
|
||||
Log.w(TAG, "onLowMemory - system-wide memory pressure")
|
||||
delegate?.onEvent("memory-pressure", mapOf("level" to "critical"))
|
||||
}
|
||||
}
|
||||
activity.registerComponentCallbacks(memoryCallback)
|
||||
|
||||
// Start position update loop
|
||||
startPositionUpdates()
|
||||
|
||||
@@ -1266,6 +1302,9 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
|
||||
abandonAudioFocus()
|
||||
audioManager = null
|
||||
|
||||
memoryCallback?.let { activity.unregisterComponentCallbacks(it) }
|
||||
memoryCallback = null
|
||||
|
||||
exoPlayer?.clearVideoSurface()
|
||||
exoPlayer?.removeListener(this)
|
||||
exoPlayer?.release()
|
||||
|
||||
@@ -32,6 +32,7 @@ class ExoPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
private var activity: Activity? = null
|
||||
private var activityBinding: ActivityPluginBinding? = null
|
||||
private val nameToId = mutableMapOf<String, Int>()
|
||||
private var configuredBufferSizeBytes: Int? = null
|
||||
|
||||
// FlutterPlugin
|
||||
|
||||
@@ -145,6 +146,7 @@ class ExoPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
}
|
||||
|
||||
val bufferSizeBytes = call.argument<Int>("bufferSizeBytes")
|
||||
configuredBufferSizeBytes = bufferSizeBytes
|
||||
|
||||
currentActivity.runOnUiThread {
|
||||
try {
|
||||
@@ -598,6 +600,13 @@ class ExoPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
mpvCore?.setProperty("vo", "gpu")
|
||||
mpvCore?.setProperty("ao", "audiotrack")
|
||||
|
||||
// Forward user's buffer config to MPV fallback
|
||||
configuredBufferSizeBytes?.let { bytes ->
|
||||
if (bytes > 0) {
|
||||
mpvCore?.setProperty("demuxer-max-bytes", bytes.toString())
|
||||
}
|
||||
}
|
||||
|
||||
// Setup property observers
|
||||
mpvCore?.observeProperty("time-pos", "double")
|
||||
mpvCore?.observeProperty("duration", "double")
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -7,6 +7,7 @@ import 'package:path/path.dart' as p;
|
||||
import 'tables.dart';
|
||||
import '../models/download_models.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
|
||||
part 'app_database.g.dart';
|
||||
|
||||
@@ -99,7 +100,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
required int duration,
|
||||
required bool shouldMarkWatched,
|
||||
}) async {
|
||||
final globalKey = '$serverId:$ratingKey';
|
||||
final globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
// Check for existing progress entry
|
||||
@@ -144,7 +145,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
required String ratingKey,
|
||||
required String actionType, // 'watched' or 'unwatched'
|
||||
}) async {
|
||||
final globalKey = '$serverId:$ratingKey';
|
||||
final globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
// Remove conflicting actions (opposite action type and progress)
|
||||
|
||||
@@ -83,6 +83,62 @@ KeyEventResult handleBackKeyNavigation<T>(BuildContext context, KeyEvent event,
|
||||
return handleBackKeyAction(event, () => Navigator.pop(context, result));
|
||||
}
|
||||
|
||||
/// Creates a [FocusOnKeyEventCallback] that dispatches d-pad / arrow keys to
|
||||
/// the provided directional callbacks.
|
||||
///
|
||||
/// Each callback is optional. Directions without a callback are ignored
|
||||
/// (passed through to the framework). Directions mapped to a callback
|
||||
/// automatically return [KeyEventResult.handled].
|
||||
///
|
||||
/// Only [KeyDownEvent] and [KeyRepeatEvent] are handled (via [isActionable]).
|
||||
///
|
||||
/// ```dart
|
||||
/// Focus(
|
||||
/// onKeyEvent: dpadKeyHandler(
|
||||
/// onUp: () => _focusAppBar(),
|
||||
/// onDown: () => _focusContent(),
|
||||
/// onLeft: () => _navigateToSidebar(),
|
||||
/// onSelect: () => _play(),
|
||||
/// ),
|
||||
/// child: ...
|
||||
/// )
|
||||
/// ```
|
||||
FocusOnKeyEventCallback dpadKeyHandler({
|
||||
VoidCallback? onUp,
|
||||
VoidCallback? onDown,
|
||||
VoidCallback? onLeft,
|
||||
VoidCallback? onRight,
|
||||
VoidCallback? onSelect,
|
||||
}) {
|
||||
return (FocusNode _, KeyEvent event) {
|
||||
if (!event.isActionable) return KeyEventResult.ignored;
|
||||
final key = event.logicalKey;
|
||||
|
||||
if (key.isUpKey && onUp != null) {
|
||||
onUp();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isDownKey && onDown != null) {
|
||||
onDown();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isLeftKey && onLeft != null) {
|
||||
onLeft();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isRightKey && onRight != null) {
|
||||
onRight();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isSelectKey && onSelect != null) {
|
||||
onSelect();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
};
|
||||
}
|
||||
|
||||
/// Navigator observer that automatically suppresses stray back KeyUp events
|
||||
/// after any route pop caused by a back key press.
|
||||
///
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "Schlaftimer aktiv",
|
||||
"playbackWillPauseIn": "Wiedergabe wird in ${duration} pausiert",
|
||||
"sleepTimerCompleted": "Schlaftimer abgelaufen – Wiedergabe pausiert",
|
||||
"stillWatching": "Schaust du noch?",
|
||||
"pausingIn": "Pause in ${seconds}s",
|
||||
"continueWatching": "Weiter",
|
||||
"autoPlayNext": "Nächstes automatisch abspielen",
|
||||
"playNext": "Nächstes abspielen",
|
||||
"playButton": "Wiedergeben",
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "Timer Active",
|
||||
"playbackWillPauseIn": "Playback will pause in ${duration}",
|
||||
"sleepTimerCompleted": "Sleep timer completed - playback paused",
|
||||
"stillWatching": "Still watching?",
|
||||
"pausingIn": "Pausing in ${seconds}s",
|
||||
"continueWatching": "Continue",
|
||||
"autoPlayNext": "Auto-Play Next",
|
||||
"playNext": "Play Next",
|
||||
"playButton": "Play",
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "Temporizador Activo",
|
||||
"playbackWillPauseIn": "La reproducción se pausará en ${duration}",
|
||||
"sleepTimerCompleted": "Temporizador completado - reproducción pausada",
|
||||
"stillWatching": "¿Sigues viendo?",
|
||||
"pausingIn": "Pausa en ${seconds}s",
|
||||
"continueWatching": "Continuar",
|
||||
"autoPlayNext": "Reproducir siguiente automáticamente",
|
||||
"playNext": "Reproducir siguiente",
|
||||
"playButton": "Reproducir",
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "Minuterie active",
|
||||
"playbackWillPauseIn": "La lecture sera mise en pause dans ${duration}",
|
||||
"sleepTimerCompleted": "Minuterie de mise en veille terminée - lecture en pause",
|
||||
"stillWatching": "Toujours en train de regarder ?",
|
||||
"pausingIn": "Pause dans ${seconds}s",
|
||||
"continueWatching": "Continuer",
|
||||
"autoPlayNext": "Lecture automatique suivante",
|
||||
"playNext": "Lire l'épisode suivant",
|
||||
"playButton": "Lire",
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "Timer attivo",
|
||||
"playbackWillPauseIn": "La riproduzione si interromperà tra ${duration}",
|
||||
"sleepTimerCompleted": "Timer di spegnimento completato - riproduzione in pausa",
|
||||
"stillWatching": "Stai ancora guardando?",
|
||||
"pausingIn": "Pausa tra ${seconds}s",
|
||||
"continueWatching": "Continua",
|
||||
"autoPlayNext": "Riproduzione automatica successivo",
|
||||
"playNext": "Riproduci successivo",
|
||||
"playButton": "Riproduci",
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "타이머 활성화됨",
|
||||
"playbackWillPauseIn": "재생이 ${duration} 후에 일시 중지 됩니다",
|
||||
"sleepTimerCompleted": "수면 타이머 완료됨 - 재생이 일시 중지되었습니다",
|
||||
"stillWatching": "아직 시청 중이신가요?",
|
||||
"pausingIn": "${seconds}초 후 일시 정지",
|
||||
"continueWatching": "계속",
|
||||
"autoPlayNext": "다음 자동 재생",
|
||||
"playNext": "다음 재생",
|
||||
"playButton": "재생",
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "Timer actief",
|
||||
"playbackWillPauseIn": "Afspelen wordt gepauzeerd over ${duration}",
|
||||
"sleepTimerCompleted": "Slaaptimer voltooid - afspelen gepauzeerd",
|
||||
"stillWatching": "Kijk je nog?",
|
||||
"pausingIn": "Pauze over ${seconds}s",
|
||||
"continueWatching": "Doorgaan",
|
||||
"autoPlayNext": "Automatisch volgende afspelen",
|
||||
"playNext": "Volgende afspelen",
|
||||
"playButton": "Afspelen",
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
/// To regenerate, run: `dart run slang`
|
||||
///
|
||||
/// Locales: 9
|
||||
/// Strings: 7254 (806 per locale)
|
||||
/// Strings: 7281 (809 per locale)
|
||||
///
|
||||
/// Built on 2026-02-23 at 04:30 UTC
|
||||
/// Built on 2026-02-24 at 03:45 UTC
|
||||
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, unused_import
|
||||
|
||||
@@ -460,6 +460,9 @@ class _TranslationsVideoControlsDe implements TranslationsVideoControlsEn {
|
||||
@override String get timerActive => 'Schlaftimer aktiv';
|
||||
@override String playbackWillPauseIn({required Object duration}) => 'Wiedergabe wird in ${duration} pausiert';
|
||||
@override String get sleepTimerCompleted => 'Schlaftimer abgelaufen – Wiedergabe pausiert';
|
||||
@override String get stillWatching => 'Schaust du noch?';
|
||||
@override String pausingIn({required Object seconds}) => 'Pause in ${seconds}s';
|
||||
@override String get continueWatching => 'Weiter';
|
||||
@override String get autoPlayNext => 'Nächstes automatisch abspielen';
|
||||
@override String get playNext => 'Nächstes abspielen';
|
||||
@override String get playButton => 'Wiedergeben';
|
||||
@@ -1580,6 +1583,9 @@ extension on TranslationsDe {
|
||||
'videoControls.timerActive' => 'Schlaftimer aktiv',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => 'Wiedergabe wird in ${duration} pausiert',
|
||||
'videoControls.sleepTimerCompleted' => 'Schlaftimer abgelaufen – Wiedergabe pausiert',
|
||||
'videoControls.stillWatching' => 'Schaust du noch?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => 'Pause in ${seconds}s',
|
||||
'videoControls.continueWatching' => 'Weiter',
|
||||
'videoControls.autoPlayNext' => 'Nächstes automatisch abspielen',
|
||||
'videoControls.playNext' => 'Nächstes abspielen',
|
||||
'videoControls.playButton' => 'Wiedergeben',
|
||||
@@ -1812,11 +1818,11 @@ extension on TranslationsDe {
|
||||
'liveTv.live' => 'LIVE',
|
||||
'liveTv.hd' => 'HD',
|
||||
'liveTv.premiere' => 'NEU',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => 'Programmführer neu laden',
|
||||
'liveTv.guideReloaded' => 'Programmdaten neu geladen',
|
||||
'liveTv.allChannels' => 'Alle Kanäle',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => 'Jetzt',
|
||||
'liveTv.today' => 'Heute',
|
||||
'liveTv.midnight' => 'Mitternacht',
|
||||
|
||||
@@ -981,6 +981,15 @@ class TranslationsVideoControlsEn {
|
||||
/// en: 'Sleep timer completed - playback paused'
|
||||
String get sleepTimerCompleted => 'Sleep timer completed - playback paused';
|
||||
|
||||
/// en: 'Still watching?'
|
||||
String get stillWatching => 'Still watching?';
|
||||
|
||||
/// en: 'Pausing in ${seconds}s'
|
||||
String pausingIn({required Object seconds}) => 'Pausing in ${seconds}s';
|
||||
|
||||
/// en: 'Continue'
|
||||
String get continueWatching => 'Continue';
|
||||
|
||||
/// en: 'Auto-Play Next'
|
||||
String get autoPlayNext => 'Auto-Play Next';
|
||||
|
||||
@@ -3199,6 +3208,9 @@ extension on Translations {
|
||||
'videoControls.timerActive' => 'Timer Active',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => 'Playback will pause in ${duration}',
|
||||
'videoControls.sleepTimerCompleted' => 'Sleep timer completed - playback paused',
|
||||
'videoControls.stillWatching' => 'Still watching?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => 'Pausing in ${seconds}s',
|
||||
'videoControls.continueWatching' => 'Continue',
|
||||
'videoControls.autoPlayNext' => 'Auto-Play Next',
|
||||
'videoControls.playNext' => 'Play Next',
|
||||
'videoControls.playButton' => 'Play',
|
||||
@@ -3431,11 +3443,11 @@ extension on Translations {
|
||||
'liveTv.live' => 'LIVE',
|
||||
'liveTv.hd' => 'HD',
|
||||
'liveTv.premiere' => 'NEW',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => 'Reload Guide',
|
||||
'liveTv.guideReloaded' => 'Guide data reloaded',
|
||||
'liveTv.allChannels' => 'All Channels',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => 'Now',
|
||||
'liveTv.today' => 'Today',
|
||||
'liveTv.midnight' => 'Midnight',
|
||||
|
||||
@@ -460,6 +460,9 @@ class _TranslationsVideoControlsEs implements TranslationsVideoControlsEn {
|
||||
@override String get timerActive => 'Temporizador Activo';
|
||||
@override String playbackWillPauseIn({required Object duration}) => 'La reproducción se pausará en ${duration}';
|
||||
@override String get sleepTimerCompleted => 'Temporizador completado - reproducción pausada';
|
||||
@override String get stillWatching => '¿Sigues viendo?';
|
||||
@override String pausingIn({required Object seconds}) => 'Pausa en ${seconds}s';
|
||||
@override String get continueWatching => 'Continuar';
|
||||
@override String get autoPlayNext => 'Reproducir siguiente automáticamente';
|
||||
@override String get playNext => 'Reproducir siguiente';
|
||||
@override String get playButton => 'Reproducir';
|
||||
@@ -1580,6 +1583,9 @@ extension on TranslationsEs {
|
||||
'videoControls.timerActive' => 'Temporizador Activo',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => 'La reproducción se pausará en ${duration}',
|
||||
'videoControls.sleepTimerCompleted' => 'Temporizador completado - reproducción pausada',
|
||||
'videoControls.stillWatching' => '¿Sigues viendo?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => 'Pausa en ${seconds}s',
|
||||
'videoControls.continueWatching' => 'Continuar',
|
||||
'videoControls.autoPlayNext' => 'Reproducir siguiente automáticamente',
|
||||
'videoControls.playNext' => 'Reproducir siguiente',
|
||||
'videoControls.playButton' => 'Reproducir',
|
||||
@@ -1812,11 +1818,11 @@ extension on TranslationsEs {
|
||||
'liveTv.live' => 'EN VIVO',
|
||||
'liveTv.hd' => 'HD',
|
||||
'liveTv.premiere' => 'NUEVO',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => 'Recargar guía',
|
||||
'liveTv.guideReloaded' => 'Datos de la guía recargados',
|
||||
'liveTv.allChannels' => 'Todos los canales',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => 'Ahora',
|
||||
'liveTv.today' => 'Hoy',
|
||||
'liveTv.midnight' => 'Medianoche',
|
||||
|
||||
@@ -460,6 +460,9 @@ class _TranslationsVideoControlsFr implements TranslationsVideoControlsEn {
|
||||
@override String get timerActive => 'Minuterie active';
|
||||
@override String playbackWillPauseIn({required Object duration}) => 'La lecture sera mise en pause dans ${duration}';
|
||||
@override String get sleepTimerCompleted => 'Minuterie de mise en veille terminée - lecture en pause';
|
||||
@override String get stillWatching => 'Toujours en train de regarder ?';
|
||||
@override String pausingIn({required Object seconds}) => 'Pause dans ${seconds}s';
|
||||
@override String get continueWatching => 'Continuer';
|
||||
@override String get autoPlayNext => 'Lecture automatique suivante';
|
||||
@override String get playNext => 'Lire l\'épisode suivant';
|
||||
@override String get playButton => 'Lire';
|
||||
@@ -1580,6 +1583,9 @@ extension on TranslationsFr {
|
||||
'videoControls.timerActive' => 'Minuterie active',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => 'La lecture sera mise en pause dans ${duration}',
|
||||
'videoControls.sleepTimerCompleted' => 'Minuterie de mise en veille terminée - lecture en pause',
|
||||
'videoControls.stillWatching' => 'Toujours en train de regarder ?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => 'Pause dans ${seconds}s',
|
||||
'videoControls.continueWatching' => 'Continuer',
|
||||
'videoControls.autoPlayNext' => 'Lecture automatique suivante',
|
||||
'videoControls.playNext' => 'Lire l\'épisode suivant',
|
||||
'videoControls.playButton' => 'Lire',
|
||||
@@ -1812,11 +1818,11 @@ extension on TranslationsFr {
|
||||
'liveTv.live' => 'EN DIRECT',
|
||||
'liveTv.hd' => 'HD',
|
||||
'liveTv.premiere' => 'NOUVEAU',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => 'Recharger le guide',
|
||||
'liveTv.guideReloaded' => 'Données du guide rechargées',
|
||||
'liveTv.allChannels' => 'Toutes les chaînes',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => 'Maintenant',
|
||||
'liveTv.today' => 'Aujourd\'hui',
|
||||
'liveTv.midnight' => 'Minuit',
|
||||
|
||||
@@ -460,6 +460,9 @@ class _TranslationsVideoControlsIt implements TranslationsVideoControlsEn {
|
||||
@override String get timerActive => 'Timer attivo';
|
||||
@override String playbackWillPauseIn({required Object duration}) => 'La riproduzione si interromperà tra ${duration}';
|
||||
@override String get sleepTimerCompleted => 'Timer di spegnimento completato - riproduzione in pausa';
|
||||
@override String get stillWatching => 'Stai ancora guardando?';
|
||||
@override String pausingIn({required Object seconds}) => 'Pausa tra ${seconds}s';
|
||||
@override String get continueWatching => 'Continua';
|
||||
@override String get autoPlayNext => 'Riproduzione automatica successivo';
|
||||
@override String get playNext => 'Riproduci successivo';
|
||||
@override String get playButton => 'Riproduci';
|
||||
@@ -1580,6 +1583,9 @@ extension on TranslationsIt {
|
||||
'videoControls.timerActive' => 'Timer attivo',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => 'La riproduzione si interromperà tra ${duration}',
|
||||
'videoControls.sleepTimerCompleted' => 'Timer di spegnimento completato - riproduzione in pausa',
|
||||
'videoControls.stillWatching' => 'Stai ancora guardando?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => 'Pausa tra ${seconds}s',
|
||||
'videoControls.continueWatching' => 'Continua',
|
||||
'videoControls.autoPlayNext' => 'Riproduzione automatica successivo',
|
||||
'videoControls.playNext' => 'Riproduci successivo',
|
||||
'videoControls.playButton' => 'Riproduci',
|
||||
@@ -1812,11 +1818,11 @@ extension on TranslationsIt {
|
||||
'liveTv.live' => 'IN DIRETTA',
|
||||
'liveTv.hd' => 'HD',
|
||||
'liveTv.premiere' => 'NUOVO',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => 'Ricarica guida',
|
||||
'liveTv.guideReloaded' => 'Dati della guida ricaricati',
|
||||
'liveTv.allChannels' => 'Tutti i canali',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => 'Ora',
|
||||
'liveTv.today' => 'Oggi',
|
||||
'liveTv.midnight' => 'Mezzanotte',
|
||||
|
||||
@@ -460,6 +460,9 @@ class _TranslationsVideoControlsKo implements TranslationsVideoControlsEn {
|
||||
@override String get timerActive => '타이머 활성화됨';
|
||||
@override String playbackWillPauseIn({required Object duration}) => '재생이 ${duration} 후에 일시 중지 됩니다';
|
||||
@override String get sleepTimerCompleted => '수면 타이머 완료됨 - 재생이 일시 중지되었습니다';
|
||||
@override String get stillWatching => '아직 시청 중이신가요?';
|
||||
@override String pausingIn({required Object seconds}) => '${seconds}초 후 일시 정지';
|
||||
@override String get continueWatching => '계속';
|
||||
@override String get autoPlayNext => '다음 자동 재생';
|
||||
@override String get playNext => '다음 재생';
|
||||
@override String get playButton => '재생';
|
||||
@@ -1580,6 +1583,9 @@ extension on TranslationsKo {
|
||||
'videoControls.timerActive' => '타이머 활성화됨',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => '재생이 ${duration} 후에 일시 중지 됩니다',
|
||||
'videoControls.sleepTimerCompleted' => '수면 타이머 완료됨 - 재생이 일시 중지되었습니다',
|
||||
'videoControls.stillWatching' => '아직 시청 중이신가요?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => '${seconds}초 후 일시 정지',
|
||||
'videoControls.continueWatching' => '계속',
|
||||
'videoControls.autoPlayNext' => '다음 자동 재생',
|
||||
'videoControls.playNext' => '다음 재생',
|
||||
'videoControls.playButton' => '재생',
|
||||
@@ -1812,11 +1818,11 @@ extension on TranslationsKo {
|
||||
'liveTv.live' => '실시간',
|
||||
'liveTv.hd' => 'HD',
|
||||
'liveTv.premiere' => '신규',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => '편성표 새로고침',
|
||||
'liveTv.guideReloaded' => '편성표 데이터가 새로고침되었습니다',
|
||||
'liveTv.allChannels' => '전체 채널',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => '지금',
|
||||
'liveTv.today' => '오늘',
|
||||
'liveTv.midnight' => '자정',
|
||||
|
||||
@@ -460,6 +460,9 @@ class _TranslationsVideoControlsNl implements TranslationsVideoControlsEn {
|
||||
@override String get timerActive => 'Timer actief';
|
||||
@override String playbackWillPauseIn({required Object duration}) => 'Afspelen wordt gepauzeerd over ${duration}';
|
||||
@override String get sleepTimerCompleted => 'Slaaptimer voltooid - afspelen gepauzeerd';
|
||||
@override String get stillWatching => 'Kijk je nog?';
|
||||
@override String pausingIn({required Object seconds}) => 'Pauze over ${seconds}s';
|
||||
@override String get continueWatching => 'Doorgaan';
|
||||
@override String get autoPlayNext => 'Automatisch volgende afspelen';
|
||||
@override String get playNext => 'Volgende afspelen';
|
||||
@override String get playButton => 'Afspelen';
|
||||
@@ -1580,6 +1583,9 @@ extension on TranslationsNl {
|
||||
'videoControls.timerActive' => 'Timer actief',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => 'Afspelen wordt gepauzeerd over ${duration}',
|
||||
'videoControls.sleepTimerCompleted' => 'Slaaptimer voltooid - afspelen gepauzeerd',
|
||||
'videoControls.stillWatching' => 'Kijk je nog?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => 'Pauze over ${seconds}s',
|
||||
'videoControls.continueWatching' => 'Doorgaan',
|
||||
'videoControls.autoPlayNext' => 'Automatisch volgende afspelen',
|
||||
'videoControls.playNext' => 'Volgende afspelen',
|
||||
'videoControls.playButton' => 'Afspelen',
|
||||
@@ -1812,11 +1818,11 @@ extension on TranslationsNl {
|
||||
'liveTv.live' => 'LIVE',
|
||||
'liveTv.hd' => 'HD',
|
||||
'liveTv.premiere' => 'NIEUW',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => 'Gids herladen',
|
||||
'liveTv.guideReloaded' => 'Gidsgegevens herladen',
|
||||
'liveTv.allChannels' => 'Alle zenders',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => 'Nu',
|
||||
'liveTv.today' => 'Vandaag',
|
||||
'liveTv.midnight' => 'Middernacht',
|
||||
|
||||
@@ -460,6 +460,9 @@ class _TranslationsVideoControlsSv implements TranslationsVideoControlsEn {
|
||||
@override String get timerActive => 'Timer aktiv';
|
||||
@override String playbackWillPauseIn({required Object duration}) => 'Uppspelningen pausas om ${duration}';
|
||||
@override String get sleepTimerCompleted => 'Sovtimer slutförd - uppspelning pausad';
|
||||
@override String get stillWatching => 'Tittar du fortfarande?';
|
||||
@override String pausingIn({required Object seconds}) => 'Pausar om ${seconds}s';
|
||||
@override String get continueWatching => 'Fortsätt';
|
||||
@override String get autoPlayNext => 'Spela nästa automatiskt';
|
||||
@override String get playNext => 'Spela nästa';
|
||||
@override String get playButton => 'Spela';
|
||||
@@ -1580,6 +1583,9 @@ extension on TranslationsSv {
|
||||
'videoControls.timerActive' => 'Timer aktiv',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => 'Uppspelningen pausas om ${duration}',
|
||||
'videoControls.sleepTimerCompleted' => 'Sovtimer slutförd - uppspelning pausad',
|
||||
'videoControls.stillWatching' => 'Tittar du fortfarande?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => 'Pausar om ${seconds}s',
|
||||
'videoControls.continueWatching' => 'Fortsätt',
|
||||
'videoControls.autoPlayNext' => 'Spela nästa automatiskt',
|
||||
'videoControls.playNext' => 'Spela nästa',
|
||||
'videoControls.playButton' => 'Spela',
|
||||
@@ -1812,11 +1818,11 @@ extension on TranslationsSv {
|
||||
'liveTv.live' => 'LIVE',
|
||||
'liveTv.hd' => 'HD',
|
||||
'liveTv.premiere' => 'NY',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => 'Ladda om programguide',
|
||||
'liveTv.guideReloaded' => 'Programdata omladdad',
|
||||
'liveTv.allChannels' => 'Alla kanaler',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => 'Nu',
|
||||
'liveTv.today' => 'Idag',
|
||||
'liveTv.midnight' => 'Midnatt',
|
||||
|
||||
@@ -460,6 +460,9 @@ class _TranslationsVideoControlsZh implements TranslationsVideoControlsEn {
|
||||
@override String get timerActive => '定时器已激活';
|
||||
@override String playbackWillPauseIn({required Object duration}) => '播放将在 ${duration} 后暂停';
|
||||
@override String get sleepTimerCompleted => '睡眠定时器已完成 - 播放已暂停';
|
||||
@override String get stillWatching => '还在看吗?';
|
||||
@override String pausingIn({required Object seconds}) => '${seconds}秒后暂停';
|
||||
@override String get continueWatching => '继续';
|
||||
@override String get autoPlayNext => '自动播放下一集';
|
||||
@override String get playNext => '播放下一集';
|
||||
@override String get playButton => '播放';
|
||||
@@ -1580,6 +1583,9 @@ extension on TranslationsZh {
|
||||
'videoControls.timerActive' => '定时器已激活',
|
||||
'videoControls.playbackWillPauseIn' => ({required Object duration}) => '播放将在 ${duration} 后暂停',
|
||||
'videoControls.sleepTimerCompleted' => '睡眠定时器已完成 - 播放已暂停',
|
||||
'videoControls.stillWatching' => '还在看吗?',
|
||||
'videoControls.pausingIn' => ({required Object seconds}) => '${seconds}秒后暂停',
|
||||
'videoControls.continueWatching' => '继续',
|
||||
'videoControls.autoPlayNext' => '自动播放下一集',
|
||||
'videoControls.playNext' => '播放下一集',
|
||||
'videoControls.playButton' => '播放',
|
||||
@@ -1812,11 +1818,11 @@ extension on TranslationsZh {
|
||||
'liveTv.live' => '直播',
|
||||
'liveTv.hd' => '高清',
|
||||
'liveTv.premiere' => '新',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.reloadGuide' => '重新加载节目指南',
|
||||
'liveTv.guideReloaded' => '节目指南已重新加载',
|
||||
'liveTv.allChannels' => '所有频道',
|
||||
_ => null,
|
||||
} ?? switch (path) {
|
||||
'liveTv.now' => '现在',
|
||||
'liveTv.today' => '今天',
|
||||
'liveTv.midnight' => '午夜',
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "Timer aktiv",
|
||||
"playbackWillPauseIn": "Uppspelningen pausas om ${duration}",
|
||||
"sleepTimerCompleted": "Sovtimer slutförd - uppspelning pausad",
|
||||
"stillWatching": "Tittar du fortfarande?",
|
||||
"pausingIn": "Pausar om ${seconds}s",
|
||||
"continueWatching": "Fortsätt",
|
||||
"autoPlayNext": "Spela nästa automatiskt",
|
||||
"playNext": "Spela nästa",
|
||||
"playButton": "Spela",
|
||||
|
||||
@@ -305,6 +305,9 @@
|
||||
"timerActive": "定时器已激活",
|
||||
"playbackWillPauseIn": "播放将在 ${duration} 后暂停",
|
||||
"sleepTimerCompleted": "睡眠定时器已完成 - 播放已暂停",
|
||||
"stillWatching": "还在看吗?",
|
||||
"pausingIn": "${seconds}秒后暂停",
|
||||
"continueWatching": "继续",
|
||||
"autoPlayNext": "自动播放下一集",
|
||||
"playNext": "播放下一集",
|
||||
"playButton": "播放",
|
||||
|
||||
+22
-4
@@ -24,8 +24,8 @@ import 'providers/playback_state_provider.dart';
|
||||
import 'providers/download_provider.dart';
|
||||
import 'providers/offline_mode_provider.dart';
|
||||
import 'providers/offline_watch_provider.dart';
|
||||
import 'providers/shader_provider.dart';
|
||||
import 'providers/companion_remote_provider.dart';
|
||||
import 'providers/shader_provider.dart';
|
||||
import 'watch_together/watch_together.dart';
|
||||
import 'services/multi_server_manager.dart';
|
||||
import 'services/offline_watch_sync_service.dart';
|
||||
@@ -36,6 +36,7 @@ import 'services/server_registry.dart';
|
||||
import 'services/download_manager_service.dart';
|
||||
import 'services/pip_service.dart';
|
||||
import 'services/download_storage_service.dart';
|
||||
import 'package:connectivity_plus/connectivity_plus.dart';
|
||||
import 'services/plex_api_cache.dart';
|
||||
import 'database/app_database.dart';
|
||||
import 'utils/app_logger.dart';
|
||||
@@ -310,8 +311,8 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
|
||||
ChangeNotifierProvider(create: (context) => LibrariesProvider()),
|
||||
ChangeNotifierProvider(create: (context) => PlaybackStateProvider()),
|
||||
ChangeNotifierProvider(create: (context) => WatchTogetherProvider()),
|
||||
ChangeNotifierProvider(create: (context) => ShaderProvider()),
|
||||
ChangeNotifierProvider(create: (context) => CompanionRemoteProvider()),
|
||||
ChangeNotifierProvider(create: (context) => ShaderProvider()),
|
||||
],
|
||||
child: Consumer<ThemeProvider>(
|
||||
builder: (context, themeProvider, child) {
|
||||
@@ -376,8 +377,14 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
final storage = await StorageService.getInstance();
|
||||
final registry = ServerRegistry(storage);
|
||||
|
||||
// Refresh servers from API to get updated connection info (IPs may change)
|
||||
await registry.refreshServersFromApi();
|
||||
// Check network connectivity early to fast-path airplane mode
|
||||
final connectivityResult = await Connectivity().checkConnectivity();
|
||||
final hasNetwork = !connectivityResult.contains(ConnectivityResult.none);
|
||||
|
||||
if (hasNetwork) {
|
||||
// Refresh servers from API to get updated connection info (IPs may change)
|
||||
await registry.refreshServersFromApi();
|
||||
}
|
||||
|
||||
// Load all configured servers
|
||||
final servers = await registry.getServers();
|
||||
@@ -391,6 +398,17 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// No network — skip connection attempts and go straight to offline mode
|
||||
if (!hasNetwork) {
|
||||
await context.read<DownloadProvider>().ensureInitialized();
|
||||
if (!mounted) return;
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => const MainScreen(isOfflineMode: true)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final result = await ServerConnectionOrchestrator.connectAndInitialize(
|
||||
servers: servers,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../utils/deletion_notifier.dart';
|
||||
import 'event_aware.dart';
|
||||
|
||||
/// Mixin for screens that need to react to deletion events.
|
||||
///
|
||||
@@ -56,31 +57,14 @@ mixin DeletionAware<T extends StatefulWidget> on State<T> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_subscribeToDeletions();
|
||||
}
|
||||
|
||||
void _subscribeToDeletions() {
|
||||
_deletionSubscription = DeletionNotifier().stream.listen((event) {
|
||||
if (!mounted) return;
|
||||
|
||||
final serverId = deletionServerId;
|
||||
if (serverId != null && event.serverId != serverId) return;
|
||||
|
||||
final globalKeys = deletionGlobalKeys;
|
||||
if (globalKeys != null) {
|
||||
if (event.affectsAnyGlobalKey(globalKeys)) {
|
||||
onDeletionEvent(event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final ratingKeys = deletionRatingKeys;
|
||||
// If keys is null, receive all events
|
||||
// Otherwise, filter to events that affect our keys
|
||||
if (ratingKeys == null || event.affectsAnyOf(ratingKeys)) {
|
||||
onDeletionEvent(event);
|
||||
}
|
||||
});
|
||||
_deletionSubscription = subscribeToHierarchicalEvents<DeletionEvent>(
|
||||
notifier: DeletionNotifier(),
|
||||
mounted: () => mounted,
|
||||
serverId: () => deletionServerId,
|
||||
globalKeys: () => deletionGlobalKeys,
|
||||
ratingKeys: () => deletionRatingKeys,
|
||||
onEvent: onDeletionEvent,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import 'dart:async';
|
||||
import '../utils/base_notifier.dart';
|
||||
import '../utils/hierarchical_event_mixin.dart';
|
||||
|
||||
/// Creates a filtered stream subscription for hierarchical events.
|
||||
///
|
||||
/// Used internally by [DeletionAware] and [WatchStateAware] to avoid
|
||||
/// duplicating the subscription and filtering logic.
|
||||
StreamSubscription<E> subscribeToHierarchicalEvents<E extends HierarchicalEventMixin>({
|
||||
required BaseNotifier<E> notifier,
|
||||
required bool Function() mounted,
|
||||
required String? Function() serverId,
|
||||
required Set<String>? Function() globalKeys,
|
||||
required Set<String>? Function() ratingKeys,
|
||||
required void Function(E event) onEvent,
|
||||
}) {
|
||||
return notifier.stream.listen((event) {
|
||||
if (!mounted()) return;
|
||||
|
||||
final sid = serverId();
|
||||
if (sid != null && event.serverId != sid) return;
|
||||
|
||||
final gk = globalKeys();
|
||||
if (gk != null) {
|
||||
if (event.affectsAnyGlobalKey(gk)) {
|
||||
onEvent(event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final rk = ratingKeys();
|
||||
if (rk == null || event.affectsAnyOf(rk)) {
|
||||
onEvent(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import 'event_aware.dart';
|
||||
|
||||
/// Mixin for screens that need to react to watch state changes.
|
||||
///
|
||||
@@ -55,31 +56,14 @@ mixin WatchStateAware<T extends StatefulWidget> on State<T> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_subscribeToWatchState();
|
||||
}
|
||||
|
||||
void _subscribeToWatchState() {
|
||||
_watchStateSubscription = WatchStateNotifier().stream.listen((event) {
|
||||
if (!mounted) return;
|
||||
|
||||
final serverId = watchStateServerId;
|
||||
if (serverId != null && event.serverId != serverId) return;
|
||||
|
||||
final globalKeys = watchedGlobalKeys;
|
||||
if (globalKeys != null) {
|
||||
if (event.affectsAnyGlobalKey(globalKeys)) {
|
||||
onWatchStateChanged(event);
|
||||
}
|
||||
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);
|
||||
}
|
||||
});
|
||||
_watchStateSubscription = subscribeToHierarchicalEvents<WatchStateEvent>(
|
||||
notifier: WatchStateNotifier(),
|
||||
mounted: () => mounted,
|
||||
serverId: () => watchStateServerId,
|
||||
globalKeys: () => watchedGlobalKeys,
|
||||
ratingKeys: () => watchedRatingKeys,
|
||||
onEvent: onWatchStateChanged,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -25,25 +25,28 @@ class RecentRemoteSession {
|
||||
|
||||
Map<String, dynamic> toJson() => _$RecentRemoteSessionToJson(this);
|
||||
|
||||
/// Create from QR code data (format: "ip|port|sessionId|pin")
|
||||
/// Create from QR code data (format: "ip1,ip2|port|sessionId|pin" or legacy "ip|port|sessionId|pin")
|
||||
factory RecentRemoteSession.fromQrData(String qrData) {
|
||||
final parts = qrData.split('|');
|
||||
if (parts.length < 4) {
|
||||
throw FormatException('Invalid QR code format - expected ip|port|sessionId|pin');
|
||||
}
|
||||
|
||||
final ip = parts.first;
|
||||
final ipsField = parts.first;
|
||||
final port = parts[1];
|
||||
final sessionId = parts[2];
|
||||
final pin = parts[3];
|
||||
|
||||
// Use the first IP for storage (comma-separated IPs supported in QR)
|
||||
final firstIp = ipsField.split(',').first;
|
||||
|
||||
return RecentRemoteSession(
|
||||
sessionId: sessionId,
|
||||
pin: pin,
|
||||
deviceName: 'Unknown Device',
|
||||
platform: 'unknown',
|
||||
lastConnected: DateTime.now(),
|
||||
hostAddress: '$ip:$port',
|
||||
hostAddress: '$firstIp:$port',
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
import 'mixins/multi_server_fields.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
|
||||
part 'plex_library.g.dart';
|
||||
|
||||
@@ -26,7 +27,7 @@ class PlexLibrary with MultiServerFields {
|
||||
final String? serverName;
|
||||
|
||||
/// Global unique identifier across all servers (serverId:key)
|
||||
String get globalKey => serverId != null ? '$serverId:$key' : key;
|
||||
String get globalKey => serverId != null ? buildGlobalKey(serverId!, key) : key;
|
||||
|
||||
PlexLibrary({
|
||||
required this.key,
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../services/settings_service.dart' show EpisodePosterMode;
|
||||
import '../widgets/plex_optimized_image.dart' show kBlurArtwork, obfuscateText;
|
||||
import 'mixins/multi_server_fields.dart';
|
||||
import 'plex_role.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
|
||||
part 'plex_metadata.g.dart';
|
||||
|
||||
@@ -111,7 +112,7 @@ class PlexMetadata with MultiServerFields {
|
||||
final String? clearLogo;
|
||||
|
||||
/// Global unique identifier across all servers (serverId:ratingKey)
|
||||
String get globalKey => serverId != null ? '$serverId:$ratingKey' : ratingKey;
|
||||
String get globalKey => serverId != null ? buildGlobalKey(serverId!, ratingKey) : ratingKey;
|
||||
|
||||
/// Parsed media type enum for type-safe comparisons
|
||||
PlexMediaType get mediaType {
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
import '../widgets/plex_optimized_image.dart' show kBlurArtwork, obfuscateText;
|
||||
import 'mixins/multi_server_fields.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
|
||||
part 'plex_playlist.g.dart';
|
||||
|
||||
@@ -65,7 +66,7 @@ class PlexPlaylist with MultiServerFields {
|
||||
bool get isEditable => !smart;
|
||||
|
||||
/// Get globally unique key across all servers
|
||||
String get globalKey => serverId != null ? '$serverId:$ratingKey' : ratingKey;
|
||||
String get globalKey => serverId != null ? buildGlobalKey(serverId!, ratingKey) : ratingKey;
|
||||
|
||||
// Properties for MediaCard compatibility with PlexMetadata interface
|
||||
|
||||
|
||||
@@ -36,6 +36,12 @@ class PlayerAndroid extends PlayerBase {
|
||||
return;
|
||||
}
|
||||
|
||||
if (name == 'memory-pressure') {
|
||||
// System memory is critically low — playback may be at risk of OOM crash
|
||||
errorController.add('Low memory — playback may be unstable');
|
||||
return;
|
||||
}
|
||||
|
||||
// Delegate to base class for common events
|
||||
super.handlePlayerEvent(name, data);
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
|
||||
void _handleEvent(dynamic event) {
|
||||
if (_disposed) return;
|
||||
if (event is List && event.length == 2) {
|
||||
final name = _propIdToName[event[0] as int];
|
||||
final name = _propIdToName[event.first as int];
|
||||
if (name != null) {
|
||||
handlePropertyChange(name, event[1]);
|
||||
}
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ class _VideoState extends State<Video> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
return ColoredBox(
|
||||
color: _hasFirstFrame ? Colors.transparent : widget.backgroundColor,
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
|
||||
@@ -205,7 +205,7 @@ class CompanionRemoteProvider with ChangeNotifier {
|
||||
_statusSubscription = null;
|
||||
}
|
||||
|
||||
Future<({String sessionId, String pin, String address})> createSession() async {
|
||||
Future<({String sessionId, String pin, List<String> addresses})> createSession() async {
|
||||
await leaveSession();
|
||||
|
||||
appLogger.d('CompanionRemote: Creating session as host');
|
||||
@@ -225,7 +225,7 @@ class CompanionRemoteProvider with ChangeNotifier {
|
||||
|
||||
notifyListeners();
|
||||
appLogger.d(
|
||||
'CompanionRemote: Session created - ID: ${result.sessionId}, PIN: ${result.pin}, Address: ${result.address}',
|
||||
'CompanionRemote: Session created - ID: ${result.sessionId}, PIN: ${result.pin}, Addresses: ${result.addresses}',
|
||||
);
|
||||
|
||||
return result;
|
||||
@@ -244,13 +244,18 @@ class CompanionRemoteProvider with ChangeNotifier {
|
||||
}
|
||||
|
||||
Future<void> joinSession(String sessionId, String pin, String hostAddress) async {
|
||||
await joinSessionMulti(sessionId, pin, [hostAddress]);
|
||||
}
|
||||
|
||||
Future<void> joinSessionMulti(String sessionId, String pin, List<String> hostAddresses) async {
|
||||
await leaveSession();
|
||||
|
||||
_lastSessionId = sessionId;
|
||||
_lastPin = pin;
|
||||
_lastHostAddress = hostAddress;
|
||||
// Store first address as fallback for reconnection; will be updated with winner
|
||||
_lastHostAddress = hostAddresses.first;
|
||||
|
||||
appLogger.d('CompanionRemote: Joining session - ID: $sessionId, Host: $hostAddress');
|
||||
appLogger.d('CompanionRemote: Joining session - ID: $sessionId, Hosts: $hostAddresses');
|
||||
|
||||
_peerService = CompanionRemotePeerService();
|
||||
_setupPeerServiceListeners();
|
||||
@@ -264,11 +269,18 @@ class CompanionRemoteProvider with ChangeNotifier {
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
await _peerService!.joinSession(sessionId, pin, _deviceName, _platform, hostAddress);
|
||||
final winner = await _peerService!.joinSessionRacing(
|
||||
sessionId,
|
||||
pin,
|
||||
_deviceName,
|
||||
_platform,
|
||||
hostAddresses,
|
||||
);
|
||||
_lastHostAddress = winner;
|
||||
|
||||
_session = _session?.copyWith(status: RemoteSessionStatus.connected);
|
||||
notifyListeners();
|
||||
appLogger.d('CompanionRemote: Successfully joined session');
|
||||
appLogger.d('CompanionRemote: Successfully joined session via $winner');
|
||||
} catch (e) {
|
||||
appLogger.e('CompanionRemote: Failed to join session', error: e);
|
||||
_session = _session?.copyWith(status: RemoteSessionStatus.error, errorMessage: e.toString());
|
||||
|
||||
@@ -172,7 +172,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
// Load show metadata
|
||||
final showRatingKey = episode.grandparentRatingKey;
|
||||
if (showRatingKey != null) {
|
||||
final showGlobalKey = '$serverId:$showRatingKey';
|
||||
final showGlobalKey = buildGlobalKey(serverId, showRatingKey);
|
||||
if (!_metadata.containsKey(showGlobalKey)) {
|
||||
final showMetadata = allMetadata[showGlobalKey];
|
||||
if (showMetadata != null) {
|
||||
@@ -187,7 +187,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
// Load season metadata
|
||||
final seasonRatingKey = episode.parentRatingKey;
|
||||
if (seasonRatingKey != null) {
|
||||
final seasonGlobalKey = '$serverId:$seasonRatingKey';
|
||||
final seasonGlobalKey = buildGlobalKey(serverId, seasonRatingKey);
|
||||
if (!_metadata.containsKey(seasonGlobalKey)) {
|
||||
final seasonMetadata = allMetadata[seasonGlobalKey];
|
||||
if (seasonMetadata != null) {
|
||||
@@ -270,7 +270,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
final showRatingKey = meta.grandparentRatingKey;
|
||||
if (showRatingKey != null && !shows.containsKey(showRatingKey)) {
|
||||
// Try to get stored show metadata first
|
||||
final showGlobalKey = '${meta.serverId}:$showRatingKey';
|
||||
final showGlobalKey = buildGlobalKey(meta.serverId!, showRatingKey);
|
||||
final storedShow = _metadata[showGlobalKey];
|
||||
|
||||
if (storedShow != null && storedShow.type == 'show') {
|
||||
@@ -384,7 +384,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
required List<DownloadProgress> episodes,
|
||||
required String entityType,
|
||||
}) {
|
||||
final globalKey = '$serverId:$ratingKey';
|
||||
final globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
|
||||
// DIAGNOSTIC: Check all sources of episode count
|
||||
final meta = _metadata[globalKey];
|
||||
@@ -604,7 +604,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
/// For shows and seasons, fetches all child episodes and queues them.
|
||||
/// Returns the number of items queued.
|
||||
Future<int> queueDownload(PlexMetadata metadata, PlexClient client) async {
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
|
||||
// Check if downloads are blocked on cellular
|
||||
if (await DownloadManagerService.shouldBlockDownloadOnCellular()) {
|
||||
@@ -646,7 +646,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
|
||||
/// Queue a single movie or episode for download
|
||||
Future<void> _queueSingleDownload(PlexMetadata metadata, PlexClient client) async {
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
|
||||
// Don't re-queue if already downloading or completed
|
||||
if (_downloads.containsKey(globalKey)) {
|
||||
@@ -657,15 +657,18 @@ class DownloadProvider extends ChangeNotifier {
|
||||
}
|
||||
|
||||
// Fetch full metadata to get year, summary, clearLogo
|
||||
// The metadata from getChildren() is summarized and missing these fields
|
||||
// The metadata from getChildren() is summarized and missing these fields.
|
||||
// If metadata already has summary, it's already full (e.g., from detail screen).
|
||||
PlexMetadata metadataToStore = metadata;
|
||||
try {
|
||||
final fullMetadata = await client.getMetadataWithImages(metadata.ratingKey);
|
||||
if (fullMetadata != null) {
|
||||
metadataToStore = fullMetadata.copyWith(serverId: metadata.serverId, serverName: metadata.serverName);
|
||||
if (metadata.summary == null) {
|
||||
try {
|
||||
final fullMetadata = await client.getMetadataWithImages(metadata.ratingKey);
|
||||
if (fullMetadata != null) {
|
||||
metadataToStore = fullMetadata.copyWith(serverId: metadata.serverId, serverName: metadata.serverName);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to fetch full metadata for ${metadata.ratingKey}, using partial', error: e);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to fetch full metadata for ${metadata.ratingKey}, using partial', error: e);
|
||||
}
|
||||
|
||||
// For episodes, also fetch and store show and season metadata for offline display
|
||||
@@ -694,7 +697,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
// Fetch and store show metadata if not already stored
|
||||
final showRatingKey = episode.grandparentRatingKey;
|
||||
if (showRatingKey != null) {
|
||||
final showGlobalKey = '$serverId:$showRatingKey';
|
||||
final showGlobalKey = buildGlobalKey(serverId, showRatingKey);
|
||||
|
||||
// Try to use existing metadata (set when queueing an entire show)
|
||||
PlexMetadata? showMetadata = _metadata[showGlobalKey];
|
||||
@@ -731,7 +734,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
// Fetch and store season metadata if not already stored
|
||||
final seasonRatingKey = episode.parentRatingKey;
|
||||
if (seasonRatingKey != null) {
|
||||
final seasonGlobalKey = '$serverId:$seasonRatingKey';
|
||||
final seasonGlobalKey = buildGlobalKey(serverId, seasonRatingKey);
|
||||
PlexMetadata? seasonMetadata = _metadata[seasonGlobalKey];
|
||||
|
||||
if (seasonMetadata == null) {
|
||||
@@ -765,7 +768,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
|
||||
/// Queue all episodes from a TV show for download
|
||||
Future<int> _queueShowDownload(PlexMetadata show, PlexClient client) async {
|
||||
final globalKey = '${show.serverId}:${show.ratingKey}';
|
||||
final globalKey = show.globalKey;
|
||||
int count = 0;
|
||||
final seasons = await client.getChildren(show.ratingKey);
|
||||
|
||||
@@ -801,7 +804,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
|
||||
/// Queue all episodes from a season for download
|
||||
Future<int> _queueSeasonDownload(PlexMetadata season, PlexClient client) async {
|
||||
final globalKey = '${season.serverId}:${season.ratingKey}';
|
||||
final globalKey = season.globalKey;
|
||||
int count = 0;
|
||||
final episodes = await client.getChildren(season.ratingKey);
|
||||
|
||||
@@ -880,7 +883,7 @@ class DownloadProvider extends ChangeNotifier {
|
||||
if (episode.type == 'episode') {
|
||||
final episodeWithServer = episode.serverId != null ? episode : episode.copyWith(serverId: season.serverId);
|
||||
|
||||
final episodeGlobalKey = '${episodeWithServer.serverId}:${episodeWithServer.ratingKey}';
|
||||
final episodeGlobalKey = episodeWithServer.globalKey;
|
||||
|
||||
// Only queue if NOT already downloaded or in progress
|
||||
final progress = _downloads[episodeGlobalKey];
|
||||
|
||||
@@ -5,6 +5,7 @@ import '../services/offline_watch_sync_service.dart';
|
||||
import '../services/plex_api_cache.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import 'download_provider.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
|
||||
/// Provider for offline watch status UI state.
|
||||
///
|
||||
@@ -174,7 +175,7 @@ class OfflineWatchProvider extends ChangeNotifier {
|
||||
required bool isNowWatched,
|
||||
required WatchStateChangeType changeType,
|
||||
}) {
|
||||
final globalKey = '$serverId:$ratingKey';
|
||||
final globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
final metadata = _downloadProvider.getMetadata(globalKey);
|
||||
if (metadata != null) {
|
||||
WatchStateNotifier().notifyWatched(metadata: metadata, isNowWatched: isNowWatched);
|
||||
|
||||
@@ -59,77 +59,68 @@ class SettingsProvider extends ChangeNotifier {
|
||||
|
||||
bool get showUnwatchedCount => _showUnwatchedCount;
|
||||
|
||||
Future<void> setLibraryDensity(LibraryDensity density) async {
|
||||
/// Helper to update a setting: ensures init, deduplicates, persists, notifies.
|
||||
Future<void> _updateSetting<T>({
|
||||
required T current,
|
||||
required T value,
|
||||
required void Function(T) setLocal,
|
||||
required Future<void> Function(T) persist,
|
||||
}) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_libraryDensity != density) {
|
||||
_libraryDensity = density;
|
||||
await _settingsService!.setLibraryDensity(density);
|
||||
if (current != value) {
|
||||
setLocal(value);
|
||||
await persist(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setViewMode(ViewMode mode) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_viewMode != mode) {
|
||||
_viewMode = mode;
|
||||
await _settingsService!.setViewMode(mode);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
Future<void> setLibraryDensity(LibraryDensity density) => _updateSetting(
|
||||
current: _libraryDensity, value: density,
|
||||
setLocal: (v) => _libraryDensity = v,
|
||||
persist: _settingsService!.setLibraryDensity,
|
||||
);
|
||||
|
||||
Future<void> setEpisodePosterMode(EpisodePosterMode mode) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_episodePosterMode != mode) {
|
||||
_episodePosterMode = mode;
|
||||
await _settingsService!.setEpisodePosterMode(mode);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
Future<void> setViewMode(ViewMode mode) => _updateSetting(
|
||||
current: _viewMode, value: mode,
|
||||
setLocal: (v) => _viewMode = v,
|
||||
persist: _settingsService!.setViewMode,
|
||||
);
|
||||
|
||||
Future<void> setShowHeroSection(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_showHeroSection != value) {
|
||||
_showHeroSection = value;
|
||||
await _settingsService!.setShowHeroSection(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
Future<void> setEpisodePosterMode(EpisodePosterMode mode) => _updateSetting(
|
||||
current: _episodePosterMode, value: mode,
|
||||
setLocal: (v) => _episodePosterMode = v,
|
||||
persist: _settingsService!.setEpisodePosterMode,
|
||||
);
|
||||
|
||||
Future<void> setUseGlobalHubs(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_useGlobalHubs != value) {
|
||||
_useGlobalHubs = value;
|
||||
await _settingsService!.setUseGlobalHubs(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
Future<void> setShowHeroSection(bool value) => _updateSetting(
|
||||
current: _showHeroSection, value: value,
|
||||
setLocal: (v) => _showHeroSection = v,
|
||||
persist: _settingsService!.setShowHeroSection,
|
||||
);
|
||||
|
||||
Future<void> setShowServerNameOnHubs(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_showServerNameOnHubs != value) {
|
||||
_showServerNameOnHubs = value;
|
||||
await _settingsService!.setShowServerNameOnHubs(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
Future<void> setUseGlobalHubs(bool value) => _updateSetting(
|
||||
current: _useGlobalHubs, value: value,
|
||||
setLocal: (v) => _useGlobalHubs = v,
|
||||
persist: _settingsService!.setUseGlobalHubs,
|
||||
);
|
||||
|
||||
Future<void> setAlwaysKeepSidebarOpen(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_alwaysKeepSidebarOpen != value) {
|
||||
_alwaysKeepSidebarOpen = value;
|
||||
await _settingsService!.setAlwaysKeepSidebarOpen(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
Future<void> setShowServerNameOnHubs(bool value) => _updateSetting(
|
||||
current: _showServerNameOnHubs, value: value,
|
||||
setLocal: (v) => _showServerNameOnHubs = v,
|
||||
persist: _settingsService!.setShowServerNameOnHubs,
|
||||
);
|
||||
|
||||
Future<void> setShowUnwatchedCount(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_showUnwatchedCount != value) {
|
||||
_showUnwatchedCount = value;
|
||||
await _settingsService!.setShowUnwatchedCount(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
Future<void> setAlwaysKeepSidebarOpen(bool value) => _updateSetting(
|
||||
current: _alwaysKeepSidebarOpen, value: value,
|
||||
setLocal: (v) => _alwaysKeepSidebarOpen = v,
|
||||
persist: _settingsService!.setAlwaysKeepSidebarOpen,
|
||||
);
|
||||
|
||||
Future<void> setShowUnwatchedCount(bool value) => _updateSetting(
|
||||
current: _showUnwatchedCount, value: value,
|
||||
setLocal: (v) => _showUnwatchedCount = v,
|
||||
persist: _settingsService!.setShowUnwatchedCount,
|
||||
);
|
||||
|
||||
String get libraryDensityDisplayName {
|
||||
switch (_libraryDensity) {
|
||||
|
||||
@@ -144,23 +144,26 @@ class _PairingScreenState extends State<PairingScreen> {
|
||||
if (data == _lastScannedCode) return;
|
||||
_lastScannedCode = data;
|
||||
|
||||
// Strip URL wrapper if present (e.g. "https://plezy.app/scan#ip|port|sid|pin")
|
||||
// Strip URL wrapper if present (e.g. "https://plezy.app/scan#ip1,ip2|port|sid|pin")
|
||||
final payload = data.contains('#') ? data.split('#').last : data;
|
||||
final parts = payload.split('|');
|
||||
if (parts.length == 4) {
|
||||
final ip = parts.first;
|
||||
final ipsField = parts.first;
|
||||
final port = parts[1];
|
||||
final sessionId = parts[2];
|
||||
final pin = parts[3];
|
||||
final hostAddress = '$ip:$port';
|
||||
|
||||
// Support comma-separated IPs (multi-NIC) or single IP (legacy)
|
||||
final ips = ipsField.split(',');
|
||||
final hostAddresses = ips.map((ip) => '$ip:$port').toList();
|
||||
|
||||
_scannerController?.stop();
|
||||
setState(() {
|
||||
_errorMessage = null;
|
||||
_isConnecting = true;
|
||||
});
|
||||
// Connect directly instead of going through _connect() which requires Form validation
|
||||
_connectWithCredentials(sessionId, pin, hostAddress);
|
||||
|
||||
_connectWithCredentialsMulti(sessionId, pin, hostAddresses);
|
||||
} else {
|
||||
setState(() {
|
||||
_errorMessage = t.companionRemote.pairing.invalidQrCode;
|
||||
@@ -168,10 +171,14 @@ class _PairingScreenState extends State<PairingScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _connectWithCredentials(String sessionId, String pin, String hostAddress) async {
|
||||
Future<void> _connectWithCredentialsMulti(String sessionId, String pin, List<String> hostAddresses) async {
|
||||
try {
|
||||
final provider = context.read<CompanionRemoteProvider>();
|
||||
await provider.joinSession(sessionId.trim().toUpperCase(), pin.trim(), hostAddress.trim());
|
||||
await provider.joinSessionMulti(
|
||||
sessionId.trim().toUpperCase(),
|
||||
pin.trim(),
|
||||
hostAddresses.map((a) => a.trim()).toList(),
|
||||
);
|
||||
|
||||
if (mounted) {
|
||||
Navigator.of(context).pop();
|
||||
|
||||
+214
-352
@@ -5,7 +5,8 @@ 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 '../focus/dpad_navigator.dart';
|
||||
import '../focus/key_event_utils.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../utils/plex_image_helper.dart';
|
||||
@@ -81,8 +82,6 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
bool _isAutoScrollPaused = false;
|
||||
HiddenLibrariesProvider? _hiddenLibrariesProvider;
|
||||
|
||||
String _toGlobalKey(String ratingKey, String serverId) => '$serverId:$ratingKey';
|
||||
|
||||
// WatchStateAware: watch on-deck items and their parent shows/seasons
|
||||
@override
|
||||
Set<String>? get watchedRatingKeys {
|
||||
@@ -106,12 +105,12 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
final serverId = item.serverId;
|
||||
if (serverId == null) return null;
|
||||
|
||||
keys.add(_toGlobalKey(item.ratingKey, serverId));
|
||||
keys.add(buildGlobalKey(serverId, item.ratingKey));
|
||||
if (item.parentRatingKey != null) {
|
||||
keys.add(_toGlobalKey(item.parentRatingKey!, serverId));
|
||||
keys.add(buildGlobalKey(serverId, item.parentRatingKey!));
|
||||
}
|
||||
if (item.grandparentRatingKey != null) {
|
||||
keys.add(_toGlobalKey(item.grandparentRatingKey!, serverId));
|
||||
keys.add(buildGlobalKey(serverId, item.grandparentRatingKey!));
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
@@ -155,16 +154,16 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
return context.getClientForServer(serverId);
|
||||
}
|
||||
|
||||
/// Update hub keys when hubs list changes
|
||||
/// Update hub keys when hubs list changes — reuse existing keys to avoid
|
||||
/// mass deep unmounts (ARM32 stack overflow during finalizeTree).
|
||||
void _updateHubKeys() {
|
||||
_hubKeys.clear();
|
||||
for (int i = 0; i < _hubs.length; i++) {
|
||||
while (_hubKeys.length < _hubs.length) {
|
||||
_hubKeys.add(GlobalKey<HubSectionState>());
|
||||
}
|
||||
// Create continue watching hub key if needed
|
||||
if (_onDeck.isNotEmpty) {
|
||||
_continueWatchingHubKey ??= GlobalKey<HubSectionState>();
|
||||
if (_hubKeys.length > _hubs.length) {
|
||||
_hubKeys.removeRange(_hubs.length, _hubKeys.length);
|
||||
}
|
||||
_continueWatchingHubKey ??= GlobalKey<HubSectionState>();
|
||||
}
|
||||
|
||||
/// Get all hub states (continue watching + other hubs)
|
||||
@@ -306,211 +305,69 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
}
|
||||
|
||||
/// Handle key events for the hero section
|
||||
KeyEventResult _handleHeroKeyEvent(FocusNode _, KeyEvent event) {
|
||||
if (!event.isActionable) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
final key = event.logicalKey;
|
||||
|
||||
// DOWN: Move to first hub
|
||||
if (key.isDownKey) {
|
||||
late final _handleHeroKeyEvent = dpadKeyHandler(
|
||||
onDown: () {
|
||||
final keys = _allHubKeys;
|
||||
if (keys.isNotEmpty) {
|
||||
keys.first.currentState?.requestFocusFromMemory();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// UP: Move to app bar (refresh button)
|
||||
if (key.isUpKey) {
|
||||
_refreshButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT: Navigate hero carousel to previous, or focus sidebar at index 0
|
||||
if (key.isLeftKey) {
|
||||
if (keys.isNotEmpty) keys.first.currentState?.requestFocusFromMemory();
|
||||
},
|
||||
onUp: () => _refreshButtonFocusNode.requestFocus(),
|
||||
onLeft: () {
|
||||
if (_currentHeroIndex > 0) {
|
||||
_heroController.previousPage(duration: tokens(context).slow, curve: Curves.easeInOut);
|
||||
} else {
|
||||
_navigateToSidebar();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// RIGHT: Navigate hero carousel to next
|
||||
if (key.isRightKey) {
|
||||
},
|
||||
onRight: () {
|
||||
if (_currentHeroIndex < _onDeck.length - 1) {
|
||||
_heroController.nextPage(duration: tokens(context).slow, curve: Curves.easeInOut);
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// SELECT: Play current hero item
|
||||
if (key.isSelectKey) {
|
||||
},
|
||||
onSelect: () {
|
||||
if (_onDeck.isNotEmpty && _currentHeroIndex < _onDeck.length) {
|
||||
navigateToVideoPlayer(context, metadata: _onDeck[_currentHeroIndex]);
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/// Handle key events for the refresh button in app bar
|
||||
KeyEventResult _handleRefreshKeyEvent(FocusNode _, KeyEvent event) {
|
||||
if (!event.isActionable) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
final key = event.logicalKey;
|
||||
|
||||
// DOWN: Return to hero/content
|
||||
if (key.isDownKey) {
|
||||
_focusContentFromAppBar();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// RIGHT: Move to watch together button
|
||||
if (key.isRightKey) {
|
||||
_watchTogetherButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT: Navigate to sidebar
|
||||
if (key.isLeftKey) {
|
||||
_navigateToSidebar();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// UP: Block at boundary
|
||||
if (key.isUpKey) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// SELECT: Trigger refresh
|
||||
if (key.isSelectKey) {
|
||||
_loadContent();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
late final _handleRefreshKeyEvent = dpadKeyHandler(
|
||||
onDown: _focusContentFromAppBar,
|
||||
onRight: () => _watchTogetherButtonFocusNode.requestFocus(),
|
||||
onLeft: _navigateToSidebar,
|
||||
onUp: () {}, // Block at boundary
|
||||
onSelect: _loadContent,
|
||||
);
|
||||
|
||||
/// Handle key events for the watch together button in app bar
|
||||
KeyEventResult _handleWatchTogetherKeyEvent(FocusNode _, KeyEvent event) {
|
||||
if (!event.isActionable) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
final key = event.logicalKey;
|
||||
|
||||
// DOWN: Return to hero/content
|
||||
if (key.isDownKey) {
|
||||
_focusContentFromAppBar();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT: Move to refresh button
|
||||
if (key.isLeftKey) {
|
||||
_refreshButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// RIGHT: Move to companion remote button
|
||||
if (key.isRightKey) {
|
||||
_companionRemoteButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// UP: Block at boundary
|
||||
if (key.isUpKey) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// SELECT: Navigate to Watch Together screen
|
||||
if (key.isSelectKey) {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (_) => const WatchTogetherScreen()));
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
late final _handleWatchTogetherKeyEvent = dpadKeyHandler(
|
||||
onDown: _focusContentFromAppBar,
|
||||
onLeft: () => _refreshButtonFocusNode.requestFocus(),
|
||||
onRight: () => _companionRemoteButtonFocusNode.requestFocus(),
|
||||
onUp: () {}, // Block at boundary
|
||||
onSelect: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const WatchTogetherScreen())),
|
||||
);
|
||||
|
||||
/// Handle key events for the companion remote button in app bar
|
||||
KeyEventResult _handleCompanionRemoteKeyEvent(FocusNode _, KeyEvent event) {
|
||||
if (!event.isActionable) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
final key = event.logicalKey;
|
||||
|
||||
// DOWN: Return to hero
|
||||
if (key.isDownKey) {
|
||||
_heroFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT: Move to watch together button
|
||||
if (key.isLeftKey) {
|
||||
_watchTogetherButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// RIGHT: Move to user button
|
||||
if (key.isRightKey) {
|
||||
_userButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// UP: Block at boundary
|
||||
if (key.isUpKey) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// SELECT: Show companion remote dialog (host a remote session)
|
||||
if (key.isSelectKey) {
|
||||
RemoteSessionDialog.show(context);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
late final _handleCompanionRemoteKeyEvent = dpadKeyHandler(
|
||||
onDown: () => _heroFocusNode.requestFocus(),
|
||||
onLeft: () => _watchTogetherButtonFocusNode.requestFocus(),
|
||||
onRight: () => _userButtonFocusNode.requestFocus(),
|
||||
onUp: () {}, // Block at boundary
|
||||
onSelect: () => RemoteSessionDialog.show(context),
|
||||
);
|
||||
|
||||
/// Handle key events for the user button in app bar
|
||||
KeyEventResult _handleUserKeyEvent(FocusNode _, KeyEvent event) {
|
||||
if (!event.isActionable) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
final key = event.logicalKey;
|
||||
|
||||
// DOWN: Return to hero/content
|
||||
if (key.isDownKey) {
|
||||
_focusContentFromAppBar();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT: Move to companion remote button
|
||||
if (key.isLeftKey) {
|
||||
_companionRemoteButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// RIGHT/UP: Block at boundary
|
||||
if (key.isRightKey || key.isUpKey) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// SELECT: Show user menu
|
||||
if (key.isSelectKey) {
|
||||
late final _handleUserKeyEvent = dpadKeyHandler(
|
||||
onDown: _focusContentFromAppBar,
|
||||
onLeft: () => _companionRemoteButtonFocusNode.requestFocus(),
|
||||
onRight: () {}, // Block at boundary
|
||||
onUp: () {}, // Block at boundary
|
||||
onSelect: () {
|
||||
final userProvider = context.read<UserProfileProvider>();
|
||||
_showUserMenu(context, userProvider);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
@@ -1240,138 +1097,137 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
final showServerNameOnHubs = context.watch<SettingsProvider>().showServerNameOnHubs;
|
||||
final duplicateHubTitles = _getDuplicateHubTitles();
|
||||
|
||||
return Scaffold(
|
||||
body: Stack(
|
||||
final bottomPadding = MediaQuery.of(context).padding.bottom;
|
||||
return Material(
|
||||
color: Theme.of(context).scaffoldBackgroundColor,
|
||||
child: Stack(
|
||||
children: [
|
||||
SafeArea(
|
||||
top: false,
|
||||
child: CustomScrollView(
|
||||
controller: _scrollController,
|
||||
slivers: [
|
||||
// Hero Section (Continue Watching) - at top of screen
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
if (_onDeck.isNotEmpty && settingsProvider.showHeroSection) {
|
||||
return _buildHeroSection();
|
||||
}
|
||||
// Add top padding when hero is not shown
|
||||
return SliverToBoxAdapter(
|
||||
child: SizedBox(height: kToolbarHeight + MediaQuery.of(context).padding.top + 16),
|
||||
);
|
||||
},
|
||||
CustomScrollView(
|
||||
controller: _scrollController,
|
||||
slivers: [
|
||||
// Hero Section (Continue Watching) - at top of screen
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
if (_onDeck.isNotEmpty && settingsProvider.showHeroSection) {
|
||||
return _buildHeroSection();
|
||||
}
|
||||
// Add top padding when hero is not shown
|
||||
return SliverToBoxAdapter(
|
||||
child: SizedBox(height: kToolbarHeight + MediaQuery.of(context).padding.top + 16),
|
||||
);
|
||||
},
|
||||
),
|
||||
if (_isLoading) const SliverFillRemaining(child: Center(child: CircularProgressIndicator())),
|
||||
if (_errorMessage != null)
|
||||
SliverFillRemaining(
|
||||
child: ErrorStateWidget(
|
||||
message: _errorMessage!,
|
||||
icon: Symbols.error_outline_rounded,
|
||||
onRetry: _loadContent,
|
||||
),
|
||||
),
|
||||
if (_isLoading) const SliverFillRemaining(child: Center(child: CircularProgressIndicator())),
|
||||
if (_errorMessage != null)
|
||||
SliverFillRemaining(
|
||||
child: ErrorStateWidget(
|
||||
message: _errorMessage!,
|
||||
icon: Symbols.error_outline_rounded,
|
||||
onRetry: _loadContent,
|
||||
if (!_isLoading && _errorMessage == null) ...[
|
||||
// On Deck / Continue Watching
|
||||
if (_onDeck.isNotEmpty)
|
||||
SliverToBoxAdapter(
|
||||
child: HubSection(
|
||||
key: _continueWatchingHubKey,
|
||||
hub: PlexHub(
|
||||
hubKey: 'continue_watching',
|
||||
title: t.discover.continueWatching,
|
||||
type: 'mixed',
|
||||
hubIdentifier: '_continue_watching_',
|
||||
size: _onDeck.length,
|
||||
more: false,
|
||||
items: _onDeck,
|
||||
),
|
||||
icon: Symbols.play_circle_rounded,
|
||||
onRefresh: updateItem,
|
||||
onRemoveFromContinueWatching: _refreshContinueWatching,
|
||||
isInContinueWatching: true,
|
||||
onVerticalNavigation: (isUp) => _handleVerticalNavigation(0, isUp),
|
||||
onNavigateUp: _focusTopBoundary,
|
||||
onNavigateToSidebar: _navigateToSidebar,
|
||||
),
|
||||
),
|
||||
if (!_isLoading && _errorMessage == null) ...[
|
||||
// On Deck / Continue Watching
|
||||
if (_onDeck.isNotEmpty)
|
||||
SliverToBoxAdapter(
|
||||
child: HubSection(
|
||||
key: _continueWatchingHubKey,
|
||||
hub: PlexHub(
|
||||
hubKey: 'continue_watching',
|
||||
title: t.discover.continueWatching,
|
||||
type: 'mixed',
|
||||
hubIdentifier: '_continue_watching_',
|
||||
size: _onDeck.length,
|
||||
more: false,
|
||||
items: _onDeck,
|
||||
),
|
||||
icon: Symbols.play_circle_rounded,
|
||||
onRefresh: updateItem,
|
||||
onRemoveFromContinueWatching: _refreshContinueWatching,
|
||||
isInContinueWatching: true,
|
||||
onVerticalNavigation: (isUp) => _handleVerticalNavigation(0, isUp),
|
||||
onNavigateUp: _focusTopBoundary,
|
||||
onNavigateToSidebar: _navigateToSidebar,
|
||||
),
|
||||
|
||||
// Recommendation Hubs (Trending, Top in Genre, etc.)
|
||||
for (int i = 0; i < _hubs.length; i++)
|
||||
SliverToBoxAdapter(
|
||||
child: HubSection(
|
||||
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) ? _focusTopBoundary : null,
|
||||
onNavigateToSidebar: _navigateToSidebar,
|
||||
),
|
||||
),
|
||||
|
||||
// Recommendation Hubs (Trending, Top in Genre, etc.)
|
||||
for (int i = 0; i < _hubs.length; i++)
|
||||
// Show loading skeleton for hubs while they're loading
|
||||
if (_areHubsLoading && _hubs.isEmpty)
|
||||
for (int i = 0; i < 3; i++)
|
||||
SliverToBoxAdapter(
|
||||
child: HubSection(
|
||||
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) ? _focusTopBoundary : null,
|
||||
onNavigateToSidebar: _navigateToSidebar,
|
||||
),
|
||||
),
|
||||
|
||||
// Show loading skeleton for hubs while they're loading
|
||||
if (_areHubsLoading && _hubs.isEmpty)
|
||||
for (int i = 0; i < 3; i++)
|
||||
SliverToBoxAdapter(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Hub title skeleton
|
||||
Container(
|
||||
width: 200,
|
||||
height: 24,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: const BorderRadius.all(Radius.circular(4)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
// Hub items skeleton
|
||||
SizedBox(
|
||||
height: 200,
|
||||
child: ListView.builder(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: 5,
|
||||
itemBuilder: (context, index) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(right: 12),
|
||||
width: 140,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
if (_onDeck.isEmpty && _hubs.isEmpty && !_areHubsLoading)
|
||||
SliverFillRemaining(
|
||||
child: Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
AppIcon(Symbols.movie_rounded, fill: 1, size: 64, color: Colors.grey),
|
||||
SizedBox(height: 16),
|
||||
Text(t.discover.noContentAvailable),
|
||||
SizedBox(height: 8),
|
||||
Text(t.discover.addMediaToLibraries, style: TextStyle(color: Colors.grey)),
|
||||
// Hub title skeleton
|
||||
Container(
|
||||
width: 200,
|
||||
height: 24,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: const BorderRadius.all(Radius.circular(4)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
// Hub items skeleton
|
||||
SizedBox(
|
||||
height: 200,
|
||||
child: ListView.builder(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: 5,
|
||||
itemBuilder: (context, index) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(right: 12),
|
||||
width: 140,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 24)),
|
||||
],
|
||||
if (_onDeck.isEmpty && _hubs.isEmpty && !_areHubsLoading)
|
||||
SliverFillRemaining(
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
AppIcon(Symbols.movie_rounded, fill: 1, size: 64, color: Colors.grey),
|
||||
SizedBox(height: 16),
|
||||
Text(t.discover.noContentAvailable),
|
||||
SizedBox(height: 8),
|
||||
Text(t.discover.addMediaToLibraries, style: TextStyle(color: Colors.grey)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
SliverToBoxAdapter(child: SizedBox(height: 24 + bottomPadding)),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
// Overlaid app bar — excluded from default focus traversal so that
|
||||
// initial/tab-switch focus lands on content (hero/hubs), not the toolbar.
|
||||
@@ -1582,14 +1438,16 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
imageType: ImageType.art,
|
||||
);
|
||||
|
||||
return blurArtwork(CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) =>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
errorWidget: (context, url, error) =>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
));
|
||||
return blurArtwork(
|
||||
CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) =>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
errorWidget: (context, url, error) =>
|
||||
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -1650,39 +1508,19 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
imageType: ImageType.logo,
|
||||
);
|
||||
|
||||
return blurArtwork(CachedNetworkImage(
|
||||
imageUrl: logoUrl,
|
||||
filterQuality: FilterQuality.medium,
|
||||
fit: BoxFit.contain,
|
||||
memCacheWidth: (400 * dpr).clamp(200, 800).round(),
|
||||
alignment: isLargeScreen ? Alignment.bottomLeft : Alignment.bottomCenter,
|
||||
placeholder: (context, url) => Align(
|
||||
alignment: isLargeScreen ? Alignment.centerLeft : Alignment.center,
|
||||
child: Text(
|
||||
showName,
|
||||
style: Theme.of(context).textTheme.displaySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.3),
|
||||
fontWeight: FontWeight.bold,
|
||||
shadows: [
|
||||
Shadow(
|
||||
color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.8),
|
||||
blurRadius: 8,
|
||||
),
|
||||
],
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: isLargeScreen ? TextAlign.left : TextAlign.center,
|
||||
),
|
||||
),
|
||||
errorWidget: (context, url, error) {
|
||||
// Fallback to text if logo fails to load
|
||||
return Align(
|
||||
return blurArtwork(
|
||||
CachedNetworkImage(
|
||||
imageUrl: logoUrl,
|
||||
filterQuality: FilterQuality.medium,
|
||||
fit: BoxFit.contain,
|
||||
memCacheWidth: (400 * dpr).clamp(200, 800).round(),
|
||||
alignment: isLargeScreen ? Alignment.bottomLeft : Alignment.bottomCenter,
|
||||
placeholder: (context, url) => Align(
|
||||
alignment: isLargeScreen ? Alignment.centerLeft : Alignment.center,
|
||||
child: Text(
|
||||
showName,
|
||||
style: Theme.of(context).textTheme.displaySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.3),
|
||||
fontWeight: FontWeight.bold,
|
||||
shadows: [
|
||||
Shadow(
|
||||
@@ -1695,9 +1533,33 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: isLargeScreen ? TextAlign.left : TextAlign.center,
|
||||
),
|
||||
);
|
||||
},
|
||||
), sigma: 10, clip: false);
|
||||
),
|
||||
errorWidget: (context, url, error) {
|
||||
// Fallback to text if logo fails to load
|
||||
return Align(
|
||||
alignment: isLargeScreen ? Alignment.centerLeft : Alignment.center,
|
||||
child: Text(
|
||||
showName,
|
||||
style: Theme.of(context).textTheme.displaySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
shadows: [
|
||||
Shadow(
|
||||
color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.8),
|
||||
blurRadius: 8,
|
||||
),
|
||||
],
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: isLargeScreen ? TextAlign.left : TextAlign.center,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
sigma: 10,
|
||||
clip: false,
|
||||
);
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
@@ -382,7 +382,7 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable, Gri
|
||||
episodePosterMode == EpisodePosterMode.episodeThumbnail && (isEpisodeOnlyHub || isMixedHub);
|
||||
|
||||
return SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
|
||||
padding: const EdgeInsets.all(8),
|
||||
sliver: SliverLayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final maxExtent = GridSizeCalculator.getMaxCrossAxisExtentWithPadding(
|
||||
|
||||
@@ -351,61 +351,29 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
}
|
||||
|
||||
/// Handle key events for the edit button in app bar
|
||||
KeyEventResult _handleEditKeyEvent(FocusNode _, KeyEvent event) {
|
||||
if (!event.isActionable) return KeyEventResult.ignored;
|
||||
final key = event.logicalKey;
|
||||
|
||||
if (key.isLeftKey) {
|
||||
// Navigate back to last tab (Playlists)
|
||||
getTabChipFocusNode(3).requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isRightKey) {
|
||||
_refreshButtonFocusNode.requestFocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isDownKey) {
|
||||
_focusCurrentTab();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isUpKey) {
|
||||
return KeyEventResult.handled; // Block at boundary
|
||||
}
|
||||
if (key.isSelectKey) {
|
||||
_showLibraryManagementSheet();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
late final _handleEditKeyEvent = dpadKeyHandler(
|
||||
onLeft: () => getTabChipFocusNode(3).requestFocus(),
|
||||
onRight: () => _refreshButtonFocusNode.requestFocus(),
|
||||
onDown: _focusCurrentTab,
|
||||
onUp: () {}, // Block at boundary
|
||||
onSelect: _showLibraryManagementSheet,
|
||||
);
|
||||
|
||||
/// Handle key events for the refresh button in app bar
|
||||
KeyEventResult _handleRefreshKeyEvent(FocusNode _, KeyEvent event) {
|
||||
if (!event.isActionable) return KeyEventResult.ignored;
|
||||
final key = event.logicalKey;
|
||||
|
||||
if (key.isLeftKey) {
|
||||
// Navigate to edit button if libraries exist, else to last tab
|
||||
late final _handleRefreshKeyEvent = dpadKeyHandler(
|
||||
onLeft: () {
|
||||
final librariesProvider = context.read<LibrariesProvider>();
|
||||
if (librariesProvider.libraries.isNotEmpty) {
|
||||
_editButtonFocusNode.requestFocus();
|
||||
} else {
|
||||
getTabChipFocusNode(3).requestFocus();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isRightKey || key.isUpKey) {
|
||||
return KeyEventResult.handled; // Block at boundary
|
||||
}
|
||||
if (key.isDownKey) {
|
||||
_focusCurrentTab();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isSelectKey) {
|
||||
_refreshCurrentTab();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
},
|
||||
onRight: () {}, // Block at boundary
|
||||
onUp: () {}, // Block at boundary
|
||||
onDown: _focusCurrentTab,
|
||||
onSelect: _refreshCurrentTab,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
@@ -1066,9 +1034,8 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
// Compute visible libraries (filtered from all libraries)
|
||||
final visibleLibraries = allLibraries.where((lib) => !hiddenKeys.contains(lib.globalKey)).toList();
|
||||
|
||||
return OverlaySheetHost(
|
||||
child: Scaffold(
|
||||
body: ScrollConfiguration(
|
||||
return Scaffold(
|
||||
body: ScrollConfiguration(
|
||||
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
|
||||
child: CustomScrollView(
|
||||
controller: _outerScrollController,
|
||||
@@ -1203,12 +1170,12 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LibraryManagementSheet extends StatefulWidget {
|
||||
|
||||
final bool isDialog;
|
||||
final List<PlexLibrary> allLibraries;
|
||||
final Set<String> hiddenLibraryKeys;
|
||||
@@ -1422,52 +1389,27 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
|
||||
Future<void> _showLibraryMenuBottomSheet(BuildContext outerContext, PlexLibrary library) async {
|
||||
final menuItems = widget.getLibraryMenuItems(library);
|
||||
final controller = OverlaySheetController.maybeOf(outerContext);
|
||||
final String? selected;
|
||||
if (controller != null) {
|
||||
selected = await controller.push<String>(
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(library.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
final selected = await OverlaySheetController.pushAdaptive<String>(
|
||||
outerContext,
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(library.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
),
|
||||
...menuItems.indexed.map(
|
||||
(entry) => ListTile(
|
||||
leading: AppIcon(entry.$2.icon, fill: 1),
|
||||
title: Text(entry.$2.label),
|
||||
onTap: () => OverlaySheetController.popAdaptive(context, entry.$2.value),
|
||||
),
|
||||
...menuItems.indexed.map(
|
||||
(entry) => ListTile(
|
||||
leading: AppIcon(entry.$2.icon, fill: 1),
|
||||
title: Text(entry.$2.label),
|
||||
onTap: () => controller.pop(entry.$2.value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
selected = await showModalBottomSheet<String>(
|
||||
context: outerContext,
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(library.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
),
|
||||
...menuItems.indexed.map(
|
||||
(entry) => ListTile(
|
||||
leading: AppIcon(entry.$2.icon, fill: 1),
|
||||
title: Text(entry.$2.label),
|
||||
onTap: () => Navigator.pop(context, entry.$2.value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
),
|
||||
);
|
||||
|
||||
if (selected != null && mounted) {
|
||||
// Find the selected item to check if confirmation is needed
|
||||
@@ -1583,7 +1525,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
),
|
||||
IconButton(
|
||||
icon: const AppIcon(Symbols.close_rounded, fill: 1),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
onPressed: () => OverlaySheetController.popAdaptive(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -94,40 +94,41 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
|
||||
action: widget.onClear != null ? TextButton(onPressed: _handleClear, child: Text(t.common.clear)) : null,
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: widget.sortOptions.length,
|
||||
itemBuilder: (context, index) {
|
||||
final sort = widget.sortOptions[index];
|
||||
final isSelected = _currentSort?.key == sort.key;
|
||||
child: RadioGroup<PlexSort>(
|
||||
groupValue: _currentSort,
|
||||
onChanged: (value) {
|
||||
if (value != null) _handleSortSelect(value);
|
||||
},
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: widget.sortOptions.length,
|
||||
itemBuilder: (context, index) {
|
||||
final sort = widget.sortOptions[index];
|
||||
final isSelected = _currentSort?.key == sort.key;
|
||||
|
||||
return Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
onKeyEvent: (node, event) {
|
||||
if (!event.isActionable) return KeyEventResult.ignored;
|
||||
if (!isSelected) return KeyEventResult.ignored;
|
||||
if (event.logicalKey.isLeftKey) {
|
||||
_handleDirectionChange(sort, false);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (event.logicalKey.isRightKey) {
|
||||
_handleDirectionChange(sort, true);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
},
|
||||
child: FocusableRadioListTile<PlexSort>(
|
||||
focusNode: (widget.selectedSort?.key == sort.key || (widget.selectedSort == null && index == 0))
|
||||
? _initialFocusNode
|
||||
: null,
|
||||
title: Text(sort.title),
|
||||
value: sort,
|
||||
groupValue: _currentSort,
|
||||
onChanged: (value) {
|
||||
if (value != null) _handleSortSelect(value);
|
||||
return Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
onKeyEvent: (node, event) {
|
||||
if (!event.isActionable) return KeyEventResult.ignored;
|
||||
if (!isSelected) return KeyEventResult.ignored;
|
||||
if (event.logicalKey.isLeftKey) {
|
||||
_handleDirectionChange(sort, false);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (event.logicalKey.isRightKey) {
|
||||
_handleDirectionChange(sort, true);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
},
|
||||
secondary: isSelected
|
||||
child: FocusableRadioListTile<PlexSort>(
|
||||
focusNode: (widget.selectedSort?.key == sort.key || (widget.selectedSort == null && index == 0))
|
||||
? _initialFocusNode
|
||||
: null,
|
||||
title: Text(sort.title),
|
||||
value: sort,
|
||||
secondary: isSelected
|
||||
? SegmentedButton<bool>(
|
||||
showSelectedIcon: false,
|
||||
segments: const [
|
||||
@@ -146,6 +147,7 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -32,6 +32,7 @@ import '../../../mixins/grid_focus_node_mixin.dart';
|
||||
import '../../../mixins/item_updatable.dart';
|
||||
import '../../../mixins/deletion_aware.dart';
|
||||
import '../../../utils/deletion_notifier.dart';
|
||||
import '../../../utils/global_key_utils.dart';
|
||||
import '../../../utils/platform_detector.dart';
|
||||
import '../../../i18n/strings.g.dart';
|
||||
import '../../main_screen.dart';
|
||||
@@ -61,7 +62,7 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
PlexClient get client => getClientForLibrary();
|
||||
|
||||
String _toGlobalKey(String ratingKey, {String? serverId}) =>
|
||||
'${serverId ?? widget.library.serverId ?? ''}:$ratingKey';
|
||||
buildGlobalKey(serverId ?? widget.library.serverId ?? '', ratingKey);
|
||||
|
||||
@override
|
||||
String? get deletionServerId => widget.library.serverId;
|
||||
@@ -495,23 +496,25 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
final options = _getGroupingOptions();
|
||||
return StatefulBuilder(
|
||||
builder: (context, setSheetState) {
|
||||
return ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: options.length,
|
||||
itemBuilder: (context, index) {
|
||||
final grouping = options[index];
|
||||
return RadioListTile<String>(
|
||||
title: Text(_getGroupingLabel(grouping)),
|
||||
value: grouping,
|
||||
groupValue: pendingGrouping,
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
setSheetState(() {
|
||||
pendingGrouping = value;
|
||||
});
|
||||
},
|
||||
);
|
||||
return RadioGroup<String>(
|
||||
groupValue: pendingGrouping,
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
setSheetState(() {
|
||||
pendingGrouping = value;
|
||||
});
|
||||
},
|
||||
child: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: options.length,
|
||||
itemBuilder: (context, index) {
|
||||
final grouping = options[index];
|
||||
return RadioListTile<String>(
|
||||
title: Text(_getGroupingLabel(grouping)),
|
||||
value: grouping,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -822,58 +825,54 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
|
||||
// For folders mode, use FolderTreeView instead of grid/list
|
||||
if (_selectedGrouping == 'folders') {
|
||||
return OverlaySheetHost(
|
||||
child: Column(
|
||||
children: [
|
||||
_buildChipsBar(),
|
||||
Expanded(
|
||||
child: FolderTreeView(
|
||||
libraryKey: widget.library.key,
|
||||
serverId: widget.library.serverId,
|
||||
onRefresh: updateItem,
|
||||
firstItemFocusNode: firstItemFocusNode,
|
||||
onNavigateUp: () => _groupingChipFocusNode.requestFocus(),
|
||||
),
|
||||
return Column(
|
||||
children: [
|
||||
_buildChipsBar(),
|
||||
Expanded(
|
||||
child: FolderTreeView(
|
||||
libraryKey: widget.library.key,
|
||||
serverId: widget.library.serverId,
|
||||
onRefresh: updateItem,
|
||||
firstItemFocusNode: firstItemFocusNode,
|
||||
onNavigateUp: () => _groupingChipFocusNode.requestFocus(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// 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 OverlaySheetHost(
|
||||
child: Stack(
|
||||
children: [
|
||||
// Grid fills the entire area, with top padding for chips bar
|
||||
Positioned.fill(child: _buildScrollableContent()),
|
||||
// Chips bar on top with solid background
|
||||
Positioned(top: 0, left: 0, right: 0, child: _buildChipsBar()),
|
||||
// Alpha jump bar / scroll handle on the right edge
|
||||
if (_shouldShowAlphaJumpBar)
|
||||
Positioned(
|
||||
top: _chipsBarHeight,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: _isPhone(context)
|
||||
? AlphaScrollHandle(
|
||||
firstCharacters: _firstCharacters,
|
||||
onJump: _jumpToIndex,
|
||||
currentLetter: _currentAlphaLetter,
|
||||
isScrolling: _isScrollActive,
|
||||
)
|
||||
: AlphaJumpBar(
|
||||
firstCharacters: _firstCharacters,
|
||||
onJump: _jumpToIndex,
|
||||
currentLetter: _currentAlphaLetter,
|
||||
focusNode: _alphaJumpBarFocusNode,
|
||||
onNavigateLeft: _navigateToGridNearScroll,
|
||||
onBack: _navigateToGridNearScroll,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
return Stack(
|
||||
children: [
|
||||
// Grid fills the entire area, with top padding for chips bar
|
||||
Positioned.fill(child: _buildScrollableContent()),
|
||||
// Chips bar on top with solid background
|
||||
Positioned(top: 0, left: 0, right: 0, child: _buildChipsBar()),
|
||||
// Alpha jump bar / scroll handle on the right edge
|
||||
if (_shouldShowAlphaJumpBar)
|
||||
Positioned(
|
||||
top: _chipsBarHeight,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: _isPhone(context)
|
||||
? AlphaScrollHandle(
|
||||
firstCharacters: _firstCharacters,
|
||||
onJump: _jumpToIndex,
|
||||
currentLetter: _currentAlphaLetter,
|
||||
isScrolling: _isScrollActive,
|
||||
)
|
||||
: AlphaJumpBar(
|
||||
firstCharacters: _firstCharacters,
|
||||
onJump: _jumpToIndex,
|
||||
currentLetter: _currentAlphaLetter,
|
||||
focusNode: _alphaJumpBarFocusNode,
|
||||
onNavigateLeft: _navigateToGridNearScroll,
|
||||
onBack: _navigateToGridNearScroll,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,31 +18,17 @@ void showProgramDetailsSheet(
|
||||
required String? posterUrl,
|
||||
required VoidCallback? onTuneChannel,
|
||||
}) {
|
||||
final controller = OverlaySheetController.maybeOf(context);
|
||||
if (controller != null) {
|
||||
controller.show(
|
||||
builder: (sheetContext) {
|
||||
return _ProgramDetailsSheetContent(
|
||||
program: program,
|
||||
channel: channel,
|
||||
posterUrl: posterUrl,
|
||||
onTuneChannel: onTuneChannel,
|
||||
);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (sheetContext) {
|
||||
return _ProgramDetailsSheetContent(
|
||||
program: program,
|
||||
channel: channel,
|
||||
posterUrl: posterUrl,
|
||||
onTuneChannel: onTuneChannel,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
OverlaySheetController.showAdaptive(
|
||||
context,
|
||||
builder: (sheetContext) {
|
||||
return _ProgramDetailsSheetContent(
|
||||
program: program,
|
||||
channel: channel,
|
||||
posterUrl: posterUrl,
|
||||
onTuneChannel: onTuneChannel,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class _ProgramDetailsSheetContent extends StatefulWidget {
|
||||
@@ -107,14 +93,7 @@ class _ProgramDetailsSheetContentState extends State<_ProgramDetailsSheetContent
|
||||
final buttons = <Widget>[];
|
||||
int buttonIndex = 0;
|
||||
|
||||
void closeSheet() {
|
||||
final controller = OverlaySheetController.maybeOf(context);
|
||||
if (controller != null) {
|
||||
controller.close();
|
||||
} else {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
}
|
||||
void closeSheet() => OverlaySheetController.closeAdaptive(context);
|
||||
|
||||
if (program.isCurrentlyAiring && widget.onTuneChannel != null) {
|
||||
final idx = buttonIndex;
|
||||
|
||||
+114
-94
@@ -17,6 +17,7 @@ import '../utils/platform_detector.dart';
|
||||
import '../utils/video_player_navigation.dart';
|
||||
import '../main.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
import '../widgets/overlay_sheet.dart';
|
||||
import '../mixins/tab_visibility_aware.dart';
|
||||
import '../navigation/navigation_tabs.dart';
|
||||
import '../providers/multi_server_provider.dart';
|
||||
@@ -194,6 +195,12 @@ class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// Native updater (Sparkle/WinSparkle) handles everything — skip Flutter dialog
|
||||
if (UpdateService.useNativeUpdater) {
|
||||
await UpdateService.checkForUpdatesNative(inBackground: true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final updateInfo = await UpdateService.checkForUpdatesOnStartup();
|
||||
|
||||
@@ -524,7 +531,12 @@ class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed && !_isOffline && !_isShowingProfileSelection) {
|
||||
_showProfileSelectionOnResume();
|
||||
// Only show profile selection on resume for mobile platforms.
|
||||
// On desktop, "resumed" fires on every window focus gain (alt-tab, click),
|
||||
// which is too frequent — the initial prompt on startup is sufficient.
|
||||
if (Platform.isAndroid || Platform.isIOS) {
|
||||
_showProfileSelectionOnResume();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -976,6 +988,10 @@ class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener
|
||||
Widget build(BuildContext context) {
|
||||
final useSideNav = PlatformDetector.shouldUseSideNavigation(context);
|
||||
|
||||
return _buildContent(context, useSideNav);
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context, bool useSideNav) {
|
||||
if (useSideNav) {
|
||||
return Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
@@ -984,62 +1000,64 @@ class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener
|
||||
? SideNavigationRailState.expandedWidth
|
||||
: SideNavigationRailState.collapsedWidth;
|
||||
|
||||
return PopScope(
|
||||
canPop: false, // Prevent system back from popping on Android TV
|
||||
// ignore: no-empty-block - required callback, back navigation handled by _handleBackKey
|
||||
onPopInvokedWithResult: (didPop, result) {},
|
||||
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),
|
||||
return OverlaySheetHost(
|
||||
child: PopScope(
|
||||
canPop: false, // Prevent system back from popping on Android TV
|
||||
// ignore: no-empty-block - required callback, back navigation handled by _handleBackKey
|
||||
onPopInvokedWithResult: (didPop, result) {},
|
||||
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: _contentFocusScope,
|
||||
// No autofocus - we control focus programmatically to prevent
|
||||
// autofocus from stealing focus back after setState() rebuilds
|
||||
child: IndexedStack(index: _currentIndex, children: _screens),
|
||||
node: _sidebarFocusScope,
|
||||
child: SideNavigationRail(
|
||||
key: _sideNavKey,
|
||||
selectedIndex: _currentIndex,
|
||||
selectedLibraryKey: _selectedLibraryGlobalKey,
|
||||
isOfflineMode: _isOffline,
|
||||
isSidebarFocused: _isSidebarFocused,
|
||||
alwaysExpanded: alwaysExpanded,
|
||||
isReconnecting: _isReconnecting,
|
||||
onDestinationSelected: (index) {
|
||||
_selectTab(index);
|
||||
_focusContent();
|
||||
},
|
||||
onLibrarySelected: (key) {
|
||||
_selectLibrary(key);
|
||||
_focusContent();
|
||||
},
|
||||
onNavigateToContent: _focusContent,
|
||||
onReconnect: _triggerReconnect,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// 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,
|
||||
isReconnecting: _isReconnecting,
|
||||
onDestinationSelected: (index) {
|
||||
_selectTab(index);
|
||||
_focusContent();
|
||||
},
|
||||
onLibrarySelected: (key) {
|
||||
_selectLibrary(key);
|
||||
_focusContent();
|
||||
},
|
||||
onNavigateToContent: _focusContent,
|
||||
onReconnect: _triggerReconnect,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -1049,53 +1067,55 @@ class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener
|
||||
);
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
body: IndexedStack(index: _currentIndex, children: _screens),
|
||||
bottomNavigationBar: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Reconnect bar when offline
|
||||
if (_isOffline)
|
||||
Material(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: InkWell(
|
||||
onTap: _isReconnecting ? null : _triggerReconnect,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
if (_isReconnecting)
|
||||
SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
return OverlaySheetHost(
|
||||
child: Scaffold(
|
||||
body: IndexedStack(index: _currentIndex, children: _screens),
|
||||
bottomNavigationBar: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Reconnect bar when offline
|
||||
if (_isOffline)
|
||||
Material(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: InkWell(
|
||||
onTap: _isReconnecting ? null : _triggerReconnect,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
if (_isReconnecting)
|
||||
SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
)
|
||||
else
|
||||
Icon(Symbols.wifi_rounded, size: 18, color: Theme.of(context).colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
t.common.reconnect,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
)
|
||||
else
|
||||
Icon(Symbols.wifi_rounded, size: 18, color: Theme.of(context).colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
t.common.reconnect,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
NavigationBar(
|
||||
selectedIndex: _currentIndex,
|
||||
onDestinationSelected: _selectTab,
|
||||
destinations: _buildNavDestinations(_isOffline),
|
||||
),
|
||||
NavigationBar(
|
||||
selectedIndex: _currentIndex,
|
||||
onDestinationSelected: _selectTab,
|
||||
destinations: _buildNavDestinations(_isOffline),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -24,6 +25,7 @@ import '../utils/plex_image_helper.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../services/plex_api_cache.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_video_playback_data.dart';
|
||||
import '../utils/content_utils.dart';
|
||||
import '../utils/rating_utils.dart';
|
||||
import '../models/download_models.dart';
|
||||
@@ -65,6 +67,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
bool _isLoadingSeasons = false;
|
||||
PlexMetadata? _fullMetadata;
|
||||
PlexMetadata? _onDeckEpisode;
|
||||
PlexVideoPlaybackData? _playbackData;
|
||||
bool _isLoadingMetadata = true;
|
||||
List<PlexMetadata>? _extras;
|
||||
late final ScrollController _scrollController;
|
||||
@@ -104,7 +107,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
final _seasonsSectionKey = GlobalKey();
|
||||
|
||||
String _toGlobalKey(String ratingKey, {String? serverId}) =>
|
||||
'${serverId ?? widget.metadata.serverId ?? ''}:$ratingKey';
|
||||
buildGlobalKey(serverId ?? widget.metadata.serverId ?? '', ratingKey);
|
||||
|
||||
// WatchStateAware: watch the show/movie and all season ratingKeys
|
||||
@override
|
||||
@@ -360,6 +363,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
metadata: metadata,
|
||||
isOffline: widget.isOffline,
|
||||
onRefresh: _loadFullMetadata,
|
||||
playbackData: _playbackData,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -421,7 +425,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
if (!widget.isOffline)
|
||||
Consumer<DownloadProvider>(
|
||||
builder: (context, downloadProvider, _) {
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
final progress = downloadProvider.getProgress(globalKey);
|
||||
final isQueueing = downloadProvider.isQueueing(globalKey);
|
||||
|
||||
@@ -848,9 +852,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
hasRating
|
||||
? (starValue == starValue.truncateToDouble()
|
||||
? '${starValue.toInt()}'
|
||||
: starValue.toStringAsFixed(1))
|
||||
? formatRating(starValue)
|
||||
: t.mediaMenu.rate,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSecondaryContainer,
|
||||
@@ -966,6 +968,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
final result = await client.getMetadataWithImagesAndOnDeck(widget.metadata.ratingKey);
|
||||
final metadata = result['metadata'] as PlexMetadata?;
|
||||
final onDeckEpisode = result['onDeckEpisode'] as PlexMetadata?;
|
||||
final playbackData = result['playbackData'] as PlexVideoPlaybackData?;
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
@@ -983,6 +986,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
setState(() {
|
||||
_fullMetadata = metadataWithServerId;
|
||||
_onDeckEpisode = onDeckWithServerId;
|
||||
_playbackData = playbackData;
|
||||
_isLoadingMetadata = false;
|
||||
});
|
||||
|
||||
@@ -2059,7 +2063,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
duration: const Duration(milliseconds: 150),
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(8)),
|
||||
border: Border.all(
|
||||
color: showFocus
|
||||
? Theme.of(context).colorScheme.primary.withValues(alpha: 0.5)
|
||||
@@ -2067,16 +2071,18 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAw
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
child: isTv
|
||||
? Text(
|
||||
metadata.summary!,
|
||||
style: Theme.of(context).textTheme.bodyLarge?.copyWith(height: 1.6),
|
||||
)
|
||||
: CollapsibleText(
|
||||
text: metadata.summary!,
|
||||
maxLines: isMobile ? 6 : 4,
|
||||
style: Theme.of(context).textTheme.bodyLarge?.copyWith(height: 1.6),
|
||||
),
|
||||
child: () {
|
||||
final summaryStyle =
|
||||
Theme.of(context).textTheme.bodyLarge?.copyWith(height: 1.6);
|
||||
if (isTv) {
|
||||
return Text(metadata.summary!, style: summaryStyle);
|
||||
}
|
||||
return CollapsibleText(
|
||||
text: metadata.summary!,
|
||||
maxLines: isMobile ? 6 : 4,
|
||||
style: summaryStyle,
|
||||
);
|
||||
}(),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
@@ -73,6 +73,16 @@ class _MetadataEditScreenState extends State<MetadataEditScreen> {
|
||||
|
||||
Future<void> _loadMetadata() async {
|
||||
try {
|
||||
// If the passed metadata already has full fields (e.g., from detail screen),
|
||||
// use it directly instead of re-fetching. We check both summary and
|
||||
// librarySectionID since the edit screen needs both for display and save.
|
||||
if (widget.metadata.summary != null && widget.metadata.librarySectionID != null) {
|
||||
_fullMetadata = widget.metadata;
|
||||
_initFieldsFromMetadata(widget.metadata);
|
||||
setState(() => _isLoading = false);
|
||||
return;
|
||||
}
|
||||
|
||||
final meta = await _client.getMetadataWithImages(widget.metadata.ratingKey);
|
||||
if (!mounted) return;
|
||||
if (meta != null) {
|
||||
@@ -232,19 +242,21 @@ class _MetadataEditScreenState extends State<MetadataEditScreen> {
|
||||
title: Text(title),
|
||||
content: SizedBox(
|
||||
width: double.maxFinite,
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: options.map((option) {
|
||||
return FocusableRadioListTile<String>(
|
||||
title: Text(option.label),
|
||||
value: option.value,
|
||||
groupValue: selected,
|
||||
onChanged: (val) {
|
||||
setDialogState(() => selected = val);
|
||||
Navigator.pop(dialogContext, val);
|
||||
},
|
||||
);
|
||||
}).toList(),
|
||||
child: RadioGroup<String>(
|
||||
groupValue: selected,
|
||||
onChanged: (val) {
|
||||
setDialogState(() => selected = val);
|
||||
Navigator.pop(dialogContext, val);
|
||||
},
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: options.map((option) {
|
||||
return FocusableRadioListTile<String>(
|
||||
title: Text(option.label),
|
||||
value: option.value,
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
@@ -480,7 +492,7 @@ class _MetadataEditScreenState extends State<MetadataEditScreen> {
|
||||
width: 40,
|
||||
height: 60,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(4)),
|
||||
child: PlexOptimizedImage(
|
||||
client: _client,
|
||||
imagePath: meta.thumb,
|
||||
@@ -500,7 +512,7 @@ class _MetadataEditScreenState extends State<MetadataEditScreen> {
|
||||
width: 80,
|
||||
height: 45,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(4)),
|
||||
child: PlexOptimizedImage(
|
||||
client: _client,
|
||||
imagePath: meta.art,
|
||||
|
||||
@@ -12,7 +12,7 @@ import '../../widgets/plex_optimized_image.dart';
|
||||
|
||||
/// Custom list item widget for playlist items
|
||||
/// Shows drag handle, poster, title/metadata, duration, and remove button
|
||||
class PlaylistItemCard extends StatelessWidget {
|
||||
class PlaylistItemCard extends StatefulWidget {
|
||||
final PlexMetadata item;
|
||||
final int index;
|
||||
final VoidCallback onRemove;
|
||||
@@ -38,21 +38,37 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
this.isMoving = false,
|
||||
});
|
||||
|
||||
@override
|
||||
State<PlaylistItemCard> createState() => _PlaylistItemCardState();
|
||||
}
|
||||
|
||||
class _PlaylistItemCardState extends State<PlaylistItemCard> {
|
||||
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
|
||||
Offset? _tapPosition;
|
||||
|
||||
void _storeTapPosition(TapDownDetails details) {
|
||||
_tapPosition = details.globalPosition;
|
||||
}
|
||||
|
||||
void _showContextMenu() {
|
||||
_contextMenuKey.currentState?.showContextMenu(context, position: _tapPosition);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
// Determine if row is focused (main content area)
|
||||
final isRowFocused = isFocused && focusedColumn == 0;
|
||||
final isRowFocused = widget.isFocused && widget.focusedColumn == 0;
|
||||
|
||||
// Focus states for individual elements
|
||||
final isDragHandleFocused = isFocused && focusedColumn == 1;
|
||||
final isRemoveButtonFocused = isFocused && focusedColumn == 2;
|
||||
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 (isMoving) {
|
||||
if (widget.isMoving) {
|
||||
cardColor = colorScheme.primaryContainer;
|
||||
} else if (isRowFocused) {
|
||||
// Row is focused - use visible border like FocusableWrapper
|
||||
@@ -64,27 +80,32 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
}
|
||||
|
||||
return MediaContextMenu(
|
||||
item: item,
|
||||
onRefresh: onRefresh,
|
||||
onTap: onTap,
|
||||
key: _contextMenuKey,
|
||||
item: widget.item,
|
||||
onRefresh: widget.onRefresh,
|
||||
onTap: widget.onTap,
|
||||
child: Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
color: cardColor,
|
||||
shape: cardShape,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
onTap: widget.onTap,
|
||||
onTapDown: _storeTapPosition,
|
||||
onLongPress: _showContextMenu,
|
||||
onSecondaryTapDown: _storeTapPosition,
|
||||
onSecondaryTap: _showContextMenu,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Row(
|
||||
children: [
|
||||
// Drag handle (if reorderable)
|
||||
// Wrapped in GestureDetector to consume long-press and prevent context menu
|
||||
if (canReorder)
|
||||
if (widget.canReorder)
|
||||
GestureDetector(
|
||||
// ignore: no-empty-block - consumes long-press to prevent context menu on drag
|
||||
onLongPress: () {},
|
||||
child: ReorderableDragStartListener(
|
||||
index: index,
|
||||
index: widget.index,
|
||||
child: Container(
|
||||
color: Colors.transparent,
|
||||
height: 90,
|
||||
@@ -99,9 +120,9 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
)
|
||||
: null,
|
||||
child: AppIcon(
|
||||
isMoving ? Symbols.swap_vert_rounded : Symbols.drag_indicator_rounded,
|
||||
widget.isMoving ? Symbols.swap_vert_rounded : Symbols.drag_indicator_rounded,
|
||||
fill: 1,
|
||||
color: (isMoving || isDragHandleFocused) ? colorScheme.primary : Colors.grey,
|
||||
color: (widget.isMoving || isDragHandleFocused) ? colorScheme.primary : Colors.grey,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -121,7 +142,7 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
children: [
|
||||
// Title
|
||||
Text(
|
||||
item.displayTitle,
|
||||
widget.item.displayTitle,
|
||||
style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -138,10 +159,14 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
),
|
||||
|
||||
// Progress indicator if partially watched
|
||||
if (item.viewOffset != null && item.duration != null)
|
||||
if (widget.item.viewOffset != null && widget.item.duration != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: MediaProgressBar(viewOffset: item.viewOffset!, duration: item.duration!, minHeight: 3),
|
||||
child: MediaProgressBar(
|
||||
viewOffset: widget.item.viewOffset!,
|
||||
duration: widget.item.duration!,
|
||||
minHeight: 3,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -150,8 +175,11 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Duration
|
||||
if (item.duration != null)
|
||||
Text(formatDurationTextual(item.duration!), style: TextStyle(fontSize: 13, color: Colors.grey[400])),
|
||||
if (widget.item.duration != null)
|
||||
Text(
|
||||
formatDurationTextual(widget.item.duration!),
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey[400]),
|
||||
),
|
||||
|
||||
const SizedBox(width: 8),
|
||||
|
||||
@@ -165,7 +193,7 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
: null,
|
||||
child: IconButton(
|
||||
icon: const AppIcon(Symbols.close_rounded, fill: 1, size: 20),
|
||||
onPressed: onRemove,
|
||||
onPressed: widget.onRemove,
|
||||
tooltip: t.playlists.removeItem,
|
||||
color: isRemoveButtonFocused ? colorScheme.primary : Colors.grey[400],
|
||||
),
|
||||
@@ -180,11 +208,11 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
|
||||
/// Get the correct PlexClient for this item's server
|
||||
PlexClient _getClientForItem(BuildContext context) {
|
||||
return context.getClientForServer(item.serverId!);
|
||||
return context.getClientForServer(widget.item.serverId!);
|
||||
}
|
||||
|
||||
Widget _buildPosterImage(BuildContext context) {
|
||||
final posterUrl = item.posterThumb();
|
||||
final posterUrl = widget.item.posterThumb();
|
||||
return ClipRRect(
|
||||
borderRadius: const BorderRadius.all(Radius.circular(6)),
|
||||
child: PlexOptimizedImage.poster(
|
||||
@@ -209,22 +237,22 @@ class PlaylistItemCard extends StatelessWidget {
|
||||
}
|
||||
|
||||
String _buildSubtitle() {
|
||||
final itemType = item.type.toLowerCase();
|
||||
final itemType = widget.item.type.toLowerCase();
|
||||
|
||||
if (itemType == 'episode') {
|
||||
// For episodes, show "S#E# - Episode Title"
|
||||
final season = item.parentIndex;
|
||||
final episode = item.index;
|
||||
final season = widget.item.parentIndex;
|
||||
final episode = widget.item.index;
|
||||
if (season != null && episode != null) {
|
||||
return 'S${season}E$episode${item.displaySubtitle != null ? ' - ${item.displaySubtitle}' : ''}';
|
||||
return 'S${season}E$episode${widget.item.displaySubtitle != null ? ' - ${widget.item.displaySubtitle}' : ''}';
|
||||
}
|
||||
return item.displaySubtitle ?? t.discover.tvShow;
|
||||
return widget.item.displaySubtitle ?? t.discover.tvShow;
|
||||
} else if (itemType == 'movie') {
|
||||
// For movies, show year
|
||||
return item.year?.toString() ?? t.discover.movie;
|
||||
return widget.item.year?.toString() ?? t.discover.movie;
|
||||
}
|
||||
|
||||
// Default to type
|
||||
return item.type;
|
||||
return widget.item.type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import 'package:provider/provider.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../main.dart';
|
||||
import '../focus/focusable_wrapper.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
import '../focus/key_event_utils.dart';
|
||||
import '../focus/dpad_navigator.dart';
|
||||
import '../focus/input_mode_tracker.dart';
|
||||
@@ -55,7 +56,7 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
|
||||
bool _suppressNextBackKeyUp = false;
|
||||
bool _routeSubscribed = false;
|
||||
|
||||
String _toGlobalKey(String ratingKey, {String? serverId}) => '${serverId ?? widget.season.serverId ?? ''}:$ratingKey';
|
||||
String _toGlobalKey(String ratingKey, {String? serverId}) => buildGlobalKey(serverId ?? widget.season.serverId ?? '', ratingKey);
|
||||
|
||||
// WatchStateAware: watch all episode ratingKeys
|
||||
@override
|
||||
@@ -270,7 +271,7 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
|
||||
String? localPosterPath;
|
||||
if (widget.isOffline && episode.serverId != null) {
|
||||
final downloadProvider = context.read<DownloadProvider>();
|
||||
final globalKey = '${episode.serverId}:${episode.ratingKey}';
|
||||
final globalKey = episode.globalKey;
|
||||
// Get the artwork reference and convert to local file path
|
||||
final artworkRef = downloadProvider.getArtworkPaths(globalKey);
|
||||
localPosterPath = artworkRef?.getLocalPath(DownloadStorageService.instance, episode.serverId!);
|
||||
@@ -499,7 +500,7 @@ class _EpisodeCardState extends State<_EpisodeCard> {
|
||||
|
||||
// Only show download status in online mode
|
||||
if (!widget.isOffline && widget.episode.serverId != null) {
|
||||
final globalKey = '${widget.episode.serverId}:${widget.episode.ratingKey}';
|
||||
final globalKey = widget.episode.globalKey;
|
||||
final progress = downloadProvider.getProgress(globalKey);
|
||||
final isQueueing = downloadProvider.isQueueing(globalKey);
|
||||
|
||||
|
||||
@@ -931,6 +931,31 @@ class _SettingsScreenState extends State<SettingsScreen> with FocusableTab {
|
||||
}
|
||||
|
||||
Widget _buildUpdateSection() {
|
||||
// Native updater: simple tile that triggers Sparkle/WinSparkle native dialog
|
||||
if (UpdateService.useNativeUpdater) {
|
||||
return Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
t.settings.updates,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
focusNode: _focusTracker.get(_kCheckForUpdates),
|
||||
leading: const AppIcon(Symbols.system_update_rounded, fill: 1),
|
||||
title: Text(t.settings.checkForUpdates),
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () => UpdateService.checkForUpdatesNative(inBackground: false),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final hasUpdate = _updateInfo != null && _updateInfo!['hasUpdate'] == true;
|
||||
|
||||
return Card(
|
||||
|
||||
@@ -18,6 +18,7 @@ import '../models/livetv_channel.dart';
|
||||
import '../services/plex_api_cache.dart';
|
||||
import '../models/plex_media_version.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_video_playback_data.dart';
|
||||
import '../utils/content_utils.dart';
|
||||
import '../models/plex_media_info.dart';
|
||||
import '../providers/download_provider.dart';
|
||||
@@ -71,6 +72,7 @@ class VideoPlayerScreen extends StatefulWidget {
|
||||
final SubtitleTrack? preferredSubtitleTrack;
|
||||
final int selectedMediaIndex;
|
||||
final bool isOffline;
|
||||
final PlexVideoPlaybackData? playbackData;
|
||||
|
||||
// Live TV fields
|
||||
final bool isLive;
|
||||
@@ -90,6 +92,7 @@ class VideoPlayerScreen extends StatefulWidget {
|
||||
this.preferredSubtitleTrack,
|
||||
this.selectedMediaIndex = 0,
|
||||
this.isOffline = false,
|
||||
this.playbackData,
|
||||
this.isLive = false,
|
||||
this.liveChannelName,
|
||||
this.liveStreamUrl,
|
||||
@@ -157,6 +160,13 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
late final FocusNode _playNextCancelFocusNode;
|
||||
late final FocusNode _playNextConfirmFocusNode;
|
||||
|
||||
// "Still watching?" prompt (sleep timer)
|
||||
bool _showStillWatchingPrompt = false;
|
||||
int _stillWatchingCountdown = 30;
|
||||
Timer? _stillWatchingTimer;
|
||||
late final FocusNode _stillWatchingPauseFocusNode;
|
||||
late final FocusNode _stillWatchingContinueFocusNode;
|
||||
|
||||
// Screen-level focus node: persists across loading/initialized phases so
|
||||
// key events never escape the video player route.
|
||||
late final FocusNode _screenFocusNode;
|
||||
@@ -218,6 +228,10 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
_playNextCancelFocusNode = FocusNode(debugLabel: 'PlayNextCancel');
|
||||
_playNextConfirmFocusNode = FocusNode(debugLabel: 'PlayNextConfirm');
|
||||
|
||||
// Initialize "Still watching?" dialog focus nodes
|
||||
_stillWatchingPauseFocusNode = FocusNode(debugLabel: 'StillWatchingPause');
|
||||
_stillWatchingContinueFocusNode = FocusNode(debugLabel: 'StillWatchingContinue');
|
||||
|
||||
// Screen-level focus node that wraps the entire build output.
|
||||
// Ensures a single stable focus target across loading → initialized phases.
|
||||
_screenFocusNode = FocusNode(debugLabel: 'VideoPlayerScreen');
|
||||
@@ -262,9 +276,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
// Wire companion remote playback callbacks
|
||||
_setupCompanionRemoteCallbacks();
|
||||
|
||||
// Exit the player when the sleep timer completes so the device can auto-lock
|
||||
_sleepTimerSubscription = SleepTimerService().onCompleted.listen((_) {
|
||||
if (mounted) _handleBackButton();
|
||||
// Show "Still watching?" prompt when sleep timer fires
|
||||
_sleepTimerSubscription = SleepTimerService().onPrompt.listen((_) {
|
||||
if (mounted) _showStillWatchingDialog();
|
||||
});
|
||||
|
||||
// Initialize player asynchronously with buffer size from settings
|
||||
@@ -460,6 +474,12 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
_isPlayerInitialized = true;
|
||||
});
|
||||
|
||||
// Restart sleep timer if we're starting a new playback session
|
||||
final p = player;
|
||||
if (p != null) {
|
||||
SleepTimerService().restartIfNeeded(() => p.pause());
|
||||
}
|
||||
|
||||
// Enable wakelock to prevent screen from turning off during playback
|
||||
WakelockPlus.enable();
|
||||
appLogger.d('Wakelock enabled for video playback');
|
||||
@@ -930,6 +950,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
metadata: widget.metadata,
|
||||
selectedMediaIndex: widget.selectedMediaIndex,
|
||||
preferOffline: true, // Use downloaded file if available
|
||||
playbackData: widget.playbackData,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -947,7 +968,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
// since the user may have watched further since downloading.
|
||||
Duration? resumePosition;
|
||||
if (widget.isOffline) {
|
||||
final globalKey = '${widget.metadata.serverId}:${widget.metadata.ratingKey}';
|
||||
final globalKey = widget.metadata.globalKey;
|
||||
final localOffset = await offlineWatchService!.getLocalViewOffset(globalKey);
|
||||
if (localOffset != null && localOffset > 0) {
|
||||
resumePosition = Duration(milliseconds: localOffset);
|
||||
@@ -1099,7 +1120,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
// Debug: log metadata info
|
||||
appLogger.d('Offline playback - serverId: ${widget.metadata.serverId}, ratingKey: ${widget.metadata.ratingKey}');
|
||||
|
||||
final globalKey = '${widget.metadata.serverId}:${widget.metadata.ratingKey}';
|
||||
final globalKey = widget.metadata.globalKey;
|
||||
appLogger.d('Looking up video with globalKey: $globalKey');
|
||||
|
||||
final videoPath = await downloadProvider.getVideoFilePath(globalKey);
|
||||
@@ -1153,6 +1174,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
|
||||
/// Restore ambient lighting from persisted setting
|
||||
Future<void> _restoreAmbientLighting() async {
|
||||
final shaderProvider = context.read<ShaderProvider>();
|
||||
final settings = await SettingsService.getInstance();
|
||||
if (!settings.getAmbientLighting()) return;
|
||||
|
||||
@@ -1173,7 +1195,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
final outputAspect = playerSize.width / playerSize.height;
|
||||
|
||||
// Clear shaders — ambient lighting and shaders are mutually exclusive
|
||||
final shaderProvider = context.read<ShaderProvider>();
|
||||
if (shaderProvider.isShaderEnabled) {
|
||||
await _shaderService!.applyPreset(ShaderPreset.none);
|
||||
shaderProvider.setCurrentPreset(ShaderPreset.none);
|
||||
@@ -1208,6 +1229,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
Future<void> _toggleAmbientLighting() async {
|
||||
final ambientLighting = _ambientLightingService;
|
||||
if (ambientLighting == null || !ambientLighting.isSupported) return;
|
||||
final shaderProvider = context.read<ShaderProvider>();
|
||||
|
||||
if (ambientLighting.isEnabled) {
|
||||
await ambientLighting.disable();
|
||||
@@ -1228,7 +1250,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
final outputAspect = playerSize.width / playerSize.height;
|
||||
|
||||
// Clear shaders — ambient lighting and shaders are mutually exclusive
|
||||
final shaderProvider = context.read<ShaderProvider>();
|
||||
if (shaderProvider.isShaderEnabled) {
|
||||
await _shaderService!.applyPreset(ShaderPreset.none);
|
||||
shaderProvider.setCurrentPreset(ShaderPreset.none);
|
||||
@@ -1244,7 +1265,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
final settings = await SettingsService.getInstance();
|
||||
settings.setAmbientLighting(ambientLighting.isEnabled);
|
||||
|
||||
setState(() {});
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
/// Toggle between contain and cover modes only (for pinch gesture)
|
||||
@@ -1566,6 +1587,11 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
_videoPIPManager?.onBeforeEnterPip = null;
|
||||
_videoFilterManager?.dispose();
|
||||
|
||||
// Mark sleep timer for restart if truly exiting (not episode transition)
|
||||
if (!_isReplacingWithVideo) {
|
||||
SleepTimerService().markNeedsRestart();
|
||||
}
|
||||
|
||||
// Cancel stream subscriptions
|
||||
_playingSubscription?.cancel();
|
||||
_completedSubscription?.cancel();
|
||||
@@ -1581,10 +1607,17 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
// Cancel auto-play timer
|
||||
_autoPlayTimer?.cancel();
|
||||
|
||||
// Cancel still watching timer
|
||||
_stillWatchingTimer?.cancel();
|
||||
|
||||
// Dispose Play Next dialog focus nodes
|
||||
_playNextCancelFocusNode.dispose();
|
||||
_playNextConfirmFocusNode.dispose();
|
||||
|
||||
// Dispose "Still watching?" dialog focus nodes
|
||||
_stillWatchingPauseFocusNode.dispose();
|
||||
_stillWatchingContinueFocusNode.dispose();
|
||||
|
||||
// Dispose screen-level focus node
|
||||
_screenFocusNode.removeListener(_onScreenFocusChanged);
|
||||
_screenFocusNode.dispose();
|
||||
@@ -1674,7 +1707,11 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
}
|
||||
|
||||
void _onVideoCompleted(bool completed) async {
|
||||
if (completed && _nextEpisode != null && !_showPlayNextDialog && !_completionTriggered) {
|
||||
if (completed &&
|
||||
_nextEpisode != null &&
|
||||
!_showPlayNextDialog &&
|
||||
!_showStillWatchingPrompt &&
|
||||
!_completionTriggered) {
|
||||
_completionTriggered = true;
|
||||
|
||||
// Capture keyboard mode before async gap
|
||||
@@ -1739,6 +1776,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
|
||||
// Cancel auto-play timer if running
|
||||
_autoPlayTimer?.cancel();
|
||||
_dismissStillWatching();
|
||||
|
||||
// Notify Watch Together of episode change before navigating
|
||||
_notifyWatchTogetherMediaChange(metadata: _nextEpisode);
|
||||
@@ -1930,6 +1968,73 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
});
|
||||
}
|
||||
|
||||
// -- "Still watching?" prompt --
|
||||
|
||||
void _showStillWatchingDialog() {
|
||||
// Don't show if auto-play dialog is already visible
|
||||
if (_showPlayNextDialog) return;
|
||||
|
||||
final isKeyboardMode = PlatformDetector.isTV() && InputModeTracker.isKeyboardMode(context);
|
||||
|
||||
setState(() {
|
||||
_showStillWatchingPrompt = true;
|
||||
_stillWatchingCountdown = 30;
|
||||
});
|
||||
|
||||
if (isKeyboardMode) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) _stillWatchingContinueFocusNode.requestFocus();
|
||||
});
|
||||
}
|
||||
|
||||
_stillWatchingTimer?.cancel();
|
||||
_stillWatchingTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
if (!mounted) {
|
||||
timer.cancel();
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_stillWatchingCountdown--;
|
||||
});
|
||||
if (_stillWatchingCountdown <= 0) {
|
||||
timer.cancel();
|
||||
_onStillWatchingTimeout();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _onStillWatchingTimeout() {
|
||||
player?.pause();
|
||||
setState(() {
|
||||
_showStillWatchingPrompt = false;
|
||||
});
|
||||
}
|
||||
|
||||
void _onStillWatchingContinue() {
|
||||
_stillWatchingTimer?.cancel();
|
||||
SleepTimerService().restartTimer();
|
||||
setState(() {
|
||||
_showStillWatchingPrompt = false;
|
||||
});
|
||||
}
|
||||
|
||||
void _onStillWatchingPause() {
|
||||
_stillWatchingTimer?.cancel();
|
||||
player?.pause();
|
||||
setState(() {
|
||||
_showStillWatchingPrompt = false;
|
||||
});
|
||||
}
|
||||
|
||||
void _dismissStillWatching() {
|
||||
_stillWatchingTimer?.cancel();
|
||||
if (_showStillWatchingPrompt) {
|
||||
setState(() {
|
||||
_showStillWatchingPrompt = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply track selection using the TrackSelectionService
|
||||
Future<void> _applyTrackSelection() async {
|
||||
if (!mounted || player == null) return;
|
||||
@@ -1952,107 +2057,126 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
);
|
||||
}
|
||||
|
||||
/// Handle audio track changes from the user - save both stream selection and language preference
|
||||
Future<void> _onAudioTrackChanged(AudioTrack track) async {
|
||||
final settings = await SettingsService.getInstance();
|
||||
/// Rating key used for series/movie level language preferences.
|
||||
String get _preferenceRatingKey {
|
||||
return widget.metadata.isEpisode
|
||||
? (widget.metadata.grandparentRatingKey ?? widget.metadata.ratingKey)
|
||||
: widget.metadata.ratingKey;
|
||||
}
|
||||
|
||||
/// Common guard checks for track change handlers.
|
||||
/// Returns the part ID if all checks pass, or null if the change should be skipped.
|
||||
Future<int?> _guardTrackChange() async {
|
||||
final settings = await SettingsService.getInstance();
|
||||
if (!settings.getRememberTrackSelections()) return null;
|
||||
|
||||
// Only save if remember track selections is enabled
|
||||
if (!settings.getRememberTrackSelections()) {
|
||||
return;
|
||||
}
|
||||
if (_currentMediaInfo == null) {
|
||||
appLogger.w('No media info available, cannot save stream selection');
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
final partId = _currentMediaInfo!.getPartId();
|
||||
if (partId == null) {
|
||||
appLogger.w('No part ID available, cannot save stream selection');
|
||||
return;
|
||||
}
|
||||
return partId;
|
||||
}
|
||||
|
||||
final languageCode = track.language;
|
||||
int? streamID;
|
||||
/// Save language preference and stream selection to the server.
|
||||
Future<void> _saveTrackPreferences({
|
||||
required int partId,
|
||||
required String trackType,
|
||||
String? languageCode,
|
||||
int? streamID,
|
||||
}) async {
|
||||
try {
|
||||
if (!mounted) return;
|
||||
final client = _getClientForMetadata(context);
|
||||
final ratingKey = _preferenceRatingKey;
|
||||
|
||||
// === Matching by attributes ===
|
||||
PlexAudioTrack? matched;
|
||||
final normalizedTrackLang = _iso6391ToPlex6392(track.language);
|
||||
final futures = <Future>[];
|
||||
|
||||
appLogger.d('Normalized media_kit language: ${track.language} -> $normalizedTrackLang');
|
||||
if (languageCode != null && (trackType == 'subtitle' || languageCode.isNotEmpty)) {
|
||||
futures.add(
|
||||
trackType == 'audio'
|
||||
? client.setMetadataPreferences(ratingKey, audioLanguage: languageCode)
|
||||
: client.setMetadataPreferences(ratingKey, subtitleLanguage: languageCode),
|
||||
);
|
||||
}
|
||||
if (streamID != null) {
|
||||
futures.add(
|
||||
trackType == 'audio'
|
||||
? client.selectStreams(partId, audioStreamID: streamID, allParts: true)
|
||||
: client.selectStreams(partId, subtitleStreamID: streamID, allParts: true),
|
||||
);
|
||||
}
|
||||
|
||||
for (final plexTrack in _currentMediaInfo!.audioTracks) {
|
||||
final matchLang = plexTrack.languageCode == normalizedTrackLang;
|
||||
final matchTitle = (track.title == null || track.title!.isEmpty)
|
||||
await Future.wait(futures);
|
||||
appLogger.d('Successfully saved $trackType preferences (language + stream)');
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to save $trackType preferences', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Match an mpv track against Plex tracks by language and title.
|
||||
int? _matchTrackByAttributes<T>({
|
||||
required String? mpvLanguage,
|
||||
required String? mpvTitle,
|
||||
required List<T> plexTracks,
|
||||
required String? Function(T) getLanguageCode,
|
||||
required String? Function(T) getDisplayTitle,
|
||||
required String? Function(T) getTitle,
|
||||
required int Function(T) getId,
|
||||
}) {
|
||||
final normalizedLang = _iso6391ToPlex6392(mpvLanguage);
|
||||
|
||||
for (final plexTrack in plexTracks) {
|
||||
final matchLang = getLanguageCode(plexTrack) == normalizedLang;
|
||||
final matchTitle = (mpvTitle == null || mpvTitle.isEmpty)
|
||||
? true
|
||||
: (plexTrack.displayTitle == track.title || plexTrack.title == track.title);
|
||||
: (getDisplayTitle(plexTrack) == mpvTitle || getTitle(plexTrack) == mpvTitle);
|
||||
|
||||
if (matchLang && matchTitle) {
|
||||
matched = plexTrack;
|
||||
appLogger.d('Matched audio by lang/title: streamID ${matched.id}');
|
||||
break;
|
||||
return getId(plexTrack);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (matched != null) {
|
||||
streamID = matched.id;
|
||||
/// Handle audio track changes from the user - save both stream selection and language preference
|
||||
Future<void> _onAudioTrackChanged(AudioTrack track) async {
|
||||
final partId = await _guardTrackChange();
|
||||
if (partId == null) return;
|
||||
|
||||
int? streamID = _matchTrackByAttributes(
|
||||
mpvLanguage: track.language,
|
||||
mpvTitle: track.title,
|
||||
plexTracks: _currentMediaInfo!.audioTracks,
|
||||
getLanguageCode: (t) => t.languageCode,
|
||||
getDisplayTitle: (t) => t.displayTitle,
|
||||
getTitle: (t) => t.title,
|
||||
getId: (t) => t.id,
|
||||
);
|
||||
|
||||
if (streamID != null) {
|
||||
appLogger.d('Matched audio by lang/title: streamID $streamID');
|
||||
} else {
|
||||
// Use property-based matching from track_selection_service
|
||||
final matchedPlex = findPlexTrackForMpvAudio(track, _currentMediaInfo!.audioTracks);
|
||||
|
||||
if (matchedPlex != null) {
|
||||
streamID = matchedPlex.id;
|
||||
streamID = matchedPlex?.id;
|
||||
if (streamID != null) {
|
||||
appLogger.d('Matched audio by properties: streamID $streamID');
|
||||
} else {
|
||||
appLogger.e('Could not match audio track to any Plex track');
|
||||
}
|
||||
}
|
||||
|
||||
final isEpisode = widget.metadata.isEpisode;
|
||||
final languagePrefRatingKey = isEpisode
|
||||
? (widget.metadata.grandparentRatingKey ?? widget.metadata.ratingKey)
|
||||
: widget.metadata.ratingKey;
|
||||
|
||||
try {
|
||||
if (!mounted) return;
|
||||
final client = _getClientForMetadata(context);
|
||||
|
||||
final futures = <Future>[];
|
||||
|
||||
// 1. Language preference (series/movie level)
|
||||
if (languageCode != null && languageCode.isNotEmpty) {
|
||||
futures.add(client.setMetadataPreferences(languagePrefRatingKey, audioLanguage: languageCode));
|
||||
}
|
||||
// 2. Exact stream selection (part level)
|
||||
if (streamID != null) {
|
||||
futures.add(client.selectStreams(partId, audioStreamID: streamID, allParts: true));
|
||||
}
|
||||
|
||||
await Future.wait(futures);
|
||||
appLogger.d('Successfully saved audio preferences (language + stream)');
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to save audio preferences', error: e);
|
||||
}
|
||||
await _saveTrackPreferences(partId: partId, trackType: 'audio', languageCode: track.language, streamID: streamID);
|
||||
}
|
||||
|
||||
/// Handle subtitle track changes from the user - save both stream selection and language preference
|
||||
Future<void> _onSubtitleTrackChanged(SubtitleTrack track) async {
|
||||
final settings = await SettingsService.getInstance();
|
||||
|
||||
// Only save if remember track selections is enabled
|
||||
if (!settings.getRememberTrackSelections()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_currentMediaInfo == null) {
|
||||
appLogger.w('No media info available, cannot save stream selection');
|
||||
return;
|
||||
}
|
||||
|
||||
final partId = _currentMediaInfo!.getPartId();
|
||||
if (partId == null) {
|
||||
appLogger.w('No part ID available, cannot save stream selection');
|
||||
return;
|
||||
}
|
||||
final partId = await _guardTrackChange();
|
||||
if (partId == null) return;
|
||||
|
||||
String? languageCode;
|
||||
int? streamID;
|
||||
@@ -2064,38 +2188,22 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
} else {
|
||||
languageCode = track.language;
|
||||
|
||||
// === Matching by attributes ===
|
||||
PlexSubtitleTrack? matched;
|
||||
final normalizedTrackLang = _iso6391ToPlex6392(track.language);
|
||||
streamID = _matchTrackByAttributes(
|
||||
mpvLanguage: track.language,
|
||||
mpvTitle: track.title,
|
||||
plexTracks: _currentMediaInfo!.subtitleTracks,
|
||||
getLanguageCode: (t) => t.languageCode,
|
||||
getDisplayTitle: (t) => t.displayTitle,
|
||||
getTitle: (t) => t.title,
|
||||
getId: (t) => t.id,
|
||||
);
|
||||
|
||||
appLogger.d('Normalized media_kit language: ${track.language} -> $normalizedTrackLang');
|
||||
|
||||
for (final plexTrack in _currentMediaInfo!.subtitleTracks) {
|
||||
final matchLang = plexTrack.languageCode == normalizedTrackLang;
|
||||
final matchTitle = (track.title == null || track.title!.isEmpty)
|
||||
? true
|
||||
: (plexTrack.displayTitle == track.title || plexTrack.title == track.title);
|
||||
|
||||
appLogger.d('Comparing with streamID ${plexTrack.id}:');
|
||||
appLogger.d(' matchLang: $matchLang (${plexTrack.languageCode} == $normalizedTrackLang)');
|
||||
appLogger.d(' matchTitle: $matchTitle');
|
||||
|
||||
if (matchLang && matchTitle) {
|
||||
matched = plexTrack;
|
||||
appLogger.d(' ✅ MATCHED!');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (matched != null) {
|
||||
streamID = matched.id;
|
||||
if (streamID != null) {
|
||||
appLogger.d('Matched subtitle by lang/title: streamID $streamID');
|
||||
} else {
|
||||
// Use property-based matching from track_selection_service
|
||||
final matchedPlex = findPlexTrackForMpvSubtitle(track, _currentMediaInfo!.subtitleTracks);
|
||||
|
||||
if (matchedPlex != null) {
|
||||
streamID = matchedPlex.id;
|
||||
streamID = matchedPlex?.id;
|
||||
if (streamID != null) {
|
||||
appLogger.d('Matched subtitle by properties: streamID $streamID');
|
||||
} else {
|
||||
appLogger.e('Could not match subtitle track to any Plex track');
|
||||
@@ -2103,36 +2211,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
}
|
||||
}
|
||||
|
||||
// Determine ratingKeys
|
||||
final isEpisode = widget.metadata.isEpisode;
|
||||
final languagePrefRatingKey = isEpisode
|
||||
? (widget.metadata.grandparentRatingKey ?? widget.metadata.ratingKey)
|
||||
: widget.metadata.ratingKey;
|
||||
|
||||
appLogger.i(
|
||||
'Saving subtitle preference: language=$languageCode (ratingKey: $languagePrefRatingKey), streamID=$streamID (partId: $partId)',
|
||||
);
|
||||
|
||||
try {
|
||||
if (!mounted) return;
|
||||
final client = _getClientForMetadata(context);
|
||||
|
||||
final futures = <Future>[];
|
||||
|
||||
// 1. Save language preference at series/movie level
|
||||
if (languageCode != null) {
|
||||
futures.add(client.setMetadataPreferences(languagePrefRatingKey, subtitleLanguage: languageCode));
|
||||
}
|
||||
// 2. Save exact stream selection using part ID
|
||||
if (streamID != null) {
|
||||
futures.add(client.selectStreams(partId, subtitleStreamID: streamID, allParts: true));
|
||||
}
|
||||
|
||||
await Future.wait(futures);
|
||||
appLogger.d('Successfully saved subtitle preferences (language + stream)');
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to save subtitle preferences', error: e);
|
||||
}
|
||||
await _saveTrackPreferences(partId: partId, trackType: 'subtitle', languageCode: languageCode, streamID: streamID);
|
||||
}
|
||||
|
||||
/// Set flag to skip orientation restoration when replacing with another video
|
||||
@@ -2263,9 +2342,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
},
|
||||
child: OverlaySheetHost(
|
||||
child: Builder(
|
||||
builder: (sheetContext) => _isPlayerInitialized && player != null
|
||||
? _buildVideoPlayer(sheetContext)
|
||||
: _buildLoadingSpinner(),
|
||||
builder: (sheetContext) =>
|
||||
_isPlayerInitialized && player != null ? _buildVideoPlayer(sheetContext) : _buildLoadingSpinner(),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -2560,6 +2638,104 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
);
|
||||
},
|
||||
),
|
||||
// "Still watching?" overlay (hidden in PiP mode)
|
||||
ValueListenableBuilder<bool>(
|
||||
valueListenable: PipService().isPipActive,
|
||||
builder: (context, isInPip, child) {
|
||||
if (isInPip || !_showStillWatchingPrompt) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: _controlsVisible,
|
||||
builder: (context, controlsShown, child) {
|
||||
return AnimatedPositioned(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
curve: Curves.easeInOut,
|
||||
right: 24,
|
||||
bottom: controlsShown ? 100 : 24,
|
||||
child: Container(
|
||||
width: 320,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.9),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(12)),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
t.videoControls.stillWatching,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withValues(alpha: 0.7),
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
t.videoControls.pausingIn(seconds: '$_stillWatchingCountdown'),
|
||||
style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: FocusableButton(
|
||||
focusNode: _stillWatchingPauseFocusNode,
|
||||
onPressed: _onStillWatchingPause,
|
||||
autoScroll: false,
|
||||
onNavigateRight: () => _stillWatchingContinueFocusNode.requestFocus(),
|
||||
onNavigateUp: () {},
|
||||
onNavigateDown: () {},
|
||||
child: OutlinedButton(
|
||||
onPressed: _onStillWatchingPause,
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.white,
|
||||
side: BorderSide(color: Colors.white.withValues(alpha: 0.5)),
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
),
|
||||
child: Text(t.videoControls.pauseButton),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: FocusableButton(
|
||||
focusNode: _stillWatchingContinueFocusNode,
|
||||
onPressed: _onStillWatchingContinue,
|
||||
autoScroll: false,
|
||||
onNavigateLeft: () => _stillWatchingPauseFocusNode.requestFocus(),
|
||||
onNavigateUp: () {},
|
||||
onNavigateDown: () {},
|
||||
child: FilledButton(
|
||||
onPressed: _onStillWatchingContinue,
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: Colors.black,
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text('$_stillWatchingCountdown'),
|
||||
const SizedBox(width: 4),
|
||||
Text(t.videoControls.continueWatching),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
// Buffering indicator (also shows during initial load, but not when exiting)
|
||||
// Hidden in PiP mode
|
||||
ValueListenableBuilder<bool>(
|
||||
|
||||
@@ -38,9 +38,7 @@ class AmbientLightingService {
|
||||
|
||||
try {
|
||||
// Write static shader (only needs to happen once)
|
||||
if (_shaderPath == null) {
|
||||
_shaderPath = await _writeShaderToTemp(_generateShader());
|
||||
}
|
||||
_shaderPath ??= await _writeShaderToTemp(_generateShader());
|
||||
|
||||
if (kDebugMode) {
|
||||
debugPrint('AmbientLightingService: Shader path: $_shaderPath');
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:convert';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Base class for services that use SharedPreferences singleton pattern.
|
||||
@@ -33,6 +34,22 @@ abstract class BaseSharedPreferencesService {
|
||||
return _instances[T] as T;
|
||||
}
|
||||
|
||||
/// Decode a JSON string to a Map with error handling.
|
||||
///
|
||||
/// If [legacyStringOk] is true and the value is a plain string (not valid
|
||||
/// JSON), returns `{'key': jsonString, 'descending': false}` for legacy
|
||||
/// library sort compatibility.
|
||||
Map<String, dynamic> decodeJsonStringToMap(String jsonString, {bool legacyStringOk = false}) {
|
||||
try {
|
||||
return json.decode(jsonString) as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
if (legacyStringOk) {
|
||||
return {'key': jsonString, 'descending': false};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/// Hook for subclass-specific initialization after SharedPreferences is ready.
|
||||
///
|
||||
/// Override this method to perform any setup that requires access to
|
||||
|
||||
@@ -86,44 +86,43 @@ class CompanionRemotePeerService {
|
||||
return List.generate(6, (index) => random.nextInt(10).toString()).join();
|
||||
}
|
||||
|
||||
Future<String> _getLocalIpAddress() async {
|
||||
Future<List<String>> _getAllLocalIpAddresses() async {
|
||||
try {
|
||||
final interfaces = await NetworkInterface.list(type: InternetAddressType.IPv4);
|
||||
|
||||
// Prefer WiFi interface, then any non-loopback
|
||||
final preferred = <String>[];
|
||||
final others = <String>[];
|
||||
|
||||
for (final interface in interfaces) {
|
||||
// Skip loopback
|
||||
if (interface.name.toLowerCase().contains('lo')) continue;
|
||||
|
||||
for (final addr in interface.addresses) {
|
||||
if (!addr.isLoopback && addr.type == InternetAddressType.IPv4) {
|
||||
// Prefer names that suggest WiFi/Ethernet
|
||||
if (interface.name.toLowerCase().contains('en') ||
|
||||
interface.name.toLowerCase().contains('wl') ||
|
||||
interface.name.toLowerCase().contains('eth')) {
|
||||
return addr.address;
|
||||
final name = interface.name.toLowerCase();
|
||||
if (name.contains('en') || name.contains('wl') || name.contains('eth')) {
|
||||
preferred.add(addr.address);
|
||||
} else {
|
||||
others.add(addr.address);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: return any non-loopback IPv4
|
||||
for (final interface in interfaces) {
|
||||
for (final addr in interface.addresses) {
|
||||
if (!addr.isLoopback && addr.type == InternetAddressType.IPv4) {
|
||||
return addr.address;
|
||||
}
|
||||
}
|
||||
final all = [...preferred, ...others];
|
||||
if (all.isEmpty) {
|
||||
throw const RemotePeerError(type: RemotePeerErrorType.networkError, message: 'No network interface found');
|
||||
}
|
||||
|
||||
throw const RemotePeerError(type: RemotePeerErrorType.networkError, message: 'No network interface found');
|
||||
return all;
|
||||
} catch (e) {
|
||||
appLogger.e('CompanionRemote: Failed to get local IP', error: e);
|
||||
appLogger.e('CompanionRemote: Failed to get local IPs', error: e);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<({String sessionId, String pin, String address})> createSession(String deviceName, String platform) async {
|
||||
Future<({String sessionId, String pin, List<String> addresses})> createSession(
|
||||
String deviceName,
|
||||
String platform,
|
||||
) async {
|
||||
if (_server != null) {
|
||||
await disconnect();
|
||||
}
|
||||
@@ -145,11 +144,12 @@ class CompanionRemotePeerService {
|
||||
_server = await HttpServer.bind(InternetAddress.anyIPv4, 0);
|
||||
}
|
||||
|
||||
final localIp = await _getLocalIpAddress();
|
||||
final localIps = await _getAllLocalIpAddresses();
|
||||
final port = _server!.port;
|
||||
_hostAddress = '$localIp:$port';
|
||||
final addresses = localIps.map((ip) => '$ip:$port').toList();
|
||||
_hostAddress = addresses.first;
|
||||
|
||||
appLogger.d('CompanionRemote: Host server started at $_hostAddress');
|
||||
appLogger.d('CompanionRemote: Host server started, addresses: $addresses');
|
||||
|
||||
// Listen for WebSocket connections
|
||||
_server!.listen((HttpRequest request) async {
|
||||
@@ -168,7 +168,7 @@ class CompanionRemotePeerService {
|
||||
|
||||
_connectionStateController.add(RemoteSessionStatus.connected);
|
||||
|
||||
return (sessionId: _sessionId!, pin: _pin!, address: _hostAddress!);
|
||||
return (sessionId: _sessionId!, pin: _pin!, addresses: addresses);
|
||||
} catch (e) {
|
||||
appLogger.e('CompanionRemote: Failed to create server', error: e);
|
||||
_errorController.add(
|
||||
@@ -441,6 +441,94 @@ class CompanionRemotePeerService {
|
||||
);
|
||||
}
|
||||
|
||||
/// Race WebSocket connections to multiple host addresses in parallel.
|
||||
/// Returns the winning address and sets up a proper managed connection via [joinSession].
|
||||
Future<String> joinSessionRacing(
|
||||
String sessionId,
|
||||
String pin,
|
||||
String deviceName,
|
||||
String platform,
|
||||
List<String> hostAddresses,
|
||||
) async {
|
||||
if (hostAddresses.length == 1) {
|
||||
await joinSession(sessionId, pin, deviceName, platform, hostAddresses.first);
|
||||
return hostAddresses.first;
|
||||
}
|
||||
|
||||
appLogger.d('CompanionRemote: Racing connections to ${hostAddresses.length} addresses');
|
||||
|
||||
final completer = Completer<String>();
|
||||
final channels = <IOWebSocketChannel>[];
|
||||
final subs = <StreamSubscription>[];
|
||||
|
||||
void cleanup() {
|
||||
for (final sub in subs) {
|
||||
sub.cancel();
|
||||
}
|
||||
for (final ch in channels) {
|
||||
try {
|
||||
ch.sink.close();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
for (final address in hostAddresses) {
|
||||
try {
|
||||
final url = 'ws://$address/ws';
|
||||
final channel = IOWebSocketChannel.connect(Uri.parse(url), connectTimeout: const Duration(seconds: 5));
|
||||
channels.add(channel);
|
||||
|
||||
// Send auth immediately
|
||||
channel.sink.add(jsonEncode({
|
||||
'type': 'auth',
|
||||
'sessionId': sessionId.toUpperCase(),
|
||||
'pin': pin,
|
||||
'deviceName': deviceName,
|
||||
'platform': platform,
|
||||
}));
|
||||
|
||||
final sub = channel.stream.listen(
|
||||
(data) {
|
||||
try {
|
||||
final json = jsonDecode(data as String) as Map<String, dynamic>;
|
||||
if (json['type'] == 'authSuccess' && !completer.isCompleted) {
|
||||
appLogger.d('CompanionRemote: Race winner: $address');
|
||||
completer.complete(address);
|
||||
}
|
||||
} catch (_) {}
|
||||
},
|
||||
onError: (_) {},
|
||||
onDone: () {},
|
||||
);
|
||||
subs.add(sub);
|
||||
} catch (e) {
|
||||
appLogger.d('CompanionRemote: Race candidate $address failed to start: $e');
|
||||
}
|
||||
}
|
||||
|
||||
if (channels.isEmpty) {
|
||||
throw const RemotePeerError(
|
||||
type: RemotePeerErrorType.connectionFailed,
|
||||
message: 'Failed to connect to any address',
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
final winner = await completer.future.timeout(const Duration(seconds: 10));
|
||||
cleanup();
|
||||
|
||||
// Now set up the proper managed connection on the winning address
|
||||
await joinSession(sessionId, pin, deviceName, platform, winner);
|
||||
return winner;
|
||||
} on TimeoutException {
|
||||
cleanup();
|
||||
throw const RemotePeerError(
|
||||
type: RemotePeerErrorType.timeout,
|
||||
message: 'Timed out connecting to all addresses',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _startPingTimer() {
|
||||
_stopPingTimer();
|
||||
_pingTimer = Timer.periodic(const Duration(seconds: 5), (_) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import '../models/plex_hub.dart';
|
||||
import '../models/plex_library.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
import 'multi_server_manager.dart';
|
||||
import 'plex_auth_service.dart';
|
||||
|
||||
@@ -45,7 +46,7 @@ class DataAggregationService {
|
||||
filteredOnDeck = allOnDeck.where((item) {
|
||||
final librarySectionId = item.librarySectionID;
|
||||
if (librarySectionId == null) return true; // Keep if no section ID
|
||||
final globalKey = '${item.serverId}:$librarySectionId';
|
||||
final globalKey = buildGlobalKey(item.serverId!, librarySectionId.toString());
|
||||
return !hiddenLibraryKeys.contains(globalKey);
|
||||
}).toList();
|
||||
}
|
||||
@@ -118,7 +119,7 @@ class DataAggregationService {
|
||||
// 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';
|
||||
final globalKey = buildGlobalKey(serverId, librarySectionId.toString());
|
||||
return !hiddenLibraryKeys.contains(globalKey);
|
||||
}).toList();
|
||||
|
||||
|
||||
@@ -430,7 +430,7 @@ class DownloadManagerService {
|
||||
bool downloadSubtitles = true,
|
||||
bool downloadArtwork = true,
|
||||
}) async {
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
|
||||
// Check if already downloading or completed
|
||||
final existing = await _database.getDownloadedMedia(globalKey);
|
||||
@@ -1252,12 +1252,13 @@ class DownloadManagerService {
|
||||
|
||||
if (metadata == null) {
|
||||
// Fallback: Try database record
|
||||
final downloadRecord = await _database.getDownloadedMedia('$serverId:$ratingKey');
|
||||
final gk = buildGlobalKey(serverId, ratingKey);
|
||||
final downloadRecord = await _database.getDownloadedMedia(gk);
|
||||
if (downloadRecord?.videoFilePath != null) {
|
||||
await _deleteByFilePath(downloadRecord!);
|
||||
return;
|
||||
}
|
||||
appLogger.w('Cannot delete - no metadata for $serverId:$ratingKey');
|
||||
appLogger.w('Cannot delete - no metadata for $gk');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1433,12 +1434,12 @@ class DownloadManagerService {
|
||||
}) async {
|
||||
for (int i = 0; i < episodes.length; i++) {
|
||||
final episode = episodes[i];
|
||||
final episodeGlobalKey = '$serverId:${episode.ratingKey}';
|
||||
final episodeGlobalKey = buildGlobalKey(serverId, episode.ratingKey);
|
||||
|
||||
// Emit progress update
|
||||
_emitDeletionProgress(
|
||||
DeletionProgress(
|
||||
globalKey: '$serverId:$parentKey',
|
||||
globalKey: buildGlobalKey(serverId, parentKey),
|
||||
itemTitle: parentTitle,
|
||||
currentItem: i + 1,
|
||||
totalItems: episodes.length,
|
||||
@@ -1551,7 +1552,7 @@ class DownloadManagerService {
|
||||
final otherEpisodes = await _database.getEpisodesBySeason(seasonKey);
|
||||
|
||||
// Check if any episodes besides this one
|
||||
return otherEpisodes.any((e) => e.globalKey != '${episode.serverId}:${episode.ratingKey}');
|
||||
return otherEpisodes.any((e) => e.globalKey != episode.globalKey);
|
||||
}
|
||||
|
||||
/// Check if show artwork is in use
|
||||
@@ -1562,7 +1563,7 @@ class DownloadManagerService {
|
||||
final showEpisodes = await _database.getEpisodesByShow(showKey);
|
||||
|
||||
// Check if any episodes belong to this show besides the current item
|
||||
return showEpisodes.any((item) => item.globalKey != '${metadata.serverId}:${metadata.ratingKey}');
|
||||
return showEpisodes.any((item) => item.globalKey != metadata.globalKey);
|
||||
}
|
||||
|
||||
/// Find file with any extension
|
||||
|
||||
@@ -47,7 +47,7 @@ class ExternalPlayerService {
|
||||
final player = settings.getSelectedExternalPlayer();
|
||||
|
||||
// On Android, always use native intent to avoid url_launcher opening in browser
|
||||
if (Platform.isAndroid) {
|
||||
if (Platform.isAndroid && context.mounted) {
|
||||
return _launchAndroidNative(resolvedUrl, player, context);
|
||||
}
|
||||
|
||||
|
||||
@@ -101,7 +101,10 @@ class GamepadService with WindowListener {
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowFocus() => _windowFocused = true;
|
||||
void onWindowFocus() {
|
||||
_windowFocused = true;
|
||||
Gamepad.instance.resume();
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowBlur() {
|
||||
@@ -123,6 +126,9 @@ class GamepadService with WindowListener {
|
||||
_leftStickDown = false;
|
||||
_leftStickLeft = false;
|
||||
_leftStickRight = false;
|
||||
|
||||
// Release native device handles so other apps can use the gamepad.
|
||||
Gamepad.instance.pause();
|
||||
}
|
||||
|
||||
void _handleGamepadEvent(GamepadEvent event) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'plex_client.dart';
|
||||
import '../models/plex_media_info.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_video_playback_data.dart';
|
||||
import '../models/download_models.dart';
|
||||
import '../mpv/mpv.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
@@ -75,10 +76,12 @@ class PlaybackInitializationService {
|
||||
///
|
||||
/// Returns a PlaybackInitializationResult with video URL and available versions
|
||||
/// If [preferOffline] is true and offline content is available, uses local file
|
||||
/// If [playbackData] is provided, skips the network call to fetch it again.
|
||||
Future<PlaybackInitializationResult> getPlaybackData({
|
||||
required PlexMetadata metadata,
|
||||
required int selectedMediaIndex,
|
||||
bool preferOffline = false,
|
||||
PlexVideoPlaybackData? playbackData,
|
||||
}) async {
|
||||
try {
|
||||
// Check for offline content first if preferOffline is enabled
|
||||
@@ -94,16 +97,17 @@ class PlaybackInitializationService {
|
||||
// For offline playback, we still need to fetch media info for subtitles
|
||||
// but use the local file path for video
|
||||
try {
|
||||
final playbackData = await client.getVideoPlaybackData(metadata.ratingKey, mediaIndex: selectedMediaIndex);
|
||||
final data =
|
||||
playbackData ?? await client.getVideoPlaybackData(metadata.ratingKey, mediaIndex: selectedMediaIndex);
|
||||
|
||||
// Build list of external subtitle tracks
|
||||
final externalSubtitles = _buildExternalSubtitles(playbackData.mediaInfo);
|
||||
final externalSubtitles = _buildExternalSubtitles(data.mediaInfo);
|
||||
|
||||
// Return result with local file path
|
||||
return PlaybackInitializationResult(
|
||||
availableVersions: playbackData.availableVersions,
|
||||
availableVersions: data.availableVersions,
|
||||
videoUrl: _formatVideoUrl(offlineVideoPath),
|
||||
mediaInfo: playbackData.mediaInfo,
|
||||
mediaInfo: data.mediaInfo,
|
||||
externalSubtitles: externalSubtitles,
|
||||
isOffline: true,
|
||||
);
|
||||
@@ -120,21 +124,22 @@ class PlaybackInitializationService {
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to network streaming
|
||||
final playbackData = await client.getVideoPlaybackData(metadata.ratingKey, mediaIndex: selectedMediaIndex);
|
||||
// Use pre-parsed data or fall back to network streaming
|
||||
final data =
|
||||
playbackData ?? await client.getVideoPlaybackData(metadata.ratingKey, mediaIndex: selectedMediaIndex);
|
||||
|
||||
if (!playbackData.hasValidVideoUrl) {
|
||||
if (!data.hasValidVideoUrl) {
|
||||
throw PlaybackException(t.messages.fileInfoNotAvailable);
|
||||
}
|
||||
|
||||
// Build list of external subtitle tracks
|
||||
final externalSubtitles = _buildExternalSubtitles(playbackData.mediaInfo);
|
||||
final externalSubtitles = _buildExternalSubtitles(data.mediaInfo);
|
||||
|
||||
// Return result with available versions and video URL
|
||||
return PlaybackInitializationResult(
|
||||
availableVersions: playbackData.availableVersions,
|
||||
videoUrl: playbackData.videoUrl,
|
||||
mediaInfo: playbackData.mediaInfo,
|
||||
availableVersions: data.availableVersions,
|
||||
videoUrl: data.videoUrl,
|
||||
mediaInfo: data.mediaInfo,
|
||||
externalSubtitles: externalSubtitles,
|
||||
isOffline: false,
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:drift/drift.dart';
|
||||
import '../database/app_database.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../utils/plex_cache_parser.dart';
|
||||
import '../utils/global_key_utils.dart';
|
||||
|
||||
/// Key-value cache for Plex API responses using Drift/SQLite.
|
||||
/// Stores raw JSON responses keyed by serverId:endpoint format.
|
||||
@@ -152,7 +153,7 @@ class PlexApiCache {
|
||||
final json = PlexCacheParser.extractFirstMetadata(data);
|
||||
if (json == null) continue;
|
||||
final metadata = PlexMetadata.fromJsonWithImages(json).copyWith(serverId: serverId);
|
||||
result['$serverId:$ratingKey'] = metadata;
|
||||
result[buildGlobalKey(serverId, ratingKey)] = metadata;
|
||||
} catch (_) {
|
||||
// Skip malformed entries
|
||||
}
|
||||
|
||||
@@ -51,7 +51,10 @@ class PlexAuthService {
|
||||
|
||||
static Future<PlexAuthService> create() async {
|
||||
final storage = await StorageService.getInstance();
|
||||
final dio = Dio();
|
||||
final dio = Dio(BaseOptions(
|
||||
connectTimeout: ConnectionTimeouts.plexTvConnect,
|
||||
receiveTimeout: ConnectionTimeouts.plexTvReceive,
|
||||
));
|
||||
|
||||
// Get or create client identifier
|
||||
String? clientIdentifier = storage.getClientIdentifier();
|
||||
|
||||
+85
-165
@@ -460,7 +460,9 @@ class PlexClient {
|
||||
),
|
||||
parseCache: (cachedData) {
|
||||
final metadata = _parseMetadataWithImagesFromCachedResponse(cachedData);
|
||||
return {'metadata': metadata, 'onDeckEpisode': null};
|
||||
final firstMetadata = PlexCacheParser.extractFirstMetadata(cachedData);
|
||||
final playbackData = parseVideoPlaybackDataFromJson(firstMetadata);
|
||||
return {'metadata': metadata, 'onDeckEpisode': null, 'playbackData': playbackData};
|
||||
},
|
||||
parseResponse: (response) {
|
||||
PlexMetadata? metadata;
|
||||
@@ -485,10 +487,13 @@ class PlexClient {
|
||||
}
|
||||
}
|
||||
|
||||
return {'metadata': metadata, 'onDeckEpisode': onDeckEpisode};
|
||||
// Parse playback data from the same response — zero extra network cost
|
||||
final playbackData = parseVideoPlaybackDataFromJson(metadataJson);
|
||||
|
||||
return {'metadata': metadata, 'onDeckEpisode': onDeckEpisode, 'playbackData': playbackData};
|
||||
},
|
||||
) ??
|
||||
{'metadata': null, 'onDeckEpisode': null};
|
||||
{'metadata': null, 'onDeckEpisode': null, 'playbackData': null};
|
||||
}
|
||||
|
||||
/// Get metadata by rating key with images (includes clearLogo)
|
||||
@@ -557,6 +562,27 @@ class PlexClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch data with cache checked first, network only on cache miss.
|
||||
///
|
||||
/// Use this when fresh data is not critical and prior fetches likely
|
||||
/// already populated the cache (e.g. playback after visiting detail screen).
|
||||
Future<T?> _fetchWithCacheFirst<T>({
|
||||
required String cacheKey,
|
||||
required Future<Response> Function() networkCall,
|
||||
required T? Function(dynamic cachedData) parseCache,
|
||||
required T? Function(Response response) parseResponse,
|
||||
bool cacheResponse = true,
|
||||
}) async {
|
||||
final cached = await _cache.get(serverId, cacheKey);
|
||||
if (cached != null) return parseCache(cached);
|
||||
if (_offlineMode) return null;
|
||||
final response = await networkCall();
|
||||
if (cacheResponse && response.data != null) {
|
||||
await _cache.put(serverId, cacheKey, response.data);
|
||||
}
|
||||
return parseResponse(response);
|
||||
}
|
||||
|
||||
/// Get first metadata JSON from response data
|
||||
Map<String, dynamic>? _getFirstMetadataJsonFromData(Map<String, dynamic>? data) =>
|
||||
PlexCacheParser.extractFirstMetadata(data);
|
||||
@@ -651,6 +677,23 @@ class PlexClient {
|
||||
}).toList();
|
||||
}
|
||||
|
||||
/// Parse markers from metadata JSON
|
||||
List<PlexMarker> _parseMarkers(Map<String, dynamic>? metadataJson) {
|
||||
if (metadataJson == null || metadataJson['Marker'] == null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
final markerList = metadataJson['Marker'] as List;
|
||||
return markerList.map((marker) {
|
||||
return PlexMarker(
|
||||
id: marker['id'] as int,
|
||||
type: marker['type'] as String,
|
||||
startTimeOffset: marker['startTimeOffset'] as int,
|
||||
endTimeOffset: marker['endTimeOffset'] as int,
|
||||
);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
/// Set per-media language preferences (audio and subtitle)
|
||||
/// For TV shows, use grandparentRatingKey to set preference for the entire series
|
||||
/// For movies, use the movie's ratingKey
|
||||
@@ -869,186 +912,43 @@ class PlexClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get chapters for a media item
|
||||
Future<List<PlexChapter>> getChapters(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey', queryParameters: {'includeChapters': 1});
|
||||
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
if (metadataJson != null && metadataJson['Chapter'] != null) {
|
||||
final chapterList = metadataJson['Chapter'] as List<dynamic>;
|
||||
return chapterList.map((chapter) {
|
||||
return PlexChapter(
|
||||
id: chapter['id'] as int,
|
||||
index: chapter['index'] as int?,
|
||||
startTimeOffset: chapter['startTimeOffset'] as int?,
|
||||
endTimeOffset: chapter['endTimeOffset'] as int?,
|
||||
title: chapter['tag'] as String?,
|
||||
thumb: chapter['thumb'] as String?,
|
||||
);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
Future<List<PlexMarker>> getMarkers(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey', queryParameters: {'includeMarkers': 1});
|
||||
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
|
||||
if (metadataJson != null && metadataJson['Marker'] != null) {
|
||||
final markerList = metadataJson['Marker'] as List;
|
||||
return markerList.map((marker) {
|
||||
return PlexMarker(
|
||||
id: marker['id'] as int,
|
||||
type: marker['type'] as String,
|
||||
startTimeOffset: marker['startTimeOffset'] as int,
|
||||
endTimeOffset: marker['endTimeOffset'] as int,
|
||||
);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get chapters and markers from cached metadata or fetch if needed
|
||||
/// Uses same cache key as other metadata methods for consistency
|
||||
Future<PlaybackExtras> getPlaybackExtras(String ratingKey) async {
|
||||
// Use same cache key as other metadata methods
|
||||
final cacheKey = '/library/metadata/$ratingKey';
|
||||
|
||||
// If offline mode, return from cache only
|
||||
if (_offlineMode) {
|
||||
final cached = await _cache.get(serverId, cacheKey);
|
||||
if (cached != null) {
|
||||
return _parsePlaybackExtrasFromCachedResponse(cached);
|
||||
}
|
||||
return PlaybackExtras(chapters: [], markers: []);
|
||||
}
|
||||
|
||||
// Online: check cache first (already has chapters/markers from other fetches)
|
||||
appLogger.d('getPlaybackExtras: serverId=$serverId, cacheKey=$cacheKey');
|
||||
final cached = await _cache.get(serverId, cacheKey);
|
||||
if (cached != null) {
|
||||
final chapters = PlexCacheParser.extractChapters(cached);
|
||||
appLogger.d('getPlaybackExtras: cache hit, ${chapters?.length ?? 0} chapters');
|
||||
return _parsePlaybackExtrasFromCachedResponse(cached);
|
||||
}
|
||||
appLogger.d('getPlaybackExtras: cache miss');
|
||||
|
||||
// Not in cache - fetch and cache
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
'/library/metadata/$ratingKey',
|
||||
queryParameters: {'includeChapters': 1, 'includeMarkers': 1},
|
||||
final data = await _fetchWithCacheFirst<Map<String, dynamic>>(
|
||||
cacheKey: '/library/metadata/$ratingKey',
|
||||
networkCall: () =>
|
||||
_dio.get('/library/metadata/$ratingKey', queryParameters: {'includeChapters': 1, 'includeMarkers': 1}),
|
||||
parseCache: (cached) => cached as Map<String, dynamic>?,
|
||||
parseResponse: (response) => response.data as Map<String, dynamic>?,
|
||||
);
|
||||
|
||||
// Cache at base endpoint
|
||||
if (response.data != null) {
|
||||
await _cache.put(serverId, cacheKey, response.data);
|
||||
}
|
||||
|
||||
return _parsePlaybackExtrasFromResponse(response);
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
return _parsePlaybackExtrasFromMetadataJson(metadataJson);
|
||||
} catch (e) {
|
||||
// Network failed
|
||||
appLogger.w('Network request failed for playback extras', error: e);
|
||||
appLogger.w('Failed to get playback extras', error: e);
|
||||
return PlaybackExtras(chapters: [], markers: []);
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse PlaybackExtras from API response
|
||||
PlaybackExtras _parsePlaybackExtrasFromResponse(Response response) {
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
return _parsePlaybackExtrasFromMetadataJson(metadataJson);
|
||||
}
|
||||
|
||||
/// Parse PlaybackExtras from cached response
|
||||
PlaybackExtras _parsePlaybackExtrasFromCachedResponse(Map<String, dynamic> cached) {
|
||||
final metadataJson = PlexCacheParser.extractFirstMetadata(cached);
|
||||
return _parsePlaybackExtrasFromMetadataJson(metadataJson);
|
||||
}
|
||||
|
||||
/// Parse PlaybackExtras from metadata JSON
|
||||
PlaybackExtras _parsePlaybackExtrasFromMetadataJson(Map<String, dynamic>? metadataJson) {
|
||||
final chapters = <PlexChapter>[];
|
||||
final markers = <PlexMarker>[];
|
||||
|
||||
if (metadataJson != null) {
|
||||
// Parse chapters
|
||||
if (metadataJson['Chapter'] != null) {
|
||||
final chapterList = metadataJson['Chapter'] as List<dynamic>;
|
||||
for (var chapter in chapterList) {
|
||||
chapters.add(
|
||||
PlexChapter(
|
||||
id: chapter['id'] as int,
|
||||
index: chapter['index'] as int?,
|
||||
startTimeOffset: chapter['startTimeOffset'] as int?,
|
||||
endTimeOffset: chapter['endTimeOffset'] as int?,
|
||||
title: chapter['tag'] as String?,
|
||||
thumb: chapter['thumb'] as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse markers
|
||||
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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PlaybackExtras.withChapterFallback(chapters: chapters, markers: markers);
|
||||
return PlaybackExtras.withChapterFallback(
|
||||
chapters: _parseChapters(metadataJson),
|
||||
markers: _parseMarkers(metadataJson),
|
||||
);
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
Map<String, dynamic>? data;
|
||||
try {
|
||||
data = await _fetchWithCacheFallback<Map<String, dynamic>>(
|
||||
cacheKey: '/library/metadata/$ratingKey',
|
||||
networkCall: () =>
|
||||
_dio.get('/library/metadata/$ratingKey', queryParameters: {'includeMarkers': 1, 'includeChapters': 1}),
|
||||
parseCache: (cached) => cached as Map<String, dynamic>?,
|
||||
parseResponse: (response) => response.data as Map<String, dynamic>?,
|
||||
);
|
||||
} catch (_) {
|
||||
// Gracefully degrade: return empty playback data on total failure
|
||||
}
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
|
||||
/// Parse video playback data from raw metadata JSON (no network call).
|
||||
/// Used by [getVideoPlaybackData] and [getMetadataWithImagesAndOnDeck] to
|
||||
/// avoid redundant fetches when the response is already available.
|
||||
PlexVideoPlaybackData parseVideoPlaybackDataFromJson(Map<String, dynamic>? metadataJson, {int mediaIndex = 0}) {
|
||||
String? videoUrl;
|
||||
PlexMediaInfo? mediaInfo;
|
||||
List<PlexMediaVersion> availableVersions = [];
|
||||
List<PlexMarker> markers = [];
|
||||
final markers = _parseMarkers(metadataJson);
|
||||
|
||||
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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
@@ -1095,11 +995,31 @@ class PlexClient {
|
||||
);
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
Map<String, dynamic>? data;
|
||||
try {
|
||||
data = await _fetchWithCacheFirst<Map<String, dynamic>>(
|
||||
cacheKey: '/library/metadata/$ratingKey',
|
||||
networkCall: () =>
|
||||
_dio.get('/library/metadata/$ratingKey', queryParameters: {'includeMarkers': 1, 'includeChapters': 1}),
|
||||
parseCache: (cached) => cached as Map<String, dynamic>?,
|
||||
parseResponse: (response) => response.data as Map<String, dynamic>?,
|
||||
);
|
||||
} catch (_) {
|
||||
// Gracefully degrade: return empty playback data on total failure
|
||||
}
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
return parseVideoPlaybackDataFromJson(metadataJson, mediaIndex: mediaIndex);
|
||||
}
|
||||
|
||||
/// Get file information for a media item
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<PlexFileInfo?> getFileInfo(String ratingKey) async {
|
||||
try {
|
||||
final data = await _fetchWithCacheFallback<Map<String, dynamic>>(
|
||||
final data = await _fetchWithCacheFirst<Map<String, dynamic>>(
|
||||
cacheKey: '/library/metadata/$ratingKey',
|
||||
networkCall: () =>
|
||||
_dio.get('/library/metadata/$ratingKey', queryParameters: {'includeMarkers': 1, 'includeChapters': 1}),
|
||||
|
||||
@@ -430,7 +430,7 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
final jsonString = prefs.getString(_keyKeyboardShortcuts);
|
||||
if (jsonString == null) return getDefaultKeyboardShortcuts();
|
||||
|
||||
final decoded = _decodeJsonStringToMap(jsonString);
|
||||
final decoded = decodeJsonStringToMap(jsonString);
|
||||
if (decoded.isEmpty) return getDefaultKeyboardShortcuts();
|
||||
|
||||
final shortcuts = decoded.map((key, value) => MapEntry(key, value.toString()));
|
||||
@@ -494,6 +494,7 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to parse keyboard hotkeys', error: e);
|
||||
return getDefaultKeyboardHotkeys();
|
||||
}
|
||||
}
|
||||
@@ -804,19 +805,10 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
final jsonString = prefs.getString(_keyMediaVersionPreferences);
|
||||
if (jsonString == null) return {};
|
||||
|
||||
final decoded = _decodeJsonStringToMap(jsonString);
|
||||
final decoded = decodeJsonStringToMap(jsonString);
|
||||
return decoded.map((key, value) => MapEntry(key, value as int));
|
||||
}
|
||||
|
||||
/// Helper to decode JSON string to Map with error handling
|
||||
Map<String, dynamic> _decodeJsonStringToMap(String jsonString) {
|
||||
try {
|
||||
return json.decode(jsonString) as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
// App Locale
|
||||
Future<void> setAppLocale(AppLocale locale) async {
|
||||
await prefs.setString(_keyAppLocale, locale.languageCode);
|
||||
@@ -1080,7 +1072,8 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
if (jsonString == null) return KnownPlayers.systemDefault;
|
||||
try {
|
||||
return ExternalPlayer.fromJsonString(jsonString);
|
||||
} catch (_) {
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to parse external player', error: e);
|
||||
return KnownPlayers.systemDefault;
|
||||
}
|
||||
}
|
||||
@@ -1096,7 +1089,8 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
try {
|
||||
final List<dynamic> decoded = json.decode(jsonString);
|
||||
return decoded.map((e) => ExternalPlayer.fromJson(e as Map<String, dynamic>)).toList();
|
||||
} catch (_) {
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to parse custom external players', error: e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,12 +12,18 @@ class SleepTimerService extends ChangeNotifier {
|
||||
Timer? _timer;
|
||||
DateTime? _endTime;
|
||||
Duration? _duration;
|
||||
Duration? _originalDuration;
|
||||
VoidCallback? _onTimerComplete;
|
||||
bool _needsRestart = false;
|
||||
final StreamController<void> _completedController = StreamController<void>.broadcast();
|
||||
final StreamController<void> _promptController = StreamController<void>.broadcast();
|
||||
|
||||
/// Emits when the sleep timer completes (not when cancelled)
|
||||
Stream<void> get onCompleted => _completedController.stream;
|
||||
|
||||
/// Emits when the timer fires and wants to show a "still watching?" prompt
|
||||
Stream<void> get onPrompt => _promptController.stream;
|
||||
|
||||
/// Whether a timer is currently active
|
||||
bool get isActive => _timer != null && _timer!.isActive;
|
||||
|
||||
@@ -27,6 +33,9 @@ class SleepTimerService extends ChangeNotifier {
|
||||
/// The original duration of the timer
|
||||
Duration? get duration => _duration;
|
||||
|
||||
/// The user-selected duration (unmodified by extendTimer)
|
||||
Duration? get originalDuration => _originalDuration;
|
||||
|
||||
/// Remaining time on the timer
|
||||
Duration? get remainingTime {
|
||||
if (_endTime == null) return null;
|
||||
@@ -41,6 +50,7 @@ class SleepTimerService extends ChangeNotifier {
|
||||
// Cancel any existing timer
|
||||
cancelTimer();
|
||||
|
||||
_originalDuration = duration;
|
||||
_duration = duration;
|
||||
_endTime = DateTime.now().add(duration);
|
||||
_onTimerComplete = onComplete;
|
||||
@@ -52,9 +62,9 @@ class SleepTimerService extends ChangeNotifier {
|
||||
final remaining = remainingTime;
|
||||
|
||||
if (remaining == null || remaining.inSeconds <= 0) {
|
||||
appLogger.d('Sleep timer completed');
|
||||
_executeCallback();
|
||||
cancelTimer();
|
||||
appLogger.d('Sleep timer completed - showing prompt');
|
||||
_stopTimerOnly();
|
||||
_promptController.add(null);
|
||||
} else {
|
||||
// Notify listeners to update UI
|
||||
notifyListeners();
|
||||
@@ -64,19 +74,51 @@ class SleepTimerService extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Cancel the active timer
|
||||
/// Cancel the active timer (user-initiated, clears everything)
|
||||
void cancelTimer() {
|
||||
if (_timer != null) {
|
||||
if (_timer != null || _originalDuration != null) {
|
||||
appLogger.d('Sleep timer cancelled');
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
_endTime = null;
|
||||
_duration = null;
|
||||
_originalDuration = null;
|
||||
_onTimerComplete = null;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// Restart the timer with the original user-selected duration
|
||||
void restartTimer() {
|
||||
if (_originalDuration != null && _onTimerComplete != null) {
|
||||
final duration = _originalDuration!;
|
||||
final callback = _onTimerComplete!;
|
||||
startTimer(duration, callback);
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute the completion callback directly (fallback path)
|
||||
void executeCompletion() {
|
||||
_executeCallback();
|
||||
}
|
||||
|
||||
/// Mark that the timer should restart when a new playback session begins
|
||||
/// (e.g. user exited the player and started something new)
|
||||
void markNeedsRestart() {
|
||||
if (isActive || _originalDuration != null) {
|
||||
_needsRestart = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Restart the timer if it was marked for restart (new playback session).
|
||||
/// [onComplete] provides the new callback for the fresh session.
|
||||
void restartIfNeeded(VoidCallback onComplete) {
|
||||
if (_needsRestart && _originalDuration != null) {
|
||||
_needsRestart = false;
|
||||
startTimer(_originalDuration!, onComplete);
|
||||
}
|
||||
}
|
||||
|
||||
/// Extend the current timer by the specified duration
|
||||
void extendTimer(Duration additionalTime) {
|
||||
if (_endTime != null) {
|
||||
@@ -87,6 +129,16 @@ class SleepTimerService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop the periodic timer but preserve _originalDuration and _onTimerComplete
|
||||
/// for the prompt flow (restart/completion)
|
||||
void _stopTimerOnly() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
_endTime = null;
|
||||
_duration = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _executeCallback() {
|
||||
if (_onTimerComplete != null) {
|
||||
try {
|
||||
@@ -102,6 +154,7 @@ class SleepTimerService extends ChangeNotifier {
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
_completedController.close();
|
||||
_promptController.close();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ class StorageService extends BaseSharedPreferencesService {
|
||||
prefs.getString(_keyLibraryFilters);
|
||||
if (jsonString == null) return {};
|
||||
|
||||
final decoded = _decodeJsonStringToMap(jsonString);
|
||||
final decoded = decodeJsonStringToMap(jsonString);
|
||||
return decoded.map((key, value) => MapEntry(key, value.toString()));
|
||||
}
|
||||
|
||||
@@ -308,24 +308,7 @@ class StorageService extends BaseSharedPreferencesService {
|
||||
final jsonString = prefs.getString(key);
|
||||
if (jsonString == null) return null;
|
||||
|
||||
return _decodeJsonStringToMap(jsonString, legacyStringOk: legacyStringOk);
|
||||
}
|
||||
|
||||
/// Helper to decode JSON string to Map with error handling
|
||||
///
|
||||
/// [jsonString] - The JSON string to decode
|
||||
/// [legacyStringOk] - If true, returns {'key': value, 'descending': false}
|
||||
/// when value is a plain string (for legacy library sort)
|
||||
Map<String, dynamic> _decodeJsonStringToMap(String jsonString, {bool legacyStringOk = false}) {
|
||||
try {
|
||||
return json.decode(jsonString) as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
if (legacyStringOk) {
|
||||
// Legacy support: if it's just a string, return it as the key
|
||||
return {'key': jsonString, 'descending': false};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
return decodeJsonStringToMap(jsonString, legacyStringOk: legacyStringOk);
|
||||
}
|
||||
|
||||
/// Remove all keys matching a prefix
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:auto_updater/auto_updater.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
@@ -5,9 +8,14 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Service to check for new versions on GitHub
|
||||
/// Only enabled when ENABLE_UPDATE_CHECK build flag is set
|
||||
///
|
||||
/// On macOS (non-Homebrew) and installed Windows: delegates to Sparkle/WinSparkle
|
||||
/// via auto_updater for native update dialogs and in-app installs.
|
||||
/// On all other platforms: falls back to GitHub API check + browser link dialog.
|
||||
class UpdateService {
|
||||
static final Logger _logger = Logger();
|
||||
static const String _githubRepo = 'edde746/plezy';
|
||||
static const String _feedUrl = 'https://github.com/edde746/plezy/releases/latest/download/appcast.xml';
|
||||
|
||||
// SharedPreferences keys
|
||||
static const String _keySkippedVersion = 'update_skipped_version';
|
||||
@@ -16,11 +24,70 @@ class UpdateService {
|
||||
// Check cooldown: 6 hours
|
||||
static const Duration _checkCooldown = Duration(hours: 6);
|
||||
|
||||
static bool _nativeUpdaterInitialized = false;
|
||||
|
||||
/// Check if update checking is enabled via build flag
|
||||
static bool get isUpdateCheckEnabled {
|
||||
return const bool.fromEnvironment('ENABLE_UPDATE_CHECK', defaultValue: false);
|
||||
}
|
||||
|
||||
/// Whether the native auto_updater (Sparkle/WinSparkle) should be used.
|
||||
/// True on macOS (non-Homebrew) and installed Windows (has uninstaller).
|
||||
static bool get useNativeUpdater {
|
||||
if (!isUpdateCheckEnabled) return false;
|
||||
if (Platform.isMacOS) return !_isHomebrewInstall();
|
||||
if (Platform.isWindows) return _isInstalledApp();
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Initialize the native auto_updater (Sparkle/WinSparkle).
|
||||
/// Call once at startup if [useNativeUpdater] is true.
|
||||
static Future<void> initNativeUpdater() async {
|
||||
if (_nativeUpdaterInitialized) return;
|
||||
_nativeUpdaterInitialized = true;
|
||||
|
||||
try {
|
||||
await autoUpdater.setFeedURL(_feedUrl);
|
||||
// 6 hours in seconds
|
||||
await autoUpdater.setScheduledCheckInterval(_checkCooldown.inSeconds);
|
||||
} catch (e) {
|
||||
_logger.e('Failed to initialize native auto updater: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Trigger a background update check via Sparkle/WinSparkle.
|
||||
/// Only shows UI if an update is found.
|
||||
static Future<void> checkForUpdatesNative({bool inBackground = true}) async {
|
||||
if (!_nativeUpdaterInitialized) await initNativeUpdater();
|
||||
try {
|
||||
await autoUpdater.checkForUpdates(inBackground: inBackground);
|
||||
} catch (e) {
|
||||
_logger.e('Native update check failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the macOS app was installed via Homebrew.
|
||||
/// Homebrew casks live under /opt/homebrew/Caskroom/ or /usr/local/Caskroom/.
|
||||
static bool _isHomebrewInstall() {
|
||||
try {
|
||||
final execPath = Platform.resolvedExecutable;
|
||||
return execPath.contains('/Caskroom/') || execPath.contains('/homebrew/');
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the Windows app is an installed copy (not portable).
|
||||
/// The Inno Setup installer places unins000.exe next to the executable.
|
||||
static bool _isInstalledApp() {
|
||||
try {
|
||||
final exeDir = File(Platform.resolvedExecutable).parent.path;
|
||||
return File('$exeDir\\unins000.exe').existsSync();
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip a specific version
|
||||
static Future<void> skipVersion(String version) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
@@ -17,4 +17,10 @@ class ConnectionTimeouts {
|
||||
|
||||
/// Dio receive timeout for streaming/large responses from a Plex server.
|
||||
static const receive = Duration(seconds: 120);
|
||||
|
||||
/// Dio connect timeout for plex.tv / clients.plex.tv API requests.
|
||||
static const plexTvConnect = Duration(seconds: 5);
|
||||
|
||||
/// Dio receive timeout for plex.tv / clients.plex.tv API responses.
|
||||
static const plexTvReceive = Duration(seconds: 10);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import '../models/plex_metadata.dart';
|
||||
import 'app_logger.dart';
|
||||
import 'base_notifier.dart';
|
||||
import 'global_key_utils.dart';
|
||||
import 'hierarchical_event_mixin.dart';
|
||||
|
||||
/// Event representing a media item deletion with parent chain for hierarchical invalidation
|
||||
@@ -42,7 +43,7 @@ class DeletionEvent with HierarchicalEventMixin {
|
||||
required this.mediaType,
|
||||
this.leafCount = 1,
|
||||
this.isDownloadOnly = false,
|
||||
}) : globalKey = '$serverId:$ratingKey';
|
||||
}) : globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
|
||||
@override
|
||||
String toString() => 'DeletionEvent(deleted: $globalKey, type: $mediaType, parents: $parentChain)';
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
/// Builds a globalKey string from [serverId] and [ratingKey].
|
||||
String buildGlobalKey(String serverId, String ratingKey) => '$serverId:$ratingKey';
|
||||
|
||||
/// Parses a globalKey string (format: "serverId:ratingKey") into its components.
|
||||
///
|
||||
/// Returns `null` if the key does not contain a colon separator.
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'global_key_utils.dart';
|
||||
|
||||
/// Mixin providing hierarchical event matching methods.
|
||||
///
|
||||
/// Events that represent changes to media items often need to check if they
|
||||
@@ -24,7 +26,7 @@ mixin HierarchicalEventMixin {
|
||||
|
||||
/// Check if this event affects a specific globalKey.
|
||||
bool affectsGlobalKey(String globalKey) =>
|
||||
this.globalKey == globalKey || parentChain.any((pk) => '$serverId:$pk' == globalKey);
|
||||
this.globalKey == globalKey || parentChain.any((pk) => buildGlobalKey(serverId, pk) == globalKey);
|
||||
|
||||
/// Check if this event affects any item in a collection.
|
||||
bool affectsAnyOf(Iterable<String> ratingKeys) => ratingKeys.any(affectsItem);
|
||||
|
||||
@@ -84,7 +84,7 @@ class LanguageCodes {
|
||||
|
||||
// Locale code (e.g. "en-US", "zh-TW")
|
||||
final parts = code.split('-');
|
||||
final langName = getLanguageName(parts[0]) ?? parts[0];
|
||||
final langName = getLanguageName(parts.first) ?? parts.first;
|
||||
final region = parts.length > 1 ? _regionNames[parts[1]] : null;
|
||||
return region != null ? '$langName ($region)' : langName;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:provider/provider.dart';
|
||||
|
||||
import '../mpv/mpv.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_video_playback_data.dart';
|
||||
import '../providers/download_provider.dart';
|
||||
import '../screens/video_player_screen.dart';
|
||||
import '../services/external_player_service.dart';
|
||||
@@ -40,12 +41,16 @@ Future<bool?> navigateToVideoPlayer(
|
||||
int? selectedMediaIndex,
|
||||
bool usePushReplacement = false,
|
||||
bool isOffline = false,
|
||||
PlexVideoPlaybackData? playbackData,
|
||||
}) async {
|
||||
// Extract navigator before any async operations
|
||||
// Extract context-dependent values before any async operations
|
||||
final navigator = Navigator.of(context);
|
||||
final downloadProvider = context.read<DownloadProvider>();
|
||||
final client = isOffline ? null : context.getClientForMetadata(metadata);
|
||||
|
||||
// Load saved media version preference if not explicitly provided
|
||||
int mediaIndex = selectedMediaIndex ?? 0;
|
||||
var effectivePlaybackData = playbackData;
|
||||
if (selectedMediaIndex == null) {
|
||||
try {
|
||||
final settingsService = await SettingsService.getInstance();
|
||||
@@ -53,6 +58,11 @@ Future<bool?> navigateToVideoPlayer(
|
||||
final savedPreference = settingsService.getMediaVersionPreference(seriesKey);
|
||||
if (savedPreference != null) {
|
||||
mediaIndex = savedPreference;
|
||||
// Pre-parsed playbackData was built with mediaIndex=0; invalidate if
|
||||
// the resolved index differs so the player re-fetches with the correct one
|
||||
if (savedPreference != 0) {
|
||||
effectivePlaybackData = null;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore errors loading preference, use default
|
||||
@@ -67,19 +77,17 @@ Future<bool?> navigateToVideoPlayer(
|
||||
|
||||
if (isOffline) {
|
||||
// Offline mode: resolve local file path for the external player
|
||||
final downloadProvider = context.read<DownloadProvider>();
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
final videoPath = await downloadProvider.getVideoFilePath(globalKey);
|
||||
if (videoPath != null) {
|
||||
if (videoPath != null && context.mounted) {
|
||||
final videoUrl = videoPath.contains('://') ? videoPath : 'file://$videoPath';
|
||||
launched = await ExternalPlayerService.launch(context: context, videoUrl: videoUrl);
|
||||
}
|
||||
} else {
|
||||
final client = context.getClientForMetadata(metadata);
|
||||
} else if (context.mounted) {
|
||||
launched = await ExternalPlayerService.launch(
|
||||
context: context,
|
||||
metadata: metadata,
|
||||
client: client,
|
||||
client: client!,
|
||||
mediaIndex: mediaIndex,
|
||||
);
|
||||
}
|
||||
@@ -109,6 +117,7 @@ Future<bool?> navigateToVideoPlayer(
|
||||
preferredSubtitleTrack: preferredSubtitleTrack,
|
||||
selectedMediaIndex: mediaIndex,
|
||||
isOffline: isOffline,
|
||||
playbackData: effectivePlaybackData,
|
||||
),
|
||||
transitionDuration: Duration.zero,
|
||||
reverseTransitionDuration: Duration.zero,
|
||||
@@ -140,6 +149,7 @@ Future<bool?> navigateToVideoPlayerWithRefresh(
|
||||
SubtitleTrack? preferredSubtitleTrack,
|
||||
int? selectedMediaIndex,
|
||||
bool usePushReplacement = false,
|
||||
PlexVideoPlaybackData? playbackData,
|
||||
}) async {
|
||||
final result = await navigateToVideoPlayer(
|
||||
context,
|
||||
@@ -149,6 +159,7 @@ Future<bool?> navigateToVideoPlayerWithRefresh(
|
||||
preferredSubtitleTrack: preferredSubtitleTrack,
|
||||
selectedMediaIndex: selectedMediaIndex,
|
||||
usePushReplacement: usePushReplacement,
|
||||
playbackData: playbackData,
|
||||
);
|
||||
|
||||
appLogger.d('Returned from playback, refreshing metadata');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import '../models/plex_metadata.dart';
|
||||
import 'app_logger.dart';
|
||||
import 'base_notifier.dart';
|
||||
import 'global_key_utils.dart';
|
||||
import 'hierarchical_event_mixin.dart';
|
||||
|
||||
/// Types of watch state changes
|
||||
@@ -47,7 +48,7 @@ class WatchStateEvent with HierarchicalEventMixin {
|
||||
required this.mediaType,
|
||||
this.viewOffset,
|
||||
this.isNowWatched,
|
||||
}) : globalKey = '$serverId:$ratingKey';
|
||||
}) : globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
|
||||
@override
|
||||
String toString() => 'WatchStateEvent($changeType, $globalKey, parents: $parentChain)';
|
||||
|
||||
@@ -129,7 +129,7 @@ class _ArtworkPickerDialogState extends State<ArtworkPickerDialog> {
|
||||
height: 400,
|
||||
child: _isLoading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _artworkList == null || _artworkList!.isEmpty
|
||||
: (_artworkList == null || _artworkList!.isEmpty)
|
||||
? Center(child: Text(t.metadataEdit.noArtworkAvailable))
|
||||
: _buildGrid(),
|
||||
),
|
||||
@@ -193,10 +193,10 @@ class _ArtworkPickerDialogState extends State<ArtworkPickerDialog> {
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(8)),
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(8)),
|
||||
child: PlexOptimizedImage(
|
||||
client: widget.client,
|
||||
imagePath: thumbUrl,
|
||||
|
||||
@@ -99,14 +99,7 @@ class BottomSheetHeader extends StatelessWidget {
|
||||
child: IconButton(
|
||||
focusNode: closeFocusNode,
|
||||
icon: AppIcon(Symbols.close_rounded, fill: 1, color: iconColor),
|
||||
onPressed: onClose ?? () {
|
||||
final sheetController = OverlaySheetController.maybeOf(context);
|
||||
if (sheetController != null) {
|
||||
sheetController.close();
|
||||
} else {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
},
|
||||
onPressed: onClose ?? () => OverlaySheetController.closeAdaptive(context),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:qr_flutter/qr_flutter.dart';
|
||||
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../../providers/companion_remote_provider.dart';
|
||||
import '../../focus/focusable_button.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
|
||||
class RemoteSessionDialog extends StatefulWidget {
|
||||
@@ -25,7 +26,7 @@ class RemoteSessionDialog extends StatefulWidget {
|
||||
class _RemoteSessionDialogState extends State<RemoteSessionDialog> {
|
||||
bool _isCreatingSession = false;
|
||||
String? _errorMessage;
|
||||
String? _hostAddress; // Format: "ip:port"
|
||||
List<String>? _hostAddresses; // Each format: "ip:port"
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -38,7 +39,7 @@ class _RemoteSessionDialogState extends State<RemoteSessionDialog> {
|
||||
setState(() {
|
||||
_isCreatingSession = true;
|
||||
_errorMessage = null;
|
||||
_hostAddress = null;
|
||||
_hostAddresses = null;
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -48,7 +49,7 @@ class _RemoteSessionDialogState extends State<RemoteSessionDialog> {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isCreatingSession = false;
|
||||
_hostAddress = result.address;
|
||||
_hostAddresses = result.addresses;
|
||||
});
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to create companion remote session', error: e);
|
||||
@@ -110,7 +111,7 @@ class _RemoteSessionDialogState extends State<RemoteSessionDialog> {
|
||||
}
|
||||
|
||||
final session = provider.session;
|
||||
if (session == null || _hostAddress == null) {
|
||||
if (session == null || _hostAddresses == null || _hostAddresses!.isEmpty) {
|
||||
return AlertDialog(
|
||||
title: Text(t.common.error),
|
||||
content: Text(t.companionRemote.session.noSession),
|
||||
@@ -118,13 +119,12 @@ class _RemoteSessionDialogState extends State<RemoteSessionDialog> {
|
||||
);
|
||||
}
|
||||
|
||||
// Parse IP and port from hostAddress
|
||||
final addressParts = _hostAddress!.split(':');
|
||||
final ip = addressParts.first;
|
||||
final port = addressParts[1];
|
||||
// Extract port from first address (all share the same port)
|
||||
final port = _hostAddresses!.first.split(':').last;
|
||||
final ips = _hostAddresses!.map((a) => a.split(':').first).join(',');
|
||||
|
||||
// URL-wrapped QR format so external scanners open a real webpage
|
||||
final qrData = 'https://plezy.app/scan#$ip|$port|${session.sessionId}|${session.pin}';
|
||||
// URL-wrapped QR format: comma-separated IPs for multi-NIC support
|
||||
final qrData = 'https://plezy.app/scan#$ips|$port|${session.sessionId}|${session.pin}';
|
||||
|
||||
return Dialog(
|
||||
child: ConstrainedBox(
|
||||
@@ -193,13 +193,17 @@ class _RemoteSessionDialogState extends State<RemoteSessionDialog> {
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_buildCodeCard(
|
||||
context,
|
||||
t.companionRemote.session.hostAddress,
|
||||
_hostAddress!,
|
||||
onCopy: () => _copyToClipboard(_hostAddress!, t.companionRemote.session.hostAddress),
|
||||
..._hostAddresses!.map(
|
||||
(addr) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: _buildCodeCard(
|
||||
context,
|
||||
t.companionRemote.session.hostAddress,
|
||||
addr,
|
||||
onCopy: () => _copyToClipboard(addr, t.companionRemote.session.hostAddress),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildCodeCard(
|
||||
context,
|
||||
t.companionRemote.session.sessionId,
|
||||
@@ -250,19 +254,30 @@ class _RemoteSessionDialogState extends State<RemoteSessionDialog> {
|
||||
label: Text(t.companionRemote.session.newSession),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
TextButton(
|
||||
FocusableButton(
|
||||
onPressed: () async {
|
||||
await provider.leaveSession();
|
||||
if (context.mounted) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
},
|
||||
child: Text(t.common.disconnect),
|
||||
child: TextButton(
|
||||
onPressed: () async {
|
||||
await provider.leaveSession();
|
||||
if (context.mounted) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
},
|
||||
child: Text(t.common.disconnect),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton(
|
||||
FocusableButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(t.companionRemote.session.minimize),
|
||||
child: FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(t.companionRemote.session.minimize),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -37,8 +37,6 @@ class _FileInfoBottomSheetState extends State<FileInfoBottomSheet> {
|
||||
BottomSheetHeader(
|
||||
title: t.fileInfo.title,
|
||||
icon: Symbols.info_rounded,
|
||||
iconColor: Colors.white,
|
||||
titleColor: Colors.white,
|
||||
closeFocusNode: _initialFocusNode,
|
||||
),
|
||||
// Content
|
||||
@@ -50,7 +48,7 @@ class _FileInfoBottomSheetState extends State<FileInfoBottomSheet> {
|
||||
if (widget.title.isNotEmpty) ...[
|
||||
Text(
|
||||
widget.title,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
@@ -115,7 +113,7 @@ class _FileInfoBottomSheetState extends State<FileInfoBottomSheet> {
|
||||
Widget _buildSectionHeader(String title) {
|
||||
return Text(
|
||||
title,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -127,12 +125,12 @@ class _FileInfoBottomSheetState extends State<FileInfoBottomSheet> {
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 140,
|
||||
child: Text(label, style: TextStyle(color: Colors.grey[400], fontSize: 14)),
|
||||
child: Text(label, style: TextStyle(color: Theme.of(context).textTheme.bodySmall?.color, fontSize: 14)),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
value,
|
||||
style: TextStyle(color: Colors.white, fontSize: 14, fontFamily: isMonospace ? 'monospace' : null),
|
||||
style: TextStyle(fontSize: 14, fontFamily: isMonospace ? 'monospace' : null),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -72,9 +72,22 @@ class FocusBuilders {
|
||||
double borderRadius = FocusTheme.defaultBorderRadius,
|
||||
required Widget child,
|
||||
}) {
|
||||
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
|
||||
// In touch mode, no item ever shows focus effects — skip animated wrappers
|
||||
// entirely. This saves ~2 element levels per card on ARM32 Android phones.
|
||||
if (!isKeyboardMode) {
|
||||
final gestureWidget = (onTap != null || onLongPress != null)
|
||||
? GestureDetector(onTap: onTap, onLongPress: onLongPress, child: child)
|
||||
: child;
|
||||
if (focusNode != null && onKeyEvent != null) {
|
||||
return Focus(focusNode: focusNode, onKeyEvent: onKeyEvent, child: gestureWidget);
|
||||
}
|
||||
return gestureWidget;
|
||||
}
|
||||
|
||||
final duration = FocusTheme.getAnimationDuration(context);
|
||||
// Only show focus effects during keyboard/d-pad navigation
|
||||
final showFocus = isFocused && InputModeTracker.isKeyboardMode(context);
|
||||
final showFocus = isFocused && isKeyboardMode;
|
||||
|
||||
final focusedWidget = AnimatedScale(
|
||||
scale: showFocus ? FocusTheme.focusScale : 1.0,
|
||||
|
||||
@@ -116,7 +116,7 @@ class _FocusableListTileState extends State<FocusableListTile> {
|
||||
/// A RadioListTile that accepts a FocusNode for keyboard/controller navigation.
|
||||
///
|
||||
/// Uses Flutter's native RadioListTile focus support - no custom styling wrapper.
|
||||
/// Can be used standalone with [groupValue]/[onChanged] or inside a [RadioGroup].
|
||||
/// Requires a [RadioGroup] ancestor to manage selection state.
|
||||
class FocusableRadioListTile<T> extends StatelessWidget {
|
||||
/// The primary content of the list tile.
|
||||
final Widget? title;
|
||||
@@ -130,14 +130,6 @@ class FocusableRadioListTile<T> extends StatelessWidget {
|
||||
/// The value represented by this radio button.
|
||||
final T value;
|
||||
|
||||
/// The currently selected value for the group.
|
||||
/// When provided, the widget works without a [RadioGroup] ancestor.
|
||||
final T? groupValue;
|
||||
|
||||
/// Called when this radio button is selected.
|
||||
/// When provided, the widget works without a [RadioGroup] ancestor.
|
||||
final ValueChanged<T?>? onChanged;
|
||||
|
||||
/// Whether this radio button is part of a vertically dense list.
|
||||
final bool dense;
|
||||
|
||||
@@ -156,8 +148,6 @@ class FocusableRadioListTile<T> extends StatelessWidget {
|
||||
this.subtitle,
|
||||
this.secondary,
|
||||
required this.value,
|
||||
this.groupValue,
|
||||
this.onChanged,
|
||||
this.dense = false,
|
||||
this.focusNode,
|
||||
this.autofocus = false,
|
||||
@@ -171,8 +161,6 @@ class FocusableRadioListTile<T> extends StatelessWidget {
|
||||
subtitle: subtitle,
|
||||
secondary: secondary,
|
||||
value: value,
|
||||
groupValue: groupValue,
|
||||
onChanged: onChanged,
|
||||
dense: dense,
|
||||
focusNode: focusNode,
|
||||
autofocus: autofocus,
|
||||
|
||||
@@ -377,10 +377,11 @@ class HubSectionState extends State<HubSection> {
|
||||
Focus(
|
||||
focusNode: _hubFocusNode,
|
||||
onKeyEvent: _handleKeyEvent,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Responsive base card width for posters (2:3 aspect ratio)
|
||||
final screenWidth = constraints.maxWidth;
|
||||
child: Builder(
|
||||
builder: (context) {
|
||||
// Use MediaQuery instead of LayoutBuilder to save 1 element level.
|
||||
// HubSection is always full-width inside CustomScrollView.
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
final settings = context.watch<SettingsProvider>();
|
||||
final densityScale = switch (settings.libraryDensity) {
|
||||
LibraryDensity.compact => 0.8,
|
||||
@@ -444,7 +445,8 @@ class HubSectionState extends State<HubSection> {
|
||||
if (index == widget.hub.items.length) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 2),
|
||||
child: _LockedHubItemWrapper(
|
||||
child: FocusBuilders.buildLockedFocusWrapper(
|
||||
context: context,
|
||||
isFocused: isItemFocused,
|
||||
onTap: () {
|
||||
_onItemTapped(index);
|
||||
@@ -481,7 +483,8 @@ class HubSectionState extends State<HubSection> {
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 2),
|
||||
child: _LockedHubItemWrapper(
|
||||
child: FocusBuilders.buildLockedFocusWrapper(
|
||||
context: context,
|
||||
isFocused: isItemFocused,
|
||||
onTap: () => _onItemTapped(index),
|
||||
onLongPress: () => _mediaCardKeys[index]?.currentState?.showContextMenu(),
|
||||
@@ -526,24 +529,3 @@ class HubSectionState extends State<HubSection> {
|
||||
_hubFocusNode.requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper that provides visual focus decoration without using Flutter's focus system.
|
||||
class _LockedHubItemWrapper extends StatelessWidget {
|
||||
final bool isFocused;
|
||||
final Widget child;
|
||||
final VoidCallback? onTap;
|
||||
final VoidCallback? onLongPress;
|
||||
|
||||
const _LockedHubItemWrapper({required this.isFocused, required this.child, this.onTap, this.onLongPress});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FocusBuilders.buildLockedFocusWrapper(
|
||||
context: context,
|
||||
isFocused: isFocused,
|
||||
onTap: onTap,
|
||||
onLongPress: onLongPress,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+183
-198
@@ -53,9 +53,14 @@ class MediaCard extends StatefulWidget {
|
||||
|
||||
class MediaCardState extends State<MediaCard> {
|
||||
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
|
||||
Offset? _tapPosition;
|
||||
|
||||
void _storeTapPosition(TapDownDetails details) {
|
||||
_tapPosition = details.globalPosition;
|
||||
}
|
||||
|
||||
void _showContextMenu() {
|
||||
_contextMenuKey.currentState?.showContextMenu(context);
|
||||
_contextMenuKey.currentState?.showContextMenu(context, position: _tapPosition);
|
||||
}
|
||||
|
||||
/// Public method to trigger tap action (for keyboard/gamepad SELECT)
|
||||
@@ -65,7 +70,7 @@ class MediaCardState extends State<MediaCard> {
|
||||
|
||||
/// Public method to show context menu (for keyboard/gamepad context menu key)
|
||||
void showContextMenu() {
|
||||
_showContextMenu();
|
||||
_contextMenuKey.currentState?.showContextMenu(context);
|
||||
}
|
||||
|
||||
String _buildSemanticLabel() {
|
||||
@@ -149,7 +154,7 @@ class MediaCardState extends State<MediaCard> {
|
||||
if (metadata.serverId == null) return null;
|
||||
|
||||
final downloadProvider = context.read<DownloadProvider>();
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
|
||||
// Get artwork reference and resolve to local path using hash (includes serverId)
|
||||
final artwork = downloadProvider.getArtworkPaths(globalKey);
|
||||
@@ -165,28 +170,22 @@ class MediaCardState extends State<MediaCard> {
|
||||
final localPosterPath = _getLocalPosterPath(context);
|
||||
|
||||
final cardWidget = viewMode == ViewMode.grid
|
||||
? _MediaCardGrid(
|
||||
item: widget.item,
|
||||
width: widget.width,
|
||||
height: widget.height,
|
||||
semanticLabel: semanticLabel,
|
||||
onTap: () => _handleTap(context),
|
||||
onLongPress: _showContextMenu,
|
||||
isOffline: widget.isOffline,
|
||||
localPosterPath: localPosterPath,
|
||||
mixedHubContext: widget.mixedHubContext,
|
||||
)
|
||||
? _buildGridCard(context, semanticLabel, localPosterPath)
|
||||
: _MediaCardList(
|
||||
item: widget.item,
|
||||
semanticLabel: semanticLabel,
|
||||
onTap: () => _handleTap(context),
|
||||
onTapDown: _storeTapPosition,
|
||||
onLongPress: _showContextMenu,
|
||||
onSecondaryTapDown: _storeTapPosition,
|
||||
onSecondaryTap: _showContextMenu,
|
||||
density: settingsProvider.libraryDensity,
|
||||
isOffline: widget.isOffline,
|
||||
localPosterPath: localPosterPath,
|
||||
);
|
||||
|
||||
// Use context menu for both PlexMetadata and PlexPlaylist items
|
||||
// MediaContextMenu as a non-widget helper — only wrap with its key for
|
||||
// programmatic context menu access; gesture callbacks are on InkWell directly.
|
||||
return MediaContextMenu(
|
||||
key: _contextMenuKey,
|
||||
item: widget.item,
|
||||
@@ -199,96 +198,91 @@ class MediaCardState extends State<MediaCard> {
|
||||
child: cardWidget,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Grid layout for media cards
|
||||
class _MediaCardGrid extends StatelessWidget {
|
||||
final dynamic item; // Can be PlexMetadata or PlexPlaylist
|
||||
final double? width;
|
||||
final double? height;
|
||||
final String semanticLabel;
|
||||
final VoidCallback onTap;
|
||||
final VoidCallback onLongPress;
|
||||
final bool isOffline;
|
||||
final String? localPosterPath;
|
||||
final bool mixedHubContext;
|
||||
/// Grid layout — inlined from former _MediaCardGrid, _PosterOverlay, and
|
||||
/// flattened Column. Semantics removed (InkWell provides button semantics).
|
||||
Widget _buildGridCard(BuildContext context, String semanticLabel, String? localPosterPath) {
|
||||
final item = widget.item;
|
||||
// Compute actual poster dimensions from card dimensions
|
||||
final posterWidth = widget.width != null ? widget.width! - 16 : null; // 8px padding each side
|
||||
final posterHeight = widget.height;
|
||||
|
||||
const _MediaCardGrid({
|
||||
required this.item,
|
||||
this.width,
|
||||
this.height,
|
||||
required this.semanticLabel,
|
||||
required this.onTap,
|
||||
required this.onLongPress,
|
||||
this.isOffline = false,
|
||||
this.localPosterPath,
|
||||
this.mixedHubContext = false,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
width: width,
|
||||
child: Semantics(
|
||||
label: semanticLabel,
|
||||
button: true,
|
||||
child: InkWell(
|
||||
canRequestFocus: false, // Keyboard handled by FocusableMediaCard
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Poster
|
||||
if (height != null)
|
||||
SizedBox(width: double.infinity, height: height, child: _buildPosterWithOverlay(context))
|
||||
else
|
||||
Expanded(child: _buildPosterWithOverlay(context)),
|
||||
const SizedBox(height: 4),
|
||||
// Text content
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item is PlexPlaylist ? (item as PlexPlaylist).title : (item as PlexMetadata).displayTitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13, height: 1.1),
|
||||
),
|
||||
if (item is PlexPlaylist)
|
||||
_MediaCardHelpers.buildPlaylistMeta(context, item as PlexPlaylist)
|
||||
else if (item is PlexMetadata)
|
||||
_MediaCardHelpers.buildMetadataSubtitle(context, item as PlexMetadata),
|
||||
],
|
||||
width: widget.width,
|
||||
child: InkWell(
|
||||
canRequestFocus: false,
|
||||
onTap: () => _handleTap(context),
|
||||
onTapDown: _storeTapPosition,
|
||||
onLongPress: _showContextMenu,
|
||||
onSecondaryTapDown: _storeTapPosition,
|
||||
onSecondaryTap: _showContextMenu,
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Poster with overlay
|
||||
if (posterHeight != null)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: posterHeight,
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: _buildPosterImage(
|
||||
context,
|
||||
item,
|
||||
isOffline: widget.isOffline,
|
||||
localPosterPath: localPosterPath,
|
||||
mixedHubContext: widget.mixedHubContext,
|
||||
knownWidth: posterWidth,
|
||||
knownHeight: posterHeight,
|
||||
),
|
||||
),
|
||||
// Inlined _PosterOverlay
|
||||
if (item is PlexMetadata) _MediaCardHelpers.buildWatchProgress(context, item),
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
Expanded(
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: _buildPosterImage(
|
||||
context,
|
||||
item,
|
||||
isOffline: widget.isOffline,
|
||||
localPosterPath: localPosterPath,
|
||||
mixedHubContext: widget.mixedHubContext,
|
||||
),
|
||||
),
|
||||
if (item is PlexMetadata) _MediaCardHelpers.buildWatchProgress(context, item),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// Title (flattened — no inner Column)
|
||||
Text(
|
||||
item is PlexPlaylist ? item.title : (item as PlexMetadata).displayTitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13, height: 1.1),
|
||||
),
|
||||
// Subtitle
|
||||
if (item is PlexPlaylist)
|
||||
_MediaCardHelpers.buildPlaylistMeta(context, item)
|
||||
else if (item is PlexMetadata)
|
||||
_MediaCardHelpers.buildMetadataSubtitle(context, item),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPosterWithOverlay(BuildContext context) {
|
||||
return Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: _buildPosterImage(
|
||||
context,
|
||||
item,
|
||||
isOffline: isOffline,
|
||||
localPosterPath: localPosterPath,
|
||||
mixedHubContext: mixedHubContext,
|
||||
),
|
||||
),
|
||||
_PosterOverlay(item: item),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// List layout for media cards
|
||||
@@ -297,6 +291,9 @@ class _MediaCardList extends StatelessWidget {
|
||||
final String semanticLabel;
|
||||
final VoidCallback onTap;
|
||||
final VoidCallback onLongPress;
|
||||
final void Function(TapDownDetails)? onTapDown;
|
||||
final VoidCallback? onSecondaryTap;
|
||||
final void Function(TapDownDetails)? onSecondaryTapDown;
|
||||
final LibraryDensity density;
|
||||
final bool isOffline;
|
||||
final String? localPosterPath;
|
||||
@@ -306,6 +303,9 @@ class _MediaCardList extends StatelessWidget {
|
||||
required this.semanticLabel,
|
||||
required this.onTap,
|
||||
required this.onLongPress,
|
||||
this.onTapDown,
|
||||
this.onSecondaryTap,
|
||||
this.onSecondaryTapDown,
|
||||
required this.density,
|
||||
this.isOffline = false,
|
||||
this.localPosterPath,
|
||||
@@ -488,92 +488,92 @@ class _MediaCardList extends StatelessWidget {
|
||||
final metadataLine = _buildMetadataLine();
|
||||
final subtitle = _buildSubtitleText();
|
||||
|
||||
return Semantics(
|
||||
label: semanticLabel,
|
||||
button: true,
|
||||
child: InkWell(
|
||||
canRequestFocus: false, // Keyboard handled by FocusableMediaCard
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Poster (responsive size based on density)
|
||||
SizedBox(
|
||||
width: _posterWidth(context),
|
||||
height: _posterHeight(context),
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: _buildPosterImage(context, item, isOffline: isOffline, localPosterPath: localPosterPath),
|
||||
),
|
||||
_PosterOverlay(item: item),
|
||||
],
|
||||
),
|
||||
return InkWell(
|
||||
canRequestFocus: false, // Keyboard handled by FocusableMediaCard
|
||||
onTap: onTap,
|
||||
onTapDown: onTapDown,
|
||||
onLongPress: onLongPress,
|
||||
onSecondaryTapDown: onSecondaryTapDown,
|
||||
onSecondaryTap: onSecondaryTap,
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Poster (responsive size based on density)
|
||||
SizedBox(
|
||||
width: _posterWidth(context),
|
||||
height: _posterHeight(context),
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: _buildPosterImage(context, item, isOffline: isOffline, localPosterPath: localPosterPath),
|
||||
),
|
||||
if (item is PlexMetadata) _MediaCardHelpers.buildWatchProgress(context, item as PlexMetadata),
|
||||
],
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// Metadata
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: [
|
||||
// Title
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// Metadata
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: [
|
||||
// Title
|
||||
Text(
|
||||
item.displayTitle,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontWeight: FontWeight.w600, fontSize: _titleFontSize, height: 1.2),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// Metadata info line (rating, duration, score, studio)
|
||||
if (metadataLine.isNotEmpty) ...[
|
||||
Text(
|
||||
item.displayTitle,
|
||||
maxLines: 2,
|
||||
metadataLine,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontWeight: FontWeight.w600, fontSize: _titleFontSize, height: 1.2),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted.withValues(alpha: 0.9),
|
||||
fontSize: _metadataFontSize,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
],
|
||||
// Subtitle (S#E# or year/parent title)
|
||||
if (subtitle != null) ...[
|
||||
Text(
|
||||
subtitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted.withValues(alpha: 0.85),
|
||||
fontSize: _subtitleFontSize,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// Metadata info line (rating, duration, score, studio)
|
||||
if (metadataLine.isNotEmpty) ...[
|
||||
Text(
|
||||
metadataLine,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted.withValues(alpha: 0.9),
|
||||
fontSize: _metadataFontSize,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
],
|
||||
// Subtitle (S#E# or year/parent title)
|
||||
if (subtitle != null) ...[
|
||||
Text(
|
||||
subtitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted.withValues(alpha: 0.85),
|
||||
fontSize: _subtitleFontSize,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
],
|
||||
// Summary
|
||||
if (item.summary != null) ...[
|
||||
Text(
|
||||
item.summary!,
|
||||
maxLines: _summaryMaxLines,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted.withValues(alpha: 0.7),
|
||||
fontSize: _summaryFontSize,
|
||||
height: 1.3,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
// Summary
|
||||
if (item.summary != null) ...[
|
||||
Text(
|
||||
item.summary!,
|
||||
maxLines: _summaryMaxLines,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted.withValues(alpha: 0.7),
|
||||
fontSize: _summaryFontSize,
|
||||
height: 1.3,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -586,6 +586,8 @@ Widget _buildPosterImage(
|
||||
bool isOffline = false,
|
||||
String? localPosterPath,
|
||||
bool mixedHubContext = false,
|
||||
double? knownWidth,
|
||||
double? knownHeight,
|
||||
}) {
|
||||
String? posterUrl;
|
||||
IconData fallbackIcon = Symbols.movie_rounded;
|
||||
@@ -597,8 +599,8 @@ Widget _buildPosterImage(
|
||||
return PlexOptimizedImage.playlist(
|
||||
client: isOffline ? null : context.getClientWithFallback(item.serverId),
|
||||
imagePath: posterUrl,
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
width: knownWidth ?? double.infinity,
|
||||
height: knownHeight ?? double.infinity,
|
||||
fit: BoxFit.cover,
|
||||
localFilePath: localPosterPath,
|
||||
);
|
||||
@@ -611,8 +613,8 @@ Widget _buildPosterImage(
|
||||
return PlexOptimizedImage.thumb(
|
||||
client: isOffline ? null : context.getClientWithFallback(item.serverId),
|
||||
imagePath: posterUrl,
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
width: knownWidth ?? double.infinity,
|
||||
height: knownHeight ?? double.infinity,
|
||||
fit: BoxFit.cover,
|
||||
localFilePath: localPosterPath,
|
||||
);
|
||||
@@ -621,8 +623,8 @@ Widget _buildPosterImage(
|
||||
return PlexOptimizedImage.poster(
|
||||
client: isOffline ? null : context.getClientWithFallback(item.serverId),
|
||||
imagePath: posterUrl,
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
width: knownWidth ?? double.infinity,
|
||||
height: knownHeight ?? double.infinity,
|
||||
fit: BoxFit.cover,
|
||||
localFilePath: localPosterPath,
|
||||
);
|
||||
@@ -633,23 +635,6 @@ Widget _buildPosterImage(
|
||||
);
|
||||
}
|
||||
|
||||
/// Overlay widget for poster showing watched indicator and progress bar
|
||||
class _PosterOverlay extends StatelessWidget {
|
||||
final dynamic item; // Can be PlexMetadata or PlexPlaylist
|
||||
|
||||
const _PosterOverlay({required this.item});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Only show overlays for PlexMetadata items
|
||||
if (item is! PlexMetadata) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return _MediaCardHelpers.buildWatchProgress(context, item as PlexMetadata);
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper methods for building media card metadata and subtitles
|
||||
class _MediaCardHelpers {
|
||||
/// Builds playlist metadata (item count)
|
||||
|
||||
@@ -72,10 +72,6 @@ class MediaContextMenu extends StatefulWidget {
|
||||
class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
Offset? _tapPosition;
|
||||
|
||||
void _storeTapPosition(TapDownDetails details) {
|
||||
_tapPosition = details.globalPosition;
|
||||
}
|
||||
|
||||
bool _openedFromKeyboard = false;
|
||||
bool _isContextMenuOpen = false;
|
||||
|
||||
@@ -110,11 +106,6 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
/// Get the correct PlexClient for this item's server
|
||||
PlexClient _getClientForItem() => context.getClientWithFallback(_itemServerId);
|
||||
|
||||
void _handleTap() {
|
||||
if (_isContextMenuOpen) return;
|
||||
widget.onTap?.call();
|
||||
}
|
||||
|
||||
void _showContextMenu(BuildContext context) async {
|
||||
if (_isContextMenuOpen) return;
|
||||
_isContextMenuOpen = true;
|
||||
@@ -195,9 +186,7 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
mediaType == PlexMediaType.show ||
|
||||
mediaType == PlexMediaType.season ||
|
||||
mediaType == PlexMediaType.episode) {
|
||||
menuActions.add(
|
||||
_MenuAction(value: 'rate', icon: Symbols.star_rounded, label: t.mediaMenu.rate),
|
||||
);
|
||||
menuActions.add(_MenuAction(value: 'rate', icon: Symbols.star_rounded, label: t.mediaMenu.rate));
|
||||
}
|
||||
|
||||
// Edit Metadata (for movies, shows, seasons, and episodes)
|
||||
@@ -263,7 +252,7 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
mediaType == PlexMediaType.show ||
|
||||
mediaType == PlexMediaType.season) {
|
||||
final downloadProvider = Provider.of<DownloadProvider>(context, listen: false);
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
final isDownloaded = downloadProvider.isDownloaded(globalKey);
|
||||
|
||||
if (isDownloaded) {
|
||||
@@ -309,26 +298,14 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
_openedFromKeyboard = false;
|
||||
|
||||
if (useBottomSheet) {
|
||||
// Show overlay sheet if available, otherwise fall back to modal bottom sheet
|
||||
final overlayController = OverlaySheetController.maybeOf(context);
|
||||
if (overlayController != null) {
|
||||
selected = await overlayController.show<String>(
|
||||
builder: (context) => _FocusableContextMenuSheet(
|
||||
title: widget.item.title,
|
||||
actions: menuActions,
|
||||
focusFirstItem: openedFromKeyboard,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
selected = await showModalBottomSheet<String>(
|
||||
context: context,
|
||||
builder: (context) => _FocusableContextMenuSheet(
|
||||
title: widget.item.title,
|
||||
actions: menuActions,
|
||||
focusFirstItem: openedFromKeyboard,
|
||||
),
|
||||
);
|
||||
}
|
||||
selected = await OverlaySheetController.showAdaptive<String>(
|
||||
context,
|
||||
builder: (context) => _FocusableContextMenuSheet(
|
||||
title: widget.item.title,
|
||||
actions: menuActions,
|
||||
focusFirstItem: openedFromKeyboard,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Show custom focusable popup menu on larger screens
|
||||
// Use stored tap position or fallback to widget position
|
||||
@@ -580,19 +557,12 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
|
||||
if (fileInfo != null && context.mounted) {
|
||||
// Show file info bottom sheet
|
||||
final overlayController = OverlaySheetController.maybeOf(context);
|
||||
if (overlayController != null) {
|
||||
await overlayController.show(
|
||||
builder: (context) => FileInfoBottomSheet(fileInfo: fileInfo, title: metadata.title),
|
||||
);
|
||||
} else {
|
||||
await showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => FileInfoBottomSheet(fileInfo: fileInfo, title: metadata.title),
|
||||
);
|
||||
}
|
||||
await OverlaySheetController.showAdaptive(
|
||||
context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => FileInfoBottomSheet(fileInfo: fileInfo, title: metadata.title),
|
||||
);
|
||||
} else if (context.mounted) {
|
||||
showErrorSnackBar(context, t.messages.fileInfoNotAvailable);
|
||||
}
|
||||
@@ -634,55 +604,29 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
|
||||
String? selected;
|
||||
if (useBottomSheet) {
|
||||
final overlayController = OverlaySheetController.maybeOf(context);
|
||||
if (overlayController != null) {
|
||||
selected = await overlayController.push<String>(
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(t.common.addTo, style: Theme.of(context).textTheme.titleMedium),
|
||||
),
|
||||
...submenuActions.map((action) {
|
||||
return ListTile(
|
||||
leading: AppIcon(action.icon, fill: 1),
|
||||
title: Text(action.label),
|
||||
onTap: () => overlayController.pop(action.value),
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
selected = await OverlaySheetController.pushAdaptive<String>(
|
||||
context,
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(t.common.addTo, style: Theme.of(context).textTheme.titleMedium),
|
||||
),
|
||||
...submenuActions.map((action) {
|
||||
return ListTile(
|
||||
leading: AppIcon(action.icon, fill: 1),
|
||||
title: Text(action.label),
|
||||
onTap: () => OverlaySheetController.popAdaptive(context, action.value),
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
selected = await showModalBottomSheet<String>(
|
||||
context: context,
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(t.common.addTo, style: Theme.of(context).textTheme.titleMedium),
|
||||
),
|
||||
...submenuActions.map((action) {
|
||||
return ListTile(
|
||||
leading: AppIcon(action.icon, fill: 1),
|
||||
title: Text(action.label),
|
||||
onTap: () => Navigator.pop(context, action.value),
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
),
|
||||
);
|
||||
} else {
|
||||
selected = await showMenu<String>(
|
||||
context: context,
|
||||
@@ -969,7 +913,9 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
|
||||
/// Handle remove from collection action
|
||||
Future<void> _showRatingSheet(BuildContext context, PlexMetadata metadata, PlexClient client) async {
|
||||
final currentStarValue = (metadata.userRating != null && metadata.userRating! > 0) ? metadata.userRating! / 2.0 : 0.0;
|
||||
final currentStarValue = (metadata.userRating != null && metadata.userRating! > 0)
|
||||
? metadata.userRating! / 2.0
|
||||
: 0.0;
|
||||
await showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => RatingBottomSheet(
|
||||
@@ -1108,10 +1054,10 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
|
||||
// Check if the item is downloaded and use local file path if available
|
||||
final downloadProvider = Provider.of<DownloadProvider>(context, listen: false);
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
if (downloadProvider.isDownloaded(globalKey)) {
|
||||
final videoPath = await downloadProvider.getVideoFilePath(globalKey);
|
||||
if (videoPath != null) {
|
||||
if (videoPath != null && context.mounted) {
|
||||
final videoUrl = videoPath.contains('://') ? videoPath : 'file://$videoPath';
|
||||
await ExternalPlayerService.launch(context: context, videoUrl: videoUrl);
|
||||
return;
|
||||
@@ -1119,6 +1065,7 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
}
|
||||
|
||||
final client = _getClientForItem();
|
||||
if (!context.mounted) return;
|
||||
await ExternalPlayerService.launch(context: context, metadata: metadata, client: client);
|
||||
}
|
||||
|
||||
@@ -1151,7 +1098,7 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
Future<void> _handleDeleteDownload(BuildContext context) async {
|
||||
final downloadProvider = Provider.of<DownloadProvider>(context, listen: false);
|
||||
final metadata = widget.item as PlexMetadata;
|
||||
final globalKey = '${metadata.serverId}:${metadata.ratingKey}';
|
||||
final globalKey = metadata.globalKey;
|
||||
|
||||
// Show confirmation dialog
|
||||
final confirmed = await showDeleteConfirmation(
|
||||
@@ -1221,14 +1168,10 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: _handleTap,
|
||||
onTapDown: _storeTapPosition,
|
||||
onLongPress: () => _showContextMenu(context),
|
||||
onSecondaryTapDown: _storeTapPosition,
|
||||
onSecondaryTap: () => _showContextMenu(context),
|
||||
child: widget.child,
|
||||
);
|
||||
// GestureDetector wrapping removed — gesture callbacks are now on InkWell
|
||||
// directly in the card widgets, saving 1 element level. The context menu
|
||||
// is still accessible programmatically via showContextMenu().
|
||||
return widget.child;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1279,10 +1222,7 @@ class _PlaylistSelectionDialog extends StatelessWidget {
|
||||
FocusableButton(
|
||||
autofocus: true,
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(t.common.cancel),
|
||||
),
|
||||
child: TextButton(onPressed: () => Navigator.pop(context), child: Text(t.common.cancel)),
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -1328,10 +1268,7 @@ class _CollectionSelectionDialog extends StatelessWidget {
|
||||
FocusableButton(
|
||||
autofocus: true,
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(t.common.cancel),
|
||||
),
|
||||
child: TextButton(onPressed: () => Navigator.pop(context), child: Text(t.common.cancel)),
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -1367,48 +1304,39 @@ class _FocusableContextMenuSheetState extends State<_FocusableContextMenuSheet>
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
widget.title,
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
widget.title,
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
...widget.actions.asMap().entries.map((entry) {
|
||||
final index = entry.key;
|
||||
final action = entry.value;
|
||||
return FocusableListTile(
|
||||
focusNode: index == 0 ? _initialFocusNode : null,
|
||||
leading: AppIcon(action.icon, fill: 1),
|
||||
title: Text(action.label),
|
||||
onTap: () => OverlaySheetController.closeAdaptive(context, action.value),
|
||||
hoverColor: action.hoverColor,
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
...widget.actions.asMap().entries.map((entry) {
|
||||
final index = entry.key;
|
||||
final action = entry.value;
|
||||
return FocusableListTile(
|
||||
focusNode: index == 0 ? _initialFocusNode : null,
|
||||
leading: AppIcon(action.icon, fill: 1),
|
||||
title: Text(action.label),
|
||||
onTap: () {
|
||||
final controller = OverlaySheetController.maybeOf(context);
|
||||
if (controller != null) {
|
||||
controller.close(action.value);
|
||||
} else {
|
||||
Navigator.pop(context, action.value);
|
||||
}
|
||||
},
|
||||
hoverColor: action.hoverColor,
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +87,73 @@ class OverlaySheetController {
|
||||
void refocus() {
|
||||
_state._refocus();
|
||||
}
|
||||
|
||||
/// Show a sheet using the overlay system if available, otherwise fall back
|
||||
/// to [showModalBottomSheet]. Returns the result from the sheet.
|
||||
static Future<T?> showAdaptive<T>(
|
||||
BuildContext context, {
|
||||
required WidgetBuilder builder,
|
||||
BoxConstraints? constraints,
|
||||
Color? backgroundColor,
|
||||
bool barrierDismissible = true,
|
||||
bool isScrollControlled = false,
|
||||
FocusNode? initialFocusNode,
|
||||
}) {
|
||||
final controller = maybeOf(context);
|
||||
if (controller != null) {
|
||||
return controller.show<T>(
|
||||
builder: builder,
|
||||
constraints: constraints,
|
||||
backgroundColor: backgroundColor,
|
||||
barrierDismissible: barrierDismissible,
|
||||
initialFocusNode: initialFocusNode,
|
||||
);
|
||||
}
|
||||
return showModalBottomSheet<T>(
|
||||
context: context,
|
||||
builder: builder,
|
||||
constraints: constraints,
|
||||
backgroundColor: backgroundColor ?? Theme.of(context).colorScheme.surface,
|
||||
barrierColor: Colors.black54,
|
||||
isScrollControlled: isScrollControlled,
|
||||
);
|
||||
}
|
||||
|
||||
/// Push a sub-page using the overlay system if available, otherwise fall
|
||||
/// back to [showModalBottomSheet]. Returns the result from the page.
|
||||
static Future<T?> pushAdaptive<T>(
|
||||
BuildContext context, {
|
||||
required WidgetBuilder builder,
|
||||
FocusNode? initialFocusNode,
|
||||
}) {
|
||||
final controller = maybeOf(context);
|
||||
if (controller != null) {
|
||||
return controller.push<T>(builder: builder, initialFocusNode: initialFocusNode);
|
||||
}
|
||||
return showModalBottomSheet<T>(context: context, builder: builder);
|
||||
}
|
||||
|
||||
/// Close the sheet entirely. Uses overlay controller if available,
|
||||
/// otherwise pops the route.
|
||||
static void closeAdaptive(BuildContext context, [dynamic result]) {
|
||||
final controller = maybeOf(context);
|
||||
if (controller != null) {
|
||||
controller.close(result);
|
||||
} else {
|
||||
Navigator.pop(context, result);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pop one level (sub-page or close if last page). Uses overlay controller
|
||||
/// if available, otherwise pops the route.
|
||||
static void popAdaptive(BuildContext context, [dynamic result]) {
|
||||
final controller = maybeOf(context);
|
||||
if (controller != null) {
|
||||
controller.pop(result);
|
||||
} else {
|
||||
Navigator.pop(context, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Host widget for the overlay-based bottom sheet system.
|
||||
@@ -120,7 +187,7 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
|
||||
bool _isClosing = false;
|
||||
bool _barrierDismissible = true;
|
||||
BoxConstraints? _constraints;
|
||||
Color _backgroundColor = Colors.grey[900]!;
|
||||
Color? _explicitBackgroundColor;
|
||||
|
||||
// Drag-to-dismiss state
|
||||
double _dragOffset = 0;
|
||||
@@ -182,7 +249,7 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
|
||||
_isClosing = false;
|
||||
_barrierDismissible = barrierDismissible;
|
||||
_constraints = constraints;
|
||||
if (backgroundColor != null) _backgroundColor = backgroundColor;
|
||||
_explicitBackgroundColor = backgroundColor;
|
||||
_dragOffset = 0;
|
||||
_isDragging = false;
|
||||
});
|
||||
@@ -325,7 +392,7 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
|
||||
}
|
||||
}
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
KeyEventResult _handleKeyEvent(FocusNode _, KeyEvent event) {
|
||||
// Suppress stale select key-ups
|
||||
if (SelectKeyUpSuppressor.consumeIfSuppressed(event)) {
|
||||
return KeyEventResult.handled;
|
||||
@@ -354,13 +421,14 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
|
||||
// No PopScope here — the parent screen's PopScope should check
|
||||
// OverlaySheetController.isOpen and delegate to us. This avoids
|
||||
// the double-callback problem with nested PopScopes in one route.
|
||||
|
||||
return _OverlaySheetScope(
|
||||
controller: _controller,
|
||||
child: Stack(
|
||||
children: [
|
||||
widget.child,
|
||||
// Barrier + sheet only when open
|
||||
if (_isOpen) ...[
|
||||
// Barrier
|
||||
AnimatedBuilder(
|
||||
animation: _barrierAnimation,
|
||||
builder: (context, child) {
|
||||
@@ -370,7 +438,6 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
|
||||
);
|
||||
},
|
||||
),
|
||||
// Sheet
|
||||
_buildSheet(context),
|
||||
],
|
||||
],
|
||||
@@ -384,11 +451,7 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
|
||||
|
||||
final effectiveConstraints =
|
||||
_constraints ??
|
||||
BoxConstraints(
|
||||
maxWidth: isDesktop ? 700 : double.infinity,
|
||||
maxHeight: isDesktop ? 400 : size.height * 0.75,
|
||||
minHeight: isDesktop ? 300 : size.height * 0.5,
|
||||
);
|
||||
BoxConstraints(maxWidth: isDesktop ? 700 : double.infinity, maxHeight: isDesktop ? 400 : size.height * 0.75);
|
||||
|
||||
Widget sheet = FocusScope(
|
||||
node: _sheetFocusScopeNode,
|
||||
@@ -403,7 +466,7 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
|
||||
child: Transform.translate(
|
||||
offset: Offset(0, _dragOffset.clamp(0, double.infinity)),
|
||||
child: Material(
|
||||
color: _backgroundColor,
|
||||
color: _explicitBackgroundColor ?? Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: SafeArea(
|
||||
|
||||
@@ -334,19 +334,23 @@ class PlexOptimizedImage extends StatelessWidget {
|
||||
// Generate cache key if not provided
|
||||
final effectiveCacheKey = cacheKey ?? _generateCacheKey(imageUrl, memWidth, memHeight);
|
||||
|
||||
return CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
return Image(
|
||||
image: CachedNetworkImageProvider(
|
||||
imageUrl,
|
||||
cacheKey: effectiveCacheKey,
|
||||
headers: const {'User-Agent': 'Plezy'},
|
||||
maxHeight: memHeight,
|
||||
),
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
filterQuality: filterQuality,
|
||||
alignment: alignment,
|
||||
fadeInDuration: fadeInDuration,
|
||||
memCacheHeight: memHeight,
|
||||
cacheKey: effectiveCacheKey,
|
||||
placeholder: placeholder != null ? placeholder! : (context, url) => _buildPlaceholder(context),
|
||||
errorWidget: errorWidget != null ? errorWidget! : (context, url, error) => _buildErrorWidget(context, error),
|
||||
httpHeaders: {'User-Agent': 'Plezy Flutter Client'},
|
||||
errorBuilder: (context, error, stackTrace) => _buildErrorWidget(context, error),
|
||||
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
|
||||
if (wasSynchronouslyLoaded || frame != null) return child;
|
||||
return _buildPlaceholder(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ class RatingBottomSheet extends StatefulWidget {
|
||||
State<RatingBottomSheet> createState() => _RatingBottomSheetState();
|
||||
}
|
||||
|
||||
String formatRating(double value) =>
|
||||
value == value.truncateToDouble() ? value.toInt().toString() : value.toStringAsFixed(1);
|
||||
|
||||
class _RatingBottomSheetState extends State<RatingBottomSheet> {
|
||||
late double _selectedRating;
|
||||
late final FocusNode _starsFocusNode;
|
||||
@@ -52,13 +55,13 @@ class _RatingBottomSheetState extends State<RatingBottomSheet> {
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(2)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
_selectedRating > 0
|
||||
? '${_selectedRating == _selectedRating.truncateToDouble() ? _selectedRating.toInt().toString() : _selectedRating.toStringAsFixed(1)} / 5'
|
||||
? '${formatRating(_selectedRating)} / 5'
|
||||
: t.mediaMenu.rate,
|
||||
style: theme.textTheme.titleMedium,
|
||||
),
|
||||
@@ -80,7 +83,7 @@ class _RatingBottomSheetState extends State<RatingBottomSheet> {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(12)),
|
||||
color: hasFocus
|
||||
? theme.colorScheme.primary.withValues(alpha: 0.12)
|
||||
: null,
|
||||
|
||||
@@ -279,7 +279,7 @@ class SideNavigationRailState extends State<SideNavigationRail> {
|
||||
}
|
||||
|
||||
/// Handle D-pad UP/DOWN by explicitly moving focus to the next/previous item.
|
||||
KeyEventResult _handleVerticalNavigation(FocusNode node, KeyEvent event, List<String> focusOrder) {
|
||||
KeyEventResult _handleVerticalNavigation(FocusNode _, KeyEvent event, List<String> focusOrder) {
|
||||
if (event is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
|
||||
final isDown = event.logicalKey == LogicalKeyboardKey.arrowDown;
|
||||
|
||||
@@ -270,7 +270,6 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
|
||||
leading: true,
|
||||
trailing: true,
|
||||
);
|
||||
_loadPlaybackExtras();
|
||||
_loadSeekTimes();
|
||||
_startHideTimer();
|
||||
_initKeyboardService();
|
||||
@@ -286,16 +285,19 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
|
||||
_initAlwaysOnTopState();
|
||||
}
|
||||
|
||||
// Focus play/pause button on first frame if in keyboard mode
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_focusPlayPauseIfKeyboardMode();
|
||||
});
|
||||
// Register global key handler for focus-independent shortcuts (desktop only)
|
||||
HardwareKeyboard.instance.addHandler(_handleGlobalKeyEvent);
|
||||
// Listen for first frame to start auto-hide timer
|
||||
widget.hasFirstFrame?.addListener(_onFirstFrameReady);
|
||||
// Listen for external requests to show controls (e.g. screen-level focus recovery)
|
||||
widget.controlsVisible?.addListener(_onControlsVisibleExternal);
|
||||
|
||||
// Defer context-dependent initialization to after first build
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
_loadPlaybackExtras();
|
||||
_focusPlayPauseIfKeyboardMode();
|
||||
});
|
||||
}
|
||||
|
||||
/// Called when hasFirstFrame changes - start auto-hide timer when first frame is ready
|
||||
@@ -634,7 +636,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
|
||||
|
||||
/// Controls hide delay: 5s on mobile/TV/keyboard-nav, 3s on desktop with mouse.
|
||||
Duration get _hideDelay {
|
||||
final isMobile = PlatformDetector.isMobile(context) && !PlatformDetector.isTV();
|
||||
final isMobile = (Platform.isIOS || Platform.isAndroid) && !PlatformDetector.isTV();
|
||||
if (isMobile || PlatformDetector.isTV() || _videoPlayerNavigationEnabled) {
|
||||
return const Duration(seconds: 5);
|
||||
}
|
||||
|
||||
@@ -46,12 +46,7 @@ class SleepTimerDurationList extends StatelessWidget {
|
||||
// Pause playback when timer completes
|
||||
player.pause();
|
||||
});
|
||||
final sheetController = OverlaySheetController.maybeOf(context);
|
||||
if (sheetController != null) {
|
||||
sheetController.close();
|
||||
} else {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
OverlaySheetController.closeAdaptive(context);
|
||||
|
||||
// Show confirmation snackbar
|
||||
showSuccessSnackBar(context, t.messages.sleepTimerSet(label: label));
|
||||
|
||||
+106
-39
@@ -3,7 +3,6 @@
|
||||
#include <flutter_linux/flutter_linux.h>
|
||||
#include <epoxy/gl.h>
|
||||
#include <epoxy/egl.h>
|
||||
#include <epoxy/glx.h>
|
||||
#include <gdk/gdk.h>
|
||||
#ifdef GDK_WINDOWING_X11
|
||||
#include <gdk/gdkx.h>
|
||||
@@ -15,24 +14,10 @@
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
// Static helper to get proc address - must be defined outside the namespace
|
||||
// to have the correct function signature.
|
||||
// Flutter on Linux uses EGL (OpenGL ES) for both X11 and Wayland.
|
||||
static void* get_opengl_proc_address(void* ctx, const char* name) {
|
||||
(void)ctx;
|
||||
#ifdef GDK_WINDOWING_WAYLAND
|
||||
// On Wayland, use EGL
|
||||
if (epoxy_has_egl()) {
|
||||
return reinterpret_cast<void*>(eglGetProcAddress(name));
|
||||
}
|
||||
#endif
|
||||
#ifdef GDK_WINDOWING_X11
|
||||
// On X11, use GLX
|
||||
return reinterpret_cast<void*>(glXGetProcAddressARB(
|
||||
reinterpret_cast<const GLubyte*>(name)));
|
||||
#else
|
||||
// Fallback: try EGL
|
||||
return reinterpret_cast<void*>(eglGetProcAddress(name));
|
||||
#endif
|
||||
}
|
||||
|
||||
namespace mpv {
|
||||
@@ -102,6 +87,54 @@ bool MpvPlayer::InitRenderContext() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Capture Flutter's EGL display and create an isolated EGL context.
|
||||
// Flutter on Linux uses EGL for both X11 and Wayland. Running mpv in
|
||||
// an isolated context prevents OpenGL state pollution between mpv and
|
||||
// Flutter, which caused corrupted/blank video on some drivers.
|
||||
EGLDisplay flutter_display = eglGetCurrentDisplay();
|
||||
EGLContext flutter_context = eglGetCurrentContext();
|
||||
|
||||
if (flutter_display == EGL_NO_DISPLAY || flutter_context == EGL_NO_CONTEXT) {
|
||||
g_warning("MPV: No EGL context available");
|
||||
return false;
|
||||
}
|
||||
|
||||
egl_display_ = flutter_display;
|
||||
|
||||
// Query Flutter's EGL config and reuse it for compatibility
|
||||
EGLConfig config = nullptr;
|
||||
EGLint config_id = 0;
|
||||
|
||||
if (!eglQueryContext(egl_display_, flutter_context, EGL_CONFIG_ID, &config_id)) {
|
||||
g_warning("MPV: Failed to query Flutter's EGL config ID");
|
||||
return false;
|
||||
}
|
||||
|
||||
EGLint num_configs = 0;
|
||||
EGLint config_attribs[] = { EGL_CONFIG_ID, config_id, EGL_NONE };
|
||||
if (!eglChooseConfig(egl_display_, config_attribs, &config, 1, &num_configs) || num_configs == 0) {
|
||||
g_warning("MPV: Failed to get Flutter's EGL config");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create isolated EGL context (NOT shared with Flutter) to prevent
|
||||
// GL state pollution
|
||||
eglBindAPI(EGL_OPENGL_ES_API);
|
||||
EGLint context_attribs[] = {
|
||||
EGL_CONTEXT_CLIENT_VERSION, 2,
|
||||
EGL_NONE,
|
||||
};
|
||||
egl_context_ = eglCreateContext(egl_display_, config, EGL_NO_CONTEXT, context_attribs);
|
||||
if (egl_context_ == EGL_NO_CONTEXT) {
|
||||
g_warning("MPV: Failed to create isolated EGL context: 0x%x", eglGetError());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Make the isolated context current for mpv render context creation
|
||||
EGLSurface flutter_draw = eglGetCurrentSurface(EGL_DRAW);
|
||||
EGLSurface flutter_read = eglGetCurrentSurface(EGL_READ);
|
||||
eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_context_);
|
||||
|
||||
// Set up OpenGL parameters for mpv.
|
||||
mpv_opengl_init_params gl_init_params{
|
||||
.get_proc_address = get_opengl_proc_address,
|
||||
@@ -112,20 +145,42 @@ bool MpvPlayer::InitRenderContext() {
|
||||
{MPV_RENDER_PARAM_API_TYPE,
|
||||
const_cast<char*>(MPV_RENDER_API_TYPE_OPENGL)},
|
||||
{MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl_init_params},
|
||||
{MPV_RENDER_PARAM_INVALID, nullptr}, // slot for X11/Wayland display
|
||||
{MPV_RENDER_PARAM_INVALID, nullptr},
|
||||
};
|
||||
|
||||
// Pass X11/Wayland display for VAAPI hardware acceleration
|
||||
GdkDisplay* gdk_display = gdk_display_get_default();
|
||||
#ifdef GDK_WINDOWING_WAYLAND
|
||||
if (GDK_IS_WAYLAND_DISPLAY(gdk_display)) {
|
||||
params[2].type = MPV_RENDER_PARAM_WL_DISPLAY;
|
||||
params[2].data = gdk_wayland_display_get_wl_display(gdk_display);
|
||||
}
|
||||
#endif
|
||||
#ifdef GDK_WINDOWING_X11
|
||||
if (GDK_IS_X11_DISPLAY(gdk_display)) {
|
||||
params[2].type = MPV_RENDER_PARAM_X11_DISPLAY;
|
||||
params[2].data = gdk_x11_display_get_xdisplay(gdk_display);
|
||||
}
|
||||
#endif
|
||||
|
||||
int err = mpv_render_context_create(&mpv_gl_, mpv_, params);
|
||||
|
||||
// Restore Flutter's context
|
||||
eglMakeCurrent(egl_display_, flutter_draw, flutter_read, flutter_context);
|
||||
|
||||
if (err < 0) {
|
||||
g_warning("MPV: mpv_render_context_create() failed: %s",
|
||||
mpv_error_string(err));
|
||||
eglDestroyContext(egl_display_, egl_context_);
|
||||
egl_context_ = EGL_NO_CONTEXT;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set up render update callback.
|
||||
mpv_render_context_set_update_callback(mpv_gl_, OnMpvRenderUpdate, this);
|
||||
|
||||
g_message("MPV: Render context created successfully");
|
||||
g_message("MPV: Render context created with isolated EGL context");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -171,21 +226,54 @@ void MpvPlayer::Dispose() {
|
||||
// Running these off the main thread prevents stalling the GLib main loop.
|
||||
auto* gl = mpv_gl_;
|
||||
auto* handle = mpv_;
|
||||
auto egl_display = egl_display_;
|
||||
auto egl_context = egl_context_;
|
||||
mpv_gl_ = nullptr;
|
||||
mpv_ = nullptr;
|
||||
egl_display_ = EGL_NO_DISPLAY;
|
||||
egl_context_ = EGL_NO_CONTEXT;
|
||||
|
||||
std::thread([gl, handle]() {
|
||||
std::thread([gl, handle, egl_display, egl_context]() {
|
||||
if (gl) {
|
||||
// mpv render context must be freed with its EGL context current
|
||||
if (egl_context != EGL_NO_CONTEXT) {
|
||||
eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_context);
|
||||
}
|
||||
mpv_render_context_free(gl);
|
||||
}
|
||||
if (handle) {
|
||||
mpv_terminate_destroy(handle);
|
||||
}
|
||||
if (egl_context != EGL_NO_CONTEXT) {
|
||||
eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
eglDestroyContext(egl_display, egl_context);
|
||||
}
|
||||
}).detach();
|
||||
|
||||
observed_properties_.clear();
|
||||
}
|
||||
|
||||
void MpvPlayer::Render(int width, int height, int fbo) {
|
||||
if (disposed_ || !mpv_gl_) return;
|
||||
|
||||
mpv_opengl_fbo mpv_fbo{
|
||||
.fbo = fbo,
|
||||
.w = width,
|
||||
.h = height,
|
||||
.internal_format = 0,
|
||||
};
|
||||
|
||||
int flip_y = 0;
|
||||
|
||||
mpv_render_param params[] = {
|
||||
{MPV_RENDER_PARAM_OPENGL_FBO, &mpv_fbo},
|
||||
{MPV_RENDER_PARAM_FLIP_Y, &flip_y},
|
||||
{MPV_RENDER_PARAM_INVALID, nullptr},
|
||||
};
|
||||
|
||||
mpv_render_context_render(mpv_gl_, params);
|
||||
}
|
||||
|
||||
void MpvPlayer::Command(const std::vector<std::string>& args) {
|
||||
if (disposed_ || !mpv_) return;
|
||||
|
||||
@@ -277,27 +365,6 @@ void MpvPlayer::ObserveProperty(const std::string& name,
|
||||
mpv_observe_property(mpv_, userdata, name.c_str(), mpv_fmt);
|
||||
}
|
||||
|
||||
void MpvPlayer::Render(int width, int height, int fbo) {
|
||||
if (disposed_ || !mpv_gl_) return;
|
||||
|
||||
mpv_opengl_fbo mpv_fbo{
|
||||
.fbo = fbo,
|
||||
.w = width,
|
||||
.h = height,
|
||||
.internal_format = 0,
|
||||
};
|
||||
|
||||
int flip_y = 0;
|
||||
|
||||
mpv_render_param params[] = {
|
||||
{MPV_RENDER_PARAM_OPENGL_FBO, &mpv_fbo},
|
||||
{MPV_RENDER_PARAM_FLIP_Y, &flip_y},
|
||||
{MPV_RENDER_PARAM_INVALID, nullptr},
|
||||
};
|
||||
|
||||
mpv_render_context_render(mpv_gl_, params);
|
||||
}
|
||||
|
||||
void MpvPlayer::ReportMouseMove(int x, int y) {
|
||||
if (disposed_ || !mpv_) return;
|
||||
std::string x_str = std::to_string(x);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <mpv/render_gl.h>
|
||||
#include <gtk/gtk.h>
|
||||
#include <epoxy/gl.h>
|
||||
#include <epoxy/egl.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
@@ -49,6 +50,12 @@ class MpvPlayer {
|
||||
/// Returns true if the render context has been created.
|
||||
bool HasRenderContext() const { return mpv_gl_ != nullptr; }
|
||||
|
||||
/// Returns the isolated EGL display used for mpv rendering.
|
||||
EGLDisplay GetEglDisplay() const { return egl_display_; }
|
||||
|
||||
/// Returns the isolated EGL context used for mpv rendering.
|
||||
EGLContext GetEglContext() const { return egl_context_; }
|
||||
|
||||
/// Disposes mpv and releases resources.
|
||||
void Dispose();
|
||||
|
||||
@@ -126,6 +133,10 @@ class MpvPlayer {
|
||||
mpv_handle* mpv_ = nullptr;
|
||||
mpv_render_context* mpv_gl_ = nullptr;
|
||||
|
||||
// Isolated EGL context for mpv rendering (not shared with Flutter)
|
||||
EGLDisplay egl_display_ = EGL_NO_DISPLAY;
|
||||
EGLContext egl_context_ = EGL_NO_CONTEXT;
|
||||
|
||||
std::atomic<bool> needs_redraw_{false};
|
||||
std::atomic<bool> disposed_{false};
|
||||
EventCallback event_callback_;
|
||||
|
||||
@@ -38,11 +38,8 @@ static void send_event(MpvPlugin* self, FlValue* event) {
|
||||
static void mpv_plugin_dispose(GObject* object) {
|
||||
MpvPlugin* self = MPV_PLUGIN(object);
|
||||
|
||||
if (self->player) {
|
||||
self->player->Dispose();
|
||||
self->player.reset();
|
||||
}
|
||||
|
||||
// Texture must be disposed BEFORE player — mpv_texture_dispose needs
|
||||
// the player's EGL context to clean up GL resources.
|
||||
if (self->texture) {
|
||||
mpv_texture_dispose(self->texture);
|
||||
if (self->texture_registrar) {
|
||||
@@ -53,6 +50,11 @@ static void mpv_plugin_dispose(GObject* object) {
|
||||
self->texture = nullptr;
|
||||
}
|
||||
|
||||
if (self->player) {
|
||||
self->player->Dispose();
|
||||
self->player.reset();
|
||||
}
|
||||
|
||||
g_clear_object(&self->method_channel);
|
||||
g_clear_object(&self->event_channel);
|
||||
g_clear_object(&self->registrar);
|
||||
@@ -137,6 +139,11 @@ static void mpv_plugin_handle_method_call(FlMethodChannel* channel,
|
||||
fl_texture_registrar_register_texture(
|
||||
self->texture_registrar, FL_TEXTURE(self->texture));
|
||||
|
||||
// Create the render context eagerly — mpv needs it BEFORE any
|
||||
// file is loaded, otherwise VO init fails with "No render context
|
||||
// set" and the video track is dropped entirely.
|
||||
self->player->InitRenderContext();
|
||||
|
||||
// Set redraw callback: when mpv has a frame, mark texture available
|
||||
MpvTexture* tex = self->texture;
|
||||
self->player->SetRedrawCallback([tex]() {
|
||||
|
||||
+152
-61
@@ -1,6 +1,26 @@
|
||||
#include "mpv_texture.h"
|
||||
|
||||
#include <epoxy/gl.h>
|
||||
#include <epoxy/egl.h>
|
||||
|
||||
// EGLImage extension function pointers
|
||||
typedef EGLImageKHR (*PFNEGLCREATEIMAGEKHRPROC)(EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint*);
|
||||
typedef EGLBoolean (*PFNEGLDESTROYIMAGEKHRPROC)(EGLDisplay, EGLImageKHR);
|
||||
typedef void (*PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)(GLenum, GLeglImageOES);
|
||||
|
||||
static PFNEGLCREATEIMAGEKHRPROC _eglCreateImageKHR = nullptr;
|
||||
static PFNEGLDESTROYIMAGEKHRPROC _eglDestroyImageKHR = nullptr;
|
||||
static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC _glEGLImageTargetTexture2DOES = nullptr;
|
||||
|
||||
static void init_egl_image_extensions() {
|
||||
static bool initialized = false;
|
||||
if (!initialized) {
|
||||
_eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR");
|
||||
_eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC)eglGetProcAddress("eglDestroyImageKHR");
|
||||
_glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress("glEGLImageTargetTexture2DOES");
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
struct _MpvTexture {
|
||||
FlTextureGL parent_instance;
|
||||
@@ -9,44 +29,96 @@ struct _MpvTexture {
|
||||
FlTextureRegistrar* registrar; // not owned
|
||||
FlView* view; // not owned, for querying allocation size
|
||||
|
||||
GLuint fbo;
|
||||
GLuint texture;
|
||||
// mpv's FBO and texture (owned by mpv's isolated EGL context)
|
||||
GLuint mpv_fbo;
|
||||
GLuint mpv_texture;
|
||||
|
||||
// Flutter's texture (owned by Flutter's EGL context)
|
||||
GLuint flutter_texture;
|
||||
|
||||
// EGLImage bridging the two contexts
|
||||
EGLImageKHR egl_image;
|
||||
|
||||
int32_t width;
|
||||
int32_t height;
|
||||
};
|
||||
|
||||
G_DEFINE_TYPE(MpvTexture, mpv_texture, fl_texture_gl_get_type())
|
||||
|
||||
static void ensure_fbo(MpvTexture* self, int32_t w, int32_t h) {
|
||||
if (self->fbo != 0 && self->width == w && self->height == h) {
|
||||
// Create/resize the FBO in mpv's context and the shared EGLImage + Flutter texture.
|
||||
static void ensure_textures(MpvTexture* self, int32_t w, int32_t h) {
|
||||
if (self->mpv_fbo != 0 && self->width == w && self->height == h) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Delete old resources.
|
||||
if (self->fbo != 0) {
|
||||
glDeleteFramebuffers(1, &self->fbo);
|
||||
self->fbo = 0;
|
||||
EGLDisplay egl_display = self->player->GetEglDisplay();
|
||||
EGLContext egl_context = self->player->GetEglContext();
|
||||
|
||||
// Save Flutter's current EGL state
|
||||
EGLDisplay flutter_display = eglGetCurrentDisplay();
|
||||
EGLContext flutter_context = eglGetCurrentContext();
|
||||
EGLSurface flutter_draw = eglGetCurrentSurface(EGL_DRAW);
|
||||
EGLSurface flutter_read = eglGetCurrentSurface(EGL_READ);
|
||||
|
||||
// --- Switch to mpv's isolated context ---
|
||||
eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_context);
|
||||
|
||||
// Clean up previous mpv resources
|
||||
if (self->mpv_texture != 0) {
|
||||
glDeleteTextures(1, &self->mpv_texture);
|
||||
}
|
||||
if (self->texture != 0) {
|
||||
glDeleteTextures(1, &self->texture);
|
||||
self->texture = 0;
|
||||
if (self->mpv_fbo != 0) {
|
||||
glDeleteFramebuffers(1, &self->mpv_fbo);
|
||||
}
|
||||
if (self->egl_image != EGL_NO_IMAGE_KHR) {
|
||||
_eglDestroyImageKHR(egl_display, self->egl_image);
|
||||
}
|
||||
|
||||
self->width = w;
|
||||
self->height = h;
|
||||
|
||||
glGenTextures(1, &self->texture);
|
||||
glBindTexture(GL_TEXTURE_2D, self->texture);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA,
|
||||
GL_UNSIGNED_BYTE, nullptr);
|
||||
// Create mpv's texture and FBO
|
||||
glGenTextures(1, &self->mpv_texture);
|
||||
glBindTexture(GL_TEXTURE_2D, self->mpv_texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
|
||||
GL_UNSIGNED_BYTE, nullptr);
|
||||
|
||||
glGenFramebuffers(1, &self->mpv_fbo);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, self->mpv_fbo);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
|
||||
GL_TEXTURE_2D, self->mpv_texture, 0);
|
||||
|
||||
// Create EGLImage from mpv's texture for cross-context sharing
|
||||
EGLint image_attribs[] = { EGL_NONE };
|
||||
self->egl_image = _eglCreateImageKHR(
|
||||
egl_display, egl_context, EGL_GL_TEXTURE_2D_KHR,
|
||||
(EGLClientBuffer)(uintptr_t)self->mpv_texture, image_attribs);
|
||||
|
||||
glGenFramebuffers(1, &self->fbo);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, self->fbo);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
|
||||
self->texture, 0);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
glBindTexture(GL_TEXTURE_2D, 0);
|
||||
glFlush();
|
||||
|
||||
// --- Switch back to Flutter's context ---
|
||||
eglMakeCurrent(flutter_display, flutter_draw, flutter_read, flutter_context);
|
||||
|
||||
// Clean up previous Flutter texture
|
||||
if (self->flutter_texture != 0) {
|
||||
glDeleteTextures(1, &self->flutter_texture);
|
||||
}
|
||||
|
||||
// Create Flutter's texture backed by the EGLImage
|
||||
glGenTextures(1, &self->flutter_texture);
|
||||
glBindTexture(GL_TEXTURE_2D, self->flutter_texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
_glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, self->egl_image);
|
||||
glBindTexture(GL_TEXTURE_2D, 0);
|
||||
}
|
||||
|
||||
static gboolean mpv_texture_populate(FlTextureGL* gl_texture,
|
||||
@@ -82,47 +154,31 @@ static gboolean mpv_texture_populate(FlTextureGL* gl_texture,
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
ensure_fbo(self, w, h);
|
||||
ensure_textures(self, w, h);
|
||||
|
||||
// Save GL state that mpv may clobber.
|
||||
GLint prev_viewport[4];
|
||||
GLint prev_scissor_box[4];
|
||||
GLboolean prev_blend, prev_scissor_test;
|
||||
GLint prev_blend_src, prev_blend_dst;
|
||||
GLint prev_fbo;
|
||||
// Save Flutter's current EGL state
|
||||
EGLDisplay flutter_display = eglGetCurrentDisplay();
|
||||
EGLContext flutter_context = eglGetCurrentContext();
|
||||
EGLSurface flutter_draw = eglGetCurrentSurface(EGL_DRAW);
|
||||
EGLSurface flutter_read = eglGetCurrentSurface(EGL_READ);
|
||||
|
||||
glGetIntegerv(GL_VIEWPORT, prev_viewport);
|
||||
glGetIntegerv(GL_SCISSOR_BOX, prev_scissor_box);
|
||||
glGetBooleanv(GL_BLEND, &prev_blend);
|
||||
glGetBooleanv(GL_SCISSOR_TEST, &prev_scissor_test);
|
||||
glGetIntegerv(GL_BLEND_SRC_ALPHA, &prev_blend_src);
|
||||
glGetIntegerv(GL_BLEND_DST_ALPHA, &prev_blend_dst);
|
||||
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo);
|
||||
// Switch to mpv's isolated context for rendering
|
||||
EGLDisplay egl_display = self->player->GetEglDisplay();
|
||||
EGLContext egl_context = self->player->GetEglContext();
|
||||
eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_context);
|
||||
|
||||
// Render mpv into our FBO.
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, self->fbo);
|
||||
glViewport(0, 0, w, h);
|
||||
// Render mpv into its FBO
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, self->mpv_fbo);
|
||||
self->player->ClearRedrawFlag();
|
||||
self->player->Render(w, h, static_cast<int>(self->fbo));
|
||||
self->player->Render(w, h, static_cast<int>(self->mpv_fbo));
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
glFlush();
|
||||
|
||||
// Restore GL state.
|
||||
glViewport(prev_viewport[0], prev_viewport[1], prev_viewport[2],
|
||||
prev_viewport[3]);
|
||||
glScissor(prev_scissor_box[0], prev_scissor_box[1], prev_scissor_box[2],
|
||||
prev_scissor_box[3]);
|
||||
if (prev_blend)
|
||||
glEnable(GL_BLEND);
|
||||
else
|
||||
glDisable(GL_BLEND);
|
||||
if (prev_scissor_test)
|
||||
glEnable(GL_SCISSOR_TEST);
|
||||
else
|
||||
glDisable(GL_SCISSOR_TEST);
|
||||
glBlendFunc(prev_blend_src, prev_blend_dst);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, prev_fbo);
|
||||
// Restore Flutter's context
|
||||
eglMakeCurrent(flutter_display, flutter_draw, flutter_read, flutter_context);
|
||||
|
||||
*target = GL_TEXTURE_2D;
|
||||
*name = self->texture;
|
||||
*name = self->flutter_texture;
|
||||
*width = static_cast<uint32_t>(w);
|
||||
*height = static_cast<uint32_t>(h);
|
||||
|
||||
@@ -137,8 +193,10 @@ static void mpv_texture_init(MpvTexture* self) {
|
||||
self->player = nullptr;
|
||||
self->registrar = nullptr;
|
||||
self->view = nullptr;
|
||||
self->fbo = 0;
|
||||
self->texture = 0;
|
||||
self->mpv_fbo = 0;
|
||||
self->mpv_texture = 0;
|
||||
self->flutter_texture = 0;
|
||||
self->egl_image = EGL_NO_IMAGE_KHR;
|
||||
self->width = 0;
|
||||
self->height = 0;
|
||||
}
|
||||
@@ -146,6 +204,7 @@ static void mpv_texture_init(MpvTexture* self) {
|
||||
MpvTexture* mpv_texture_new(mpv::MpvPlayer* player,
|
||||
FlTextureRegistrar* registrar,
|
||||
FlView* view) {
|
||||
init_egl_image_extensions();
|
||||
MpvTexture* self = MPV_TEXTURE(g_object_new(MPV_TEXTURE_TYPE, nullptr));
|
||||
self->player = player;
|
||||
self->registrar = registrar;
|
||||
@@ -163,13 +222,45 @@ void mpv_texture_mark_frame_available(MpvTexture* self) {
|
||||
void mpv_texture_dispose(MpvTexture* self) {
|
||||
if (!self) return;
|
||||
|
||||
if (self->fbo != 0) {
|
||||
glDeleteFramebuffers(1, &self->fbo);
|
||||
self->fbo = 0;
|
||||
EGLDisplay egl_display = EGL_NO_DISPLAY;
|
||||
EGLContext egl_context = EGL_NO_CONTEXT;
|
||||
|
||||
if (self->player) {
|
||||
egl_display = self->player->GetEglDisplay();
|
||||
egl_context = self->player->GetEglContext();
|
||||
}
|
||||
if (self->texture != 0) {
|
||||
glDeleteTextures(1, &self->texture);
|
||||
self->texture = 0;
|
||||
|
||||
// Clean up Flutter's texture (in Flutter's current context)
|
||||
if (self->flutter_texture != 0) {
|
||||
glDeleteTextures(1, &self->flutter_texture);
|
||||
self->flutter_texture = 0;
|
||||
}
|
||||
|
||||
// Clean up EGLImage
|
||||
if (self->egl_image != EGL_NO_IMAGE_KHR && egl_display != EGL_NO_DISPLAY) {
|
||||
_eglDestroyImageKHR(egl_display, self->egl_image);
|
||||
self->egl_image = EGL_NO_IMAGE_KHR;
|
||||
}
|
||||
|
||||
// Clean up mpv's GL resources in mpv's context
|
||||
if (egl_context != EGL_NO_CONTEXT) {
|
||||
EGLDisplay cur_display = eglGetCurrentDisplay();
|
||||
EGLContext cur_context = eglGetCurrentContext();
|
||||
EGLSurface cur_draw = eglGetCurrentSurface(EGL_DRAW);
|
||||
EGLSurface cur_read = eglGetCurrentSurface(EGL_READ);
|
||||
|
||||
eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_context);
|
||||
|
||||
if (self->mpv_texture != 0) {
|
||||
glDeleteTextures(1, &self->mpv_texture);
|
||||
self->mpv_texture = 0;
|
||||
}
|
||||
if (self->mpv_fbo != 0) {
|
||||
glDeleteFramebuffers(1, &self->mpv_fbo);
|
||||
self->mpv_fbo = 0;
|
||||
}
|
||||
|
||||
eglMakeCurrent(cur_display, cur_draw, cur_read, cur_context);
|
||||
}
|
||||
|
||||
self->player = nullptr;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import FlutterMacOS
|
||||
import Foundation
|
||||
|
||||
import auto_updater_macos
|
||||
import connectivity_plus
|
||||
import device_info_plus
|
||||
import file_picker
|
||||
@@ -23,6 +24,7 @@ import wakelock_plus
|
||||
import window_manager
|
||||
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
AutoUpdaterMacosPlugin.register(with: registry.registrar(forPlugin: "AutoUpdaterMacosPlugin"))
|
||||
ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin"))
|
||||
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
|
||||
FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin"))
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
PODS:
|
||||
- auto_updater_macos (0.0.1):
|
||||
- FlutterMacOS
|
||||
- Sparkle
|
||||
- connectivity_plus (0.0.1):
|
||||
- FlutterMacOS
|
||||
- device_info_plus (0.0.1):
|
||||
@@ -22,6 +25,7 @@ PODS:
|
||||
- shared_preferences_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- Sparkle (2.9.0)
|
||||
- sqflite_darwin (0.0.4):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
@@ -60,6 +64,7 @@ PODS:
|
||||
- FlutterMacOS
|
||||
|
||||
DEPENDENCIES:
|
||||
- auto_updater_macos (from `Flutter/ephemeral/.symlinks/plugins/auto_updater_macos/macos`)
|
||||
- connectivity_plus (from `Flutter/ephemeral/.symlinks/plugins/connectivity_plus/macos`)
|
||||
- device_info_plus (from `Flutter/ephemeral/.symlinks/plugins/device_info_plus/macos`)
|
||||
- file_picker (from `Flutter/ephemeral/.symlinks/plugins/file_picker/macos`)
|
||||
@@ -80,9 +85,12 @@ DEPENDENCIES:
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- Sparkle
|
||||
- sqlite3
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
auto_updater_macos:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/auto_updater_macos/macos
|
||||
connectivity_plus:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/connectivity_plus/macos
|
||||
device_info_plus:
|
||||
@@ -119,6 +127,7 @@ EXTERNAL SOURCES:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/window_manager/macos
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
auto_updater_macos: 3a42f1a06be6981f1a18be37e6e7bf86aa732118
|
||||
connectivity_plus: 4adf20a405e25b42b9c9f87feff8f4b6fde18a4e
|
||||
device_info_plus: 4fb280989f669696856f8b129e4a5e3cd6c48f76
|
||||
file_picker: 7584aae6fa07a041af2b36a2655122d42f578c1a
|
||||
@@ -130,6 +139,7 @@ SPEC CHECKSUMS:
|
||||
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
|
||||
screen_retriever_macos: 452e51764a9e1cdb74b3c541238795849f21557f
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
Sparkle: f4355f9ebbe9b7d932df4980d70f13922ac97b2a
|
||||
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
|
||||
sqlite3: 8d708bc63e9f4ce48f0ad9d6269e478c5ced1d9b
|
||||
sqlite3_flutter_libs: d13b8b3003f18f596e542bcb9482d105577eff41
|
||||
|
||||
@@ -30,5 +30,9 @@
|
||||
<string>NSApplication</string>
|
||||
<key>FLTEnableMergedPlatformUIThread</key>
|
||||
<false/>
|
||||
<key>SUFeedURL</key>
|
||||
<string>https://github.com/edde746/plezy/releases/latest/download/appcast.xml</string>
|
||||
<key>SUPublicEDKey</key>
|
||||
<string>q7t6eu1txRrqv1PeWDCRV95rFxnmD/D3GZWbUPMwUyU=</string>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
+44
-2
@@ -65,6 +65,40 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.13.0"
|
||||
auto_updater:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "packages/auto_updater"
|
||||
ref: HEAD
|
||||
resolved-ref: c70320c6885db88ef8360d278f936e90a7cc9689
|
||||
url: "https://github.com/edde746/auto_updater"
|
||||
source: git
|
||||
version: "1.0.0"
|
||||
auto_updater_macos:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: auto_updater_macos
|
||||
sha256: ef9de0daf38d782d2243fe131503a9404d62df762f5386e5360020e43c01867f
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.0"
|
||||
auto_updater_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: auto_updater_platform_interface
|
||||
sha256: ed5dff8cea18c58bc5ac787ff9122fedd1644272e02015d28c9b592f8078c5dc
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.0"
|
||||
auto_updater_windows:
|
||||
dependency: "direct overridden"
|
||||
description:
|
||||
path: "packages/auto_updater_windows"
|
||||
ref: HEAD
|
||||
resolved-ref: c70320c6885db88ef8360d278f936e90a7cc9689
|
||||
url: "https://github.com/edde746/auto_updater"
|
||||
source: git
|
||||
version: "1.0.0"
|
||||
background_downloader:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -273,6 +307,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.7"
|
||||
cryptography:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cryptography
|
||||
sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.9.0"
|
||||
csslib:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1263,10 +1305,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: universal_gamepad
|
||||
sha256: afd3106195aa2052ec23fe61069cad8d0caed255c7e2e6ed33a403e0a94f365e
|
||||
sha256: b638bd9d2bf25c15cf815c7f1a66629d56e8d5229178d7347ffc68efd7c646dd
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.4"
|
||||
version: "1.5.0"
|
||||
url_launcher:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user