Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70f6e2142d | ||
|
|
37f025056c | ||
|
|
ea8ea6f059 | ||
|
|
05f4c9e1f6 | ||
|
|
3a18d07593 | ||
|
|
d2eaadb07d | ||
|
|
4db60bc7c2 | ||
|
|
27ff86f822 | ||
|
|
c4789070d0 | ||
|
|
c189bef42c | ||
|
|
aea4cfcf59 | ||
|
|
cffef8671e | ||
|
|
8e5b9de471 | ||
|
|
a91a419ef3 | ||
|
|
c71db8f9eb | ||
|
|
abe0919324 | ||
|
|
f4d3dbd7d8 | ||
|
|
570f1fdc58 | ||
|
|
da1a4e7aa8 | ||
|
|
5ed2532bf1 | ||
|
|
ed98a65c60 | ||
|
|
562b54d1cb | ||
|
|
85b056f3d0 | ||
|
|
da6ba9bd67 | ||
|
|
6bfda5e6d4 | ||
|
|
a10dfcc004 | ||
|
|
08f8d2373a | ||
|
|
ce6686e634 | ||
|
|
c53018b53b | ||
|
|
1191d8a438 | ||
|
|
1d67a5d992 | ||
|
|
e3c1cba600 | ||
|
|
a0f28b1dc7 | ||
|
|
442899eecd | ||
|
|
76db3cb450 | ||
|
|
bea485bddc | ||
|
|
b36e585fd7 | ||
|
|
8b89529ac8 | ||
|
|
8b3b8ad596 | ||
|
|
1d8a5ee23e | ||
|
|
4453eb995e | ||
|
|
9e506d3f68 | ||
|
|
a698ab0930 | ||
|
|
b0d669d93a | ||
|
|
8dafac4ea5 | ||
|
|
ef7fe85d5d | ||
|
|
b796491e60 | ||
|
|
2ad06c4dbc | ||
|
|
3494fbc5be | ||
|
|
c2ff56b1f1 | ||
|
|
95436529c6 | ||
|
|
ad7f381f54 | ||
|
|
d50a86501b | ||
|
|
d9bc7d6b86 | ||
|
|
8ab972691a | ||
|
|
47cb3f2614 | ||
|
|
743f2bb9f2 | ||
|
|
5f4c5a012b | ||
|
|
dae1750d86 | ||
|
|
e9d1055c60 | ||
|
|
c2933c0fdf | ||
|
|
e252532988 | ||
|
|
16087cf640 | ||
|
|
4804a25c1e | ||
|
|
a74838d914 | ||
|
|
b396464f70 | ||
|
|
f9198c7d7a | ||
|
|
f4753e6b2e | ||
|
|
3c5739eefd | ||
|
|
d8d39cca86 | ||
|
|
84c255b917 | ||
|
|
44007e6564 | ||
|
|
2dfebf32b6 | ||
|
|
b27aa9cbda | ||
|
|
1bce10a6a4 | ||
|
|
c018cfef03 | ||
|
|
d340536578 | ||
|
|
1419f6e043 | ||
|
|
722b53c0b9 | ||
|
|
c61b2301a6 | ||
|
|
14f0e95a3d | ||
|
|
688ad291bd | ||
|
|
2644c3ca55 | ||
|
|
2f3774db3d | ||
|
|
e11ebca370 | ||
|
|
bed2c35d97 | ||
|
|
8db30c1568 | ||
|
|
c6727baf07 | ||
|
|
d9350d704f |
@@ -1,4 +1,4 @@
|
||||
name: Build Flutter App
|
||||
name: Build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -57,27 +57,35 @@ jobs:
|
||||
storeFile=upload-keystore.jks
|
||||
EOF
|
||||
|
||||
- name: Build APK
|
||||
run: flutter build apk --release --dart-define=ENABLE_UPDATE_CHECK=true
|
||||
- name: Build APKs
|
||||
run: flutter build apk --release --split-per-abi --dart-define=ENABLE_UPDATE_CHECK=true
|
||||
|
||||
- name: Clean up keystore
|
||||
if: always()
|
||||
run: rm -f android/app/upload-keystore.jks android/key.properties
|
||||
|
||||
- name: Rename APK
|
||||
- name: Package APKs
|
||||
run: |
|
||||
cp build/app/outputs/flutter-apk/app-release.apk plezy-android.apk
|
||||
tar -czf plezy-android-arm64-v8a.tar.gz -C build/app/outputs/flutter-apk app-arm64-v8a-release.apk --transform 's/app-arm64-v8a-release.apk/plezy.apk/'
|
||||
tar -czf plezy-android-armeabi-v7a.tar.gz -C build/app/outputs/flutter-apk app-armeabi-v7a-release.apk --transform 's/app-armeabi-v7a-release.apk/plezy.apk/'
|
||||
tar -czf plezy-android-x86_64.tar.gz -C build/app/outputs/flutter-apk app-x86_64-release.apk --transform 's/app-x86_64-release.apk/plezy.apk/'
|
||||
|
||||
- name: Attest APK
|
||||
- name: Attest APKs
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: plezy-android.apk
|
||||
subject-path: |
|
||||
plezy-android-arm64-v8a.tar.gz
|
||||
plezy-android-armeabi-v7a.tar.gz
|
||||
plezy-android-x86_64.tar.gz
|
||||
|
||||
- name: Upload APK
|
||||
- name: Upload APKs
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: android-apk
|
||||
path: plezy-android.apk
|
||||
path: |
|
||||
plezy-android-arm64-v8a.tar.gz
|
||||
plezy-android-armeabi-v7a.tar.gz
|
||||
plezy-android-x86_64.tar.gz
|
||||
|
||||
build-ios:
|
||||
runs-on: macos-26
|
||||
@@ -207,7 +215,7 @@ jobs:
|
||||
IDENTITY=$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -1 | grep -o '".*"' | tr -d '"')
|
||||
echo "Signing with identity: $IDENTITY"
|
||||
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
|
||||
# Sign all frameworks and dylibs first (inside-out signing)
|
||||
find "$APP_PATH/Contents/Frameworks" -name "*.framework" -o -name "*.dylib" | while read framework; do
|
||||
@@ -221,7 +229,7 @@ jobs:
|
||||
|
||||
- name: Verify Signature
|
||||
run: |
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
echo "Verifying signature..."
|
||||
codesign -dvvv "$APP_PATH"
|
||||
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
|
||||
@@ -232,7 +240,7 @@ jobs:
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
|
||||
# Create a temporary ZIP for notarization submission
|
||||
echo "Creating ZIP for notarization..."
|
||||
@@ -254,21 +262,23 @@ jobs:
|
||||
echo "Verifying notarization..."
|
||||
xcrun stapler validate "$APP_PATH"
|
||||
|
||||
- name: Create ZIP
|
||||
- name: Create DMG
|
||||
run: |
|
||||
cd build/macos/Build/Products/Release
|
||||
ditto -c -k --sequesterRsrc --keepParent plezy.app $GITHUB_WORKSPACE/plezy-macos.zip
|
||||
mkdir -p dmg-staging
|
||||
cp -R build/macos/Build/Products/Release/Plezy.app dmg-staging/
|
||||
ln -s /Applications dmg-staging/Applications
|
||||
hdiutil create -format ULMO -srcfolder dmg-staging -volname "Plezy" plezy-macos.dmg
|
||||
|
||||
- name: Attest macOS ZIP
|
||||
- name: Attest macOS DMG
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: plezy-macos.zip
|
||||
subject-path: plezy-macos.dmg
|
||||
|
||||
- name: Upload macOS ZIP
|
||||
- name: Upload macOS DMG
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: macos-zip
|
||||
path: plezy-macos.zip
|
||||
name: macos-dmg
|
||||
path: plezy-macos.dmg
|
||||
|
||||
build-windows:
|
||||
runs-on: windows-latest
|
||||
@@ -307,14 +317,14 @@ jobs:
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: |
|
||||
plezy-windows-portable.zip
|
||||
plezy-windows-portable.7z
|
||||
plezy-windows-installer.exe
|
||||
|
||||
- name: Upload Portable Archive
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-portable
|
||||
path: plezy-windows-portable.zip
|
||||
path: plezy-windows-portable.7z
|
||||
|
||||
- name: Upload Installer
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -349,13 +359,16 @@ jobs:
|
||||
- name: Cache APT packages
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0
|
||||
version: 1.0
|
||||
packages: clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0 ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
|
||||
version: 1.1
|
||||
|
||||
- name: Install Linux dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0
|
||||
sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0 ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick
|
||||
|
||||
- name: Install fpm
|
||||
run: sudo gem install fpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
@@ -368,10 +381,17 @@ jobs:
|
||||
cd build/linux/x64/release/bundle
|
||||
tar -czf $GITHUB_WORKSPACE/plezy-linux.tar.gz *
|
||||
|
||||
- name: Attest Linux tarball
|
||||
- name: Build Linux Packages
|
||||
run: OUTPUT_DIR=$GITHUB_WORKSPACE python3 linux/packaging/build-packages.py
|
||||
|
||||
- name: Attest Linux artifacts
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: plezy-linux.tar.gz
|
||||
subject-path: |
|
||||
plezy-linux.tar.gz
|
||||
plezy-linux.deb
|
||||
plezy-linux.rpm
|
||||
plezy-linux.pkg.tar.zst
|
||||
|
||||
- name: Upload Linux App
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -379,15 +399,17 @@ jobs:
|
||||
name: linux-app
|
||||
path: plezy-linux.tar.gz
|
||||
|
||||
- name: Upload Linux Packages
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-packages
|
||||
path: |
|
||||
plezy-linux.deb
|
||||
plezy-linux.rpm
|
||||
plezy-linux.pkg.tar.zst
|
||||
|
||||
create-release:
|
||||
needs:
|
||||
[
|
||||
build-android,
|
||||
build-ios,
|
||||
build-macos,
|
||||
build-windows,
|
||||
build-linux,
|
||||
]
|
||||
needs: [build-android, build-ios, build-macos, build-windows, build-linux]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -404,12 +426,15 @@ jobs:
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: |
|
||||
artifacts/android-apk/plezy-android.apk
|
||||
artifacts/android-apk/plezy-android-arm64-v8a.tar.gz
|
||||
artifacts/android-apk/plezy-android-armeabi-v7a.tar.gz
|
||||
artifacts/android-apk/plezy-android-x86_64.tar.gz
|
||||
artifacts/ios-ipa/plezy-ios.ipa
|
||||
artifacts/macos-zip/plezy-macos.zip
|
||||
artifacts/windows-portable/plezy-windows-portable.zip
|
||||
artifacts/macos-dmg/plezy-macos.dmg
|
||||
artifacts/windows-portable/plezy-windows-portable.7z
|
||||
artifacts/windows-installer/plezy-windows-installer.exe
|
||||
artifacts/linux-app/plezy-linux.tar.gz
|
||||
artifacts/linux-packages/*
|
||||
draft: true
|
||||
prerelease: false
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
# Privacy Policy for Plezy
|
||||
|
||||
**Last Updated: October 22, 2025**
|
||||
|
||||
## Introduction
|
||||
|
||||
Plezy ("we", "our", or "the app") is a third-party Plex client that allows you to access and stream content from your Plex Media Server. This privacy policy explains how we handle your information when you use our app.
|
||||
|
||||
## Information We Collect
|
||||
|
||||
### Authentication Information
|
||||
When you sign in to Plezy using your Plex account, we collect and process:
|
||||
- Plex authentication tokens
|
||||
- Plex account username
|
||||
- Plex server connection information
|
||||
|
||||
### Local Network Information
|
||||
To connect to your Plex Media Server on your local network, we may access:
|
||||
- Local network device discovery information
|
||||
- IP addresses of Plex servers on your network
|
||||
|
||||
### Usage Information
|
||||
The app stores locally on your device:
|
||||
- Your authentication session
|
||||
- App preferences and settings
|
||||
- Recently accessed content history
|
||||
|
||||
## How We Use Your Information
|
||||
|
||||
We use the collected information solely to:
|
||||
- Authenticate you with your Plex account
|
||||
- Connect to and communicate with your Plex Media Server
|
||||
- Display your media library and stream content
|
||||
- Maintain your session and app preferences
|
||||
|
||||
## Data Storage and Security
|
||||
|
||||
- **Authentication tokens** are stored securely on your device using platform-specific secure storage mechanisms
|
||||
- **App preferences** are stored locally on your device
|
||||
- **No data** is transmitted to our servers - all communication is directly between your device and your Plex Media Server or Plex's authentication services
|
||||
|
||||
## Third-Party Services
|
||||
|
||||
### Plex
|
||||
Plezy uses Plex's authentication and media services. When you use this app:
|
||||
- You authenticate directly with Plex's servers
|
||||
- Your media streaming occurs between your device and your Plex Media Server
|
||||
- Plex's own privacy policy applies to their services: https://www.plex.tv/about/privacy-legal/
|
||||
|
||||
We do not control and are not responsible for Plex's data practices.
|
||||
|
||||
## Data Sharing
|
||||
|
||||
We do not:
|
||||
- Sell your personal information
|
||||
- Share your information with third parties for marketing purposes
|
||||
- Transmit your data to our own servers
|
||||
- Track your viewing habits outside of local app functionality
|
||||
|
||||
Your data is only shared with:
|
||||
- **Plex services** for authentication and media server communication (as required for the app to function)
|
||||
|
||||
## Your Rights and Choices
|
||||
|
||||
You can:
|
||||
- **Sign out** at any time to remove your authentication session from the device
|
||||
- **Uninstall the app** to remove all locally stored data
|
||||
- **Manage your Plex account** directly through Plex's services
|
||||
|
||||
## Children's Privacy
|
||||
|
||||
Plezy does not knowingly collect personal information from children under 13. The app relies on Plex account authentication, and users must comply with Plex's terms of service and age requirements.
|
||||
|
||||
## Changes to This Privacy Policy
|
||||
|
||||
We may update this privacy policy from time to time. We will notify users of any material changes by updating the "Last Updated" date at the top of this policy.
|
||||
|
||||
## Data Retention
|
||||
|
||||
- Authentication tokens are retained on your device until you sign out or uninstall the app
|
||||
- Local preferences and settings are retained until you uninstall the app
|
||||
- No data is retained on our servers as we do not operate any backend services
|
||||
|
||||
## International Data Transfers
|
||||
|
||||
As we do not operate backend servers, there are no international data transfers from our side. Any data transfers occur directly between your device and Plex's services, subject to Plex's privacy policy.
|
||||
|
||||
## Legal Compliance
|
||||
|
||||
This app complies with:
|
||||
- General Data Protection Regulation (GDPR)
|
||||
- California Consumer Privacy Act (CCPA)
|
||||
- Children's Online Privacy Protection Act (COPPA)
|
||||
- Other applicable privacy laws
|
||||
|
||||
## Your Consent
|
||||
|
||||
By using Plezy, you consent to this privacy policy and the processing of your information as described herein.
|
||||
@@ -3,13 +3,13 @@
|
||||
Plezy
|
||||
</h1>
|
||||
|
||||
Plezy is a modern Plex media client that provides a seamless streaming experience across desktop and mobile platforms. Built with Flutter, it offers native performance and a clean, intuitive interface for browsing and playing your Plex media library.
|
||||
A modern Plex client for desktop and mobile. Built with Flutter for native performance and a clean interface.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
|
||||
</p>
|
||||
|
||||
*See more screenshots in the [screenshots folder](assets/screenshots/#readme)*
|
||||
*More screenshots in the [screenshots folder](assets/screenshots/#readme)*
|
||||
|
||||
## Download
|
||||
|
||||
@@ -19,66 +19,58 @@ Plezy is a modern Plex media client that provides a seamless streaming experienc
|
||||
|
||||
### Desktop
|
||||
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
|
||||
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.zip)
|
||||
- [Linux (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-linux.tar.gz)
|
||||
|
||||
> Download the latest release from the [Releases page](https://github.com/edde746/plezy/releases)
|
||||
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg)
|
||||
- [Linux (x64)](https://github.com/edde746/plezy/releases/latest) - .deb, .rpm, .pkg.tar.zst, and portable tar.gz available
|
||||
- [NixOS/Nix](https://github.com/mio-19/nurpkgs/tree/main/pkgs/plezy) - Community package by [@mio-19](https://github.com/mio-19)
|
||||
- [Homebrew](https://github.com/Tazi0/homebrew-plezy) - Community tap by [@Tazi0](https://github.com/Tazi0)
|
||||
|
||||
## Features
|
||||
|
||||
### 🔐 Authentication & Server Management
|
||||
### 🔐 Authentication
|
||||
- Sign in with Plex
|
||||
- Automatic server discovery with smart connection selection
|
||||
- Automatic server discovery and smart connection selection
|
||||
- Persistent sessions with auto-login
|
||||
|
||||
### 📚 Media Browsing
|
||||
- Browse libraries with rich metadata
|
||||
- Discover featured content
|
||||
- Advanced search across all media
|
||||
- Season and episode navigation
|
||||
- Collections and playlists
|
||||
|
||||
### 🎬 Video Playback
|
||||
- Wide codec support including HEVC, AV1, VP9, and more
|
||||
- HDR and Dolby Vision support (iOS, macOS & Windows)
|
||||
- Advanced subtitle rendering with full ASS/SSA support
|
||||
- Audio and subtitle track selection with user profile preferences
|
||||
- Playback progress sync and resume functionality
|
||||
### 🎬 Playback
|
||||
- Wide codec support (HEVC, AV1, VP9, and more)
|
||||
- HDR and Dolby Vision (iOS, macOS, Windows)
|
||||
- Full ASS/SSA subtitle support
|
||||
- Audio and subtitle preferences synced with Plex profile
|
||||
- Progress sync and resume
|
||||
- Auto-play next episode
|
||||
|
||||
## Prerequisites
|
||||
### 📥 Downloads
|
||||
- Download media for offline viewing
|
||||
- Background downloads with queue management
|
||||
|
||||
- Flutter SDK 3.8.1 or higher
|
||||
- A Plex account
|
||||
- Access to a Plex Media Server (local or remote)
|
||||
### 👥 Watch Together
|
||||
- Synchronized playback with friends
|
||||
- Real-time play/pause and seek sync
|
||||
|
||||
## Installation
|
||||
## Building from Source
|
||||
|
||||
### Prerequisites
|
||||
- Flutter SDK 3.8.1+
|
||||
- A Plex account with server access
|
||||
|
||||
### Setup
|
||||
|
||||
1. Clone the repository:
|
||||
```bash
|
||||
git clone https://github.com/edde746/plezy.git
|
||||
cd plezy
|
||||
```
|
||||
|
||||
2. Install dependencies:
|
||||
```bash
|
||||
flutter pub get
|
||||
```
|
||||
|
||||
3. Generate required code:
|
||||
```bash
|
||||
dart run build_runner build
|
||||
```
|
||||
|
||||
4. Run the application:
|
||||
```bash
|
||||
flutter run
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
### Code Generation
|
||||
|
||||
The project uses code generation for JSON serialization. After modifying model classes, run:
|
||||
After modifying model classes:
|
||||
|
||||
```bash
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
@@ -88,6 +80,4 @@ dart run build_runner build --delete-conflicting-outputs
|
||||
|
||||
- Built with [Flutter](https://flutter.dev)
|
||||
- Designed for [Plex Media Server](https://www.plex.tv)
|
||||
- Playback powered by [mpv](https://mpv.io)
|
||||
- [MPVKit](https://github.com/mpvkit/MPVKit)
|
||||
- [mpv-android](https://github.com/mpv-android/mpv-android)
|
||||
- Playback powered by [mpv](https://mpv.io) via [MPVKit](https://github.com/mpvkit/MPVKit) and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
<!-- Internet access permissions -->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
|
||||
<!-- PIP Permissions -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
||||
|
||||
<!-- Media session permissions for OS media controls -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
||||
@@ -18,16 +22,21 @@
|
||||
<!-- Touchscreen not required for TV -->
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||
|
||||
<!-- Android Automotive OS support -->
|
||||
<uses-feature android:name="android.hardware.type.automotive" android:required="false" />
|
||||
|
||||
<application
|
||||
android:label="Plezy"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/ic_launcher">
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:appCategory="video">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/LaunchTheme"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
|
||||
android:hardwareAccelerated="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
package com.edde746.plezy.mpv
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.graphics.PixelFormat
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.ViewTreeObserver
|
||||
import android.view.TextureView
|
||||
import android.view.WindowManager
|
||||
import androidx.annotation.RequiresApi
|
||||
import dev.jdtech.mpv.MPVLib
|
||||
import java.math.BigDecimal
|
||||
import java.math.RoundingMode
|
||||
|
||||
interface MpvPlayerDelegate {
|
||||
fun onPropertyChange(name: String, value: Any?)
|
||||
@@ -19,10 +29,12 @@ interface MpvPlayerDelegate {
|
||||
|
||||
class MpvPlayerCore(private val activity: Activity) :
|
||||
SurfaceHolder.Callback,
|
||||
MPVLib.EventObserver {
|
||||
MPVLib.EventObserver,
|
||||
MPVLib.LogObserver {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MpvPlayerCore"
|
||||
private const val SHORT_VIDEO_LENGTH_MS = 300000L // 5 minutes
|
||||
}
|
||||
|
||||
private var surfaceView: SurfaceView? = null
|
||||
@@ -33,6 +45,11 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
var isInitialized: Boolean = false
|
||||
private set
|
||||
|
||||
// Frame rate matching
|
||||
private var currentVideoFps: Float = 0f
|
||||
private var displayListener: DisplayManager.DisplayListener? = null
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
private fun ensureFlutterOverlayOnTop() {
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
contentView.post {
|
||||
@@ -143,8 +160,9 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
// Initialize MPV
|
||||
MPVLib.init()
|
||||
|
||||
// Register event observer
|
||||
// Register event and log observers
|
||||
MPVLib.addObserver(this)
|
||||
MPVLib.addLogObserver(this)
|
||||
|
||||
isInitialized = true
|
||||
Log.d(TAG, "Initialized successfully")
|
||||
@@ -235,6 +253,28 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
}
|
||||
}
|
||||
|
||||
// MPVLib.LogObserver
|
||||
|
||||
override fun logMessage(prefix: String, level: Int, text: String) {
|
||||
val levelStr = when (level) {
|
||||
MPVLib.MPV_LOG_LEVEL_FATAL -> "fatal"
|
||||
MPVLib.MPV_LOG_LEVEL_ERROR -> "error"
|
||||
MPVLib.MPV_LOG_LEVEL_WARN -> "warn"
|
||||
MPVLib.MPV_LOG_LEVEL_INFO -> "info"
|
||||
MPVLib.MPV_LOG_LEVEL_V -> "v"
|
||||
MPVLib.MPV_LOG_LEVEL_DEBUG -> "debug"
|
||||
MPVLib.MPV_LOG_LEVEL_TRACE -> "trace"
|
||||
else -> "info"
|
||||
}
|
||||
activity.runOnUiThread {
|
||||
delegate?.onEvent("log-message", mapOf(
|
||||
"prefix" to prefix,
|
||||
"level" to levelStr,
|
||||
"text" to text
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// Public API
|
||||
|
||||
fun setProperty(name: String, value: String) {
|
||||
@@ -276,12 +316,205 @@ class MpvPlayerCore(private val activity: Activity) :
|
||||
}
|
||||
}
|
||||
|
||||
// Frame Rate Matching
|
||||
|
||||
private fun getDisplayManager(): DisplayManager {
|
||||
return activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the video frame rate for display refresh rate matching.
|
||||
* Based on VLC Android's FrameRateManager implementation.
|
||||
*/
|
||||
fun setVideoFrameRate(fps: Float, videoDurationMs: Long) {
|
||||
currentVideoFps = fps
|
||||
if (fps <= 0f) {
|
||||
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
|
||||
return
|
||||
}
|
||||
|
||||
val surface = surfaceView?.holder?.surface
|
||||
if (surface == null) {
|
||||
Log.d(TAG, "setVideoFrameRate: Surface not available")
|
||||
return
|
||||
}
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=${videoDurationMs}ms, API=${Build.VERSION.SDK_INT}")
|
||||
|
||||
when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> setFrameRateS(fps, surface, videoDurationMs)
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> setFrameRateR(fps, surface)
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> setFrameRateM(fps)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear frame rate setting and cleanup display listener.
|
||||
*/
|
||||
fun clearVideoFrameRate() {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
currentVideoFps = 0f
|
||||
displayListener?.let {
|
||||
getDisplayManager().unregisterDisplayListener(it)
|
||||
displayListener = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and register display listener for mode switch completion.
|
||||
* Resumes playback after display mode change (needed for HDMI/projectors).
|
||||
*/
|
||||
private fun registerDisplayListener() {
|
||||
displayListener?.let {
|
||||
getDisplayManager().unregisterDisplayListener(it)
|
||||
}
|
||||
|
||||
displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = Unit
|
||||
override fun onDisplayRemoved(displayId: Int) = Unit
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
// Mode switch may pause playback (HDMI), wait and resume
|
||||
handler.postDelayed({
|
||||
try {
|
||||
val isPaused = MPVLib.getPropertyBoolean("pause")
|
||||
if (isPaused) {
|
||||
Log.d(TAG, "Display changed, resuming playback")
|
||||
MPVLib.setPropertyBoolean("pause", false)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to resume playback after display change", e)
|
||||
}
|
||||
}, 2000L) // Wait 2 seconds for mode switch to complete
|
||||
getDisplayManager().unregisterDisplayListener(this)
|
||||
displayListener = null
|
||||
}
|
||||
}
|
||||
getDisplayManager().registerDisplayListener(displayListener, handler)
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.R)
|
||||
private fun setFrameRateR(fps: Float, surface: Surface) {
|
||||
Log.d(TAG, "setFrameRateR: Setting frame rate to $fps")
|
||||
surface.setFrameRate(fps, Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE)
|
||||
registerDisplayListener()
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.S)
|
||||
private fun setFrameRateS(fps: Float, surface: Surface, videoDurationMs: Long) {
|
||||
Log.d(TAG, "setFrameRateS: fps=$fps, duration=${videoDurationMs}ms")
|
||||
|
||||
// For short videos (<5min), only switch if seamless
|
||||
if (videoDurationMs < SHORT_VIDEO_LENGTH_MS) {
|
||||
Log.d(TAG, "Short video, using seamless-only switching")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// For longer videos, check if switch will be seamless
|
||||
var seamless = false
|
||||
activity.display?.mode?.alternativeRefreshRates?.let { refreshRates ->
|
||||
for (rate in refreshRates) {
|
||||
// Check if rates match or are integer multiples
|
||||
if (fps.toString().startsWith(rate.toString()) ||
|
||||
rate.toString().startsWith(fps.toString()) ||
|
||||
rate % fps == 0f) {
|
||||
seamless = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (seamless) {
|
||||
Log.d(TAG, "Seamless switch available, using CHANGE_FRAME_RATE_ALWAYS")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ALWAYS
|
||||
)
|
||||
registerDisplayListener()
|
||||
} else {
|
||||
// Non-seamless: only switch if user enabled it at OS level
|
||||
val userPreference = getDisplayManager().matchContentFrameRateUserPreference
|
||||
if (userPreference == DisplayManager.MATCH_CONTENT_FRAMERATE_ALWAYS) {
|
||||
Log.d(TAG, "User preference allows non-seamless switch")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ALWAYS
|
||||
)
|
||||
registerDisplayListener()
|
||||
} else {
|
||||
Log.d(TAG, "Non-seamless switch not allowed by user preference, using seamless-only")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setFrameRateM(fps: Float) {
|
||||
Log.d(TAG, "setFrameRateM: fps=$fps")
|
||||
val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
val display = wm.defaultDisplay ?: return
|
||||
|
||||
display.supportedModes?.let { supportedModes ->
|
||||
val currentMode = display.mode
|
||||
var modeToUse = currentMode
|
||||
|
||||
for (mode in supportedModes) {
|
||||
// Skip modes with different resolution
|
||||
if (mode.physicalHeight != currentMode.physicalHeight ||
|
||||
mode.physicalWidth != currentMode.physicalWidth) {
|
||||
continue
|
||||
}
|
||||
|
||||
Log.d(TAG, "Supported mode: ${mode.modeId} - ${mode.refreshRate}Hz")
|
||||
|
||||
// Check for exact match
|
||||
if (BigDecimal(fps.toString()).setScale(1, RoundingMode.FLOOR) ==
|
||||
BigDecimal(mode.refreshRate.toString()).setScale(1, RoundingMode.FLOOR)) {
|
||||
modeToUse = mode
|
||||
Log.d(TAG, "Found exact match: ${mode.refreshRate}Hz")
|
||||
break
|
||||
}
|
||||
// Check for integer multiple (e.g., 48Hz for 24fps)
|
||||
else if (mode.refreshRate % fps == 0f) {
|
||||
modeToUse = mode
|
||||
Log.d(TAG, "Found integer multiple: ${mode.refreshRate}Hz")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (modeToUse != currentMode) {
|
||||
Log.d(TAG, "Switching to mode ${modeToUse.modeId} (${modeToUse.refreshRate}Hz)")
|
||||
activity.window?.attributes?.let { attrs ->
|
||||
attrs.preferredDisplayModeId = modeToUse.modeId
|
||||
activity.window?.attributes = attrs
|
||||
}
|
||||
registerDisplayListener()
|
||||
} else {
|
||||
Log.d(TAG, "No better mode found, staying at ${currentMode.refreshRate}Hz")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
|
||||
fun dispose() {
|
||||
Log.d(TAG, "Disposing")
|
||||
|
||||
// Clean up frame rate listener
|
||||
clearVideoFrameRate()
|
||||
|
||||
MPVLib.removeObserver(this)
|
||||
MPVLib.removeLogObserver(this)
|
||||
|
||||
surfaceView?.holder?.removeCallback(this)
|
||||
overlayLayoutListener?.let { listener ->
|
||||
|
||||
@@ -94,6 +94,8 @@ class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
"observeProperty" -> handleObserveProperty(call, result)
|
||||
"command" -> handleCommand(call, result)
|
||||
"setVisible" -> handleSetVisible(call, result)
|
||||
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
|
||||
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
|
||||
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
@@ -202,6 +204,21 @@ class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVideoFrameRate(call: MethodCall, result: MethodChannel.Result) {
|
||||
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
|
||||
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration")
|
||||
playerCore?.setVideoFrameRate(fps, duration)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
playerCore?.clearVideoFrameRate()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
// MpvPlayerDelegate
|
||||
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
|
||||
@@ -2,11 +2,18 @@ package com.edde746.plezy
|
||||
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.res.Configuration
|
||||
import android.util.Rational
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import com.edde746.plezy.mpv.MpvPlayerPlugin
|
||||
|
||||
class MainActivity : FlutterActivity() {
|
||||
|
||||
private val PIP_CHANNEL = "app.plezy/pip"
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
@@ -20,5 +27,27 @@ class MainActivity : FlutterActivity() {
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
flutterEngine.plugins.add(MpvPlayerPlugin())
|
||||
|
||||
MethodChannel( flutterEngine.dartExecutor.binaryMessenger, PIP_CHANNEL ).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"isSupported" -> {
|
||||
result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
|
||||
}
|
||||
"enter" -> {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val width = call.argument<Int>("width") ?: 16
|
||||
val height = call.argument<Int>("height") ?: 9
|
||||
val params = PictureInPictureParams.Builder().setAspectRatio(Rational(width, height)).build()
|
||||
enterPictureInPictureMode(params)
|
||||
}
|
||||
result.success(null)
|
||||
} else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean,newConfig: Configuration) {
|
||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||
MethodChannel( flutterEngine!!.dartExecutor.binaryMessenger, PIP_CHANNEL ).invokeMethod( "onPipChanged" , isInPictureInPictureMode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
@@ -11,5 +14,8 @@
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">?android:colorBackground</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
@@ -11,5 +14,8 @@
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">?android:colorBackground</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
|
||||
@@ -32,13 +32,13 @@ platform :android do
|
||||
desc "Build release AAB"
|
||||
lane :build do
|
||||
# Navigate to Flutter project root and build
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build appbundle")
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build appbundle --dart-define=ENABLE_IN_APP_REVIEW=true")
|
||||
end
|
||||
|
||||
desc "Build and deploy to Google Play Store"
|
||||
lane :release do
|
||||
# Build the Flutter app
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build appbundle")
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build appbundle --dart-define=ENABLE_IN_APP_REVIEW=true")
|
||||
|
||||
# Get version code from pubspec.yaml
|
||||
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
|
||||
|
||||
|
Before Width: | Height: | Size: 2.7 MiB After Width: | Height: | Size: 3.8 MiB |
|
Before Width: | Height: | Size: 2.8 MiB After Width: | Height: | Size: 2.4 MiB |
|
Before Width: | Height: | Size: 1.7 MiB After Width: | Height: | Size: 2.6 MiB |
|
Before Width: | Height: | Size: 1.9 MiB After Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 3.4 MiB After Width: | Height: | Size: 4.4 MiB |
|
Before Width: | Height: | Size: 3.5 MiB After Width: | Height: | Size: 3.4 MiB |
|
Before Width: | Height: | Size: 2.5 MiB After Width: | Height: | Size: 3.0 MiB |
|
Before Width: | Height: | Size: 1.5 MiB After Width: | Height: | Size: 1.2 MiB |
@@ -1,5 +1,5 @@
|
||||
# Uncomment this line to define a global platform for your project
|
||||
# platform :ios, '13.0'
|
||||
platform :ios, '14.0'
|
||||
|
||||
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
|
||||
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
|
||||
@@ -25,6 +25,10 @@ end
|
||||
|
||||
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
|
||||
|
||||
# Disable file_picker's media picker on iOS - removes DKImagePickerController dependency
|
||||
# This app only uses file_picker for directory selection on desktop
|
||||
Pod.const_set(:PICKER_MEDIA, false) unless Pod.const_defined?(:PICKER_MEDIA)
|
||||
|
||||
flutter_ios_podfile_setup
|
||||
|
||||
target 'Runner' do
|
||||
|
||||
@@ -3,46 +3,16 @@ PODS:
|
||||
- Flutter
|
||||
- device_info_plus (0.0.1):
|
||||
- Flutter
|
||||
- DKImagePickerController/Core (4.3.9):
|
||||
- DKImagePickerController/ImageDataManager
|
||||
- DKImagePickerController/Resource
|
||||
- DKImagePickerController/ImageDataManager (4.3.9)
|
||||
- DKImagePickerController/PhotoGallery (4.3.9):
|
||||
- DKImagePickerController/Core
|
||||
- DKPhotoGallery
|
||||
- DKImagePickerController/Resource (4.3.9)
|
||||
- DKPhotoGallery (0.0.19):
|
||||
- DKPhotoGallery/Core (= 0.0.19)
|
||||
- DKPhotoGallery/Model (= 0.0.19)
|
||||
- DKPhotoGallery/Preview (= 0.0.19)
|
||||
- DKPhotoGallery/Resource (= 0.0.19)
|
||||
- SDWebImage
|
||||
- SwiftyGif
|
||||
- DKPhotoGallery/Core (0.0.19):
|
||||
- DKPhotoGallery/Model
|
||||
- DKPhotoGallery/Preview
|
||||
- SDWebImage
|
||||
- SwiftyGif
|
||||
- DKPhotoGallery/Model (0.0.19):
|
||||
- SDWebImage
|
||||
- SwiftyGif
|
||||
- DKPhotoGallery/Preview (0.0.19):
|
||||
- DKPhotoGallery/Model
|
||||
- DKPhotoGallery/Resource
|
||||
- SDWebImage
|
||||
- SwiftyGif
|
||||
- DKPhotoGallery/Resource (0.0.19):
|
||||
- SDWebImage
|
||||
- SwiftyGif
|
||||
- file_picker (0.0.1):
|
||||
- DKImagePickerController/PhotoGallery
|
||||
- Flutter
|
||||
- Flutter (1.0.0)
|
||||
- flutter_webrtc (0.11.3):
|
||||
- flutter_webrtc (1.2.0):
|
||||
- Flutter
|
||||
- WebRTC-SDK (= 125.6422.04)
|
||||
- WebRTC-SDK (= 137.7151.04)
|
||||
- gamepads_ios (0.1.1):
|
||||
- Flutter
|
||||
- in_app_review (2.0.0):
|
||||
- Flutter
|
||||
- os_media_controls (0.0.1):
|
||||
- Flutter
|
||||
- package_info_plus (0.4.5):
|
||||
@@ -50,11 +20,6 @@ PODS:
|
||||
- path_provider_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- SDWebImage (5.21.3):
|
||||
- SDWebImage/Core (= 5.21.3)
|
||||
- SDWebImage/Core (5.21.3)
|
||||
- share_plus (0.0.1):
|
||||
- Flutter
|
||||
- shared_preferences_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
@@ -86,12 +51,11 @@ PODS:
|
||||
- sqlite3/perf-threadsafe
|
||||
- sqlite3/rtree
|
||||
- sqlite3/session
|
||||
- SwiftyGif (5.4.5)
|
||||
- url_launcher_ios (0.0.1):
|
||||
- Flutter
|
||||
- wakelock_plus (0.0.1):
|
||||
- Flutter
|
||||
- WebRTC-SDK (125.6422.04)
|
||||
- WebRTC-SDK (137.7151.04)
|
||||
- workmanager_apple (0.0.1):
|
||||
- Flutter
|
||||
|
||||
@@ -102,10 +66,10 @@ DEPENDENCIES:
|
||||
- Flutter (from `Flutter`)
|
||||
- flutter_webrtc (from `.symlinks/plugins/flutter_webrtc/ios`)
|
||||
- gamepads_ios (from `.symlinks/plugins/gamepads_ios/ios`)
|
||||
- in_app_review (from `.symlinks/plugins/in_app_review/ios`)
|
||||
- os_media_controls (from `.symlinks/plugins/os_media_controls/ios`)
|
||||
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
|
||||
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
|
||||
- share_plus (from `.symlinks/plugins/share_plus/ios`)
|
||||
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||
- sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`)
|
||||
- sqlite3_flutter_libs (from `.symlinks/plugins/sqlite3_flutter_libs/darwin`)
|
||||
@@ -115,11 +79,7 @@ DEPENDENCIES:
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- DKImagePickerController
|
||||
- DKPhotoGallery
|
||||
- SDWebImage
|
||||
- sqlite3
|
||||
- SwiftyGif
|
||||
- WebRTC-SDK
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
@@ -135,14 +95,14 @@ EXTERNAL SOURCES:
|
||||
:path: ".symlinks/plugins/flutter_webrtc/ios"
|
||||
gamepads_ios:
|
||||
:path: ".symlinks/plugins/gamepads_ios/ios"
|
||||
in_app_review:
|
||||
:path: ".symlinks/plugins/in_app_review/ios"
|
||||
os_media_controls:
|
||||
:path: ".symlinks/plugins/os_media_controls/ios"
|
||||
package_info_plus:
|
||||
:path: ".symlinks/plugins/package_info_plus/ios"
|
||||
path_provider_foundation:
|
||||
:path: ".symlinks/plugins/path_provider_foundation/darwin"
|
||||
share_plus:
|
||||
:path: ".symlinks/plugins/share_plus/ios"
|
||||
shared_preferences_foundation:
|
||||
:path: ".symlinks/plugins/shared_preferences_foundation/darwin"
|
||||
sqflite_darwin:
|
||||
@@ -159,27 +119,23 @@ EXTERNAL SOURCES:
|
||||
SPEC CHECKSUMS:
|
||||
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
|
||||
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
|
||||
DKImagePickerController: 946cec48c7873164274ecc4624d19e3da4c1ef3c
|
||||
DKPhotoGallery: b3834fecb755ee09a593d7c9e389d8b5d6deed60
|
||||
file_picker: a0560bc09d61de87f12d246fc47d2119e6ef37be
|
||||
file_picker: 8fc6fe5e42585a217d44d22f79ec046cb8d81140
|
||||
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
|
||||
flutter_webrtc: 89f078a5050779eaa4a6a4f472954737bb91f39f
|
||||
flutter_webrtc: c3e21fc0dcd9d8eb246ae4d5256fcbeb2f5ecd22
|
||||
gamepads_ios: c75c6d31377d275b0effb9174c619e2705678c09
|
||||
in_app_review: 7dd1ea365263f834b8464673f9df72c80c17c937
|
||||
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
|
||||
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
|
||||
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
|
||||
SDWebImage: 16309af6d214ba3f77a7c6f6fdda888cb313a50a
|
||||
share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
|
||||
sqlite3: 8d708bc63e9f4ce48f0ad9d6269e478c5ced1d9b
|
||||
sqlite3_flutter_libs: d13b8b3003f18f596e542bcb9482d105577eff41
|
||||
SwiftyGif: 706c60cf65fa2bc5ee0313beece843c8eb8194d4
|
||||
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
|
||||
wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
|
||||
WebRTC-SDK: c3d69a87e7185fad3568f6f3cff7c9ac5890acf3
|
||||
WebRTC-SDK: 40d4f5ba05cadff14e4db5614aec402a633f007e
|
||||
workmanager_apple: 904529ae31e97fc5be632cf628507652294a0778
|
||||
|
||||
PODFILE CHECKSUM: 3c63482e143d1b91d2d2560aee9fb04ecc74ac7e
|
||||
PODFILE CHECKSUM: faeab82d8b6e3c9d039ddf62b7666988a3dea540
|
||||
|
||||
COCOAPODS: 1.16.2
|
||||
|
||||
@@ -39,6 +39,8 @@
|
||||
</array>
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>This app needs to connect to your Plex Media Server on your local network.</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Camera access is included by the WebRTC library used for Watch Together, but is not actively used by this app.</string>
|
||||
<key>UIApplicationSupportsIndirectInputEvents</key>
|
||||
<true/>
|
||||
<key>UIFileSharingEnabled</key>
|
||||
|
||||
@@ -49,6 +49,7 @@ class MpvPlayerCore: NSObject {
|
||||
weak var delegate: MpvPlayerDelegate?
|
||||
|
||||
private(set) var isInitialized = false
|
||||
private var isDisposing = false // Flag to prevent race conditions during disposal
|
||||
|
||||
// HDR settings
|
||||
private var hdrEnabled = true // User preference for HDR
|
||||
@@ -147,7 +148,8 @@ class MpvPlayerCore: NSObject {
|
||||
mpv_set_wakeup_callback(
|
||||
mpv,
|
||||
{ ctx in
|
||||
let core = Unmanaged<MpvPlayerCore>.fromOpaque(ctx!).takeUnretainedValue()
|
||||
guard let ctx = ctx else { return } // Safe guard instead of force unwrap
|
||||
let core = Unmanaged<MpvPlayerCore>.fromOpaque(ctx).takeUnretainedValue()
|
||||
core.readEvents()
|
||||
}, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
|
||||
|
||||
@@ -308,7 +310,7 @@ class MpvPlayerCore: NSObject {
|
||||
|
||||
private func readEvents() {
|
||||
queue.async { [weak self] in
|
||||
guard let self = self, let mpv = self.mpv else { return }
|
||||
guard let self = self, !self.isDisposing, let mpv = self.mpv else { return }
|
||||
|
||||
while true {
|
||||
let event = mpv_wait_event(mpv, 0)
|
||||
@@ -344,13 +346,24 @@ class MpvPlayerCore: NSObject {
|
||||
case MPV_EVENT_SHUTDOWN:
|
||||
print("[MpvPlayerCore] MPV shutdown event")
|
||||
|
||||
case MPV_EVENT_PLAYBACK_RESTART:
|
||||
DispatchQueue.main.async {
|
||||
self.delegate?.onEvent(name: "playback-restart", data: nil)
|
||||
}
|
||||
|
||||
case MPV_EVENT_LOG_MESSAGE:
|
||||
if let msgPtr = event.data?.assumingMemoryBound(to: mpv_event_log_message.self) {
|
||||
let msg = msgPtr.pointee
|
||||
if let prefix = msg.prefix, let level = msg.level, let text = msg.text {
|
||||
print(
|
||||
"[MPV:\(String(cString: prefix))] \(String(cString: level)): \(String(cString: text))",
|
||||
terminator: "")
|
||||
let prefix = msg.prefix.map { String(cString: $0) } ?? ""
|
||||
let level = msg.level.map { String(cString: $0) } ?? ""
|
||||
let text = msg.text.map { String(cString: $0) } ?? ""
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.delegate?.onEvent(name: "log-message", data: [
|
||||
"prefix": prefix,
|
||||
"level": level,
|
||||
"text": text
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,12 +489,16 @@ class MpvPlayerCore: NSObject {
|
||||
// MARK: - Cleanup
|
||||
|
||||
func dispose() {
|
||||
// Set disposing flag first to prevent race conditions with event callbacks
|
||||
isDisposing = true
|
||||
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
|
||||
let mpvHandle = mpv
|
||||
mpv = nil
|
||||
|
||||
queue.sync {
|
||||
// Use async to avoid blocking the main thread (prevents deadlock)
|
||||
queue.async {
|
||||
if let handle = mpvHandle {
|
||||
mpv_set_wakeup_callback(handle, nil, nil)
|
||||
mpv_terminate_destroy(handle)
|
||||
|
||||
@@ -19,13 +19,13 @@ platform :ios do
|
||||
desc "Build release IPA"
|
||||
lane :build do
|
||||
# Navigate to Flutter project root and build
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true")
|
||||
end
|
||||
|
||||
desc "Build and deploy to TestFlight"
|
||||
lane :deploy_testflight do
|
||||
# Build the Flutter app
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true")
|
||||
|
||||
# Upload to TestFlight
|
||||
upload_to_testflight(
|
||||
@@ -36,7 +36,7 @@ platform :ios do
|
||||
desc "Build and deploy to App Store"
|
||||
lane :deploy_appstore do
|
||||
# Build the Flutter app
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true")
|
||||
|
||||
# Upload to App Store
|
||||
upload_to_app_store(
|
||||
|
||||
@@ -197,8 +197,29 @@ class AppDatabase extends _$AppDatabase {
|
||||
|
||||
LazyDatabase _openConnection() {
|
||||
return LazyDatabase(() async {
|
||||
final dbFolder = await getApplicationDocumentsDirectory();
|
||||
final Directory dbFolder;
|
||||
if (Platform.isAndroid || Platform.isIOS) {
|
||||
dbFolder = await getApplicationDocumentsDirectory();
|
||||
} else {
|
||||
dbFolder = await getApplicationSupportDirectory();
|
||||
}
|
||||
|
||||
final file = File(p.join(dbFolder.path, 'plezy_downloads.db'));
|
||||
|
||||
// Ensure directory exists
|
||||
if (!await file.parent.exists()) {
|
||||
await file.parent.create(recursive: true);
|
||||
}
|
||||
|
||||
// Migrate from old location on desktop (was in Documents subfolder)
|
||||
if (!Platform.isAndroid && !Platform.isIOS && !await file.exists()) {
|
||||
final oldFolder = await getApplicationDocumentsDirectory();
|
||||
final oldFile = File(p.join(oldFolder.path, 'plezy_downloads.db'));
|
||||
if (await oldFile.exists()) {
|
||||
await oldFile.rename(file.path);
|
||||
}
|
||||
}
|
||||
|
||||
return NativeDatabase(file);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -95,6 +95,13 @@ class _InputModeTrackerState extends State<InputModeTracker> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// On Android TV, don't switch to pointer mode from pointer events
|
||||
// as D-pad can generate synthetic pointer events that would incorrectly
|
||||
// trigger pointer mode and show a cursor instead of D-pad focus navigation
|
||||
if (TvDetectionService.isTVSync()) {
|
||||
return _InputModeProvider(mode: _mode, child: widget.child);
|
||||
}
|
||||
|
||||
return Listener(
|
||||
// Switch to pointer mode on mouse activity
|
||||
onPointerDown: (_) => _setMode(InputMode.pointer),
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
"licenses": "Licenses",
|
||||
"switchProfile": "Switch Profile",
|
||||
"subtitleStyling": "Subtitle Styling",
|
||||
"mpvConfig": "MPV Configuration",
|
||||
"search": "Search",
|
||||
"logs": "Logs"
|
||||
},
|
||||
@@ -58,7 +59,13 @@
|
||||
"appearance": "Appearance",
|
||||
"videoPlayback": "Video Playback",
|
||||
"advanced": "Advanced",
|
||||
"useSeasonPostersDescription": "Show season poster instead of series poster for episodes",
|
||||
"episodePosterMode": "Episode Poster Style",
|
||||
"seriesPoster": "Series Poster",
|
||||
"seriesPosterDescription": "Show the series poster for all episodes",
|
||||
"seasonPoster": "Season Poster",
|
||||
"seasonPosterDescription": "Show the season-specific poster for episodes",
|
||||
"episodeThumbnail": "Episode Thumbnail",
|
||||
"episodeThumbnailDescription": "Show 16:9 episode screenshot thumbnails",
|
||||
"showHeroSectionDescription": "Display featured content carousel on home screen",
|
||||
"secondsLabel": "Seconds",
|
||||
"minutesLabel": "Minutes",
|
||||
@@ -81,8 +88,9 @@
|
||||
"gridViewDescription": "Display items in a grid layout",
|
||||
"listView": "List",
|
||||
"listViewDescription": "Display items in a list layout",
|
||||
"useSeasonPosters": "Use Season Posters",
|
||||
"showHeroSection": "Show Hero Section",
|
||||
"useGlobalHubs": "Use Plex Home Layout",
|
||||
"useGlobalHubsDescription": "Show home page hubs like the official Plex client. When off, shows per-library recommendations instead.",
|
||||
"hardwareDecoding": "Hardware Decoding",
|
||||
"hardwareDecodingDescription": "Use hardware acceleration when available",
|
||||
"bufferSize": "Buffer Size",
|
||||
@@ -141,7 +149,15 @@
|
||||
"downloadLocationSelectError": "Failed to select folder",
|
||||
"downloadOnWifiOnly": "Download on WiFi only",
|
||||
"downloadOnWifiOnlyDescription": "Prevent downloads when on cellular data",
|
||||
"cellularDownloadBlocked": "Downloads are disabled on cellular data. Connect to WiFi or change the setting."
|
||||
"cellularDownloadBlocked": "Downloads are disabled on cellular data. Connect to WiFi or change the setting.",
|
||||
"maxVolume": "Maximum Volume",
|
||||
"maxVolumeDescription": "Allow volume boost above 100% for quiet media",
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Enter max volume (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Show what you're watching on Discord",
|
||||
"matchContentFrameRate": "Match Content Frame Rate",
|
||||
"matchContentFrameRateDescription": "Adjust display refresh rate to match video content, reducing judder and saving battery"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Search movies, shows, music...",
|
||||
@@ -240,6 +256,7 @@
|
||||
"subtitlesButton": "Subtitles",
|
||||
"chaptersButton": "Chapters",
|
||||
"versionsButton": "Video versions",
|
||||
"pipButton": "Picture-in-Picture mode",
|
||||
"aspectRatioButton": "Aspect ratio",
|
||||
"fullscreenButton": "Enter fullscreen",
|
||||
"exitFullscreenButton": "Exit fullscreen",
|
||||
@@ -296,6 +313,32 @@
|
||||
"backgroundOpacity": "Background Opacity",
|
||||
"backgroundColor": "Background Color"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "MPV Configuration",
|
||||
"description": "Advanced video player settings",
|
||||
"properties": "Properties",
|
||||
"presets": "Presets",
|
||||
"noProperties": "No properties configured",
|
||||
"noPresets": "No saved presets",
|
||||
"addProperty": "Add Property",
|
||||
"editProperty": "Edit Property",
|
||||
"deleteProperty": "Delete Property",
|
||||
"propertyKey": "Property Key",
|
||||
"propertyKeyHint": "e.g., hwdec, demuxer-max-bytes",
|
||||
"propertyValue": "Property Value",
|
||||
"propertyValueHint": "e.g., auto, 256000000",
|
||||
"saveAsPreset": "Save as Preset...",
|
||||
"presetName": "Preset Name",
|
||||
"presetNameHint": "Enter a name for this preset",
|
||||
"loadPreset": "Load",
|
||||
"deletePreset": "Delete",
|
||||
"presetSaved": "Preset saved",
|
||||
"presetLoaded": "Preset loaded",
|
||||
"presetDeleted": "Preset deleted",
|
||||
"confirmDeletePreset": "Are you sure you want to delete this preset?",
|
||||
"confirmDeleteProperty": "Are you sure you want to delete this property?",
|
||||
"entriesCount": "${count} entries"
|
||||
},
|
||||
"dialog": {
|
||||
"confirmAction": "Confirm Action",
|
||||
"cancel": "Cancel",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"selectServer": "Server auswählen",
|
||||
"switchProfile": "Profil wechseln",
|
||||
"subtitleStyling": "Untertitel-Stil",
|
||||
"mpvConfig": "MPV-Konfiguration",
|
||||
"search": "Suche",
|
||||
"logs": "Protokolle"
|
||||
},
|
||||
@@ -59,7 +60,13 @@
|
||||
"appearance": "Darstellung",
|
||||
"videoPlayback": "Videowiedergabe",
|
||||
"advanced": "Erweitert",
|
||||
"useSeasonPostersDescription": "Staffelposter statt Serienposter für Episoden anzeigen",
|
||||
"episodePosterMode": "Episoden-Poster-Stil",
|
||||
"seriesPoster": "Serienposter",
|
||||
"seriesPosterDescription": "Zeige das Serienposter für alle Episoden",
|
||||
"seasonPoster": "Staffelposter",
|
||||
"seasonPosterDescription": "Zeige das staffelspezifische Poster für Episoden",
|
||||
"episodeThumbnail": "Episoden-Miniatur",
|
||||
"episodeThumbnailDescription": "Zeige 16:9 Episoden-Vorschaubilder",
|
||||
"showHeroSectionDescription": "Bereich mit empfohlenen Inhalten auf der Startseite anzeigen",
|
||||
"secondsLabel": "Sekunden",
|
||||
"minutesLabel": "Minuten",
|
||||
@@ -82,8 +89,9 @@
|
||||
"gridViewDescription": "Elemente im Raster anzeigen",
|
||||
"listView": "Liste",
|
||||
"listViewDescription": "Elemente in Listenansicht anzeigen",
|
||||
"useSeasonPosters": "Staffelposter verwenden",
|
||||
"showHeroSection": "Hero-Bereich anzeigen",
|
||||
"useGlobalHubs": "Plex-Startseiten-Layout verwenden",
|
||||
"useGlobalHubsDescription": "Zeigt Startseiten-Hubs wie der offizielle Plex-Client. Wenn deaktiviert, werden stattdessen Empfehlungen pro Bibliothek angezeigt.",
|
||||
"hardwareDecoding": "Hardware-Decodierung",
|
||||
"hardwareDecodingDescription": "Hardwarebeschleunigung verwenden, sofern verfügbar",
|
||||
"bufferSize": "Puffergröße",
|
||||
@@ -142,7 +150,15 @@
|
||||
"downloadLocationSelectError": "Ordnerauswahl fehlgeschlagen",
|
||||
"downloadOnWifiOnly": "Nur über WLAN herunterladen",
|
||||
"downloadOnWifiOnlyDescription": "Downloads über mobile Daten verhindern",
|
||||
"cellularDownloadBlocked": "Downloads sind über mobile Daten deaktiviert. Verbinde dich mit einem WLAN oder ändere die Einstellung."
|
||||
"cellularDownloadBlocked": "Downloads sind über mobile Daten deaktiviert. Verbinde dich mit einem WLAN oder ändere die Einstellung.",
|
||||
"maxVolume": "Maximale Lautstärke",
|
||||
"maxVolumeDescription": "Lautstärke über 100% für leise Medien erlauben",
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Maximale Lautstärke eingeben (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Zeige auf Discord, was du gerade schaust",
|
||||
"matchContentFrameRate": "Inhalts-Bildrate anpassen",
|
||||
"matchContentFrameRateDescription": "Bildwiederholfrequenz des Displays an den Videoinhalt anpassen, reduziert Ruckeln und spart Akku"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Filme, Serien, Musik suchen...",
|
||||
@@ -241,6 +257,7 @@
|
||||
"subtitlesButton": "Untertitel",
|
||||
"chaptersButton": "Kapitel",
|
||||
"versionsButton": "Videoversionen",
|
||||
"pipButton": "Bild-in-Bild Modus",
|
||||
"aspectRatioButton": "Seitenverhältnis",
|
||||
"fullscreenButton": "Vollbild aktivieren",
|
||||
"exitFullscreenButton": "Vollbild verlassen",
|
||||
@@ -297,6 +314,32 @@
|
||||
"backgroundOpacity": "Hintergrunddeckkraft",
|
||||
"backgroundColor": "Hintergrundfarbe"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "MPV-Konfiguration",
|
||||
"description": "Erweiterte Videoplayer-Einstellungen",
|
||||
"properties": "Eigenschaften",
|
||||
"presets": "Voreinstellungen",
|
||||
"noProperties": "Keine Eigenschaften konfiguriert",
|
||||
"noPresets": "Keine gespeicherten Voreinstellungen",
|
||||
"addProperty": "Eigenschaft hinzufügen",
|
||||
"editProperty": "Eigenschaft bearbeiten",
|
||||
"deleteProperty": "Eigenschaft löschen",
|
||||
"propertyKey": "Eigenschaftsschlüssel",
|
||||
"propertyKeyHint": "z.B. hwdec, demuxer-max-bytes",
|
||||
"propertyValue": "Eigenschaftswert",
|
||||
"propertyValueHint": "z.B. auto, 256000000",
|
||||
"saveAsPreset": "Als Voreinstellung speichern...",
|
||||
"presetName": "Name der Voreinstellung",
|
||||
"presetNameHint": "Namen für diese Voreinstellung eingeben",
|
||||
"loadPreset": "Laden",
|
||||
"deletePreset": "Löschen",
|
||||
"presetSaved": "Voreinstellung gespeichert",
|
||||
"presetLoaded": "Voreinstellung geladen",
|
||||
"presetDeleted": "Voreinstellung gelöscht",
|
||||
"confirmDeletePreset": "Möchten Sie diese Voreinstellung wirklich löschen?",
|
||||
"confirmDeleteProperty": "Möchten Sie diese Eigenschaft wirklich löschen?",
|
||||
"entriesCount": "${count} Einträge"
|
||||
},
|
||||
"dialog": {
|
||||
"confirmAction": "Aktion bestätigen",
|
||||
"cancel": "Abbrechen",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"selectServer": "Seleziona server",
|
||||
"switchProfile": "Cambia profilo",
|
||||
"subtitleStyling": "Stile sottotitoli",
|
||||
"mpvConfig": "Configurazione MPV",
|
||||
"search": "Cerca",
|
||||
"logs": "Registro"
|
||||
},
|
||||
@@ -59,7 +60,13 @@
|
||||
"appearance": "Aspetto",
|
||||
"videoPlayback": "Riproduzione video",
|
||||
"advanced": "Avanzate",
|
||||
"useSeasonPostersDescription": "Mostra il poster della stagione invece del poster della serie per gli episodi",
|
||||
"episodePosterMode": "Stile poster episodio",
|
||||
"seriesPoster": "Poster della serie",
|
||||
"seriesPosterDescription": "Mostra il poster della serie per tutti gli episodi",
|
||||
"seasonPoster": "Poster della stagione",
|
||||
"seasonPosterDescription": "Mostra il poster specifico della stagione per gli episodi",
|
||||
"episodeThumbnail": "Miniatura episodio",
|
||||
"episodeThumbnailDescription": "Mostra miniature 16:9 degli episodi",
|
||||
"showHeroSectionDescription": "Visualizza il carosello dei contenuti in primo piano sulla schermata iniziale",
|
||||
"secondsLabel": "Secondi",
|
||||
"minutesLabel": "Minuti",
|
||||
@@ -82,8 +89,9 @@
|
||||
"gridViewDescription": "Visualizza gli elementi in un layout a griglia",
|
||||
"listView": "Elenco",
|
||||
"listViewDescription": "Visualizza gli elementi in un layout a elenco",
|
||||
"useSeasonPosters": "Usa poster delle stagioni",
|
||||
"showHeroSection": "Mostra sezione principale",
|
||||
"useGlobalHubs": "Usa layout Home di Plex",
|
||||
"useGlobalHubsDescription": "Mostra gli hub della home page come il client Plex ufficiale. Se disattivato, mostra invece i suggerimenti per libreria.",
|
||||
"hardwareDecoding": "Decodifica Hardware",
|
||||
"hardwareDecodingDescription": "Utilizza l'accelerazione hardware quando disponibile",
|
||||
"bufferSize": "Dimensione buffer",
|
||||
@@ -142,7 +150,15 @@
|
||||
"downloadLocationSelectError": "Impossibile selezionare la cartella",
|
||||
"downloadOnWifiOnly": "Scarica solo con WiFi",
|
||||
"downloadOnWifiOnlyDescription": "Impedisci i download quando si utilizza la rete dati cellulare",
|
||||
"cellularDownloadBlocked": "I download sono disabilitati sulla rete dati cellulare. Connettiti al WiFi o modifica l'impostazione."
|
||||
"cellularDownloadBlocked": "I download sono disabilitati sulla rete dati cellulare. Connettiti al WiFi o modifica l'impostazione.",
|
||||
"maxVolume": "Volume massimo",
|
||||
"maxVolumeDescription": "Consenti volume superiore al 100% per contenuti audio bassi",
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Inserisci volume massimo (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Mostra su Discord cosa stai guardando",
|
||||
"matchContentFrameRate": "Adatta frequenza fotogrammi",
|
||||
"matchContentFrameRateDescription": "Regola la frequenza di aggiornamento del display in base al contenuto video, riducendo i tremolii e risparmiando batteria"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Cerca film. spettacoli, musica...",
|
||||
@@ -241,6 +257,7 @@
|
||||
"subtitlesButton": "Sottotitoli",
|
||||
"chaptersButton": "Capitoli",
|
||||
"versionsButton": "Versioni video",
|
||||
"pipButton": "Modalità Picture-in-Picture",
|
||||
"aspectRatioButton": "Proporzioni",
|
||||
"fullscreenButton": "Attiva schermo intero",
|
||||
"exitFullscreenButton": "Esci da schermo intero",
|
||||
@@ -297,6 +314,32 @@
|
||||
"backgroundOpacity": "Opacità sfondo",
|
||||
"backgroundColor": "Colore sfondo"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "Configurazione MPV",
|
||||
"description": "Impostazioni avanzate del lettore video",
|
||||
"properties": "Proprietà",
|
||||
"presets": "Preset",
|
||||
"noProperties": "Nessuna proprietà configurata",
|
||||
"noPresets": "Nessun preset salvato",
|
||||
"addProperty": "Aggiungi proprietà",
|
||||
"editProperty": "Modifica proprietà",
|
||||
"deleteProperty": "Elimina proprietà",
|
||||
"propertyKey": "Chiave proprietà",
|
||||
"propertyKeyHint": "es. hwdec, demuxer-max-bytes",
|
||||
"propertyValue": "Valore proprietà",
|
||||
"propertyValueHint": "es. auto, 256000000",
|
||||
"saveAsPreset": "Salva come preset...",
|
||||
"presetName": "Nome preset",
|
||||
"presetNameHint": "Inserisci un nome per questo preset",
|
||||
"loadPreset": "Carica",
|
||||
"deletePreset": "Elimina",
|
||||
"presetSaved": "Preset salvato",
|
||||
"presetLoaded": "Preset caricato",
|
||||
"presetDeleted": "Preset eliminato",
|
||||
"confirmDeletePreset": "Sei sicuro di voler eliminare questo preset?",
|
||||
"confirmDeleteProperty": "Sei sicuro di voler eliminare questa proprietà?",
|
||||
"entriesCount": "${count} voci"
|
||||
},
|
||||
"dialog": {
|
||||
"confirmAction": "Conferma azione",
|
||||
"cancel": "Cancella",
|
||||
|
||||
@@ -0,0 +1,587 @@
|
||||
{
|
||||
"app": {
|
||||
"title": "Plezy",
|
||||
"loading": "로딩 중..."
|
||||
},
|
||||
"auth": {
|
||||
"signInWithPlex": "Plex 계정으로 로그인",
|
||||
"showQRCode": "QR 코드",
|
||||
"cancel": "취소",
|
||||
"authenticate": "인증",
|
||||
"retry": "재시도",
|
||||
"debugEnterToken": "디버깅을 위해 Plex 토큰을 입력하세요.",
|
||||
"plexTokenLabel": "Plex 인증 토큰",
|
||||
"plexTokenHint": "Plex.tv 토큰을 입력하세요",
|
||||
"authenticationTimeout": "인증 시간이 초과되었습니다. 다시 시도해 주세요.",
|
||||
"scanQRCodeInstruction": "Plex 계정에 로그인된 기기에서 이 QR 코드를 스캔하여 본인 인증을 해주세요.",
|
||||
"waitingForAuth": "인증 대기 중... 브라우저에서 로그인을 완료해 주세요."
|
||||
},
|
||||
"common": {
|
||||
"cancel": "취소",
|
||||
"save": "저장",
|
||||
"close": "닫기",
|
||||
"clear": "지우기",
|
||||
"reset": "초기화",
|
||||
"later": "나중에",
|
||||
"submit": "보내기",
|
||||
"confirm": "확인",
|
||||
"retry": "재시도",
|
||||
"logout": "로그아웃",
|
||||
"unknown": "알 수 없는",
|
||||
"refresh": "새로고침",
|
||||
"yes": "예",
|
||||
"no": "아니오",
|
||||
"delete": "삭제",
|
||||
"shuffle": "무작위 재생",
|
||||
"addTo": "추가하기..."
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "라이선스",
|
||||
"selectServer": "서버 선택",
|
||||
"switchProfile": "프로필 전환",
|
||||
"subtitleStyling": "자막 스타일 설정",
|
||||
"mpvConfig": "MPV 설정",
|
||||
"search": "검색",
|
||||
"logs": "로그"
|
||||
},
|
||||
"update": {
|
||||
"available": "사용 가능한 업데이트",
|
||||
"versionAvailable": "버전 ${version} 출시됨",
|
||||
"currentVersion": "현재 버전: ${version}",
|
||||
"skipVersion": "이 버전 건너뛰기",
|
||||
"viewRelease": "릴리스 정보 보기",
|
||||
"latestVersion": "최신 버전을 사용 중입니다",
|
||||
"checkFailed": "업데이트 확인 실패"
|
||||
},
|
||||
"settings": {
|
||||
"title": "설정",
|
||||
"language": "언어",
|
||||
"theme": "테마",
|
||||
"appearance": "외관",
|
||||
"videoPlayback": "비디오 재생",
|
||||
"advanced": "고급",
|
||||
"episodePosterMode": "에피소드 포스터 스타일",
|
||||
"seriesPoster": "시리즈 포스터",
|
||||
"seriesPosterDescription": "모든 에피소드에 시리즈 포스터 표시",
|
||||
"seasonPoster": "시즌 포스터",
|
||||
"seasonPosterDescription": "에피소드에 시즌별 포스터 표시",
|
||||
"episodeThumbnail": "에피소드 썸네일",
|
||||
"episodeThumbnailDescription": "16:9 에피소드 스크린샷 썸네일 표시",
|
||||
"showHeroSectionDescription": "홈 화면에 주요 콘텐츠 캐러셀(슬라이드) 표시",
|
||||
"secondsLabel": "초",
|
||||
"minutesLabel": "분",
|
||||
"secondsShort": "초",
|
||||
"minutesShort": "분",
|
||||
"durationHint": "기간 입력 (${min}-${max})",
|
||||
"systemTheme": "시스템 설정",
|
||||
"systemThemeDescription": "시스템 설정에 따름",
|
||||
"lightTheme": "라이트 모드",
|
||||
"darkTheme": "다크 모드",
|
||||
"libraryDensity": "라이브러리 표시 밀도",
|
||||
"compact": "좁게",
|
||||
"compactDescription": "카드를 작게 표시하여 더 많은 항목을 보여줍니다.",
|
||||
"normal": "보통",
|
||||
"normalDescription": "기본 크기",
|
||||
"comfortable": "넓게",
|
||||
"comfortableDescription": "카드를 크게 표시하여 더 적은 항목을 보여줍니다.",
|
||||
"viewMode": "보기 모드",
|
||||
"gridView": "그리드 보기",
|
||||
"gridViewDescription": "항목을 그리드 레이아웃으로 표시합니다",
|
||||
"listView": "목록 보기",
|
||||
"listViewDescription": "항목을 목록 레이아웃으로 표시합니다",
|
||||
"showHeroSection": "주요 추천 영역 표시",
|
||||
"useGlobalHubs": "Plex 홈 레이아웃 사용",
|
||||
"useGlobalHubsDescription": "공식 Plex 클라이언트처럼 홈 페이지 허브를 표시합니다. 끄면 라이브러리별 추천이 대신 표시됩니다.",
|
||||
"hardwareDecoding": "하드웨어 디코딩",
|
||||
"hardwareDecodingDescription": "가능한 경우 하드웨어 가속을 사용합니다",
|
||||
"bufferSize": "버퍼 크기",
|
||||
"bufferSizeMB": "${size}MB",
|
||||
"subtitleStyling": "자막 스타일",
|
||||
"subtitleStylingDescription": "자막의 외형을 사용자 설정",
|
||||
"smallSkipDuration": "짧은 건너뛰기 시간",
|
||||
"largeSkipDuration": "긴 건너뛰기 시간",
|
||||
"secondsUnit": "${seconds}초",
|
||||
"defaultSleepTimer": "기본 취침 타이머",
|
||||
"minutesUnit": "${minutes}분",
|
||||
"rememberTrackSelections": "에피소드/영화별 트랙 선택 기억",
|
||||
"rememberTrackSelectionsDescription": "재생 중 트랙을 변경할 때 오디오 및 자막 언어 설정을 자동으로 저장합니다",
|
||||
"videoPlayerControls": "비디오 플레이어 컨트롤",
|
||||
"keyboardShortcuts": "키보드 단축키",
|
||||
"keyboardShortcutsDescription": "사용자 정의 키보드 단축키",
|
||||
"videoPlayerNavigation": "비디오 플레이어 탐색",
|
||||
"videoPlayerNavigationDescription": "방향 키를 사용하여 비디오 플레이어 컨트롤 탐색",
|
||||
"debugLogging": "디버그 로깅",
|
||||
"debugLoggingDescription": "문제 해결을 위해 상세 로깅 활성화",
|
||||
"viewLogs": "로그 보기",
|
||||
"viewLogsDescription": "애플리케이션 로그 확인",
|
||||
"clearCache": "캐시 삭제",
|
||||
"clearCacheDescription": "모든 캐시된 이미지와 데이터를 지웁니다. 캐시를 지우면 애플리케이션 콘텐츠 로딩 속도가 느려질 수 있습니다.",
|
||||
"clearCacheSuccess": "캐시 삭제 성공",
|
||||
"resetSettings": "설정 재설정",
|
||||
"resetSettingsDescription": "모든 설정을 기본값으로 재설정합니다. 이 작업은 되돌릴 수 없습니다.",
|
||||
"resetSettingsSuccess": "설정 재설정 성공",
|
||||
"shortcutsReset": "단축키가 기본값으로 재설정되었습니다",
|
||||
"about": "정보",
|
||||
"aboutDescription": "응용 프로그램 정보 및 라이선스",
|
||||
"updates": "업데이트",
|
||||
"updateAvailable": "사용 가능한 업데이트 있음",
|
||||
"checkForUpdates": "업데이트 확인",
|
||||
"validationErrorEnterNumber": "유효한 숫자를 입력하세요",
|
||||
"validationErrorDuration": "기간은 ${min}과 ${max} ${unit} 사이여야 합니다",
|
||||
"shortcutAlreadyAssigned": "단축키가 이미 ${action}에 할당 되었습니다",
|
||||
"shortcutUpdated": "단축키가 ${action}에 대해 업데이트 되었습니다",
|
||||
"autoSkip": "자동 건너뛰기",
|
||||
"autoSkipIntro": "자동으로 오프닝 건너뛰기",
|
||||
"autoSkipIntroDescription": "몇 초 후 오프닝을 자동으로 건너뛰기",
|
||||
"autoSkipCredits": "자동으로 엔딩 건너뛰기",
|
||||
"autoSkipCreditsDescription": "엔딩 크레딧 자동 건너뛰기 후 다음 에피소드 재생",
|
||||
"autoSkipDelay": "자동 건너뛰기 지연",
|
||||
"autoSkipDelayDescription": "자동 건너뛰기 전 ${seconds} 초 대기",
|
||||
"downloads": "다운로드",
|
||||
"downloadLocationDescription": "다운로드 콘텐츠 저장 위치 선택",
|
||||
"downloadLocationDefault": "기본값 (앱 저장소)",
|
||||
"downloadLocationCustom": "사용자 지정 위치",
|
||||
"selectFolder": "폴더 선택",
|
||||
"resetToDefault": "기본값으로 재설정",
|
||||
"currentPath": "현재: ${path}",
|
||||
"downloadLocationChanged": "다운로드 위치가 변경 되었습니다",
|
||||
"downloadLocationReset": "다운로드 위치가 기본값으로 재설정 되었습니다",
|
||||
"downloadLocationInvalid": "선택한 폴더에 쓰기 권한이 없습니다",
|
||||
"downloadLocationSelectError": "폴더 선택 실패",
|
||||
"downloadOnWifiOnly": "WiFi 연결 시에만 다운로드",
|
||||
"downloadOnWifiOnlyDescription": "셀룰러 데이터 사용 시 다운로드 불가",
|
||||
"cellularDownloadBlocked": "셀룰러 데이터에서 다운로드가 차단 되었습니다. WiFi에 연결하거나 설정을 변경하세요.",
|
||||
"maxVolume": "최대 볼륨",
|
||||
"maxVolumeDescription": "조용한 미디어를 위해 100% 이상의 볼륨 허용",
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "최대 볼륨 입력 (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Discord에서 시청 중인 콘텐츠 표시",
|
||||
"matchContentFrameRate": "콘텐츠 프레임 레이트 맞춤",
|
||||
"matchContentFrameRateDescription": "비디오 콘텐츠에 맞게 디스플레이 주사율을 조정하여 떨림을 줄이고 배터리를 절약합니다"
|
||||
},
|
||||
"search": {
|
||||
"hint": "영화, 시리즈, 음악 등을 검색하세요...",
|
||||
"tryDifferentTerm": "다른 검색어를 시도해 보세요",
|
||||
"searchYourMedia": "미디어 검색",
|
||||
"enterTitleActorOrKeyword": "제목, 배우 또는 키워드를 입력하세요"
|
||||
},
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "${actionName}에 대한 단축키 설정",
|
||||
"clearShortcut": "단축키 삭제"
|
||||
},
|
||||
"pinEntry": {
|
||||
"enterPin": "PIN 입력",
|
||||
"showPin": "PIN 표시",
|
||||
"hidePin": "PIN 숨기기"
|
||||
},
|
||||
"fileInfo": {
|
||||
"title": "파일 정보",
|
||||
"video": "비디오",
|
||||
"audio": "오디오",
|
||||
"file": "파일",
|
||||
"advanced": "고급",
|
||||
"codec": "코덱",
|
||||
"resolution": "해상도",
|
||||
"bitrate": "비트레이트",
|
||||
"frameRate": "프레임 속도",
|
||||
"aspectRatio": "종횡비",
|
||||
"profile": "프로파일",
|
||||
"bitDepth": "비트 심도",
|
||||
"colorSpace": "색 공간",
|
||||
"colorRange": "색 범위",
|
||||
"colorPrimaries": "색상 원색",
|
||||
"chromaSubsampling": "채도 서브샘플링",
|
||||
"channels": "채널",
|
||||
"path": "경로",
|
||||
"size": "크기",
|
||||
"container": "컨테이너",
|
||||
"duration": "재생 시간",
|
||||
"optimizedForStreaming": "스트리밍 최적화",
|
||||
"has64bitOffsets": "64비트 오프셋"
|
||||
},
|
||||
"mediaMenu": {
|
||||
"markAsWatched": "시청 완료로 표시",
|
||||
"markAsUnwatched": "시청 안 함으로 표시",
|
||||
"removeFromContinueWatching": "계속 보기에서 제거",
|
||||
"goToSeries": "시리즈로 이동",
|
||||
"goToSeason": "시즌으로 이동",
|
||||
"shufflePlay": "무작위 재생",
|
||||
"fileInfo": "파일 정보"
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}, 영화",
|
||||
"mediaCardShow": "${title}, TV 프로그램",
|
||||
"mediaCardEpisode": "${title}, ${episodeInfo}",
|
||||
"mediaCardSeason": "${title}, ${seasonInfo}",
|
||||
"mediaCardWatched": "시청 완료",
|
||||
"mediaCardPartiallyWatched": "${percent} 퍼센트 시청 완료",
|
||||
"mediaCardUnwatched": "미시청",
|
||||
"tapToPlay": "터치 하여 재생"
|
||||
},
|
||||
"tooltips": {
|
||||
"shufflePlay": "무작위 재생",
|
||||
"markAsWatched": "시청 완료로 표시",
|
||||
"markAsUnwatched": "시청 안 함으로 표시"
|
||||
},
|
||||
"videoControls": {
|
||||
"audioLabel": "오디오",
|
||||
"subtitlesLabel": "자막",
|
||||
"resetToZero": "0ms로 재설정",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} 나중에 재생됨",
|
||||
"playsEarlier": "${label} 더 먼저 재생됨",
|
||||
"noOffset": "오프셋 없음",
|
||||
"letterbox": "레터박스 모드",
|
||||
"fillScreen": "화면 채우기",
|
||||
"stretch": "확장",
|
||||
"lockRotation": "회전 잠금",
|
||||
"unlockRotation": "회전 잠금 해제",
|
||||
"sleepTimer": "수면 타이머",
|
||||
"timerActive": "타이머 활성화됨",
|
||||
"playbackWillPauseIn": "재생이 ${duration} 후에 일시 중지 됩니다",
|
||||
"sleepTimerCompleted": "수면 타이머 완료됨 - 재생이 일시 중지되었습니다",
|
||||
"playButton": "재생",
|
||||
"pauseButton": "일시정지",
|
||||
"seekBackwardButton": "${seconds} 초 뒤로",
|
||||
"seekForwardButton": "${seconds} 초 앞으로",
|
||||
"previousButton": "이전 에피소드",
|
||||
"nextButton": "다음 에피소드",
|
||||
"previousChapterButton": "이전 챕터",
|
||||
"nextChapterButton": "다음 챕터",
|
||||
"muteButton": "음소거",
|
||||
"unmuteButton": "음소거 해제",
|
||||
"settingsButton": "동영상 설정",
|
||||
"audioTrackButton": "음원 트랙",
|
||||
"subtitlesButton": "자막",
|
||||
"chaptersButton": "챕터",
|
||||
"versionsButton": "동영상 버전",
|
||||
"pipButton": "픽처 인 픽처 모드",
|
||||
"aspectRatioButton": "화면비율",
|
||||
"fullscreenButton": "전체화면",
|
||||
"exitFullscreenButton": "전체화면 종료",
|
||||
"alwaysOnTopButton": "창 최상위 고정",
|
||||
"rotationLockButton": "회전 잠금",
|
||||
"timelineSlider": "타임라인",
|
||||
"volumeSlider": "볼륨 조절",
|
||||
"backButton": "뒤로 가기"
|
||||
},
|
||||
"userStatus": {
|
||||
"admin": "관리자",
|
||||
"restricted": "제한됨",
|
||||
"protected": "보호됨",
|
||||
"current": "현재"
|
||||
},
|
||||
"messages": {
|
||||
"markedAsWatched": "시청 완료로 표시됨",
|
||||
"markedAsUnwatched": "시청 안 함으로 표시됨",
|
||||
"markedAsWatchedOffline": "시청 완료로 표시됨 (연결 시 동기화됨)",
|
||||
"markedAsUnwatchedOffline": "미시청으로 표시됨 (연결 시 동기화됨)",
|
||||
"removedFromContinueWatching": "계속 시청 목록에서 제거됨",
|
||||
"errorLoading": "오류: ${error}",
|
||||
"fileInfoNotAvailable": "파일 정보가 없습니다",
|
||||
"errorLoadingFileInfo": "파일 정보 로딩 중 오류: ${error}",
|
||||
"errorLoadingSeries": "시리즈 로딩 중 오류",
|
||||
"errorLoadingSeason": "시즌 로딩 중 오류",
|
||||
"musicNotSupported": "음악 재생 미지원",
|
||||
"logsCleared": "로그가 삭제 되었습니다",
|
||||
"logsCopied": "로그가 클립보드에 복사 되었습니다",
|
||||
"noLogsAvailable": "사용 가능한 로그가 없습니다",
|
||||
"libraryScanning": "\"${title}\"을(를) 스캔 중입니다...",
|
||||
"libraryScanStarted": "\"${title}\" 미디어 라이브러리 스캔 시작",
|
||||
"libraryScanFailed": "미디어 라이브러리 스캔 실패: ${error}",
|
||||
"metadataRefreshing": "\"${title}\" 메타데이터 새로고침 중...",
|
||||
"metadataRefreshStarted": "\"${title}\" 메타데이터 새로고침 시작됨",
|
||||
"metadataRefreshFailed": "메타데이터 새로고침 실패: ${error}",
|
||||
"logoutConfirm": "로그아웃 하시겠습니까?",
|
||||
"noSeasonsFound": "시즌을 찾을 수 없음",
|
||||
"noEpisodesFound": "시즌 1에서 에피소드를 찾을 수 없습니다",
|
||||
"noEpisodesFoundGeneral": "에피소드를 찾을 수 없습니다",
|
||||
"noResultsFound": "결과를 찾을 수 없습니다",
|
||||
"sleepTimerSet": "수면 타이머가 ${label}로 설정 되었습니다",
|
||||
"noItemsAvailable": "사용 가능한 항목이 없습니다",
|
||||
"failedToCreatePlayQueue": "재생 대기열 생성 실패",
|
||||
"failedToCreatePlayQueueNoItems": "재생 대기열 생성 실패 - 항목 없음",
|
||||
"failedPlayback": "${action}을(를) 수행할 수 없습니다: ${error}"
|
||||
},
|
||||
"subtitlingStyling": {
|
||||
"stylingOptions": "스타일 옵션",
|
||||
"fontSize": "글자 크기",
|
||||
"textColor": "텍스트 색상",
|
||||
"borderSize": "테두리 크기",
|
||||
"borderColor": "테두리 색상",
|
||||
"backgroundOpacity": "배경 불투명도",
|
||||
"backgroundColor": "배경색"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "MPV 설정",
|
||||
"description": "고급 비디오 플레이어 설정",
|
||||
"properties": "속성",
|
||||
"presets": "사전 설정",
|
||||
"noProperties": "설정된 속성이 없습니다",
|
||||
"noPresets": "저장된 사전 설정이 없습니다",
|
||||
"addProperty": "속성 추가",
|
||||
"editProperty": "속성 편집",
|
||||
"deleteProperty": "속성 삭제",
|
||||
"propertyKey": "속성 키",
|
||||
"propertyKeyHint": "예: hwdec, demuxer-max-bytes",
|
||||
"propertyValue": "속성값",
|
||||
"propertyValueHint": "예: auto, 256000000",
|
||||
"saveAsPreset": "프리셋으로 저장...",
|
||||
"presetName": "프리셋 이름",
|
||||
"presetNameHint": "이 프리셋의 이름을 입력하세요",
|
||||
"loadPreset": "로드",
|
||||
"deletePreset": "삭제",
|
||||
"presetSaved": "프리셋이 저장 되었습니다",
|
||||
"presetLoaded": "프리셋이 로드 되었습니다",
|
||||
"presetDeleted": "프리셋이 삭제 되었습니다",
|
||||
"confirmDeletePreset": "이 프리셋을 삭제 하시겠습니까?",
|
||||
"confirmDeleteProperty": "이 속성을 삭제 하시겠습니까?",
|
||||
"entriesCount": "${count} 항목"
|
||||
},
|
||||
"dialog": {
|
||||
"confirmAction": "확인",
|
||||
"cancel": "취소",
|
||||
"playNow": "지금 재생"
|
||||
},
|
||||
"discover": {
|
||||
"title": "발견",
|
||||
"switchProfile": "사용자 전환",
|
||||
"switchServer": "서버 전환",
|
||||
"logout": "로그아웃",
|
||||
"noContentAvailable": "사용 가능한 콘텐츠가 없습니다",
|
||||
"addMediaToLibraries": "미디어 라이브러리에 미디어를 추가해 주세요",
|
||||
"continueWatching": "계속 시청",
|
||||
"play": "재생",
|
||||
"playEpisode": "S${season}E${episode}",
|
||||
"pause": "일시정지",
|
||||
"overview": "개요",
|
||||
"cast": "출연진",
|
||||
"seasons": "시즌 수",
|
||||
"studio": "제작사",
|
||||
"rating": "연령 등급",
|
||||
"watched": "시청 완료",
|
||||
"episodeCount": "${count} 편",
|
||||
"watchedProgress": "${watched}/${total} 편 시청 완료",
|
||||
"movie": "영화",
|
||||
"tvShow": "TV 시리즈",
|
||||
"minutesLeft": "${minutes}분 남음"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "검색 실패: ${error}",
|
||||
"connectionTimeout": "${context} 로드 중 연결 시간 초과",
|
||||
"connectionFailed": "Plex 서버에 연결할 수 없음",
|
||||
"failedToLoad": "${context} 로드 실패: ${error}",
|
||||
"noClientAvailable": "사용 가능한 클라이언트가 없습니다",
|
||||
"authenticationFailed": "인증 실패: ${error}",
|
||||
"couldNotLaunchUrl": "인증 URL을 열 수 없습니다",
|
||||
"pleaseEnterToken": "토큰을 입력해 주세요",
|
||||
"invalidToken": "토큰이 유효하지 않습니다",
|
||||
"failedToVerifyToken": "토큰을 확인할 수 없습니다: ${error}",
|
||||
"failedToSwitchProfile": "${displayName}으로 전환할 수 없습니다"
|
||||
},
|
||||
"libraries": {
|
||||
"title": "미디어 라이브러리",
|
||||
"scanLibraryFiles": "미디어 라이브러리 파일 스캔",
|
||||
"scanLibrary": "미디어 라이브러리 스캔",
|
||||
"analyze": "분석",
|
||||
"analyzeLibrary": "미디어 라이브러리 분석",
|
||||
"refreshMetadata": "메타데이터 새로 고침",
|
||||
"emptyTrash": "휴지통 비우기",
|
||||
"emptyingTrash": "「${title}」의 휴지통을 비우고 있습니다...",
|
||||
"trashEmptied": "「${title}」의 휴지통을 비웠습니다",
|
||||
"failedToEmptyTrash": "휴지통 비우기 실패: ${error}",
|
||||
"analyzing": "\"${title}\" 분석 중...",
|
||||
"analysisStarted": "\"${title}\" 분석 시작됨",
|
||||
"failedToAnalyze": "미디어 라이브러리 분석 실패: ${error}",
|
||||
"noLibrariesFound": "미디어 라이브러리 없음",
|
||||
"thisLibraryIsEmpty": "이 미디어 라이브러리는 비어 있습니다",
|
||||
"all": "전체",
|
||||
"clearAll": "모두 삭제",
|
||||
"scanLibraryConfirm": "「${title}」를 스캔 하시겠습니까?",
|
||||
"analyzeLibraryConfirm": "「${title}」를 분석 하시겠습니까?",
|
||||
"refreshMetadataConfirm": "「${title}」의 메타데이터를 새로고침 하시겠습니까?",
|
||||
"emptyTrashConfirm": "${title}의 휴지통을 비우시겠습니까?",
|
||||
"manageLibraries": "미디어 라이브러리 관리",
|
||||
"sort": "정렬",
|
||||
"sortBy": "정렬 기준",
|
||||
"filters": "필터",
|
||||
"confirmActionMessage": "이 작업을 실행 하시겠습니까?",
|
||||
"showLibrary": "미디어 라이브러리 표시",
|
||||
"hideLibrary": "미디어 라이브러리 숨기기",
|
||||
"libraryOptions": "미디어 라이브러리 옵션",
|
||||
"content": "미디어 라이브러리 콘텐츠",
|
||||
"selectLibrary": "미디어 라이브러리 선택",
|
||||
"filtersWithCount": "필터 (${count})",
|
||||
"noRecommendations": "추천 없음",
|
||||
"noCollections": "이 미디어 라이브러리에는 컬렉션이 없습니다",
|
||||
"noFoldersFound": "폴더를 찾을 수 없습니다",
|
||||
"folders": "폴더",
|
||||
"tabs": {
|
||||
"recommended": "추천",
|
||||
"browse": "찾아보기",
|
||||
"collections": "컬렉션",
|
||||
"playlists": "재생 목록"
|
||||
},
|
||||
"groupings": {
|
||||
"all": "전체",
|
||||
"movies": "영화",
|
||||
"shows": "TV 프로그램",
|
||||
"seasons": "시즌",
|
||||
"episodes": "화",
|
||||
"folders": "폴더"
|
||||
}
|
||||
},
|
||||
"about": {
|
||||
"title": "소개",
|
||||
"openSourceLicenses": "오픈소스 라이선스",
|
||||
"versionLabel": "버전 ${version}",
|
||||
"appDescription": "아름다운 Flutter Plex 클라이언트",
|
||||
"viewLicensesDescription": "타사 라이브러리 라이선스 보기"
|
||||
},
|
||||
"serverSelection": {
|
||||
"allServerConnectionsFailed": "어떤 서버에도 연결할 수 없습니다. 네트워크를 확인하고 다시 시도하세요.",
|
||||
"noServersFound": "서버를 찾을 수 없습니다.",
|
||||
"noServersFoundForAccount": "${username} (${email})의 서버를 찾을 수 없습니다.",
|
||||
"failedToLoadServers": "서버를 로드할 수 없습니다: ${error}"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "제목",
|
||||
"releaseYear": "출시 연도",
|
||||
"dateAdded": "추가 날짜",
|
||||
"rating": "평점",
|
||||
"noItemsFound": "항목이 없습니다"
|
||||
},
|
||||
"logs": {
|
||||
"clearLogs": "로그 지우기",
|
||||
"copyLogs": "로그 복사",
|
||||
"error": "오류:",
|
||||
"stackTrace": "스택 추적 (Stack Trace):"
|
||||
},
|
||||
"licenses": {
|
||||
"relatedPackages": "관련 소프트웨어 패키지",
|
||||
"license": "라이선스",
|
||||
"licenseNumber": "라이선스 ${number}",
|
||||
"licensesCount": "${count} 개의 라이선스"
|
||||
},
|
||||
"navigation": {
|
||||
"home": "홈",
|
||||
"search": "검색",
|
||||
"libraries": "미디어 라이브러리",
|
||||
"settings": "설정",
|
||||
"downloads": "다운로드"
|
||||
},
|
||||
"collections": {
|
||||
"title": "컬렉션",
|
||||
"collection": "컬렉션",
|
||||
"empty": "컬렉션이 비어 있습니다",
|
||||
"unknownLibrarySection": "삭제할 수 없습니다: 알 수 없는 미디어 라이브러리 섹션입니다",
|
||||
"deleteCollection": "컬렉션 삭제",
|
||||
"deleteConfirm": "\"${title}\"을(를) 삭제 하시겠습니까? 이 작업은 되돌릴 수 없습니다.",
|
||||
"deleted": "컬렉션 삭제됨",
|
||||
"deleteFailed": "컬렉션 삭제 실패",
|
||||
"deleteFailedWithError": "컬렉션 삭제 실패: ${error}",
|
||||
"failedToLoadItems": "컬렉션 항목 로드 실패: ${error}",
|
||||
"selectCollection": "컬렉션 선택",
|
||||
"createNewCollection": "새 컬렉션 생성",
|
||||
"collectionName": "컬렉션 이름",
|
||||
"enterCollectionName": "컬렉션 이름 입력",
|
||||
"addedToCollection": "컬렉션에 추가됨",
|
||||
"errorAddingToCollection": "컬렉션에 추가 실패",
|
||||
"created": "컬렉션 생성됨",
|
||||
"removeFromCollection": "컬렉션에서 제거",
|
||||
"removeFromCollectionConfirm": "${title}을/를 이 컬렉션에서 제거 하시겠습니까?",
|
||||
"removedFromCollection": "컬렉션에서 제거됨",
|
||||
"removeFromCollectionFailed": "컬렉션에서 제거 실패",
|
||||
"removeFromCollectionError": "컬렉션에서 제거 중 오류 발생: ${error}"
|
||||
},
|
||||
"playlists": {
|
||||
"title": "플레이리스트",
|
||||
"playlist": "재생 목록",
|
||||
"noPlaylists": "재생 목록을 찾을 수 없습니다",
|
||||
"create": "재생 목록 생성",
|
||||
"playlistName": "재생 목록 이름",
|
||||
"enterPlaylistName": "재생 목록 이름 입력",
|
||||
"delete": "재생 목록 삭제",
|
||||
"removeItem": "재생 목록에서 항목 제거",
|
||||
"smartPlaylist": "스마트 재생 목록",
|
||||
"itemCount": "${count}개 항목",
|
||||
"oneItem": "1개 항목",
|
||||
"emptyPlaylist": "이 재생 목록은 비어 있습니다",
|
||||
"deleteConfirm": "재생 목록을 삭제 하시겠습니까?",
|
||||
"deleteMessage": "\"${name}\"을(를) 삭제 하시겠습니까?",
|
||||
"created": "재생 목록이 생성 되었습니다",
|
||||
"deleted": "재생 목록이 삭제 되었습니다",
|
||||
"itemAdded": "재생 목록에 추가 되었습니다",
|
||||
"itemRemoved": "재생 목록에서 제거됨",
|
||||
"selectPlaylist": "재생 목록 선택",
|
||||
"createNewPlaylist": "새 재생 목록 생성",
|
||||
"errorCreating": "재생 목록 생성 실패",
|
||||
"errorDeleting": "재생 목록 삭제 실패",
|
||||
"errorLoading": "재생 목록 로드 실패",
|
||||
"errorAdding": "재생 목록에 추가 실패",
|
||||
"errorReordering": "재생 목록 항목 재정렬 실패",
|
||||
"errorRemoving": "재생 목록에서 제거 실패"
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "함께 보기",
|
||||
"description": "친구 및 가족과 콘텐츠를 동시에 시청하세요",
|
||||
"createSession": "세션 생성",
|
||||
"creating": "생성 중...",
|
||||
"joinSession": "세션 참여",
|
||||
"joining": "참가 중...",
|
||||
"controlMode": "제어 모드",
|
||||
"controlModeQuestion": "누가 재생을 제어할 수 있나요?",
|
||||
"hostOnly": "호스트만",
|
||||
"anyone": "누구나",
|
||||
"hostingSession": "세션 호스팅",
|
||||
"inSession": "세션 중",
|
||||
"sessionCode": "세션 코드",
|
||||
"hostControlsPlayback": "호스트 재생 제어",
|
||||
"anyoneCanControl": "누구나 재생 제어 가능",
|
||||
"hostControls": "호스트 제어",
|
||||
"anyoneControls": "누구나 제어",
|
||||
"participants": "참가자",
|
||||
"host": "호스트",
|
||||
"hostBadge": "호스트",
|
||||
"youAreHost": "당신은 호스트 입니다",
|
||||
"watchingWithOthers": "다른 사람과 함께 시청 중",
|
||||
"endSession": "세션 종료",
|
||||
"leaveSession": "세션 탈퇴",
|
||||
"endSessionQuestion": "세션을 종료 하시겠습니까?",
|
||||
"leaveSessionQuestion": "세션을 탈퇴 하시겠습니까?",
|
||||
"endSessionConfirm": "이 작업은 모든 참가자의 세션을 종료합니다.",
|
||||
"leaveSessionConfirm": "당신은 세션에서 제거됩니다.",
|
||||
"endSessionConfirmOverlay": "이것은 모든 참가자의 시청 세션을 종료합니다.",
|
||||
"leaveSessionConfirmOverlay": "시청 세션 연결이 끊어집니다.",
|
||||
"end": "종료",
|
||||
"leave": "이탈",
|
||||
"syncing": "동기화 중...",
|
||||
"participant": "참여자",
|
||||
"joinWatchSession": "시청 세션에 참여",
|
||||
"enterCodeHint": "8자리 코드 입력",
|
||||
"pasteFromClipboard": "클립보드에서 붙여넣기",
|
||||
"pleaseEnterCode": "세션 코드를 입력하세요",
|
||||
"codeMustBe8Chars": "세션 코드는 반드시 8자리여야 합니다",
|
||||
"joinInstructions": "호스트가 공유한 세션 코드를 입력하여 시청 세션에 참여하세요.",
|
||||
"failedToCreate": "세션 생성 실패",
|
||||
"failedToJoin": "세션 참여 실패"
|
||||
},
|
||||
"downloads": {
|
||||
"title": "다운로드",
|
||||
"manage": "관리",
|
||||
"tvShows": "TV 프로그램",
|
||||
"movies": "영화",
|
||||
"noDownloads": "다운로드 없음",
|
||||
"noDownloadsDescription": "다운로드한 콘텐츠는 오프라인 시청을 위해 여기에 표시됩니다",
|
||||
"downloadNow": "다운로드",
|
||||
"deleteDownload": "다운로드 삭제",
|
||||
"retryDownload": "다운로드 재시도",
|
||||
"downloadQueued": "다운로드 대기 중",
|
||||
"episodesQueued": "${count} 에피소드가 다운로드 대기열에 추가 되었습니다",
|
||||
"downloadDeleted": "다운로드 삭제됨",
|
||||
"deleteConfirm": "\"${title}\"를 삭제 하시겠습니까? 다운로드한 파일이 기기에서 삭제됩니다.",
|
||||
"deletingWithProgress": "${title} 삭제 중... (${current}/${total})"
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@
|
||||
"selectServer": "Selecteer server",
|
||||
"switchProfile": "Wissel van profiel",
|
||||
"subtitleStyling": "Ondertitel opmaak",
|
||||
"mpvConfig": "MPV-configuratie",
|
||||
"search": "Zoeken",
|
||||
"logs": "Logbestanden"
|
||||
},
|
||||
@@ -59,7 +60,13 @@
|
||||
"appearance": "Uiterlijk",
|
||||
"videoPlayback": "Video afspelen",
|
||||
"advanced": "Geavanceerd",
|
||||
"useSeasonPostersDescription": "Toon seizoenposter in plaats van serieposter voor afleveringen",
|
||||
"episodePosterMode": "Aflevering poster stijl",
|
||||
"seriesPoster": "Serie poster",
|
||||
"seriesPosterDescription": "Toon de serie poster voor alle afleveringen",
|
||||
"seasonPoster": "Seizoen poster",
|
||||
"seasonPosterDescription": "Toon de seizoensspecifieke poster voor afleveringen",
|
||||
"episodeThumbnail": "Aflevering miniatuur",
|
||||
"episodeThumbnailDescription": "Toon 16:9 aflevering miniaturen",
|
||||
"showHeroSectionDescription": "Toon uitgelichte inhoud carrousel op startscherm",
|
||||
"secondsLabel": "Seconden",
|
||||
"minutesLabel": "Minuten",
|
||||
@@ -82,8 +89,9 @@
|
||||
"gridViewDescription": "Items weergeven in een rasterindeling",
|
||||
"listView": "Lijst",
|
||||
"listViewDescription": "Items weergeven in een lijstindeling",
|
||||
"useSeasonPosters": "Gebruik seizoenposters",
|
||||
"showHeroSection": "Toon hoofdsectie",
|
||||
"useGlobalHubs": "Plex Home-indeling gebruiken",
|
||||
"useGlobalHubsDescription": "Toon startpagina-hubs zoals de officiële Plex-client. Indien uitgeschakeld, worden in plaats daarvan aanbevelingen per bibliotheek getoond.",
|
||||
"hardwareDecoding": "Hardware decodering",
|
||||
"hardwareDecodingDescription": "Gebruik hardware versnelling indien beschikbaar",
|
||||
"bufferSize": "Buffer grootte",
|
||||
@@ -142,7 +150,15 @@
|
||||
"downloadLocationSelectError": "Kan map niet selecteren",
|
||||
"downloadOnWifiOnly": "Alleen via WiFi downloaden",
|
||||
"downloadOnWifiOnlyDescription": "Voorkom downloads bij gebruik van mobiele data",
|
||||
"cellularDownloadBlocked": "Downloads zijn uitgeschakeld bij mobiele data. Maak verbinding met WiFi of wijzig de instelling."
|
||||
"cellularDownloadBlocked": "Downloads zijn uitgeschakeld bij mobiele data. Maak verbinding met WiFi of wijzig de instelling.",
|
||||
"maxVolume": "Maximaal volume",
|
||||
"maxVolumeDescription": "Volume boven 100% toestaan voor stille media",
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Voer maximaal volume in (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Toon op Discord wat je aan het kijken bent",
|
||||
"matchContentFrameRate": "Inhoudsframesnelheid afstemmen",
|
||||
"matchContentFrameRateDescription": "Pas de schermverversingssnelheid aan op de video-inhoud, vermindert haperingen en bespaart batterij"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Zoek films, series, muziek...",
|
||||
@@ -241,6 +257,7 @@
|
||||
"subtitlesButton": "Ondertitels",
|
||||
"chaptersButton": "Hoofdstukken",
|
||||
"versionsButton": "Videoversies",
|
||||
"pipButton": "Beeld-in-beeld modus",
|
||||
"aspectRatioButton": "Beeldverhouding",
|
||||
"fullscreenButton": "Volledig scherm activeren",
|
||||
"exitFullscreenButton": "Volledig scherm verlaten",
|
||||
@@ -297,6 +314,32 @@
|
||||
"backgroundOpacity": "Achtergrond transparantie",
|
||||
"backgroundColor": "Achtergrondkleur"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "MPV-configuratie",
|
||||
"description": "Geavanceerde videospeler-instellingen",
|
||||
"properties": "Eigenschappen",
|
||||
"presets": "Voorinstellingen",
|
||||
"noProperties": "Geen eigenschappen geconfigureerd",
|
||||
"noPresets": "Geen opgeslagen voorinstellingen",
|
||||
"addProperty": "Eigenschap toevoegen",
|
||||
"editProperty": "Eigenschap bewerken",
|
||||
"deleteProperty": "Eigenschap verwijderen",
|
||||
"propertyKey": "Eigenschapssleutel",
|
||||
"propertyKeyHint": "bijv. hwdec, demuxer-max-bytes",
|
||||
"propertyValue": "Eigenschapswaarde",
|
||||
"propertyValueHint": "bijv. auto, 256000000",
|
||||
"saveAsPreset": "Opslaan als voorinstelling...",
|
||||
"presetName": "Naam voorinstelling",
|
||||
"presetNameHint": "Voer een naam in voor deze voorinstelling",
|
||||
"loadPreset": "Laden",
|
||||
"deletePreset": "Verwijderen",
|
||||
"presetSaved": "Voorinstelling opgeslagen",
|
||||
"presetLoaded": "Voorinstelling geladen",
|
||||
"presetDeleted": "Voorinstelling verwijderd",
|
||||
"confirmDeletePreset": "Weet je zeker dat je deze voorinstelling wilt verwijderen?",
|
||||
"confirmDeleteProperty": "Weet je zeker dat je deze eigenschap wilt verwijderen?",
|
||||
"entriesCount": "${count} items"
|
||||
},
|
||||
"dialog": {
|
||||
"confirmAction": "Bevestig actie",
|
||||
"cancel": "Annuleren",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"selectServer": "Välj server",
|
||||
"switchProfile": "Byt profil",
|
||||
"subtitleStyling": "Undertext-styling",
|
||||
"mpvConfig": "MPV-konfiguration",
|
||||
"search": "Sök",
|
||||
"logs": "Loggar"
|
||||
},
|
||||
@@ -59,7 +60,13 @@
|
||||
"appearance": "Utseende",
|
||||
"videoPlayback": "Videouppspelning",
|
||||
"advanced": "Avancerat",
|
||||
"useSeasonPostersDescription": "Visa säsongsaffisch istället för serieaffisch för avsnitt",
|
||||
"episodePosterMode": "Avsnittsaffisch-stil",
|
||||
"seriesPoster": "Serieaffisch",
|
||||
"seriesPosterDescription": "Visa seriens affisch för alla avsnitt",
|
||||
"seasonPoster": "Säsongsaffisch",
|
||||
"seasonPosterDescription": "Visa säsongens affisch för avsnitt",
|
||||
"episodeThumbnail": "Avsnittsminiatyr",
|
||||
"episodeThumbnailDescription": "Visa 16:9 skärmbild från avsnittet",
|
||||
"showHeroSectionDescription": "Visa utvalda innehållskarusell på startsidan",
|
||||
"secondsLabel": "Sekunder",
|
||||
"minutesLabel": "Minuter",
|
||||
@@ -82,8 +89,9 @@
|
||||
"gridViewDescription": "Visa objekt i rutnätslayout",
|
||||
"listView": "Lista",
|
||||
"listViewDescription": "Visa objekt i listlayout",
|
||||
"useSeasonPosters": "Använd säsongsaffischer",
|
||||
"showHeroSection": "Visa hjältesektion",
|
||||
"useGlobalHubs": "Använd Plex hem-layout",
|
||||
"useGlobalHubsDescription": "Visar startsidans hubbar som den officiella Plex-klienten. När av visas rekommendationer per bibliotek istället.",
|
||||
"hardwareDecoding": "Hårdvaruavkodning",
|
||||
"hardwareDecodingDescription": "Använd hårdvaruacceleration när tillgängligt",
|
||||
"bufferSize": "Bufferstorlek",
|
||||
@@ -142,7 +150,15 @@
|
||||
"downloadLocationSelectError": "Kunde inte välja mapp",
|
||||
"downloadOnWifiOnly": "Ladda ner endast på WiFi",
|
||||
"downloadOnWifiOnlyDescription": "Förhindra nedladdningar vid användning av mobildata",
|
||||
"cellularDownloadBlocked": "Nedladdningar är inaktiverade på mobildata. Anslut till WiFi eller ändra inställningen."
|
||||
"cellularDownloadBlocked": "Nedladdningar är inaktiverade på mobildata. Anslut till WiFi eller ändra inställningen.",
|
||||
"maxVolume": "Maximal volym",
|
||||
"maxVolumeDescription": "Tillåt volym över 100% för tyst media",
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "Ange maximal volym (100-300)",
|
||||
"discordRichPresence": "Discord Rich Presence",
|
||||
"discordRichPresenceDescription": "Visa vad du tittar på i Discord",
|
||||
"matchContentFrameRate": "Matcha innehållets bildfrekvens",
|
||||
"matchContentFrameRateDescription": "Justera skärmens uppdateringsfrekvens för att matcha videoinnehållet, minskar hackighet och sparar batteri"
|
||||
},
|
||||
"search": {
|
||||
"hint": "Sök filmer, serier, musik...",
|
||||
@@ -241,6 +257,7 @@
|
||||
"subtitlesButton": "Undertexter",
|
||||
"chaptersButton": "Kapitel",
|
||||
"versionsButton": "Videoversioner",
|
||||
"pipButton": "Bild-i-bild läge",
|
||||
"aspectRatioButton": "Bildförhållande",
|
||||
"fullscreenButton": "Aktivera helskärm",
|
||||
"exitFullscreenButton": "Avsluta helskärm",
|
||||
@@ -297,6 +314,32 @@
|
||||
"backgroundOpacity": "Bakgrundsopacitet",
|
||||
"backgroundColor": "Bakgrundsfärg"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "MPV-konfiguration",
|
||||
"description": "Avancerade videospelares inställningar",
|
||||
"properties": "Egenskaper",
|
||||
"presets": "Förval",
|
||||
"noProperties": "Inga egenskaper konfigurerade",
|
||||
"noPresets": "Inga sparade förval",
|
||||
"addProperty": "Lägg till egenskap",
|
||||
"editProperty": "Redigera egenskap",
|
||||
"deleteProperty": "Ta bort egenskap",
|
||||
"propertyKey": "Egenskapsnyckel",
|
||||
"propertyKeyHint": "t.ex. hwdec, demuxer-max-bytes",
|
||||
"propertyValue": "Egenskapsvärde",
|
||||
"propertyValueHint": "t.ex. auto, 256000000",
|
||||
"saveAsPreset": "Spara som förval...",
|
||||
"presetName": "Förvalnamn",
|
||||
"presetNameHint": "Ange ett namn för detta förval",
|
||||
"loadPreset": "Ladda",
|
||||
"deletePreset": "Ta bort",
|
||||
"presetSaved": "Förval sparat",
|
||||
"presetLoaded": "Förval laddat",
|
||||
"presetDeleted": "Förval borttaget",
|
||||
"confirmDeletePreset": "Är du säker på att du vill ta bort detta förval?",
|
||||
"confirmDeleteProperty": "Är du säker på att du vill ta bort denna egenskap?",
|
||||
"entriesCount": "${count} poster"
|
||||
},
|
||||
"dialog": {
|
||||
"confirmAction": "Bekräfta åtgärd",
|
||||
"cancel": "Avbryt",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"selectServer": "选择服务器",
|
||||
"switchProfile": "切换用户",
|
||||
"subtitleStyling": "字幕样式",
|
||||
"mpvConfig": "MPV 配置",
|
||||
"search": "搜索",
|
||||
"logs": "日志"
|
||||
},
|
||||
@@ -59,7 +60,13 @@
|
||||
"appearance": "外观",
|
||||
"videoPlayback": "视频播放",
|
||||
"advanced": "高级",
|
||||
"useSeasonPostersDescription": "为剧集显示季海报而非剧集海报",
|
||||
"episodePosterMode": "剧集海报样式",
|
||||
"seriesPoster": "剧集海报",
|
||||
"seriesPosterDescription": "为所有剧集显示剧集海报",
|
||||
"seasonPoster": "季海报",
|
||||
"seasonPosterDescription": "为剧集显示特定季的海报",
|
||||
"episodeThumbnail": "剧集缩略图",
|
||||
"episodeThumbnailDescription": "显示16:9剧集截图缩略图",
|
||||
"showHeroSectionDescription": "在主屏幕上显示精选内容轮播区",
|
||||
"secondsLabel": "秒",
|
||||
"minutesLabel": "分钟",
|
||||
@@ -82,8 +89,9 @@
|
||||
"gridViewDescription": "以网格布局显示项目",
|
||||
"listView": "列表视图",
|
||||
"listViewDescription": "以列表布局显示项目",
|
||||
"useSeasonPosters": "使用季海报",
|
||||
"showHeroSection": "显示主要精选区",
|
||||
"useGlobalHubs": "使用 Plex 主页布局",
|
||||
"useGlobalHubsDescription": "显示与官方 Plex 客户端相同的主页推荐。关闭时将显示按媒体库分类的推荐。",
|
||||
"hardwareDecoding": "硬件解码",
|
||||
"hardwareDecodingDescription": "如果可用,使用硬件加速",
|
||||
"bufferSize": "缓冲区大小",
|
||||
@@ -142,7 +150,15 @@
|
||||
"downloadLocationSelectError": "选择文件夹失败",
|
||||
"downloadOnWifiOnly": "仅在 WiFi 时下载",
|
||||
"downloadOnWifiOnlyDescription": "使用蜂窝数据时禁止下载",
|
||||
"cellularDownloadBlocked": "蜂窝数据下已禁用下载。请连接 WiFi 或更改设置。"
|
||||
"cellularDownloadBlocked": "蜂窝数据下已禁用下载。请连接 WiFi 或更改设置。",
|
||||
"maxVolume": "最大音量",
|
||||
"maxVolumeDescription": "允许音量超过 100% 以适应安静的媒体",
|
||||
"maxVolumePercent": "${percent}%",
|
||||
"maxVolumeHint": "输入最大音量 (100-300)",
|
||||
"discordRichPresence": "Discord 动态状态",
|
||||
"discordRichPresenceDescription": "在 Discord 上显示您正在观看的内容",
|
||||
"matchContentFrameRate": "匹配内容帧率",
|
||||
"matchContentFrameRateDescription": "调整显示刷新率以匹配视频内容,减少画面抖动并节省电量"
|
||||
},
|
||||
"search": {
|
||||
"hint": "搜索电影、系列、音乐...",
|
||||
@@ -241,6 +257,7 @@
|
||||
"subtitlesButton": "字幕",
|
||||
"chaptersButton": "章节",
|
||||
"versionsButton": "视频版本",
|
||||
"pipButton": "画中画模式",
|
||||
"aspectRatioButton": "宽高比",
|
||||
"fullscreenButton": "进入全屏",
|
||||
"exitFullscreenButton": "退出全屏",
|
||||
@@ -297,6 +314,32 @@
|
||||
"backgroundOpacity": "背景不透明度",
|
||||
"backgroundColor": "背景颜色"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "MPV 配置",
|
||||
"description": "高级视频播放器设置",
|
||||
"properties": "属性",
|
||||
"presets": "预设",
|
||||
"noProperties": "未配置任何属性",
|
||||
"noPresets": "没有保存的预设",
|
||||
"addProperty": "添加属性",
|
||||
"editProperty": "编辑属性",
|
||||
"deleteProperty": "删除属性",
|
||||
"propertyKey": "属性键",
|
||||
"propertyKeyHint": "例如 hwdec, demuxer-max-bytes",
|
||||
"propertyValue": "属性值",
|
||||
"propertyValueHint": "例如 auto, 256000000",
|
||||
"saveAsPreset": "保存为预设...",
|
||||
"presetName": "预设名称",
|
||||
"presetNameHint": "输入此预设的名称",
|
||||
"loadPreset": "加载",
|
||||
"deletePreset": "删除",
|
||||
"presetSaved": "预设已保存",
|
||||
"presetLoaded": "预设已加载",
|
||||
"presetDeleted": "预设已删除",
|
||||
"confirmDeletePreset": "确定要删除此预设吗?",
|
||||
"confirmDeleteProperty": "确定要删除此属性吗?",
|
||||
"entriesCount": "${count} 条目"
|
||||
},
|
||||
"dialog": {
|
||||
"confirmAction": "确认操作",
|
||||
"cancel": "取消",
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'screens/main_screen.dart';
|
||||
import 'screens/auth_screen.dart';
|
||||
import 'services/storage_service.dart';
|
||||
import 'services/macos_titlebar_service.dart';
|
||||
import 'services/fullscreen_state_manager.dart';
|
||||
import 'services/update_service.dart';
|
||||
import 'services/settings_service.dart';
|
||||
import 'utils/platform_detector.dart';
|
||||
import 'services/discord_rpc_service.dart';
|
||||
import 'services/gamepad_service.dart';
|
||||
import 'providers/user_profile_provider.dart';
|
||||
import 'providers/plex_client_provider.dart';
|
||||
@@ -27,8 +27,10 @@ import 'watch_together/watch_together.dart';
|
||||
import 'services/multi_server_manager.dart';
|
||||
import 'services/offline_watch_sync_service.dart';
|
||||
import 'services/data_aggregation_service.dart';
|
||||
import 'services/in_app_review_service.dart';
|
||||
import 'services/server_registry.dart';
|
||||
import 'services/download_manager_service.dart';
|
||||
import 'services/pip_service.dart';
|
||||
import 'services/download_storage_service.dart';
|
||||
import 'services/plex_api_cache.dart';
|
||||
import 'database/app_database.dart';
|
||||
@@ -38,8 +40,26 @@ import 'utils/language_codes.dart';
|
||||
import 'i18n/strings.g.dart';
|
||||
import 'focus/input_mode_tracker.dart';
|
||||
|
||||
// Workaround for Flutter bug #177992: iPadOS 26.1+ misinterprets fake touch events
|
||||
// at (0,0) as barrier taps, causing modals to dismiss immediately.
|
||||
// Remove when Flutter PR #179643 is merged.
|
||||
bool _zeroOffsetPointerGuardInstalled = false;
|
||||
|
||||
void _installZeroOffsetPointerGuard() {
|
||||
if (_zeroOffsetPointerGuardInstalled) return;
|
||||
GestureBinding.instance.pointerRouter.addGlobalRoute(_absorbZeroOffsetPointerEvent);
|
||||
_zeroOffsetPointerGuardInstalled = true;
|
||||
}
|
||||
|
||||
void _absorbZeroOffsetPointerEvent(PointerEvent event) {
|
||||
if (event.position == Offset.zero) {
|
||||
GestureBinding.instance.cancelPointer(event.pointer);
|
||||
}
|
||||
}
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
_installZeroOffsetPointerGuard(); // Workaround for iPadOS 26.1+ modal dismissal bug
|
||||
|
||||
// Initialize settings first to get saved locale
|
||||
final settings = await SettingsService.getInstance();
|
||||
@@ -59,9 +79,11 @@ void main() async {
|
||||
futures.add(windowManager.ensureInitialized());
|
||||
}
|
||||
|
||||
// Initialize TV detection for Android
|
||||
// Initialize TV detection and PiP service for Android
|
||||
if (Platform.isAndroid) {
|
||||
futures.add(TvDetectionService.getInstance().then((_) {}));
|
||||
// Initialize PiP service to listen for PiP state changes
|
||||
PipService();
|
||||
}
|
||||
|
||||
// Configure macOS window with custom titlebar (depends on window manager)
|
||||
@@ -89,6 +111,7 @@ void main() async {
|
||||
// Initialize gamepad service for desktop platforms
|
||||
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
|
||||
GamepadService.instance.start();
|
||||
DiscordRPCService.instance.initialize();
|
||||
}
|
||||
|
||||
// DTD service is available for MCP tooling connection if needed
|
||||
@@ -129,6 +152,9 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
|
||||
_downloadManager = DownloadManagerService(database: _appDatabase, storageService: DownloadStorageService.instance);
|
||||
|
||||
_offlineWatchSyncService = OfflineWatchSyncService(database: _appDatabase, serverManager: _serverManager);
|
||||
|
||||
// Start in-app review session tracking
|
||||
InAppReviewService.instance.startSession();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -139,9 +165,19 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
// App came back to foreground - trigger sync check
|
||||
_offlineWatchSyncService.onAppResumed();
|
||||
switch (state) {
|
||||
case AppLifecycleState.resumed:
|
||||
// App came back to foreground - trigger sync check and start new session
|
||||
_offlineWatchSyncService.onAppResumed();
|
||||
InAppReviewService.instance.startSession();
|
||||
case AppLifecycleState.paused:
|
||||
case AppLifecycleState.detached:
|
||||
// App went to background or is closing - end session
|
||||
InAppReviewService.instance.endSession();
|
||||
case AppLifecycleState.inactive:
|
||||
case AppLifecycleState.hidden:
|
||||
// Transitional states - don't trigger session events
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,78 +303,6 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
_loadSavedCredentials();
|
||||
}
|
||||
|
||||
Future<void> _checkForUpdatesOnStartup() async {
|
||||
// Delay slightly to allow UI to settle
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
try {
|
||||
final updateInfo = await UpdateService.checkForUpdatesOnStartup();
|
||||
|
||||
if (updateInfo != null && updateInfo['hasUpdate'] == true && mounted) {
|
||||
_showUpdateDialog(updateInfo);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Error checking for updates', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
void _showUpdateDialog(Map<String, dynamic> updateInfo) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext dialogContext) {
|
||||
return AlertDialog(
|
||||
title: Text(t.update.available),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
t.update.versionAvailable(version: updateInfo['latestVersion']),
|
||||
style: Theme.of(dialogContext).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
t.update.currentVersion(version: updateInfo['currentVersion']),
|
||||
style: Theme.of(dialogContext).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(dialogContext);
|
||||
},
|
||||
child: Text(t.common.later),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
await UpdateService.skipVersion(updateInfo['latestVersion']);
|
||||
if (dialogContext.mounted) {
|
||||
Navigator.pop(dialogContext);
|
||||
}
|
||||
},
|
||||
child: Text(t.update.skipVersion),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final url = Uri.parse(updateInfo['releaseUrl']);
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
if (dialogContext.mounted) {
|
||||
Navigator.pop(dialogContext);
|
||||
}
|
||||
},
|
||||
child: Text(t.update.viewRelease),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _loadSavedCredentials() async {
|
||||
final storage = await StorageService.getInstance();
|
||||
final registry = ServerRegistry(storage);
|
||||
@@ -397,9 +361,6 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
final firstClient = multiServerProvider.serverManager.onlineClients.values.first;
|
||||
|
||||
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => MainScreen(client: firstClient)));
|
||||
|
||||
// Check for updates in background after navigation
|
||||
_checkForUpdatesOnStartup();
|
||||
}
|
||||
} else {
|
||||
// All connections failed - navigate to offline mode
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
|
||||
/// Mixin for screens that need to react to watch state changes.
|
||||
///
|
||||
/// Provides automatic subscription management and filtering based on
|
||||
/// which items the screen cares about.
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// class _MyScreenState extends State<MyScreen> with WatchStateAware {
|
||||
/// List<PlexMetadata> _items = [];
|
||||
///
|
||||
/// @override
|
||||
/// Set<String>? get watchedRatingKeys =>
|
||||
/// _items.map((e) => e.ratingKey).toSet();
|
||||
///
|
||||
/// @override
|
||||
/// void onWatchStateChanged(WatchStateEvent event) {
|
||||
/// // Refresh affected item
|
||||
/// _refreshItem(event.ratingKey);
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
mixin WatchStateAware<T extends StatefulWidget> on State<T> {
|
||||
StreamSubscription<WatchStateEvent>? _watchStateSubscription;
|
||||
|
||||
/// Override to specify which ratingKeys this screen cares about.
|
||||
///
|
||||
/// Return null to receive ALL events (not recommended for performance).
|
||||
/// Return an empty set to receive no events.
|
||||
///
|
||||
/// The set should include:
|
||||
/// - Direct items displayed (e.g., episode ratingKeys in a season view)
|
||||
/// - Parent items that affect display (e.g., show ratingKey for on-deck)
|
||||
Set<String>? get watchedRatingKeys;
|
||||
|
||||
/// Called when a relevant watch state change occurs.
|
||||
///
|
||||
/// Only called if [watchedRatingKeys] is null or contains an affected key.
|
||||
void onWatchStateChanged(WatchStateEvent event);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_subscribeToWatchState();
|
||||
}
|
||||
|
||||
void _subscribeToWatchState() {
|
||||
_watchStateSubscription = WatchStateNotifier().stream.listen((event) {
|
||||
if (!mounted) return;
|
||||
|
||||
final keys = watchedRatingKeys;
|
||||
// If keys is null, receive all events
|
||||
// Otherwise, filter to events that affect our keys
|
||||
if (keys == null || event.affectsAnyOf(keys)) {
|
||||
onWatchStateChanged(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_watchStateSubscription?.cancel();
|
||||
_watchStateSubscription = null;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/// Represents a single MPV configuration entry
|
||||
class MpvConfigEntry {
|
||||
final String key;
|
||||
final String value;
|
||||
final bool isEnabled;
|
||||
|
||||
const MpvConfigEntry({required this.key, required this.value, this.isEnabled = true});
|
||||
|
||||
factory MpvConfigEntry.fromJson(Map<String, dynamic> json) {
|
||||
return MpvConfigEntry(
|
||||
key: json['key'] as String,
|
||||
value: json['value'] as String,
|
||||
isEnabled: json['isEnabled'] as bool? ?? true,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {'key': key, 'value': value, 'isEnabled': isEnabled};
|
||||
|
||||
MpvConfigEntry copyWith({String? key, String? value, bool? isEnabled}) {
|
||||
return MpvConfigEntry(key: key ?? this.key, value: value ?? this.value, isEnabled: isEnabled ?? this.isEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a saved preset of MPV configurations
|
||||
class MpvPreset {
|
||||
final String name;
|
||||
final List<MpvConfigEntry> entries;
|
||||
final DateTime createdAt;
|
||||
|
||||
const MpvPreset({required this.name, required this.entries, required this.createdAt});
|
||||
|
||||
factory MpvPreset.fromJson(Map<String, dynamic> json) {
|
||||
return MpvPreset(
|
||||
name: json['name'] as String,
|
||||
entries: (json['entries'] as List).map((e) => MpvConfigEntry.fromJson(e as Map<String, dynamic>)).toList(),
|
||||
createdAt: DateTime.parse(json['createdAt'] as String),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'name': name,
|
||||
'entries': entries.map((e) => e.toJson()).toList(),
|
||||
'createdAt': createdAt.toIso8601String(),
|
||||
};
|
||||
}
|
||||
@@ -53,6 +53,7 @@ class PlexConfig {
|
||||
'X-Plex-Product': product,
|
||||
'X-Plex-Version': version,
|
||||
'X-Plex-Platform': platform,
|
||||
'X-Plex-Client-Profile-Name': 'Generic',
|
||||
if (device != null) 'X-Plex-Device': device!,
|
||||
if (acceptJson) 'Accept': 'application/json',
|
||||
'Accept-Charset': 'utf-8',
|
||||
|
||||
@@ -30,11 +30,18 @@ class PlexHub {
|
||||
final metadataList = <PlexMetadata>[];
|
||||
|
||||
// Helper function to parse entries from a JSON list
|
||||
void parseEntries(List? entries) {
|
||||
void parseEntries(List? entries, {bool isDirectory = false}) {
|
||||
if (entries == null) return;
|
||||
for (final item in entries) {
|
||||
try {
|
||||
metadataList.add(PlexMetadata.fromJson(item));
|
||||
if (isDirectory && item is Map && !item.containsKey('type')) {
|
||||
// Directory items often represent shows but might miss the type field
|
||||
// Default to 'show' if it looks like a show (has leafCount or childCount)
|
||||
// or 'folder' as a safe default
|
||||
final String type = (item.containsKey('leafCount') || item.containsKey('childCount')) ? 'show' : 'folder';
|
||||
item['type'] = type;
|
||||
}
|
||||
metadataList.add(PlexMetadata.fromJson(item as Map<String, dynamic>));
|
||||
} catch (e) {
|
||||
// Skip items that fail to parse
|
||||
}
|
||||
@@ -43,7 +50,7 @@ class PlexHub {
|
||||
|
||||
// Hubs can contain either Metadata or Directory entries
|
||||
parseEntries(json['Metadata'] as List?);
|
||||
parseEntries(json['Directory'] as List?);
|
||||
parseEntries(json['Directory'] as List?, isDirectory: true);
|
||||
|
||||
return PlexHub(
|
||||
hubKey: json['key'] as String? ?? '',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
import '../services/settings_service.dart' show EpisodePosterMode;
|
||||
import 'mixins/multi_server_fields.dart';
|
||||
import 'plex_role.dart';
|
||||
|
||||
@@ -294,27 +295,62 @@ class PlexMetadata with MultiServerFields {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Helper to get the poster (show poster for episodes/seasons, thumb otherwise)
|
||||
// If useSeasonPoster is true, episodes will use season poster instead of series poster
|
||||
String? posterThumb({bool useSeasonPoster = false}) {
|
||||
/// Returns the appropriate image path based on episode poster mode.
|
||||
/// For episodes:
|
||||
/// - seriesPoster: grandparentThumb (series poster)
|
||||
/// - seasonPoster: parentThumb (season poster)
|
||||
/// - episodeThumbnail: thumb (16:9 episode still)
|
||||
/// For seasons: returns grandparentThumb (series poster), or art/thumb in mixed hub context
|
||||
/// For movies/shows/seasons in mixed hub context: returns art (16:9 background)
|
||||
/// For other types: returns thumb
|
||||
String? posterThumb({EpisodePosterMode mode = EpisodePosterMode.seriesPoster, bool mixedHubContext = false}) {
|
||||
final itemType = type.toLowerCase();
|
||||
|
||||
if (itemType == 'episode') {
|
||||
// If season poster is enabled and available, use it
|
||||
if (useSeasonPoster && parentThumb != null) {
|
||||
return parentThumb!;
|
||||
switch (mode) {
|
||||
case EpisodePosterMode.episodeThumbnail:
|
||||
return thumb; // 16:9 episode thumbnail
|
||||
case EpisodePosterMode.seasonPoster:
|
||||
return parentThumb ?? grandparentThumb ?? thumb;
|
||||
case EpisodePosterMode.seriesPoster:
|
||||
return grandparentThumb ?? thumb;
|
||||
}
|
||||
// Otherwise fall back to series poster, then item thumb
|
||||
} else if (itemType == 'season') {
|
||||
// In mixed hub with episode thumbnail mode, use art/thumb (16:9)
|
||||
if (mixedHubContext && mode == EpisodePosterMode.episodeThumbnail) {
|
||||
return art ?? thumb;
|
||||
}
|
||||
// Otherwise use series poster (2:3)
|
||||
if (grandparentThumb != null) {
|
||||
return grandparentThumb!;
|
||||
}
|
||||
} else if (itemType == 'season' && grandparentThumb != null) {
|
||||
// For seasons, always use series poster
|
||||
return grandparentThumb!;
|
||||
}
|
||||
|
||||
// For movies/shows in mixed hub context with episode thumbnail mode, use art (16:9)
|
||||
if (mixedHubContext && mode == EpisodePosterMode.episodeThumbnail &&
|
||||
(itemType == 'movie' || itemType == 'show')) {
|
||||
return art ?? thumb;
|
||||
}
|
||||
|
||||
return thumb;
|
||||
}
|
||||
|
||||
/// Returns true if this item should use 16:9 aspect ratio.
|
||||
/// Episodes use 16:9 when in episodeThumbnail mode.
|
||||
/// Movies, shows, and seasons use 16:9 in mixed hub context with episodeThumbnail mode.
|
||||
bool usesWideAspectRatio(EpisodePosterMode mode, {bool mixedHubContext = false}) {
|
||||
final itemType = type.toLowerCase();
|
||||
if (itemType == 'episode' && mode == EpisodePosterMode.episodeThumbnail) {
|
||||
return true;
|
||||
}
|
||||
// Movies, shows, and seasons use 16:9 in mixed hubs with episode thumbnail mode
|
||||
if (mixedHubContext && mode == EpisodePosterMode.episodeThumbnail &&
|
||||
(itemType == 'movie' || itemType == 'show' || itemType == 'season')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Helper to determine if content is watched
|
||||
bool get isWatched {
|
||||
// For series/seasons, check if all episodes are watched
|
||||
|
||||
@@ -13,7 +13,15 @@ class PlexVideoPlaybackData {
|
||||
/// Available media versions/qualities for this content
|
||||
final List<PlexMediaVersion> availableVersions;
|
||||
|
||||
PlexVideoPlaybackData({required this.videoUrl, required this.mediaInfo, required this.availableVersions});
|
||||
/// Markers for intro/credits skip functionality
|
||||
final List<PlexMarker> markers;
|
||||
|
||||
PlexVideoPlaybackData({
|
||||
required this.videoUrl,
|
||||
required this.mediaInfo,
|
||||
required this.availableVersions,
|
||||
this.markers = const [],
|
||||
});
|
||||
|
||||
/// Returns true if this playback data has a valid video URL
|
||||
bool get hasValidVideoUrl => videoUrl != null && videoUrl!.isNotEmpty;
|
||||
|
||||
@@ -4,15 +4,15 @@ import 'package:flutter/services.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
/// Utility class for loading font assets on Android for libass subtitle rendering.
|
||||
/// Utility class for loading font assets for libass subtitle rendering.
|
||||
///
|
||||
/// On Android, libass cannot access system fonts through fontconfig, so we need
|
||||
/// to extract font files from Flutter assets to the app's cache directory.
|
||||
class AndroidFontLoader {
|
||||
/// Extracts font files from Flutter assets to the app's cache directory to ensure
|
||||
/// comprehensive Unicode coverage (including CJK characters) for subtitles.
|
||||
class SubtitleFontLoader {
|
||||
static const String _fontAssetPath = 'assets/go-noto-current-regular.ttf';
|
||||
static const String _fontName = 'Go Noto Current-Regular';
|
||||
|
||||
/// Loads the subtitle font from assets to the Android cache directory.
|
||||
/// Loads the subtitle font from assets to the cache directory.
|
||||
/// Returns the directory path containing the font file.
|
||||
static Future<String?> loadSubtitleFont() async {
|
||||
try {
|
||||
@@ -1,5 +1,3 @@
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../player_native.dart';
|
||||
|
||||
/// Linux implementation of [Player].
|
||||
@@ -9,19 +7,6 @@ import '../player_native.dart';
|
||||
/// the Flutter view using a GtkOverlay, with transparent regions
|
||||
/// in the Flutter UI allowing the video to show through.
|
||||
class PlayerLinux extends PlayerNative {
|
||||
static const _methodChannel = MethodChannel('com.plezy/mpv_player');
|
||||
|
||||
@override
|
||||
int? get textureId => null; // Uses GtkGLArea, not Flutter texture
|
||||
|
||||
/// Sets the visibility of the video controls overlay.
|
||||
///
|
||||
/// On Linux, due to Flutter's lack of transparency support in GtkOverlay,
|
||||
/// we hide the video layer when controls are visible and show it when
|
||||
/// controls are hidden. This provides a workaround for the transparency
|
||||
/// limitation.
|
||||
@override
|
||||
Future<void> setControlsVisible(bool visible) async {
|
||||
await _methodChannel.invokeMethod('setControlsVisible', {'visible': visible});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,13 +163,6 @@ abstract class Player {
|
||||
/// Returns true if the operation was successful.
|
||||
Future<bool> setVisible(bool visible);
|
||||
|
||||
/// Notify the player about controls visibility.
|
||||
///
|
||||
/// On Linux, due to Flutter's lack of transparency support in GtkOverlay,
|
||||
/// the video layer is hidden when controls are visible and shown when
|
||||
/// controls are hidden. On other platforms, this is a no-op.
|
||||
Future<void> setControlsVisible(bool visible);
|
||||
|
||||
/// Update the video frame/surface dimensions.
|
||||
///
|
||||
/// On iOS/macOS, this updates the Metal layer's frame to match the current
|
||||
@@ -177,6 +170,28 @@ abstract class Player {
|
||||
/// On other platforms, this is a no-op.
|
||||
Future<void> updateFrame();
|
||||
|
||||
// ============================================
|
||||
// Frame Rate Matching (Android)
|
||||
// ============================================
|
||||
|
||||
/// Set the video frame rate for display refresh rate matching.
|
||||
///
|
||||
/// On Android, this hints the system to adjust the display refresh rate
|
||||
/// to match the video content's frame rate, reducing judder and saving
|
||||
/// battery on LTPO displays.
|
||||
///
|
||||
/// [fps] - The video frame rate (e.g., 23.976, 24, 30, 60).
|
||||
/// [durationMs] - The video duration in milliseconds.
|
||||
///
|
||||
/// On other platforms, this is a no-op.
|
||||
Future<void> setVideoFrameRate(double fps, int durationMs);
|
||||
|
||||
/// Clear the video frame rate hint and restore default display mode.
|
||||
///
|
||||
/// Call this when playback ends to restore the normal display refresh rate.
|
||||
/// On other platforms, this is a no-op.
|
||||
Future<void> clearVideoFrameRate();
|
||||
|
||||
// ============================================
|
||||
// Lifecycle
|
||||
// ============================================
|
||||
|
||||
@@ -4,7 +4,8 @@ import 'dart:io' show Platform;
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../android_font_loader.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../font_loader.dart';
|
||||
import '../models.dart';
|
||||
import 'player.dart';
|
||||
import 'player_state.dart';
|
||||
@@ -44,6 +45,7 @@ class PlayerNative implements Player {
|
||||
final _errorController = StreamController<String>.broadcast();
|
||||
final _audioDeviceController = StreamController<AudioDevice>.broadcast();
|
||||
final _audioDevicesController = StreamController<List<AudioDevice>>.broadcast();
|
||||
final _playbackRestartController = StreamController<void>.broadcast();
|
||||
|
||||
StreamSubscription? _eventSubscription;
|
||||
bool _disposed = false;
|
||||
@@ -65,9 +67,45 @@ class PlayerNative implements Player {
|
||||
error: _errorController.stream,
|
||||
audioDevice: _audioDeviceController.stream,
|
||||
audioDevices: _audioDevicesController.stream,
|
||||
playbackRestart: _playbackRestartController.stream,
|
||||
);
|
||||
|
||||
_setupEventListener();
|
||||
|
||||
// Forward MPV logs to app logger
|
||||
_logController.stream.listen(_forwardToAppLogger);
|
||||
}
|
||||
|
||||
void _forwardToAppLogger(PlayerLog log) {
|
||||
final message = '[MPV:${log.prefix}] ${log.text}'.trimRight();
|
||||
switch (log.level) {
|
||||
case PlayerLogLevel.fatal:
|
||||
case PlayerLogLevel.error:
|
||||
appLogger.e(message);
|
||||
case PlayerLogLevel.warn:
|
||||
appLogger.w(message);
|
||||
case PlayerLogLevel.info:
|
||||
case PlayerLogLevel.verbose:
|
||||
appLogger.i(message);
|
||||
case PlayerLogLevel.debug:
|
||||
case PlayerLogLevel.trace:
|
||||
appLogger.d(message);
|
||||
case PlayerLogLevel.none:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
PlayerLogLevel _parseLogLevel(String level) {
|
||||
return switch (level) {
|
||||
'fatal' => PlayerLogLevel.fatal,
|
||||
'error' => PlayerLogLevel.error,
|
||||
'warn' => PlayerLogLevel.warn,
|
||||
'info' => PlayerLogLevel.info,
|
||||
'v' || 'verbose' => PlayerLogLevel.verbose,
|
||||
'debug' => PlayerLogLevel.debug,
|
||||
'trace' => PlayerLogLevel.trace,
|
||||
_ => PlayerLogLevel.info,
|
||||
};
|
||||
}
|
||||
|
||||
void _setupEventListener() {
|
||||
@@ -203,6 +241,19 @@ class PlayerNative implements Player {
|
||||
_state = _state.copyWith(completed: false);
|
||||
_completedController.add(false);
|
||||
break;
|
||||
|
||||
case 'playback-restart':
|
||||
// Playback started/restarted - first frame is ready
|
||||
_playbackRestartController.add(null);
|
||||
break;
|
||||
|
||||
case 'log-message':
|
||||
final prefix = data?['prefix'] as String? ?? '';
|
||||
final levelStr = data?['level'] as String? ?? 'info';
|
||||
final text = data?['text'] as String? ?? '';
|
||||
final level = _parseLogLevel(levelStr);
|
||||
_logController.add(PlayerLog(level: level, prefix: prefix, text: text));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,11 +305,18 @@ class PlayerNative implements Player {
|
||||
}
|
||||
|
||||
void _updateSelectedSubtitleTrack(dynamic trackId) {
|
||||
_updateSelectedTrack<SubtitleTrack>(
|
||||
trackId,
|
||||
_state.tracks.subtitle.cast<SubtitleTrack?>().toList(),
|
||||
(selection, track) => selection.copyWith(subtitle: track),
|
||||
);
|
||||
final id = trackId?.toString();
|
||||
SubtitleTrack? selectedTrack;
|
||||
|
||||
if (id == null || id == 'no') {
|
||||
// Explicitly set SubtitleTrack.off so episode navigation can detect "subtitles off"
|
||||
selectedTrack = SubtitleTrack.off;
|
||||
} else {
|
||||
selectedTrack = _state.tracks.subtitle.cast<SubtitleTrack?>().firstWhere((t) => t?.id == id, orElse: () => null);
|
||||
}
|
||||
|
||||
_state = _state.copyWith(track: _state.track.copyWith(subtitle: selectedTrack));
|
||||
_trackController.add(_state.track);
|
||||
}
|
||||
|
||||
void _updateSelectedTrack<T>(
|
||||
@@ -292,10 +350,8 @@ class PlayerNative implements Player {
|
||||
throw Exception('Failed to initialize player');
|
||||
}
|
||||
|
||||
// Configure subtitle fonts for Android libass support
|
||||
if (Platform.isAndroid) {
|
||||
await _configureAndroidSubtitleFonts();
|
||||
}
|
||||
// Configure subtitle fonts for libass support
|
||||
await _configureSubtitleFonts();
|
||||
|
||||
// Subscribe to MPV properties
|
||||
await _observeProperty('time-pos', 'double');
|
||||
@@ -305,6 +361,7 @@ class PlayerNative implements Player {
|
||||
await _observeProperty('track-list', (Platform.isAndroid || Platform.isWindows) ? 'string' : 'node');
|
||||
await _observeProperty('eof-reached', 'flag');
|
||||
await _observeProperty('volume', 'double');
|
||||
await _observeProperty('speed', 'double');
|
||||
await _observeProperty('aid', 'string');
|
||||
await _observeProperty('sid', 'string');
|
||||
} catch (e) {
|
||||
@@ -317,17 +374,17 @@ class PlayerNative implements Player {
|
||||
await _methodChannel.invokeMethod('observeProperty', {'name': name, 'format': format});
|
||||
}
|
||||
|
||||
/// Configures subtitle fonts for Android libass support.
|
||||
/// On Android, libass cannot access system fonts, so we need to provide
|
||||
/// a font file from assets.
|
||||
Future<void> _configureAndroidSubtitleFonts() async {
|
||||
/// Configures subtitle fonts for libass support.
|
||||
/// Provides a comprehensive Unicode font (Go Noto) with CJK coverage to ensure
|
||||
/// proper rendering of non-Latin characters in subtitles.
|
||||
Future<void> _configureSubtitleFonts() async {
|
||||
try {
|
||||
final fontDir = await AndroidFontLoader.loadSubtitleFont();
|
||||
final fontDir = await SubtitleFontLoader.loadSubtitleFont();
|
||||
if (fontDir != null) {
|
||||
// Configure MPV to use the extracted font for libass
|
||||
await setProperty('config', 'yes');
|
||||
await setProperty('sub-fonts-dir', fontDir);
|
||||
await setProperty('sub-font', AndroidFontLoader.fontName);
|
||||
await setProperty('sub-font', SubtitleFontLoader.fontName);
|
||||
}
|
||||
} catch (e) {
|
||||
// Font configuration is not critical - continue without it
|
||||
@@ -350,8 +407,14 @@ class PlayerNative implements Player {
|
||||
_checkDisposed();
|
||||
await _ensureInitialized();
|
||||
|
||||
// Show the video layer
|
||||
await _methodChannel.invokeMethod('setVisible', {'visible': true});
|
||||
// Show the video layer (use error-handled method)
|
||||
await setVisible(true);
|
||||
|
||||
// Set HTTP headers for Plex authentication and profile
|
||||
if (media.headers != null && media.headers!.isNotEmpty) {
|
||||
final headerList = media.headers!.entries.map((e) => '${e.key}: ${e.value}').toList();
|
||||
await setProperty('http-header-fields', headerList.join(','));
|
||||
}
|
||||
|
||||
// Set start position if provided (must be set before loading file)
|
||||
if (media.start != null && media.start!.inSeconds > 0) {
|
||||
@@ -361,10 +424,14 @@ class PlayerNative implements Player {
|
||||
await setProperty('start', 'none');
|
||||
}
|
||||
|
||||
await command(['loadfile', media.uri, 'replace']);
|
||||
// Set pause BEFORE loadfile to prevent decoder from starting immediately.
|
||||
// This is important for adding external subtitles before playback begins,
|
||||
// avoiding a race condition that can freeze the video decoder on Android (issue #226).
|
||||
if (!play) {
|
||||
await setProperty('pause', 'yes');
|
||||
}
|
||||
|
||||
await command(['loadfile', media.uri, 'replace']);
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -507,11 +574,6 @@ class PlayerNative implements Player {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setControlsVisible(bool visible) async {
|
||||
// No-op on most platforms. Override on Linux for transparency workaround.
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> updateFrame() async {
|
||||
_checkDisposed();
|
||||
@@ -522,6 +584,28 @@ class PlayerNative implements Player {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Frame Rate Matching (Android)
|
||||
// ============================================
|
||||
|
||||
@override
|
||||
Future<void> setVideoFrameRate(double fps, int durationMs) async {
|
||||
_checkDisposed();
|
||||
if (!Platform.isAndroid) return;
|
||||
if (!_initialized) return;
|
||||
|
||||
await _methodChannel.invokeMethod('setVideoFrameRate', {'fps': fps, 'duration': durationMs});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearVideoFrameRate() async {
|
||||
_checkDisposed();
|
||||
if (!Platform.isAndroid) return;
|
||||
if (!_initialized) return;
|
||||
|
||||
await _methodChannel.invokeMethod('clearVideoFrameRate');
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Lifecycle
|
||||
// ============================================
|
||||
@@ -548,5 +632,6 @@ class PlayerNative implements Player {
|
||||
await _errorController.close();
|
||||
await _audioDeviceController.close();
|
||||
await _audioDevicesController.close();
|
||||
await _playbackRestartController.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ class PlayerStreams {
|
||||
/// Stream of available audio devices.
|
||||
final Stream<List<AudioDevice>> audioDevices;
|
||||
|
||||
/// Stream that emits when playback restarts (first frame ready after load/seek).
|
||||
final Stream<void> playbackRestart;
|
||||
|
||||
const PlayerStreams({
|
||||
required this.playing,
|
||||
required this.completed,
|
||||
@@ -62,5 +65,6 @@ class PlayerStreams {
|
||||
required this.error,
|
||||
required this.audioDevice,
|
||||
required this.audioDevices,
|
||||
required this.playbackRestart,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../services/offline_watch_sync_service.dart';
|
||||
import '../services/plex_api_cache.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import 'download_provider.dart';
|
||||
|
||||
/// Provider for offline watch status UI state.
|
||||
@@ -106,6 +107,22 @@ class OfflineWatchProvider extends ChangeNotifier {
|
||||
return episodes;
|
||||
}
|
||||
|
||||
/// Batch resolve watch statuses for a list of episodes.
|
||||
///
|
||||
/// Returns a map of globalKey -> isWatched for each episode.
|
||||
Future<Map<String, bool>> _resolveEpisodeWatchStatuses(List<PlexMetadata> episodes) async {
|
||||
if (episodes.isEmpty) return {};
|
||||
|
||||
final globalKeys = episodes.map((e) => e.globalKey).toSet();
|
||||
final localStatuses = await _syncService.getLocalWatchStatusesBatched(globalKeys);
|
||||
|
||||
return {
|
||||
for (final episode in episodes)
|
||||
episode.globalKey:
|
||||
localStatuses[episode.globalKey] ?? _downloadProvider.getMetadata(episode.globalKey)?.isWatched ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Find the next unwatched downloaded episode for a show.
|
||||
///
|
||||
/// This is the "offline OnDeck" calculation - finds the first
|
||||
@@ -118,15 +135,11 @@ class OfflineWatchProvider extends ChangeNotifier {
|
||||
final episodes = _getSortedEpisodes(showRatingKey);
|
||||
if (episodes.isEmpty) return null;
|
||||
|
||||
// Batch fetch all watch statuses in a single query
|
||||
final globalKeys = episodes.map((e) => e.globalKey).toSet();
|
||||
final localStatuses = await _syncService.getLocalWatchStatusesBatched(globalKeys);
|
||||
final watchStatuses = await _resolveEpisodeWatchStatuses(episodes);
|
||||
|
||||
// Find first unwatched episode
|
||||
for (final episode in episodes) {
|
||||
final localStatus = localStatuses[episode.globalKey];
|
||||
final watched = localStatus ?? _downloadProvider.getMetadata(episode.globalKey)?.isWatched ?? false;
|
||||
if (!watched) {
|
||||
if (!watchStatuses[episode.globalKey]!) {
|
||||
return episode;
|
||||
}
|
||||
}
|
||||
@@ -156,17 +169,57 @@ class OfflineWatchProvider extends ChangeNotifier {
|
||||
|
||||
/// Mark an item as watched while offline.
|
||||
///
|
||||
/// This queues the action for sync when online.
|
||||
/// This queues the action for sync when online and emits a [WatchStateEvent].
|
||||
Future<void> markAsWatched({required String serverId, required String ratingKey}) async {
|
||||
await _syncService.queueMarkWatched(serverId: serverId, ratingKey: ratingKey);
|
||||
|
||||
// Emit event for immediate UI update
|
||||
final globalKey = '$serverId:$ratingKey';
|
||||
final metadata = _downloadProvider.getMetadata(globalKey);
|
||||
if (metadata != null) {
|
||||
WatchStateNotifier().notifyWatched(metadata: metadata, isNowWatched: true);
|
||||
} else {
|
||||
// Fallback: emit minimal event without parent chain
|
||||
WatchStateNotifier().notify(
|
||||
WatchStateEvent(
|
||||
ratingKey: ratingKey,
|
||||
serverId: serverId,
|
||||
changeType: WatchStateChangeType.watched,
|
||||
parentChain: [],
|
||||
mediaType: 'unknown',
|
||||
isNowWatched: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Mark an item as unwatched while offline.
|
||||
///
|
||||
/// This queues the action for sync when online.
|
||||
/// This queues the action for sync when online and emits a [WatchStateEvent].
|
||||
Future<void> markAsUnwatched({required String serverId, required String ratingKey}) async {
|
||||
await _syncService.queueMarkUnwatched(serverId: serverId, ratingKey: ratingKey);
|
||||
|
||||
// Emit event for immediate UI update
|
||||
final globalKey = '$serverId:$ratingKey';
|
||||
final metadata = _downloadProvider.getMetadata(globalKey);
|
||||
if (metadata != null) {
|
||||
WatchStateNotifier().notifyWatched(metadata: metadata, isNowWatched: false);
|
||||
} else {
|
||||
// Fallback: emit minimal event without parent chain
|
||||
WatchStateNotifier().notify(
|
||||
WatchStateEvent(
|
||||
ratingKey: ratingKey,
|
||||
serverId: serverId,
|
||||
changeType: WatchStateChangeType.unwatched,
|
||||
parentChain: [],
|
||||
mediaType: 'unknown',
|
||||
isNowWatched: false,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -176,21 +229,11 @@ class OfflineWatchProvider extends ChangeNotifier {
|
||||
/// Uses batched database query for efficiency.
|
||||
Future<List<(PlexMetadata episode, bool isWatched)>> getEpisodesWithWatchStatus(String showRatingKey) async {
|
||||
final episodes = _downloadProvider.getDownloadedEpisodesForShow(showRatingKey);
|
||||
|
||||
if (episodes.isEmpty) return [];
|
||||
|
||||
// Batch fetch all watch statuses in a single query
|
||||
final globalKeys = episodes.map((e) => e.globalKey).toSet();
|
||||
final localStatuses = await _syncService.getLocalWatchStatusesBatched(globalKeys);
|
||||
final watchStatuses = await _resolveEpisodeWatchStatuses(episodes);
|
||||
|
||||
final results = <(PlexMetadata, bool)>[];
|
||||
for (final episode in episodes) {
|
||||
final localStatus = localStatuses[episode.globalKey];
|
||||
final watched = localStatus ?? _downloadProvider.getMetadata(episode.globalKey)?.isWatched ?? false;
|
||||
results.add((episode, watched));
|
||||
}
|
||||
|
||||
return results;
|
||||
return [for (final episode in episodes) (episode, watchStatuses[episode.globalKey]!)];
|
||||
}
|
||||
|
||||
/// Trigger a manual sync of pending items.
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../services/settings_service.dart';
|
||||
|
||||
class SettingsProvider extends ChangeNotifier {
|
||||
SettingsService? _settingsService;
|
||||
LibraryDensity _libraryDensity = LibraryDensity.normal;
|
||||
ViewMode _viewMode = ViewMode.grid;
|
||||
bool _useSeasonPoster = false;
|
||||
EpisodePosterMode _episodePosterMode = EpisodePosterMode.seriesPoster;
|
||||
bool _showHeroSection = true;
|
||||
bool _useGlobalHubs = true;
|
||||
bool _isInitialized = false;
|
||||
Future<void>? _initFuture;
|
||||
|
||||
@@ -25,8 +27,9 @@ class SettingsProvider extends ChangeNotifier {
|
||||
_settingsService = await SettingsService.getInstance();
|
||||
_libraryDensity = _settingsService!.getLibraryDensity();
|
||||
_viewMode = _settingsService!.getViewMode();
|
||||
_useSeasonPoster = _settingsService!.getUseSeasonPoster();
|
||||
_episodePosterMode = _settingsService!.getEpisodePosterMode();
|
||||
_showHeroSection = _settingsService!.getShowHeroSection();
|
||||
_useGlobalHubs = _settingsService!.getUseGlobalHubs();
|
||||
_isInitialized = true;
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -38,10 +41,12 @@ class SettingsProvider extends ChangeNotifier {
|
||||
|
||||
ViewMode get viewMode => _viewMode;
|
||||
|
||||
bool get useSeasonPoster => _useSeasonPoster;
|
||||
EpisodePosterMode get episodePosterMode => _episodePosterMode;
|
||||
|
||||
bool get showHeroSection => _showHeroSection;
|
||||
|
||||
bool get useGlobalHubs => _useGlobalHubs;
|
||||
|
||||
Future<void> setLibraryDensity(LibraryDensity density) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_libraryDensity != density) {
|
||||
@@ -60,11 +65,11 @@ class SettingsProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setUseSeasonPoster(bool value) async {
|
||||
Future<void> setEpisodePosterMode(EpisodePosterMode mode) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_useSeasonPoster != value) {
|
||||
_useSeasonPoster = value;
|
||||
await _settingsService!.setUseSeasonPoster(value);
|
||||
if (_episodePosterMode != mode) {
|
||||
_episodePosterMode = mode;
|
||||
await _settingsService!.setEpisodePosterMode(mode);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -78,6 +83,15 @@ class SettingsProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setUseGlobalHubs(bool value) async {
|
||||
if (!_isInitialized) await _initializeSettings();
|
||||
if (_useGlobalHubs != value) {
|
||||
_useGlobalHubs = value;
|
||||
await _settingsService!.setUseGlobalHubs(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
String get libraryDensityDisplayName {
|
||||
switch (_libraryDensity) {
|
||||
case LibraryDensity.compact:
|
||||
@@ -88,4 +102,15 @@ class SettingsProvider extends ChangeNotifier {
|
||||
return 'Comfortable';
|
||||
}
|
||||
}
|
||||
|
||||
String get episodePosterModeDisplayName {
|
||||
switch (_episodePosterMode) {
|
||||
case EpisodePosterMode.seriesPoster:
|
||||
return t.settings.seriesPoster;
|
||||
case EpisodePosterMode.seasonPoster:
|
||||
return t.settings.seasonPoster;
|
||||
case EpisodePosterMode.episodeThumbnail:
|
||||
return t.settings.episodeThumbnail;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:plezy/widgets/app_icon.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../models/plex_hub.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_sort.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../services/settings_service.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../widgets/media_grid_sliver.dart';
|
||||
@@ -245,11 +248,35 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
|
||||
else if (_filteredItems.isEmpty)
|
||||
SliverFillRemaining(child: Center(child: Text(t.hubDetail.noItemsFound)))
|
||||
else
|
||||
MediaGridSliver(
|
||||
items: _filteredItems,
|
||||
onRefresh: _handleItemRefresh,
|
||||
usePaddingAwareExtent: true,
|
||||
horizontalPadding: 16,
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final episodePosterMode = context.watch<SettingsProvider>().episodePosterMode;
|
||||
|
||||
// Determine hub content type for layout decisions
|
||||
final hasEpisodes = _filteredItems.any((item) =>
|
||||
item.usesWideAspectRatio(episodePosterMode));
|
||||
final hasNonEpisodes = _filteredItems.any((item) =>
|
||||
!item.usesWideAspectRatio(episodePosterMode));
|
||||
|
||||
// Mixed hub = has both episodes AND non-episodes
|
||||
final isMixedHub = hasEpisodes && hasNonEpisodes;
|
||||
|
||||
// Episode-only = all items are episodes with thumbnails
|
||||
final isEpisodeOnlyHub = hasEpisodes && !hasNonEpisodes;
|
||||
|
||||
// Use 16:9 for episode-only hubs OR mixed hubs (with episode thumbnail mode)
|
||||
final useWideLayout = episodePosterMode == EpisodePosterMode.episodeThumbnail &&
|
||||
(isEpisodeOnlyHub || isMixedHub);
|
||||
|
||||
return MediaGridSliver(
|
||||
items: _filteredItems,
|
||||
onRefresh: _handleItemRefresh,
|
||||
usePaddingAwareExtent: true,
|
||||
horizontalPadding: 16,
|
||||
useWideAspectRatio: useWideLayout,
|
||||
mixedHubContext: isMixedHub,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -169,10 +169,19 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
|
||||
/// Focus the first item in the currently active tab
|
||||
void _focusCurrentTab() {
|
||||
// Don't focus during tab animations - wait for animation to complete
|
||||
// This prevents race conditions during focus restoration
|
||||
if (_tabController.indexIsChanging) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-enable auto-focus since user is navigating into tab content
|
||||
setState(() {
|
||||
_suppressAutoFocus = false;
|
||||
});
|
||||
// Only call setState if the value actually changes to avoid unnecessary rebuilds
|
||||
if (_suppressAutoFocus) {
|
||||
setState(() {
|
||||
_suppressAutoFocus = false;
|
||||
});
|
||||
}
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
@@ -482,13 +491,10 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
if (savedTabIndex != null && savedTabIndex >= 0 && savedTabIndex < 4) {
|
||||
// Set flag to prevent _onTabChanged from triggering focus
|
||||
_isRestoringTab = true;
|
||||
_updateState(() {
|
||||
_tabController.index = savedTabIndex;
|
||||
});
|
||||
// Clear flag after the tab change has been processed
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_isRestoringTab = false;
|
||||
});
|
||||
// Use animateTo with zero duration for instant switch without animation race conditions
|
||||
_tabController.animateTo(savedTabIndex, duration: Duration.zero);
|
||||
// Clear flag synchronously - animateTo with zero duration completes immediately
|
||||
_isRestoringTab = false;
|
||||
}
|
||||
|
||||
// Focus is handled by onDataLoaded callbacks from each tab.
|
||||
@@ -1107,6 +1113,11 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
child: TabBarView(
|
||||
key: ValueKey(_selectedLibraryGlobalKey),
|
||||
controller: _tabController,
|
||||
// Disable swipe on desktop - trackpad scrolling triggers accidental tab switches
|
||||
// See: https://github.com/flutter/flutter/issues/11132
|
||||
physics: PlatformDetector.isDesktop(context)
|
||||
? const NeverScrollableScrollPhysics()
|
||||
: null,
|
||||
children: [
|
||||
LibraryRecommendedTab(
|
||||
key: _recommendedTabKey,
|
||||
|
||||
@@ -18,7 +18,7 @@ import '../filters_bottom_sheet.dart';
|
||||
import '../sort_bottom_sheet.dart';
|
||||
import '../state_messages.dart';
|
||||
import '../../../services/storage_service.dart';
|
||||
import '../../../services/settings_service.dart' show ViewMode;
|
||||
import '../../../services/settings_service.dart' show ViewMode, EpisodePosterMode;
|
||||
import '../../../mixins/item_updatable.dart';
|
||||
import '../../../i18n/strings.g.dart';
|
||||
import 'base_library_tab.dart';
|
||||
@@ -460,87 +460,24 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
Widget build(BuildContext context) {
|
||||
super.build(context); // Required for AutomaticKeepAliveClientMixin
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
// Filter bar with chips
|
||||
Container(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
alignment: Alignment.centerLeft,
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Grouping chip
|
||||
FocusableFilterChip(
|
||||
focusNode: _groupingChipFocusNode,
|
||||
icon: Symbols.category_rounded,
|
||||
label: _getGroupingLabel(_selectedGrouping),
|
||||
onPressed: _showGroupingBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Filters chip
|
||||
if (_filters.isNotEmpty && _selectedGrouping != 'folders')
|
||||
FocusableFilterChip(
|
||||
focusNode: _filtersChipFocusNode,
|
||||
icon: Symbols.filter_alt_rounded,
|
||||
label: _selectedFilters.isEmpty
|
||||
? t.libraries.filters
|
||||
: t.libraries.filtersWithCount(count: _selectedFilters.length),
|
||||
onPressed: _showFiltersBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
if (_filters.isNotEmpty && _selectedGrouping != 'folders') const SizedBox(width: 8),
|
||||
// Sort chip
|
||||
if (_sortOptions.isNotEmpty && _selectedGrouping != 'folders')
|
||||
FocusableFilterChip(
|
||||
focusNode: _sortChipFocusNode,
|
||||
icon: Symbols.sort_rounded,
|
||||
label: _selectedSort?.title ?? t.libraries.sort,
|
||||
onPressed: _showSortBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
],
|
||||
// For folders mode, keep the column structure with FolderTreeView
|
||||
if (_selectedGrouping == 'folders') {
|
||||
return Column(
|
||||
children: [
|
||||
_buildChipsBar(),
|
||||
Expanded(
|
||||
child: FolderTreeView(
|
||||
libraryKey: widget.library.key,
|
||||
serverId: widget.library.serverId,
|
||||
onRefresh: updateItem,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Content
|
||||
Expanded(child: _buildContent()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent() {
|
||||
// Show folder tree view when in folders mode
|
||||
if (_selectedGrouping == 'folders') {
|
||||
return FolderTreeView(libraryKey: widget.library.key, serverId: widget.library.serverId, onRefresh: updateItem);
|
||||
}
|
||||
|
||||
if (isLoading && items.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (errorMessage != null && items.isEmpty) {
|
||||
return ErrorStateWidget(
|
||||
message: errorMessage!,
|
||||
icon: Symbols.error_outline_rounded,
|
||||
onRetry: _loadContent,
|
||||
retryLabel: t.common.retry,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (items.isEmpty) {
|
||||
return EmptyStateWidget(message: t.libraries.thisLibraryIsEmpty, icon: Symbols.folder_open_rounded);
|
||||
}
|
||||
|
||||
// For list/grid modes, use CustomScrollView with slivers
|
||||
// Chips are pinned at the top while content scrolls underneath
|
||||
return NotificationListener<ScrollNotification>(
|
||||
onNotification: (notification) {
|
||||
if (notification.metrics.pixels >= notification.metrics.maxScrollExtent - 300 && _hasMoreItems && !isLoading) {
|
||||
@@ -548,33 +485,133 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
}
|
||||
return false;
|
||||
},
|
||||
child: Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return _buildItemsView(context, settingsProvider);
|
||||
},
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
// Pinned chips bar - stays at top while content scrolls underneath
|
||||
SliverPersistentHeader(pinned: true, delegate: _ChipsHeaderDelegate(child: _buildChipsBar())),
|
||||
|
||||
// Content slivers
|
||||
..._buildContentSlivers(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds either a list or grid view based on the view mode
|
||||
Widget _buildItemsView(BuildContext context, SettingsProvider settingsProvider) {
|
||||
/// Builds the chips bar widget
|
||||
Widget _buildChipsBar() {
|
||||
return Container(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Grouping chip
|
||||
FocusableFilterChip(
|
||||
focusNode: _groupingChipFocusNode,
|
||||
icon: Symbols.category_rounded,
|
||||
label: _getGroupingLabel(_selectedGrouping),
|
||||
onPressed: _showGroupingBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Filters chip
|
||||
if (_filters.isNotEmpty && _selectedGrouping != 'folders')
|
||||
FocusableFilterChip(
|
||||
focusNode: _filtersChipFocusNode,
|
||||
icon: Symbols.filter_alt_rounded,
|
||||
label: _selectedFilters.isEmpty
|
||||
? t.libraries.filters
|
||||
: t.libraries.filtersWithCount(count: _selectedFilters.length),
|
||||
onPressed: _showFiltersBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
if (_filters.isNotEmpty && _selectedGrouping != 'folders') const SizedBox(width: 8),
|
||||
// Sort chip
|
||||
if (_sortOptions.isNotEmpty && _selectedGrouping != 'folders')
|
||||
FocusableFilterChip(
|
||||
focusNode: _sortChipFocusNode,
|
||||
icon: Symbols.sort_rounded,
|
||||
label: _selectedSort?.title ?? t.libraries.sort,
|
||||
onPressed: _showSortBottomSheet,
|
||||
onNavigateDown: _navigateToGrid,
|
||||
onNavigateUp: widget.onBack,
|
||||
onBack: widget.onBack,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds content as slivers for the CustomScrollView
|
||||
List<Widget> _buildContentSlivers() {
|
||||
if (isLoading && items.isEmpty) {
|
||||
return [const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))];
|
||||
}
|
||||
|
||||
if (errorMessage != null && items.isEmpty) {
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
child: ErrorStateWidget(
|
||||
message: errorMessage!,
|
||||
icon: Symbols.error_outline_rounded,
|
||||
onRetry: _loadContent,
|
||||
retryLabel: t.common.retry,
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
if (items.isEmpty) {
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
child: EmptyStateWidget(message: t.libraries.thisLibraryIsEmpty, icon: Symbols.folder_open_rounded),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return _buildItemsSliver(context, settingsProvider);
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// Builds either a sliver list or sliver grid based on the view mode
|
||||
Widget _buildItemsSliver(BuildContext context, SettingsProvider settingsProvider) {
|
||||
final itemCount = items.length + (_hasMoreItems && isLoading ? 1 : 0);
|
||||
|
||||
if (settingsProvider.viewMode == ViewMode.list) {
|
||||
// In list view, only the first item can navigate up to chips
|
||||
return ListView.builder(
|
||||
return SliverPadding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(index, isFirstRow: index == 0),
|
||||
sliver: SliverList.builder(
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(index, isFirstRow: index == 0),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// In grid view, calculate columns and pass to item builder
|
||||
final columnCount = _getGridColumnCount(context, settingsProvider);
|
||||
return GridView.builder(
|
||||
// Use 16:9 aspect ratio when browsing episodes with episode thumbnail mode
|
||||
final useWideRatio =
|
||||
_selectedGrouping == 'episodes' && settingsProvider.episodePosterMode == EpisodePosterMode.episodeThumbnail;
|
||||
return SliverPadding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
gridDelegate: MediaGridDelegate.createDelegate(context: context, density: settingsProvider.libraryDensity),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(index, isFirstRow: _isFirstRow(index, columnCount)),
|
||||
sliver: SliverGrid.builder(
|
||||
gridDelegate: MediaGridDelegate.createDelegate(
|
||||
context: context,
|
||||
density: settingsProvider.libraryDensity,
|
||||
useWideAspectRatio: useWideRatio,
|
||||
),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => _buildMediaCardItem(index, isFirstRow: _isFirstRow(index, columnCount)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -597,3 +634,26 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Delegate for pinned chips header that stays fixed at the top while content scrolls underneath
|
||||
class _ChipsHeaderDelegate extends SliverPersistentHeaderDelegate {
|
||||
final Widget child;
|
||||
|
||||
_ChipsHeaderDelegate({required this.child});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
|
||||
return Container(color: Theme.of(context).scaffoldBackgroundColor, child: child);
|
||||
}
|
||||
|
||||
@override
|
||||
double get maxExtent => 40.0; // Height of chips bar
|
||||
|
||||
@override
|
||||
double get minExtent => 40.0; // Same as max (no shrinking)
|
||||
|
||||
@override
|
||||
bool shouldRebuild(covariant _ChipsHeaderDelegate oldDelegate) {
|
||||
return child != oldDelegate.child;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import '../../services/plex_client.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../services/update_service.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/platform_detector.dart';
|
||||
@@ -123,9 +126,75 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
if (!_isSidebarFocused) {
|
||||
_contentFocusScope.requestFocus();
|
||||
}
|
||||
|
||||
// Check for updates on startup
|
||||
_checkForUpdatesOnStartup();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _checkForUpdatesOnStartup() async {
|
||||
// Delay slightly to allow UI to settle
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
try {
|
||||
final updateInfo = await UpdateService.checkForUpdatesOnStartup();
|
||||
|
||||
if (updateInfo != null && updateInfo['hasUpdate'] == true && mounted) {
|
||||
_showUpdateDialog(updateInfo);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Error checking for updates', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
void _showUpdateDialog(Map<String, dynamic> updateInfo) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext dialogContext) {
|
||||
return AlertDialog(
|
||||
title: Text(t.update.available),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
t.update.versionAvailable(version: updateInfo['latestVersion']),
|
||||
style: Theme.of(dialogContext).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
t.update.currentVersion(version: updateInfo['currentVersion']),
|
||||
style: Theme.of(dialogContext).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.common.later)),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
await UpdateService.skipVersion(updateInfo['latestVersion']);
|
||||
if (dialogContext.mounted) Navigator.pop(dialogContext);
|
||||
},
|
||||
child: Text(t.update.skipVersion),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final url = Uri.parse(updateInfo['releaseUrl']);
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
if (dialogContext.mounted) Navigator.pop(dialogContext);
|
||||
},
|
||||
child: Text(t.update.viewRelease),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Set up the Watch Together navigation callback for guests
|
||||
void _setupWatchTogetherCallback() {
|
||||
try {
|
||||
|
||||
@@ -30,6 +30,8 @@ import '../widgets/horizontal_scroll_with_arrows.dart';
|
||||
import '../widgets/focusable_media_card.dart';
|
||||
import '../widgets/media_context_menu.dart';
|
||||
import '../widgets/placeholder_container.dart';
|
||||
import '../mixins/watch_state_aware.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import 'season_detail_screen.dart';
|
||||
|
||||
class MediaDetailScreen extends StatefulWidget {
|
||||
@@ -42,7 +44,7 @@ class MediaDetailScreen extends StatefulWidget {
|
||||
State<MediaDetailScreen> createState() => _MediaDetailScreenState();
|
||||
}
|
||||
|
||||
class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
class _MediaDetailScreenState extends State<MediaDetailScreen> with WatchStateAware {
|
||||
List<PlexMetadata> _seasons = [];
|
||||
bool _isLoadingSeasons = false;
|
||||
PlexMetadata? _fullMetadata;
|
||||
@@ -53,6 +55,61 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
bool _watchStateChanged = false;
|
||||
double _scrollOffset = 0;
|
||||
|
||||
// WatchStateAware: watch the show/movie and all season ratingKeys
|
||||
@override
|
||||
Set<String>? get watchedRatingKeys {
|
||||
final keys = <String>{widget.metadata.ratingKey};
|
||||
for (final season in _seasons) {
|
||||
keys.add(season.ratingKey);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
@override
|
||||
void onWatchStateChanged(WatchStateEvent event) {
|
||||
// Lightweight refresh - no loader, preserves scroll position
|
||||
if (!widget.isOffline) {
|
||||
_refreshWatchState();
|
||||
}
|
||||
}
|
||||
|
||||
/// Lightweight refresh for watch state changes - no loader, preserves scroll
|
||||
Future<void> _refreshWatchState() async {
|
||||
final client = _getClientForMetadata(context);
|
||||
if (client == null) return;
|
||||
|
||||
try {
|
||||
// Fetch updated metadata + on-deck without showing loader
|
||||
final result = await client.getMetadataWithImagesAndOnDeck(widget.metadata.ratingKey);
|
||||
final metadata = result['metadata'] as PlexMetadata?;
|
||||
final onDeckEpisode = result['onDeckEpisode'] as PlexMetadata?;
|
||||
|
||||
if (metadata != null && mounted) {
|
||||
setState(() {
|
||||
_fullMetadata = metadata.copyWith(serverId: widget.metadata.serverId, serverName: widget.metadata.serverName);
|
||||
_onDeckEpisode = onDeckEpisode?.copyWith(
|
||||
serverId: widget.metadata.serverId,
|
||||
serverName: widget.metadata.serverName,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Refresh seasons for updated watched counts (also without loader)
|
||||
if (widget.metadata.isShow) {
|
||||
final seasons = await client.getChildren(widget.metadata.ratingKey);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_seasons = seasons
|
||||
.map((s) => s.copyWith(serverId: widget.metadata.serverId, serverName: widget.metadata.serverName))
|
||||
.toList();
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Silently fail - data will refresh on next navigation
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
@@ -54,12 +54,16 @@ class _PlaylistItemCardState extends State<PlaylistItemCard> {
|
||||
child: Row(
|
||||
children: [
|
||||
// Drag handle (if reorderable)
|
||||
// Wrapped in GestureDetector to consume long-press and prevent context menu
|
||||
if (widget.canReorder)
|
||||
ReorderableDragStartListener(
|
||||
index: widget.index,
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.only(right: 12),
|
||||
child: AppIcon(Symbols.drag_indicator_rounded, fill: 1, color: Colors.grey),
|
||||
GestureDetector(
|
||||
onLongPress: () {},
|
||||
child: ReorderableDragStartListener(
|
||||
index: widget.index,
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.only(right: 12),
|
||||
child: AppIcon(Symbols.drag_indicator_rounded, fill: 1, color: Colors.grey),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/media_context_menu.dart';
|
||||
import '../widgets/placeholder_container.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
import '../mixins/watch_state_aware.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import '../theme/mono_tokens.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
|
||||
@@ -32,7 +34,7 @@ class SeasonDetailScreen extends StatefulWidget {
|
||||
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
|
||||
}
|
||||
|
||||
class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdatable {
|
||||
class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdatable, WatchStateAware {
|
||||
PlexClient? _client;
|
||||
|
||||
@override
|
||||
@@ -41,6 +43,20 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdata
|
||||
List<PlexMetadata> _episodes = [];
|
||||
bool _isLoadingEpisodes = false;
|
||||
bool _watchStateChanged = false;
|
||||
// Capture keyboard mode once at init to avoid rebuild dependency
|
||||
bool _initialKeyboardMode = false;
|
||||
|
||||
// WatchStateAware: watch all episode ratingKeys
|
||||
@override
|
||||
Set<String>? get watchedRatingKeys => _episodes.map((e) => e.ratingKey).toSet();
|
||||
|
||||
@override
|
||||
void onWatchStateChanged(WatchStateEvent event) {
|
||||
// Update the affected episode
|
||||
if (!widget.isOffline && _client != null) {
|
||||
updateItem(event.ratingKey);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the correct PlexClient for this season's server
|
||||
PlexClient? _getClientForSeason(BuildContext context) {
|
||||
@@ -55,6 +71,8 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdata
|
||||
super.initState();
|
||||
// Initialize the client once in initState
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
// Capture keyboard mode once to avoid rebuild dependency when mode changes
|
||||
_initialKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
_client = _getClientForSeason(context);
|
||||
_loadEpisodes();
|
||||
});
|
||||
@@ -165,7 +183,7 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> with ItemUpdata
|
||||
client: _client,
|
||||
isOffline: widget.isOffline,
|
||||
localPosterPath: localPosterPath,
|
||||
autofocus: index == 0 && InputModeTracker.isKeyboardMode(context),
|
||||
autofocus: index == 0 && _initialKeyboardMode,
|
||||
onTap: () async {
|
||||
await navigateToVideoPlayerWithRefresh(
|
||||
context,
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:plezy/widgets/app_icon.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../../models/mpv_config_models.dart';
|
||||
import '../../services/settings_service.dart';
|
||||
import '../../widgets/desktop_app_bar.dart';
|
||||
|
||||
class MpvConfigScreen extends StatefulWidget {
|
||||
const MpvConfigScreen({super.key});
|
||||
|
||||
@override
|
||||
State<MpvConfigScreen> createState() => _MpvConfigScreenState();
|
||||
}
|
||||
|
||||
class _MpvConfigScreenState extends State<MpvConfigScreen> {
|
||||
late SettingsService _settingsService;
|
||||
bool _isLoading = true;
|
||||
|
||||
List<MpvConfigEntry> _entries = [];
|
||||
List<MpvPreset> _presets = [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadSettings();
|
||||
}
|
||||
|
||||
Future<void> _loadSettings() async {
|
||||
_settingsService = await SettingsService.getInstance();
|
||||
|
||||
setState(() {
|
||||
_entries = _settingsService.getMpvConfigEntries();
|
||||
_presets = _settingsService.getMpvPresets();
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _saveEntries() async {
|
||||
await _settingsService.setMpvConfigEntries(_entries);
|
||||
}
|
||||
|
||||
void _toggleEntry(int index) {
|
||||
setState(() {
|
||||
_entries[index] = _entries[index].copyWith(isEnabled: !_entries[index].isEnabled);
|
||||
});
|
||||
_saveEntries();
|
||||
}
|
||||
|
||||
void _deleteEntry(int index) {
|
||||
setState(() {
|
||||
_entries.removeAt(index);
|
||||
});
|
||||
_saveEntries();
|
||||
}
|
||||
|
||||
void _addEntry(MpvConfigEntry entry) {
|
||||
setState(() {
|
||||
_entries.add(entry);
|
||||
});
|
||||
_saveEntries();
|
||||
}
|
||||
|
||||
void _updateEntry(int index, MpvConfigEntry entry) {
|
||||
setState(() {
|
||||
_entries[index] = entry;
|
||||
});
|
||||
_saveEntries();
|
||||
}
|
||||
|
||||
Future<void> _showEntryDialog({int? editIndex}) async {
|
||||
final isEdit = editIndex != null;
|
||||
final existingEntry = isEdit ? _entries[editIndex] : null;
|
||||
|
||||
final keyController = TextEditingController(text: existingEntry?.key ?? '');
|
||||
final valueController = TextEditingController(text: existingEntry?.value ?? '');
|
||||
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(isEdit ? t.mpvConfig.editProperty : t.mpvConfig.addProperty),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextField(
|
||||
controller: keyController,
|
||||
decoration: InputDecoration(labelText: t.mpvConfig.propertyKey, hintText: t.mpvConfig.propertyKeyHint),
|
||||
autofocus: true,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: valueController,
|
||||
decoration: InputDecoration(
|
||||
labelText: t.mpvConfig.propertyValue,
|
||||
hintText: t.mpvConfig.propertyValueHint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (keyController.text.isNotEmpty && valueController.text.isNotEmpty) {
|
||||
Navigator.pop(context, true);
|
||||
}
|
||||
},
|
||||
child: Text(t.common.save),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (result == true) {
|
||||
final entry = MpvConfigEntry(
|
||||
key: keyController.text.trim(),
|
||||
value: valueController.text.trim(),
|
||||
isEnabled: existingEntry?.isEnabled ?? true,
|
||||
);
|
||||
|
||||
if (isEdit) {
|
||||
_updateEntry(editIndex, entry);
|
||||
} else {
|
||||
_addEntry(entry);
|
||||
}
|
||||
}
|
||||
|
||||
keyController.dispose();
|
||||
valueController.dispose();
|
||||
}
|
||||
|
||||
Future<bool> _showConfirmDeleteDialog({required String title, required String content}) async {
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(title),
|
||||
content: Text(content),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
|
||||
TextButton(onPressed: () => Navigator.pop(context, true), child: Text(t.common.delete)),
|
||||
],
|
||||
),
|
||||
);
|
||||
return result == true;
|
||||
}
|
||||
|
||||
Future<void> _showDeleteEntryDialog(int index) async {
|
||||
final confirmed = await _showConfirmDeleteDialog(
|
||||
title: t.mpvConfig.deleteProperty,
|
||||
content: t.mpvConfig.confirmDeleteProperty,
|
||||
);
|
||||
if (confirmed) {
|
||||
_deleteEntry(index);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showSavePresetDialog() async {
|
||||
if (_entries.isEmpty) return;
|
||||
|
||||
final nameController = TextEditingController();
|
||||
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(t.mpvConfig.saveAsPreset),
|
||||
content: TextField(
|
||||
controller: nameController,
|
||||
decoration: InputDecoration(labelText: t.mpvConfig.presetName, hintText: t.mpvConfig.presetNameHint),
|
||||
autofocus: true,
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (nameController.text.isNotEmpty) {
|
||||
Navigator.pop(context, true);
|
||||
}
|
||||
},
|
||||
child: Text(t.common.save),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (result == true) {
|
||||
await _settingsService.saveMpvPreset(nameController.text.trim(), _entries);
|
||||
setState(() {
|
||||
_presets = _settingsService.getMpvPresets();
|
||||
});
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.mpvConfig.presetSaved)));
|
||||
}
|
||||
}
|
||||
|
||||
nameController.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadPreset(MpvPreset preset) async {
|
||||
await _settingsService.loadMpvPreset(preset.name);
|
||||
setState(() {
|
||||
_entries = _settingsService.getMpvConfigEntries();
|
||||
});
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.mpvConfig.presetLoaded)));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _deletePreset(MpvPreset preset) async {
|
||||
final confirmed = await _showConfirmDeleteDialog(
|
||||
title: t.mpvConfig.deletePreset,
|
||||
content: t.mpvConfig.confirmDeletePreset,
|
||||
);
|
||||
|
||||
if (confirmed) {
|
||||
await _settingsService.deleteMpvPreset(preset.name);
|
||||
setState(() {
|
||||
_presets = _settingsService.getMpvPresets();
|
||||
});
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.mpvConfig.presetDeleted)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_isLoading) {
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(title: Text(t.screens.mpvConfig), pinned: true),
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate([
|
||||
_buildPresetsCard(),
|
||||
const SizedBox(height: 16),
|
||||
_buildEntriesCard(),
|
||||
const SizedBox(height: 24),
|
||||
]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPresetsCard() {
|
||||
return Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
t.mpvConfig.presets,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
leading: const AppIcon(Symbols.save_rounded, fill: 1),
|
||||
title: Text(t.mpvConfig.saveAsPreset),
|
||||
enabled: _entries.isNotEmpty,
|
||||
onTap: _entries.isNotEmpty ? _showSavePresetDialog : null,
|
||||
),
|
||||
if (_presets.isNotEmpty) ...[
|
||||
const Divider(),
|
||||
..._presets.map(
|
||||
(preset) => ListTile(
|
||||
leading: const AppIcon(Symbols.folder_rounded, fill: 1),
|
||||
title: Text(preset.name),
|
||||
subtitle: Text(t.mpvConfig.entriesCount(count: preset.entries.length)),
|
||||
trailing: PopupMenuButton<String>(
|
||||
onSelected: (value) {
|
||||
if (value == 'load') {
|
||||
_loadPreset(preset);
|
||||
} else if (value == 'delete') {
|
||||
_deletePreset(preset);
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem(value: 'load', child: Text(t.mpvConfig.loadPreset)),
|
||||
PopupMenuItem(value: 'delete', child: Text(t.mpvConfig.deletePreset)),
|
||||
],
|
||||
),
|
||||
onTap: () => _loadPreset(preset),
|
||||
),
|
||||
),
|
||||
] else
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Text(
|
||||
t.mpvConfig.noPresets,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEntriesCard() {
|
||||
return Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
t.mpvConfig.properties,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const AppIcon(Symbols.add_rounded, fill: 1),
|
||||
onPressed: () => _showEntryDialog(),
|
||||
tooltip: t.mpvConfig.addProperty,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_entries.isNotEmpty) ...[
|
||||
const Divider(height: 1),
|
||||
...List.generate(_entries.length, (index) {
|
||||
final entry = _entries[index];
|
||||
return ListTile(
|
||||
leading: Switch(value: entry.isEnabled, onChanged: (_) => _toggleEntry(index)),
|
||||
title: Text(
|
||||
entry.key,
|
||||
style: TextStyle(color: entry.isEnabled ? null : Theme.of(context).colorScheme.onSurfaceVariant),
|
||||
),
|
||||
subtitle: Text(
|
||||
entry.value,
|
||||
style: TextStyle(color: entry.isEnabled ? null : Theme.of(context).colorScheme.onSurfaceVariant),
|
||||
),
|
||||
trailing: PopupMenuButton<String>(
|
||||
onSelected: (value) {
|
||||
if (value == 'edit') {
|
||||
_showEntryDialog(editIndex: index);
|
||||
} else if (value == 'delete') {
|
||||
_showDeleteEntryDialog(index);
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem(value: 'edit', child: Text(t.mpvConfig.editProperty)),
|
||||
PopupMenuItem(value: 'delete', child: Text(t.mpvConfig.deleteProperty)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}),
|
||||
] else
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Text(
|
||||
t.mpvConfig.noProperties,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../i18n/strings.g.dart';
|
||||
import '../../services/discord_rpc_service.dart';
|
||||
import '../../services/download_storage_service.dart';
|
||||
import '../../services/saf_storage_service.dart';
|
||||
import '../../providers/settings_provider.dart';
|
||||
@@ -17,10 +18,13 @@ import '../../services/keyboard_shortcuts_service.dart';
|
||||
import '../../services/settings_service.dart' as settings;
|
||||
import '../../services/update_service.dart';
|
||||
import '../../utils/snackbar_helper.dart';
|
||||
import '../../utils/platform_detector.dart';
|
||||
import '../../widgets/desktop_app_bar.dart';
|
||||
import '../../widgets/tv_number_spinner.dart';
|
||||
import 'hotkey_recorder_widget.dart';
|
||||
import 'about_screen.dart';
|
||||
import 'logs_screen.dart';
|
||||
import 'mpv_config_screen.dart';
|
||||
import 'subtitle_styling_screen.dart';
|
||||
|
||||
/// Helper class for option selection dialog items
|
||||
@@ -57,6 +61,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
int _autoSkipDelay = 5;
|
||||
bool _downloadOnWifiOnly = false;
|
||||
bool _videoPlayerNavigationEnabled = false;
|
||||
int _maxVolume = 100;
|
||||
bool _enableDiscordRPC = false;
|
||||
bool _matchContentFrameRate = false;
|
||||
|
||||
// Update checking state
|
||||
bool _isCheckingForUpdate = false;
|
||||
@@ -87,6 +94,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_autoSkipDelay = _settingsService.getAutoSkipDelay();
|
||||
_downloadOnWifiOnly = _settingsService.getDownloadOnWifiOnly();
|
||||
_videoPlayerNavigationEnabled = _settingsService.getVideoPlayerNavigationEnabled();
|
||||
_maxVolume = _settingsService.getMaxVolume();
|
||||
_enableDiscordRPC = _settingsService.getEnableDiscordRPC();
|
||||
_matchContentFrameRate = _settingsService.getMatchContentFrameRate();
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
@@ -181,14 +191,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SwitchListTile(
|
||||
secondary: const AppIcon(Symbols.image_rounded, fill: 1),
|
||||
title: Text(t.settings.useSeasonPosters),
|
||||
subtitle: Text(t.settings.useSeasonPostersDescription),
|
||||
value: settingsProvider.useSeasonPoster,
|
||||
onChanged: (value) async {
|
||||
await settingsProvider.setUseSeasonPoster(value);
|
||||
},
|
||||
return ListTile(
|
||||
leading: const AppIcon(Symbols.image_rounded, fill: 1),
|
||||
title: Text(t.settings.episodePosterMode),
|
||||
subtitle: Text(settingsProvider.episodePosterModeDisplayName),
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () => _showEpisodePosterModeDialog(),
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -205,6 +213,19 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
},
|
||||
),
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SwitchListTile(
|
||||
secondary: const AppIcon(Symbols.home_rounded, fill: 1),
|
||||
title: Text(t.settings.useGlobalHubs),
|
||||
subtitle: Text(t.settings.useGlobalHubsDescription),
|
||||
value: settingsProvider.useGlobalHubs,
|
||||
onChanged: (value) async {
|
||||
await settingsProvider.setUseGlobalHubs(value);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -234,6 +255,19 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
await _settingsService.setEnableHardwareDecoding(value);
|
||||
},
|
||||
),
|
||||
if (Platform.isAndroid)
|
||||
SwitchListTile(
|
||||
secondary: const AppIcon(Symbols.display_settings_rounded, fill: 1),
|
||||
title: Text(t.settings.matchContentFrameRate),
|
||||
subtitle: Text(t.settings.matchContentFrameRateDescription),
|
||||
value: _matchContentFrameRate,
|
||||
onChanged: (value) async {
|
||||
setState(() {
|
||||
_matchContentFrameRate = value;
|
||||
});
|
||||
await _settingsService.setMatchContentFrameRate(value);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const AppIcon(Symbols.memory_rounded, fill: 1),
|
||||
title: Text(t.settings.bufferSize),
|
||||
@@ -250,6 +284,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (context) => const SubtitleStylingScreen()));
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const AppIcon(Symbols.tune_rounded, fill: 1),
|
||||
title: Text(t.mpvConfig.title),
|
||||
subtitle: Text(t.mpvConfig.description),
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (context) => const MpvConfigScreen()));
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const AppIcon(Symbols.replay_10_rounded, fill: 1),
|
||||
title: Text(t.settings.smallSkipDuration),
|
||||
@@ -271,6 +314,25 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () => _showSleepTimerDurationDialog(),
|
||||
),
|
||||
ListTile(
|
||||
leading: const AppIcon(Symbols.volume_up_rounded, fill: 1),
|
||||
title: Text(t.settings.maxVolume),
|
||||
subtitle: Text(t.settings.maxVolumePercent(percent: _maxVolume.toString())),
|
||||
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
onTap: () => _showMaxVolumeDialog(),
|
||||
),
|
||||
if (DiscordRPCService.isAvailable)
|
||||
SwitchListTile(
|
||||
secondary: const AppIcon(Symbols.chat_rounded, fill: 1),
|
||||
title: Text(t.settings.discordRichPresence),
|
||||
subtitle: Text(t.settings.discordRichPresenceDescription),
|
||||
value: _enableDiscordRPC,
|
||||
onChanged: (value) async {
|
||||
setState(() => _enableDiscordRPC = value);
|
||||
await _settingsService.setEnableDiscordRPC(value);
|
||||
await DiscordRPCService.instance.setEnabled(value);
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
secondary: const AppIcon(Symbols.bookmark_rounded, fill: 1),
|
||||
title: Text(t.settings.rememberTrackSelections),
|
||||
@@ -591,9 +653,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
color: hasUpdate ? Colors.orange : null,
|
||||
),
|
||||
title: Text(hasUpdate ? t.settings.updateAvailable : t.settings.checkForUpdates),
|
||||
subtitle: hasUpdate
|
||||
? Text(t.update.versionAvailable(version: _updateInfo!['latestVersion']))
|
||||
: Text(t.update.checkFailed),
|
||||
subtitle: hasUpdate ? Text(t.update.versionAvailable(version: _updateInfo!['latestVersion'])) : null,
|
||||
trailing: _isCheckingForUpdate
|
||||
? const SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
|
||||
@@ -716,7 +776,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Generic numeric input dialog to avoid duplication across settings
|
||||
/// Generic numeric input dialog to avoid duplication across settings.
|
||||
/// On TV, uses a spinner widget with +/- buttons for D-pad navigation.
|
||||
/// On other platforms, uses a TextField with focus management.
|
||||
void _showNumericInputDialog({
|
||||
required String title,
|
||||
required String labelText,
|
||||
@@ -725,9 +787,105 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
required int max,
|
||||
required int currentValue,
|
||||
required Future<void> Function(int value) onSave,
|
||||
}) {
|
||||
final isTV = PlatformDetector.isTV();
|
||||
|
||||
if (isTV) {
|
||||
_showNumericInputDialogTV(
|
||||
title: title,
|
||||
suffixText: suffixText,
|
||||
min: min,
|
||||
max: max,
|
||||
currentValue: currentValue,
|
||||
onSave: onSave,
|
||||
);
|
||||
} else {
|
||||
_showNumericInputDialogStandard(
|
||||
title: title,
|
||||
labelText: labelText,
|
||||
suffixText: suffixText,
|
||||
min: min,
|
||||
max: max,
|
||||
currentValue: currentValue,
|
||||
onSave: onSave,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// TV-specific numeric input dialog with spinner widget.
|
||||
void _showNumericInputDialogTV({
|
||||
required String title,
|
||||
required String suffixText,
|
||||
required int min,
|
||||
required int max,
|
||||
required int currentValue,
|
||||
required Future<void> Function(int value) onSave,
|
||||
}) {
|
||||
int spinnerValue = currentValue;
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext dialogContext) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setDialogState) {
|
||||
return AlertDialog(
|
||||
title: Text(title),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TvNumberSpinner(
|
||||
value: spinnerValue,
|
||||
min: min,
|
||||
max: max,
|
||||
suffix: suffixText,
|
||||
autofocus: true,
|
||||
onChanged: (value) {
|
||||
setDialogState(() {
|
||||
spinnerValue = value;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
t.settings.durationHint(min: min, max: max),
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodySmall?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.common.cancel)),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
await onSave(spinnerValue);
|
||||
if (dialogContext.mounted) {
|
||||
Navigator.pop(dialogContext);
|
||||
}
|
||||
},
|
||||
child: Text(t.common.save),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Standard numeric input dialog with TextField for non-TV platforms.
|
||||
void _showNumericInputDialogStandard({
|
||||
required String title,
|
||||
required String labelText,
|
||||
required String suffixText,
|
||||
required int min,
|
||||
required int max,
|
||||
required int currentValue,
|
||||
required Future<void> Function(int value) onSave,
|
||||
}) {
|
||||
final controller = TextEditingController(text: currentValue.toString());
|
||||
String? errorText;
|
||||
final saveFocusNode = FocusNode();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
@@ -746,6 +904,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
suffixText: suffixText,
|
||||
),
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
onEditingComplete: () {
|
||||
// Move focus to Save button when keyboard checkmark is pressed
|
||||
saveFocusNode.requestFocus();
|
||||
},
|
||||
onChanged: (value) {
|
||||
final parsed = int.tryParse(value);
|
||||
setDialogState(() {
|
||||
@@ -762,6 +925,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.common.cancel)),
|
||||
TextButton(
|
||||
focusNode: saveFocusNode,
|
||||
onPressed: () async {
|
||||
final parsed = int.tryParse(controller.text);
|
||||
if (parsed != null && parsed >= min && parsed <= max) {
|
||||
@@ -778,7 +942,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
).then((_) {
|
||||
// Clean up focus node when dialog is dismissed
|
||||
saveFocusNode.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
void _showSeekTimeSmallDialog() {
|
||||
@@ -847,6 +1014,21 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
void _showMaxVolumeDialog() {
|
||||
_showNumericInputDialog(
|
||||
title: t.settings.maxVolume,
|
||||
labelText: t.settings.maxVolumeDescription,
|
||||
suffixText: '%',
|
||||
min: 100,
|
||||
max: 300,
|
||||
currentValue: _maxVolume,
|
||||
onSave: (value) async {
|
||||
setState(() => _maxVolume = value);
|
||||
await _settingsService.setMaxVolume(value);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _showKeyboardShortcutsDialog() {
|
||||
if (_keyboardService == null) return;
|
||||
|
||||
@@ -927,6 +1109,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
return 'Deutsch';
|
||||
case AppLocale.zh:
|
||||
return '中文';
|
||||
case AppLocale.ko:
|
||||
return '한국어';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1137,6 +1321,31 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
onSelect: (value, provider) => provider.setViewMode(value),
|
||||
);
|
||||
}
|
||||
|
||||
void _showEpisodePosterModeDialog() {
|
||||
_showOptionSelectionDialog<settings.EpisodePosterMode>(
|
||||
title: t.settings.episodePosterMode,
|
||||
options: [
|
||||
_DialogOption(
|
||||
value: settings.EpisodePosterMode.seriesPoster,
|
||||
title: t.settings.seriesPoster,
|
||||
subtitle: t.settings.seriesPosterDescription,
|
||||
),
|
||||
_DialogOption(
|
||||
value: settings.EpisodePosterMode.seasonPoster,
|
||||
title: t.settings.seasonPoster,
|
||||
subtitle: t.settings.seasonPosterDescription,
|
||||
),
|
||||
_DialogOption(
|
||||
value: settings.EpisodePosterMode.episodeThumbnail,
|
||||
title: t.settings.episodeThumbnail,
|
||||
subtitle: t.settings.episodeThumbnailDescription,
|
||||
),
|
||||
],
|
||||
getCurrentValue: (p) => p.episodePosterMode,
|
||||
onSelect: (value, provider) => provider.setEpisodePosterMode(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _KeyboardShortcutsScreen extends StatefulWidget {
|
||||
|
||||
@@ -20,6 +20,7 @@ import '../models/plex_media_info.dart';
|
||||
import '../providers/download_provider.dart';
|
||||
import '../providers/multi_server_provider.dart';
|
||||
import '../providers/playback_state_provider.dart';
|
||||
import '../services/discord_rpc_service.dart';
|
||||
import '../services/episode_navigation_service.dart';
|
||||
import '../services/media_controls_manager.dart';
|
||||
import '../services/playback_initialization_service.dart';
|
||||
@@ -28,6 +29,8 @@ import '../services/offline_watch_sync_service.dart';
|
||||
import '../services/settings_service.dart';
|
||||
import '../services/track_selection_service.dart';
|
||||
import '../services/video_filter_manager.dart';
|
||||
import '../services/video_pip_manager.dart';
|
||||
import '../services/pip_service.dart';
|
||||
import '../providers/user_profile_provider.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/orientation_helper.dart';
|
||||
@@ -86,8 +89,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
StreamSubscription<dynamic>? _mediaControlSubscription;
|
||||
StreamSubscription<bool>? _bufferingSubscription;
|
||||
StreamSubscription<Tracks>? _trackLoadingSubscription;
|
||||
StreamSubscription<Duration>? _positionSubscription;
|
||||
StreamSubscription<void>? _playbackRestartSubscription;
|
||||
bool _isReplacingWithVideo = false; // Flag to skip orientation restoration during video-to-video navigation
|
||||
bool _isDisposingForNavigation = false;
|
||||
bool _waitingForExternalSubsTrackSelection = false;
|
||||
|
||||
// Auto-play next episode
|
||||
Timer? _autoPlayTimer;
|
||||
int _autoPlayCountdown = 5;
|
||||
bool _completionTriggered = false;
|
||||
|
||||
// App lifecycle state tracking
|
||||
bool _wasPlayingBeforeInactive = false;
|
||||
@@ -96,6 +107,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
MediaControlsManager? _mediaControlsManager;
|
||||
PlaybackProgressTracker? _progressTracker;
|
||||
VideoFilterManager? _videoFilterManager;
|
||||
VideoPIPManager? _videoPIPManager;
|
||||
final EpisodeNavigationService _episodeNavigation = EpisodeNavigationService();
|
||||
|
||||
// Watch Together provider reference (stored early to use in dispose)
|
||||
@@ -107,6 +119,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
}
|
||||
|
||||
final ValueNotifier<bool> _isBuffering = ValueNotifier<bool>(false); // Track if video is currently buffering
|
||||
final ValueNotifier<bool> _hasFirstFrame = ValueNotifier<bool>(false); // Track if first video frame has rendered
|
||||
final ValueNotifier<bool> _isExiting = ValueNotifier<bool>(false); // Track if navigating away (for black overlay)
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -179,17 +193,19 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
|
||||
switch (state) {
|
||||
case AppLifecycleState.inactive:
|
||||
// App is inactive (Control Center, Notification Screen, etc.)
|
||||
// Pause video but keep media controls for quick resume (mobile only)
|
||||
// App is inactive (notification shade, split-screen, etc.)
|
||||
// Don't pause - user may still be watching
|
||||
break;
|
||||
case AppLifecycleState.hidden:
|
||||
// App is being hidden (user is switching away)
|
||||
// Pause video since we don't support background playback (mobile only)
|
||||
if (PlatformDetector.isMobile(context)) {
|
||||
if (player != null && _isPlayerInitialized) {
|
||||
_wasPlayingBeforeInactive = player!.state.playing;
|
||||
if (_wasPlayingBeforeInactive) {
|
||||
player!.pause();
|
||||
appLogger.d('Video paused due to app becoming inactive (mobile)');
|
||||
appLogger.d('Video paused due to app being hidden (mobile)');
|
||||
}
|
||||
// Keep media controls active on mobile for quick resume
|
||||
_updateMediaControlsPlaybackState();
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -229,8 +245,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
}
|
||||
break;
|
||||
case AppLifecycleState.detached:
|
||||
case AppLifecycleState.hidden:
|
||||
// No action needed for these states
|
||||
// No action needed for this state
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -313,8 +328,23 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
await player!.setProperty('sub-delay', offsetSeconds.toString());
|
||||
}
|
||||
|
||||
// Apply saved volume
|
||||
final savedVolume = settingsService.getVolume();
|
||||
// Apply custom MPV config entries
|
||||
final customMpvConfig = settingsService.getEnabledMpvConfigEntries();
|
||||
for (final entry in customMpvConfig.entries) {
|
||||
try {
|
||||
await player!.setProperty(entry.key, entry.value);
|
||||
appLogger.d('Applied custom MPV property: ${entry.key}=${entry.value}');
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to set MPV property ${entry.key}', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
// Set max volume limit for volume boost
|
||||
final maxVolume = settingsService.getMaxVolume();
|
||||
await player!.setProperty('volume-max', maxVolume.toString());
|
||||
|
||||
// Apply saved volume (clamped to max volume)
|
||||
final savedVolume = settingsService.getVolume().clamp(0.0, maxVolume.toDouble());
|
||||
player!.setVolume(savedVolume);
|
||||
|
||||
// Notify that player is ready
|
||||
@@ -368,6 +398,34 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
_isBuffering.value = isBuffering;
|
||||
});
|
||||
|
||||
// Listen to playback restart to detect first frame ready
|
||||
_playbackRestartSubscription = player!.streams.playbackRestart.listen((_) async {
|
||||
if (!_hasFirstFrame.value) {
|
||||
_hasFirstFrame.value = true;
|
||||
|
||||
// Apply frame rate matching on Android if enabled
|
||||
if (Platform.isAndroid && settingsService.getMatchContentFrameRate()) {
|
||||
await _applyFrameRateMatching();
|
||||
}
|
||||
}
|
||||
if (_waitingForExternalSubsTrackSelection) {
|
||||
_waitingForExternalSubsTrackSelection = false;
|
||||
_applyTrackSelection();
|
||||
}
|
||||
});
|
||||
|
||||
// Listen to position for completion detection (fallback for unreliable MPV events)
|
||||
_positionSubscription = player!.streams.position.listen((position) {
|
||||
final duration = player!.state.duration;
|
||||
if (duration.inMilliseconds > 0 &&
|
||||
position.inMilliseconds >= duration.inMilliseconds - 1000 &&
|
||||
!_showPlayNextDialog &&
|
||||
!_completionTriggered &&
|
||||
_nextEpisode != null) {
|
||||
_onVideoCompleted(true);
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize services
|
||||
await _initializeServices();
|
||||
|
||||
@@ -386,15 +444,50 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply frame rate matching on Android by setting the display refresh rate
|
||||
/// to match the video content's frame rate.
|
||||
Future<void> _applyFrameRateMatching() async {
|
||||
if (player == null || !Platform.isAndroid) return;
|
||||
|
||||
try {
|
||||
final fpsStr = await player!.getProperty('container-fps');
|
||||
final fps = double.tryParse(fpsStr ?? '');
|
||||
if (fps == null || fps <= 0) {
|
||||
appLogger.d('Frame rate matching: No valid fps available ($fpsStr)');
|
||||
return;
|
||||
}
|
||||
|
||||
final durationMs = player!.state.duration.inMilliseconds;
|
||||
await player!.setVideoFrameRate(fps, durationMs);
|
||||
|
||||
// Set MPV video-sync mode for smoother playback when display is synced
|
||||
await player!.setProperty('video-sync', 'display-tempo');
|
||||
|
||||
appLogger.d('Frame rate matching: Set display to ${fps}fps (duration: ${durationMs}ms)');
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to apply frame rate matching', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear frame rate matching and restore default display mode
|
||||
Future<void> _clearFrameRateMatching() async {
|
||||
if (player == null || !Platform.isAndroid) return;
|
||||
|
||||
try {
|
||||
await player!.clearVideoFrameRate();
|
||||
await player!.setProperty('video-sync', 'audio');
|
||||
appLogger.d('Frame rate matching: Cleared, restored default display mode');
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to clear frame rate matching', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Add external subtitle tracks to the player
|
||||
Future<void> _addExternalSubtitles(List<SubtitleTrack> externalSubtitles) async {
|
||||
if (player == null || externalSubtitles.isEmpty) return;
|
||||
|
||||
appLogger.d('Adding ${externalSubtitles.length} external subtitle(s) to player');
|
||||
|
||||
// Wait for media to be ready
|
||||
await _waitForMediaReady();
|
||||
|
||||
for (final subtitleTrack in externalSubtitles) {
|
||||
if (subtitleTrack.uri == null) continue;
|
||||
|
||||
@@ -412,21 +505,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for media to be ready (duration > 0)
|
||||
Future<void> _waitForMediaReady() async {
|
||||
if (player == null) return;
|
||||
|
||||
int attempts = 0;
|
||||
while (player!.state.duration.inMilliseconds == 0 && attempts < 100) {
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
attempts++;
|
||||
}
|
||||
|
||||
if (attempts >= 100) {
|
||||
appLogger.w('Media ready timeout - proceeding anyway');
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize the service layer
|
||||
Future<void> _initializeServices() async {
|
||||
if (!mounted || player == null) return;
|
||||
@@ -512,14 +590,20 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
_updateMediaControlsPlaybackState();
|
||||
});
|
||||
|
||||
// Listen to position updates for media controls
|
||||
// Listen to position updates for media controls and Discord
|
||||
player!.streams.position.listen((position) {
|
||||
_mediaControlsManager?.updatePlaybackState(
|
||||
isPlaying: player!.state.playing,
|
||||
position: position,
|
||||
speed: player!.state.rate,
|
||||
);
|
||||
DiscordRPCService.instance.updatePosition(position);
|
||||
});
|
||||
|
||||
// Start Discord Rich Presence for current media
|
||||
if (client != null) {
|
||||
DiscordRPCService.instance.startPlayback(widget.metadata, client);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure a play queue exists for sequential episode playback
|
||||
@@ -621,6 +705,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
|
||||
try {
|
||||
PlaybackInitializationResult result;
|
||||
Map<String, String>? plexHeaders;
|
||||
|
||||
if (widget.isOffline) {
|
||||
// Offline mode: get video path from downloads without requiring server
|
||||
@@ -628,6 +713,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
} else {
|
||||
// Online mode: use server-specific client
|
||||
final client = _getClientForMetadata(context);
|
||||
plexHeaders = client.config.headers;
|
||||
final playbackService = PlaybackInitializationService(client: client, database: PlexApiCache.instance.database);
|
||||
result = await playbackService.getPlaybackData(
|
||||
metadata: widget.metadata,
|
||||
@@ -638,11 +724,22 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
|
||||
// Open video through Player
|
||||
if (result.videoUrl != null) {
|
||||
// Reset first frame flag for new video
|
||||
_hasFirstFrame.value = false;
|
||||
|
||||
// Pass resume position if available
|
||||
final resumePosition = widget.metadata.viewOffset != null
|
||||
? Duration(milliseconds: widget.metadata.viewOffset!)
|
||||
: null;
|
||||
await player!.open(Media(result.videoUrl!, start: resumePosition));
|
||||
|
||||
// If we have external subtitles, open paused to add them before playback starts.
|
||||
// This prevents a race condition on Android where adding subtitle tracks
|
||||
// during active playback can freeze the video decoder (issue #226).
|
||||
final hasExternalSubs = result.externalSubtitles.isNotEmpty;
|
||||
await player!.open(
|
||||
Media(result.videoUrl!, start: resumePosition, headers: plexHeaders),
|
||||
play: !hasExternalSubs,
|
||||
);
|
||||
|
||||
// Attach player to Watch Together session for sync (if in session)
|
||||
if (mounted && !widget.isOffline) {
|
||||
@@ -658,7 +755,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
_currentMediaInfo = result.mediaInfo;
|
||||
});
|
||||
|
||||
// Initialize video filter manager with player and available versions
|
||||
// Initialize video PIP and filter manager with player and available versions
|
||||
if (player != null) {
|
||||
_videoFilterManager = VideoFilterManager(
|
||||
player: player!,
|
||||
@@ -667,27 +764,44 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
);
|
||||
// Update video filter once dimensions are available
|
||||
_videoFilterManager!.updateVideoFilter();
|
||||
|
||||
// PIP Manager
|
||||
_videoPIPManager = VideoPIPManager(player: player!);
|
||||
}
|
||||
|
||||
// Add external subtitles to the player
|
||||
// Add external subtitles while paused, then start playback
|
||||
if (result.externalSubtitles.isNotEmpty) {
|
||||
await _addExternalSubtitles(result.externalSubtitles);
|
||||
_hasFirstFrame.value = false;
|
||||
_waitingForExternalSubsTrackSelection = true;
|
||||
|
||||
try {
|
||||
await _addExternalSubtitles(result.externalSubtitles);
|
||||
} finally {
|
||||
if (player != null && mounted) {
|
||||
await player!.play();
|
||||
final pos = player!.state.position;
|
||||
await player!.seek(pos.inMilliseconds > 0 ? pos : Duration.zero);
|
||||
|
||||
// Fallback if playbackRestart doesn't fire
|
||||
Future.delayed(const Duration(seconds: 3), () {
|
||||
if (_waitingForExternalSubsTrackSelection && mounted) {
|
||||
_waitingForExternalSubsTrackSelection = false;
|
||||
_applyTrackSelection();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_trackLoadingSubscription?.cancel();
|
||||
_trackLoadingSubscription = player!.streams.tracks.listen((tracks) {
|
||||
if (tracks.audio.isEmpty && tracks.subtitle.isEmpty) return;
|
||||
|
||||
_trackLoadingSubscription?.cancel();
|
||||
_trackLoadingSubscription = null;
|
||||
_applyTrackSelection();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Set up track loading subscription to apply track selection when tracks are loaded
|
||||
_trackLoadingSubscription?.cancel();
|
||||
_trackLoadingSubscription = player!.streams.tracks.listen((tracks) {
|
||||
// Only process when we have actual tracks loaded
|
||||
if (tracks.audio.isEmpty && tracks.subtitle.isEmpty) return;
|
||||
|
||||
// Cancel subscription after first load to avoid re-applying on every track change
|
||||
_trackLoadingSubscription?.cancel();
|
||||
_trackLoadingSubscription = null;
|
||||
|
||||
// Apply track selection using the service
|
||||
_applyTrackSelection();
|
||||
});
|
||||
} on PlaybackException catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.message)));
|
||||
@@ -726,6 +840,12 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
);
|
||||
}
|
||||
|
||||
void _togglePIPMode() {
|
||||
setState(() {
|
||||
_videoPIPManager?.togglePIP();
|
||||
});
|
||||
}
|
||||
|
||||
/// Cycle through BoxFit modes: contain → cover → fill → contain (for button)
|
||||
void _cycleBoxFitMode() {
|
||||
setState(() {
|
||||
@@ -855,12 +975,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
|
||||
if (confirmed == true && mounted) {
|
||||
await _watchTogetherProvider!.leaveSession();
|
||||
if (mounted) Navigator.of(context).pop(true);
|
||||
if (mounted) {
|
||||
_isExiting.value = true;
|
||||
Navigator.of(context).pop(true);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Default behavior for hosts or non-session users
|
||||
_isExiting.value = true;
|
||||
Navigator.of(context).pop(true);
|
||||
}
|
||||
|
||||
@@ -884,6 +1008,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
|
||||
// Dispose value notifiers
|
||||
_isBuffering.dispose();
|
||||
_hasFirstFrame.dispose();
|
||||
_isExiting.dispose();
|
||||
|
||||
// Stop progress tracking and send final state
|
||||
_progressTracker?.sendProgress('stopped');
|
||||
@@ -901,11 +1027,24 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
_mediaControlSubscription?.cancel();
|
||||
_bufferingSubscription?.cancel();
|
||||
_trackLoadingSubscription?.cancel();
|
||||
_positionSubscription?.cancel();
|
||||
_playbackRestartSubscription?.cancel();
|
||||
|
||||
// Cancel auto-play timer
|
||||
_autoPlayTimer?.cancel();
|
||||
|
||||
// Clear media controls and dispose manager
|
||||
_mediaControlsManager?.clear();
|
||||
_mediaControlsManager?.dispose();
|
||||
|
||||
// Clear Discord Rich Presence
|
||||
DiscordRPCService.instance.stopPlayback();
|
||||
|
||||
// Clear frame rate matching before disposing player (Android only)
|
||||
if (Platform.isAndroid && player != null) {
|
||||
player!.clearVideoFrameRate();
|
||||
}
|
||||
|
||||
// Disable wakelock when leaving the video player
|
||||
WakelockPlus.disable();
|
||||
appLogger.d('Wakelock disabled');
|
||||
@@ -942,18 +1081,36 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
}
|
||||
|
||||
void _onPlayingStateChanged(bool isPlaying) {
|
||||
// Toggle wakelock based on playback state
|
||||
if (isPlaying) {
|
||||
WakelockPlus.enable();
|
||||
} else {
|
||||
WakelockPlus.disable();
|
||||
}
|
||||
|
||||
// Send timeline update when playback state changes
|
||||
_progressTracker?.sendProgress(isPlaying ? 'playing' : 'paused');
|
||||
|
||||
// Update OS media controls playback state
|
||||
_updateMediaControlsPlaybackState();
|
||||
|
||||
// Update Discord Rich Presence
|
||||
if (isPlaying) {
|
||||
DiscordRPCService.instance.resumePlayback();
|
||||
} else {
|
||||
DiscordRPCService.instance.pausePlayback();
|
||||
}
|
||||
}
|
||||
|
||||
void _onVideoCompleted(bool completed) {
|
||||
if (completed && _nextEpisode != null && !_showPlayNextDialog) {
|
||||
if (completed && _nextEpisode != null && !_showPlayNextDialog && !_completionTriggered) {
|
||||
_completionTriggered = true;
|
||||
|
||||
setState(() {
|
||||
_showPlayNextDialog = true;
|
||||
_autoPlayCountdown = 5;
|
||||
});
|
||||
_startAutoPlayTimer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1001,6 +1158,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
Future<void> _playNext() async {
|
||||
if (_nextEpisode == null || _isLoadingNext) return;
|
||||
|
||||
// Cancel auto-play timer if running
|
||||
_autoPlayTimer?.cancel();
|
||||
|
||||
// Notify Watch Together of episode change before navigating
|
||||
_notifyWatchTogetherMediaChange(metadata: _nextEpisode);
|
||||
|
||||
@@ -1021,22 +1181,49 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
await _navigateToEpisode(_previousEpisode!);
|
||||
}
|
||||
|
||||
void _startAutoPlayTimer() {
|
||||
_autoPlayTimer?.cancel();
|
||||
_autoPlayTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
if (!mounted) {
|
||||
timer.cancel();
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_autoPlayCountdown--;
|
||||
});
|
||||
if (_autoPlayCountdown <= 0) {
|
||||
timer.cancel();
|
||||
_playNext();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _cancelAutoPlay() {
|
||||
_autoPlayTimer?.cancel();
|
||||
_completionTriggered = false; // Reset so it can trigger again if user seeks near end
|
||||
setState(() {
|
||||
_showPlayNextDialog = false;
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply track selection using the TrackSelectionService
|
||||
Future<void> _applyTrackSelection() async {
|
||||
if (!mounted || player == null) return;
|
||||
|
||||
final profileSettings = context.read<UserProfileProvider>().profileSettings;
|
||||
|
||||
final trackService = TrackSelectionService(
|
||||
player: player!,
|
||||
profileSettings: profileSettings,
|
||||
metadata: widget.metadata,
|
||||
plexMediaInfo: _currentMediaInfo,
|
||||
);
|
||||
|
||||
await trackService.selectAndApplyTracks(
|
||||
preferredAudioTrack: widget.preferredAudioTrack,
|
||||
preferredSubtitleTrack: widget.preferredSubtitleTrack,
|
||||
preferredPlaybackRate: widget.preferredPlaybackRate,
|
||||
onAudioTrackChanged: _onAudioTrackChanged,
|
||||
onSubtitleTrackChanged: _onSubtitleTrackChanged,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1247,6 +1434,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
// Set flag to skip orientation restoration in dispose()
|
||||
_isReplacingWithVideo = true;
|
||||
|
||||
// Clear Discord Rich Presence before switching episodes
|
||||
DiscordRPCService.instance.stopPlayback();
|
||||
|
||||
// If player isn't available, navigate without preserving settings
|
||||
if (player == null) {
|
||||
if (mounted) {
|
||||
@@ -1294,11 +1484,14 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
Future<void> disposePlayerForNavigation() async {
|
||||
if (_isDisposingForNavigation) return;
|
||||
_isDisposingForNavigation = true;
|
||||
_isExiting.value = true; // Show black overlay during transition
|
||||
|
||||
try {
|
||||
_detachFromWatchTogetherSession();
|
||||
_progressTracker?.sendProgress('stopped');
|
||||
_progressTracker?.stopTracking();
|
||||
// Clear frame rate matching before disposing (Android only)
|
||||
await _clearFrameRateMatching();
|
||||
await player?.dispose();
|
||||
} catch (e) {
|
||||
appLogger.d('Error disposing player before navigation', error: e);
|
||||
@@ -1392,6 +1585,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
onPrevious: (_previousEpisode != null && _canNavigateEpisodes()) ? _playPrevious : null,
|
||||
availableVersions: _availableVersions,
|
||||
selectedMediaIndex: widget.selectedMediaIndex,
|
||||
onTogglePIPMode: _togglePIPMode,
|
||||
boxFitMode: _videoFilterManager?.boxFitMode ?? 0,
|
||||
onCycleBoxFitMode: _cycleBoxFitMode,
|
||||
onAudioTrackChanged: _onAudioTrackChanged,
|
||||
@@ -1411,108 +1605,178 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
|
||||
},
|
||||
onBack: _handleBackButton,
|
||||
canControl: canControl,
|
||||
hasFirstFrame: _hasFirstFrame,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
// Play Next Dialog
|
||||
if (_showPlayNextDialog && _nextEpisode != null)
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
color: Colors.black.withValues(alpha: 0.8),
|
||||
child: Center(
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 32),
|
||||
padding: const EdgeInsets.all(32),
|
||||
decoration: BoxDecoration(color: Colors.grey[900], borderRadius: BorderRadius.circular(16)),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const AppIcon(Symbols.play_circle_rounded, fill: 1, size: 64, color: Colors.white),
|
||||
const SizedBox(height: 24),
|
||||
Consumer<PlaybackStateProvider>(
|
||||
builder: (context, playbackState, child) {
|
||||
final isShuffleActive = playbackState.isShuffleActive;
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
// Netflix-style auto-play overlay (hidden in PiP mode)
|
||||
ValueListenableBuilder<bool>(
|
||||
valueListenable: PipService().isPipActive,
|
||||
builder: (context, isInPip, child) {
|
||||
if (isInPip || !_showPlayNextDialog || _nextEpisode == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Positioned(
|
||||
right: 24,
|
||||
bottom: 100,
|
||||
child: Container(
|
||||
width: 320,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.9),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Up Next',
|
||||
style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold),
|
||||
Consumer<PlaybackStateProvider>(
|
||||
builder: (context, playbackState, child) {
|
||||
final isShuffleActive = playbackState.isShuffleActive;
|
||||
return Row(
|
||||
children: [
|
||||
Text(
|
||||
'Next Episode',
|
||||
style: TextStyle(
|
||||
color: Colors.white.withValues(alpha: 0.7),
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
if (isShuffleActive) ...[
|
||||
const SizedBox(width: 4),
|
||||
AppIcon(
|
||||
Symbols.shuffle_rounded,
|
||||
fill: 1,
|
||||
size: 12,
|
||||
color: Colors.white.withValues(alpha: 0.7),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
if (isShuffleActive) ...[
|
||||
const SizedBox(width: 8),
|
||||
const AppIcon(Symbols.shuffle_rounded, fill: 1, size: 20, color: Colors.white70),
|
||||
],
|
||||
const SizedBox(height: 4),
|
||||
if (_nextEpisode!.parentIndex != null && _nextEpisode!.index != null)
|
||||
Text(
|
||||
'S${_nextEpisode!.parentIndex} E${_nextEpisode!.index} · ${_nextEpisode!.title}',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
)
|
||||
else
|
||||
Text(
|
||||
_nextEpisode!.title,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
_nextEpisode!.grandparentTitle ?? _nextEpisode!.title,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 18),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (_nextEpisode!.parentIndex != null && _nextEpisode!.index != null)
|
||||
Text(
|
||||
'S${_nextEpisode!.parentIndex} · E${_nextEpisode!.index} · ${_nextEpisode!.title}',
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 16),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
OutlinedButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_showPlayNextDialog = false;
|
||||
});
|
||||
},
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: _cancelAutoPlay,
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.white,
|
||||
side: const BorderSide(color: Colors.white),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
|
||||
side: BorderSide(color: Colors.white.withValues(alpha: 0.5)),
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
),
|
||||
child: Text(t.dialog.cancel),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
FilledButton(
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: FilledButton(
|
||||
onPressed: _playNext,
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: Colors.black,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text('$_autoPlayCountdown'),
|
||||
const SizedBox(width: 4),
|
||||
const AppIcon(Symbols.play_arrow_rounded, fill: 1, size: 18),
|
||||
],
|
||||
),
|
||||
child: Text(t.dialog.playNow),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Buffering indicator
|
||||
ValueListenableBuilder<bool>(
|
||||
valueListenable: _isBuffering,
|
||||
builder: (context, isBuffering, child) {
|
||||
if (!isBuffering) return const SizedBox.shrink();
|
||||
return Positioned.fill(
|
||||
child: Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.5), shape: BoxShape.circle),
|
||||
child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 3),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
// Buffering indicator (also shows during initial load, but not when exiting)
|
||||
// Hidden in PiP mode
|
||||
ValueListenableBuilder<bool>(
|
||||
valueListenable: PipService().isPipActive,
|
||||
builder: (context, isInPip, child) {
|
||||
if (isInPip) return const SizedBox.shrink();
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: _isBuffering,
|
||||
builder: (context, isBuffering, child) {
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: _hasFirstFrame,
|
||||
builder: (context, hasFrame, child) {
|
||||
if ((!isBuffering && hasFrame) || _isExiting.value) return const SizedBox.shrink();
|
||||
return Positioned.fill(
|
||||
child: Stack(
|
||||
children: [
|
||||
if (!hasFrame) Container(color: Colors.black),
|
||||
Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.5),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 3),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
// Black overlay during exit (no spinner - just covers transparency)
|
||||
ValueListenableBuilder<bool>(
|
||||
valueListenable: _isExiting,
|
||||
builder: (context, isExiting, child) {
|
||||
if (!isExiting) return const SizedBox.shrink();
|
||||
return Positioned.fill(child: Container(color: Colors.black));
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -98,11 +98,15 @@ class DataAggregationService {
|
||||
return librariesByServer;
|
||||
}
|
||||
|
||||
/// Fetch recommendation hubs from all servers using pre-fetched libraries
|
||||
/// Fetch recommendation hubs from all servers
|
||||
/// When useGlobalHubs is true (default), uses the global /hubs endpoint
|
||||
/// to get the true home page hubs like "Recently Added Movies", "Recently Added TV"
|
||||
/// When false, uses per-library hubs from /hubs/sections/{sectionId}
|
||||
Future<List<PlexHub>> getHubsFromAllServers({
|
||||
int? limit,
|
||||
Map<String, List<PlexLibrary>>? librariesByServer,
|
||||
Set<String>? hiddenLibraryKeys,
|
||||
Map<String, List<PlexLibrary>>? librariesByServer,
|
||||
bool useGlobalHubs = true,
|
||||
}) async {
|
||||
final clients = _serverManager.onlineClients;
|
||||
|
||||
@@ -111,10 +115,98 @@ class DataAggregationService {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (useGlobalHubs) {
|
||||
return _fetchGlobalHubs(clients, limit: limit, hiddenLibraryKeys: hiddenLibraryKeys);
|
||||
} else {
|
||||
return _fetchLibraryHubs(
|
||||
clients,
|
||||
limit: limit,
|
||||
hiddenLibraryKeys: hiddenLibraryKeys,
|
||||
librariesByServer: librariesByServer,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch global hubs using /hubs endpoint (matches official Plex client)
|
||||
Future<List<PlexHub>> _fetchGlobalHubs(
|
||||
Map<String, PlexClient> clients, {
|
||||
int? limit,
|
||||
Set<String>? hiddenLibraryKeys,
|
||||
}) async {
|
||||
appLogger.d('Fetching global hubs from ${clients.length} servers');
|
||||
|
||||
final allHubs = <PlexHub>[];
|
||||
|
||||
// Fetch global hubs from all servers in parallel
|
||||
final hubFutures = clients.entries.map((entry) async {
|
||||
final serverId = entry.key;
|
||||
final client = entry.value;
|
||||
|
||||
try {
|
||||
final hubs = await client.getGlobalHubs(limit: limit ?? 10);
|
||||
appLogger.d('Fetched ${hubs.length} global hubs from server $serverId');
|
||||
|
||||
// Filter out items from hidden libraries if specified
|
||||
if (hiddenLibraryKeys != null && hiddenLibraryKeys.isNotEmpty) {
|
||||
return hubs.map((hub) {
|
||||
final filteredItems = hub.items.where((item) {
|
||||
// Build the global key for the item's library section
|
||||
final librarySectionId = item.librarySectionID;
|
||||
if (librarySectionId == null) return true; // Keep if no section ID
|
||||
final globalKey = '$serverId:$librarySectionId';
|
||||
return !hiddenLibraryKeys.contains(globalKey);
|
||||
}).toList();
|
||||
|
||||
if (filteredItems.isEmpty) return null;
|
||||
|
||||
return PlexHub(
|
||||
hubKey: hub.hubKey,
|
||||
title: hub.title,
|
||||
type: hub.type,
|
||||
hubIdentifier: hub.hubIdentifier,
|
||||
size: filteredItems.length,
|
||||
more: hub.more,
|
||||
items: filteredItems,
|
||||
serverId: hub.serverId,
|
||||
serverName: hub.serverName,
|
||||
);
|
||||
}).whereType<PlexHub>().toList();
|
||||
}
|
||||
|
||||
return hubs;
|
||||
} catch (e, stackTrace) {
|
||||
appLogger.e('Failed to fetch hubs from server $serverId', error: e, stackTrace: stackTrace);
|
||||
_serverManager.updateServerStatus(serverId, false);
|
||||
return <PlexHub>[];
|
||||
}
|
||||
});
|
||||
|
||||
final results = await Future.wait(hubFutures);
|
||||
|
||||
// Flatten results
|
||||
for (final hubs in results) {
|
||||
allHubs.addAll(hubs);
|
||||
}
|
||||
|
||||
// Apply limit if specified (applied after merging from all servers)
|
||||
final result = limit != null && limit < allHubs.length ? allHubs.sublist(0, limit) : allHubs;
|
||||
|
||||
appLogger.i('Fetched ${result.length} global hubs from all servers');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Fetch per-library hubs using /hubs/sections/{sectionId} endpoint
|
||||
Future<List<PlexHub>> _fetchLibraryHubs(
|
||||
Map<String, PlexClient> clients, {
|
||||
int? limit,
|
||||
Set<String>? hiddenLibraryKeys,
|
||||
Map<String, List<PlexLibrary>>? librariesByServer,
|
||||
}) async {
|
||||
// Use pre-fetched libraries or fetch them if not provided
|
||||
final libraries = librariesByServer ?? await getLibrariesFromAllServersGrouped();
|
||||
|
||||
appLogger.d('Fetching hubs from ${clients.length} servers');
|
||||
appLogger.d('Fetching per-library hubs from ${clients.length} servers');
|
||||
|
||||
final allHubs = <PlexHub>[];
|
||||
|
||||
@@ -185,7 +277,7 @@ class DataAggregationService {
|
||||
// Apply limit if specified
|
||||
final result = limit != null && limit < allHubs.length ? allHubs.sublist(0, limit) : allHubs;
|
||||
|
||||
appLogger.i('Fetched ${result.length} hubs from all servers');
|
||||
appLogger.i('Fetched ${result.length} library hubs from all servers');
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -247,15 +339,11 @@ class DataAggregationService {
|
||||
|
||||
// Private helper methods
|
||||
|
||||
/// Higher-order helper for per-server fan-out operations
|
||||
/// Base helper for per-server fan-out operations
|
||||
///
|
||||
/// Iterates over all online clients, executes the operation for each server,
|
||||
/// handles errors, updates server status, and aggregates results.
|
||||
///
|
||||
/// Type parameter `T` is the item type returned by the operation
|
||||
/// [operationName] is used for logging (e.g., "fetching libraries")
|
||||
/// [operation] is the async function to run per server, returning `List<T>`
|
||||
Future<List<T>> _perServer<T>({
|
||||
/// Returns raw results as (serverId, result) tuples.
|
||||
/// Used by [_perServer] and [_perServerGrouped] for different aggregation strategies.
|
||||
Future<List<(String serverId, List<T> result)>> _perServerRaw<T>({
|
||||
required String operationName,
|
||||
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
|
||||
}) async {
|
||||
@@ -268,61 +356,6 @@ class DataAggregationService {
|
||||
|
||||
appLogger.d('$operationName from ${clients.length} servers');
|
||||
|
||||
final allResults = <T>[];
|
||||
|
||||
// Execute operation on all servers in parallel
|
||||
final Iterable<Future<List<T>>> futures = clients.entries.map((entry) async {
|
||||
final serverId = entry.key;
|
||||
final client = entry.value;
|
||||
final server = _serverManager.getServer(serverId);
|
||||
final sw = Stopwatch()..start();
|
||||
|
||||
try {
|
||||
final result = await operation(serverId, client, server);
|
||||
appLogger.d(
|
||||
'$operationName for server $serverId completed in ${sw.elapsedMilliseconds}ms with ${result.length} items',
|
||||
);
|
||||
return result;
|
||||
} catch (e, stackTrace) {
|
||||
appLogger.e('Failed $operationName from server $serverId', error: e, stackTrace: stackTrace);
|
||||
_serverManager.updateServerStatus(serverId, false);
|
||||
appLogger.d('$operationName for server $serverId failed after ${sw.elapsedMilliseconds}ms');
|
||||
return <T>[];
|
||||
}
|
||||
});
|
||||
|
||||
final List<List<T>> results = await Future.wait<List<T>>(futures);
|
||||
|
||||
// Flatten results
|
||||
for (final items in results) {
|
||||
allResults.addAll(items);
|
||||
}
|
||||
|
||||
return allResults;
|
||||
}
|
||||
|
||||
/// Higher-order helper for per-server fan-out operations that groups results by server
|
||||
///
|
||||
/// Similar to [_perServer] but returns a Map with results grouped by serverId
|
||||
/// instead of flattening into a single list.
|
||||
///
|
||||
/// Type parameter `T` is the item type returned by the operation
|
||||
/// [operationName] is used for logging (e.g., "fetching libraries")
|
||||
/// [operation] is the async function to run per server, returning `List<T>`
|
||||
Future<Map<String, List<T>>> _perServerGrouped<T>({
|
||||
required String operationName,
|
||||
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
|
||||
}) async {
|
||||
final clients = _serverManager.onlineClients;
|
||||
|
||||
if (clients.isEmpty) {
|
||||
appLogger.w('No online servers available for $operationName');
|
||||
return {};
|
||||
}
|
||||
|
||||
appLogger.d('$operationName from ${clients.length} servers');
|
||||
|
||||
// Execute operation on all servers in parallel
|
||||
final futures = clients.entries.map((entry) async {
|
||||
final serverId = entry.key;
|
||||
final client = entry.value;
|
||||
@@ -334,17 +367,38 @@ class DataAggregationService {
|
||||
appLogger.d(
|
||||
'$operationName for server $serverId completed in ${sw.elapsedMilliseconds}ms with ${result.length} items',
|
||||
);
|
||||
return MapEntry(serverId, result);
|
||||
return (serverId, result);
|
||||
} catch (e, stackTrace) {
|
||||
appLogger.e('Failed $operationName from server $serverId', error: e, stackTrace: stackTrace);
|
||||
_serverManager.updateServerStatus(serverId, false);
|
||||
appLogger.d('$operationName for server $serverId failed after ${sw.elapsedMilliseconds}ms');
|
||||
return MapEntry(serverId, <T>[]);
|
||||
return (serverId, <T>[]);
|
||||
}
|
||||
});
|
||||
|
||||
final results = await Future.wait(futures);
|
||||
return await Future.wait(futures);
|
||||
}
|
||||
|
||||
return Map.fromEntries(results);
|
||||
/// Higher-order helper for per-server fan-out operations
|
||||
///
|
||||
/// Iterates over all online clients, executes the operation for each server,
|
||||
/// handles errors, updates server status, and flattens results into a single list.
|
||||
Future<List<T>> _perServer<T>({
|
||||
required String operationName,
|
||||
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
|
||||
}) async {
|
||||
final results = await _perServerRaw(operationName: operationName, operation: operation);
|
||||
return [for (final (_, items) in results) ...items];
|
||||
}
|
||||
|
||||
/// Higher-order helper for per-server fan-out operations that groups results by server
|
||||
///
|
||||
/// Similar to [_perServer] but returns a Map with results grouped by serverId.
|
||||
Future<Map<String, List<T>>> _perServerGrouped<T>({
|
||||
required String operationName,
|
||||
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
|
||||
}) async {
|
||||
final results = await _perServerRaw(operationName: operationName, operation: operation);
|
||||
return {for (final (id, items) in results) id: items};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:dart_discord_presence/dart_discord_presence.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'plex_client.dart';
|
||||
import 'settings_service.dart';
|
||||
|
||||
/// Cached Litterbox URL with expiry timestamp
|
||||
class _CachedUrl {
|
||||
final String url;
|
||||
final DateTime expiresAt;
|
||||
|
||||
_CachedUrl(this.url, this.expiresAt);
|
||||
|
||||
bool get isExpired => DateTime.now().isAfter(expiresAt);
|
||||
}
|
||||
|
||||
/// Service that manages Discord Rich Presence integration.
|
||||
///
|
||||
/// Desktop only (Windows, macOS, Linux). Shows "Watching" activity
|
||||
/// when video is playing. Gracefully handles Discord not running.
|
||||
class DiscordRPCService {
|
||||
static const String _applicationId = '1453773470306402439';
|
||||
static const String _litterboxUrl = 'https://litterbox.catbox.moe/resources/internals/api.php';
|
||||
|
||||
/// Cache of Plex thumbnail paths to Litterbox URLs with expiry (1 hour)
|
||||
static final Map<String, _CachedUrl> _litterboxCache = {};
|
||||
|
||||
static DiscordRPCService? _instance;
|
||||
static DiscordRPCService get instance {
|
||||
_instance ??= DiscordRPCService._();
|
||||
return _instance!;
|
||||
}
|
||||
|
||||
DiscordRPC? _rpc;
|
||||
bool _isConnected = false;
|
||||
bool _isEnabled = false;
|
||||
bool _isInitialized = false;
|
||||
PlexMetadata? _currentMetadata;
|
||||
PlexClient? _currentClient;
|
||||
String? _cachedThumbnailUrl;
|
||||
DateTime? _playbackStartTime;
|
||||
Duration? _mediaDuration;
|
||||
Duration? _currentPosition;
|
||||
Timer? _reconnectTimer;
|
||||
DateTime? _lastPresenceUpdate;
|
||||
StreamSubscription<void>? _readySubscription;
|
||||
StreamSubscription<void>? _disconnectedSubscription;
|
||||
StreamSubscription<dynamic>? _errorSubscription;
|
||||
|
||||
DiscordRPCService._();
|
||||
|
||||
/// Check if Discord RPC is available on this platform
|
||||
static bool get isAvailable {
|
||||
if (!Platform.isMacOS && !Platform.isWindows && !Platform.isLinux) {
|
||||
return false;
|
||||
}
|
||||
return DiscordRPC.isAvailable;
|
||||
}
|
||||
|
||||
/// Initialize the service. Call once at app startup (main.dart).
|
||||
Future<void> initialize() async {
|
||||
if (!isAvailable) {
|
||||
appLogger.d('Discord RPC not available on this platform');
|
||||
return;
|
||||
}
|
||||
|
||||
if (_isInitialized) return;
|
||||
_isInitialized = true;
|
||||
|
||||
final settings = await SettingsService.getInstance();
|
||||
_isEnabled = settings.getEnableDiscordRPC();
|
||||
|
||||
if (_isEnabled) {
|
||||
await _connect();
|
||||
}
|
||||
}
|
||||
|
||||
/// Enable or disable Discord RPC
|
||||
Future<void> setEnabled(bool enabled) async {
|
||||
if (_isEnabled == enabled) return;
|
||||
|
||||
_isEnabled = enabled;
|
||||
|
||||
if (enabled) {
|
||||
await _connect();
|
||||
// Restore presence if we have active playback
|
||||
if (_currentMetadata != null) {
|
||||
await _updatePresence();
|
||||
}
|
||||
} else {
|
||||
await _disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/// Start showing presence for media playback
|
||||
Future<void> startPlayback(PlexMetadata metadata, PlexClient client) async {
|
||||
_currentMetadata = metadata;
|
||||
_currentClient = client;
|
||||
_playbackStartTime = DateTime.now();
|
||||
_mediaDuration = metadata.duration != null ? Duration(milliseconds: metadata.duration!) : null;
|
||||
_currentPosition = Duration.zero;
|
||||
_cachedThumbnailUrl = null;
|
||||
|
||||
if (_isEnabled && _isConnected) {
|
||||
// Upload thumbnail in background, don't block playback
|
||||
_uploadThumbnailAndUpdatePresence();
|
||||
}
|
||||
}
|
||||
|
||||
/// Update current playback position (for progress bar)
|
||||
void updatePosition(Duration position) {
|
||||
final previousPosition = _currentPosition;
|
||||
_currentPosition = position;
|
||||
|
||||
// Update presence if position jumped significantly (seek detected)
|
||||
if (_isEnabled && _isConnected && _playbackStartTime != null && previousPosition != null) {
|
||||
final drift = (position - previousPosition).abs();
|
||||
// If position changed by more than 5 seconds, likely a seek
|
||||
if (drift > const Duration(seconds: 5)) {
|
||||
// Throttle updates to max once per second
|
||||
final now = DateTime.now();
|
||||
if (_lastPresenceUpdate == null || now.difference(_lastPresenceUpdate!) > const Duration(seconds: 1)) {
|
||||
_lastPresenceUpdate = now;
|
||||
_updatePresence();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resume playback (restore timestamp)
|
||||
Future<void> resumePlayback() async {
|
||||
if (_currentMetadata == null) return;
|
||||
|
||||
// Reset start time for elapsed time display
|
||||
_playbackStartTime = DateTime.now();
|
||||
|
||||
if (_isEnabled && _isConnected) {
|
||||
await _updatePresence();
|
||||
}
|
||||
}
|
||||
|
||||
/// Pause - clear timestamp but keep showing what's playing
|
||||
Future<void> pausePlayback() async {
|
||||
// Clear start time so Discord stops counting
|
||||
_playbackStartTime = null;
|
||||
|
||||
if (_isEnabled && _isConnected) {
|
||||
await _updatePresence();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop showing presence when playback ends
|
||||
Future<void> stopPlayback() async {
|
||||
_currentMetadata = null;
|
||||
_currentClient = null;
|
||||
_playbackStartTime = null;
|
||||
_cachedThumbnailUrl = null;
|
||||
|
||||
if (_isEnabled && _isConnected) {
|
||||
await clearPresence();
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear the presence
|
||||
Future<void> clearPresence() async {
|
||||
try {
|
||||
_rpc?.clearPresence();
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to clear Discord presence', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispose the service (call on app shutdown)
|
||||
Future<void> dispose() async {
|
||||
_reconnectTimer?.cancel();
|
||||
await _disconnect();
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
||||
Future<void> _connect() async {
|
||||
if (_rpc != null) return;
|
||||
|
||||
try {
|
||||
_rpc = DiscordRPC();
|
||||
|
||||
_readySubscription = _rpc!.onReady.listen((_) async {
|
||||
_isConnected = true;
|
||||
appLogger.i('Discord RPC connected');
|
||||
|
||||
// Small delay to let Discord stabilize after connection
|
||||
await Future.delayed(const Duration(milliseconds: 200));
|
||||
|
||||
// Update presence if we have active playback
|
||||
if (_currentMetadata != null) {
|
||||
await _uploadThumbnailAndUpdatePresence();
|
||||
}
|
||||
});
|
||||
|
||||
_disconnectedSubscription = _rpc!.onDisconnected.listen((_) {
|
||||
_isConnected = false;
|
||||
appLogger.i('Discord RPC disconnected');
|
||||
_scheduleReconnect();
|
||||
});
|
||||
|
||||
_errorSubscription = _rpc!.onError.listen((error) {
|
||||
appLogger.w('Discord RPC error: $error');
|
||||
});
|
||||
|
||||
await _rpc!.initialize(_applicationId);
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to initialize Discord RPC', error: e);
|
||||
// Clean up on failure so reconnect attempts can work
|
||||
await _readySubscription?.cancel();
|
||||
await _disconnectedSubscription?.cancel();
|
||||
await _errorSubscription?.cancel();
|
||||
_readySubscription = null;
|
||||
_disconnectedSubscription = null;
|
||||
_errorSubscription = null;
|
||||
try {
|
||||
_rpc?.dispose();
|
||||
} catch (_) {}
|
||||
_rpc = null;
|
||||
_scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _disconnect() async {
|
||||
_reconnectTimer?.cancel();
|
||||
_isConnected = false;
|
||||
|
||||
await _readySubscription?.cancel();
|
||||
await _disconnectedSubscription?.cancel();
|
||||
await _errorSubscription?.cancel();
|
||||
_readySubscription = null;
|
||||
_disconnectedSubscription = null;
|
||||
_errorSubscription = null;
|
||||
|
||||
try {
|
||||
_rpc?.dispose();
|
||||
} catch (e) {
|
||||
appLogger.d('Error disposing Discord RPC', error: e);
|
||||
}
|
||||
_rpc = null;
|
||||
}
|
||||
|
||||
void _scheduleReconnect() {
|
||||
if (!_isEnabled) return;
|
||||
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = Timer(const Duration(seconds: 30), () {
|
||||
if (_isEnabled && !_isConnected) {
|
||||
_connect();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _uploadThumbnailAndUpdatePresence() async {
|
||||
// Try to upload thumbnail, but don't block on failure
|
||||
if (_cachedThumbnailUrl == null && _currentMetadata != null && _currentClient != null) {
|
||||
_cachedThumbnailUrl = await _uploadThumbnail(_currentMetadata!, _currentClient!);
|
||||
}
|
||||
await _updatePresence();
|
||||
}
|
||||
|
||||
Future<String?> _uploadThumbnail(PlexMetadata metadata, PlexClient client) async {
|
||||
try {
|
||||
// Get the thumbnail path (prefer show poster for episodes)
|
||||
final thumbPath = metadata.grandparentThumb ?? metadata.thumb;
|
||||
if (thumbPath == null || thumbPath.isEmpty) return null;
|
||||
|
||||
// Check cache first (with expiry check)
|
||||
final cached = _litterboxCache[thumbPath];
|
||||
if (cached != null && !cached.isExpired) {
|
||||
appLogger.d('Using cached Litterbox URL for: $thumbPath');
|
||||
return cached.url;
|
||||
}
|
||||
|
||||
// Get the full URL with auth token
|
||||
final imageUrl = client.getThumbnailUrl(thumbPath);
|
||||
if (imageUrl.isEmpty) return null;
|
||||
|
||||
// Fetch image data
|
||||
final dio = Dio();
|
||||
final imageResponse = await dio.get<List<int>>(
|
||||
imageUrl,
|
||||
options: Options(responseType: ResponseType.bytes, receiveTimeout: const Duration(seconds: 10)),
|
||||
);
|
||||
|
||||
final imageBytes = imageResponse.data;
|
||||
if (imageBytes == null || imageBytes.isEmpty) return null;
|
||||
|
||||
// Upload to Litterbox
|
||||
final formData = FormData.fromMap({
|
||||
'reqtype': 'fileupload',
|
||||
'time': '1h',
|
||||
'fileToUpload': MultipartFile.fromBytes(Uint8List.fromList(imageBytes), filename: 'thumbnail.jpg'),
|
||||
});
|
||||
|
||||
final uploadResponse = await dio.post<String>(
|
||||
_litterboxUrl,
|
||||
data: formData,
|
||||
options: Options(receiveTimeout: const Duration(seconds: 15)),
|
||||
);
|
||||
|
||||
final uploadedUrl = uploadResponse.data?.trim();
|
||||
if (uploadedUrl != null && uploadedUrl.startsWith('http')) {
|
||||
// Cache the URL with 1 hour expiry (matching Litterbox)
|
||||
_litterboxCache[thumbPath] = _CachedUrl(uploadedUrl, DateTime.now().add(const Duration(hours: 1)));
|
||||
appLogger.d('Uploaded and cached thumbnail: $uploadedUrl');
|
||||
return uploadedUrl;
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to upload thumbnail to Litterbox', error: e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _updatePresence() async {
|
||||
if (_rpc == null || !_isConnected || _currentMetadata == null) return;
|
||||
|
||||
try {
|
||||
final metadata = _currentMetadata!;
|
||||
final details = _buildDetails(metadata);
|
||||
final state = _buildState(metadata);
|
||||
|
||||
await _rpc!.setPresence(
|
||||
DiscordPresence(
|
||||
type: DiscordActivityType.watching,
|
||||
details: details,
|
||||
state: state,
|
||||
timestamps: _buildTimestamps(),
|
||||
statusDisplayType: DiscordStatusDisplayType.details,
|
||||
largeAsset: _cachedThumbnailUrl != null
|
||||
? DiscordAsset(url: _cachedThumbnailUrl!, text: metadata.grandparentTitle ?? metadata.title)
|
||||
: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to update Discord presence', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build timestamps for Discord progress bar
|
||||
DiscordTimestamps? _buildTimestamps() {
|
||||
// When paused, don't show timestamps (progress bar would be inaccurate)
|
||||
if (_playbackStartTime == null) return null;
|
||||
|
||||
// If we have duration, show progress bar
|
||||
if (_mediaDuration != null) {
|
||||
final now = DateTime.now();
|
||||
final position = _currentPosition ?? Duration.zero;
|
||||
|
||||
// Calculate when playback "started" (now minus current position)
|
||||
final effectiveStart = now.subtract(position);
|
||||
|
||||
// Calculate when playback will "end" (start + total duration)
|
||||
final effectiveEnd = effectiveStart.add(_mediaDuration!);
|
||||
|
||||
return DiscordTimestamps.range(effectiveStart, effectiveEnd);
|
||||
}
|
||||
|
||||
// Fallback: just show elapsed time
|
||||
return DiscordTimestamps.started(_playbackStartTime!);
|
||||
}
|
||||
|
||||
/// Build the main "details" line (first line of presence)
|
||||
String _buildDetails(PlexMetadata metadata) {
|
||||
switch (metadata.mediaType) {
|
||||
case PlexMediaType.movie:
|
||||
final year = metadata.year != null ? ' (${metadata.year})' : '';
|
||||
return metadata.title + year;
|
||||
|
||||
case PlexMediaType.episode:
|
||||
// Show: "Show Name" or just episode title if no show name
|
||||
return metadata.grandparentTitle ?? metadata.title;
|
||||
|
||||
default:
|
||||
return metadata.title;
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the "state" line (second line of presence)
|
||||
String? _buildState(PlexMetadata metadata) {
|
||||
switch (metadata.mediaType) {
|
||||
case PlexMediaType.episode:
|
||||
// Format: "S1 E5 - Episode Title"
|
||||
final season = metadata.parentIndex;
|
||||
final episode = metadata.index;
|
||||
if (season != null && episode != null) {
|
||||
return 'S$season E$episode - ${metadata.title}';
|
||||
}
|
||||
return metadata.title;
|
||||
|
||||
case PlexMediaType.movie:
|
||||
return metadata.studio;
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,16 +344,13 @@ class DownloadManagerService {
|
||||
}
|
||||
final metadata = PlexMetadata.fromJson(firstMetadata).copyWith(serverId: serverId);
|
||||
|
||||
// Get video playback data (includes URL, streams, etc.)
|
||||
// Get video playback data (includes URL, streams, markers, etc.)
|
||||
// This also caches the metadata with chapters/markers for offline use
|
||||
final playbackData = await client.getVideoPlaybackData(metadata.ratingKey);
|
||||
if (playbackData.videoUrl == null) {
|
||||
throw Exception('Could not get video URL');
|
||||
}
|
||||
|
||||
// Cache playback extras (chapters + markers) for offline use
|
||||
// This fetches and caches in one call
|
||||
await client.getPlaybackExtras(metadata.ratingKey);
|
||||
|
||||
// Determine file extension from URL or default to mp4
|
||||
final extension = _getExtensionFromUrl(playbackData.videoUrl!) ?? 'mp4';
|
||||
|
||||
|
||||
@@ -1,64 +1,17 @@
|
||||
import 'package:macos_window_utils/macos_window_utils.dart';
|
||||
import 'package:macos_window_utils/macos/ns_window_delegate.dart';
|
||||
import 'package:macos_window_utils/macos/ns_window_button_type.dart';
|
||||
import 'package:flutter/material.dart' show Offset;
|
||||
import 'fullscreen_state_manager.dart';
|
||||
import 'macos_window_delegate.dart';
|
||||
|
||||
/// Custom window delegate that manages titlebar configuration during fullscreen transitions
|
||||
class FullscreenWindowDelegate extends NSWindowDelegate {
|
||||
static const double _customButtonY = 21.0;
|
||||
|
||||
/// Custom window delegate that manages fullscreen state
|
||||
/// Note: Window manipulation (toolbar, titlebar, traffic lights) is now handled
|
||||
/// directly in Swift's WindowDelegate. This class only updates Dart-side state.
|
||||
class FullscreenWindowDelegate extends MacOSWindowDelegate {
|
||||
@override
|
||||
void windowWillEnterFullScreen() {
|
||||
// Notify global state manager
|
||||
FullscreenStateManager().setFullscreen(true);
|
||||
|
||||
// Remove toolbar and restore default titlebar before entering fullscreen
|
||||
_prepareForFullscreen();
|
||||
}
|
||||
|
||||
@override
|
||||
void windowWillExitFullScreen() {
|
||||
// Hide title and make transparent immediately (safe to do before transition)
|
||||
WindowManipulator.hideTitle();
|
||||
WindowManipulator.makeTitlebarTransparent();
|
||||
}
|
||||
|
||||
@override
|
||||
void windowDidExitFullScreen() {
|
||||
// Notify global state manager
|
||||
FullscreenStateManager().setFullscreen(false);
|
||||
|
||||
// Add toolbar and reposition traffic lights after transition completes
|
||||
WindowManipulator.addToolbar();
|
||||
|
||||
// Restore custom traffic light positions
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.closeButton,
|
||||
offset: const Offset(20, _customButtonY),
|
||||
);
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.miniaturizeButton,
|
||||
offset: const Offset(40, _customButtonY),
|
||||
);
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.zoomButton,
|
||||
offset: const Offset(60, _customButtonY),
|
||||
);
|
||||
}
|
||||
|
||||
/// Prepare titlebar for fullscreen mode
|
||||
void _prepareForFullscreen() {
|
||||
WindowManipulator.removeToolbar();
|
||||
WindowManipulator.showTitle();
|
||||
WindowManipulator.makeTitlebarOpaque();
|
||||
|
||||
// Set traffic lights to standard fullscreen positions (null = default)
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(buttonType: NSWindowButtonType.closeButton, offset: null);
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.miniaturizeButton,
|
||||
offset: null,
|
||||
);
|
||||
WindowManipulator.overrideStandardWindowButtonPosition(buttonType: NSWindowButtonType.zoomButton, offset: null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:in_app_review/in_app_review.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// Service to manage in-app review prompts
|
||||
/// Only enabled when ENABLE_IN_APP_REVIEW build flag is set
|
||||
class InAppReviewService {
|
||||
static final InAppReviewService _instance = InAppReviewService._();
|
||||
static InAppReviewService get instance => _instance;
|
||||
|
||||
InAppReviewService._();
|
||||
|
||||
final InAppReview _inAppReview = InAppReview.instance;
|
||||
|
||||
// SharedPreferences keys
|
||||
static const String _keyQualifyingSessionsCount = 'review_qualifying_sessions_count';
|
||||
static const String _keyLastPromptTime = 'review_last_prompt_time';
|
||||
|
||||
// Configuration
|
||||
static const int _requiredSessions = 6;
|
||||
static const Duration _minimumSessionDuration = Duration(minutes: 5);
|
||||
static const Duration _promptCooldown = Duration(days: 60);
|
||||
|
||||
// Session tracking
|
||||
DateTime? _sessionStartTime;
|
||||
|
||||
/// Check if in-app review is enabled via build flag
|
||||
/// Only enabled on mobile platforms (iOS and Android)
|
||||
static bool get isEnabled {
|
||||
if (!Platform.isIOS && !Platform.isAndroid) {
|
||||
return false;
|
||||
}
|
||||
const enabled = bool.fromEnvironment('ENABLE_IN_APP_REVIEW', defaultValue: false);
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/// Start tracking a new session
|
||||
void startSession() {
|
||||
if (!isEnabled) return;
|
||||
_sessionStartTime = DateTime.now();
|
||||
appLogger.d('In-app review: Session started');
|
||||
// Prompt checks should run while the app is in the foreground.
|
||||
unawaited(maybeRequestReview());
|
||||
}
|
||||
|
||||
/// End the current session and check if it qualifies
|
||||
/// Call this when app goes to background or is closed
|
||||
Future<void> endSession() async {
|
||||
if (!isEnabled || _sessionStartTime == null) return;
|
||||
|
||||
final sessionDuration = DateTime.now().difference(_sessionStartTime!);
|
||||
_sessionStartTime = null;
|
||||
|
||||
if (sessionDuration >= _minimumSessionDuration) {
|
||||
await _incrementQualifyingSessions();
|
||||
appLogger.d('In-app review: Qualifying session ended (${sessionDuration.inMinutes} minutes)');
|
||||
} else {
|
||||
appLogger.d('In-app review: Session too short (${sessionDuration.inMinutes} minutes)');
|
||||
}
|
||||
}
|
||||
|
||||
/// Increment the qualifying sessions counter
|
||||
Future<void> _incrementQualifyingSessions() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final currentCount = prefs.getInt(_keyQualifyingSessionsCount) ?? 0;
|
||||
await prefs.setInt(_keyQualifyingSessionsCount, currentCount + 1);
|
||||
}
|
||||
|
||||
/// Get the current qualifying sessions count
|
||||
Future<int> _getQualifyingSessionsCount() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getInt(_keyQualifyingSessionsCount) ?? 0;
|
||||
}
|
||||
|
||||
/// Check if we should request a review based on session count and cooldown
|
||||
Future<bool> _shouldRequestReview() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
// Check session count
|
||||
final sessionCount = await _getQualifyingSessionsCount();
|
||||
if (sessionCount < _requiredSessions) {
|
||||
appLogger.d('In-app review: Not enough sessions ($sessionCount/$_requiredSessions)');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check cooldown
|
||||
final lastPromptString = prefs.getString(_keyLastPromptTime);
|
||||
if (lastPromptString != null) {
|
||||
final lastPrompt = DateTime.parse(lastPromptString);
|
||||
final timeSinceLastPrompt = DateTime.now().difference(lastPrompt);
|
||||
if (timeSinceLastPrompt < _promptCooldown) {
|
||||
final daysRemaining = (_promptCooldown - timeSinceLastPrompt).inDays;
|
||||
appLogger.d('In-app review: Cooldown active ($daysRemaining days remaining)');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Request a review if conditions are met
|
||||
Future<void> maybeRequestReview() async {
|
||||
if (!isEnabled) return;
|
||||
|
||||
final shouldRequest = await _shouldRequestReview();
|
||||
if (!shouldRequest) return;
|
||||
|
||||
try {
|
||||
// Check if in-app review is available on this device
|
||||
final isAvailable = await _inAppReview.isAvailable();
|
||||
if (!isAvailable) {
|
||||
appLogger.d('In-app review: Not available on this device');
|
||||
return;
|
||||
}
|
||||
|
||||
// Request the review
|
||||
await _inAppReview.requestReview();
|
||||
appLogger.i('In-app review: Review prompt shown');
|
||||
|
||||
// Record that we showed the prompt and reset session count
|
||||
await _recordPromptShown();
|
||||
} catch (e) {
|
||||
appLogger.e('In-app review: Error requesting review', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Record that the review prompt was shown
|
||||
Future<void> _recordPromptShown() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyLastPromptTime, DateTime.now().toIso8601String());
|
||||
// Reset session count so user needs to use app more before next prompt
|
||||
await prefs.setInt(_keyQualifyingSessionsCount, 0);
|
||||
}
|
||||
|
||||
/// Get debug info about the current state (for development/testing)
|
||||
Future<Map<String, dynamic>> getDebugInfo() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final sessionCount = prefs.getInt(_keyQualifyingSessionsCount) ?? 0;
|
||||
final lastPromptString = prefs.getString(_keyLastPromptTime);
|
||||
final isAvailable = await _inAppReview.isAvailable();
|
||||
|
||||
return {
|
||||
'isEnabled': isEnabled,
|
||||
'isAvailable': isAvailable,
|
||||
'qualifyingSessions': sessionCount,
|
||||
'requiredSessions': _requiredSessions,
|
||||
'lastPromptTime': lastPromptString,
|
||||
'cooldownDays': _promptCooldown.inDays,
|
||||
'currentSessionStartTime': _sessionStartTime?.toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
/// Reset all stored data (for testing purposes)
|
||||
Future<void> reset() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyQualifyingSessionsCount);
|
||||
await prefs.remove(_keyLastPromptTime);
|
||||
_sessionStartTime = null;
|
||||
appLogger.d('In-app review: State reset');
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ class KeyboardShortcutsService {
|
||||
Map<String, HotKey> _hotkeys = {}; // New HotKey objects
|
||||
int _seekTimeSmall = 10; // Default, loaded from settings
|
||||
int _seekTimeLarge = 30; // Default, loaded from settings
|
||||
int _maxVolume = 100; // Default, loaded from settings (100-300%)
|
||||
|
||||
KeyboardShortcutsService._();
|
||||
|
||||
@@ -38,6 +39,7 @@ class KeyboardShortcutsService {
|
||||
_hotkeys = await _settingsService.getKeyboardHotkeys(); // Primary method
|
||||
_seekTimeSmall = _settingsService.getSeekTimeSmall();
|
||||
_seekTimeLarge = _settingsService.getSeekTimeLarge();
|
||||
_maxVolume = _settingsService.getMaxVolume();
|
||||
}
|
||||
|
||||
Map<String, String> get shortcuts => Map.from(_shortcuts);
|
||||
@@ -258,12 +260,12 @@ class KeyboardShortcutsService {
|
||||
player.playOrPause();
|
||||
break;
|
||||
case 'volume_up':
|
||||
final newVolume = (player.state.volume + 10).clamp(0.0, 100.0);
|
||||
final newVolume = (player.state.volume + 10).clamp(0.0, _maxVolume.toDouble());
|
||||
player.setVolume(newVolume);
|
||||
_settingsService.setVolume(newVolume);
|
||||
break;
|
||||
case 'volume_down':
|
||||
final newVolume = (player.state.volume - 10).clamp(0.0, 100.0);
|
||||
final newVolume = (player.state.volume - 10).clamp(0.0, _maxVolume.toDouble());
|
||||
player.setVolume(newVolume);
|
||||
_settingsService.setVolume(newVolume);
|
||||
break;
|
||||
|
||||
@@ -1,61 +1,25 @@
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:flutter/material.dart' show Offset;
|
||||
import 'package:macos_window_utils/macos_window_utils.dart';
|
||||
import 'package:macos_window_utils/macos/ns_window_button_type.dart';
|
||||
import 'fullscreen_window_delegate.dart';
|
||||
import 'macos_window_service.dart';
|
||||
|
||||
/// Service to manage macOS titlebar configuration
|
||||
class MacOSTitlebarService {
|
||||
// Standard button Y position when using custom toolbar
|
||||
static const double _customButtonY = 21.0;
|
||||
static bool _initialized = false;
|
||||
|
||||
/// Initialize the custom titlebar setup (transparent with toolbar)
|
||||
/// This configuration automatically handles fullscreen mode natively
|
||||
/// Initialize the custom titlebar setup.
|
||||
///
|
||||
/// Note: The initial window configuration (transparent titlebar, toolbar,
|
||||
/// button positions, fullscreen presentation options) is now applied in
|
||||
/// MainFlutterWindow.swift / WindowDelegate.swift BEFORE frame restoration
|
||||
/// to prevent the window from shrinking on launch.
|
||||
///
|
||||
/// This method only sets up the Dart-side callbacks.
|
||||
static Future<void> setupCustomTitlebar() async {
|
||||
if (!Platform.isMacOS) return;
|
||||
if (!Platform.isMacOS || _initialized) return;
|
||||
_initialized = true;
|
||||
|
||||
// Enable window delegate to use presentation options and fullscreen callbacks
|
||||
await WindowManipulator.initialize(enableWindowDelegate: true);
|
||||
|
||||
// Register custom delegate to handle fullscreen transitions
|
||||
await MacOSWindowService.initialize(enableWindowDelegate: true);
|
||||
final delegate = FullscreenWindowDelegate();
|
||||
WindowManipulator.addNSWindowDelegate(delegate);
|
||||
|
||||
// Make titlebar transparent but keep it functional
|
||||
await WindowManipulator.makeTitlebarTransparent();
|
||||
await WindowManipulator.hideTitle();
|
||||
await WindowManipulator.enableFullSizeContentView();
|
||||
|
||||
// Add toolbar to create space for traffic lights in normal mode
|
||||
await WindowManipulator.addToolbar();
|
||||
|
||||
// Set custom traffic light positions for normal mode
|
||||
await _setCustomButtonPositions();
|
||||
|
||||
// Configure fullscreen presentation to auto-hide toolbar and menubar
|
||||
// This tells macOS to automatically hide the toolbar when entering fullscreen
|
||||
final presentationOptions = NSAppPresentationOptions.from({
|
||||
NSAppPresentationOption.fullScreen,
|
||||
NSAppPresentationOption.autoHideToolbar,
|
||||
NSAppPresentationOption.autoHideMenuBar,
|
||||
NSAppPresentationOption.autoHideDock,
|
||||
});
|
||||
presentationOptions.applyAsFullScreenPresentationOptions();
|
||||
}
|
||||
|
||||
/// Set traffic light buttons to custom positions (with toolbar offset)
|
||||
static Future<void> _setCustomButtonPositions() async {
|
||||
await WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.closeButton,
|
||||
offset: const Offset(20, _customButtonY),
|
||||
);
|
||||
await WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.miniaturizeButton,
|
||||
offset: const Offset(40, _customButtonY),
|
||||
);
|
||||
await WindowManipulator.overrideStandardWindowButtonPosition(
|
||||
buttonType: NSWindowButtonType.zoomButton,
|
||||
offset: const Offset(60, _customButtonY),
|
||||
);
|
||||
MacOSWindowService.addWindowDelegate(delegate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/// Abstract class for receiving macOS window delegate callbacks.
|
||||
/// Extend this class and register with MacOSWindowService to receive
|
||||
/// fullscreen transition events.
|
||||
abstract class MacOSWindowDelegate {
|
||||
/// Called when the window is about to enter fullscreen mode.
|
||||
void windowWillEnterFullScreen() {}
|
||||
|
||||
/// Called when the window has entered fullscreen mode.
|
||||
void windowDidEnterFullScreen() {}
|
||||
|
||||
/// Called when the window is about to exit fullscreen mode.
|
||||
void windowWillExitFullScreen() {}
|
||||
|
||||
/// Called when the window has exited fullscreen mode.
|
||||
void windowDidExitFullScreen() {}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:flutter/services.dart';
|
||||
import 'macos_window_delegate.dart';
|
||||
|
||||
/// Service for manipulating macOS window properties.
|
||||
/// This is a native implementation replacing the macos_window_utils package.
|
||||
///
|
||||
/// Note: Titlebar, toolbar, and traffic light position management is now handled
|
||||
/// directly in Swift (WindowDelegate.swift) during fullscreen transitions.
|
||||
/// This service only exposes what's needed externally:
|
||||
/// - Traffic light visibility (for video controls)
|
||||
/// - Fullscreen enter/exit (for video controls)
|
||||
/// - Delegate registration (for FullscreenStateManager updates)
|
||||
class MacOSWindowService {
|
||||
static const _channel = MethodChannel('com.plezy/window_utils');
|
||||
static bool _initialized = false;
|
||||
static bool _delegateEnabled = false;
|
||||
static final List<MacOSWindowDelegate> _delegates = [];
|
||||
|
||||
// MARK: - Private Helpers
|
||||
|
||||
static Future<void> _invoke(String method, [Map<String, dynamic>? args]) async {
|
||||
if (!Platform.isMacOS) return;
|
||||
await _channel.invokeMethod(method, args);
|
||||
}
|
||||
|
||||
static void _notifyDelegates(void Function(MacOSWindowDelegate) callback) {
|
||||
for (final delegate in _delegates) {
|
||||
callback(delegate);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<dynamic> _handleMethodCall(MethodCall call) async {
|
||||
switch (call.method) {
|
||||
case 'windowWillEnterFullScreen':
|
||||
_notifyDelegates((d) => d.windowWillEnterFullScreen());
|
||||
case 'windowDidEnterFullScreen':
|
||||
_notifyDelegates((d) => d.windowDidEnterFullScreen());
|
||||
case 'windowWillExitFullScreen':
|
||||
_notifyDelegates((d) => d.windowWillExitFullScreen());
|
||||
case 'windowDidExitFullScreen':
|
||||
_notifyDelegates((d) => d.windowDidExitFullScreen());
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
/// Initialize the window service.
|
||||
/// Must be called before using other methods.
|
||||
/// Set [enableWindowDelegate] to true to receive fullscreen callbacks.
|
||||
static Future<void> initialize({bool enableWindowDelegate = false}) async {
|
||||
if (!Platform.isMacOS) return;
|
||||
|
||||
if (!_initialized) {
|
||||
await _channel.invokeMethod('initialize', {'enableWindowDelegate': enableWindowDelegate});
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
// Set up handler if not already done and delegate is requested
|
||||
if (enableWindowDelegate && !_delegateEnabled) {
|
||||
_channel.setMethodCallHandler(_handleMethodCall);
|
||||
_delegateEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a delegate to receive window events.
|
||||
static void addWindowDelegate(MacOSWindowDelegate delegate) {
|
||||
if (!_delegates.contains(delegate)) {
|
||||
_delegates.add(delegate);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a previously added delegate.
|
||||
static void removeWindowDelegate(MacOSWindowDelegate delegate) {
|
||||
_delegates.remove(delegate);
|
||||
}
|
||||
|
||||
// MARK: - Traffic Light Buttons
|
||||
|
||||
/// Show or hide all traffic light buttons (close, miniaturize, zoom).
|
||||
static Future<void> setTrafficLightsVisible(bool visible) => _invoke('setTrafficLightsVisible', {'visible': visible});
|
||||
|
||||
// MARK: - Fullscreen
|
||||
|
||||
/// Enter fullscreen mode.
|
||||
static Future<void> enterFullscreen() => _invoke('enterFullscreen');
|
||||
|
||||
/// Exit fullscreen mode.
|
||||
static Future<void> exitFullscreen() => _invoke('exitFullscreen');
|
||||
|
||||
/// Check if the window is in fullscreen mode.
|
||||
static Future<bool> isFullscreen() async {
|
||||
if (!Platform.isMacOS) return false;
|
||||
return await _channel.invokeMethod<bool>('isFullscreen') ?? false;
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,8 @@ class MediaControlsManager {
|
||||
final params = _PlaybackStateParams(isPlaying: isPlaying, position: position, speed: speed);
|
||||
|
||||
if (force) {
|
||||
// Bypass throttling for forced updates
|
||||
// Cancel any pending throttled update to prevent stale state from overwriting
|
||||
_throttledUpdate.cancel();
|
||||
await _doUpdatePlaybackState(params);
|
||||
} else {
|
||||
// Use throttled update
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class PipService {
|
||||
static const MethodChannel _channel = MethodChannel('app.plezy/pip');
|
||||
|
||||
// Singleton instance
|
||||
static final PipService _instance = PipService._internal();
|
||||
factory PipService() => _instance;
|
||||
|
||||
PipService._internal() {
|
||||
// Listen for callbacks from native Android
|
||||
_channel.setMethodCallHandler(_handleMethodCall);
|
||||
}
|
||||
|
||||
/// ValueNotifier for PiP state - widgets can listen to this
|
||||
final ValueNotifier<bool> isPipActive = ValueNotifier<bool>(false);
|
||||
|
||||
Future<dynamic> _handleMethodCall(MethodCall call) async {
|
||||
switch (call.method) {
|
||||
case 'onPipChanged':
|
||||
final isInPip = call.arguments as bool;
|
||||
isPipActive.value = isInPip;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> isSupported() async {
|
||||
return await _channel.invokeMethod<bool>('isSupported') ?? false;
|
||||
}
|
||||
|
||||
static Future<void> enter({int? width, int? height}) async {
|
||||
await _channel.invokeMethod('enter', {'width': width, 'height': height});
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import 'plex_client.dart';
|
||||
import 'offline_watch_sync_service.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
|
||||
/// Tracks playback progress and reports it to the Plex server.
|
||||
///
|
||||
@@ -103,6 +104,15 @@ class PlaybackProgressTracker {
|
||||
// Send progress to server immediately
|
||||
await _sendOnlineProgress(state, position, duration);
|
||||
}
|
||||
|
||||
// Emit watch state event on stop for UI updates across screens
|
||||
if (state == 'stopped' && position.inMilliseconds > 0) {
|
||||
WatchStateNotifier().notifyProgress(
|
||||
metadata: metadata,
|
||||
viewOffset: position.inMilliseconds,
|
||||
duration: duration.inMilliseconds,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.d('Failed to send progress update (non-critical)', error: e);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import '../utils/app_logger.dart';
|
||||
import '../utils/log_redaction_manager.dart';
|
||||
import '../utils/plex_cache_parser.dart';
|
||||
import '../utils/plex_url_helper.dart';
|
||||
import '../utils/watch_state_notifier.dart';
|
||||
import 'plex_api_cache.dart';
|
||||
|
||||
/// Constants for Plex stream types
|
||||
@@ -443,7 +444,10 @@ class PlexClient {
|
||||
|
||||
// Online: try network first
|
||||
try {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey', queryParameters: queryParams);
|
||||
// Always include markers and chapters to ensure cached data is complete
|
||||
// This prevents cache corruption when different methods fetch the same endpoint
|
||||
final mergedParams = {'includeMarkers': 1, 'includeChapters': 1, ...?queryParams};
|
||||
final response = await _dio.get('/library/metadata/$ratingKey', queryParameters: mergedParams);
|
||||
|
||||
// Cache at base endpoint
|
||||
if (response.data != null) {
|
||||
@@ -533,7 +537,6 @@ class PlexClient {
|
||||
final streamType = stream['streamType'] as int?;
|
||||
|
||||
if (streamType == PlexStreamType.audio) {
|
||||
// Audio track
|
||||
audioTracks.add(
|
||||
PlexAudioTrack(
|
||||
id: stream['id'] as int,
|
||||
@@ -544,11 +547,10 @@ class PlexClient {
|
||||
title: stream['title'] as String?,
|
||||
displayTitle: stream['displayTitle'] as String?,
|
||||
channels: stream['channels'] as int?,
|
||||
selected: stream['selected'] == 1,
|
||||
selected: stream['selected'] == 1 || stream['selected'] == true,
|
||||
),
|
||||
);
|
||||
} else if (streamType == PlexStreamType.subtitle) {
|
||||
// Subtitle track
|
||||
subtitleTracks.add(
|
||||
PlexSubtitleTrack(
|
||||
id: stream['id'] as int,
|
||||
@@ -558,7 +560,7 @@ class PlexClient {
|
||||
languageCode: stream['languageCode'] as String?,
|
||||
title: stream['title'] as String?,
|
||||
displayTitle: stream['displayTitle'] as String?,
|
||||
selected: stream['selected'] == 1,
|
||||
selected: stream['selected'] == 1 || stream['selected'] == true,
|
||||
forced: stream['forced'] == 1,
|
||||
key: stream['key'] as String?,
|
||||
),
|
||||
@@ -782,36 +784,6 @@ class PlexClient {
|
||||
return '${config.baseUrl}/$path'.withPlexToken(config.token);
|
||||
}
|
||||
|
||||
/// Get video URL for direct playback
|
||||
/// [mediaIndex] specifies which Media item to use (defaults to 0 - first version)
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<String?> getVideoUrl(String ratingKey, {int mediaIndex = 0}) async {
|
||||
final data = await _fetchMetadataWithCache(ratingKey);
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
|
||||
if (metadataJson != null && metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
}
|
||||
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
if (partKey != null) {
|
||||
// Return direct play URL
|
||||
return '${config.baseUrl}$partKey'.withPlexToken(config.token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Get chapters for a media item
|
||||
Future<List<PlexChapter>> getChapters(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey', queryParameters: {'includeChapters': 1});
|
||||
@@ -953,63 +925,8 @@ class PlexClient {
|
||||
return PlaybackExtras(chapters: chapters, markers: markers);
|
||||
}
|
||||
|
||||
/// Get detailed media info including chapters and tracks
|
||||
/// [mediaIndex] specifies which Media item to use (defaults to 0 - first version)
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<PlexMediaInfo?> getMediaInfo(String ratingKey, {int mediaIndex = 0}) async {
|
||||
final data = await _fetchMetadataWithCache(ratingKey);
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
|
||||
if (metadataJson != null && metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
}
|
||||
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
if (partKey != null) {
|
||||
// Parse streams using helper
|
||||
final streams = _parseStreams(part['Stream'] as List<dynamic>?);
|
||||
// Parse chapters using helper
|
||||
final chapters = _parseChapters(metadataJson);
|
||||
|
||||
return PlexMediaInfo(
|
||||
videoUrl: '${config.baseUrl}$partKey'.withPlexToken(config.token),
|
||||
audioTracks: streams.audio,
|
||||
subtitleTracks: streams.subtitles,
|
||||
chapters: chapters,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Get all available media versions for a media item
|
||||
/// Returns a list of PlexMediaVersion objects representing different quality/format options
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<List<PlexMediaVersion>> getMediaVersions(String ratingKey) async {
|
||||
final data = await _fetchMetadataWithCache(ratingKey);
|
||||
final metadataJson = _getFirstMetadataJsonFromData(data);
|
||||
|
||||
if (metadataJson != null && metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
return mediaList.map((media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>)).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get consolidated video playback data (URL, media info, and versions) in a single API call
|
||||
/// This method combines the functionality of getVideoUrl(), getMediaInfo(), and getMediaVersions()
|
||||
/// to reduce redundant API calls during video playback initialization.
|
||||
/// Get consolidated video playback data (URL, media info, versions, and markers) in a single API call.
|
||||
/// This is the primary method for playback initialization.
|
||||
/// Uses cache for offline mode support and network fallback.
|
||||
Future<PlexVideoPlaybackData> getVideoPlaybackData(String ratingKey, {int mediaIndex = 0}) async {
|
||||
final data = await _fetchMetadataWithCache(ratingKey);
|
||||
@@ -1018,45 +935,68 @@ class PlexClient {
|
||||
String? videoUrl;
|
||||
PlexMediaInfo? mediaInfo;
|
||||
List<PlexMediaVersion> availableVersions = [];
|
||||
List<PlexMarker> markers = [];
|
||||
|
||||
if (metadataJson != null && metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
// Parse available media versions first
|
||||
availableVersions = mediaList.map((media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>)).toList();
|
||||
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
if (metadataJson != null) {
|
||||
// Parse markers (for auto-skip functionality)
|
||||
if (metadataJson['Marker'] != null) {
|
||||
final markerList = metadataJson['Marker'] as List;
|
||||
for (var marker in markerList) {
|
||||
markers.add(
|
||||
PlexMarker(
|
||||
id: marker['id'] as int,
|
||||
type: marker['type'] as String,
|
||||
startTimeOffset: marker['startTimeOffset'] as int,
|
||||
endTimeOffset: marker['endTimeOffset'] as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
if (metadataJson['Media'] != null && (metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
if (partKey != null) {
|
||||
// Get video URL
|
||||
videoUrl = '${config.baseUrl}$partKey'.withPlexToken(config.token);
|
||||
// Parse available media versions first
|
||||
availableVersions = mediaList.map((media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>)).toList();
|
||||
|
||||
// Parse streams using helper
|
||||
final streams = _parseStreams(part['Stream'] as List<dynamic>?);
|
||||
// Parse chapters using helper
|
||||
final chapters = _parseChapters(metadataJson);
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
}
|
||||
|
||||
// Create media info
|
||||
mediaInfo = PlexMediaInfo(
|
||||
videoUrl: videoUrl,
|
||||
audioTracks: streams.audio,
|
||||
subtitleTracks: streams.subtitles,
|
||||
chapters: chapters,
|
||||
partId: part['id'] as int?,
|
||||
);
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
if (partKey != null) {
|
||||
// Get video URL
|
||||
videoUrl = '${config.baseUrl}$partKey'.withPlexToken(config.token);
|
||||
|
||||
// Parse streams using helper
|
||||
final streams = _parseStreams(part['Stream'] as List<dynamic>?);
|
||||
// Parse chapters using helper
|
||||
final chapters = _parseChapters(metadataJson);
|
||||
|
||||
// Create media info
|
||||
mediaInfo = PlexMediaInfo(
|
||||
videoUrl: videoUrl,
|
||||
audioTracks: streams.audio,
|
||||
subtitleTracks: streams.subtitles,
|
||||
chapters: chapters,
|
||||
partId: part['id'] as int?,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PlexVideoPlaybackData(videoUrl: videoUrl, mediaInfo: mediaInfo, availableVersions: availableVersions);
|
||||
return PlexVideoPlaybackData(
|
||||
videoUrl: videoUrl,
|
||||
mediaInfo: mediaInfo,
|
||||
availableVersions: availableVersions,
|
||||
markers: markers,
|
||||
);
|
||||
}
|
||||
|
||||
/// Get file information for a media item
|
||||
@@ -1125,13 +1065,23 @@ class PlexClient {
|
||||
}
|
||||
|
||||
/// Mark media as watched
|
||||
Future<void> markAsWatched(String ratingKey) async {
|
||||
///
|
||||
/// If [metadata] is provided, emits a [WatchStateEvent] for UI updates.
|
||||
Future<void> markAsWatched(String ratingKey, {PlexMetadata? metadata}) async {
|
||||
await _dio.get('/:/scrobble', queryParameters: {'key': ratingKey, 'identifier': 'com.plexapp.plugins.library'});
|
||||
if (metadata != null) {
|
||||
WatchStateNotifier().notifyWatched(metadata: metadata, isNowWatched: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark media as unwatched
|
||||
Future<void> markAsUnwatched(String ratingKey) async {
|
||||
///
|
||||
/// If [metadata] is provided, emits a [WatchStateEvent] for UI updates.
|
||||
Future<void> markAsUnwatched(String ratingKey, {PlexMetadata? metadata}) async {
|
||||
await _dio.get('/:/unscrobble', queryParameters: {'key': ratingKey, 'identifier': 'com.plexapp.plugins.library'});
|
||||
if (metadata != null) {
|
||||
WatchStateNotifier().notifyWatched(metadata: metadata, isNowWatched: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Update playback progress
|
||||
@@ -1263,11 +1213,9 @@ class PlexClient {
|
||||
final hub = PlexHub.fromJson(hubJson);
|
||||
// Only include hubs that have items and are movie/show content
|
||||
if (hub.items.isNotEmpty) {
|
||||
// Filter out non-video content types and tag with server info
|
||||
// Filter to only video content (movies, shows, seasons, episodes) and tag with server info
|
||||
final videoItems = hub.items
|
||||
.where((item) {
|
||||
return item.isMovie || item.isShow;
|
||||
})
|
||||
.where((item) => item.isVideoContent)
|
||||
.map((item) => item.copyWith(serverId: serverId, serverName: serverName))
|
||||
.toList();
|
||||
|
||||
@@ -1299,14 +1247,65 @@ class PlexClient {
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get global hubs (home page recommendations)
|
||||
/// Returns actual home page hubs like "Recently Added Movies", "Recently Added TV", etc.
|
||||
/// This matches the official Plex client's home page layout.
|
||||
Future<List<PlexHub>> getGlobalHubs({int limit = 10}) async {
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
'/hubs',
|
||||
queryParameters: {'count': limit, 'includeGuids': 1},
|
||||
);
|
||||
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Hub'] != null) {
|
||||
final hubs = <PlexHub>[];
|
||||
for (final hubJson in container['Hub'] as List) {
|
||||
try {
|
||||
final hub = PlexHub.fromJson(hubJson);
|
||||
if (hub.items.isEmpty) continue;
|
||||
|
||||
// Filter to only video content (movies, shows, seasons, episodes) and tag with server info
|
||||
final videoItems = hub.items
|
||||
.where((item) => item.isVideoContent)
|
||||
.map((item) => item.copyWith(serverId: serverId, serverName: serverName))
|
||||
.toList();
|
||||
|
||||
if (videoItems.isNotEmpty) {
|
||||
hubs.add(
|
||||
PlexHub(
|
||||
hubKey: hub.hubKey,
|
||||
title: hub.title,
|
||||
type: hub.type,
|
||||
hubIdentifier: hub.hubIdentifier,
|
||||
size: hub.size,
|
||||
more: hub.more,
|
||||
items: videoItems,
|
||||
serverId: serverId,
|
||||
serverName: serverName,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to parse global hub', error: e);
|
||||
}
|
||||
}
|
||||
return hubs;
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to get global hubs: $e');
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get full content from a hub using its hub key
|
||||
/// Returns the complete list of metadata items in the hub
|
||||
Future<List<PlexMetadata>> getHubContent(String hubKey) async {
|
||||
return _wrapListApiCall<PlexMetadata>(() => _dio.get(hubKey), (response) {
|
||||
final allItems = _extractMetadataList(response);
|
||||
// Filter out non-video content types
|
||||
// Filter to only video content (movies, shows, seasons, episodes)
|
||||
return allItems.where((item) {
|
||||
return item.isMovie || item.isShow;
|
||||
return item.isVideoContent;
|
||||
}).toList();
|
||||
}, 'Failed to get hub content');
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:hotkey_manager/hotkey_manager.dart';
|
||||
import 'package:plezy/utils/app_logger.dart';
|
||||
import '../i18n/strings.g.dart';
|
||||
import '../models/mpv_config_models.dart';
|
||||
import 'base_shared_preferences_service.dart';
|
||||
import '../utils/platform_detector.dart';
|
||||
|
||||
@@ -12,6 +13,8 @@ enum LibraryDensity { compact, normal, comfortable }
|
||||
|
||||
enum ViewMode { grid, list }
|
||||
|
||||
enum EpisodePosterMode { seriesPoster, seasonPoster, episodeThumbnail }
|
||||
|
||||
class SettingsService extends BaseSharedPreferencesService {
|
||||
static const String _keyThemeMode = 'theme_mode';
|
||||
static const String _keyEnableDebugLogging = 'enable_debug_logging';
|
||||
@@ -24,11 +27,13 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
static const String _keyPreferredAudioCodec = 'preferred_audio_codec';
|
||||
static const String _keyLibraryDensity = 'library_density';
|
||||
static const String _keyViewMode = 'view_mode';
|
||||
static const String _keyUseSeasonPoster = 'use_season_poster';
|
||||
static const String _keyUseSeasonPoster = 'use_season_poster'; // Legacy key for migration
|
||||
static const String _keyEpisodePosterMode = 'episode_poster_mode';
|
||||
static const String _keySeekTimeSmall = 'seek_time_small';
|
||||
static const String _keySeekTimeLarge = 'seek_time_large';
|
||||
static const String _keyMediaVersionPreferences = 'media_version_preferences';
|
||||
static const String _keyShowHeroSection = 'show_hero_section';
|
||||
static const String _keyUseGlobalHubs = 'use_global_hubs';
|
||||
static const String _keySleepTimerDuration = 'sleep_timer_duration';
|
||||
static const String _keyAudioSyncOffset = 'audio_sync_offset';
|
||||
static const String _keySubtitleSyncOffset = 'subtitle_sync_offset';
|
||||
@@ -49,6 +54,12 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
static const String _keyCustomDownloadPathType = 'custom_download_path_type';
|
||||
static const String _keyDownloadOnWifiOnly = 'download_on_wifi_only';
|
||||
static const String _keyVideoPlayerNavigationEnabled = 'video_player_navigation_enabled';
|
||||
static const String _keyShowPerformanceOverlay = 'show_performance_overlay';
|
||||
static const String _keyMpvConfigEntries = 'mpv_config_entries';
|
||||
static const String _keyMpvConfigPresets = 'mpv_config_presets';
|
||||
static const String _keyMaxVolume = 'max_volume';
|
||||
static const String _keyEnableDiscordRPC = 'enable_discord_rpc';
|
||||
static const String _keyMatchContentFrameRate = 'match_content_frame_rate';
|
||||
|
||||
SettingsService._();
|
||||
|
||||
@@ -146,13 +157,23 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return _getEnumValue(_keyViewMode, ViewMode.values, ViewMode.grid);
|
||||
}
|
||||
|
||||
// Use Season Poster
|
||||
Future<void> setUseSeasonPoster(bool enabled) async {
|
||||
await prefs.setBool(_keyUseSeasonPoster, enabled);
|
||||
// Episode Poster Mode
|
||||
Future<void> setEpisodePosterMode(EpisodePosterMode mode) async {
|
||||
await prefs.setString(_keyEpisodePosterMode, mode.name);
|
||||
}
|
||||
|
||||
bool getUseSeasonPoster() {
|
||||
return prefs.getBool(_keyUseSeasonPoster) ?? false; // Default: false (use series poster)
|
||||
EpisodePosterMode getEpisodePosterMode() {
|
||||
// Migration: check old boolean key first
|
||||
final legacyValue = prefs.getBool(_keyUseSeasonPoster);
|
||||
if (legacyValue != null) {
|
||||
// Migrate old setting: true = seasonPoster, false = seriesPoster
|
||||
final migratedMode = legacyValue ? EpisodePosterMode.seasonPoster : EpisodePosterMode.seriesPoster;
|
||||
// Clear old key and save new format (fire and forget)
|
||||
prefs.remove(_keyUseSeasonPoster);
|
||||
prefs.setString(_keyEpisodePosterMode, migratedMode.name);
|
||||
return migratedMode;
|
||||
}
|
||||
return _getEnumValue(_keyEpisodePosterMode, EpisodePosterMode.values, EpisodePosterMode.episodeThumbnail);
|
||||
}
|
||||
|
||||
// Show Hero Section
|
||||
@@ -164,6 +185,15 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return prefs.getBool(_keyShowHeroSection) ?? true; // Default: true (show hero section)
|
||||
}
|
||||
|
||||
// Use Global Hubs (true = global /hubs endpoint, false = per-library hubs)
|
||||
Future<void> setUseGlobalHubs(bool enabled) async {
|
||||
await prefs.setBool(_keyUseGlobalHubs, enabled);
|
||||
}
|
||||
|
||||
bool getUseGlobalHubs() {
|
||||
return prefs.getBool(_keyUseGlobalHubs) ?? true; // Default: true (use global hubs like official Plex)
|
||||
}
|
||||
|
||||
// Seek Time Small (in seconds)
|
||||
Future<void> setSeekTimeSmall(int seconds) async {
|
||||
await prefs.setInt(_keySeekTimeSmall, seconds);
|
||||
@@ -218,6 +248,15 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return prefs.getDouble(_keyVolume) ?? 100.0; // Default: full volume
|
||||
}
|
||||
|
||||
// Max Volume (100-300%, for volume boost)
|
||||
Future<void> setMaxVolume(int percent) async {
|
||||
await prefs.setInt(_keyMaxVolume, percent.clamp(100, 300));
|
||||
}
|
||||
|
||||
int getMaxVolume() {
|
||||
return prefs.getInt(_keyMaxVolume) ?? 100; // Default: 100% (no boost)
|
||||
}
|
||||
|
||||
// Rotation Lock (mobile only)
|
||||
Future<void> setRotationLocked(bool locked) async {
|
||||
await prefs.setBool(_keyRotationLocked, locked);
|
||||
@@ -431,6 +470,15 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return prefs.getBool(_keyVideoPlayerNavigationEnabled) ?? TvDetectionService.isTVSync();
|
||||
}
|
||||
|
||||
// Performance Overlay (show debug stats on video player)
|
||||
Future<void> setShowPerformanceOverlay(bool enabled) async {
|
||||
await prefs.setBool(_keyShowPerformanceOverlay, enabled);
|
||||
}
|
||||
|
||||
bool getShowPerformanceOverlay() {
|
||||
return prefs.getBool(_keyShowPerformanceOverlay) ?? false; // Default: disabled
|
||||
}
|
||||
|
||||
// Helper methods for HotKey serialization
|
||||
static const _modifierMap = <String, HotKeyModifier>{
|
||||
'alt': HotKeyModifier.alt,
|
||||
@@ -442,7 +490,10 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
};
|
||||
|
||||
Map<String, dynamic> _serializeHotKey(HotKey hotKey) {
|
||||
return {'key': hotKey.key.toString(), 'modifiers': hotKey.modifiers?.map((m) => m.name).toList() ?? []};
|
||||
// Use USB HID code for reliable serialization across debug/release modes
|
||||
final physicalKey = hotKey.key as PhysicalKeyboardKey;
|
||||
final usbHidCode = physicalKey.usbHidUsage.toRadixString(16).padLeft(8, '0');
|
||||
return {'key': usbHidCode, 'modifiers': hotKey.modifiers?.map((m) => m.name).toList() ?? []};
|
||||
}
|
||||
|
||||
HotKey? _deserializeHotKey(Map<String, dynamic> data) {
|
||||
@@ -456,7 +507,8 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
.cast<HotKeyModifier>()
|
||||
.toList();
|
||||
|
||||
final key = _findKeyByString(keyString);
|
||||
// Try direct USB HID lookup first (new format), fall back to string parsing (backwards compat)
|
||||
final key = _usbHidKeyMap[keyString] ?? _findKeyByString(keyString);
|
||||
if (key != null) {
|
||||
return HotKey(key: key, modifiers: modifiers.isNotEmpty ? modifiers : null);
|
||||
}
|
||||
@@ -795,6 +847,96 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
return prefs.getBool(_keyDownloadOnWifiOnly) ?? false;
|
||||
}
|
||||
|
||||
// MPV Config Entries
|
||||
|
||||
/// Get all MPV config entries
|
||||
List<MpvConfigEntry> getMpvConfigEntries() {
|
||||
final jsonString = prefs.getString(_keyMpvConfigEntries);
|
||||
if (jsonString == null) return [];
|
||||
|
||||
try {
|
||||
final List<dynamic> decoded = json.decode(jsonString);
|
||||
return decoded.map((e) => MpvConfigEntry.fromJson(e as Map<String, dynamic>)).toList();
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Save all MPV config entries
|
||||
Future<void> setMpvConfigEntries(List<MpvConfigEntry> entries) async {
|
||||
final jsonString = json.encode(entries.map((e) => e.toJson()).toList());
|
||||
await prefs.setString(_keyMpvConfigEntries, jsonString);
|
||||
}
|
||||
|
||||
/// Get only enabled MPV config entries (for player initialization)
|
||||
Map<String, String> getEnabledMpvConfigEntries() {
|
||||
final entries = getMpvConfigEntries();
|
||||
return Map.fromEntries(entries.where((e) => e.isEnabled).map((e) => MapEntry(e.key, e.value)));
|
||||
}
|
||||
|
||||
// MPV Presets
|
||||
|
||||
/// Get all saved presets
|
||||
List<MpvPreset> getMpvPresets() {
|
||||
final jsonString = prefs.getString(_keyMpvConfigPresets);
|
||||
if (jsonString == null) return [];
|
||||
|
||||
try {
|
||||
final List<dynamic> decoded = json.decode(jsonString);
|
||||
return decoded.map((e) => MpvPreset.fromJson(e as Map<String, dynamic>)).toList();
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Save a new preset (overwrites existing with same name)
|
||||
Future<void> saveMpvPreset(String name, List<MpvConfigEntry> entries) async {
|
||||
final presets = getMpvPresets();
|
||||
|
||||
// Remove existing preset with same name
|
||||
presets.removeWhere((p) => p.name == name);
|
||||
|
||||
presets.add(MpvPreset(name: name, entries: entries, createdAt: DateTime.now()));
|
||||
|
||||
final jsonString = json.encode(presets.map((p) => p.toJson()).toList());
|
||||
await prefs.setString(_keyMpvConfigPresets, jsonString);
|
||||
}
|
||||
|
||||
/// Delete a preset by name
|
||||
Future<void> deleteMpvPreset(String name) async {
|
||||
final presets = getMpvPresets();
|
||||
presets.removeWhere((p) => p.name == name);
|
||||
|
||||
final jsonString = json.encode(presets.map((p) => p.toJson()).toList());
|
||||
await prefs.setString(_keyMpvConfigPresets, jsonString);
|
||||
}
|
||||
|
||||
/// Load a preset (replaces current entries)
|
||||
Future<void> loadMpvPreset(String name) async {
|
||||
final presets = getMpvPresets();
|
||||
final preset = presets.firstWhere((p) => p.name == name, orElse: () => throw Exception('Preset not found: $name'));
|
||||
|
||||
await setMpvConfigEntries(preset.entries);
|
||||
}
|
||||
|
||||
// Discord Rich Presence
|
||||
Future<void> setEnableDiscordRPC(bool enabled) async {
|
||||
await prefs.setBool(_keyEnableDiscordRPC, enabled);
|
||||
}
|
||||
|
||||
bool getEnableDiscordRPC() {
|
||||
return prefs.getBool(_keyEnableDiscordRPC) ?? false; // Default disabled
|
||||
}
|
||||
|
||||
// Match Content Frame Rate (Android only)
|
||||
Future<void> setMatchContentFrameRate(bool enabled) async {
|
||||
await prefs.setBool(_keyMatchContentFrameRate, enabled);
|
||||
}
|
||||
|
||||
bool getMatchContentFrameRate() {
|
||||
return prefs.getBool(_keyMatchContentFrameRate) ?? false; // Default disabled
|
||||
}
|
||||
|
||||
// Reset all settings to defaults
|
||||
Future<void> resetAllSettings() async {
|
||||
await Future.wait([
|
||||
@@ -809,7 +951,8 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
prefs.remove(_keyPreferredAudioCodec),
|
||||
prefs.remove(_keyLibraryDensity),
|
||||
prefs.remove(_keyViewMode),
|
||||
prefs.remove(_keyUseSeasonPoster),
|
||||
prefs.remove(_keyUseSeasonPoster), // Legacy key
|
||||
prefs.remove(_keyEpisodePosterMode),
|
||||
prefs.remove(_keyShowHeroSection),
|
||||
prefs.remove(_keySeekTimeSmall),
|
||||
prefs.remove(_keySeekTimeLarge),
|
||||
@@ -818,6 +961,7 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
prefs.remove(_keyAudioSyncOffset),
|
||||
prefs.remove(_keySubtitleSyncOffset),
|
||||
prefs.remove(_keyVolume),
|
||||
prefs.remove(_keyMaxVolume),
|
||||
prefs.remove(_keySubtitleFontSize),
|
||||
prefs.remove(_keySubtitleTextColor),
|
||||
prefs.remove(_keySubtitleBorderSize),
|
||||
@@ -830,6 +974,11 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
prefs.remove(_keyCustomDownloadPathType),
|
||||
prefs.remove(_keyDownloadOnWifiOnly),
|
||||
prefs.remove(_keyVideoPlayerNavigationEnabled),
|
||||
prefs.remove(_keyShowPerformanceOverlay),
|
||||
prefs.remove(_keyMpvConfigEntries),
|
||||
prefs.remove(_keyMpvConfigPresets),
|
||||
prefs.remove(_keyEnableDiscordRPC),
|
||||
prefs.remove(_keyMatchContentFrameRate),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -854,7 +1003,7 @@ class SettingsService extends BaseSharedPreferencesService {
|
||||
'preferredAudioCodec': getPreferredAudioCodec(),
|
||||
'libraryDensity': getLibraryDensity().name,
|
||||
'viewMode': getViewMode().name,
|
||||
'useSeasonPoster': getUseSeasonPoster(),
|
||||
'episodePosterMode': getEpisodePosterMode().name,
|
||||
'seekTimeSmall': getSeekTimeSmall(),
|
||||
'seekTimeLarge': getSeekTimeLarge(),
|
||||
'keyboardShortcuts': getKeyboardShortcuts(),
|
||||
|
||||
@@ -1,18 +1,38 @@
|
||||
import '../mpv/mpv.dart';
|
||||
|
||||
import '../models/plex_media_info.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_user_profile.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/language_codes.dart';
|
||||
|
||||
/// Priority levels for track selection
|
||||
enum TrackSelectionPriority {
|
||||
navigation, // Priority 1: User's manual selection from previous episode
|
||||
plexSelected, // Priority 2: Plex's selected track
|
||||
perMedia, // Priority 3: Per-media language preference
|
||||
profile, // Priority 4: User profile preferences
|
||||
defaultTrack, // Priority 5: Default or first track
|
||||
off, // Priority 6: Subtitles off (subtitle only)
|
||||
}
|
||||
|
||||
/// Result of track selection including the selected track and which priority was used
|
||||
class TrackSelectionResult<T> {
|
||||
final T track;
|
||||
final TrackSelectionPriority priority;
|
||||
|
||||
TrackSelectionResult(this.track, this.priority);
|
||||
}
|
||||
|
||||
/// Service for selecting and applying audio and subtitle tracks based on
|
||||
/// preferences, user profiles, and per-media settings.
|
||||
class TrackSelectionService {
|
||||
final Player player;
|
||||
final PlexUserProfile? profileSettings;
|
||||
final PlexMetadata metadata;
|
||||
final PlexMediaInfo? plexMediaInfo;
|
||||
|
||||
TrackSelectionService({required this.player, this.profileSettings, required this.metadata});
|
||||
TrackSelectionService({required this.player, this.profileSettings, required this.metadata, this.plexMediaInfo});
|
||||
|
||||
/// Build list of preferred languages from a user profile
|
||||
List<String> _buildPreferredLanguages(PlexUserProfile profile, {required bool isAudio}) {
|
||||
@@ -38,8 +58,6 @@ class TrackSelectionService {
|
||||
String trackType,
|
||||
) {
|
||||
final languageVariations = LanguageCodes.getVariations(preferredLanguage);
|
||||
appLogger.d('Checking language variations for "$preferredLanguage": ${languageVariations.join(", ")}');
|
||||
|
||||
return _findTrackByLanguageVariations<T>(
|
||||
tracks,
|
||||
preferredLanguage,
|
||||
@@ -53,11 +71,7 @@ class TrackSelectionService {
|
||||
/// Apply a filter to tracks, falling back to original if filter produces empty result
|
||||
List<T> _applyFilterWithFallback<T>(List<T> tracks, List<T> Function(List<T>) filter, String filterDescription) {
|
||||
final filtered = filter(tracks);
|
||||
if (filtered.isNotEmpty) {
|
||||
return filtered;
|
||||
}
|
||||
appLogger.d('No tracks match $filterDescription, using all tracks');
|
||||
return tracks;
|
||||
return filtered.isNotEmpty ? filtered : tracks;
|
||||
}
|
||||
|
||||
/// Generic track matching for audio and subtitle tracks
|
||||
@@ -111,28 +125,11 @@ class TrackSelectionService {
|
||||
}
|
||||
|
||||
AudioTrack? findAudioTrackByProfile(List<AudioTrack> availableTracks, PlexUserProfile profile) {
|
||||
appLogger.d('Audio track selection using user profile');
|
||||
appLogger.d(
|
||||
'Profile settings - autoSelectAudio: ${profile.autoSelectAudio}, defaultAudioLanguage: ${profile.defaultAudioLanguage}, defaultAudioLanguages: ${profile.defaultAudioLanguages}',
|
||||
);
|
||||
|
||||
if (availableTracks.isEmpty || !profile.autoSelectAudio) {
|
||||
appLogger.d(
|
||||
'Cannot use profile: ${availableTracks.isEmpty ? "No tracks available" : "autoSelectAudio is false"}',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (availableTracks.isEmpty || !profile.autoSelectAudio) return null;
|
||||
|
||||
final preferredLanguages = _buildPreferredLanguages(profile, isAudio: true);
|
||||
if (preferredLanguages.isEmpty) return null;
|
||||
|
||||
if (preferredLanguages.isEmpty) {
|
||||
appLogger.d('Cannot use profile: No defaultAudioLanguage(s) specified');
|
||||
return null;
|
||||
}
|
||||
|
||||
appLogger.d('Preferred languages: ${preferredLanguages.join(", ")}');
|
||||
|
||||
// Try to find track matching any preferred language
|
||||
for (final preferredLanguage in preferredLanguages) {
|
||||
final match = _findTrackByPreferredLanguage<AudioTrack>(
|
||||
availableTracks,
|
||||
@@ -144,7 +141,6 @@ class TrackSelectionService {
|
||||
if (match != null) return match;
|
||||
}
|
||||
|
||||
appLogger.d('No audio track found matching profile languages or their variations');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -168,69 +164,35 @@ class TrackSelectionService {
|
||||
PlexUserProfile profile, {
|
||||
AudioTrack? selectedAudioTrack,
|
||||
}) {
|
||||
appLogger.d('Subtitle track selection using user profile');
|
||||
appLogger.d(
|
||||
'Profile settings - autoSelectSubtitle: ${profile.autoSelectSubtitle}, defaultSubtitleLanguage: ${profile.defaultSubtitleLanguage}, defaultSubtitleLanguages: ${profile.defaultSubtitleLanguages}, defaultSubtitleForced: ${profile.defaultSubtitleForced}, defaultSubtitleAccessibility: ${profile.defaultSubtitleAccessibility}',
|
||||
);
|
||||
|
||||
if (availableTracks.isEmpty) {
|
||||
appLogger.d('Cannot use profile: No subtitle tracks available');
|
||||
return null;
|
||||
}
|
||||
if (availableTracks.isEmpty) return null;
|
||||
|
||||
// Mode 0: Manually selected - return OFF
|
||||
if (profile.autoSelectSubtitle == 0) {
|
||||
appLogger.d('Profile specifies manual mode (autoSelectSubtitle=0) - Subtitles OFF');
|
||||
return SubtitleTrack.off;
|
||||
}
|
||||
if (profile.autoSelectSubtitle == 0) return SubtitleTrack.off;
|
||||
|
||||
// Mode 1: Shown with foreign audio
|
||||
if (profile.autoSelectSubtitle == 1) {
|
||||
appLogger.d('Profile specifies foreign audio mode (autoSelectSubtitle=1)');
|
||||
|
||||
// Check if audio language matches user's preferred subtitle language
|
||||
if (selectedAudioTrack != null && profile.defaultSubtitleLanguage != null) {
|
||||
final audioLang = selectedAudioTrack.language?.toLowerCase();
|
||||
final prefLang = profile.defaultSubtitleLanguage!.toLowerCase();
|
||||
final languageVariations = LanguageCodes.getVariations(prefLang);
|
||||
|
||||
appLogger.d('Checking if audio is foreign - audio: $audioLang, preferred subtitle lang: $prefLang');
|
||||
|
||||
// If audio matches preferred language, no subtitles needed
|
||||
if (audioLang != null && languageVariations.contains(audioLang)) {
|
||||
appLogger.d('Audio matches preferred language - Subtitles OFF');
|
||||
return SubtitleTrack.off;
|
||||
}
|
||||
appLogger.d('Foreign audio detected - enabling subtitles');
|
||||
}
|
||||
// Foreign audio detected or cannot determine, enable subtitles
|
||||
}
|
||||
|
||||
// Mode 2: Always enabled (or continuing from mode 1 with foreign audio)
|
||||
appLogger.d('Selecting subtitle track based on preferences');
|
||||
|
||||
final preferredLanguages = _buildPreferredLanguages(profile, isAudio: false);
|
||||
|
||||
if (preferredLanguages.isEmpty) {
|
||||
appLogger.d('Cannot use profile: No defaultSubtitleLanguage(s) specified');
|
||||
return null;
|
||||
}
|
||||
|
||||
appLogger.d('Preferred languages: ${preferredLanguages.join(", ")}');
|
||||
if (preferredLanguages.isEmpty) return null;
|
||||
|
||||
// Apply filtering with fallback to original tracks if filter produces empty result
|
||||
var candidateTracks = availableTracks;
|
||||
|
||||
// Filter by SDH (defaultSubtitleAccessibility: 0-3)
|
||||
candidateTracks = filterSubtitlesBySDH(candidateTracks, profile.defaultSubtitleAccessibility);
|
||||
|
||||
// Filter by forced subtitle preference (defaultSubtitleForced: 0-3)
|
||||
candidateTracks = filterSubtitlesByForced(candidateTracks, profile.defaultSubtitleForced);
|
||||
|
||||
// If no candidates after filtering, relax filters
|
||||
candidateTracks = _applyFilterWithFallback(availableTracks, (_) => candidateTracks, 'strict filters');
|
||||
|
||||
// Try to find track matching any preferred language
|
||||
for (final preferredLanguage in preferredLanguages) {
|
||||
final match = _findTrackByPreferredLanguage<SubtitleTrack>(
|
||||
candidateTracks,
|
||||
@@ -242,7 +204,6 @@ class TrackSelectionService {
|
||||
if (match != null) return match;
|
||||
}
|
||||
|
||||
appLogger.d('No subtitle track found matching profile languages or their variations');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -255,27 +216,13 @@ class TrackSelectionService {
|
||||
/// - 3: Only show non-SDH subtitles
|
||||
List<SubtitleTrack> filterSubtitlesBySDH(List<SubtitleTrack> tracks, int preference) {
|
||||
if (preference == 0 || preference == 1) {
|
||||
// Prefer but don't require
|
||||
final preferSDH = preference == 1;
|
||||
final preferred = tracks.where((t) => isSDH(t) == preferSDH).toList();
|
||||
if (preferred.isNotEmpty) {
|
||||
appLogger.d(
|
||||
'Applying SDH preference: ${preferSDH ? "prefer SDH" : "prefer non-SDH"} (${preferred.length} tracks)',
|
||||
);
|
||||
return preferred;
|
||||
}
|
||||
appLogger.d('No tracks match SDH preference, using all tracks');
|
||||
return tracks;
|
||||
return preferred.isNotEmpty ? preferred : tracks;
|
||||
} else if (preference == 2) {
|
||||
// Only SDH
|
||||
final filtered = tracks.where((t) => isSDH(t)).toList();
|
||||
appLogger.d('Filtering to SDH only (${filtered.length} tracks)');
|
||||
return filtered;
|
||||
return tracks.where((t) => isSDH(t)).toList();
|
||||
} else if (preference == 3) {
|
||||
// Only non-SDH
|
||||
final filtered = tracks.where((t) => !isSDH(t)).toList();
|
||||
appLogger.d('Filtering to non-SDH only (${filtered.length} tracks)');
|
||||
return filtered;
|
||||
return tracks.where((t) => !isSDH(t)).toList();
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
@@ -289,27 +236,13 @@ class TrackSelectionService {
|
||||
/// - 3: Only show non-forced subtitles
|
||||
List<SubtitleTrack> filterSubtitlesByForced(List<SubtitleTrack> tracks, int preference) {
|
||||
if (preference == 0 || preference == 1) {
|
||||
// Prefer but don't require
|
||||
final preferForced = preference == 1;
|
||||
final preferred = tracks.where((t) => isForced(t) == preferForced).toList();
|
||||
if (preferred.isNotEmpty) {
|
||||
appLogger.d(
|
||||
'Applying forced preference: ${preferForced ? "prefer forced" : "prefer non-forced"} (${preferred.length} tracks)',
|
||||
);
|
||||
return preferred;
|
||||
}
|
||||
appLogger.d('No tracks match forced preference, using all tracks');
|
||||
return tracks;
|
||||
return preferred.isNotEmpty ? preferred : tracks;
|
||||
} else if (preference == 2) {
|
||||
// Only forced
|
||||
final filtered = tracks.where((t) => isForced(t)).toList();
|
||||
appLogger.d('Filtering to forced only (${filtered.length} tracks)');
|
||||
return filtered;
|
||||
return tracks.where((t) => isForced(t)).toList();
|
||||
} else if (preference == 3) {
|
||||
// Only non-forced
|
||||
final filtered = tracks.where((t) => !isForced(t)).toList();
|
||||
appLogger.d('Filtering to non-forced only (${filtered.length} tracks)');
|
||||
return filtered;
|
||||
return tracks.where((t) => !isForced(t)).toList();
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
@@ -346,9 +279,6 @@ class TrackSelectionService {
|
||||
for (var track in tracks) {
|
||||
final trackLang = getLanguage(track)?.toLowerCase();
|
||||
if (trackLang != null && languageVariations.any((lang) => trackLang.startsWith(lang))) {
|
||||
appLogger.d(
|
||||
'Found $trackType matching profile language "$preferredLanguage" (matched: "$trackLang"): ${getTrackDescription(track)}',
|
||||
);
|
||||
return track;
|
||||
}
|
||||
}
|
||||
@@ -383,178 +313,133 @@ class TrackSelectionService {
|
||||
return variations.contains(trackBase);
|
||||
}
|
||||
|
||||
/// Log available tracks for debugging
|
||||
void logAvailableTracks(List<AudioTrack> audioTracks, List<SubtitleTrack> subtitleTracks) {
|
||||
appLogger.d('Available audio tracks: ${audioTracks.length}');
|
||||
for (var track in audioTracks) {
|
||||
appLogger.d(
|
||||
' - ${track.title ?? "Track ${track.id}"} (${track.language ?? "unknown"}) ${track.isDefault == true ? "[DEFAULT]" : ""}',
|
||||
);
|
||||
}
|
||||
appLogger.d('Available subtitle tracks: ${subtitleTracks.length}');
|
||||
for (var track in subtitleTracks) {
|
||||
appLogger.d(
|
||||
' - ${track.title ?? "Track ${track.id}"} (${track.language ?? "unknown"}) ${track.isDefault == true ? "[DEFAULT]" : ""}',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the best audio track based on priority:
|
||||
/// Priority 1: Preferred track from navigation
|
||||
/// Priority 2: Per-media language preference
|
||||
/// Priority 3: User profile preferences
|
||||
/// Priority 4: Default or first track
|
||||
AudioTrack? selectAudioTrack(List<AudioTrack> availableTracks, AudioTrack? preferredAudioTrack) {
|
||||
/// Priority 2: Plex-selected track from media info
|
||||
/// Priority 3: Per-media language preference
|
||||
/// Priority 4: User profile preferences
|
||||
/// Priority 5: Default or first track
|
||||
TrackSelectionResult<AudioTrack>? selectAudioTrack(
|
||||
List<AudioTrack> availableTracks,
|
||||
AudioTrack? preferredAudioTrack,
|
||||
) {
|
||||
if (availableTracks.isEmpty) return null;
|
||||
|
||||
AudioTrack? trackToSelect;
|
||||
|
||||
// Priority 1: Try to match preferred track from navigation
|
||||
if (preferredAudioTrack != null) {
|
||||
appLogger.d('Priority 1: Checking preferred track from navigation');
|
||||
appLogger.d(
|
||||
' Preferred: ${preferredAudioTrack.title ?? "Track ${preferredAudioTrack.id}"} (${preferredAudioTrack.language ?? "unknown"})',
|
||||
);
|
||||
trackToSelect = findBestAudioMatch(availableTracks, preferredAudioTrack);
|
||||
if (trackToSelect != null) {
|
||||
appLogger.d(' Matched preferred track');
|
||||
return trackToSelect;
|
||||
return TrackSelectionResult(trackToSelect, TrackSelectionPriority.navigation);
|
||||
}
|
||||
appLogger.d(' No match found for preferred track');
|
||||
} else {
|
||||
appLogger.d('Priority 1: No preferred track from navigation');
|
||||
}
|
||||
|
||||
// Priority 2: If no preferred track matched, try per-media language preference
|
||||
if (metadata.audioLanguage != null) {
|
||||
appLogger.d('Priority 2: Checking per-media audio language preference');
|
||||
appLogger.d(' Per-media audio language: ${metadata.audioLanguage}');
|
||||
// Priority 2: Check Plex-selected track from media info
|
||||
if (plexMediaInfo != null) {
|
||||
final plexAudioTracks = plexMediaInfo!.audioTracks;
|
||||
final plexSelectedIndex = plexAudioTracks.indexWhere((t) => t.selected);
|
||||
if (plexSelectedIndex >= 0 && plexSelectedIndex < availableTracks.length) {
|
||||
return TrackSelectionResult(availableTracks[plexSelectedIndex], TrackSelectionPriority.plexSelected);
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 3: Try per-media language preference
|
||||
if (metadata.audioLanguage != null) {
|
||||
final matchedTrack = availableTracks.firstWhere(
|
||||
(track) => languageMatches(track.language, metadata.audioLanguage),
|
||||
orElse: () => availableTracks.first,
|
||||
);
|
||||
|
||||
if (languageMatches(matchedTrack.language, metadata.audioLanguage)) {
|
||||
appLogger.d(' Matched per-media audio language preference');
|
||||
return matchedTrack;
|
||||
return TrackSelectionResult(matchedTrack, TrackSelectionPriority.perMedia);
|
||||
}
|
||||
appLogger.d(' No match found for per-media audio language');
|
||||
} else {
|
||||
appLogger.d('Priority 2: No per-media audio language preference');
|
||||
}
|
||||
|
||||
// Priority 3: If no preferred track matched, try user profile preferences
|
||||
// Priority 4: Try user profile preferences
|
||||
if (profileSettings != null) {
|
||||
appLogger.d('Priority 3: Checking user profile preferences');
|
||||
trackToSelect = findAudioTrackByProfile(availableTracks, profileSettings!);
|
||||
if (trackToSelect != null) {
|
||||
return trackToSelect;
|
||||
return TrackSelectionResult(trackToSelect, TrackSelectionPriority.profile);
|
||||
}
|
||||
} else {
|
||||
appLogger.d('Priority 3: No user profile available');
|
||||
}
|
||||
|
||||
// Priority 4: If no match, use default or first track
|
||||
appLogger.d('Priority 4: Using default or first available track');
|
||||
// Priority 5: Use default or first track
|
||||
trackToSelect = availableTracks.firstWhere((t) => t.isDefault == true, orElse: () => availableTracks.first);
|
||||
final isDefault = trackToSelect.isDefault == true;
|
||||
appLogger.d(
|
||||
' Selected ${isDefault ? "default" : "first"} track: ${trackToSelect.title ?? "Track ${trackToSelect.id}"} (${trackToSelect.language ?? "unknown"})',
|
||||
);
|
||||
|
||||
return trackToSelect;
|
||||
return TrackSelectionResult(trackToSelect, TrackSelectionPriority.defaultTrack);
|
||||
}
|
||||
|
||||
/// Select the best subtitle track based on priority:
|
||||
/// Priority 1: Preferred track from navigation
|
||||
/// Priority 2: Per-media language preference
|
||||
/// Priority 3: User profile preferences
|
||||
/// Priority 4: Default track
|
||||
/// Priority 5: Off
|
||||
SubtitleTrack selectSubtitleTrack(
|
||||
/// Priority 2: Plex-selected track from media info
|
||||
/// Priority 3: Per-media language preference
|
||||
/// Priority 4: User profile preferences
|
||||
/// Priority 5: Default track
|
||||
/// Priority 6: Off
|
||||
TrackSelectionResult<SubtitleTrack> selectSubtitleTrack(
|
||||
List<SubtitleTrack> availableTracks,
|
||||
SubtitleTrack? preferredSubtitleTrack,
|
||||
AudioTrack? selectedAudioTrack,
|
||||
) {
|
||||
SubtitleTrack? subtitleToSelect;
|
||||
|
||||
// Priority 1: Try preferred track from navigation (always wins)
|
||||
// Priority 1: Try preferred track from navigation
|
||||
if (preferredSubtitleTrack != null) {
|
||||
appLogger.d('Priority 1: Checking preferred track from navigation');
|
||||
if (preferredSubtitleTrack.id == 'no') {
|
||||
appLogger.d(' Preferred: OFF');
|
||||
return SubtitleTrack.off;
|
||||
return TrackSelectionResult(SubtitleTrack.off, TrackSelectionPriority.navigation);
|
||||
} else if (availableTracks.isNotEmpty) {
|
||||
appLogger.d(
|
||||
' Preferred: ${preferredSubtitleTrack.title ?? "Track ${preferredSubtitleTrack.id}"} (${preferredSubtitleTrack.language ?? "unknown"})',
|
||||
);
|
||||
subtitleToSelect = findBestSubtitleMatch(availableTracks, preferredSubtitleTrack);
|
||||
if (subtitleToSelect != null) {
|
||||
appLogger.d(' Matched preferred track');
|
||||
return subtitleToSelect;
|
||||
return TrackSelectionResult(subtitleToSelect, TrackSelectionPriority.navigation);
|
||||
}
|
||||
appLogger.d(' No match found for preferred track');
|
||||
}
|
||||
} else {
|
||||
appLogger.d('Priority 1: No preferred track from navigation');
|
||||
}
|
||||
|
||||
// Priority 2: If no preferred match, try per-media language preference
|
||||
if (metadata.subtitleLanguage != null) {
|
||||
appLogger.d('Priority 2: Checking per-media subtitle language preference');
|
||||
appLogger.d(' Per-media subtitle language: ${metadata.subtitleLanguage}');
|
||||
// Priority 2: Check Plex-selected track from media info
|
||||
if (plexMediaInfo != null && availableTracks.isNotEmpty) {
|
||||
final plexSubtitleTracks = plexMediaInfo!.subtitleTracks;
|
||||
final plexSelectedIndex = plexSubtitleTracks.indexWhere((t) => t.selected);
|
||||
if (plexSelectedIndex >= 0 && plexSelectedIndex < availableTracks.length) {
|
||||
return TrackSelectionResult(availableTracks[plexSelectedIndex], TrackSelectionPriority.plexSelected);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if subtitle should be disabled
|
||||
// Priority 3: Try per-media language preference
|
||||
if (metadata.subtitleLanguage != null) {
|
||||
if (metadata.subtitleLanguage == 'none' || metadata.subtitleLanguage!.isEmpty) {
|
||||
appLogger.d(' Per-media preference: Subtitles OFF');
|
||||
return SubtitleTrack.off;
|
||||
return TrackSelectionResult(SubtitleTrack.off, TrackSelectionPriority.perMedia);
|
||||
} else if (availableTracks.isNotEmpty) {
|
||||
final matchedTrack = availableTracks.firstWhere(
|
||||
(track) => languageMatches(track.language, metadata.subtitleLanguage),
|
||||
orElse: () => availableTracks.first,
|
||||
);
|
||||
if (languageMatches(matchedTrack.language, metadata.subtitleLanguage)) {
|
||||
appLogger.d(' Matched per-media subtitle language preference');
|
||||
return matchedTrack;
|
||||
return TrackSelectionResult(matchedTrack, TrackSelectionPriority.perMedia);
|
||||
}
|
||||
appLogger.d(' No match found for per-media subtitle language');
|
||||
}
|
||||
} else {
|
||||
appLogger.d('Priority 2: No per-media subtitle language preference');
|
||||
}
|
||||
|
||||
// Priority 3: If no preferred match, apply user profile preferences
|
||||
// Priority 4: Apply user profile preferences
|
||||
if (profileSettings != null && availableTracks.isNotEmpty) {
|
||||
appLogger.d('Priority 3: Checking user profile preferences');
|
||||
subtitleToSelect = findSubtitleTrackByProfile(
|
||||
availableTracks,
|
||||
profileSettings!,
|
||||
selectedAudioTrack: selectedAudioTrack,
|
||||
);
|
||||
if (subtitleToSelect != null) {
|
||||
return subtitleToSelect;
|
||||
return TrackSelectionResult(subtitleToSelect, TrackSelectionPriority.profile);
|
||||
}
|
||||
} else if (availableTracks.isNotEmpty) {
|
||||
appLogger.d('Priority 3: No user profile available');
|
||||
}
|
||||
|
||||
// Priority 4: If no profile match, check for default subtitle
|
||||
// Priority 5: Check for default subtitle
|
||||
if (availableTracks.isNotEmpty) {
|
||||
appLogger.d('Priority 4: Checking for default subtitle track');
|
||||
final defaultTrack = availableTracks.firstWhere((t) => t.isDefault == true, orElse: () => availableTracks.first);
|
||||
if (defaultTrack.isDefault == true) {
|
||||
appLogger.d(
|
||||
' Found default track: ${defaultTrack.title ?? "Track ${defaultTrack.id}"} (${defaultTrack.language ?? "unknown"})',
|
||||
);
|
||||
return defaultTrack;
|
||||
return TrackSelectionResult(defaultTrack, TrackSelectionPriority.defaultTrack);
|
||||
}
|
||||
appLogger.d(' No default subtitle track found');
|
||||
}
|
||||
|
||||
// Priority 5: If still no subtitle selected, turn off
|
||||
appLogger.d('Priority 5: No subtitle selected - Subtitles OFF');
|
||||
return SubtitleTrack.off;
|
||||
// Priority 6: Turn off subtitles
|
||||
return TrackSelectionResult(SubtitleTrack.off, TrackSelectionPriority.off);
|
||||
}
|
||||
|
||||
/// Select and apply audio and subtitle tracks based on preferences
|
||||
@@ -572,42 +457,43 @@ class TrackSelectionService {
|
||||
attempts++;
|
||||
}
|
||||
|
||||
appLogger.d('Starting track selection process');
|
||||
|
||||
// Get real tracks (excluding auto and no)
|
||||
final realAudioTracks = player.state.tracks.audio.where((t) => t.id != 'auto' && t.id != 'no').toList();
|
||||
final realSubtitleTracks = player.state.tracks.subtitle.where((t) => t.id != 'auto' && t.id != 'no').toList();
|
||||
|
||||
// Log available tracks
|
||||
logAvailableTracks(realAudioTracks, realSubtitleTracks);
|
||||
|
||||
// Select and apply audio track
|
||||
appLogger.d('Audio track selection');
|
||||
final selectedAudioTrack = selectAudioTrack(realAudioTracks, preferredAudioTrack);
|
||||
if (selectedAudioTrack != null) {
|
||||
appLogger.i(
|
||||
'Final audio selection: ${selectedAudioTrack.title ?? "Track ${selectedAudioTrack.id}"} (${selectedAudioTrack.language ?? "unknown"})',
|
||||
final audioResult = selectAudioTrack(realAudioTracks, preferredAudioTrack);
|
||||
AudioTrack? selectedAudioTrack;
|
||||
if (audioResult != null) {
|
||||
selectedAudioTrack = audioResult.track;
|
||||
appLogger.d(
|
||||
'Audio: ${selectedAudioTrack.title ?? selectedAudioTrack.language ?? "Track ${selectedAudioTrack.id}"} [${audioResult.priority.name}]',
|
||||
);
|
||||
player.selectAudioTrack(selectedAudioTrack);
|
||||
} else {
|
||||
appLogger.d('No audio tracks available');
|
||||
|
||||
// Save to Plex if this was user's navigation preference (Priority 1)
|
||||
if (audioResult.priority == TrackSelectionPriority.navigation && onAudioTrackChanged != null) {
|
||||
onAudioTrackChanged(selectedAudioTrack);
|
||||
}
|
||||
}
|
||||
|
||||
// Select and apply subtitle track
|
||||
appLogger.d('Subtitle track selection');
|
||||
final selectedSubtitleTrack = selectSubtitleTrack(realSubtitleTracks, preferredSubtitleTrack, selectedAudioTrack);
|
||||
final finalSubtitle = selectedSubtitleTrack.id == 'no'
|
||||
final subtitleResult = selectSubtitleTrack(realSubtitleTracks, preferredSubtitleTrack, selectedAudioTrack);
|
||||
final selectedSubtitleTrack = subtitleResult.track;
|
||||
final subtitleName = selectedSubtitleTrack.id == 'no'
|
||||
? 'OFF'
|
||||
: '${selectedSubtitleTrack.title ?? "Track ${selectedSubtitleTrack.id}"} (${selectedSubtitleTrack.language ?? "unknown"})';
|
||||
appLogger.i('Final subtitle selection: $finalSubtitle');
|
||||
: (selectedSubtitleTrack.title ?? selectedSubtitleTrack.language ?? 'Track ${selectedSubtitleTrack.id}');
|
||||
appLogger.d('Subtitle: $subtitleName [${subtitleResult.priority.name}]');
|
||||
player.selectSubtitleTrack(selectedSubtitleTrack);
|
||||
|
||||
// Save to Plex if this was user's navigation preference (Priority 1)
|
||||
if (subtitleResult.priority == TrackSelectionPriority.navigation && onSubtitleTrackChanged != null) {
|
||||
onSubtitleTrackChanged(selectedSubtitleTrack);
|
||||
}
|
||||
|
||||
// Set playback rate if preferred rate was provided
|
||||
if (preferredPlaybackRate != null) {
|
||||
appLogger.d('Setting preferred playback rate: ${preferredPlaybackRate}x');
|
||||
player.setRate(preferredPlaybackRate);
|
||||
}
|
||||
|
||||
appLogger.d('Track selection complete');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../mpv/mpv.dart';
|
||||
import '../services/pip_service.dart';
|
||||
|
||||
/// Manages video Picture-in-Picture mode
|
||||
class VideoPIPManager {
|
||||
final Player player;
|
||||
|
||||
VideoPIPManager({required this.player});
|
||||
|
||||
Size? _playerSize;
|
||||
Size? get playerSize => _playerSize;
|
||||
|
||||
/// Access PiP state from the service
|
||||
ValueNotifier<bool> get isPipActive => PipService().isPipActive;
|
||||
|
||||
/// Toggle native PiP
|
||||
Future<void> togglePIP() async {
|
||||
final supported = await PipService.isSupported();
|
||||
if (!supported) return;
|
||||
|
||||
// Try to get actual video dimensions from MPV
|
||||
int? width;
|
||||
int? height;
|
||||
|
||||
try {
|
||||
final dwidth = await player.getProperty('dwidth');
|
||||
final dheight = await player.getProperty('dheight');
|
||||
if (dwidth != null && dheight != null) {
|
||||
width = int.tryParse(dwidth);
|
||||
height = int.tryParse(dheight);
|
||||
}
|
||||
} catch (_) {
|
||||
// Fall through to use viewport size
|
||||
}
|
||||
|
||||
// Fall back to viewport size if video dimensions unavailable
|
||||
width ??= _playerSize?.width.toInt();
|
||||
height ??= _playerSize?.height.toInt();
|
||||
|
||||
await PipService.enter(width: width, height: height);
|
||||
}
|
||||
}
|
||||
@@ -59,9 +59,16 @@ class GridLayoutConstants {
|
||||
static const double normalTablet = 200;
|
||||
static const double normalMobile = 170;
|
||||
|
||||
/// Default aspect ratio for media cards (poster)
|
||||
/// Default aspect ratio for media card grid cells (poster + text)
|
||||
static const double posterAspectRatio = 2 / 3.3;
|
||||
|
||||
/// Aspect ratio for episode thumbnail image (16:9)
|
||||
static const double episodeThumbnailAspectRatio = 16 / 9;
|
||||
|
||||
/// Aspect ratio for episode thumbnail grid cells (16:9 image + text area)
|
||||
/// This is wider than posterAspectRatio but accounts for ~60px text below
|
||||
static const double episodeGridCellAspectRatio = 1.4;
|
||||
|
||||
/// Grid spacing (edge-to-edge cards)
|
||||
static const double crossAxisSpacing = 0;
|
||||
static const double mainAxisSpacing = 0;
|
||||
|
||||
@@ -22,10 +22,12 @@ enum MediaNavigationResult {
|
||||
/// Navigates to the appropriate screen based on the item type.
|
||||
///
|
||||
/// For episodes, starts playback directly via video player.
|
||||
/// For movies, starts playback directly if [playDirectly] is true, otherwise
|
||||
/// navigates to media detail screen.
|
||||
/// For seasons, navigates to season detail screen.
|
||||
/// For playlists, navigates to playlist detail screen.
|
||||
/// For collections, navigates to collection detail screen.
|
||||
/// For other types (shows, movies), navigates to media detail screen.
|
||||
/// For other types (shows), navigates to media detail screen.
|
||||
/// For music types (artist, album, track), returns [MediaNavigationResult.unsupported].
|
||||
///
|
||||
/// The [onRefresh] callback is invoked with the item's ratingKey after
|
||||
@@ -33,6 +35,8 @@ enum MediaNavigationResult {
|
||||
///
|
||||
/// Set [isOffline] to true for downloaded content without server access.
|
||||
///
|
||||
/// Set [playDirectly] to true to play movies immediately (e.g., from continue watching).
|
||||
///
|
||||
/// Returns a [MediaNavigationResult] indicating what action was taken:
|
||||
/// - [MediaNavigationResult.navigated]: Navigation completed, item refresh handled
|
||||
/// - [MediaNavigationResult.listRefreshNeeded]: Caller should refresh entire list
|
||||
@@ -42,6 +46,7 @@ Future<MediaNavigationResult> navigateToMediaItem(
|
||||
dynamic item, {
|
||||
void Function(String)? onRefresh,
|
||||
bool isOffline = false,
|
||||
bool playDirectly = false,
|
||||
}) async {
|
||||
// Handle playlists
|
||||
if (item is PlexPlaylist) {
|
||||
@@ -77,11 +82,24 @@ Future<MediaNavigationResult> navigateToMediaItem(
|
||||
}
|
||||
return MediaNavigationResult.navigated;
|
||||
|
||||
case PlexMediaType.movie:
|
||||
if (playDirectly) {
|
||||
// For movies in continue watching, start playback directly
|
||||
final result = await navigateToVideoPlayer(context, metadata: metadata, isOffline: isOffline);
|
||||
if (result == true) {
|
||||
onRefresh?.call(metadata.ratingKey);
|
||||
}
|
||||
return MediaNavigationResult.navigated;
|
||||
}
|
||||
// Fall through to default case for detail screen
|
||||
continue defaultCase;
|
||||
|
||||
case PlexMediaType.season:
|
||||
await Navigator.push(context, MaterialPageRoute(builder: (context) => SeasonDetailScreen(season: metadata)));
|
||||
onRefresh?.call(metadata.ratingKey);
|
||||
return MediaNavigationResult.navigated;
|
||||
|
||||
defaultCase:
|
||||
default:
|
||||
// For all other types (shows, movies), show detail screen
|
||||
final result = await Navigator.push<bool>(
|
||||
|
||||
@@ -139,9 +139,9 @@ class PlexImageHelper {
|
||||
return '';
|
||||
}
|
||||
|
||||
// For art/backgrounds and clear logos, prefer the original image to avoid
|
||||
// any aspect ratio changes from Plex photo transcoding.
|
||||
if (imageType == ImageType.art || imageType == ImageType.logo) {
|
||||
// For art/backgrounds, clear logos, and episode thumbnails, prefer the
|
||||
// original image to avoid any aspect ratio changes from Plex photo transcoding.
|
||||
if (imageType == ImageType.art || imageType == ImageType.logo || imageType == ImageType.thumb) {
|
||||
return client.getThumbnailUrl(basePath);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import 'dart:async';
|
||||
import '../models/plex_metadata.dart';
|
||||
import 'app_logger.dart';
|
||||
|
||||
/// Types of watch state changes
|
||||
enum WatchStateChangeType { watched, unwatched, progressUpdate }
|
||||
|
||||
/// Event representing a watch state change with parent chain for hierarchical invalidation
|
||||
class WatchStateEvent {
|
||||
/// The item that changed
|
||||
final String ratingKey;
|
||||
|
||||
/// Composite key: serverId:ratingKey
|
||||
final String globalKey;
|
||||
|
||||
/// Server this item belongs to
|
||||
final String serverId;
|
||||
|
||||
/// Type of change
|
||||
final WatchStateChangeType changeType;
|
||||
|
||||
/// Parent chain for hierarchical invalidation
|
||||
/// For an episode: [seasonRatingKey, showRatingKey]
|
||||
/// For a season: [showRatingKey]
|
||||
/// For a movie: []
|
||||
final List<String> parentChain;
|
||||
|
||||
/// Media type that changed
|
||||
final String mediaType;
|
||||
|
||||
/// New progress value (for progressUpdate)
|
||||
final int? viewOffset;
|
||||
|
||||
/// Whether item is now considered watched (>90% progress or marked)
|
||||
final bool? isNowWatched;
|
||||
|
||||
WatchStateEvent({
|
||||
required this.ratingKey,
|
||||
required this.serverId,
|
||||
required this.changeType,
|
||||
required this.parentChain,
|
||||
required this.mediaType,
|
||||
this.viewOffset,
|
||||
this.isNowWatched,
|
||||
}) : globalKey = '$serverId:$ratingKey';
|
||||
|
||||
/// Check if this event affects a specific item by ratingKey
|
||||
bool affectsItem(String ratingKey) => this.ratingKey == ratingKey || parentChain.contains(ratingKey);
|
||||
|
||||
/// Check if this event affects a specific globalKey
|
||||
bool affectsGlobalKey(String globalKey) =>
|
||||
this.globalKey == globalKey || parentChain.any((pk) => '$serverId:$pk' == globalKey);
|
||||
|
||||
/// Check if this event affects any item in a collection
|
||||
bool affectsAnyOf(Iterable<String> ratingKeys) => ratingKeys.any(affectsItem);
|
||||
|
||||
@override
|
||||
String toString() => 'WatchStateEvent($changeType, $globalKey, parents: $parentChain)';
|
||||
}
|
||||
|
||||
/// Notifier for watch state changes across the app.
|
||||
///
|
||||
/// Singleton pattern following [LibraryRefreshNotifier]. Screens subscribe
|
||||
/// to receive events when items are marked watched/unwatched or progress updates.
|
||||
class WatchStateNotifier {
|
||||
static final WatchStateNotifier _instance = WatchStateNotifier._internal();
|
||||
|
||||
factory WatchStateNotifier() => _instance;
|
||||
|
||||
WatchStateNotifier._internal();
|
||||
|
||||
StreamController<WatchStateEvent>? _controller;
|
||||
|
||||
StreamController<WatchStateEvent> get _ensureController {
|
||||
if (_controller == null || _controller!.isClosed) {
|
||||
_controller = StreamController<WatchStateEvent>.broadcast();
|
||||
}
|
||||
return _controller!;
|
||||
}
|
||||
|
||||
/// Stream of all watch state events
|
||||
Stream<WatchStateEvent> get stream => _ensureController.stream;
|
||||
|
||||
/// Filter for events affecting a specific server
|
||||
Stream<WatchStateEvent> forServer(String serverId) => stream.where((e) => e.serverId == serverId);
|
||||
|
||||
/// Filter for events affecting a specific item or its children
|
||||
Stream<WatchStateEvent> forItem(String ratingKey) => stream.where((e) => e.affectsItem(ratingKey));
|
||||
|
||||
/// Emit a watch state event
|
||||
void notify(WatchStateEvent event) {
|
||||
appLogger.d('WatchStateNotifier: $event');
|
||||
_ensureController.add(event);
|
||||
}
|
||||
|
||||
/// Helper to emit a watched/unwatched event from metadata
|
||||
void notifyWatched({required PlexMetadata metadata, bool isNowWatched = true}) {
|
||||
notify(
|
||||
WatchStateEvent(
|
||||
ratingKey: metadata.ratingKey,
|
||||
serverId: metadata.serverId ?? '',
|
||||
changeType: isNowWatched ? WatchStateChangeType.watched : WatchStateChangeType.unwatched,
|
||||
parentChain: _buildParentChain(metadata),
|
||||
mediaType: metadata.type,
|
||||
isNowWatched: isNowWatched,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Helper to emit a progress update event
|
||||
void notifyProgress({required PlexMetadata metadata, required int viewOffset, required int duration}) {
|
||||
const threshold = 0.90;
|
||||
final isNowWatched = duration > 0 && (viewOffset / duration) >= threshold;
|
||||
|
||||
notify(
|
||||
WatchStateEvent(
|
||||
ratingKey: metadata.ratingKey,
|
||||
serverId: metadata.serverId ?? '',
|
||||
changeType: WatchStateChangeType.progressUpdate,
|
||||
parentChain: _buildParentChain(metadata),
|
||||
mediaType: metadata.type,
|
||||
viewOffset: viewOffset,
|
||||
isNowWatched: isNowWatched,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Build parent chain from metadata's parent keys
|
||||
List<String> _buildParentChain(PlexMetadata metadata) {
|
||||
final chain = <String>[];
|
||||
if (metadata.parentRatingKey != null) {
|
||||
chain.add(metadata.parentRatingKey!);
|
||||
}
|
||||
if (metadata.grandparentRatingKey != null) {
|
||||
chain.add(metadata.grandparentRatingKey!);
|
||||
}
|
||||
return chain;
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_controller?.close();
|
||||
_controller = null;
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,14 @@ class WatchTogetherProvider with ChangeNotifier {
|
||||
_displayName = name;
|
||||
}
|
||||
|
||||
/// Wire up sync manager's state change callback to update provider state
|
||||
void _wireSyncStateChanges() {
|
||||
_syncManager!.onSyncStateChanged = (isSyncing) {
|
||||
_isSyncing = isSyncing;
|
||||
notifyListeners();
|
||||
};
|
||||
}
|
||||
|
||||
/// Create a new watch together session as host
|
||||
Future<String> createSession({
|
||||
required ControlMode controlMode,
|
||||
@@ -113,10 +121,7 @@ class WatchTogetherProvider with ChangeNotifier {
|
||||
displayName: _displayName,
|
||||
);
|
||||
|
||||
_syncManager!.onSyncStateChanged = (isSyncing) {
|
||||
_isSyncing = isSyncing;
|
||||
notifyListeners();
|
||||
};
|
||||
_wireSyncStateChanges();
|
||||
|
||||
notifyListeners();
|
||||
appLogger.d('WatchTogether: Session created: $sessionId');
|
||||
@@ -164,10 +169,7 @@ class WatchTogetherProvider with ChangeNotifier {
|
||||
notifyListeners();
|
||||
};
|
||||
|
||||
_syncManager!.onSyncStateChanged = (isSyncing) {
|
||||
_isSyncing = isSyncing;
|
||||
notifyListeners();
|
||||
};
|
||||
_wireSyncStateChanges();
|
||||
|
||||
// Add self to participants
|
||||
_participants.add(Participant(peerId: _peerService!.myPeerId!, displayName: _displayName, isHost: false));
|
||||
|
||||
@@ -83,6 +83,31 @@ class WatchTogetherPeerService {
|
||||
return const Uuid().v4().substring(0, 8).toUpperCase();
|
||||
}
|
||||
|
||||
/// Attach common peer event listeners for disconnected/close/error events
|
||||
void _attachCommonPeerListeners({
|
||||
required Completer completer,
|
||||
required PeerErrorType errorType,
|
||||
required String errorMessage,
|
||||
}) {
|
||||
_peer!.on('disconnected').listen((_) {
|
||||
appLogger.w('WatchTogether: Peer disconnected from server');
|
||||
_handleDisconnectedFromServer();
|
||||
});
|
||||
|
||||
_peer!.on('close').listen((_) {
|
||||
appLogger.d('WatchTogether: Peer closed');
|
||||
_connectionStateController.add(false);
|
||||
});
|
||||
|
||||
_peer!.on('error').listen((error) {
|
||||
appLogger.e('WatchTogether: Peer error', error: error);
|
||||
_errorController.add(PeerError(type: errorType, message: '$errorMessage: $error', originalError: error));
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Create a new session as host
|
||||
///
|
||||
/// Returns the session ID that others can use to join
|
||||
@@ -115,25 +140,11 @@ class WatchTogetherPeerService {
|
||||
_handleNewConnection(dataConn);
|
||||
});
|
||||
|
||||
_peer!.on('error').listen((error) {
|
||||
appLogger.e('WatchTogether: Peer error', error: error);
|
||||
_errorController.add(
|
||||
PeerError(type: PeerErrorType.serverError, message: error.toString(), originalError: error),
|
||||
);
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(error);
|
||||
}
|
||||
});
|
||||
|
||||
_peer!.on('disconnected').listen((_) {
|
||||
appLogger.w('WatchTogether: Peer disconnected from server');
|
||||
_handleDisconnectedFromServer();
|
||||
});
|
||||
|
||||
_peer!.on('close').listen((_) {
|
||||
appLogger.d('WatchTogether: Peer closed');
|
||||
_connectionStateController.add(false);
|
||||
});
|
||||
_attachCommonPeerListeners(
|
||||
completer: completer,
|
||||
errorType: PeerErrorType.serverError,
|
||||
errorMessage: 'Server error',
|
||||
);
|
||||
} catch (e) {
|
||||
appLogger.e('WatchTogether: Failed to create peer', error: e);
|
||||
if (!completer.isCompleted) {
|
||||
@@ -178,29 +189,11 @@ class WatchTogetherPeerService {
|
||||
_handleNewConnection(conn, isOutgoing: true, completer: completer);
|
||||
});
|
||||
|
||||
_peer!.on('error').listen((error) {
|
||||
appLogger.e('WatchTogether: Peer error', error: error);
|
||||
_errorController.add(
|
||||
PeerError(
|
||||
type: PeerErrorType.connectionFailed,
|
||||
message: 'Failed to connect to session: $error',
|
||||
originalError: error,
|
||||
),
|
||||
);
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(error);
|
||||
}
|
||||
});
|
||||
|
||||
_peer!.on('disconnected').listen((_) {
|
||||
appLogger.w('WatchTogether: Peer disconnected from server');
|
||||
_handleDisconnectedFromServer();
|
||||
});
|
||||
|
||||
_peer!.on('close').listen((_) {
|
||||
appLogger.d('WatchTogether: Peer closed');
|
||||
_connectionStateController.add(false);
|
||||
});
|
||||
_attachCommonPeerListeners(
|
||||
completer: completer,
|
||||
errorType: PeerErrorType.connectionFailed,
|
||||
errorMessage: 'Failed to connect to session',
|
||||
);
|
||||
} catch (e) {
|
||||
appLogger.e('WatchTogether: Failed to create peer for joining', error: e);
|
||||
if (!completer.isCompleted) {
|
||||
|
||||
@@ -241,19 +241,9 @@ class _DownloadTreeViewState extends State<DownloadTreeView> {
|
||||
);
|
||||
}
|
||||
|
||||
// Sort shows by status and title
|
||||
shows.sort((a, b) {
|
||||
final statusCompare = _compareByStatus(a.status, b.status);
|
||||
if (statusCompare != 0) return statusCompare;
|
||||
return a.title.compareTo(b.title);
|
||||
});
|
||||
|
||||
// Sort movies by status and title
|
||||
movies.sort((a, b) {
|
||||
final statusCompare = _compareByStatus(a.status, b.status);
|
||||
if (statusCompare != 0) return statusCompare;
|
||||
return a.title.compareTo(b.title);
|
||||
});
|
||||
// Sort shows and movies by status and title
|
||||
_sortNodesByStatusAndTitle(shows);
|
||||
_sortNodesByStatusAndTitle(movies);
|
||||
|
||||
// Combine movies and shows
|
||||
return [...movies, ...shows];
|
||||
@@ -292,6 +282,15 @@ class _DownloadTreeViewState extends State<DownloadTreeView> {
|
||||
return (statusOrder[a] ?? 99).compareTo(statusOrder[b] ?? 99);
|
||||
}
|
||||
|
||||
/// Sort nodes by status (downloading first) then by title
|
||||
void _sortNodesByStatusAndTitle(List<DownloadTreeNode> nodes) {
|
||||
nodes.sort((a, b) {
|
||||
final statusCompare = _compareByStatus(a.status, b.status);
|
||||
if (statusCompare != 0) return statusCompare;
|
||||
return a.title.compareTo(b.title);
|
||||
});
|
||||
}
|
||||
|
||||
/// Flatten the tree into a list of visible nodes with their depths
|
||||
List<_FlatNode> _flattenTree(List<DownloadTreeNode> nodes, [int depth = 0]) {
|
||||
final List<_FlatNode> result = [];
|
||||
|
||||
@@ -61,25 +61,16 @@ class _HorizontalScrollWithArrowsState extends State<HorizontalScrollWithArrows>
|
||||
});
|
||||
}
|
||||
|
||||
void _scrollLeft() {
|
||||
void _animateScroll(double direction) {
|
||||
final position = _scrollController.position;
|
||||
final targetScroll = (position.pixels - (position.viewportDimension * widget.scrollAmount)).clamp(
|
||||
0.0,
|
||||
position.maxScrollExtent,
|
||||
);
|
||||
|
||||
final delta = direction * position.viewportDimension * widget.scrollAmount;
|
||||
final targetScroll = (position.pixels + delta).clamp(0.0, position.maxScrollExtent);
|
||||
_scrollController.animateTo(targetScroll, duration: tokens(context).slow, curve: Curves.easeInOut);
|
||||
}
|
||||
|
||||
void _scrollRight() {
|
||||
final position = _scrollController.position;
|
||||
final targetScroll = (position.pixels + (position.viewportDimension * widget.scrollAmount)).clamp(
|
||||
0.0,
|
||||
position.maxScrollExtent,
|
||||
);
|
||||
void _scrollLeft() => _animateScroll(-1);
|
||||
|
||||
_scrollController.animateTo(targetScroll, duration: tokens(context).slow, curve: Curves.easeInOut);
|
||||
}
|
||||
void _scrollRight() => _animateScroll(1);
|
||||
|
||||
Widget _buildArrowButton({
|
||||
required double position,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
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 '../providers/settings_provider.dart';
|
||||
import '../services/settings_service.dart' show EpisodePosterMode;
|
||||
import '../theme/mono_tokens.dart';
|
||||
import '../utils/layout_constants.dart';
|
||||
import '../focus/locked_hub_controller.dart';
|
||||
@@ -231,7 +234,7 @@ class HubSectionState extends State<HubSection> {
|
||||
}
|
||||
|
||||
Future<void> _navigateToItem(dynamic item) async {
|
||||
await navigateToMediaItem(context, item, onRefresh: widget.onRefresh);
|
||||
await navigateToMediaItem(context, item, onRefresh: widget.onRefresh, playDirectly: widget.isInContinueWatching);
|
||||
}
|
||||
|
||||
void _navigateToHubDetail(BuildContext context) {
|
||||
@@ -286,9 +289,9 @@ class HubSectionState extends State<HubSection> {
|
||||
onKeyEvent: _handleKeyEvent,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Responsive card width based on screen size
|
||||
// Responsive base card width for posters (2:3 aspect ratio)
|
||||
final screenWidth = constraints.maxWidth;
|
||||
final cardWidth = ScreenBreakpoints.isLargeDesktop(screenWidth)
|
||||
final baseCardWidth = ScreenBreakpoints.isLargeDesktop(screenWidth)
|
||||
? 220.0
|
||||
: ScreenBreakpoints.isDesktop(screenWidth)
|
||||
? 200.0
|
||||
@@ -296,15 +299,35 @@ class HubSectionState extends State<HubSection> {
|
||||
? 190.0
|
||||
: 160.0;
|
||||
|
||||
// Store item extent for scroll calculations
|
||||
_itemExtent = cardWidth + 4; // 4px total horizontal padding
|
||||
// Get episode poster mode setting
|
||||
final episodePosterMode = context.watch<SettingsProvider>().episodePosterMode;
|
||||
|
||||
// Determine hub content type for layout decisions
|
||||
final hasEpisodes = widget.hub.items.any((item) =>
|
||||
item.usesWideAspectRatio(episodePosterMode));
|
||||
final hasNonEpisodes = widget.hub.items.any((item) =>
|
||||
!item.usesWideAspectRatio(episodePosterMode));
|
||||
|
||||
// Mixed hub = has both episodes AND non-episodes (like Continue Watching)
|
||||
final isMixedHub = hasEpisodes && hasNonEpisodes;
|
||||
|
||||
// Episode-only = all items are episodes with thumbnails
|
||||
final isEpisodeOnlyHub = hasEpisodes && !hasNonEpisodes;
|
||||
|
||||
// Use 16:9 for episode-only hubs OR mixed hubs (with episode thumbnail mode)
|
||||
final useWideLayout = episodePosterMode == EpisodePosterMode.episodeThumbnail &&
|
||||
(isEpisodeOnlyHub || isMixedHub);
|
||||
|
||||
// Card dimensions based on hub type
|
||||
const wideCardMultiplier = 1.5;
|
||||
final cardWidth = useWideLayout ? baseCardWidth * wideCardMultiplier : baseCardWidth;
|
||||
final posterWidth = cardWidth - 16; // 8px padding on each side
|
||||
final posterHeight = useWideLayout
|
||||
? posterWidth * (9 / 16) // 16:9 for wide layout
|
||||
: posterWidth * 1.5; // 2:3 for poster layout
|
||||
|
||||
// MediaCard has 8px padding on all sides (16px total horizontally)
|
||||
final posterWidth = cardWidth - 16;
|
||||
// 2:3 poster aspect ratio
|
||||
final posterHeight = posterWidth * 1.5;
|
||||
// Container height calculation
|
||||
final containerHeight = posterHeight + 66;
|
||||
_itemExtent = cardWidth + 4;
|
||||
|
||||
return SizedBox(
|
||||
height: containerHeight,
|
||||
@@ -334,6 +357,7 @@ class HubSectionState extends State<HubSection> {
|
||||
onRemoveFromContinueWatching: widget.onRemoveFromContinueWatching,
|
||||
forceGridMode: true,
|
||||
isInContinueWatching: widget.isInContinueWatching,
|
||||
mixedHubContext: isMixedHub,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -30,6 +30,7 @@ class MediaCard extends StatefulWidget {
|
||||
final bool isInContinueWatching;
|
||||
final String? collectionId; // The collection ID if displaying within a collection
|
||||
final bool isOffline; // True for downloaded content without server access
|
||||
final bool mixedHubContext; // True when in a hub with mixed content (movies + episodes)
|
||||
|
||||
const MediaCard({
|
||||
super.key,
|
||||
@@ -43,6 +44,7 @@ class MediaCard extends StatefulWidget {
|
||||
this.isInContinueWatching = false,
|
||||
this.collectionId,
|
||||
this.isOffline = false,
|
||||
this.mixedHubContext = false,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -69,7 +71,18 @@ class MediaCardState extends State<MediaCard> {
|
||||
String _buildSemanticLabel() {
|
||||
final item = widget.item;
|
||||
|
||||
// Build base label based on type
|
||||
// Playlists don't expose mediaType, so build a simple localized label and exit early
|
||||
if (item is PlexPlaylist) {
|
||||
final count = item.leafCount;
|
||||
final countText = count != null ? ', ${t.playlists.itemCount(count: count)}' : '';
|
||||
return '${item.displayTitle}, ${t.playlists.playlist}$countText';
|
||||
}
|
||||
|
||||
// Build base label based on PlexMetadata media type
|
||||
if (item is! PlexMetadata) {
|
||||
return '$item';
|
||||
}
|
||||
|
||||
String baseLabel;
|
||||
switch (item.mediaType) {
|
||||
case PlexMediaType.episode:
|
||||
@@ -108,6 +121,7 @@ class MediaCardState extends State<MediaCard> {
|
||||
widget.item,
|
||||
onRefresh: widget.onRefresh,
|
||||
isOffline: widget.isOffline,
|
||||
playDirectly: widget.isInContinueWatching,
|
||||
);
|
||||
|
||||
if (!context.mounted) return;
|
||||
@@ -157,6 +171,7 @@ class MediaCardState extends State<MediaCard> {
|
||||
onLongPress: _showContextMenu,
|
||||
isOffline: widget.isOffline,
|
||||
localPosterPath: localPosterPath,
|
||||
mixedHubContext: widget.mixedHubContext,
|
||||
)
|
||||
: _MediaCardList(
|
||||
item: widget.item,
|
||||
@@ -193,6 +208,7 @@ class _MediaCardGrid extends StatelessWidget {
|
||||
final VoidCallback onLongPress;
|
||||
final bool isOffline;
|
||||
final String? localPosterPath;
|
||||
final bool mixedHubContext;
|
||||
|
||||
const _MediaCardGrid({
|
||||
required this.item,
|
||||
@@ -203,6 +219,7 @@ class _MediaCardGrid extends StatelessWidget {
|
||||
required this.onLongPress,
|
||||
this.isOffline = false,
|
||||
this.localPosterPath,
|
||||
this.mixedHubContext = false,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -257,7 +274,7 @@ class _MediaCardGrid extends StatelessWidget {
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(tokens(context).radiusSm),
|
||||
child: _buildPosterImage(context, item, isOffline: isOffline, localPosterPath: localPosterPath),
|
||||
child: _buildPosterImage(context, item, isOffline: isOffline, localPosterPath: localPosterPath, mixedHubContext: mixedHubContext),
|
||||
),
|
||||
_PosterOverlay(item: item),
|
||||
],
|
||||
@@ -285,7 +302,7 @@ class _MediaCardList extends StatelessWidget {
|
||||
this.localPosterPath,
|
||||
});
|
||||
|
||||
double get _posterWidth {
|
||||
double _basePosterWidth() {
|
||||
switch (density) {
|
||||
case LibraryDensity.compact:
|
||||
return 80;
|
||||
@@ -296,8 +313,29 @@ class _MediaCardList extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
double get _posterHeight {
|
||||
return _posterWidth * 1.5; // Maintain 2:3 aspect ratio
|
||||
double _posterWidth(BuildContext context) {
|
||||
final base = _basePosterWidth();
|
||||
// For episodes with thumbnail mode, use wider width to maintain reasonable thumbnail size
|
||||
if (item is PlexMetadata) {
|
||||
final mode = context.watch<SettingsProvider>().episodePosterMode;
|
||||
if ((item as PlexMetadata).usesWideAspectRatio(mode)) {
|
||||
return base * 1.6; // Wider for 16:9 thumbnails
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
double _posterHeight(BuildContext context) {
|
||||
final base = _basePosterWidth();
|
||||
// For episodes with thumbnail mode, use 16:9 aspect ratio
|
||||
if (item is PlexMetadata) {
|
||||
final mode = context.watch<SettingsProvider>().episodePosterMode;
|
||||
if ((item as PlexMetadata).usesWideAspectRatio(mode)) {
|
||||
// 16:9: height = width * 9/16 = base * 1.6 * 9/16 = base * 0.9
|
||||
return base * 0.9;
|
||||
}
|
||||
}
|
||||
return base * 1.5; // Default 2:3 aspect ratio
|
||||
}
|
||||
|
||||
double get _titleFontSize {
|
||||
@@ -455,8 +493,8 @@ class _MediaCardList extends StatelessWidget {
|
||||
children: [
|
||||
// Poster (responsive size based on density)
|
||||
SizedBox(
|
||||
width: _posterWidth,
|
||||
height: _posterHeight,
|
||||
width: _posterWidth(context),
|
||||
height: _posterHeight(context),
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
@@ -533,7 +571,7 @@ class _MediaCardList extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildPosterImage(BuildContext context, dynamic item, {bool isOffline = false, String? localPosterPath}) {
|
||||
Widget _buildPosterImage(BuildContext context, dynamic item, {bool isOffline = false, String? localPosterPath, bool mixedHubContext = false}) {
|
||||
String? posterUrl;
|
||||
IconData fallbackIcon = Symbols.movie_rounded;
|
||||
|
||||
@@ -550,8 +588,20 @@ Widget _buildPosterImage(BuildContext context, dynamic item, {bool isOffline = f
|
||||
localFilePath: localPosterPath,
|
||||
);
|
||||
} else if (item is PlexMetadata) {
|
||||
final useSeasonPoster = context.watch<SettingsProvider>().useSeasonPoster;
|
||||
posterUrl = item.posterThumb(useSeasonPoster: useSeasonPoster);
|
||||
final episodePosterMode = context.watch<SettingsProvider>().episodePosterMode;
|
||||
posterUrl = item.posterThumb(mode: episodePosterMode, mixedHubContext: mixedHubContext);
|
||||
|
||||
// Use thumb image type for 16:9 content (episodes, or movies in mixed hubs)
|
||||
if (item.usesWideAspectRatio(episodePosterMode, mixedHubContext: mixedHubContext)) {
|
||||
return PlexOptimizedImage.thumb(
|
||||
client: isOffline ? null : context.getClientWithFallback(item.serverId),
|
||||
imagePath: posterUrl,
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
fit: BoxFit.cover,
|
||||
localFilePath: localPosterPath,
|
||||
);
|
||||
}
|
||||
|
||||
return PlexOptimizedImage.poster(
|
||||
client: isOffline ? null : context.getClientWithFallback(item.serverId),
|
||||
|
||||
@@ -289,7 +289,7 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
switch (selected) {
|
||||
case 'watch':
|
||||
if (isOffline && metadata?.serverId != null) {
|
||||
// Offline mode: queue action for later sync
|
||||
// Offline mode: queue action for later sync (emits WatchStateEvent)
|
||||
final offlineWatch = context.read<OfflineWatchProvider>();
|
||||
await offlineWatch.markAsWatched(serverId: metadata!.serverId!, ratingKey: metadata.ratingKey);
|
||||
if (context.mounted) {
|
||||
@@ -297,13 +297,18 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
widget.onRefresh?.call(metadata.ratingKey);
|
||||
}
|
||||
} else {
|
||||
await _executeAction(context, () => client.markAsWatched(metadata!.ratingKey), t.messages.markedAsWatched);
|
||||
// Pass metadata to emit WatchStateEvent for cross-screen updates
|
||||
await _executeAction(
|
||||
context,
|
||||
() => client.markAsWatched(metadata!.ratingKey, metadata: metadata),
|
||||
t.messages.markedAsWatched,
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'unwatch':
|
||||
if (isOffline && metadata?.serverId != null) {
|
||||
// Offline mode: queue action for later sync
|
||||
// Offline mode: queue action for later sync (emits WatchStateEvent)
|
||||
final offlineWatch = context.read<OfflineWatchProvider>();
|
||||
await offlineWatch.markAsUnwatched(serverId: metadata!.serverId!, ratingKey: metadata.ratingKey);
|
||||
if (context.mounted) {
|
||||
@@ -311,9 +316,10 @@ class MediaContextMenuState extends State<MediaContextMenu> {
|
||||
widget.onRefresh?.call(metadata.ratingKey);
|
||||
}
|
||||
} else {
|
||||
// Pass metadata to emit WatchStateEvent for cross-screen updates
|
||||
await _executeAction(
|
||||
context,
|
||||
() => client.markAsUnwatched(metadata!.ratingKey),
|
||||
() => client.markAsUnwatched(metadata!.ratingKey, metadata: metadata),
|
||||
t.messages.markedAsUnwatched,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,19 +10,31 @@ class MediaGridDelegate {
|
||||
///
|
||||
/// Uses [GridSizeCalculator.getMaxCrossAxisExtent] by default.
|
||||
/// Set [usePaddingAware] to true to use [GridSizeCalculator.getMaxCrossAxisExtentWithPadding] instead.
|
||||
/// Set [useWideAspectRatio] to true to use 16:9 aspect ratio for episode thumbnails.
|
||||
static SliverGridDelegateWithMaxCrossAxisExtent createDelegate({
|
||||
required BuildContext context,
|
||||
required LibraryDensity density,
|
||||
bool usePaddingAware = false,
|
||||
double horizontalPadding = 16,
|
||||
bool useWideAspectRatio = false,
|
||||
}) {
|
||||
final maxCrossAxisExtent = usePaddingAware
|
||||
var maxCrossAxisExtent = usePaddingAware
|
||||
? GridSizeCalculator.getMaxCrossAxisExtentWithPadding(context, density, horizontalPadding)
|
||||
: GridSizeCalculator.getMaxCrossAxisExtent(context, density);
|
||||
|
||||
final aspectRatio = useWideAspectRatio
|
||||
? GridLayoutConstants.episodeGridCellAspectRatio
|
||||
: GridLayoutConstants.posterAspectRatio;
|
||||
|
||||
// For wide aspect ratio (16:9), increase max extent so items are larger
|
||||
// and there are fewer per row (roughly 1.8x wider to maintain similar visual area)
|
||||
if (useWideAspectRatio) {
|
||||
maxCrossAxisExtent *= 1.8;
|
||||
}
|
||||
|
||||
return SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: maxCrossAxisExtent,
|
||||
childAspectRatio: GridLayoutConstants.posterAspectRatio,
|
||||
childAspectRatio: aspectRatio,
|
||||
crossAxisSpacing: GridLayoutConstants.crossAxisSpacing,
|
||||
mainAxisSpacing: GridLayoutConstants.mainAxisSpacing,
|
||||
);
|
||||
|
||||
@@ -33,6 +33,13 @@ class MediaGridSliver extends StatelessWidget {
|
||||
/// Only used if usePaddingAwareExtent is true
|
||||
final double horizontalPadding;
|
||||
|
||||
/// Whether to use 16:9 aspect ratio for episode thumbnails
|
||||
final bool useWideAspectRatio;
|
||||
|
||||
/// Whether this grid is displaying items from a mixed hub context
|
||||
/// (containing both episodes and non-episodes)
|
||||
final bool mixedHubContext;
|
||||
|
||||
const MediaGridSliver({
|
||||
super.key,
|
||||
required this.items,
|
||||
@@ -42,6 +49,8 @@ class MediaGridSliver extends StatelessWidget {
|
||||
this.padding = const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
this.usePaddingAwareExtent = false,
|
||||
this.horizontalPadding = 16,
|
||||
this.useWideAspectRatio = false,
|
||||
this.mixedHubContext = false,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -56,6 +65,7 @@ class MediaGridSliver extends StatelessWidget {
|
||||
density: settingsProvider.libraryDensity,
|
||||
usePaddingAware: usePaddingAwareExtent,
|
||||
horizontalPadding: horizontalPadding,
|
||||
useWideAspectRatio: useWideAspectRatio,
|
||||
),
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
final item = items[index];
|
||||
@@ -65,6 +75,7 @@ class MediaGridSliver extends StatelessWidget {
|
||||
onRefresh: onRefresh,
|
||||
collectionId: collectionId,
|
||||
onListRefresh: onListRefresh,
|
||||
mixedHubContext: mixedHubContext,
|
||||
);
|
||||
}, childCount: items.length),
|
||||
);
|
||||
|
||||
@@ -241,11 +241,14 @@ class PlexOptimizedImage extends StatelessWidget {
|
||||
// Pick the explicit size when it's a finite positive number, otherwise
|
||||
// fall back to the constraint or a sensible default so we don't end up
|
||||
// with NaN/Infinity when rounding to ints for caching.
|
||||
final candidate = explicit ?? (constraintMax.isFinite && constraintMax > 0 ? constraintMax : fallback);
|
||||
if (candidate.isNaN || candidate.isInfinite || candidate <= 0) {
|
||||
// When explicit is infinite (double.infinity), prefer the constraint over fallback.
|
||||
if (explicit == null || explicit.isNaN || explicit.isInfinite || explicit <= 0) {
|
||||
if (constraintMax.isFinite && constraintMax > 0) {
|
||||
return constraintMax;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
return candidate;
|
||||
return explicit;
|
||||
}
|
||||
|
||||
// Return empty container if no image path
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../focus/dpad_navigator.dart';
|
||||
import '../focus/focus_theme.dart';
|
||||
import '../focus/input_mode_tracker.dart';
|
||||
import 'app_icon.dart';
|
||||
import '../theme/mono_tokens.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
|
||||
/// A TV-friendly number spinner with +/- buttons for D-pad navigation.
|
||||
///
|
||||
/// Displays a value with decrement/increment buttons on either side.
|
||||
/// Supports keyboard repeat for faster value changes when holding arrows.
|
||||
class TvNumberSpinner extends StatefulWidget {
|
||||
/// Current value.
|
||||
final int value;
|
||||
|
||||
/// Minimum allowed value.
|
||||
final int min;
|
||||
|
||||
/// Maximum allowed value.
|
||||
final int max;
|
||||
|
||||
/// Step size for each increment/decrement.
|
||||
final int step;
|
||||
|
||||
/// Optional suffix text (e.g., "s" for seconds).
|
||||
final String? suffix;
|
||||
|
||||
/// Called when the value changes.
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
/// Whether the spinner should request focus when built.
|
||||
final bool autofocus;
|
||||
|
||||
const TvNumberSpinner({
|
||||
super.key,
|
||||
required this.value,
|
||||
required this.min,
|
||||
required this.max,
|
||||
required this.onChanged,
|
||||
this.step = 1,
|
||||
this.suffix,
|
||||
this.autofocus = false,
|
||||
});
|
||||
|
||||
@override
|
||||
State<TvNumberSpinner> createState() => _TvNumberSpinnerState();
|
||||
}
|
||||
|
||||
class _TvNumberSpinnerState extends State<TvNumberSpinner> {
|
||||
late FocusNode _focusNode;
|
||||
Timer? _repeatTimer;
|
||||
bool _isFocused = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_focusNode = FocusNode(debugLabel: 'TvNumberSpinner');
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_repeatTimer?.cancel();
|
||||
_focusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _increment() {
|
||||
final newValue = widget.value + widget.step;
|
||||
if (newValue <= widget.max) {
|
||||
widget.onChanged(newValue);
|
||||
}
|
||||
}
|
||||
|
||||
void _decrement() {
|
||||
final newValue = widget.value - widget.step;
|
||||
if (newValue >= widget.min) {
|
||||
widget.onChanged(newValue);
|
||||
}
|
||||
}
|
||||
|
||||
void _startRepeat(VoidCallback action) {
|
||||
// Execute once immediately
|
||||
action();
|
||||
|
||||
// Start repeat timer after initial delay
|
||||
_repeatTimer?.cancel();
|
||||
_repeatTimer = Timer(const Duration(milliseconds: 400), () {
|
||||
_repeatTimer = Timer.periodic(const Duration(milliseconds: 100), (_) {
|
||||
action();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void _stopRepeat() {
|
||||
_repeatTimer?.cancel();
|
||||
_repeatTimer = null;
|
||||
}
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
|
||||
if (event is KeyDownEvent) {
|
||||
if (key.isUpKey || key.isRightKey) {
|
||||
_startRepeat(_increment);
|
||||
return KeyEventResult.handled;
|
||||
} else if (key.isDownKey || key.isLeftKey) {
|
||||
_startRepeat(_decrement);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
} else if (event is KeyUpEvent) {
|
||||
if (key.isUpKey || key.isRightKey || key.isDownKey || key.isLeftKey) {
|
||||
_stopRepeat();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final tokens = theme.extension<MonoTokens>();
|
||||
final canDecrement = widget.value > widget.min;
|
||||
final canIncrement = widget.value < widget.max;
|
||||
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
|
||||
|
||||
return Focus(
|
||||
focusNode: _focusNode,
|
||||
autofocus: widget.autofocus,
|
||||
onFocusChange: (hasFocus) {
|
||||
setState(() => _isFocused = hasFocus);
|
||||
if (!hasFocus) _stopRepeat();
|
||||
},
|
||||
onKeyEvent: _handleKeyEvent,
|
||||
child: AnimatedContainer(
|
||||
duration: tokens?.fast ?? const Duration(milliseconds: 150),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(FocusTheme.defaultBorderRadius),
|
||||
border: Border.all(
|
||||
color: _isFocused && isKeyboardMode ? FocusTheme.getFocusBorderColor(context) : Colors.transparent,
|
||||
width: FocusTheme.focusBorderWidth,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
// Decrement button
|
||||
_SpinnerButton(
|
||||
icon: Symbols.remove_rounded,
|
||||
onPressed: canDecrement ? _decrement : null,
|
||||
onLongPressStart: canDecrement ? () => _startRepeat(_decrement) : null,
|
||||
onLongPressEnd: _stopRepeat,
|
||||
semanticLabel: 'Decrease',
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
// Value display
|
||||
Container(
|
||||
constraints: const BoxConstraints(minWidth: 60),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
widget.suffix != null ? '${widget.value}${widget.suffix}' : '${widget.value}',
|
||||
style: theme.textTheme.headlineMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
// Increment button
|
||||
_SpinnerButton(
|
||||
icon: Symbols.add_rounded,
|
||||
onPressed: canIncrement ? _increment : null,
|
||||
onLongPressStart: canIncrement ? () => _startRepeat(_increment) : null,
|
||||
onLongPressEnd: _stopRepeat,
|
||||
semanticLabel: 'Increase',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Individual +/- button with long-press support.
|
||||
class _SpinnerButton extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final VoidCallback? onPressed;
|
||||
final VoidCallback? onLongPressStart;
|
||||
final VoidCallback? onLongPressEnd;
|
||||
final String semanticLabel;
|
||||
|
||||
const _SpinnerButton({
|
||||
required this.icon,
|
||||
required this.onPressed,
|
||||
this.onLongPressStart,
|
||||
this.onLongPressEnd,
|
||||
required this.semanticLabel,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final isEnabled = onPressed != null;
|
||||
|
||||
return Semantics(
|
||||
label: semanticLabel,
|
||||
button: true,
|
||||
enabled: isEnabled,
|
||||
child: GestureDetector(
|
||||
onLongPressStart: onLongPressStart != null ? (_) => onLongPressStart!() : null,
|
||||
onLongPressEnd: onLongPressEnd != null ? (_) => onLongPressEnd!() : null,
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
onTap: onPressed,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
child: Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isEnabled ? theme.colorScheme.primaryContainer : theme.colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
child: Center(
|
||||
child: AppIcon(
|
||||
icon,
|
||||
fill: 1,
|
||||
color: isEnabled
|
||||
? theme.colorScheme.onPrimaryContainer
|
||||
: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ class DesktopVideoControls extends StatefulWidget {
|
||||
final int subtitleSyncOffset;
|
||||
final bool isFullscreen;
|
||||
final bool isAlwaysOnTop;
|
||||
final VoidCallback? onTogglePIPMode;
|
||||
final VoidCallback? onCycleBoxFitMode;
|
||||
final VoidCallback? onToggleFullscreen;
|
||||
final VoidCallback? onToggleAlwaysOnTop;
|
||||
@@ -67,6 +68,9 @@ class DesktopVideoControls extends StatefulWidget {
|
||||
/// Whether the user can control playback (false in host-only mode for non-host).
|
||||
final bool canControl;
|
||||
|
||||
/// Notifier for whether first video frame has rendered (shows loading state when false).
|
||||
final ValueNotifier<bool>? hasFirstFrame;
|
||||
|
||||
const DesktopVideoControls({
|
||||
super.key,
|
||||
required this.player,
|
||||
@@ -92,6 +96,7 @@ class DesktopVideoControls extends StatefulWidget {
|
||||
this.subtitleSyncOffset = 0,
|
||||
this.isFullscreen = false,
|
||||
this.isAlwaysOnTop = false,
|
||||
this.onTogglePIPMode,
|
||||
this.onCycleBoxFitMode,
|
||||
this.onToggleFullscreen,
|
||||
this.onToggleAlwaysOnTop,
|
||||
@@ -104,6 +109,7 @@ class DesktopVideoControls extends StatefulWidget {
|
||||
this.serverId = '',
|
||||
this.onBack,
|
||||
this.canControl = true,
|
||||
this.hasFirstFrame,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -128,6 +134,10 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
|
||||
// List of button focus nodes for horizontal navigation
|
||||
late final List<FocusNode> _buttonFocusNodes;
|
||||
|
||||
// Progressive seek acceleration state
|
||||
LogicalKeyboardKey? _seekDirection; // Current direction being held
|
||||
int _seekRepeatCount = 0; // Consecutive key repeats for acceleration
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -186,6 +196,9 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
|
||||
void _onFocusChange(bool hasFocus) {
|
||||
if (hasFocus) {
|
||||
widget.onFocusActivity?.call();
|
||||
} else {
|
||||
// Reset progressive seek state when timeline loses focus
|
||||
_resetSeekState();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,43 +252,84 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Reset progressive seek state
|
||||
void _resetSeekState() {
|
||||
_seekDirection = null;
|
||||
_seekRepeatCount = 0;
|
||||
}
|
||||
|
||||
/// Calculate seek multiplier based on repeat count (stepped tiers)
|
||||
double _getSeekMultiplier() {
|
||||
if (_seekRepeatCount <= 5) {
|
||||
return 1.5;
|
||||
} else if (_seekRepeatCount <= 15) {
|
||||
return 3.0;
|
||||
} else if (_seekRepeatCount <= 30) {
|
||||
return 6.0;
|
||||
} else {
|
||||
return 10.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle key events for timeline navigation
|
||||
KeyEventResult _handleTimelineKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
|
||||
// Handle key release to reset progressive seek state
|
||||
if (event is KeyUpEvent) {
|
||||
if (key == LogicalKeyboardKey.arrowLeft || key == LogicalKeyboardKey.arrowRight) {
|
||||
_resetSeekState();
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
if (!event.isActionable) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
final key = event.logicalKey;
|
||||
final duration = widget.player.state.duration;
|
||||
final position = widget.player.state.position;
|
||||
|
||||
// UP arrow - hide controls
|
||||
// UP arrow - hide controls and reset seek state
|
||||
if (key == LogicalKeyboardKey.arrowUp) {
|
||||
_resetSeekState();
|
||||
widget.onHideControls?.call();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// DOWN arrow - move focus to play/pause button
|
||||
// DOWN arrow - move focus to play/pause button and reset seek state
|
||||
if (key == LogicalKeyboardKey.arrowDown) {
|
||||
_resetSeekState();
|
||||
_playPauseFocusNode.requestFocus();
|
||||
widget.onFocusActivity?.call();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// LEFT/RIGHT for smooth scrubbing - only if user can control
|
||||
// LEFT/RIGHT for smooth scrubbing with progressive acceleration
|
||||
if (key == LogicalKeyboardKey.arrowLeft || key == LogicalKeyboardKey.arrowRight) {
|
||||
// Ignore seeking if user cannot control
|
||||
if (!widget.canControl) return KeyEventResult.handled;
|
||||
|
||||
if (duration.inMilliseconds <= 0) return KeyEventResult.handled;
|
||||
|
||||
// Base step: 0.5% of duration, minimum 500ms
|
||||
final baseStep = Duration(milliseconds: (duration.inMilliseconds * 0.005).clamp(500, 15000).toInt());
|
||||
// Track direction change - reset if direction changes
|
||||
if (_seekDirection != key) {
|
||||
_seekDirection = key;
|
||||
_seekRepeatCount = 0;
|
||||
}
|
||||
|
||||
// Accelerate on key repeat
|
||||
final step = event is KeyRepeatEvent
|
||||
? Duration(milliseconds: (baseStep.inMilliseconds * 2).clamp(500, 30000))
|
||||
: baseStep;
|
||||
// Increment repeat count on KeyRepeatEvent
|
||||
if (event is KeyRepeatEvent) {
|
||||
_seekRepeatCount++;
|
||||
}
|
||||
|
||||
// Base step: 0.5% of duration, minimum 500ms, maximum 15s
|
||||
final baseStepMs = (duration.inMilliseconds * 0.005).clamp(500, 15000).toInt();
|
||||
|
||||
// Apply progressive multiplier only on repeat events (initial press uses 1x)
|
||||
final effectiveMultiplier = event is KeyRepeatEvent ? _getSeekMultiplier() : 1.0;
|
||||
final stepMs = (baseStepMs * effectiveMultiplier).clamp(500, 60000).toInt();
|
||||
final step = Duration(milliseconds: stepMs);
|
||||
|
||||
final isForward = key == LogicalKeyboardKey.arrowRight;
|
||||
final newPosition = isForward ? position + step : position - step;
|
||||
@@ -293,14 +347,24 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
// Top bar with back button and title
|
||||
_buildTopBar(context),
|
||||
const Spacer(),
|
||||
// Bottom controls
|
||||
_buildBottomControls(context),
|
||||
],
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: widget.hasFirstFrame ?? ValueNotifier(true),
|
||||
builder: (context, hasFrame, child) {
|
||||
return Column(
|
||||
children: [
|
||||
// Top bar with back button and title (always visible)
|
||||
_buildTopBar(context),
|
||||
if (!hasFrame)
|
||||
// Loading: empty space, spinner shown by video_player_screen
|
||||
const Expanded(child: SizedBox.shrink())
|
||||
else ...[
|
||||
// Loaded: spacer + bottom controls
|
||||
const Spacer(),
|
||||
_buildBottomControlsContent(context, hasFrame: true),
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -334,7 +398,8 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
|
||||
return DesktopAppBarHelper.wrapWithGestureDetector(topBar, opaque: true);
|
||||
}
|
||||
|
||||
Widget _buildBottomControls(BuildContext context) {
|
||||
Widget _buildBottomControlsContent(BuildContext context, {required bool hasFrame}) {
|
||||
final canInteract = widget.canControl && hasFrame;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
|
||||
child: Column(
|
||||
@@ -350,7 +415,7 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
|
||||
focusNode: _timelineFocusNode,
|
||||
onKeyEvent: _handleTimelineKeyEvent,
|
||||
onFocusChange: _onFocusChange,
|
||||
enabled: widget.canControl,
|
||||
enabled: canInteract,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// Row 2: Playback controls and options
|
||||
@@ -461,6 +526,7 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
|
||||
isFullscreen: widget.isFullscreen,
|
||||
isAlwaysOnTop: widget.isAlwaysOnTop,
|
||||
serverId: widget.serverId,
|
||||
onTogglePIPMode: null, // PIP not supported on desktop
|
||||
onCycleBoxFitMode: widget.onCycleBoxFitMode,
|
||||
onToggleFullscreen: widget.onToggleFullscreen,
|
||||
onToggleAlwaysOnTop: widget.onToggleAlwaysOnTop,
|
||||
|
||||
@@ -6,8 +6,6 @@ import '../../mpv/mpv.dart';
|
||||
import '../../models/plex_media_info.dart';
|
||||
import '../../models/plex_metadata.dart';
|
||||
import '../../utils/desktop_window_padding.dart';
|
||||
import '../../utils/player_utils.dart';
|
||||
import 'icons.dart';
|
||||
import '../../i18n/strings.g.dart';
|
||||
import 'widgets/video_controls_header.dart';
|
||||
import 'widgets/video_timeline_bar.dart';
|
||||
@@ -32,10 +30,15 @@ class MobileVideoControls extends StatelessWidget {
|
||||
final VoidCallback? onCancelAutoHide;
|
||||
final VoidCallback? onStartAutoHide;
|
||||
final VoidCallback? onBack;
|
||||
final VoidCallback? onNext;
|
||||
final VoidCallback? onPrevious;
|
||||
|
||||
/// Whether the user can control playback (false in host-only mode for non-host).
|
||||
final bool canControl;
|
||||
|
||||
/// Notifier for whether first video frame has rendered (shows loading state when false).
|
||||
final ValueNotifier<bool>? hasFirstFrame;
|
||||
|
||||
const MobileVideoControls({
|
||||
super.key,
|
||||
required this.player,
|
||||
@@ -51,7 +54,10 @@ class MobileVideoControls extends StatelessWidget {
|
||||
this.onCancelAutoHide,
|
||||
this.onStartAutoHide,
|
||||
this.onBack,
|
||||
this.onNext,
|
||||
this.onPrevious,
|
||||
this.canControl = true,
|
||||
this.hasFirstFrame,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -94,6 +100,24 @@ class MobileVideoControls extends StatelessWidget {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
// Check if we're still loading first frame
|
||||
final hasFirstFrameNotifier = hasFirstFrame;
|
||||
if (hasFirstFrameNotifier != null) {
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: hasFirstFrameNotifier,
|
||||
builder: (context, hasFrame, child) {
|
||||
if (!hasFrame) {
|
||||
// Empty space, spinner shown by video_player_screen
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return _buildPlaybackControlsContent(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
return _buildPlaybackControlsContent(context);
|
||||
}
|
||||
|
||||
Widget _buildPlaybackControlsContent(BuildContext context) {
|
||||
return StreamBuilder<bool>(
|
||||
stream: player.streams.playing,
|
||||
initialData: player.state.playing,
|
||||
@@ -102,16 +126,14 @@ class MobileVideoControls extends StatelessWidget {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
// Previous episode button (greyed out when unavailable)
|
||||
_buildCircularButton(
|
||||
semanticLabel: t.videoControls.seekBackwardButton(seconds: seekTimeSmall),
|
||||
icon: getReplayIcon(seekTimeSmall),
|
||||
semanticLabel: t.videoControls.previousButton,
|
||||
icon: Symbols.skip_previous_rounded,
|
||||
iconSize: 48,
|
||||
onPressed: () {
|
||||
final newPosition = seekWithClamping(player, Duration(seconds: -seekTimeSmall));
|
||||
onSeekCompleted?.call(newPosition);
|
||||
},
|
||||
onPressed: onPrevious,
|
||||
),
|
||||
const SizedBox(width: 48),
|
||||
const SizedBox(width: 24),
|
||||
_buildCircularButton(
|
||||
semanticLabel: isPlaying ? t.videoControls.pauseButton : t.videoControls.playButton,
|
||||
icon: isPlaying ? Symbols.pause_rounded : Symbols.play_arrow_rounded,
|
||||
@@ -126,15 +148,13 @@ class MobileVideoControls extends StatelessWidget {
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 48),
|
||||
const SizedBox(width: 24),
|
||||
// Next episode button (greyed out when unavailable)
|
||||
_buildCircularButton(
|
||||
semanticLabel: t.videoControls.seekForwardButton(seconds: seekTimeSmall),
|
||||
icon: getForwardIcon(seekTimeSmall),
|
||||
semanticLabel: t.videoControls.nextButton,
|
||||
icon: Symbols.skip_next_rounded,
|
||||
iconSize: 48,
|
||||
onPressed: () {
|
||||
final newPosition = seekWithClamping(player, Duration(seconds: seekTimeSmall));
|
||||
onSeekCompleted?.call(newPosition);
|
||||
},
|
||||
onPressed: onNext,
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -143,6 +163,24 @@ class MobileVideoControls extends StatelessWidget {
|
||||
}
|
||||
|
||||
Widget _buildBottomBar(BuildContext context) {
|
||||
// Check if we're still loading first frame
|
||||
final hasFirstFrameNotifier = hasFirstFrame;
|
||||
if (hasFirstFrameNotifier != null) {
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: hasFirstFrameNotifier,
|
||||
builder: (context, hasFrame, child) {
|
||||
if (!hasFrame) {
|
||||
// Hide timeline while loading
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return _buildBottomBarContent(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
return _buildBottomBarContent(context);
|
||||
}
|
||||
|
||||
Widget _buildBottomBarContent(BuildContext context) {
|
||||
return _conditionalSafeArea(
|
||||
context: context,
|
||||
top: false, // Only respect bottom safe area when in portrait
|
||||
@@ -165,8 +203,9 @@ class MobileVideoControls extends StatelessWidget {
|
||||
required String semanticLabel,
|
||||
required IconData icon,
|
||||
required double iconSize,
|
||||
required VoidCallback onPressed,
|
||||
VoidCallback? onPressed,
|
||||
}) {
|
||||
final isEnabled = onPressed != null;
|
||||
return Container(
|
||||
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.5), shape: BoxShape.circle),
|
||||
child: Semantics(
|
||||
@@ -174,7 +213,12 @@ class MobileVideoControls extends StatelessWidget {
|
||||
button: true,
|
||||
excludeSemantics: true,
|
||||
child: IconButton(
|
||||
icon: AppIcon(icon, fill: 1, color: Colors.white, size: iconSize),
|
||||
icon: AppIcon(
|
||||
icon,
|
||||
fill: 1,
|
||||
color: isEnabled ? Colors.white : Colors.white.withValues(alpha: 0.3),
|
||||
size: iconSize,
|
||||
),
|
||||
iconSize: iconSize,
|
||||
onPressed: onPressed,
|
||||
),
|
||||
|
||||
@@ -111,6 +111,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
|
||||
late int _audioSyncOffset;
|
||||
late int _subtitleSyncOffset;
|
||||
bool _enableHDR = true;
|
||||
bool _showPerformanceOverlay = false;
|
||||
late final FocusNode _initialFocusNode;
|
||||
|
||||
@override
|
||||
@@ -119,7 +120,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
|
||||
_audioSyncOffset = widget.audioSyncOffset;
|
||||
_subtitleSyncOffset = widget.subtitleSyncOffset;
|
||||
_initialFocusNode = FocusNode(debugLabel: 'VideoSettingsInitialFocus');
|
||||
_loadHDRSetting();
|
||||
_loadSettings();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -128,10 +129,11 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadHDRSetting() async {
|
||||
Future<void> _loadSettings() async {
|
||||
final settings = await SettingsService.getInstance();
|
||||
setState(() {
|
||||
_enableHDR = settings.getEnableHDR();
|
||||
_showPerformanceOverlay = settings.getShowPerformanceOverlay();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -146,6 +148,15 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
|
||||
await widget.player.setProperty('hdr-enabled', newValue ? 'yes' : 'no');
|
||||
}
|
||||
|
||||
Future<void> _togglePerformanceOverlay() async {
|
||||
final newValue = !_showPerformanceOverlay;
|
||||
final settings = await SettingsService.getInstance();
|
||||
await settings.setShowPerformanceOverlay(newValue);
|
||||
setState(() {
|
||||
_showPerformanceOverlay = newValue;
|
||||
});
|
||||
}
|
||||
|
||||
void _navigateTo(_SettingsView view) {
|
||||
setState(() {
|
||||
_currentView = view;
|
||||
@@ -289,6 +300,22 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
// Performance Overlay Toggle
|
||||
ListTile(
|
||||
leading: AppIcon(
|
||||
Symbols.analytics_rounded,
|
||||
fill: 1,
|
||||
color: _showPerformanceOverlay ? Colors.amber : Colors.white70,
|
||||
),
|
||||
title: const Text('Performance Overlay', style: TextStyle(color: Colors.white)),
|
||||
trailing: Switch(
|
||||
value: _showPerformanceOverlay,
|
||||
onChanged: (_) => _togglePerformanceOverlay(),
|
||||
activeThumbColor: Colors.amber,
|
||||
),
|
||||
onTap: _togglePerformanceOverlay,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
|
||||
import '../../../../mpv/mpv.dart';
|
||||
import '../../../../widgets/app_icon.dart';
|
||||
import 'performance_stats.dart';
|
||||
import 'performance_stats_service.dart';
|
||||
|
||||
/// A toggleable overlay displaying real-time video player performance statistics.
|
||||
///
|
||||
/// Shows a single card with two columns of metrics organized by section.
|
||||
/// Positioned in the top-left corner of the video player.
|
||||
class PlayerPerformanceOverlay extends StatefulWidget {
|
||||
final Player player;
|
||||
|
||||
const PlayerPerformanceOverlay({super.key, required this.player});
|
||||
|
||||
@override
|
||||
State<PlayerPerformanceOverlay> createState() => _PlayerPerformanceOverlayState();
|
||||
}
|
||||
|
||||
class _PlayerPerformanceOverlayState extends State<PlayerPerformanceOverlay> {
|
||||
late final PerformanceStatsService _statsService;
|
||||
PerformanceStats _stats = const PerformanceStats.empty();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_statsService = PerformanceStatsService(widget.player);
|
||||
_statsService.statsStream.listen((stats) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_stats = stats;
|
||||
});
|
||||
}
|
||||
});
|
||||
_statsService.startPolling();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_statsService.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
constraints: const BoxConstraints(maxWidth: 380),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.8),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.3), blurRadius: 4)],
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Left column
|
||||
Flexible(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_buildSection(Symbols.videocam_rounded, 'Video', [
|
||||
_metric('Codec', _stats.videoCodec ?? 'N/A'),
|
||||
_metric('Resolution', _stats.resolution),
|
||||
_metric('FPS', _stats.videoFpsFormatted),
|
||||
_metric('Bitrate', _stats.videoBitrateFormatted),
|
||||
_metric('Decoder', _stats.hwdecFormatted),
|
||||
if (_stats.aspectName != null && _stats.aspectName!.isNotEmpty) _metric('Aspect', _stats.aspectName!),
|
||||
if (_stats.rotate != null && _stats.rotate != 0) _metric('Rotation', _stats.rotateFormatted),
|
||||
]),
|
||||
const SizedBox(height: 12),
|
||||
_buildSection(Symbols.palette_rounded, 'Color', [
|
||||
_metric('Pixel Fmt', _stats.pixelformat ?? 'N/A'),
|
||||
if (_stats.hwPixelformat != null && _stats.hwPixelformat != _stats.pixelformat)
|
||||
_metric('HW Fmt', _stats.hwPixelformat!),
|
||||
_metric('Matrix', _stats.colormatrix ?? 'N/A'),
|
||||
_metric('Primaries', _stats.primaries ?? 'N/A'),
|
||||
_metric('Transfer', _stats.gamma ?? 'N/A'),
|
||||
]),
|
||||
if (_stats.hasHdrMetadata) ...[
|
||||
const SizedBox(height: 12),
|
||||
_buildSection(Symbols.hdr_on_rounded, 'HDR', [
|
||||
if (_stats.maxLuma != null) _metric('Max Luma', _stats.maxLumaFormatted),
|
||||
if (_stats.minLuma != null) _metric('Min Luma', _stats.minLumaFormatted),
|
||||
if (_stats.maxCll != null) _metric('MaxCLL', _stats.maxCllFormatted),
|
||||
if (_stats.maxFall != null) _metric('MaxFALL', _stats.maxFallFormatted),
|
||||
]),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 24),
|
||||
// Right column
|
||||
Flexible(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_buildSection(Symbols.volume_up_rounded, 'Audio', [
|
||||
_metric('Codec', _stats.audioCodec ?? 'N/A'),
|
||||
_metric('Sample Rate', _stats.sampleRateFormatted),
|
||||
_metric('Channels', _stats.audioChannels ?? 'N/A'),
|
||||
_metric('Bitrate', _stats.audioBitrateFormatted),
|
||||
]),
|
||||
const SizedBox(height: 12),
|
||||
_buildSection(Symbols.speed_rounded, 'Performance', [
|
||||
_metric('Render FPS', _stats.actualFpsFormatted),
|
||||
_metric('Display FPS', _stats.displayFpsFormatted),
|
||||
_metric('A/V Sync', _stats.avsyncFormatted),
|
||||
_metric('Dropped', _stats.droppedFramesFormatted),
|
||||
]),
|
||||
const SizedBox(height: 12),
|
||||
_buildSection(Symbols.memory_rounded, 'Buffer', [
|
||||
_metric('Duration', _stats.cacheDurationFormatted),
|
||||
_metric('Cache Used', _stats.cacheUsedFormatted),
|
||||
_metric('Speed', _stats.cacheSpeedFormatted),
|
||||
]),
|
||||
const SizedBox(height: 12),
|
||||
_buildSection(Symbols.apps_rounded, 'App', [
|
||||
_metric('Memory', _stats.appMemoryFormatted),
|
||||
_metric('UI FPS', _stats.uiFpsFormatted),
|
||||
]),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSection(IconData icon, String title, List<_Metric> metrics) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
AppIcon(icon, fill: 1, color: Colors.white70, size: 12),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
title,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.w600),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
...metrics.map(_buildMetricRow),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMetricRow(_Metric metric) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 2),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('${metric.label}: ', style: const TextStyle(color: Colors.white60, fontSize: 10)),
|
||||
Flexible(
|
||||
child: Text(
|
||||
metric.value,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w500,
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
_Metric _metric(String label, String value) => _Metric(label, value);
|
||||
}
|
||||
|
||||
class _Metric {
|
||||
final String label;
|
||||
final String value;
|
||||
const _Metric(this.label, this.value);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/// Data model for video player performance statistics.
|
||||
///
|
||||
/// Contains metrics queried from libmpv including video/audio codec info,
|
||||
/// playback performance, and buffer state.
|
||||
class PerformanceStats {
|
||||
// Video metrics
|
||||
final String? videoCodec;
|
||||
final int? videoWidth;
|
||||
final int? videoHeight;
|
||||
final double? videoFps;
|
||||
final String? hwdecCurrent;
|
||||
final int? videoBitrate;
|
||||
final String? aspectName;
|
||||
final int? rotate;
|
||||
|
||||
// Color/Format metrics
|
||||
final String? pixelformat;
|
||||
final String? hwPixelformat;
|
||||
final String? colormatrix;
|
||||
final String? primaries;
|
||||
final String? gamma;
|
||||
|
||||
// HDR metadata
|
||||
final double? maxLuma;
|
||||
final double? minLuma;
|
||||
final double? maxCll;
|
||||
final double? maxFall;
|
||||
|
||||
// Audio metrics
|
||||
final String? audioCodec;
|
||||
final int? audioSamplerate;
|
||||
final String? audioChannels;
|
||||
final int? audioBitrate;
|
||||
|
||||
// Performance metrics
|
||||
final double? actualFps;
|
||||
final double? avsyncChange;
|
||||
final double? displayFps;
|
||||
final int? frameDropCount;
|
||||
final int? decoderFrameDropCount;
|
||||
|
||||
// Buffer metrics
|
||||
final int? cacheUsed;
|
||||
final double? cacheSpeed;
|
||||
final double? cacheDuration;
|
||||
|
||||
// App metrics
|
||||
final int? appMemoryBytes;
|
||||
final double? uiFps;
|
||||
|
||||
const PerformanceStats({
|
||||
this.videoCodec,
|
||||
this.videoWidth,
|
||||
this.videoHeight,
|
||||
this.videoFps,
|
||||
this.hwdecCurrent,
|
||||
this.videoBitrate,
|
||||
this.aspectName,
|
||||
this.rotate,
|
||||
this.pixelformat,
|
||||
this.hwPixelformat,
|
||||
this.colormatrix,
|
||||
this.primaries,
|
||||
this.gamma,
|
||||
this.maxLuma,
|
||||
this.minLuma,
|
||||
this.maxCll,
|
||||
this.maxFall,
|
||||
this.audioCodec,
|
||||
this.audioSamplerate,
|
||||
this.audioChannels,
|
||||
this.audioBitrate,
|
||||
this.actualFps,
|
||||
this.avsyncChange,
|
||||
this.displayFps,
|
||||
this.frameDropCount,
|
||||
this.decoderFrameDropCount,
|
||||
this.cacheUsed,
|
||||
this.cacheSpeed,
|
||||
this.cacheDuration,
|
||||
this.appMemoryBytes,
|
||||
this.uiFps,
|
||||
});
|
||||
|
||||
/// Creates an empty stats object (used as initial state).
|
||||
const PerformanceStats.empty()
|
||||
: videoCodec = null,
|
||||
videoWidth = null,
|
||||
videoHeight = null,
|
||||
videoFps = null,
|
||||
hwdecCurrent = null,
|
||||
videoBitrate = null,
|
||||
aspectName = null,
|
||||
rotate = null,
|
||||
pixelformat = null,
|
||||
hwPixelformat = null,
|
||||
colormatrix = null,
|
||||
primaries = null,
|
||||
gamma = null,
|
||||
maxLuma = null,
|
||||
minLuma = null,
|
||||
maxCll = null,
|
||||
maxFall = null,
|
||||
audioCodec = null,
|
||||
audioSamplerate = null,
|
||||
audioChannels = null,
|
||||
audioBitrate = null,
|
||||
actualFps = null,
|
||||
avsyncChange = null,
|
||||
displayFps = null,
|
||||
frameDropCount = null,
|
||||
decoderFrameDropCount = null,
|
||||
cacheUsed = null,
|
||||
cacheSpeed = null,
|
||||
cacheDuration = null,
|
||||
appMemoryBytes = null,
|
||||
uiFps = null;
|
||||
|
||||
/// Format video resolution as "WxH".
|
||||
String get resolution {
|
||||
if (videoWidth == null || videoHeight == null) return 'N/A';
|
||||
return '${videoWidth}x$videoHeight';
|
||||
}
|
||||
|
||||
/// Format video bitrate in Mbps.
|
||||
String get videoBitrateFormatted {
|
||||
if (videoBitrate == null || videoBitrate == 0) return 'N/A';
|
||||
final mbps = videoBitrate! / 1000000;
|
||||
return '${mbps.toStringAsFixed(1)} Mbps';
|
||||
}
|
||||
|
||||
/// Format audio bitrate in kbps.
|
||||
String get audioBitrateFormatted {
|
||||
if (audioBitrate == null || audioBitrate == 0) return 'N/A';
|
||||
final kbps = audioBitrate! / 1000;
|
||||
return '${kbps.toStringAsFixed(0)} kbps';
|
||||
}
|
||||
|
||||
/// Format audio sample rate in kHz.
|
||||
String get sampleRateFormatted {
|
||||
if (audioSamplerate == null) return 'N/A';
|
||||
final khz = audioSamplerate! / 1000;
|
||||
return '${khz.toStringAsFixed(1)} kHz';
|
||||
}
|
||||
|
||||
/// Format FPS with 2 decimal places.
|
||||
String get actualFpsFormatted {
|
||||
if (actualFps == null) return 'N/A';
|
||||
return actualFps!.toStringAsFixed(2);
|
||||
}
|
||||
|
||||
/// Format source FPS with 2 decimal places.
|
||||
String get videoFpsFormatted {
|
||||
if (videoFps == null) return 'N/A';
|
||||
return videoFps!.toStringAsFixed(2);
|
||||
}
|
||||
|
||||
/// Format A/V sync in milliseconds.
|
||||
String get avsyncFormatted {
|
||||
if (avsyncChange == null) return 'N/A';
|
||||
final ms = (avsyncChange! * 1000).round();
|
||||
return '${ms > 0 ? '+' : ''}${ms}ms';
|
||||
}
|
||||
|
||||
/// Format cache used in MB.
|
||||
String get cacheUsedFormatted {
|
||||
if (cacheUsed == null) return 'N/A';
|
||||
final mb = cacheUsed! / (1024 * 1024);
|
||||
return '${mb.toStringAsFixed(1)} MB';
|
||||
}
|
||||
|
||||
/// Format cache speed in MB/s.
|
||||
String get cacheSpeedFormatted {
|
||||
if (cacheSpeed == null) return 'N/A';
|
||||
final mbps = cacheSpeed! / (1024 * 1024);
|
||||
return '${mbps.toStringAsFixed(1)} MB/s';
|
||||
}
|
||||
|
||||
/// Format cache duration in seconds.
|
||||
String get cacheDurationFormatted {
|
||||
if (cacheDuration == null) return 'N/A';
|
||||
return '${cacheDuration!.toStringAsFixed(1)}s';
|
||||
}
|
||||
|
||||
/// Format display FPS.
|
||||
String get displayFpsFormatted {
|
||||
if (displayFps == null) return 'N/A';
|
||||
return displayFps!.toStringAsFixed(0);
|
||||
}
|
||||
|
||||
/// Format dropped frames count.
|
||||
String get droppedFramesFormatted {
|
||||
final total = (frameDropCount ?? 0) + (decoderFrameDropCount ?? 0);
|
||||
return total.toString();
|
||||
}
|
||||
|
||||
/// Format hardware decoding mode.
|
||||
String get hwdecFormatted {
|
||||
if (hwdecCurrent == null || hwdecCurrent!.isEmpty || hwdecCurrent == 'no') {
|
||||
return 'Software';
|
||||
}
|
||||
return hwdecCurrent!;
|
||||
}
|
||||
|
||||
/// Format app memory usage in MB.
|
||||
String get appMemoryFormatted {
|
||||
if (appMemoryBytes == null) return 'N/A';
|
||||
final mb = appMemoryBytes! / (1024 * 1024);
|
||||
return '${mb.toStringAsFixed(1)} MB';
|
||||
}
|
||||
|
||||
/// Format UI FPS with 1 decimal place.
|
||||
String get uiFpsFormatted {
|
||||
if (uiFps == null) return 'N/A';
|
||||
return uiFps!.toStringAsFixed(1);
|
||||
}
|
||||
|
||||
/// Format rotation in degrees.
|
||||
String get rotateFormatted {
|
||||
if (rotate == null || rotate == 0) return 'N/A';
|
||||
return '$rotate°';
|
||||
}
|
||||
|
||||
/// Format luminance value in cd/m².
|
||||
String get maxLumaFormatted {
|
||||
if (maxLuma == null) return 'N/A';
|
||||
return '${maxLuma!.toStringAsFixed(0)} cd/m²';
|
||||
}
|
||||
|
||||
/// Format minimum luminance value in cd/m².
|
||||
String get minLumaFormatted {
|
||||
if (minLuma == null) return 'N/A';
|
||||
return '${minLuma!.toStringAsFixed(4)} cd/m²';
|
||||
}
|
||||
|
||||
/// Format MaxCLL value in cd/m².
|
||||
String get maxCllFormatted {
|
||||
if (maxCll == null) return 'N/A';
|
||||
return '${maxCll!.toStringAsFixed(0)} cd/m²';
|
||||
}
|
||||
|
||||
/// Format MaxFALL value in cd/m².
|
||||
String get maxFallFormatted {
|
||||
if (maxFall == null) return 'N/A';
|
||||
return '${maxFall!.toStringAsFixed(0)} cd/m²';
|
||||
}
|
||||
|
||||
/// Check if HDR metadata is available.
|
||||
bool get hasHdrMetadata {
|
||||
return maxLuma != null || maxCll != null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io' show ProcessInfo;
|
||||
|
||||
import 'package:flutter/scheduler.dart';
|
||||
|
||||
import '../../../../mpv/mpv.dart';
|
||||
import '../../../../utils/app_logger.dart';
|
||||
import 'performance_stats.dart';
|
||||
|
||||
/// Service that polls MPV properties and provides performance stats via a stream.
|
||||
///
|
||||
/// Usage:
|
||||
/// ```dart
|
||||
/// final service = PerformanceStatsService(player);
|
||||
/// service.startPolling();
|
||||
/// service.statsStream.listen((stats) => print(stats.resolution));
|
||||
/// service.stopPolling();
|
||||
/// service.dispose();
|
||||
/// ```
|
||||
class PerformanceStatsService {
|
||||
final Player player;
|
||||
Timer? _pollingTimer;
|
||||
final _statsController = StreamController<PerformanceStats>.broadcast();
|
||||
|
||||
/// The interval between stats updates.
|
||||
static const pollInterval = Duration(milliseconds: 500);
|
||||
|
||||
// FPS tracking
|
||||
int _frameCount = 0;
|
||||
DateTime _lastFpsUpdate = DateTime.now();
|
||||
double? _currentUiFps;
|
||||
|
||||
PerformanceStatsService(this.player);
|
||||
|
||||
/// Stream of performance stats updates.
|
||||
Stream<PerformanceStats> get statsStream => _statsController.stream;
|
||||
|
||||
/// Start polling for stats at regular intervals.
|
||||
void startPolling() {
|
||||
_pollingTimer?.cancel();
|
||||
// Start FPS tracking
|
||||
_startFpsTracking();
|
||||
// Fetch immediately, then poll
|
||||
_fetchStats();
|
||||
_pollingTimer = Timer.periodic(pollInterval, (_) => _fetchStats());
|
||||
}
|
||||
|
||||
/// Start tracking UI frame rate.
|
||||
void _startFpsTracking() {
|
||||
_frameCount = 0;
|
||||
_lastFpsUpdate = DateTime.now();
|
||||
SchedulerBinding.instance.addPersistentFrameCallback(_onFrame);
|
||||
}
|
||||
|
||||
/// Called every frame to count FPS.
|
||||
void _onFrame(Duration timestamp) {
|
||||
_frameCount++;
|
||||
final now = DateTime.now();
|
||||
final elapsed = now.difference(_lastFpsUpdate);
|
||||
if (elapsed.inMilliseconds >= 1000) {
|
||||
_currentUiFps = _frameCount * 1000 / elapsed.inMilliseconds;
|
||||
_frameCount = 0;
|
||||
_lastFpsUpdate = now;
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop polling for stats.
|
||||
void stopPolling() {
|
||||
_pollingTimer?.cancel();
|
||||
_pollingTimer = null;
|
||||
}
|
||||
|
||||
/// Fetch all performance stats from MPV.
|
||||
Future<void> _fetchStats() async {
|
||||
try {
|
||||
// Fetch all properties in parallel for efficiency
|
||||
final results = await Future.wait([
|
||||
player.getProperty('video-codec'), // 0
|
||||
player.getProperty('video-params/w'), // 1
|
||||
player.getProperty('video-params/h'), // 2
|
||||
player.getProperty('container-fps'), // 3
|
||||
player.getProperty('estimated-vf-fps'), // 4
|
||||
player.getProperty('video-bitrate'), // 5
|
||||
player.getProperty('hwdec-current'), // 6
|
||||
player.getProperty('audio-codec-name'), // 7
|
||||
player.getProperty('audio-params/samplerate'), // 8
|
||||
player.getProperty('audio-params/hr-channels'), // 9
|
||||
player.getProperty('audio-bitrate'), // 10
|
||||
player.getProperty('total-avsync-change'), // 11
|
||||
player.getProperty('cache-used'), // 12
|
||||
player.getProperty('cache-speed'), // 13
|
||||
player.getProperty('display-fps'), // 14
|
||||
player.getProperty('frame-drop-count'), // 15
|
||||
player.getProperty('decoder-frame-drop-count'), // 16
|
||||
player.getProperty('demuxer-cache-duration'), // 17
|
||||
// Color/Format properties
|
||||
player.getProperty('video-params/pixelformat'), // 18
|
||||
player.getProperty('video-params/hw-pixelformat'), // 19
|
||||
player.getProperty('video-params/colormatrix'), // 20
|
||||
player.getProperty('video-params/primaries'), // 21
|
||||
player.getProperty('video-params/gamma'), // 22
|
||||
// HDR metadata
|
||||
player.getProperty('video-params/max-luma'), // 23
|
||||
player.getProperty('video-params/min-luma'), // 24
|
||||
player.getProperty('video-params/max-cll'), // 25
|
||||
player.getProperty('video-params/max-fall'), // 26
|
||||
// Other
|
||||
player.getProperty('video-params/aspect-name'), // 27
|
||||
player.getProperty('video-params/rotate'), // 28
|
||||
]);
|
||||
|
||||
// Get app memory usage
|
||||
int? appMemory;
|
||||
try {
|
||||
appMemory = ProcessInfo.currentRss;
|
||||
} catch (_) {
|
||||
// ProcessInfo not available on all platforms
|
||||
}
|
||||
|
||||
final stats = PerformanceStats(
|
||||
videoCodec: _formatCodecName(results[0]),
|
||||
videoWidth: _parseInt(results[1]),
|
||||
videoHeight: _parseInt(results[2]),
|
||||
videoFps: _parseDouble(results[3]),
|
||||
actualFps: _parseDouble(results[4]),
|
||||
videoBitrate: _parseInt(results[5]),
|
||||
hwdecCurrent: results[6],
|
||||
audioCodec: _formatCodecName(results[7]),
|
||||
audioSamplerate: _parseInt(results[8]),
|
||||
audioChannels: results[9],
|
||||
audioBitrate: _parseInt(results[10]),
|
||||
avsyncChange: _parseDouble(results[11]),
|
||||
cacheUsed: _parseInt(results[12]),
|
||||
cacheSpeed: _parseDouble(results[13]),
|
||||
displayFps: _parseDouble(results[14]),
|
||||
frameDropCount: _parseInt(results[15]),
|
||||
decoderFrameDropCount: _parseInt(results[16]),
|
||||
cacheDuration: _parseDouble(results[17]),
|
||||
// Color/Format properties
|
||||
pixelformat: results[18],
|
||||
hwPixelformat: results[19],
|
||||
colormatrix: results[20],
|
||||
primaries: results[21],
|
||||
gamma: results[22],
|
||||
// HDR metadata
|
||||
maxLuma: _parseDouble(results[23]),
|
||||
minLuma: _parseDouble(results[24]),
|
||||
maxCll: _parseDouble(results[25]),
|
||||
maxFall: _parseDouble(results[26]),
|
||||
// Other
|
||||
aspectName: results[27],
|
||||
rotate: _parseInt(results[28]),
|
||||
appMemoryBytes: appMemory,
|
||||
uiFps: _currentUiFps,
|
||||
);
|
||||
|
||||
_statsController.add(stats);
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to fetch performance stats', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a string to int, returning null if parsing fails.
|
||||
int? _parseInt(String? value) {
|
||||
if (value == null || value.isEmpty) return null;
|
||||
return int.tryParse(value);
|
||||
}
|
||||
|
||||
/// Parse a string to double, returning null if parsing fails.
|
||||
double? _parseDouble(String? value) {
|
||||
if (value == null || value.isEmpty) return null;
|
||||
return double.tryParse(value);
|
||||
}
|
||||
|
||||
/// Format codec name for display (uppercase common codecs).
|
||||
String? _formatCodecName(String? codec) {
|
||||
if (codec == null || codec.isEmpty) return null;
|
||||
// Common codec name mappings
|
||||
final upper = codec.toUpperCase();
|
||||
if (upper.contains('HEVC') || upper.contains('H265')) return 'HEVC';
|
||||
if (upper.contains('H264') || upper.contains('AVC')) return 'H.264';
|
||||
if (upper.contains('AV1')) return 'AV1';
|
||||
if (upper.contains('VP9')) return 'VP9';
|
||||
if (upper.contains('AAC')) return 'AAC';
|
||||
if (upper.contains('AC3') || upper.contains('AC-3')) return 'AC3';
|
||||
if (upper.contains('EAC3') || upper.contains('E-AC-3')) return 'EAC3';
|
||||
if (upper.contains('DTS')) return 'DTS';
|
||||
if (upper.contains('TRUEHD')) return 'TrueHD';
|
||||
if (upper.contains('FLAC')) return 'FLAC';
|
||||
if (upper.contains('OPUS')) return 'Opus';
|
||||
if (upper.contains('VORBIS')) return 'Vorbis';
|
||||
if (upper.contains('MP3')) return 'MP3';
|
||||
return codec;
|
||||
}
|
||||
|
||||
/// Dispose of the service and release resources.
|
||||
void dispose() {
|
||||
stopPolling();
|
||||
_statsController.close();
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ class TrackChapterControls extends StatelessWidget {
|
||||
final bool isRotationLocked;
|
||||
final bool isFullscreen;
|
||||
final bool isAlwaysOnTop;
|
||||
final VoidCallback? onTogglePIPMode;
|
||||
final VoidCallback? onCycleBoxFitMode;
|
||||
final VoidCallback? onToggleRotationLock;
|
||||
final VoidCallback? onToggleFullscreen;
|
||||
@@ -70,6 +71,7 @@ class TrackChapterControls extends StatelessWidget {
|
||||
required this.isFullscreen,
|
||||
required this.serverId,
|
||||
this.isAlwaysOnTop = false,
|
||||
this.onTogglePIPMode,
|
||||
this.onCycleBoxFitMode,
|
||||
this.onToggleRotationLock,
|
||||
this.onToggleFullscreen,
|
||||
@@ -288,6 +290,24 @@ class TrackChapterControls extends StatelessWidget {
|
||||
buttonIndex++;
|
||||
}
|
||||
|
||||
// Picture-in-Picture mode
|
||||
if (onTogglePIPMode != null) {
|
||||
final currentIndex = buttonIndex;
|
||||
buttons.add(
|
||||
_buildTrackButton(
|
||||
buttonIndex: currentIndex,
|
||||
icon: Symbols.picture_in_picture_alt,
|
||||
tooltip: t.videoControls.pipButton,
|
||||
semanticLabel: t.videoControls.pipButton,
|
||||
tracks: tracks,
|
||||
isMobile: isMobile,
|
||||
isDesktop: isDesktop,
|
||||
onPressed: onTogglePIPMode,
|
||||
),
|
||||
);
|
||||
buttonIndex++;
|
||||
}
|
||||
|
||||
// BoxFit mode button
|
||||
if (onCycleBoxFitMode != null) {
|
||||
final currentIndex = buttonIndex;
|
||||
@@ -372,6 +392,7 @@ class TrackChapterControls extends StatelessWidget {
|
||||
if (_hasSubtitles(tracks)) count++;
|
||||
if (chapters.isNotEmpty) count++;
|
||||
if (availableVersions.length > 1 && onSwitchVersion != null) count++;
|
||||
if (onTogglePIPMode != null) count++;
|
||||
if (onCycleBoxFitMode != null) count++;
|
||||
if (isMobile && !PlatformDetector.isTV()) count++; // Rotation lock (not on TV)
|
||||
if (isDesktop) count++; // Fullscreen
|
||||
|
||||
@@ -52,6 +52,24 @@ class _VolumeControlState extends State<VolumeControl> {
|
||||
/// Volume step size for keyboard adjustment.
|
||||
static const double _volumeStep = 5.0;
|
||||
|
||||
/// Maximum volume from settings (100-300).
|
||||
int _maxVolume = 100;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadMaxVolume();
|
||||
}
|
||||
|
||||
Future<void> _loadMaxVolume() async {
|
||||
final settings = await SettingsService.getInstance();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_maxVolume = settings.getMaxVolume();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _enterAdjustMode() {
|
||||
setState(() {
|
||||
_isAdjustMode = true;
|
||||
@@ -66,7 +84,7 @@ class _VolumeControlState extends State<VolumeControl> {
|
||||
|
||||
Future<void> _adjustVolume(double delta) async {
|
||||
final currentVolume = widget.player.state.volume;
|
||||
final newVolume = (currentVolume + delta).clamp(0.0, 100.0);
|
||||
final newVolume = (currentVolume + delta).clamp(0.0, _maxVolume.toDouble());
|
||||
widget.player.setVolume(newVolume);
|
||||
final settings = await SettingsService.getInstance();
|
||||
await settings.setVolume(newVolume);
|
||||
@@ -178,33 +196,58 @@ class _VolumeControlState extends State<VolumeControl> {
|
||||
Widget _buildVolumeSlider(double volume, bool isKeyboardMode) {
|
||||
// Show visual indicator when in adjust mode with keyboard
|
||||
final showAdjustIndicator = _isAdjustMode && isKeyboardMode;
|
||||
final maxVolumeDouble = _maxVolume.toDouble();
|
||||
|
||||
// Calculate 100% marker position as fraction of slider width
|
||||
// Only show marker if max volume > 100
|
||||
final showMarker = _maxVolume > 100;
|
||||
final markerPosition = showMarker ? (100.0 / maxVolumeDouble) : 0.0;
|
||||
|
||||
return SizedBox(
|
||||
width: 100,
|
||||
child: SliderTheme(
|
||||
data: SliderThemeData(
|
||||
trackHeight: showAdjustIndicator ? 4 : 3,
|
||||
thumbShape: RoundSliderThumbShape(enabledThumbRadius: showAdjustIndicator ? 8 : 6),
|
||||
overlayShape: const RoundSliderOverlayShape(overlayRadius: 12),
|
||||
),
|
||||
child: Semantics(
|
||||
label: t.videoControls.volumeSlider,
|
||||
slider: true,
|
||||
child: Slider(
|
||||
value: volume,
|
||||
min: 0.0,
|
||||
max: 100.0,
|
||||
onChanged: (value) {
|
||||
widget.player.setVolume(value);
|
||||
},
|
||||
onChangeEnd: (value) async {
|
||||
final settings = await SettingsService.getInstance();
|
||||
await settings.setVolume(value);
|
||||
},
|
||||
activeColor: Colors.white,
|
||||
inactiveColor: Colors.white.withValues(alpha: 0.3),
|
||||
child: Stack(
|
||||
alignment: Alignment.centerLeft,
|
||||
children: [
|
||||
// 100% marker (only shown if max > 100)
|
||||
if (showMarker)
|
||||
Positioned(
|
||||
left: 100 * markerPosition - 1, // Adjust for marker width
|
||||
child: Container(
|
||||
width: 2,
|
||||
height: 12,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.6),
|
||||
borderRadius: BorderRadius.circular(1),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Volume slider
|
||||
SliderTheme(
|
||||
data: SliderThemeData(
|
||||
trackHeight: showAdjustIndicator ? 4 : 3,
|
||||
thumbShape: RoundSliderThumbShape(enabledThumbRadius: showAdjustIndicator ? 8 : 6),
|
||||
overlayShape: const RoundSliderOverlayShape(overlayRadius: 12),
|
||||
),
|
||||
child: Semantics(
|
||||
label: t.videoControls.volumeSlider,
|
||||
slider: true,
|
||||
child: Slider(
|
||||
value: volume.clamp(0.0, maxVolumeDouble),
|
||||
min: 0.0,
|
||||
max: maxVolumeDouble,
|
||||
onChanged: (value) {
|
||||
widget.player.setVolume(value);
|
||||
},
|
||||
onChangeEnd: (value) async {
|
||||
final settings = await SettingsService.getInstance();
|
||||
await settings.setVolume(value);
|
||||
},
|
||||
activeColor: Colors.white,
|
||||
inactiveColor: Colors.white.withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
# Update icon cache
|
||||
if command -v gtk-update-icon-cache &> /dev/null; then
|
||||
gtk-update-icon-cache -f -t /usr/share/icons/hicolor || true
|
||||
fi
|
||||
|
||||
# Update desktop database
|
||||
if command -v update-desktop-database &> /dev/null; then
|
||||
update-desktop-database /usr/share/applications || true
|
||||
fi
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
# Update icon cache
|
||||
if command -v gtk-update-icon-cache &> /dev/null; then
|
||||
gtk-update-icon-cache -f -t /usr/share/icons/hicolor || true
|
||||
fi
|
||||
|
||||
# Update desktop database
|
||||
if command -v update-desktop-database &> /dev/null; then
|
||||
update-desktop-database /usr/share/applications || true
|
||||
fi
|
||||