Compare commits

..
59 Commits
Author SHA1 Message Date
github-actions[bot] 67a6bb29bf chore: bump version to 1.14.1 2026-01-13 21:59:48 +00:00
edde746 a87aa2968c fix: windows ui distortion
close #227
2026-01-13 22:54:43 +01:00
edde746 80cae9e220 Revert "Change dwExStyle to WS_EX_APPWINDOW, SetLayeredWindowAttributes, edit kWindowName String in MpvContainer"
This reverts commit 05f4c9e1f6.
2026-01-13 22:42:57 +01:00
github-actions[bot] 70f6e2142d chore: bump version to 1.14.0 2026-01-12 10:10:26 +00:00
edde746 37f025056c fix: iPad modal auto-dismiss on iPadOS 26.1+
close #224, credits to @Jon-Salmon for the workaround: https://github.com/flutter/flutter/issues/175606#issuecomment-3453392532
2026-01-12 11:05:57 +01:00
edde746andGitHub ea8ea6f059 Merge pull request #229 from ZhunCn/fix-discord-streaming
Workaround for Discord Screensharing on Windows
2026-01-12 03:28:07 +01:00
Randy Chen 05f4c9e1f6 Change dwExStyle to WS_EX_APPWINDOW, SetLayeredWindowAttributes, edit kWindowName String in MpvContainer 2026-01-11 09:33:07 -08:00
edde746 3a18d07593 fix: database path and directory creation
close #228
2026-01-11 16:26:39 +01:00
edde746 d2eaadb07d Merge branch 'fix/external-subs-blackscreen' 2026-01-11 16:06:34 +01:00
edde746 4db60bc7c2 fix: tab switching race conditions and trackpad swipe 2026-01-11 16:06:20 +01:00
edde746 27ff86f822 fix: pin browse tab chips while scrolling 2026-01-11 16:01:02 +01:00
edde746 c4789070d0 fix: apply mixed hub aspect ratio to hub detail grid 2026-01-11 14:27:57 +01:00
edde746 c189bef42c fix: mixed hub aspect ratio for non-episode items 2026-01-11 14:22:27 +01:00
edde746 aea4cfcf59 Merge branch 'feat/frame-rate-matching' 2026-01-11 13:04:01 +01:00
edde746 cffef8671e fix: black screen with external subtitles 2026-01-11 12:59:25 +01:00
edde746 8e5b9de471 feat: match content frame rate 2026-01-09 14:16:09 +01:00
edde746andGitHub a91a419ef3 Merge pull request #225 from cinsekrap/aaos-support
Add Android Automotive OS (AAOS) support
2026-01-09 04:34:53 +01:00
Nic Chambers-Parkes c71db8f9eb Add Android Automotive OS (AAOS) support
- Add android:appCategory="video" for AAOS video app compliance
  - Add uses-feature for android.hardware.type.automotive

  This enables Plezy to run on AAOS vehicles (e.g., Polestar 2).
  The system automatically handles driving restrictions for video apps.
2026-01-08 22:45:11 +00:00
edde746 abe0919324 feat: episode thumbnail display mode 2026-01-08 15:08:50 +01:00
edde746andGitHub f4d3dbd7d8 Merge pull request #222 from ulovecode/fix/include-spisodes
fix(tv): include episodes in video content filtering
2026-01-08 00:01:53 +01:00
zhubowen 570f1fdc58 feat(plex): improve video content filtering and directory parsing 2026-01-07 19:59:57 +08:00
zhubowen da1a4e7aa8 fix(tv): include episodes in video content filtering 2026-01-07 19:33:35 +08:00
edde746 5ed2532bf1 feat: global hubs with settings toggle
close #216 & #217
2026-01-06 23:23:03 +01:00
edde746 ed98a65c60 Merge branch 'linux-fixes' 2026-01-05 19:40:50 +01:00
edde746 562b54d1cb fix(linux): GL threading, state management, and animation fixes 2026-01-05 19:40:04 +01:00
edde746 85b056f3d0 fix(playlist): drag handle gesture conflict
close #167
2026-01-04 08:19:36 +01:00
edde746 da6ba9bd67 fix: always cache markers for auto-skip
close #210
2026-01-04 04:26:05 +01:00
edde746 6bfda5e6d4 fix: move review prompt 2026-01-03 12:23:56 +01:00
edde746 a10dfcc004 fix(pip): correct aspect ratio 2026-01-02 01:34:11 +01:00
edde746 08f8d2373a Merge branch 'dansl/main'
# Conflicts:
#	lib/widgets/video_controls/video_controls.dart
2026-01-02 01:24:15 +01:00
edde746 ce6686e634 fix(media-controls): prevent stale state overwrites 2026-01-02 01:11:50 +01:00
edde746 c53018b53b fix: hide controls in PiP mode 2026-01-02 01:01:24 +01:00
edde746 1191d8a438 refactor: format 2026-01-01 22:06:36 +01:00
edde746 1d67a5d992 feat: reactive watch state updates 2026-01-01 22:05:55 +01:00
Dan Long e3c1cba600 fix for translation 2025-12-31 00:55:25 -06:00
Dan Long a0f28b1dc7 fixes translation files 2025-12-31 00:49:12 -06:00
Dan Long 442899eecd Updated translations 2025-12-31 00:33:43 -06:00
Dan Long 76db3cb450 Merge branch 'main' of https://github.com/dansl/plezy 2025-12-31 00:23:47 -06:00
Dan Long bea485bddc Add Picture-in-Picture support for Android video playback
Implemented native Picture-in-Picture (PiP) mode for Android by updating the AndroidManifest, MainActivity, and introducing PipService and VideoPIPManager. Updated video player screen and controls to support toggling PiP mode, and added localized strings for the PiP button in multiple languages.

Relating to Issue #44: At this time PiP in Plezy only supports Android devices... iOS+MacOS will require significant changes to the video player for it to work properly...
2025-12-31 00:23:39 -06:00
edde746 b36e585fd7 fix(player): spacebar unpause no longer plays first episode 2025-12-30 20:12:14 +01:00
edde746 8b89529ac8 fix(player): preserve subtitles off across episodes 2025-12-30 20:11:16 +01:00
edde746 8b3b8ad596 fix(player): harden playback initialization against crashes 2025-12-29 20:47:35 +01:00
edde746 1d8a5ee23e fix: consistent continue watching behavior 2025-12-29 09:53:03 +01:00
edde746 4453eb995e feat(macOS): save window position 2025-12-27 12:53:27 +01:00
edde746 9e506d3f68 refactor: replace macos_window_utils 2025-12-27 12:38:38 +01:00
edde746 a698ab0930 docs: add Homebrew tap to README
close #29
2025-12-26 21:00:53 +01:00
edde746 b0d669d93a fix: main screen hero image subpixel gap 2025-12-26 18:49:27 +01:00
edde746 8dafac4ea5 fix: app update check 2025-12-26 18:19:07 +01:00
edde746 ef7fe85d5d fix: dmg name casing 2025-12-26 17:21:26 +01:00
github-actions[bot] b796491e60 chore: bump version to 1.13.0 2025-12-26 15:55:54 +00:00
edde746 2ad06c4dbc feat: better linux packaging
close #24
2025-12-26 15:27:59 +01:00
edde746 3494fbc5be feat: better packaging 2025-12-26 11:32:49 +01:00
edde746 c2ff56b1f1 feat: discord rpc
close #148
2025-12-26 08:33:52 +01:00
edde746 95436529c6 fix: observe speed property
close #193
2025-12-26 06:23:44 +01:00
edde746 ad7f381f54 fix: show disabled buttons instead of hiding them 2025-12-25 09:02:57 +01:00
edde746 d50a86501b feat: hold to 2x
close #192
2025-12-25 08:59:12 +01:00
edde746 d9bc7d6b86 feat(mobile): declutter controls and add stacking skips
close #189 and #190
2025-12-24 09:02:16 +01:00
edde746 8ab972691a feat: better package apks 2025-12-24 08:18:43 +01:00
edde746 47cb3f2614 fix: pass headers to mpv 2025-12-23 19:54:05 +01:00
86 changed files with 12454 additions and 16650 deletions
+63 -38
View File
@@ -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
+4 -3
View File
@@ -19,9 +19,10 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
### 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)
- [NixOS/Nix](https://github.com/mio-19/nurpkgs/tree/main/pkgs/plezy) - Community package by [@mio-19](https://github.com/mio-19) via `nur.repos.mio.plezy`
- [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
+10 -1
View File
@@ -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?)
@@ -24,6 +34,7 @@ class MpvPlayerCore(private val activity: Activity) :
companion object {
private const val TAG = "MpvPlayerCore"
private const val SHORT_VIDEO_LENGTH_MS = 300000L // 5 minutes
}
private var surfaceView: SurfaceView? = null
@@ -34,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 {
@@ -300,11 +316,203 @@ 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)
@@ -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)
}
}
-6
View File
@@ -20,8 +20,6 @@ PODS:
- path_provider_foundation (0.0.1):
- Flutter
- FlutterMacOS
- share_plus (0.0.1):
- Flutter
- shared_preferences_foundation (0.0.1):
- Flutter
- FlutterMacOS
@@ -72,7 +70,6 @@ DEPENDENCIES:
- 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`)
@@ -106,8 +103,6 @@ EXTERNAL SOURCES:
: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:
@@ -132,7 +127,6 @@ SPEC CHECKSUMS:
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
sqlite3: 8d708bc63e9f4ce48f0ad9d6269e478c5ced1d9b
+9 -3
View File
@@ -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)
@@ -487,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)
+22 -1
View File
@@ -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);
});
}
+8395 -15336
View File
File diff suppressed because it is too large Load Diff
+15 -3
View File
@@ -59,7 +59,13 @@
"appearance": "Appearance",
"videoPlayback": "Video Playback",
"advanced": "Advanced",
"useSeasonPostersDescription": "Show season poster instead of series poster for episodes",
"episodePosterMode": "Episode Poster Style",
"seriesPoster": "Series Poster",
"seriesPosterDescription": "Show the series poster for all episodes",
"seasonPoster": "Season Poster",
"seasonPosterDescription": "Show the season-specific poster for episodes",
"episodeThumbnail": "Episode Thumbnail",
"episodeThumbnailDescription": "Show 16:9 episode screenshot thumbnails",
"showHeroSectionDescription": "Display featured content carousel on home screen",
"secondsLabel": "Seconds",
"minutesLabel": "Minutes",
@@ -82,8 +88,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",
@@ -146,7 +153,11 @@
"maxVolume": "Maximum Volume",
"maxVolumeDescription": "Allow volume boost above 100% for quiet media",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Enter max volume (100-300)"
"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...",
@@ -245,6 +256,7 @@
"subtitlesButton": "Subtitles",
"chaptersButton": "Chapters",
"versionsButton": "Video versions",
"pipButton": "Picture-in-Picture mode",
"aspectRatioButton": "Aspect ratio",
"fullscreenButton": "Enter fullscreen",
"exitFullscreenButton": "Exit fullscreen",
+15 -3
View File
@@ -60,7 +60,13 @@
"appearance": "Darstellung",
"videoPlayback": "Videowiedergabe",
"advanced": "Erweitert",
"useSeasonPostersDescription": "Staffelposter statt Serienposter für Episoden anzeigen",
"episodePosterMode": "Episoden-Poster-Stil",
"seriesPoster": "Serienposter",
"seriesPosterDescription": "Zeige das Serienposter für alle Episoden",
"seasonPoster": "Staffelposter",
"seasonPosterDescription": "Zeige das staffelspezifische Poster für Episoden",
"episodeThumbnail": "Episoden-Miniatur",
"episodeThumbnailDescription": "Zeige 16:9 Episoden-Vorschaubilder",
"showHeroSectionDescription": "Bereich mit empfohlenen Inhalten auf der Startseite anzeigen",
"secondsLabel": "Sekunden",
"minutesLabel": "Minuten",
@@ -83,8 +89,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",
@@ -147,7 +154,11 @@
"maxVolume": "Maximale Lautstärke",
"maxVolumeDescription": "Lautstärke über 100% für leise Medien erlauben",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Maximale Lautstärke eingeben (100-300)"
"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...",
@@ -246,6 +257,7 @@
"subtitlesButton": "Untertitel",
"chaptersButton": "Kapitel",
"versionsButton": "Videoversionen",
"pipButton": "Bild-in-Bild Modus",
"aspectRatioButton": "Seitenverhältnis",
"fullscreenButton": "Vollbild aktivieren",
"exitFullscreenButton": "Vollbild verlassen",
+15 -3
View File
@@ -60,7 +60,13 @@
"appearance": "Aspetto",
"videoPlayback": "Riproduzione video",
"advanced": "Avanzate",
"useSeasonPostersDescription": "Mostra il poster della stagione invece del poster della serie per gli episodi",
"episodePosterMode": "Stile poster episodio",
"seriesPoster": "Poster della serie",
"seriesPosterDescription": "Mostra il poster della serie per tutti gli episodi",
"seasonPoster": "Poster della stagione",
"seasonPosterDescription": "Mostra il poster specifico della stagione per gli episodi",
"episodeThumbnail": "Miniatura episodio",
"episodeThumbnailDescription": "Mostra miniature 16:9 degli episodi",
"showHeroSectionDescription": "Visualizza il carosello dei contenuti in primo piano sulla schermata iniziale",
"secondsLabel": "Secondi",
"minutesLabel": "Minuti",
@@ -83,8 +89,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",
@@ -147,7 +154,11 @@
"maxVolume": "Volume massimo",
"maxVolumeDescription": "Consenti volume superiore al 100% per contenuti audio bassi",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Inserisci volume massimo (100-300)"
"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...",
@@ -246,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",
+15 -3
View File
@@ -60,7 +60,13 @@
"appearance": "외관",
"videoPlayback": "비디오 재생",
"advanced": "고급",
"useSeasonPostersDescription": "에피소드에 시리즈 포스터 대신 시즌 포스터 표시",
"episodePosterMode": "에피소드 포스터 스타일",
"seriesPoster": "시리즈 포스터",
"seriesPosterDescription": "모든 에피소드에 시리즈 포스터 표시",
"seasonPoster": "시즌 포스터",
"seasonPosterDescription": "에피소드에 시즌별 포스터 표시",
"episodeThumbnail": "에피소드 썸네일",
"episodeThumbnailDescription": "16:9 에피소드 스크린샷 썸네일 표시",
"showHeroSectionDescription": "홈 화면에 주요 콘텐츠 캐러셀(슬라이드) 표시",
"secondsLabel": "초",
"minutesLabel": "분",
@@ -83,8 +89,9 @@
"gridViewDescription": "항목을 그리드 레이아웃으로 표시합니다",
"listView": "목록 보기",
"listViewDescription": "항목을 목록 레이아웃으로 표시합니다",
"useSeasonPosters": "시즌 포스터 사용",
"showHeroSection": "주요 추천 영역 표시",
"useGlobalHubs": "Plex 홈 레이아웃 사용",
"useGlobalHubsDescription": "공식 Plex 클라이언트처럼 홈 페이지 허브를 표시합니다. 끄면 라이브러리별 추천이 대신 표시됩니다.",
"hardwareDecoding": "하드웨어 디코딩",
"hardwareDecodingDescription": "가능한 경우 하드웨어 가속을 사용합니다",
"bufferSize": "버퍼 크기",
@@ -147,7 +154,11 @@
"maxVolume": "최대 볼륨",
"maxVolumeDescription": "조용한 미디어를 위해 100% 이상의 볼륨 허용",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "최대 볼륨 입력 (100-300)"
"maxVolumeHint": "최대 볼륨 입력 (100-300)",
"discordRichPresence": "Discord Rich Presence",
"discordRichPresenceDescription": "Discord에서 시청 중인 콘텐츠 표시",
"matchContentFrameRate": "콘텐츠 프레임 레이트 맞춤",
"matchContentFrameRateDescription": "비디오 콘텐츠에 맞게 디스플레이 주사율을 조정하여 떨림을 줄이고 배터리를 절약합니다"
},
"search": {
"hint": "영화, 시리즈, 음악 등을 검색하세요...",
@@ -246,6 +257,7 @@
"subtitlesButton": "자막",
"chaptersButton": "챕터",
"versionsButton": "동영상 버전",
"pipButton": "픽처 인 픽처 모드",
"aspectRatioButton": "화면비율",
"fullscreenButton": "전체화면",
"exitFullscreenButton": "전체화면 종료",
+15 -3
View File
@@ -60,7 +60,13 @@
"appearance": "Uiterlijk",
"videoPlayback": "Video afspelen",
"advanced": "Geavanceerd",
"useSeasonPostersDescription": "Toon seizoenposter in plaats van serieposter voor afleveringen",
"episodePosterMode": "Aflevering poster stijl",
"seriesPoster": "Serie poster",
"seriesPosterDescription": "Toon de serie poster voor alle afleveringen",
"seasonPoster": "Seizoen poster",
"seasonPosterDescription": "Toon de seizoensspecifieke poster voor afleveringen",
"episodeThumbnail": "Aflevering miniatuur",
"episodeThumbnailDescription": "Toon 16:9 aflevering miniaturen",
"showHeroSectionDescription": "Toon uitgelichte inhoud carrousel op startscherm",
"secondsLabel": "Seconden",
"minutesLabel": "Minuten",
@@ -83,8 +89,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",
@@ -147,7 +154,11 @@
"maxVolume": "Maximaal volume",
"maxVolumeDescription": "Volume boven 100% toestaan voor stille media",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Voer maximaal volume in (100-300)"
"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...",
@@ -246,6 +257,7 @@
"subtitlesButton": "Ondertitels",
"chaptersButton": "Hoofdstukken",
"versionsButton": "Videoversies",
"pipButton": "Beeld-in-beeld modus",
"aspectRatioButton": "Beeldverhouding",
"fullscreenButton": "Volledig scherm activeren",
"exitFullscreenButton": "Volledig scherm verlaten",
+15 -3
View File
@@ -60,7 +60,13 @@
"appearance": "Utseende",
"videoPlayback": "Videouppspelning",
"advanced": "Avancerat",
"useSeasonPostersDescription": "Visa säsongsaffisch istället för serieaffisch för avsnitt",
"episodePosterMode": "Avsnittsaffisch-stil",
"seriesPoster": "Serieaffisch",
"seriesPosterDescription": "Visa seriens affisch för alla avsnitt",
"seasonPoster": "Säsongsaffisch",
"seasonPosterDescription": "Visa säsongens affisch för avsnitt",
"episodeThumbnail": "Avsnittsminiatyr",
"episodeThumbnailDescription": "Visa 16:9 skärmbild från avsnittet",
"showHeroSectionDescription": "Visa utvalda innehållskarusell på startsidan",
"secondsLabel": "Sekunder",
"minutesLabel": "Minuter",
@@ -83,8 +89,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",
@@ -147,7 +154,11 @@
"maxVolume": "Maximal volym",
"maxVolumeDescription": "Tillåt volym över 100% för tyst media",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Ange maximal volym (100-300)"
"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...",
@@ -246,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",
+15 -3
View File
@@ -60,7 +60,13 @@
"appearance": "外观",
"videoPlayback": "视频播放",
"advanced": "高级",
"useSeasonPostersDescription": "为剧集显示季海报而非剧集海报",
"episodePosterMode": "剧集海报样式",
"seriesPoster": "剧集海报",
"seriesPosterDescription": "为所有剧集显示剧集海报",
"seasonPoster": "季海报",
"seasonPosterDescription": "为剧集显示特定季的海报",
"episodeThumbnail": "剧集缩略图",
"episodeThumbnailDescription": "显示16:9剧集截图缩略图",
"showHeroSectionDescription": "在主屏幕上显示精选内容轮播区",
"secondsLabel": "秒",
"minutesLabel": "分钟",
@@ -83,8 +89,9 @@
"gridViewDescription": "以网格布局显示项目",
"listView": "列表视图",
"listViewDescription": "以列表布局显示项目",
"useSeasonPosters": "使用季海报",
"showHeroSection": "显示主要精选区",
"useGlobalHubs": "使用 Plex 主页布局",
"useGlobalHubsDescription": "显示与官方 Plex 客户端相同的主页推荐。关闭时将显示按媒体库分类的推荐。",
"hardwareDecoding": "硬件解码",
"hardwareDecodingDescription": "如果可用,使用硬件加速",
"bufferSize": "缓冲区大小",
@@ -147,7 +154,11 @@
"maxVolume": "最大音量",
"maxVolumeDescription": "允许音量超过 100% 以适应安静的媒体",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "输入最大音量 (100-300)"
"maxVolumeHint": "输入最大音量 (100-300)",
"discordRichPresence": "Discord 动态状态",
"discordRichPresenceDescription": "在 Discord 上显示您正在观看的内容",
"matchContentFrameRate": "匹配内容帧率",
"matchContentFrameRateDescription": "调整显示刷新率以匹配视频内容,减少画面抖动并节省电量"
},
"search": {
"hint": "搜索电影、系列、音乐...",
@@ -246,6 +257,7 @@
"subtitlesButton": "字幕",
"chaptersButton": "章节",
"versionsButton": "视频版本",
"pipButton": "画中画模式",
"aspectRatioButton": "宽高比",
"fullscreenButton": "进入全屏",
"exitFullscreenButton": "退出全屏",
+25 -78
View File
@@ -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';
@@ -30,6 +30,7 @@ import 'services/data_aggregation_service.dart';
import 'services/in_app_review_service.dart';
import 'services/server_registry.dart';
import 'services/download_manager_service.dart';
import 'services/pip_service.dart';
import 'services/download_storage_service.dart';
import 'services/plex_api_cache.dart';
import 'database/app_database.dart';
@@ -39,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();
@@ -60,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)
@@ -90,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
@@ -281,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);
@@ -411,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
+69
View File
@@ -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();
}
}
+1
View File
@@ -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',
+10 -3
View File
@@ -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? ?? '',
+46 -10
View File
@@ -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
+9 -1
View File
@@ -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;
-15
View File
@@ -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});
}
}
+22 -7
View File
@@ -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
// ============================================
+48 -13
View File
@@ -305,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>(
@@ -354,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) {
@@ -399,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) {
@@ -410,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
@@ -556,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();
@@ -571,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
// ============================================
+43 -2
View File
@@ -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.
@@ -168,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();
}
+32 -7
View File
@@ -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;
}
}
}
+60 -31
View File
@@ -22,6 +22,8 @@ import '../providers/settings_provider.dart';
import '../mixins/refreshable.dart';
import '../i18n/strings.g.dart';
import '../mixins/item_updatable.dart';
import '../mixins/watch_state_aware.dart';
import '../utils/watch_state_notifier.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
@@ -42,7 +44,7 @@ class DiscoverScreen extends StatefulWidget {
}
class _DiscoverScreenState extends State<DiscoverScreen>
with Refreshable, FullRefreshable, ItemUpdatable, SingleTickerProviderStateMixin {
with Refreshable, FullRefreshable, ItemUpdatable, WatchStateAware, SingleTickerProviderStateMixin {
static const Duration _heroAutoScrollDuration = Duration(seconds: 8);
@override
@@ -66,6 +68,28 @@ class _DiscoverScreenState extends State<DiscoverScreen>
late AnimationController _indicatorAnimationController;
bool _isAutoScrollPaused = false;
// WatchStateAware: watch on-deck items and their parent shows/seasons
@override
Set<String>? get watchedRatingKeys {
final keys = <String>{};
for (final item in _onDeck) {
keys.add(item.ratingKey);
if (item.parentRatingKey != null) {
keys.add(item.parentRatingKey!);
}
if (item.grandparentRatingKey != null) {
keys.add(item.grandparentRatingKey!);
}
}
return keys;
}
@override
void onWatchStateChanged(WatchStateEvent event) {
// Refresh continue watching when any relevant item changes
_refreshContinueWatching();
}
// Hub navigation keys
GlobalKey<HubSectionState>? _continueWatchingHubKey;
final List<GlobalKey<HubSectionState>> _hubKeys = [];
@@ -455,16 +479,25 @@ class _DiscoverScreenState extends State<DiscoverScreen>
});
try {
appLogger.d('Fetching onDeck and hubs from all Plex servers');
appLogger.d('Fetching onDeck and global hubs from all Plex servers');
final multiServerProvider = Provider.of<MultiServerProvider>(context, listen: false);
if (!multiServerProvider.hasConnectedServers) {
throw Exception('No servers available');
}
// Start OnDeck and libraries fetch in parallel
// Get hidden libraries for filtering
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(context, listen: false);
// Get settings for hub mode preference
final settingsProvider = Provider.of<SettingsProvider>(context, listen: false);
// Start OnDeck and hubs fetch in parallel
final onDeckFuture = multiServerProvider.aggregationService.getOnDeckFromAllServers(limit: 20);
final librariesFuture = multiServerProvider.aggregationService.getLibrariesFromAllServersGrouped();
final hubsFuture = multiServerProvider.aggregationService.getHubsFromAllServers(
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
useGlobalHubs: settingsProvider.useGlobalHubs,
);
// Wait for OnDeck to complete and show it immediately
final onDeck = await onDeckFuture;
@@ -487,32 +520,22 @@ class _DiscoverScreenState extends State<DiscoverScreen>
_heroController.jumpToPage(0);
}
// Wait for libraries and then fetch hubs
final librariesByServer = await librariesFuture;
// Wait for global hubs
final allHubs = await hubsFuture;
if (!mounted) return;
// Get hidden libraries to filter from hubs
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(context, listen: false);
// Fetch hubs using the pre-fetched libraries and hidden keys
final allHubs = await multiServerProvider.aggregationService.getHubsFromAllServers(
librariesByServer: librariesByServer,
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
);
// Filter out duplicate hubs that we already fetch separately
// Filter out Continue Watching / On Deck hubs (handled separately in hero section)
final filteredHubs = allHubs.where((hub) {
final hubId = hub.hubIdentifier?.toLowerCase() ?? '';
final title = hub.title.toLowerCase();
// Skip "Continue Watching" and "On Deck" hubs (we handle these separately)
return !hubId.contains('ondeck') &&
!hubId.contains('continue') &&
!title.contains('continue watching') &&
!title.contains('on deck');
}).toList();
appLogger.d('Received ${onDeck.length} on deck items and ${filteredHubs.length} hubs from all servers');
appLogger.d('Received ${onDeck.length} on deck items and ${filteredHubs.length} global hubs from all servers');
if (!mounted) return;
setState(() {
_hubs = filteredHubs;
@@ -1255,20 +1278,26 @@ class _DiscoverScreenState extends State<DiscoverScreen>
Container(color: Theme.of(context).colorScheme.surfaceContainerHighest),
// Gradient Overlay - blends into scaffold background
Builder(
builder: (context) {
final bgColor = Theme.of(context).scaffoldBackgroundColor;
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, bgColor.withValues(alpha: 0.9), bgColor],
stops: const [0.5, 0.85, 1.0],
Positioned(
top: 0,
left: 0,
right: 0,
bottom: -1, // Extend 1px past to prevent subpixel gap
child: Builder(
builder: (context) {
final bgColor = Theme.of(context).scaffoldBackgroundColor;
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, bgColor.withValues(alpha: 0.9), bgColor],
stops: const [0.5, 0.85, 1.0],
),
),
),
);
},
);
},
),
),
// Content with responsive alignment
+32 -5
View File
@@ -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,
);
},
),
],
);
+21 -10
View File
@@ -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;
}
}
+69
View File
@@ -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 {
+58 -1
View File
@@ -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();
+9 -5
View File
@@ -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),
),
),
),
+20 -2
View File
@@ -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,
+75 -11
View File
@@ -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';
@@ -61,6 +62,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _downloadOnWifiOnly = false;
bool _videoPlayerNavigationEnabled = false;
int _maxVolume = 100;
bool _enableDiscordRPC = false;
bool _matchContentFrameRate = false;
// Update checking state
bool _isCheckingForUpdate = false;
@@ -92,6 +95,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
_downloadOnWifiOnly = _settingsService.getDownloadOnWifiOnly();
_videoPlayerNavigationEnabled = _settingsService.getVideoPlayerNavigationEnabled();
_maxVolume = _settingsService.getMaxVolume();
_enableDiscordRPC = _settingsService.getEnableDiscordRPC();
_matchContentFrameRate = _settingsService.getMatchContentFrameRate();
_isLoading = false;
});
}
@@ -186,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(),
);
},
),
@@ -210,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);
},
);
},
),
],
),
);
@@ -239,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),
@@ -292,6 +321,18 @@ class _SettingsScreenState extends State<SettingsScreen> {
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),
@@ -612,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),
@@ -1282,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 {
+280 -174
View File
@@ -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';
@@ -90,6 +93,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
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;
@@ -103,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)
@@ -394,9 +399,18 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
});
// Listen to playback restart to detect first frame ready
_playbackRestartSubscription = player!.streams.playbackRestart.listen((_) {
_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();
}
});
@@ -430,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;
@@ -456,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;
@@ -556,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
@@ -665,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
@@ -672,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,
@@ -689,7 +731,15 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
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) {
@@ -705,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!,
@@ -714,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)));
@@ -773,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(() {
@@ -964,6 +1037,14 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_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');
@@ -1012,17 +1093,19 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// 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 && !_completionTriggered) {
_completionTriggered = true;
// On Linux, show the Flutter layer so the overlay is visible
if (Platform.isLinux) {
player?.setControlsVisible(true);
}
setState(() {
_showPlayNextDialog = true;
_autoPlayCountdown = 5;
@@ -1351,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) {
@@ -1404,6 +1490,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_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);
@@ -1497,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,
@@ -1522,142 +1611,159 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
},
),
),
// Netflix-style auto-play overlay
if (_showPlayNextDialog && _nextEpisode != null)
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: [
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),
),
],
],
);
},
),
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: 12),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: _cancelAutoPlay,
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: BorderSide(color: Colors.white.withValues(alpha: 0.5)),
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: Text(t.dialog.cancel),
),
),
const SizedBox(width: 8),
Expanded(
child: FilledButton(
onPressed: _playNext,
style: FilledButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
// 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: [
Text('$_autoPlayCountdown'),
const SizedBox(width: 4),
const AppIcon(Symbols.play_arrow_rounded, fill: 1, size: 18),
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),
),
],
],
);
},
),
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,
),
],
),
),
),
],
),
],
),
),
),
// Buffering indicator (also shows during initial load, but not when exiting)
ValueListenableBuilder<bool>(
valueListenable: _isBuffering,
builder: (context, isBuffering, child) {
return ValueListenableBuilder<bool>(
valueListenable: _hasFirstFrame,
builder: (context, hasFrame, child) {
// Don't show spinner when exiting (just black overlay)
// Show spinner when (buffering OR loading) AND NOT exiting
if ((!isBuffering && hasFrame) || _isExiting.value) 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),
],
),
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: _cancelAutoPlay,
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: BorderSide(color: Colors.white.withValues(alpha: 0.5)),
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: Text(t.dialog.cancel),
),
),
const SizedBox(width: 8),
Expanded(
child: FilledButton(
onPressed: _playNext,
style: FilledButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
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),
],
),
),
),
],
),
],
),
),
);
},
),
// 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),
),
),
],
),
);
},
);
},
);
+96 -4
View File
@@ -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;
}
+408
View File
@@ -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;
}
}
}
+2 -5
View File
@@ -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';
+5 -52
View File
@@ -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);
}
}
+3 -1
View File
@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:in_app_review/in_app_review.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -40,6 +41,8 @@ class InAppReviewService {
if (!isEnabled) return;
_sessionStartTime = DateTime.now();
appLogger.d('In-app review: Session started');
// Prompt checks should run while the app is in the foreground.
unawaited(maybeRequestReview());
}
/// End the current session and check if it qualifies
@@ -53,7 +56,6 @@ class InAppReviewService {
if (sessionDuration >= _minimumSessionDuration) {
await _incrementQualifyingSessions();
appLogger.d('In-app review: Qualifying session ended (${sessionDuration.inMinutes} minutes)');
await maybeRequestReview();
} else {
appLogger.d('In-app review: Session too short (${sessionDuration.inMinutes} minutes)');
}
+14 -50
View File
@@ -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);
}
}
+16
View File
@@ -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() {}
}
+96
View File
@@ -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;
}
}
+2 -1
View File
@@ -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
+35
View File
@@ -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);
}
+126 -125
View File
@@ -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) {
@@ -780,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});
@@ -951,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);
@@ -1016,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
@@ -1123,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
@@ -1261,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();
@@ -1297,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');
}
+54 -8
View File
@@ -13,6 +13,8 @@ enum LibraryDensity { compact, normal, comfortable }
enum ViewMode { grid, list }
enum EpisodePosterMode { seriesPoster, seasonPoster, episodeThumbnail }
class SettingsService extends BaseSharedPreferencesService {
static const String _keyThemeMode = 'theme_mode';
static const String _keyEnableDebugLogging = 'enable_debug_logging';
@@ -25,11 +27,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';
@@ -54,6 +58,8 @@ class SettingsService extends BaseSharedPreferencesService {
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._();
@@ -151,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
@@ -169,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);
@@ -894,6 +919,24 @@ class SettingsService extends BaseSharedPreferencesService {
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([
@@ -908,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),
@@ -933,6 +977,8 @@ class SettingsService extends BaseSharedPreferencesService {
prefs.remove(_keyShowPerformanceOverlay),
prefs.remove(_keyMpvConfigEntries),
prefs.remove(_keyMpvConfigPresets),
prefs.remove(_keyEnableDiscordRPC),
prefs.remove(_keyMatchContentFrameRate),
]);
}
@@ -957,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(),
+44
View File
@@ -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);
}
}
+8 -1
View File
@@ -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;
+19 -1
View File
@@ -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>(
+3 -3
View File
@@ -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);
}
+144
View File
@@ -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;
}
}
+34 -10
View File
@@ -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,
),
),
);
+48 -9
View File
@@ -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
@@ -119,6 +121,7 @@ class MediaCardState extends State<MediaCard> {
widget.item,
onRefresh: widget.onRefresh,
isOffline: widget.isOffline,
playDirectly: widget.isInContinueWatching,
);
if (!context.mounted) return;
@@ -168,6 +171,7 @@ class MediaCardState extends State<MediaCard> {
onLongPress: _showContextMenu,
isOffline: widget.isOffline,
localPosterPath: localPosterPath,
mixedHubContext: widget.mixedHubContext,
)
: _MediaCardList(
item: widget.item,
@@ -204,6 +208,7 @@ class _MediaCardGrid extends StatelessWidget {
final VoidCallback onLongPress;
final bool isOffline;
final String? localPosterPath;
final bool mixedHubContext;
const _MediaCardGrid({
required this.item,
@@ -214,6 +219,7 @@ class _MediaCardGrid extends StatelessWidget {
required this.onLongPress,
this.isOffline = false,
this.localPosterPath,
this.mixedHubContext = false,
});
@override
@@ -268,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),
],
@@ -296,7 +302,7 @@ class _MediaCardList extends StatelessWidget {
this.localPosterPath,
});
double get _posterWidth {
double _basePosterWidth() {
switch (density) {
case LibraryDensity.compact:
return 80;
@@ -307,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 {
@@ -466,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(
@@ -544,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;
@@ -561,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),
+10 -4
View File
@@ -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,
);
}
+14 -2
View File
@@ -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,
);
+11
View File
@@ -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),
);
+6 -3
View File
@@ -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
@@ -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;
@@ -95,6 +96,7 @@ class DesktopVideoControls extends StatefulWidget {
this.subtitleSyncOffset = 0,
this.isFullscreen = false,
this.isAlwaysOnTop = false,
this.onTogglePIPMode,
this.onCycleBoxFitMode,
this.onToggleFullscreen,
this.onToggleAlwaysOnTop,
@@ -524,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';
@@ -128,26 +126,14 @@ class MobileVideoControls extends StatelessWidget {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Previous episode button (hidden when unavailable)
if (onPrevious != null) ...[
_buildCircularButton(
semanticLabel: t.videoControls.previousButton,
icon: Symbols.skip_previous_rounded,
iconSize: 48,
onPressed: onPrevious!,
),
const SizedBox(width: 16),
],
// 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,
@@ -162,26 +148,14 @@ 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,
),
// Next episode button (hidden when unavailable)
if (onNext != null) ...[
const SizedBox(width: 16),
_buildCircularButton(
semanticLabel: t.videoControls.nextButton,
icon: Symbols.skip_next_rounded,
iconSize: 48,
onPressed: onNext!,
),
],
],
);
},
@@ -229,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(
@@ -238,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,
),
File diff suppressed because it is too large Load Diff
@@ -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
+10
View File
@@ -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
+10
View File
@@ -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
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
import os
import re
import subprocess
import shutil
from pathlib import Path
# Paths
SCRIPT_DIR = Path(__file__).parent.resolve()
PROJECT_ROOT = SCRIPT_DIR.parent.parent
BUILD_DIR = PROJECT_ROOT / "build/linux/x64/release/bundle"
OUTPUT_DIR = Path(os.environ.get("OUTPUT_DIR", PROJECT_ROOT))
# Package metadata
METADATA = {
"name": "plezy",
"license": "Proprietary",
"vendor": "edde746",
"maintainer": "edde746 <noreply@github.com>",
"url": "https://github.com/edde746/plezy",
"description": "A modern Plex client for desktop and mobile",
}
# Icon sizes to generate
ICON_SIZES = [16, 32, 48, 64, 128, 256, 512]
# Distro-specific configuration
DISTROS = {
"deb": {
"type": "deb",
"arch": "amd64",
"category": "video",
"ext": "deb",
"compression": ["--deb-compression", "xz", "--deb-priority", "optional"],
"depends": [
"libgtk-3-0",
"libmpv2 | libmpv1",
"libepoxy0",
"libkeybinder-3.0-0",
"libasound2",
"libglib2.0-0",
],
},
"rpm": {
"type": "rpm",
"arch": "x86_64",
"category": "Multimedia",
"ext": "rpm",
"compression": ["--rpm-compression", "xzmt"],
"depends": [
"gtk3",
"mpv-libs",
"libepoxy",
"keybinder3",
"alsa-lib",
"glib2",
],
},
"pacman": {
"type": "pacman",
"arch": "x86_64",
"category": None,
"ext": "pkg.tar.zst",
"compression": ["--pacman-compression", "zstd"],
"depends": [
"gtk3",
"mpv",
"libepoxy",
"keybinder3",
"alsa-lib",
"glib2",
],
},
}
def get_version() -> str:
"""Extract version from pubspec.yaml."""
pubspec = PROJECT_ROOT / "pubspec.yaml"
content = pubspec.read_text()
match = re.search(r"^version:\s*(.+)$", content, re.MULTILINE)
if not match:
raise RuntimeError("Could not find version in pubspec.yaml")
return match.group(1).split("+")[0]
def generate_icons():
"""Generate icons at multiple sizes using ImageMagick."""
print("Generating icons...")
source = PROJECT_ROOT / "assets/plezy.png"
for size in ICON_SIZES:
dest_dir = SCRIPT_DIR / f"icons/{size}x{size}"
dest_dir.mkdir(parents=True, exist_ok=True)
dest = dest_dir / "plezy.png"
# Try magick (ImageMagick 7) first, then convert (ImageMagick 6)
for cmd in ["magick", "convert"]:
if shutil.which(cmd):
subprocess.run([cmd, str(source), "-resize", f"{size}x{size}", str(dest)], check=True)
break
else:
print(f"Warning: ImageMagick not found, copying original icon for {size}x{size}")
shutil.copy(source, dest)
def get_file_mappings() -> list[str]:
"""Get file mappings for fpm."""
mappings = [
f"{BUILD_DIR}/=/opt/plezy/",
f"{SCRIPT_DIR}/com.edde746.plezy.desktop=/usr/share/applications/com.edde746.plezy.desktop",
f"{SCRIPT_DIR}/plezy.sh=/usr/bin/plezy",
]
for size in ICON_SIZES:
mappings.append(
f"{SCRIPT_DIR}/icons/{size}x{size}/plezy.png=/usr/share/icons/hicolor/{size}x{size}/apps/plezy.png"
)
return mappings
def build_package(distro: str, version: str):
"""Build a package for the specified distro."""
config = DISTROS[distro]
output_file = OUTPUT_DIR / f"{METADATA['name']}-linux.{config['ext']}"
print(f"Building .{config['ext']} package...")
cmd = [
"fpm",
"-s", "dir",
"-t", config["type"],
"-n", METADATA["name"],
"-v", version,
"--iteration", "1",
"--license", METADATA["license"],
"--vendor", METADATA["vendor"],
"--maintainer", METADATA["maintainer"],
"--url", METADATA["url"],
"--description", METADATA["description"],
"--architecture", config["arch"],
]
if config["category"]:
cmd.extend(["--category", config["category"]])
for dep in config["depends"]:
cmd.extend(["--depends", dep])
cmd.extend(config["compression"])
cmd.extend([
"--after-install", str(SCRIPT_DIR / "after-install.sh"),
"--after-remove", str(SCRIPT_DIR / "after-remove.sh"),
"--package", str(output_file),
])
cmd.extend(get_file_mappings())
subprocess.run(cmd, check=True)
print(f"Created: {output_file}")
def main():
# Verify build exists
if not BUILD_DIR.exists():
print(f"Error: Build directory not found at {BUILD_DIR}")
print("Please run 'flutter build linux --release' first")
exit(1)
version = get_version()
print(f"Building packages for {METADATA['name']} version {version}")
# Make scripts executable
for script in ["plezy.sh", "after-install.sh", "after-remove.sh"]:
(SCRIPT_DIR / script).chmod(0o755)
# Generate icons
generate_icons()
# Build all packages
for distro in DISTROS:
build_package(distro, version)
print("\nAll packages built successfully!")
for f in OUTPUT_DIR.glob(f"{METADATA['name']}-linux.*"):
print(f" {f}")
if __name__ == "__main__":
main()
+10
View File
@@ -0,0 +1,10 @@
[Desktop Entry]
Type=Application
Name=Plezy
Comment=A modern Plex client for desktop and mobile
Exec=/opt/plezy/plezy
Icon=plezy
Terminal=false
Categories=AudioVideo;Video;Player;
Keywords=plex;media;streaming;video;
StartupWMClass=plezy
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
cd /opt/plezy
exec ./plezy "$@"
+10 -3
View File
@@ -135,6 +135,10 @@ bool MpvPlayer::Initialize(GtkGLArea* gl_area) {
}
void MpvPlayer::Dispose() {
// Lock mutex to prevent race with OnMpvWakeup callbacks.
// This ensures no new event processing starts during dispose.
std::lock_guard<std::mutex> lock(callback_mutex_);
// Guard against multiple dispose calls (double-free protection)
if (disposed_.exchange(true)) {
return; // Already disposed
@@ -282,15 +286,18 @@ void MpvPlayer::RequestRedraw() {
void MpvPlayer::OnMpvWakeup(void* ctx) {
auto* player = static_cast<MpvPlayer*>(ctx);
// Don't schedule if already disposed
// Don't schedule if already disposed (atomic check for early exit)
if (player->disposed_) return;
// Schedule event processing on the main thread.
g_idle_add(
[](gpointer data) -> gboolean {
auto* player = static_cast<MpvPlayer*>(data);
// Check disposed again when callback runs
if (!player->disposed_) {
// Check disposed - atomic ensures we see updated value.
// Don't lock mutex here - ProcessEvents() calls SendPropertyChange/SendEvent
// which lock callback_mutex_, causing deadlock if we hold it here.
if (!player->disposed_ && player->mpv_) {
player->ProcessEvents();
}
return G_SOURCE_REMOVE;
+67 -26
View File
@@ -31,6 +31,7 @@ static gboolean on_gl_render(GtkGLArea* area,
gpointer user_data);
static void on_gl_realize(GtkGLArea* area, gpointer user_data);
static void on_gl_unrealize(GtkGLArea* area, gpointer user_data);
static void on_gl_resize(GtkGLArea* area, gint width, gint height, gpointer user_data);
static void mpv_plugin_dispose(GObject* object) {
MpvPlugin* self = MPV_PLUGIN(object);
@@ -103,6 +104,7 @@ MpvPlugin* mpv_plugin_new(FlPluginRegistrar* registrar,
g_signal_connect(gl_area, "render", G_CALLBACK(on_gl_render), self);
g_signal_connect(gl_area, "realize", G_CALLBACK(on_gl_realize), self);
g_signal_connect(gl_area, "unrealize", G_CALLBACK(on_gl_unrealize), self);
g_signal_connect(gl_area, "resize", G_CALLBACK(on_gl_resize), self);
// Set up auto-render to false - we control when to render.
gtk_gl_area_set_auto_render(gl_area, FALSE);
@@ -132,6 +134,17 @@ static gboolean on_gl_render(GtkGLArea* area,
(void)context;
MpvPlugin* self = MPV_PLUGIN(user_data);
// Ensure GL context is current before any GL operations.
// Critical during fullscreen transitions and workspace switches (issue #202).
gtk_gl_area_make_current(area);
// Check for GL context errors (can happen during window state changes)
GError* error = gtk_gl_area_get_error(area);
if (error != nullptr) {
g_warning("MPV Plugin: GL context error in render: %s", error->message);
return FALSE; // Signal failure to GTK
}
if (!self->player || !self->player->IsInitialized() || !self->visible) {
// Clear to transparent when not showing video.
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
@@ -152,10 +165,41 @@ static gboolean on_gl_render(GtkGLArea* area,
GLint fbo = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &fbo);
// Render the video frame.
// Save GL state before MPV render (MPV modifies these and doesn't restore them)
// This prevents GL state pollution that corrupts Flutter's rendering.
GLint prev_viewport[4];
GLint prev_scissor_box[4];
GLboolean prev_blend, prev_scissor_test;
GLint prev_blend_src, prev_blend_dst;
glGetIntegerv(GL_VIEWPORT, prev_viewport);
glGetIntegerv(GL_SCISSOR_BOX, prev_scissor_box);
glGetBooleanv(GL_BLEND, &prev_blend);
glGetBooleanv(GL_SCISSOR_TEST, &prev_scissor_test);
glGetIntegerv(GL_BLEND_SRC_ALPHA, &prev_blend_src);
glGetIntegerv(GL_BLEND_DST_ALPHA, &prev_blend_dst);
// Set viewport and render the video frame.
glViewport(0, 0, width, height);
self->player->Render(width, height, fbo);
self->player->ClearRedrawFlag();
// Restore GL state after MPV render to prevent Flutter corruption.
glViewport(prev_viewport[0], prev_viewport[1], prev_viewport[2], prev_viewport[3]);
glScissor(prev_scissor_box[0], prev_scissor_box[1], prev_scissor_box[2], prev_scissor_box[3]);
if (prev_blend) {
glEnable(GL_BLEND);
} else {
glDisable(GL_BLEND);
}
if (prev_scissor_test) {
glEnable(GL_SCISSOR_TEST);
} else {
glDisable(GL_SCISSOR_TEST);
}
glBlendFunc(prev_blend_src, prev_blend_dst);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
return TRUE;
}
@@ -184,6 +228,13 @@ static void on_gl_unrealize(GtkGLArea* area, gpointer user_data) {
gtk_gl_area_make_current(area);
// Check if context is valid before disposing GL resources (issue #202)
GError* error = gtk_gl_area_get_error(area);
if (error != nullptr) {
g_warning("MPV Plugin: GL context error in unrealize: %s", error->message);
}
// Always try to dispose - Dispose() handles its own safety checks
if (self->player) {
self->player->Dispose();
}
@@ -191,6 +242,21 @@ static void on_gl_unrealize(GtkGLArea* area, gpointer user_data) {
g_message("MPV Plugin: GL area unrealized");
}
/// GtkGLArea resize callback.
static void on_gl_resize(GtkGLArea* area,
gint width,
gint height,
gpointer user_data) {
MpvPlugin* self = MPV_PLUGIN(user_data);
(void)width;
(void)height;
// Force a redraw when size changes to prevent lag during resize.
if (self->visible && self->player && self->player->IsInitialized()) {
gtk_gl_area_queue_render(area);
}
}
/// Method call handler.
static void mpv_plugin_handle_method_call(FlMethodChannel* channel,
FlMethodCall* method_call,
@@ -252,9 +318,7 @@ static void mpv_plugin_handle_method_call(FlMethodChannel* channel,
self->initialized = FALSE;
self->visible = FALSE;
gtk_widget_set_visible(GTK_WIDGET(self->gl_area), FALSE);
// Restore Flutter view opacity to 1.0 (may have been set to 0 by setControlsVisible)
if (self->flutter_view != nullptr) {
gtk_widget_set_opacity(self->flutter_view, 1.0);
// Force Flutter view to redraw
gtk_widget_queue_draw(self->flutter_view);
}
@@ -367,29 +431,6 @@ static void mpv_plugin_handle_method_call(FlMethodChannel* channel,
gtk_gl_area_queue_render(self->gl_area);
}
response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr));
}
} else if (strcmp(method, "setControlsVisible") == 0) {
// Set Flutter view opacity when controls are hidden/shown.
// This is a workaround for Flutter's lack of transparency support on Linux.
// When controls are hidden, setting opacity to 0 shows only the video
// while keeping the widget interactive for mouse events.
FlValue* controls_visible_value = fl_value_lookup_string(args, "visible");
if (controls_visible_value == nullptr ||
fl_value_get_type(controls_visible_value) != FL_VALUE_TYPE_BOOL) {
response = FL_METHOD_RESPONSE(fl_method_error_response_new(
"INVALID_ARGS", "Missing 'visible'", nullptr));
} else {
gboolean controls_visible = fl_value_get_bool(controls_visible_value);
// When controls are hidden, set Flutter view opacity to 0.
// When controls are visible, set opacity to 1.
// Using opacity keeps the widget interactive for mouse events.
if (self->flutter_view != nullptr) {
gtk_widget_set_opacity(self->flutter_view, controls_visible ? 1.0 : 0.0);
}
response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr));
}
} else if (strcmp(method, "isInitialized") == 0) {
+3 -2
View File
@@ -109,8 +109,9 @@ static void my_application_activate(GApplication* application) {
gtk_widget_set_hexpand(GTK_WIDGET(self->flutter_view), TRUE);
gtk_widget_set_vexpand(GTK_WIDGET(self->flutter_view), TRUE);
// Enable transparency for the Flutter view.
gtk_widget_set_app_paintable(GTK_WIDGET(self->flutter_view), TRUE);
// Set up RGBA visual for transparency support.
// Note: app_paintable is only set on the window (line 73), not on child widgets,
// to avoid redundant composition passes.
setup_rgba_visual(GTK_WIDGET(self->flutter_view));
// Enable transparent background for the Flutter view.
@@ -12,12 +12,10 @@ import flutter_webrtc
import gamepads_darwin
import hotkey_manager_macos
import in_app_review
import macos_window_utils
import os_media_controls
import package_info_plus
import path_provider_foundation
import screen_retriever_macos
import share_plus
import shared_preferences_foundation
import sqflite_darwin
import sqlite3_flutter_libs
@@ -33,12 +31,10 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
GamepadsDarwinPlugin.register(with: registry.registrar(forPlugin: "GamepadsDarwinPlugin"))
HotkeyManagerMacosPlugin.register(with: registry.registrar(forPlugin: "HotkeyManagerMacosPlugin"))
InAppReviewPlugin.register(with: registry.registrar(forPlugin: "InAppReviewPlugin"))
MacOSWindowUtilsPlugin.register(with: registry.registrar(forPlugin: "MacOSWindowUtilsPlugin"))
OsMediaControlsPlugin.register(with: registry.registrar(forPlugin: "OsMediaControlsPlugin"))
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin"))
SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin"))
Sqlite3FlutterLibsPlugin.register(with: registry.registrar(forPlugin: "Sqlite3FlutterLibsPlugin"))
-12
View File
@@ -17,8 +17,6 @@ PODS:
- HotKey
- in_app_review (2.0.0):
- FlutterMacOS
- macos_window_utils (1.0.0):
- FlutterMacOS
- os_media_controls (0.0.1):
- FlutterMacOS
- package_info_plus (0.0.1):
@@ -28,8 +26,6 @@ PODS:
- FlutterMacOS
- screen_retriever_macos (0.0.1):
- FlutterMacOS
- share_plus (0.0.1):
- FlutterMacOS
- shared_preferences_foundation (0.0.1):
- Flutter
- FlutterMacOS
@@ -78,12 +74,10 @@ DEPENDENCIES:
- gamepads_darwin (from `Flutter/ephemeral/.symlinks/plugins/gamepads_darwin/macos`)
- hotkey_manager_macos (from `Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos`)
- in_app_review (from `Flutter/ephemeral/.symlinks/plugins/in_app_review/macos`)
- macos_window_utils (from `Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos`)
- os_media_controls (from `Flutter/ephemeral/.symlinks/plugins/os_media_controls/macos`)
- package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`)
- path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin`)
- screen_retriever_macos (from `Flutter/ephemeral/.symlinks/plugins/screen_retriever_macos/macos`)
- share_plus (from `Flutter/ephemeral/.symlinks/plugins/share_plus/macos`)
- shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`)
- sqflite_darwin (from `Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin`)
- sqlite3_flutter_libs (from `Flutter/ephemeral/.symlinks/plugins/sqlite3_flutter_libs/darwin`)
@@ -114,8 +108,6 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos
in_app_review:
:path: Flutter/ephemeral/.symlinks/plugins/in_app_review/macos
macos_window_utils:
:path: Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos
os_media_controls:
:path: Flutter/ephemeral/.symlinks/plugins/os_media_controls/macos
package_info_plus:
@@ -124,8 +116,6 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin
screen_retriever_macos:
:path: Flutter/ephemeral/.symlinks/plugins/screen_retriever_macos/macos
share_plus:
:path: Flutter/ephemeral/.symlinks/plugins/share_plus/macos
shared_preferences_foundation:
:path: Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin
sqflite_darwin:
@@ -149,12 +139,10 @@ SPEC CHECKSUMS:
HotKey: 400beb7caa29054ea8d864c96f5ba7e5b4852277
hotkey_manager_macos: a4317849af96d2430fa89944d3c58977ca089fbe
in_app_review: 66e7680752b632d83f4f0e88b34d52ed303fbff4
macos_window_utils: 23f54331a0fd51eea9e0ed347253bf48fd379d1d
os_media_controls: c07c04c4afdf59dda0a3f398457a46823c4ce0ed
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
screen_retriever_macos: 452e51764a9e1cdb74b3c541238795849f21557f
share_plus: 510bf0af1a42cd602274b4629920c9649c52f4cc
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
sqlite3: 8d708bc63e9f4ce48f0ad9d6269e478c5ced1d9b
+8
View File
@@ -30,6 +30,8 @@
6AC86ED72EA70B4C0067BC66 /* plezy.icon in Resources */ = {isa = PBXBuildFile; fileRef = 6AC86ED62EA70B4C0067BC66 /* plezy.icon */; };
6AD8B1612ED7B50000E9E1B4 /* MpvPlayerCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AD8B1632ED7B50000E9E1B4 /* MpvPlayerCore.swift */; };
6AD8B1622ED7B50000E9E1B4 /* MpvPlayerPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AD8B1642ED7B50000E9E1B4 /* MpvPlayerPlugin.swift */; };
6AD8B1662ED7B50000E9E1B5 /* WindowUtilsPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AD8B1682ED7B50000E9E1B5 /* WindowUtilsPlugin.swift */; };
6AD8B1672ED7B50000E9E1B5 /* WindowDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AD8B1692ED7B50000E9E1B5 /* WindowDelegate.swift */; };
9AECA605E2E1BECE3CA5BD01 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 78F9F23331B540A25C4A70C7 /* Pods_Runner.framework */; };
FE52EE1D2D489FA88507D14E /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 84260356652A3270E664FED4 /* Pods_RunnerTests.framework */; };
/* End PBXBuildFile section */
@@ -86,6 +88,8 @@
6AC86ED62EA70B4C0067BC66 /* plezy.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = plezy.icon; sourceTree = "<group>"; };
6AD8B1632ED7B50000E9E1B4 /* MpvPlayerCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MpvPlayerCore.swift; sourceTree = "<group>"; };
6AD8B1642ED7B50000E9E1B4 /* MpvPlayerPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MpvPlayerPlugin.swift; sourceTree = "<group>"; };
6AD8B1682ED7B50000E9E1B5 /* WindowUtilsPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowUtilsPlugin.swift; sourceTree = "<group>"; };
6AD8B1692ED7B50000E9E1B5 /* WindowDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowDelegate.swift; sourceTree = "<group>"; };
78F9F23331B540A25C4A70C7 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
84260356652A3270E664FED4 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -196,6 +200,8 @@
children = (
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
6AD8B1682ED7B50000E9E1B5 /* WindowUtilsPlugin.swift */,
6AD8B1692ED7B50000E9E1B5 /* WindowDelegate.swift */,
6AD8B1652ED7B50000E9E1B4 /* MpvPlayer */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
@@ -460,6 +466,8 @@
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
6AD8B1612ED7B50000E9E1B4 /* MpvPlayerCore.swift in Sources */,
6AD8B1622ED7B50000E9E1B4 /* MpvPlayerPlugin.swift in Sources */,
6AD8B1662ED7B50000E9E1B5 /* WindowUtilsPlugin.swift in Sources */,
6AD8B1672ED7B50000E9E1B5 /* WindowDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
+20
View File
@@ -13,11 +13,31 @@ class MainFlutterWindow: NSWindow {
self.contentViewController = flutterViewController
self.setFrame(windowFrame, display: true)
// Apply initial window configuration BEFORE frame restoration
// This prevents the window from shrinking on launch
self.titlebarAppearsTransparent = true
self.titleVisibility = .hidden
self.styleMask.insert(.fullSizeContentView)
// Add forwarding toolbar for click-through in titlebar area
let toolbar = ForwardingToolbar(flutterViewController: flutterViewController)
self.toolbar = toolbar
// Register MPV player plugin for video playback
MpvPlayerPlugin.register(with: flutterViewController.registrar(forPlugin: "MpvPlayerPlugin"))
// Register window utils plugin for dynamic titlebar/fullscreen control from Dart
WindowUtilsPlugin.register(with: flutterViewController.registrar(forPlugin: "WindowUtilsPlugin"))
WindowUtilsPlugin.setWindow(self)
// Set custom traffic light positions using centralized values from plugin
WindowUtilsPlugin.setInitialTrafficLightPositions()
RegisterGeneratedPlugins(registry: flutterViewController)
// Enable window position/size persistence
self.setFrameAutosaveName("com.edde746.plezy.MainWindow")
super.awakeFromNib()
}
}
+1 -1
View File
@@ -213,7 +213,7 @@ class MpvPlayerCore: NSObject {
// Re-insert after background layer but before Flutter control views
layer.removeFromSuperlayer()
if let superlayer = window?.contentView?.layer {
superlayer.insertSublayer(layer, at: 1)
superlayer.insertSublayer(layer, at: 0)
}
}
+65
View File
@@ -0,0 +1,65 @@
import Cocoa
import FlutterMacOS
class WindowDelegate: NSObject, NSWindowDelegate {
weak var channel: FlutterMethodChannel?
weak var window: NSWindow?
// Hardcoded presentation options for fullscreen mode
// Auto-hide toolbar, menu bar, and dock when in fullscreen
private let fullScreenPresentationOptions: NSApplication.PresentationOptions = [
.fullScreen,
.autoHideToolbar,
.autoHideMenuBar,
.autoHideDock
]
// MARK: - Private Helpers
private func emit(_ method: String) {
channel?.invokeMethod(method, arguments: nil)
}
// MARK: - NSWindowDelegate
func window(_ window: NSWindow, willUseFullScreenPresentationOptions proposedOptions: NSApplication.PresentationOptions) -> NSApplication.PresentationOptions {
return fullScreenPresentationOptions
}
func windowWillEnterFullScreen(_ notification: Notification) {
guard let window = window else { return }
// Remove toolbar before entering fullscreen
window.toolbar = nil
// Show title and make titlebar opaque for native fullscreen look
window.titleVisibility = .visible
window.titlebarAppearsTransparent = false
// Reset traffic light positions to default
WindowUtilsPlugin.setTrafficLightPositions(custom: false, window: window)
// Notify Dart for state management only
emit("windowWillEnterFullScreen")
}
func windowDidEnterFullScreen(_ notification: Notification) {
emit("windowDidEnterFullScreen")
}
func windowWillExitFullScreen(_ notification: Notification) {
guard let window = window else { return }
// Hide title and make titlebar transparent BEFORE exiting
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
emit("windowWillExitFullScreen")
}
func windowDidExitFullScreen(_ notification: Notification) {
guard let window = window else { return }
// Restore toolbar
if let flutterVC = window.contentViewController {
let toolbar = ForwardingToolbar(flutterViewController: flutterVC)
window.toolbar = toolbar
}
// Restore custom traffic light positions
WindowUtilsPlugin.setTrafficLightPositions(custom: true, window: window)
emit("windowDidExitFullScreen")
}
}
+224
View File
@@ -0,0 +1,224 @@
import Cocoa
import FlutterMacOS
// MARK: - ForwardingView
// A view that forwards mouse events to the Flutter view controller
class ForwardingView: NSView {
weak var flutterViewController: NSViewController?
override func mouseDown(with event: NSEvent) {
flutterViewController?.mouseDown(with: event)
}
override func mouseUp(with event: NSEvent) {
flutterViewController?.mouseUp(with: event)
}
}
// MARK: - ForwardingToolbar
// A custom toolbar that forwards mouse events from the toolbar area to Flutter
class ForwardingToolbar: NSToolbar, NSToolbarDelegate {
let flutterViewController: NSViewController
init(flutterViewController: NSViewController) {
self.flutterViewController = flutterViewController
super.init(identifier: "ForwardingToolbar")
self.delegate = self
self.showsBaselineSeparator = false
// Prevent toolbar customization UI (the "rounded box")
self.allowsUserCustomization = false
self.allowsExtensionItems = false
if #available(macOS 15.0, *) {
self.allowsDisplayModeCustomization = false
}
}
func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
[.flexibleSpace, NSToolbarItem.Identifier("ForwardingItem")]
}
func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
toolbarDefaultItemIdentifiers(toolbar)
}
func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
if itemIdentifier == NSToolbarItem.Identifier("ForwardingItem") {
let item = NSToolbarItem(itemIdentifier: itemIdentifier)
item.isBordered = false // Remove the rounded box appearance
let view = ForwardingView()
view.flutterViewController = flutterViewController
view.widthAnchor.constraint(lessThanOrEqualToConstant: 100000).isActive = true
view.widthAnchor.constraint(greaterThanOrEqualToConstant: 1).isActive = true
item.view = view
return item
}
return nil
}
}
// MARK: - WindowUtilsPlugin
class WindowUtilsPlugin: NSObject, FlutterPlugin {
private static var instance: WindowUtilsPlugin?
private var channel: FlutterMethodChannel?
private weak var window: NSWindow?
private var windowDelegate: WindowDelegate?
private var originalButtonConstraints: [NSWindow.ButtonType: [NSLayoutConstraint]] = [:]
// Centralized traffic light positions - the single source of truth
private static let customButtonPositions: [(NSWindow.ButtonType, CGPoint)] = [
(.closeButton, CGPoint(x: 20, y: 21)),
(.miniaturizeButton, CGPoint(x: 40, y: 21)),
(.zoomButton, CGPoint(x: 60, y: 21))
]
static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(
name: "com.plezy/window_utils",
binaryMessenger: registrar.messenger
)
let instance = WindowUtilsPlugin()
instance.channel = channel
registrar.addMethodCallDelegate(instance, channel: channel)
self.instance = instance
}
static func setWindow(_ window: NSWindow) {
instance?.window = window
}
/// Apply custom traffic light positions. Called by MainFlutterWindow on startup.
static func setInitialTrafficLightPositions() {
guard let instance = instance, let window = instance.window else { return }
instance.applyTrafficLightPositions(custom: true, window: window)
}
/// Apply traffic light positions. Called by WindowDelegate during fullscreen transitions.
static func setTrafficLightPositions(custom: Bool, window: NSWindow) {
guard let instance = instance else { return }
instance.applyTrafficLightPositions(custom: custom, window: window)
}
private func applyTrafficLightPositions(custom: Bool, window: NSWindow) {
if custom {
for (buttonType, offset) in WindowUtilsPlugin.customButtonPositions {
overrideButtonPosition(window: window, buttonType: buttonType, offset: offset)
}
} else {
for (buttonType, _) in WindowUtilsPlugin.customButtonPositions {
resetButtonPosition(window: window, buttonType: buttonType)
}
}
}
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let window = window else {
result(FlutterError(code: "NO_WINDOW", message: "Window not available", details: nil))
return
}
switch call.method {
case "initialize":
let args = call.arguments as? [String: Any]
let enableWindowDelegate = args?["enableWindowDelegate"] as? Bool ?? false
initialize(window: window, enableWindowDelegate: enableWindowDelegate)
result(nil)
case "setTrafficLightsVisible":
let args = call.arguments as? [String: Any]
let visible = args?["visible"] as? Bool ?? true
for buttonType in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] {
window.standardWindowButton(buttonType)?.isHidden = !visible
}
result(nil)
case "enterFullscreen":
if !window.styleMask.contains(.fullScreen) {
window.toggleFullScreen(nil)
}
result(nil)
case "exitFullscreen":
if window.styleMask.contains(.fullScreen) {
window.toggleFullScreen(nil)
}
result(nil)
case "isFullscreen":
result(window.styleMask.contains(.fullScreen))
default:
result(FlutterMethodNotImplemented)
}
}
private func initialize(window: NSWindow, enableWindowDelegate: Bool) {
self.window = window
if enableWindowDelegate {
let delegate = WindowDelegate()
delegate.channel = channel
delegate.window = window
windowDelegate = delegate
window.delegate = delegate
}
}
private func withButton(
_ buttonType: NSWindow.ButtonType,
in window: NSWindow,
action: (NSButton, NSView) -> Void
) {
guard let button = window.standardWindowButton(buttonType),
let superview = button.superview else { return }
action(button, superview)
}
private func positionConstraints(for button: NSButton, in superview: NSView) -> [NSLayoutConstraint] {
superview.constraints.filter { constraint in
((constraint.firstItem as? NSButton) == button || (constraint.secondItem as? NSButton) == button) &&
(constraint.firstAttribute == .left || constraint.firstAttribute == .leading ||
constraint.firstAttribute == .top || constraint.firstAttribute == .centerY)
}
}
private func overrideButtonPosition(window: NSWindow, buttonType: NSWindow.ButtonType, offset: CGPoint) {
withButton(buttonType, in: window) { button, superview in
// Store original constraints if not already stored
if originalButtonConstraints[buttonType] == nil {
let constraints = superview.constraints.filter { constraint in
(constraint.firstItem as? NSButton) == button || (constraint.secondItem as? NSButton) == button
}
originalButtonConstraints[buttonType] = constraints
}
// Remove existing position constraints
superview.removeConstraints(positionConstraints(for: button, in: superview))
button.translatesAutoresizingMaskIntoConstraints = false
// Add new positioning constraints
superview.addConstraints([
button.leftAnchor.constraint(equalTo: superview.leftAnchor, constant: offset.x),
button.topAnchor.constraint(equalTo: superview.topAnchor, constant: offset.y)
])
superview.layoutSubtreeIfNeeded()
}
}
private func resetButtonPosition(window: NSWindow, buttonType: NSWindow.ButtonType) {
withButton(buttonType, in: window) { button, superview in
// Remove custom constraints
superview.removeConstraints(positionConstraints(for: button, in: superview))
// Restore original constraints if we have them
if let originalConstraints = originalButtonConstraints[buttonType] {
superview.addConstraints(originalConstraints)
originalButtonConstraints.removeValue(forKey: buttonType)
}
button.translatesAutoresizingMaskIntoConstraints = true
superview.layoutSubtreeIfNeeded()
}
}
}
+9 -25
View File
@@ -281,6 +281,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.1"
dart_discord_presence:
dependency: "direct main"
description:
name: dart_discord_presence
sha256: "4679b197eb37af3676766bbfba9f1f766ba27131588237f13ea7085e9dfe068a"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
dart_style:
dependency: transitive
description:
@@ -760,14 +768,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.3.0"
macos_window_utils:
dependency: "direct main"
description:
name: macos_window_utils
sha256: d4df3501fd32ac0d2d7590cb6a8e4758337d061c8fa0db816fdd636be63a8438
url: "https://pub.dev"
source: hosted
version: "1.9.0"
matcher:
dependency: transitive
description:
@@ -1105,22 +1105,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.2.0"
share_plus:
dependency: "direct main"
description:
name: share_plus
sha256: fce43200aa03ea87b91ce4c3ac79f0cecd52e2a7a56c7a4185023c271fbfa6da
url: "https://pub.dev"
source: hosted
version: "10.1.4"
share_plus_platform_interface:
dependency: transitive
description:
name: share_plus_platform_interface
sha256: cc012a23fc2d479854e6c80150696c4a5f5bb62cb89af4de1c505cf78d0a5d0b
url: "https://pub.dev"
source: hosted
version: "5.0.2"
shared_preferences:
dependency: "direct main"
description:
@@ -1615,5 +1599,5 @@ packages:
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.9.2 <4.0.0"
dart: ">=3.10.4 <4.0.0"
flutter: ">=3.35.0"
+2 -3
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.12.0+28
version: 1.14.1+31
environment:
sdk: ^3.8.1
@@ -13,7 +13,6 @@ dependencies:
json_annotation: ^4.8.1
shared_preferences: ^2.2.2
cached_network_image: ^3.4.1
macos_window_utils: ^1.9.0
url_launcher: ^6.3.0
uuid: ^4.4.0
window_manager: ^0.4.3
@@ -46,8 +45,8 @@ dependencies:
saf_stream: ^0.12.2
material_symbols_icons: ^4.2892.0
peerdart: ^0.5.6
share_plus: ^10.0.0
in_app_review: ^2.0.11
dart_discord_presence: ^1.1.0
dev_dependencies:
flutter_test:
+21 -2
View File
@@ -18,7 +18,7 @@ Set-Location $ProjectRoot
# Define paths
$BuildDir = "build\windows\x64\runner\Release"
$PortableZip = Join-Path (Resolve-Path $OutputDir) "plezy-windows-portable.zip"
$PortableZip = Join-Path (Resolve-Path $OutputDir) "plezy-windows-portable.7z"
$InstallerExe = Join-Path (Resolve-Path $OutputDir) "plezy-windows-installer.exe"
$SetupScript = "setup.iss"
@@ -30,6 +30,25 @@ if (-not (Test-Path $BuildDir)) {
Write-Host "Found build at: $BuildDir" -ForegroundColor Green
# Check for 7-Zip
Write-Host "`nChecking for 7-Zip..." -ForegroundColor Cyan
if (-not (Get-Command 7z -ErrorAction SilentlyContinue)) {
Write-Host "7-Zip not found in PATH. Installing via Chocolatey..." -ForegroundColor Yellow
if (-not (Get-Command choco -ErrorAction SilentlyContinue)) {
Write-Error "Chocolatey is not installed. Please install it from https://chocolatey.org/install"
exit 1
}
choco install 7zip -y
refreshenv
if (-not (Get-Command 7z -ErrorAction SilentlyContinue)) {
Write-Error "Failed to install 7-Zip"
exit 1
}
}
# Create Portable Archive
Write-Host "`nCreating portable archive..." -ForegroundColor Cyan
Push-Location $BuildDir
@@ -37,7 +56,7 @@ try {
if (Test-Path $PortableZip) {
Remove-Item $PortableZip -Force
}
Compress-Archive -Path * -DestinationPath $PortableZip
7z a -mx=9 $PortableZip *
Write-Host "Created: $PortableZip" -ForegroundColor Green
} finally {
Pop-Location
@@ -12,7 +12,6 @@
#include <hotkey_manager_windows/hotkey_manager_windows_plugin_c_api.h>
#include <os_media_controls/os_media_controls_plugin_c_api.h>
#include <screen_retriever_windows/screen_retriever_windows_plugin_c_api.h>
#include <share_plus/share_plus_windows_plugin_c_api.h>
#include <sqlite3_flutter_libs/sqlite3_flutter_libs_plugin.h>
#include <url_launcher_windows/url_launcher_windows.h>
#include <window_manager/window_manager_plugin.h>
@@ -30,8 +29,6 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
registry->GetRegistrarForPlugin("OsMediaControlsPluginCApi"));
ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi"));
SharePlusWindowsPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi"));
Sqlite3FlutterLibsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("Sqlite3FlutterLibsPlugin"));
UrlLauncherWindowsRegisterWithRegistrar(
-1
View File
@@ -9,7 +9,6 @@ list(APPEND FLUTTER_PLUGIN_LIST
hotkey_manager_windows
os_media_controls
screen_retriever_windows
share_plus
sqlite3_flutter_libs
url_launcher_windows
window_manager