Compare commits

...
42 Commits
Author SHA1 Message Date
edde746 260681aa24 chore: bump version 2025-11-08 10:10:58 +01:00
edde746 6228eb2690 refactor: rewrite os media controls
# Conflicts:
#	lib/screens/video_player_screen.dart
#	lib/services/media_service_manager.dart
#	pubspec.yaml
2025-11-08 10:04:51 +01:00
edde746 0d4f7a9e9f refactor: remove duplicate audio sessions 2025-11-08 08:35:52 +01:00
edde746 fac7aed1e7 feat: shuffle settings 2025-11-07 20:50:09 +01:00
edde746 b6234120dd fix: android crash 2025-11-07 17:53:44 +01:00
edde746 2eb33eb234 fix: android icons 2025-11-07 17:44:50 +01:00
edde746 d744e783ac feat: pgs & truehd support 2025-11-07 17:24:30 +01:00
edde746 3e068b2bea chore: update lockfile 2025-11-07 02:21:23 +01:00
edde746andGitHub 36a843b43f Merge pull request #65 from ComicalHysteria/QR-code-sign-in
Add QR code generation for sign in
2025-11-07 02:19:08 +01:00
edde746 3f40007f03 feat: throttle seeking commands 2025-11-07 02:16:07 +01:00
ComicalHysteriaandGitHub 66941b06d4 Add QR code generation for sign in 2025-11-06 14:40:38 -06:00
edde746 47f5454f61 feat: os media controls 2025-11-06 15:14:40 +01:00
edde746 2a6098c3ba feat: load library in parts 2025-11-06 11:54:31 +01:00
edde746 60a84380a6 feat: external subtitle support 2025-11-06 10:36:26 +01:00
edde746 e047c820ae chore: bump version 2025-11-06 07:06:52 +01:00
edde746 e4e7911573 fix: try http connections 2025-11-06 03:58:50 +01:00
edde746 7fcf79045b Revert "ci: cache cleanup"
This reverts commit 40b3142d23.
2025-11-05 20:34:32 +01:00
edde746 40b3142d23 ci: cache cleanup 2025-11-05 20:30:54 +01:00
edde746 8f18a7c941 chore: bump dependencies 2025-11-05 20:24:20 +01:00
edde746 07b4ba371e chore: bump version 2025-11-05 20:17:03 +01:00
edde746 2571a6c38b refactor: adjust video controls button sizes 2025-11-05 20:16:12 +01:00
edde746 57b691782c feat: subtitle styling 2025-11-05 20:06:18 +01:00
edde746 eb8968c428 feat(android): dark mode icon 2025-11-05 19:33:44 +01:00
edde746 8b6052d97b feat: rotation lock 2025-11-05 16:46:31 +01:00
edde746 155ac2042e feat: audio device selector 2025-11-05 15:00:17 +01:00
edde746 1c7fccdd6b feat: persist volume 2025-11-05 14:50:13 +01:00
edde746 c15bc6d4c2 feat: subtitle delay config 2025-11-05 14:43:05 +01:00
edde746 4888d125e4 refactor: merge video controls into one sheet 2025-11-05 14:22:24 +01:00
edde746 1c8d36f0e9 feat: configurable audio delay 2025-11-05 14:15:14 +01:00
edde746 6e58f26ee4 refactor: move fullscreen button into controls 2025-11-05 14:03:30 +01:00
edde746 b30c9c6420 refactor: split up video controls 2025-11-05 13:52:21 +01:00
edde746 cef1e38f6d Merge branch 'sleep-timer-47' 2025-11-05 13:29:45 +01:00
edde746 00c02730d7 refactor(sleep timer): remove default styling 2025-11-05 13:29:32 +01:00
edde746 bb97e5a418 feat: list mode 2025-11-05 13:26:02 +01:00
edde746andGitHub d51c3ff607 Merge pull request #53 from TheLidlMan/screen-refresh-fix
fix: home refresh everytime you go back a to home page
2025-11-05 12:44:04 +01:00
Sam Matthews e500fe452d fix: when navigating back to home screen it does full screen refresh, making it feel slow now it just refreshes the continue watching tab and keeps everything else the same. 2025-11-05 11:39:29 +00:00
edde746 fd9ba46b7b fix: allow malformed utf-8 2025-11-05 12:36:09 +01:00
Sam Matthews 00da8a23e3 feat: sleep timer
- default timer values in settings
- extend timer function
- pauses playback when done and shows popup
2025-11-05 11:28:51 +00:00
edde746 0817153f4b feat: shuffle play button on media detail screen 2025-11-05 12:20:52 +01:00
edde746 c559fbf89c fix: reload libraries on refresh 2025-11-05 11:06:52 +01:00
edde746 844965e051 refactor: fix warnings 2025-11-05 11:03:35 +01:00
edde746 60ba1b1570 feat: video fill modes 2025-11-05 11:00:22 +01:00
58 changed files with 5709 additions and 1406 deletions
+22
View File
@@ -3,6 +3,11 @@
<!-- Internet access permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Audio service permissions -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<!-- Explicitly remove media permissions that media_kit may add -->
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" tools:node="remove" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" tools:node="remove" />
@@ -40,6 +45,23 @@
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<!-- Audio service -->
<service android:name="com.ryanheise.audioservice.AudioService"
android:foregroundServiceType="mediaPlayback"
android:exported="true" tools:ignore="Instantiatable">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
<!-- Media button receiver -->
<receiver android:name="com.ryanheise.audioservice.MediaButtonReceiver"
android:exported="true" tools:ignore="Instantiatable">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
@@ -1,5 +1,5 @@
package com.edde746.plezy
import io.flutter.embedding.android.FlutterActivity
import com.ryanheise.audioservice.AudioServiceActivity
class MainActivity : FlutterActivity()
class MainActivity : AudioServiceActivity()
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 820 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

@@ -1,5 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
<foreground>
<inset
android:drawable="@drawable/ic_launcher_foreground"
android:inset="16%" />
</foreground>
<monochrome>
<inset
android:drawable="@mipmap/ic_launcher_monochrome"
android:inset="16%" />
</monochrome>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#1a1a1a</color>
</resources>
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+15 -2
View File
@@ -1,4 +1,9 @@
PODS:
- audio_service (0.0.1):
- Flutter
- FlutterMacOS
- audio_session (0.0.1):
- Flutter
- Flutter (1.0.0)
- media_kit_libs_ios_video (1.0.4):
- Flutter
@@ -23,6 +28,8 @@ PODS:
- Flutter
DEPENDENCIES:
- audio_service (from `.symlinks/plugins/audio_service/darwin`)
- audio_session (from `.symlinks/plugins/audio_session/ios`)
- Flutter (from `Flutter`)
- media_kit_libs_ios_video (from `.symlinks/plugins/media_kit_libs_ios_video/ios`)
- media_kit_video (from `.symlinks/plugins/media_kit_video/ios`)
@@ -35,6 +42,10 @@ DEPENDENCIES:
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
EXTERNAL SOURCES:
audio_service:
:path: ".symlinks/plugins/audio_service/darwin"
audio_session:
:path: ".symlinks/plugins/audio_session/ios"
Flutter:
:path: Flutter
media_kit_libs_ios_video:
@@ -57,12 +68,14 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/wakelock_plus/ios"
SPEC CHECKSUMS:
audio_service: aa99a6ba2ae7565996015322b0bb024e1d25c6fd
audio_session: 9bb7f6c970f21241b19f5a3658097ae459681ba0
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854
media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
volume_controller: 3657a1f65bedb98fa41ff7dc5793537919f31b12
+4
View File
@@ -39,6 +39,10 @@
<string>This app needs to connect to your Plex Media Server on your local network.</string>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
+14 -1
View File
@@ -1,3 +1,4 @@
import 'dart:convert';
import 'package:dio/dio.dart';
import '../config/plex_config.dart';
import '../models/plex_library.dart';
@@ -22,16 +23,26 @@ class PlexClient {
PlexConfig config;
late final Dio _dio;
/// Custom response decoder that handles malformed UTF-8 gracefully
static String _lenientUtf8Decoder(
List<int> responseBytes,
RequestOptions options,
ResponseBody responseBody,
) {
return utf8.decode(responseBytes, allowMalformed: true);
}
PlexClient(this.config) {
_dio = Dio(
BaseOptions(
baseUrl: config.baseUrl,
headers: config.headers,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 120),
validateStatus: (status) => status != null && status < 500,
responseType: ResponseType.json,
contentType: 'application/json; charset=utf-8',
responseDecoder: _lenientUtf8Decoder,
),
);
@@ -217,6 +228,7 @@ class PlexClient {
int? start,
int? size,
Map<String, String>? filters,
CancelToken? cancelToken,
}) async {
final queryParams = <String, dynamic>{};
if (start != null) queryParams['X-Plex-Container-Start'] = start;
@@ -230,6 +242,7 @@ class PlexClient {
final response = await _dio.get(
'/library/sections/$sectionId/all',
queryParameters: queryParams,
cancelToken: cancelToken,
);
return _extractMetadataList(response);
+44
View File
@@ -77,6 +77,50 @@ class PlexSubtitleTrack {
if (forced) parts.add('Forced');
return parts.isEmpty ? 'Track ${index ?? id}' : parts.join(' · ');
}
/// Returns true if this subtitle track is an external file (sidecar subtitle)
/// External subtitles have a key property that points to /library/streams/{id}
bool get isExternal => key != null && key!.isNotEmpty;
/// Constructs the full URL for fetching external subtitle files
/// Returns null if this is not an external subtitle
String? getSubtitleUrl(String baseUrl, String token) {
if (!isExternal) return null;
// Determine file extension based on codec
final ext = _getExtensionFromCodec(codec);
// Construct URL with authentication token
return '$baseUrl$key.$ext?X-Plex-Token=$token';
}
/// Maps Plex subtitle codec names to file extensions
String _getExtensionFromCodec(String? codec) {
if (codec == null) return 'srt';
switch (codec.toLowerCase()) {
case 'subrip':
case 'srt':
return 'srt';
case 'ass':
return 'ass';
case 'ssa':
return 'ssa';
case 'webvtt':
case 'vtt':
return 'vtt';
case 'mov_text':
return 'srt';
case 'pgs':
case 'hdmv_pgs_subtitle':
return 'sup';
case 'dvd_subtitle':
case 'dvdsub':
return 'sub';
default:
return 'srt'; // Default to SRT for unknown codecs
}
}
}
class PlexChapter {
+32 -1
View File
@@ -25,7 +25,8 @@ class PlaybackStateProvider with ChangeNotifier {
/// Gets the next episode in the shuffle queue.
/// Returns null if queue is exhausted or current episode is not in queue.
PlexMetadata? getNextEpisode(String currentEpisodeKey) {
/// [loopQueue] - If true, restart from beginning when queue is exhausted
PlexMetadata? getNextEpisode(String currentEpisodeKey, {bool loopQueue = false}) {
if (_shuffleQueue.isEmpty) return null;
// Find current episode in queue
@@ -42,6 +43,11 @@ class PlaybackStateProvider with ChangeNotifier {
// Check if there's a next episode
if (currentIndex + 1 >= _shuffleQueue.length) {
// Queue exhausted
if (loopQueue && _shuffleQueue.isNotEmpty) {
// Loop back to beginning
_currentIndex = 0;
return _shuffleQueue[_currentIndex];
}
return null;
}
@@ -49,6 +55,31 @@ class PlaybackStateProvider with ChangeNotifier {
return _shuffleQueue[_currentIndex];
}
/// Gets the previous episode in the shuffle queue.
/// Returns null if at the beginning of the queue or current episode is not in queue.
PlexMetadata? getPreviousEpisode(String currentEpisodeKey) {
if (_shuffleQueue.isEmpty) return null;
// Find current episode in queue
final currentIndex = _shuffleQueue.indexWhere(
(ep) => ep.ratingKey == currentEpisodeKey,
);
if (currentIndex == -1) {
// Current episode not in queue
return null;
}
// Check if there's a previous episode
if (currentIndex <= 0) {
// At the beginning of queue
return null;
}
_currentIndex = currentIndex - 1;
return _shuffleQueue[_currentIndex];
}
/// Clears the shuffle queue and exits shuffle mode
void clearShuffle() {
_shuffleQueue = [];
+44
View File
@@ -4,8 +4,12 @@ import '../services/settings_service.dart';
class SettingsProvider extends ChangeNotifier {
late SettingsService _settingsService;
LibraryDensity _libraryDensity = LibraryDensity.normal;
ViewMode _viewMode = ViewMode.grid;
bool _useSeasonPoster = false;
bool _showHeroSection = true;
bool _shuffleUnwatchedOnly = true;
bool _shuffleOrderNavigation = true;
bool _shuffleLoopQueue = false;
SettingsProvider() {
_initializeSettings();
@@ -14,14 +18,22 @@ class SettingsProvider extends ChangeNotifier {
Future<void> _initializeSettings() async {
_settingsService = await SettingsService.getInstance();
_libraryDensity = _settingsService.getLibraryDensity();
_viewMode = _settingsService.getViewMode();
_useSeasonPoster = _settingsService.getUseSeasonPoster();
_showHeroSection = _settingsService.getShowHeroSection();
_shuffleUnwatchedOnly = _settingsService.getShuffleUnwatchedOnly();
_shuffleOrderNavigation = _settingsService.getShuffleOrderNavigation();
_shuffleLoopQueue = _settingsService.getShuffleLoopQueue();
notifyListeners();
}
LibraryDensity get libraryDensity => _libraryDensity;
ViewMode get viewMode => _viewMode;
bool get useSeasonPoster => _useSeasonPoster;
bool get showHeroSection => _showHeroSection;
bool get shuffleUnwatchedOnly => _shuffleUnwatchedOnly;
bool get shuffleOrderNavigation => _shuffleOrderNavigation;
bool get shuffleLoopQueue => _shuffleLoopQueue;
Future<void> setLibraryDensity(LibraryDensity density) async {
if (_libraryDensity != density) {
@@ -31,6 +43,14 @@ class SettingsProvider extends ChangeNotifier {
}
}
Future<void> setViewMode(ViewMode mode) async {
if (_viewMode != mode) {
_viewMode = mode;
await _settingsService.setViewMode(mode);
notifyListeners();
}
}
Future<void> setUseSeasonPoster(bool value) async {
if (_useSeasonPoster != value) {
_useSeasonPoster = value;
@@ -47,6 +67,30 @@ class SettingsProvider extends ChangeNotifier {
}
}
Future<void> setShuffleUnwatchedOnly(bool value) async {
if (_shuffleUnwatchedOnly != value) {
_shuffleUnwatchedOnly = value;
await _settingsService.setShuffleUnwatchedOnly(value);
notifyListeners();
}
}
Future<void> setShuffleOrderNavigation(bool value) async {
if (_shuffleOrderNavigation != value) {
_shuffleOrderNavigation = value;
await _settingsService.setShuffleOrderNavigation(value);
notifyListeners();
}
}
Future<void> setShuffleLoopQueue(bool value) async {
if (_shuffleLoopQueue != value) {
_shuffleLoopQueue = value;
await _settingsService.setShuffleLoopQueue(value);
notifyListeners();
}
}
String get libraryDensityDisplayName {
switch (_libraryDensity) {
case LibraryDensity.compact:
+67 -13
View File
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import 'server_selection_screen.dart';
@@ -18,6 +19,8 @@ class _AuthScreenState extends State<AuthScreen> {
String? _errorMessage;
late PlexAuthService _authService;
bool _shouldCancelPolling = false;
bool _useQrFlow = false; // whether current auth attempt is QR based
String? _qrAuthUrl; // auth URL rendered as QR
@override
void initState() {
@@ -34,6 +37,10 @@ class _AuthScreenState extends State<AuthScreen> {
_isAuthenticating = true;
_errorMessage = null;
_shouldCancelPolling = false;
// preserve _useQrFlow as chosen prior to calling
if (!_useQrFlow) {
_qrAuthUrl = null; // ensure stale QR cleared for browser flow
}
});
try {
@@ -45,12 +52,19 @@ class _AuthScreenState extends State<AuthScreen> {
// Construct auth URL
final authUrl = _authService.getAuthUrl(pinCode);
// Open browser (in-app for mobile, external for desktop)
final uri = Uri.parse(authUrl);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.inAppBrowserView);
if (_useQrFlow) {
// Display QR instead of launching browser
setState(() {
_qrAuthUrl = authUrl;
});
} else {
throw Exception('Could not launch auth URL');
// Open browser (in-app for mobile, external for desktop)
final uri = Uri.parse(authUrl);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.inAppBrowserView);
} else {
throw Exception('Could not launch auth URL');
}
}
// Poll for authentication with cancellation support
@@ -73,10 +87,12 @@ class _AuthScreenState extends State<AuthScreen> {
}
// Auto-close the in-app browser on mobile (no-op on desktop)
try {
await closeInAppWebView();
} catch (e) {
// Ignore errors - browser might already be closed or on desktop
if (!_useQrFlow) {
try {
await closeInAppWebView();
} catch (e) {
// Ignore errors - browser might already be closed or on desktop
}
}
// Store the token
@@ -95,6 +111,11 @@ class _AuthScreenState extends State<AuthScreen> {
),
);
}
// Clear QR URL after successful auth
setState(() {
_qrAuthUrl = null;
_useQrFlow = false;
});
} catch (e) {
setState(() {
_isAuthenticating = false;
@@ -107,6 +128,7 @@ class _AuthScreenState extends State<AuthScreen> {
setState(() {
_shouldCancelPolling = true;
_isAuthenticating = false;
_qrAuthUrl = null;
});
// Start new authentication after a brief delay to ensure cleanup
Future.delayed(const Duration(milliseconds: 100), _startAuthentication);
@@ -226,11 +248,30 @@ class _AuthScreenState extends State<AuthScreen> {
if (_isAuthenticating) ...[
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
const Text(
'Waiting for authentication...\nPlease complete sign-in in your browser.',
Text(
_useQrFlow
? 'Scan this QR code with a device logged into Plex to authenticate.'
: 'Waiting for authentication...\nPlease complete sign-in in your browser.',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
style: const TextStyle(color: Colors.grey),
),
if (_useQrFlow && _qrAuthUrl != null) ...[
const SizedBox(height: 24),
Center(
child: QrImageView(
data: _qrAuthUrl!,
size: 200,
version: QrVersions.auto,
backgroundColor: Colors.white,
),
),
const SizedBox(height: 16),
SelectableText(
_qrAuthUrl!,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 10, color: Colors.grey),
),
],
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
@@ -242,7 +283,7 @@ class _AuthScreenState extends State<AuthScreen> {
),
child: const Text('Retry'),
),
] else ...[
] else ...[ // add QR button here
ElevatedButton(
onPressed: _startAuthentication,
style: ElevatedButton.styleFrom(
@@ -250,6 +291,19 @@ class _AuthScreenState extends State<AuthScreen> {
),
child: const Text('Sign in with Plex'),
),
const SizedBox(height: 12),
OutlinedButton(
onPressed: () {
setState(() {
_useQrFlow = true;
});
_startAuthentication();
},
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: const Text('Show QR Code'),
),
if (kDebugMode) ...[
const SizedBox(height: 12),
OutlinedButton(
+37 -1
View File
@@ -239,11 +239,46 @@ class _DiscoverScreenState extends State<DiscoverScreen>
}
}
/// Refresh only the Continue Watching section in the background
/// This is called when returning to the home screen to avoid blocking UI
Future<void> _refreshContinueWatching() async {
appLogger.d('Refreshing Continue Watching in background');
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
appLogger.w('No client available for background refresh');
return;
}
final onDeck = await client.getOnDeck();
if (mounted) {
setState(() {
_onDeck = onDeck;
// Reset hero index if needed
if (_currentHeroIndex >= onDeck.length) {
_currentHeroIndex = 0;
if (_heroController.hasClients && onDeck.isNotEmpty) {
_heroController.jumpToPage(0);
}
}
});
appLogger.d('Continue Watching refreshed successfully');
}
} catch (e) {
appLogger.w('Failed to refresh Continue Watching', error: e);
// Silently fail - don't show error to user for background refresh
}
}
// Public method to refresh content
@override
void refresh() {
appLogger.d('DiscoverScreen.refresh() called');
_loadContent();
// Only refresh Continue Watching in background, not full screen reload
_refreshContinueWatching();
}
/// Get icon for hub based on its title
@@ -1256,6 +1291,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
width: cardWidth,
height: posterHeight,
onRefresh: updateItem,
forceGridMode: true,
),
);
},
+3 -9
View File
@@ -61,16 +61,10 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
final hubKey = widget.hub.hubKey;
appLogger.d('Hub key: $hubKey');
RegExpMatch? match;
// Try different patterns
match = RegExp(r'/hubs/sections/(\d+)').firstMatch(hubKey);
if (match == null) {
match = RegExp(r'/library/sections/(\d+)').firstMatch(hubKey);
}
if (match == null) {
match = RegExp(r'sections/(\d+)').firstMatch(hubKey);
}
RegExpMatch? match = RegExp(r'/hubs/sections/(\d+)').firstMatch(hubKey);
match ??= RegExp(r'/library/sections/(\d+)').firstMatch(hubKey);
match ??= RegExp(r'sections/(\d+)').firstMatch(hubKey);
if (match != null) {
final sectionId = match.group(1)!;
+221 -102
View File
@@ -46,6 +46,13 @@ class _LibrariesScreenState extends State<LibrariesScreen>
bool _isSortDescending = false;
bool _isInitialLoad = true;
// Pagination state
int _currentPage = 0;
bool _hasMoreItems = true;
CancelToken? _cancelToken;
int _requestId = 0;
static const int _pageSize = 1000;
@override
void initState() {
super.initState();
@@ -201,17 +208,6 @@ class _LibrariesScreenState extends State<LibrariesScreen>
await storage.saveLibraryOrder(libraryKeys);
}
void _reorderLibraries(int oldIndex, int newIndex) {
setState(() {
if (newIndex > oldIndex) {
newIndex -= 1;
}
final library = _allLibraries.removeAt(oldIndex);
_allLibraries.insert(newIndex, library);
});
_saveLibraryOrder();
}
Future<void> _loadLibraryContent(String libraryKey) async {
// Compute visible libraries based on current provider state
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(
@@ -267,6 +263,18 @@ class _LibrariesScreenState extends State<LibrariesScreen>
await storage.saveLibraryFilters({});
}
// Cancel any existing requests
_cancelToken?.cancel();
_cancelToken = CancelToken();
final currentRequestId = ++_requestId;
// Reset pagination state
setState(() {
_currentPage = 0;
_hasMoreItems = true;
_items = [];
});
try {
// Load filters and sort options for the new library
_loadFilters(libraryKey);
@@ -280,16 +288,19 @@ class _LibrariesScreenState extends State<LibrariesScreen>
);
}
// Load content
final items = await client.getLibraryContent(
// Load pages sequentially
await _loadAllPagesSequentially(
libraryKey,
filters: filtersWithSort,
filtersWithSort,
currentRequestId,
client,
);
setState(() {
_items = items;
_isLoadingItems = false;
});
} catch (e) {
// Ignore cancellation errors
if (e is DioException && e.type == DioExceptionType.cancel) {
return;
}
setState(() {
_errorMessage = _getErrorMessage(e, 'library content');
_isLoadingItems = false;
@@ -297,6 +308,54 @@ class _LibrariesScreenState extends State<LibrariesScreen>
}
}
/// Load all pages sequentially until all items are fetched
Future<void> _loadAllPagesSequentially(
String libraryKey,
Map<String, String> filtersWithSort,
int requestId,
PlexClient client,
) async {
while (_hasMoreItems && requestId == _requestId) {
try {
final items = await client.getLibraryContent(
libraryKey,
start: _currentPage * _pageSize,
size: _pageSize,
filters: filtersWithSort,
cancelToken: _cancelToken,
);
// Check if request is still valid
if (requestId != _requestId) {
return; // Request was superseded
}
setState(() {
_items.addAll(items);
_currentPage++;
_hasMoreItems = items.length >= _pageSize;
// Mark as not loading if this is the last page
if (!_hasMoreItems) {
_isLoadingItems = false;
}
});
} catch (e) {
// Check if it's a cancellation
if (e is DioException && e.type == DioExceptionType.cancel) {
return;
}
// For other errors, update state and rethrow
setState(() {
_isLoadingItems = false;
_hasMoreItems = false;
});
rethrow;
}
}
}
Future<void> _loadFilters(String libraryKey) async {
try {
final clientProvider = Provider.of<PlexClientProvider>(
@@ -370,9 +429,17 @@ class _LibrariesScreenState extends State<LibrariesScreen>
}
Future<void> _applyFilters() async {
// Cancel any existing requests
_cancelToken?.cancel();
_cancelToken = CancelToken();
final currentRequestId = ++_requestId;
setState(() {
_isLoadingItems = true;
_errorMessage = null;
_currentPage = 0;
_hasMoreItems = true;
_items = [];
});
try {
@@ -393,15 +460,19 @@ class _LibrariesScreenState extends State<LibrariesScreen>
);
}
final items = await client.getLibraryContent(
// Load pages sequentially
await _loadAllPagesSequentially(
_selectedLibraryKey!,
filters: filtersWithSort,
filtersWithSort,
currentRequestId,
client,
);
setState(() {
_items = items;
_isLoadingItems = false;
});
} catch (e) {
// Ignore cancellation errors
if (e is DioException && e.type == DioExceptionType.cancel) {
return;
}
setState(() {
_errorMessage = 'Failed to load library content: $e';
_isLoadingItems = false;
@@ -435,9 +506,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
// Public method to refresh content
@override
void refresh() {
if (_allLibraries.isNotEmpty) {
_applyFilters();
}
_loadLibraries();
}
Future<void> _toggleLibraryVisibility(PlexLibrary library) async {
@@ -924,7 +993,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
),
// Content grid
if (_isLoadingItems)
if (_isLoadingItems && _items.isEmpty)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
@@ -964,29 +1033,67 @@ class _LibrariesScreenState extends State<LibrariesScreen>
),
),
)
else
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: _getMaxCrossAxisExtent(
context,
context.watch<SettingsProvider>().libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
else ...[
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _items.length),
),
);
}, childCount: _items.length),
),
} else {
return SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: _getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _items.length),
),
);
}
},
),
// Show loading indicator if there are more items to load
if (_hasMoreItems && _isLoadingItems)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
const CircularProgressIndicator(),
const SizedBox(height: 8),
Text(
'Loading library... (${_items.length} items loaded)',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
),
],
],
],
),
@@ -1436,45 +1543,63 @@ class _SortBottomSheetState extends State<_SortBottomSheet> {
// Sort options list
Expanded(
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: widget.sortOptions.length,
itemBuilder: (context, index) {
final sort = widget.sortOptions[index];
final isSelected = _tempSelectedSort?.key == sort.key;
child: RadioGroup<String>(
groupValue: _tempSelectedSort?.key,
onChanged: (value) {
final sort = widget.sortOptions.firstWhere(
(s) => s.key == value,
);
setState(() {
_tempSelectedSort = sort;
// Use default direction for newly selected sort
_tempDescending = sort.isDefaultDescending;
});
// Apply sort immediately with default direction
widget.onSortChanged(sort, sort.isDefaultDescending);
},
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: widget.sortOptions.length,
itemBuilder: (context, index) {
final sort = widget.sortOptions[index];
final isSelected = _tempSelectedSort?.key == sort.key;
return ListTile(
title: Text(sort.title),
trailing: isSelected
? Row(
mainAxisSize: MainAxisSize.min,
children: [
// Direction toggle buttons
SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: Icon(Icons.arrow_upward, size: 16),
),
ButtonSegment(
value: true,
icon: Icon(Icons.arrow_downward, size: 16),
),
],
selected: {_tempDescending},
onSelectionChanged: (Set<bool> selected) {
widget.onSortChanged(sort, selected.first);
},
),
],
)
: null,
leading: Radio<String>(
value: sort.key,
groupValue: _tempSelectedSort?.key,
onChanged: (value) {
return ListTile(
title: Text(sort.title),
trailing: isSelected
? Row(
mainAxisSize: MainAxisSize.min,
children: [
// Direction toggle buttons
SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: Icon(Icons.arrow_upward, size: 16),
),
ButtonSegment(
value: true,
icon: Icon(
Icons.arrow_downward,
size: 16,
),
),
],
selected: {_tempDescending},
onSelectionChanged: (Set<bool> selected) {
widget.onSortChanged(sort, selected.first);
},
),
],
)
: null,
leading: Radio<String>(
value: sort.key,
toggleable: false,
),
onTap: () {
setState(() {
_tempSelectedSort = sort;
// Use default direction for newly selected sort
@@ -1483,18 +1608,9 @@ class _SortBottomSheetState extends State<_SortBottomSheet> {
// Apply sort immediately with default direction
widget.onSortChanged(sort, sort.isDefaultDescending);
},
),
onTap: () {
setState(() {
_tempSelectedSort = sort;
// Use default direction for newly selected sort
_tempDescending = sort.isDefaultDescending;
});
// Apply sort immediately with default direction
widget.onSortChanged(sort, sort.isDefaultDescending);
},
);
},
);
},
),
),
),
],
@@ -1587,6 +1703,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
);
if (selectedItem.requiresConfirmation) {
if (!mounted || !context.mounted) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
@@ -1701,9 +1818,11 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
padding: const EdgeInsets.only(right: 12),
child: Icon(
Icons.drag_indicator,
color: Theme.of(
context,
).textTheme.bodyMedium?.color?.withOpacity(0.5),
color: Theme.of(context)
.textTheme
.bodyMedium
?.color
?.withValues(alpha: 0.5),
),
),
),
+18
View File
@@ -10,6 +10,7 @@ import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/content_rating_formatter.dart';
import '../utils/shuffle_play_helper.dart';
import '../theme/theme_helper.dart';
import 'season_detail_screen.dart';
@@ -574,6 +575,23 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
),
),
const SizedBox(width: 12),
// Shuffle button (only for shows and seasons)
if (metadata.type.toLowerCase() == 'show' ||
metadata.type.toLowerCase() == 'season') ...[
IconButton.filledTonal(
onPressed: () async {
await handleShufflePlay(context, metadata);
},
icon: const Icon(Icons.shuffle),
tooltip: 'Shuffle play',
iconSize: 20,
style: IconButton.styleFrom(
minimumSize: const Size(48, 48),
maximumSize: const Size(48, 48),
),
),
const SizedBox(width: 12),
],
IconButton.filledTonal(
onPressed: () async {
try {
+43 -20
View File
@@ -213,27 +213,50 @@ class _SearchScreenState extends State<SearchScreen>
),
)
else
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: _getMaxCrossAxisExtent(
context,
context.watch<SettingsProvider>().libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
},
childCount: _searchResults.length,
),
),
);
}, childCount: _searchResults.length),
),
} else {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: _getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _searchResults.length),
),
);
}
},
),
],
),
+223 -3
View File
@@ -11,6 +11,7 @@ import '../widgets/desktop_app_bar.dart';
import '../widgets/hotkey_recorder_widget.dart';
import 'about_screen.dart';
import 'logs_screen.dart';
import 'subtitle_styling_screen.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@@ -29,6 +30,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
int _bufferSize = 128;
int _seekTimeSmall = 10;
int _seekTimeLarge = 30;
int _sleepTimerDuration = 30;
// Update checking state
bool _isCheckingForUpdate = false;
@@ -50,6 +52,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_bufferSize = _settingsService.getBufferSize();
_seekTimeSmall = _settingsService.getSeekTimeSmall();
_seekTimeLarge = _settingsService.getSeekTimeLarge();
_sleepTimerDuration = _settingsService.getSleepTimerDuration();
_isLoading = false;
});
}
@@ -72,6 +75,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 24),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildShufflePlaySection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
@@ -126,6 +131,17 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return ListTile(
leading: const Icon(Icons.view_list),
title: const Text('View Mode'),
subtitle: Text(settingsProvider.viewMode == settings.ViewMode.grid ? 'Grid' : 'List'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showViewModeDialog(),
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
@@ -194,6 +210,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
trailing: const Icon(Icons.chevron_right),
onTap: () => _showBufferSizeDialog(),
),
ListTile(
leading: const Icon(Icons.subtitles),
title: const Text('Subtitle Styling'),
subtitle: const Text('Customize subtitle appearance'),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SubtitleStylingScreen(),
),
);
},
),
ListTile(
leading: const Icon(Icons.replay_10),
title: const Text('Small Skip Duration'),
@@ -208,6 +238,77 @@ class _SettingsScreenState extends State<SettingsScreen> {
trailing: const Icon(Icons.chevron_right),
onTap: () => _showSeekTimeLargeDialog(),
),
ListTile(
leading: const Icon(Icons.bedtime),
title: const Text('Default Sleep Timer'),
subtitle: Text('$_sleepTimerDuration minutes'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showSleepTimerDurationDialog(),
),
],
),
);
}
Widget _buildShufflePlaySection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Shuffle Play',
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.visibility_off),
title: const Text('Unwatched Only'),
subtitle: const Text(
'Only include unwatched episodes in shuffle queue',
),
value: settingsProvider.shuffleUnwatchedOnly,
onChanged: (value) async {
await settingsProvider.setShuffleUnwatchedOnly(value);
},
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.shuffle),
title: const Text('Shuffle Order Navigation'),
subtitle: const Text(
'Next/previous buttons follow shuffled order',
),
value: settingsProvider.shuffleOrderNavigation,
onChanged: (value) async {
await settingsProvider.setShuffleOrderNavigation(value);
},
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.loop),
title: const Text('Loop Shuffle Queue'),
subtitle: const Text(
'Restart queue when reaching the end',
),
value: settingsProvider.shuffleLoopQueue,
onChanged: (value) async {
await settingsProvider.setShuffleLoopQueue(value);
},
);
},
),
],
),
);
@@ -273,9 +374,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const LogsScreen(),
),
MaterialPageRoute(builder: (context) => const LogsScreen()),
);
},
),
@@ -588,6 +687,70 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
void _showSleepTimerDurationDialog() {
final controller = TextEditingController(
text: _sleepTimerDuration.toString(),
);
String? errorText;
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
title: const Text('Default Sleep Timer'),
content: TextField(
controller: controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Minutes',
hintText: 'Enter duration (5-180)',
errorText: errorText,
suffixText: 'min',
),
autofocus: true,
onChanged: (value) {
final parsed = int.tryParse(value);
setDialogState(() {
if (parsed == null) {
errorText = 'Please enter a valid number';
} else if (parsed < 5 || parsed > 180) {
errorText = 'Duration must be between 5 and 180 minutes';
} else {
errorText = null;
}
});
},
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
final parsed = int.tryParse(controller.text);
if (parsed != null && parsed >= 5 && parsed <= 180) {
setState(() {
_sleepTimerDuration = parsed;
_settingsService.setSleepTimerDuration(parsed);
});
if (dialogContext.mounted) {
Navigator.pop(dialogContext);
}
}
},
child: const Text('Save'),
),
],
);
},
);
},
);
}
void _showKeyboardShortcutsDialog() {
Navigator.push(
context,
@@ -827,6 +990,63 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
);
}
void _showViewModeDialog() {
final settingsProvider = context.read<SettingsProvider>();
showDialog(
context: context,
builder: (BuildContext context) {
return Consumer<SettingsProvider>(
builder: (context, provider, child) {
return AlertDialog(
title: const Text('View Mode'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: Icon(
provider.viewMode == settings.ViewMode.grid
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('Grid'),
subtitle: const Text('Display items in a grid layout'),
onTap: () async {
await settingsProvider.setViewMode(
settings.ViewMode.grid,
);
if (context.mounted) Navigator.pop(context);
},
),
ListTile(
leading: Icon(
provider.viewMode == settings.ViewMode.list
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('List'),
subtitle: const Text('Display items in a list layout'),
onTap: () async {
await settingsProvider.setViewMode(
settings.ViewMode.list,
);
if (context.mounted) Navigator.pop(context);
},
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
);
},
);
},
);
}
}
class _KeyboardShortcutsScreen extends StatefulWidget {
+328
View File
@@ -0,0 +1,328 @@
import 'package:flutter/material.dart';
import 'package:flex_color_picker/flex_color_picker.dart';
import '../services/settings_service.dart';
import '../widgets/desktop_app_bar.dart';
class SubtitleStylingScreen extends StatefulWidget {
const SubtitleStylingScreen({super.key});
@override
State<SubtitleStylingScreen> createState() => _SubtitleStylingScreenState();
}
class _SubtitleStylingScreenState extends State<SubtitleStylingScreen> {
static const EdgeInsets _sliderPadding = EdgeInsets.fromLTRB(16, 16, 16, 8);
late SettingsService _settingsService;
bool _isLoading = true;
int _fontSize = 55;
String _textColor = '#FFFFFF';
int _borderSize = 3;
String _borderColor = '#000000';
String _backgroundColor = '#000000';
int _backgroundOpacity = 0;
@override
void initState() {
super.initState();
_loadSettings();
}
Future<void> _loadSettings() async {
_settingsService = await SettingsService.getInstance();
setState(() {
_fontSize = _settingsService.getSubtitleFontSize();
_textColor = _settingsService.getSubtitleTextColor();
_borderSize = _settingsService.getSubtitleBorderSize();
_borderColor = _settingsService.getSubtitleBorderColor();
_backgroundColor = _settingsService.getSubtitleBackgroundColor();
_backgroundOpacity = _settingsService.getSubtitleBackgroundOpacity();
_isLoading = false;
});
}
Color _hexToColor(String hexString) {
final buffer = StringBuffer();
if (hexString.length == 7) buffer.write('ff');
buffer.write(hexString.replaceFirst('#', ''));
return Color(int.parse(buffer.toString(), radix: 16));
}
String _colorToHex(Color color) {
return '#${color.red.toRadixString(16).padLeft(2, '0')}${color.green.toRadixString(16).padLeft(2, '0')}${color.blue.toRadixString(16).padLeft(2, '0')}'.toUpperCase();
}
Future<void> _showColorPicker(String title, String currentColor, Function(String) onColorSelected) async {
Color initialColor = _hexToColor(currentColor);
final Color? selectedColor = await showColorPickerDialog(
context,
initialColor,
title: Text(title),
barrierColor: Colors.black54,
width: 40,
height: 40,
spacing: 0,
runSpacing: 0,
borderRadius: 4,
wheelDiameter: 165,
enableOpacity: false,
showColorCode: true,
colorCodeHasColor: true,
pickersEnabled: const <ColorPickerType, bool>{
ColorPickerType.both: false,
ColorPickerType.primary: true,
ColorPickerType.accent: false,
ColorPickerType.wheel: true,
ColorPickerType.custom: false,
},
actionButtons: const ColorPickerActionButtons(
okButton: true,
closeButton: true,
dialogActionButtons: false,
),
);
if (selectedColor != null) {
final hexColor = _colorToHex(selectedColor);
onColorSelected(hexColor);
}
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Subtitle Styling'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildStylingCard(),
const SizedBox(height: 24),
]),
),
),
],
),
);
}
Widget _buildStylingCard() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Styling Options',
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
// Font Size Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Font Size'),
Text('$_fontSize'),
],
),
const SizedBox(height: 8),
Row(
children: [
const Text('30', style: TextStyle(fontSize: 12, color: Colors.grey)),
Expanded(
child: Slider(
value: _fontSize.toDouble(),
min: 30,
max: 80,
divisions: 50,
label: _fontSize.toString(),
onChanged: (value) {
setState(() {
_fontSize = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleFontSize(_fontSize);
},
),
),
const Text('80', style: TextStyle(fontSize: 12, color: Colors.grey)),
],
),
],
),
),
const Divider(),
// Text Color
ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: _hexToColor(_textColor),
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4),
),
),
title: const Text('Text Color'),
subtitle: Text(_textColor),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showColorPicker('Text Color', _textColor, (color) {
setState(() {
_textColor = color;
});
_settingsService.setSubtitleTextColor(color);
});
},
),
const Divider(),
// Border Size Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Border Size'),
Text('$_borderSize'),
],
),
const SizedBox(height: 8),
Row(
children: [
const Text('0', style: TextStyle(fontSize: 12, color: Colors.grey)),
Expanded(
child: Slider(
value: _borderSize.toDouble(),
min: 0,
max: 5,
divisions: 5,
label: _borderSize.toString(),
onChanged: (value) {
setState(() {
_borderSize = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleBorderSize(_borderSize);
},
),
),
const Text('5', style: TextStyle(fontSize: 12, color: Colors.grey)),
],
),
],
),
),
const Divider(),
// Border Color
ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: _hexToColor(_borderColor),
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4),
),
),
title: const Text('Border Color'),
subtitle: Text(_borderColor),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showColorPicker('Border Color', _borderColor, (color) {
setState(() {
_borderColor = color;
});
_settingsService.setSubtitleBorderColor(color);
});
},
),
const Divider(),
// Background Opacity Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Background Opacity'),
Text('$_backgroundOpacity%'),
],
),
const SizedBox(height: 8),
Row(
children: [
const Text('0%', style: TextStyle(fontSize: 12, color: Colors.grey)),
Expanded(
child: Slider(
value: _backgroundOpacity.toDouble(),
min: 0,
max: 100,
divisions: 20,
label: '$_backgroundOpacity%',
onChanged: (value) {
setState(() {
_backgroundOpacity = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleBackgroundOpacity(_backgroundOpacity);
},
),
),
const Text('100%', style: TextStyle(fontSize: 12, color: Colors.grey)),
],
),
],
),
),
const Divider(),
// Background Color
ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: _hexToColor(_backgroundColor),
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4),
),
),
title: const Text('Background Color'),
subtitle: Text(_backgroundColor),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showColorPicker('Background Color', _backgroundColor, (color) {
setState(() {
_backgroundColor = color;
});
_settingsService.setSubtitleBackgroundColor(color);
});
},
),
],
),
);
}
}
+420 -148
View File
@@ -8,11 +8,13 @@ import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../providers/playback_state_provider.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/plex_video_controls.dart';
import '../widgets/video_controls/video_controls.dart';
import '../utils/language_codes.dart';
import '../utils/app_logger.dart';
import '../services/settings_service.dart';
import '../services/audio_service_manager.dart';
import '../utils/orientation_helper.dart';
import '../utils/video_player_navigation.dart';
import '../utils/platform_detector.dart';
@@ -35,10 +37,10 @@ class VideoPlayerScreen extends StatefulWidget {
});
@override
State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
State<VideoPlayerScreen> createState() => VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
class VideoPlayerScreenState extends State<VideoPlayerScreen> {
Player? player;
VideoController? controller;
bool _isPlayerInitialized = false;
@@ -52,6 +54,14 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
List<PlexMediaVersion> _availableVersions = [];
StreamSubscription<PlayerLog>? _logSubscription;
StreamSubscription<String>? _errorSubscription;
StreamSubscription<bool>? _playingSubscription;
StreamSubscription<bool>? _completedSubscription;
bool _isReplacingWithVideo =
false; // Flag to skip orientation restoration during video-to-video navigation
// BoxFit mode state: 0=contain (letterbox), 1=cover (fill screen), 2=fill (stretch)
int _boxFitMode = 0;
bool _isPinching = false; // Track if a pinch gesture is occurring
@override
void initState() {
@@ -95,10 +105,6 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
}
void _setLandscapeOrientation() {
OrientationHelper.setLandscapeOrientation();
}
Future<void> _initializePlayer() async {
try {
// Load buffer size from settings
@@ -117,6 +123,16 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
libassAndroidFontName: 'Droid Sans Fallback',
bufferSize: bufferSizeBytes,
logLevel: debugLoggingEnabled ? MPVLogLevel.debug : MPVLogLevel.error,
mpvConfiguration: {
'sub-font-size': settingsService.getSubtitleFontSize().toString(),
'sub-color': settingsService.getSubtitleTextColor(),
'sub-border-size': settingsService
.getSubtitleBorderSize()
.toString(),
'sub-border-color': settingsService.getSubtitleBorderColor(),
'sub-back-color':
'#${(settingsService.getSubtitleBackgroundOpacity() * 255 / 100).toInt().toRadixString(16).padLeft(2, '0').toUpperCase()}${settingsService.getSubtitleBackgroundColor().replaceFirst('#', '')}',
},
),
);
controller = VideoController(
@@ -126,6 +142,30 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
),
);
// Apply audio sync offset
final audioSyncOffset = settingsService.getAudioSyncOffset();
if (audioSyncOffset != 0) {
final offsetSeconds = audioSyncOffset / 1000.0;
await (player!.platform as dynamic).setProperty(
'audio-delay',
offsetSeconds.toString(),
);
}
// Apply subtitle sync offset
final subtitleSyncOffset = settingsService.getSubtitleSyncOffset();
if (subtitleSyncOffset != 0) {
final offsetSeconds = subtitleSyncOffset / 1000.0;
await (player!.platform as dynamic).setProperty(
'sub-delay',
offsetSeconds.toString(),
);
}
// Apply saved volume
final savedVolume = settingsService.getVolume();
player!.setVolume(savedVolume);
// Notify that player is ready
if (mounted) {
setState(() {
@@ -139,21 +179,35 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Load available media versions
_loadMediaVersions();
// Set fullscreen mode and landscape orientation
// Set fullscreen mode and orientation based on rotation lock setting
if (mounted) {
try {
_setLandscapeOrientation();
// Check rotation lock setting before applying orientation
final isRotationLocked = settingsService.getRotationLocked();
if (isRotationLocked) {
// Locked: Apply landscape orientation only
OrientationHelper.setLandscapeOrientation();
} else {
// Unlocked: Allow all orientations immediately
SystemChrome.setPreferredOrientations(DeviceOrientation.values);
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
}
} catch (e) {
appLogger.w('Failed to set landscape orientation', error: e);
appLogger.w('Failed to set orientation', error: e);
// Don't crash if orientation fails - video can still play
}
}
// Listen to playback state changes
player!.stream.playing.listen(_onPlayingStateChanged);
_playingSubscription = player!.stream.playing.listen(
_onPlayingStateChanged,
);
// Listen to completion
player!.stream.completed.listen(_onVideoCompleted);
_completedSubscription = player!.stream.completed.listen(
_onVideoCompleted,
);
// Listen to MPV logs
_logSubscription = player!.stream.log.listen(_onPlayerLog);
@@ -166,6 +220,9 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Load next/previous episodes
_loadAdjacentEpisodes();
// Initialize audio service for OS media controls
_initializeAudioService();
} catch (e) {
appLogger.e('Failed to initialize player', error: e);
if (mounted) {
@@ -176,6 +233,7 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
}
Future<void> _loadAdjacentEpisodes() async {
if (widget.metadata.type.toLowerCase() != 'episode') {
return;
@@ -187,16 +245,29 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
if (client == null) return;
final playbackState = context.read<PlaybackStateProvider>();
final settingsProvider = context.read<SettingsProvider>();
PlexMetadata? next;
PlexMetadata? previous;
// Check if shuffle mode is active
if (playbackState.isShuffleActive) {
// Get next episode from shuffle queue
next = playbackState.getNextEpisode(widget.metadata.ratingKey);
// No previous episode in shuffle mode
previous = null;
// Get settings
final shuffleOrderNavigation = settingsProvider.shuffleOrderNavigation;
final loopQueue = settingsProvider.shuffleLoopQueue;
if (shuffleOrderNavigation) {
// Use shuffled order for next/previous
next = playbackState.getNextEpisode(
widget.metadata.ratingKey,
loopQueue: loopQueue,
);
previous = playbackState.getPreviousEpisode(widget.metadata.ratingKey);
} else {
// Use chronological order even in shuffle mode
next = await client.findAdjacentEpisode(widget.metadata, 1);
previous = await client.findAdjacentEpisode(widget.metadata, -1);
}
} else {
// Use normal sequential episode loading
next = await client.findAdjacentEpisode(widget.metadata, 1);
@@ -208,12 +279,52 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
_nextEpisode = next;
_previousEpisode = previous;
});
// Update audio handler navigation availability
_updateAudioHandlerNavigation();
}
} catch (e) {
// Silently handle errors
}
}
Future<void> _initializeAudioService() async {
try {
if (player == null) return;
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final audioManager = AudioServiceManager.instance;
// Initialize audio service (will only happen once)
await audioManager.initialize(
player: player!,
plexServerUrl: client.config.baseUrl,
authToken: client.config.token ?? '',
onSkipToNext: _nextEpisode != null ? _playNext : null,
onSkipToPrevious: _previousEpisode != null ? _playPrevious : null,
);
// Update media item with current content
audioManager.updateMediaItem(widget.metadata);
appLogger.d('Audio service initialized/updated successfully');
} catch (e) {
appLogger.e('Failed to initialize audio service', error: e);
// Continue playback even if audio service fails
}
}
void _updateAudioHandlerNavigation() {
final audioManager = AudioServiceManager.instance;
audioManager.updateNavigation(
onNext: _nextEpisode != null ? _playNext : null,
onPrevious: _previousEpisode != null ? _playPrevious : null,
);
}
Future<void> _startPlayback() async {
try {
final clientProvider = context.plexClient;
@@ -229,7 +340,63 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
);
if (videoUrl != null) {
// Open video without auto-playing
// Fetch media info to check for external subtitle tracks
final mediaInfo = await client.getMediaInfo(
widget.metadata.ratingKey,
mediaIndex: widget.selectedMediaIndex,
);
// Build list of external subtitle tracks for media_kit
final externalSubtitles = <SubtitleTrack>[];
if (mediaInfo != null) {
final externalTracks = mediaInfo.subtitleTracks
.where((track) => track.isExternal)
.toList();
if (externalTracks.isNotEmpty) {
appLogger.d(
'Found ${externalTracks.length} external subtitle track(s)',
);
}
for (final plexTrack in externalTracks) {
try {
// Skip if no auth token is available
final token = client.config.token;
if (token == null) {
appLogger.w('No auth token available for external subtitles');
continue;
}
final url = plexTrack.getSubtitleUrl(
client.config.baseUrl,
token,
);
// Skip if URL couldn't be constructed
if (url == null) continue;
externalSubtitles.add(
SubtitleTrack.uri(
url,
title:
plexTrack.displayTitle ??
plexTrack.language ??
'Track ${plexTrack.id}',
language: plexTrack.languageCode,
),
);
} catch (e) {
// Silent fallback - log error but continue with other subtitles
appLogger.w(
'Failed to add external subtitle track ${plexTrack.id}',
error: e,
);
}
}
}
// Open video (without external subtitles in Media constructor)
await player!.open(Media(videoUrl), play: false);
// Wait for media to be ready (duration > 0)
@@ -239,6 +406,33 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
attempts++;
}
// Add external subtitle tracks without auto-selecting them
if (externalSubtitles.isNotEmpty) {
appLogger.d(
'Adding ${externalSubtitles.length} external subtitle(s) to player',
);
final nativePlayer = player!.platform as dynamic;
for (final subtitleTrack in externalSubtitles) {
try {
// Use mpv's sub-add with 'auto' flag to avoid auto-selection
await nativePlayer.command([
'sub-add',
subtitleTrack.id,
'auto',
subtitleTrack.title ?? 'external',
subtitleTrack.language ?? 'auto',
]);
} catch (e) {
appLogger.w(
'Failed to add external subtitle: ${subtitleTrack.title}',
error: e,
);
}
}
}
// Set up playback position if resuming
if (widget.metadata.viewOffset != null &&
widget.metadata.viewOffset! > 0) {
@@ -287,40 +481,83 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
}
/// Cycle through BoxFit modes: contain → cover → fill → contain (for button)
void _cycleBoxFitMode() {
setState(() {
_boxFitMode = (_boxFitMode + 1) % 3;
});
}
/// Toggle between contain and cover modes only (for pinch gesture)
void _toggleContainCover() {
setState(() {
_boxFitMode = _boxFitMode == 0 ? 1 : 0;
});
}
/// Get current BoxFit based on mode
BoxFit get _getCurrentBoxFit {
switch (_boxFitMode) {
case 0:
return BoxFit.contain;
case 1:
return BoxFit.cover;
case 2:
return BoxFit.fill;
default:
return BoxFit.contain;
}
}
@override
void dispose() {
// Stop progress tracking
_progressTimer?.cancel();
// Cancel stream subscriptions
_playingSubscription?.cancel();
_completedSubscription?.cancel();
_logSubscription?.cancel();
_errorSubscription?.cancel();
// Handle audio service based on navigation intent
if (_isReplacingWithVideo) {
// Switching to another episode: pause but keep notification visible
// The new VideoPlayerScreen will update the notification
AudioServiceManager.instance.pause();
} else {
// Truly exiting player: clear notification but keep singleton alive
// This allows controls to reappear when playing again
AudioServiceManager.instance.clearNotification();
}
// Send final stopped state
_sendProgress('stopped');
// Restore system UI and orientation preferences
OrientationHelper.restoreSystemUI();
// Restore system UI and orientation preferences (skip if navigating to another video)
if (!_isReplacingWithVideo) {
OrientationHelper.restoreSystemUI();
// Restore orientation based on cached device type (no context needed)
try {
if (_isPhone) {
// Phone: portrait only
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
} else {
// Tablet/Desktop: all orientations
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
// Restore orientation based on cached device type (no context needed)
try {
if (_isPhone) {
// Phone: portrait only
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
} else {
// Tablet/Desktop: all orientations
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
} catch (e) {
appLogger.w('Failed to restore orientation in dispose', error: e);
}
} catch (e) {
appLogger.w('Failed to restore orientation in dispose', error: e);
}
player?.dispose();
@@ -964,8 +1201,16 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
await _navigateToEpisode(_previousEpisode!);
}
/// Set flag to skip orientation restoration when replacing with another video
void setReplacingWithVideo() {
_isReplacingWithVideo = true;
}
/// Navigates to a new episode, preserving playback state and track selections
Future<void> _navigateToEpisode(PlexMetadata episodeMetadata) async {
// Set flag to skip orientation restoration in dispose()
_isReplacingWithVideo = true;
// If player isn't available, navigate without preserving settings
if (player == null) {
if (mounted) {
@@ -1022,134 +1267,161 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
},
child: Scaffold(
backgroundColor: Colors.black,
body: Stack(
children: [
// Video player
Center(
child: Video(
controller: controller!,
controls: (state) => plexVideoControlsBuilder(
player!,
widget.metadata,
onNext: _nextEpisode != null ? _playNext : null,
onPrevious: _previousEpisode != null ? _playPrevious : null,
availableVersions: _availableVersions,
selectedMediaIndex: widget.selectedMediaIndex,
body: GestureDetector(
behavior: HitTestBehavior
.translucent, // Allow taps to pass through to controls
onScaleStart: (details) {
// Initialize pinch gesture tracking (mobile only)
if (!PlatformDetector.isMobile(context)) return;
_isPinching = false;
},
onScaleUpdate: (details) {
// Track if this is a pinch gesture (2+ fingers) on mobile
if (!PlatformDetector.isMobile(context)) return;
if (details.pointerCount >= 2) {
_isPinching = true;
}
},
onScaleEnd: (details) {
// Only toggle if we detected a pinch gesture on mobile
if (!PlatformDetector.isMobile(context)) return;
if (_isPinching) {
_toggleContainCover();
_isPinching = false;
}
},
child: Stack(
children: [
// Video player
Center(
child: Video(
controller: controller!,
fit: _getCurrentBoxFit,
controls: (state) => plexVideoControlsBuilder(
player!,
widget.metadata,
onNext: _nextEpisode != null ? _playNext : null,
onPrevious: _previousEpisode != null ? _playPrevious : null,
availableVersions: _availableVersions,
selectedMediaIndex: widget.selectedMediaIndex,
boxFitMode: _boxFitMode,
onCycleBoxFitMode: _cycleBoxFitMode,
),
),
),
),
// Play Next Dialog
if (_showPlayNextDialog && _nextEpisode != null)
Positioned.fill(
child: Container(
color: Colors.black.withValues(alpha: 0.8),
child: Center(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 32),
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(
color: Colors.grey[900],
borderRadius: BorderRadius.circular(16),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.play_circle_outline,
size: 64,
color: Colors.white,
),
const SizedBox(height: 24),
Consumer<PlaybackStateProvider>(
builder: (context, playbackState, child) {
final isShuffleActive =
playbackState.isShuffleActive;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Up Next',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
if (isShuffleActive) ...[
const SizedBox(width: 8),
const Icon(
Icons.shuffle,
size: 20,
color: Colors.white70,
),
],
],
);
},
),
const SizedBox(height: 16),
Text(
_nextEpisode!.grandparentTitle ??
_nextEpisode!.title,
style: const TextStyle(
// Play Next Dialog
if (_showPlayNextDialog && _nextEpisode != null)
Positioned.fill(
child: Container(
color: Colors.black.withValues(alpha: 0.8),
child: Center(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 32),
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(
color: Colors.grey[900],
borderRadius: BorderRadius.circular(16),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.play_circle_outline,
size: 64,
color: Colors.white,
fontSize: 18,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
if (_nextEpisode!.parentIndex != null &&
_nextEpisode!.index != null)
const SizedBox(height: 24),
Consumer<PlaybackStateProvider>(
builder: (context, playbackState, child) {
final isShuffleActive =
playbackState.isShuffleActive;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Up Next',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
if (isShuffleActive) ...[
const SizedBox(width: 8),
const Icon(
Icons.shuffle,
size: 20,
color: Colors.white70,
),
],
],
);
},
),
const SizedBox(height: 16),
Text(
'S${_nextEpisode!.parentIndex} · E${_nextEpisode!.index} · ${_nextEpisode!.title}',
_nextEpisode!.grandparentTitle ??
_nextEpisode!.title,
style: const TextStyle(
color: Colors.white70,
fontSize: 16,
color: Colors.white,
fontSize: 18,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlinedButton(
onPressed: () {
setState(() {
_showPlayNextDialog = false;
});
},
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: const BorderSide(color: Colors.white),
padding: const EdgeInsets.symmetric(
horizontal: 32,
vertical: 16,
),
const SizedBox(height: 8),
if (_nextEpisode!.parentIndex != null &&
_nextEpisode!.index != null)
Text(
'S${_nextEpisode!.parentIndex} · E${_nextEpisode!.index} · ${_nextEpisode!.title}',
style: const TextStyle(
color: Colors.white70,
fontSize: 16,
),
child: const Text('Cancel'),
textAlign: TextAlign.center,
),
const SizedBox(width: 16),
FilledButton(
onPressed: _playNext,
style: FilledButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
padding: const EdgeInsets.symmetric(
horizontal: 32,
vertical: 16,
const SizedBox(height: 32),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlinedButton(
onPressed: () {
setState(() {
_showPlayNextDialog = false;
});
},
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: const BorderSide(color: Colors.white),
padding: const EdgeInsets.symmetric(
horizontal: 32,
vertical: 16,
),
),
child: const Text('Cancel'),
),
child: const Text('Play Now'),
),
],
),
],
const SizedBox(width: 16),
FilledButton(
onPressed: _playNext,
style: FilledButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
padding: const EdgeInsets.symmetric(
horizontal: 32,
vertical: 16,
),
),
child: const Text('Play Now'),
),
],
),
],
),
),
),
),
),
),
],
],
),
),
),
);
+186
View File
@@ -0,0 +1,186 @@
import 'package:audio_service/audio_service.dart';
import 'package:media_kit/media_kit.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
import 'media_kit_audio_handler.dart';
/// Global singleton manager for audio service
/// Ensures AudioService.init() is only called once and the handler is reused
class AudioServiceManager {
static AudioServiceManager? _instance;
MediaKitAudioHandler? _handler;
bool _isInitialized = false;
bool _isInitializing = false;
AudioServiceManager._();
static AudioServiceManager get instance {
_instance ??= AudioServiceManager._();
return _instance!;
}
/// Initialize the audio service with the given player and configuration
/// This should only be called once - subsequent calls will reuse the existing handler
Future<void> initialize({
required Player player,
required String plexServerUrl,
required String authToken,
Future<void> Function()? onSkipToNext,
Future<void> Function()? onSkipToPrevious,
}) async {
// If already initialized, update the player reference and callbacks
if (_isInitialized && _handler != null) {
appLogger.d('Audio service already initialized, updating player reference and callbacks');
// Update the player reference (critical for episode switching)
await _handler!.updatePlayer(player);
// Update navigation callbacks
_handler!.onSkipToNext = onSkipToNext;
_handler!.onSkipToPrevious = onSkipToPrevious;
return;
}
// Prevent concurrent initialization
if (_isInitializing) {
appLogger.d('Audio service initialization already in progress, waiting...');
// Wait for initialization to complete
while (_isInitializing) {
await Future.delayed(const Duration(milliseconds: 100));
}
return;
}
try {
_isInitializing = true;
appLogger.d('Initializing audio service for the first time');
final handler = await AudioService.init(
builder: () => MediaKitAudioHandler(
player: player,
plexServerUrl: plexServerUrl,
authToken: authToken,
onSkipToNext: onSkipToNext,
onSkipToPrevious: onSkipToPrevious,
),
config: const AudioServiceConfig(
androidNotificationChannelId: 'com.edde746.plezy.audio',
androidNotificationChannelName: 'Plezy Playback',
androidNotificationOngoing: true,
androidShowNotificationBadge: true,
),
);
_handler = handler;
_isInitialized = true;
appLogger.d('Audio service initialized successfully');
} catch (e) {
appLogger.e('Failed to initialize audio service', error: e);
rethrow;
} finally {
_isInitializing = false;
}
}
/// Update the current media item being played
void updateMediaItem(PlexMetadata metadata) {
if (_handler == null) {
appLogger.w('Cannot update media item: audio handler not initialized');
return;
}
_handler!.updateCurrentMediaItem(metadata);
}
/// Update navigation callbacks for next/previous episode
void updateNavigation({
Future<void> Function()? onNext,
Future<void> Function()? onPrevious,
}) {
if (_handler == null) {
appLogger.w('Cannot update navigation: audio handler not initialized');
return;
}
_handler!.updateNavigationCallbacks(
onNext: onNext,
onPrevious: onPrevious,
);
}
/// Pause playback but keep the media session active
Future<void> pause() async {
if (_handler == null) {
appLogger.w('Cannot pause: audio handler not initialized');
return;
}
await _handler!.pause();
}
/// Clear the notification but keep the audio service singleton alive
/// This is used when exiting the video player but not closing the app
Future<void> clearNotification() async {
if (_handler == null) {
appLogger.w('Cannot clear notification: audio handler not initialized');
return;
}
appLogger.d('Clearing notification while keeping audio service alive');
// Broadcast idle state to remove notification
_handler!.playbackState.add(PlaybackState(
processingState: AudioProcessingState.idle,
playing: false,
controls: [],
systemActions: const {},
updatePosition: Duration.zero,
bufferedPosition: Duration.zero,
speed: 1.0,
));
// Clear media item
_handler!.mediaItem.add(null);
// IMPORTANT: DON'T reset _isInitialized or _handler
// Keep the singleton alive for next playback
appLogger.d('Notification cleared, audio service remains initialized');
}
/// Stop playback completely and remove the notification
/// This should only be called when the app is closing or user explicitly stops
Future<void> shutdown() async {
if (_handler == null) {
appLogger.w('Cannot shutdown: audio handler not initialized');
return;
}
appLogger.d('Shutting down audio service and removing notification');
// Broadcast idle state to remove notification
_handler!.playbackState.add(PlaybackState(
processingState: AudioProcessingState.idle,
playing: false,
controls: [],
systemActions: const {},
updatePosition: Duration.zero,
bufferedPosition: Duration.zero,
speed: 1.0,
));
// Clear media item
_handler!.mediaItem.add(null);
// Dispose the handler
await _handler!.dispose();
_handler = null;
_isInitialized = false;
appLogger.d('Audio service shutdown complete');
}
/// Check if the audio service is initialized
bool get isInitialized => _isInitialized;
/// Get the current handler (for advanced use cases)
MediaKitAudioHandler? get handler => _handler;
}
+5 -1
View File
@@ -262,10 +262,12 @@ class KeyboardShortcutsService {
case 'volume_up':
final newVolume = (player.state.volume + 10).clamp(0.0, 100.0);
player.setVolume(newVolume);
_settingsService.setVolume(newVolume);
break;
case 'volume_down':
final newVolume = (player.state.volume - 10).clamp(0.0, 100.0);
player.setVolume(newVolume);
_settingsService.setVolume(newVolume);
break;
case 'seek_forward':
_seekWithClamping(player, Duration(seconds: _seekTimeSmall));
@@ -283,7 +285,9 @@ class KeyboardShortcutsService {
onToggleFullscreen?.call();
break;
case 'mute_toggle':
player.setVolume(player.state.volume > 0 ? 0.0 : 100.0);
final newVolume = player.state.volume > 0 ? 0.0 : 100.0;
player.setVolume(newVolume);
_settingsService.setVolume(newVolume);
break;
case 'subtitle_toggle':
onToggleSubtitles?.call();
+314
View File
@@ -0,0 +1,314 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:media_kit/media_kit.dart';
import 'package:rxdart/rxdart.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
/// Audio handler that bridges media_kit player with OS media controls
class MediaKitAudioHandler extends BaseAudioHandler with SeekHandler {
Player _player;
final String plexServerUrl;
final String authToken;
// Getter for player
Player get player => _player;
// Callback functions for episode navigation
Future<void> Function()? onSkipToNext;
Future<void> Function()? onSkipToPrevious;
// Stream subscriptions
StreamSubscription<bool>? _playingSubscription;
StreamSubscription<Duration>? _positionSubscription;
StreamSubscription<Duration>? _durationSubscription;
StreamSubscription<Duration>? _bufferSubscription;
// Queue management
final BehaviorSubject<List<MediaItem>> _queueSubject = BehaviorSubject.seeded([]);
MediaKitAudioHandler({
required Player player,
required this.plexServerUrl,
required this.authToken,
this.onSkipToNext,
this.onSkipToPrevious,
}) : _player = player {
_init();
}
void _init() {
// Map player state to playback state
_playingSubscription = _player.stream.playing.listen((isPlaying) {
_updatePlaybackState();
});
_positionSubscription = _player.stream.position.listen((_) {
_updatePlaybackState();
});
_durationSubscription = _player.stream.duration.listen((_) {
_updatePlaybackState();
});
_bufferSubscription = _player.stream.buffer.listen((_) {
_updatePlaybackState();
});
// Set initial state
_updatePlaybackState();
}
/// Update media item with current playing content
void updateCurrentMediaItem(PlexMetadata metadata) {
final artworkUrl = _getArtworkUrl(metadata);
final newMediaItem = MediaItem(
id: metadata.ratingKey,
title: metadata.title,
album: _getAlbumName(metadata),
artist: _getArtistName(metadata),
duration: metadata.duration != null
? Duration(milliseconds: metadata.duration!)
: null,
artUri: artworkUrl != null ? Uri.parse(artworkUrl) : null,
extras: {
'ratingKey': metadata.ratingKey,
'type': metadata.type,
},
);
mediaItem.add(newMediaItem);
appLogger.d('Updated media item: ${metadata.title}');
}
/// Update navigation callbacks
void updateNavigationCallbacks({
Future<void> Function()? onNext,
Future<void> Function()? onPrevious,
}) {
onSkipToNext = onNext;
onSkipToPrevious = onPrevious;
_updatePlaybackState();
}
/// Update the queue with episodes
void updateEpisodeQueue(List<PlexMetadata> episodes, int currentIndex) {
final items = episodes.map((episode) {
final artworkUrl = _getArtworkUrl(episode);
return MediaItem(
id: episode.ratingKey,
title: episode.title,
album: _getAlbumName(episode),
artist: _getArtistName(episode),
duration: episode.duration != null
? Duration(milliseconds: episode.duration!)
: null,
artUri: artworkUrl != null ? Uri.parse(artworkUrl) : null,
extras: {
'ratingKey': episode.ratingKey,
'type': episode.type,
},
);
}).toList();
_queueSubject.add(items);
queue.add(items);
if (currentIndex >= 0 && currentIndex < items.length) {
mediaItem.add(items[currentIndex]);
}
appLogger.d('Updated queue with ${items.length} episodes, current index: $currentIndex');
}
String? _getArtworkUrl(PlexMetadata metadata) {
String? thumbPath;
// For episodes, prefer show poster over episode thumbnail
if (metadata.type.toLowerCase() == 'episode') {
thumbPath = metadata.grandparentThumb ?? metadata.thumb;
} else {
thumbPath = metadata.thumb;
}
if (thumbPath == null) return null;
// Build full URL with authentication
return '$plexServerUrl$thumbPath?X-Plex-Token=$authToken';
}
String _getAlbumName(PlexMetadata metadata) {
// For episodes: "Show Name - Season X"
if (metadata.type.toLowerCase() == 'episode') {
final showName = metadata.grandparentTitle ?? '';
final seasonNum = metadata.parentIndex;
if (seasonNum != null) {
return '$showName - Season $seasonNum';
}
return showName;
}
// For movies: studio or year
return metadata.studio ?? metadata.year?.toString() ?? '';
}
String _getArtistName(PlexMetadata metadata) {
// For episodes: show episode info
if (metadata.type.toLowerCase() == 'episode') {
final seasonNum = metadata.parentIndex;
final episodeNum = metadata.index;
if (seasonNum != null && episodeNum != null) {
return 'S${seasonNum.toString().padLeft(2, '0')}E${episodeNum.toString().padLeft(2, '0')}';
}
}
return '';
}
void _updatePlaybackState() {
final isPlaying = _player.state.playing;
final position = _player.state.position;
final bufferedPosition = _player.state.buffer;
// Determine processing state
AudioProcessingState processingState;
if (_player.state.buffering) {
processingState = AudioProcessingState.buffering;
} else if (_player.state.completed) {
processingState = AudioProcessingState.completed;
} else {
processingState = AudioProcessingState.ready;
}
// Build controls based on state and available navigation
final controls = <MediaControl>[
if (onSkipToPrevious != null) MediaControl.skipToPrevious,
MediaControl.rewind,
if (isPlaying) MediaControl.pause else MediaControl.play,
MediaControl.fastForward,
if (onSkipToNext != null) MediaControl.skipToNext,
];
playbackState.add(PlaybackState(
controls: controls,
systemActions: const {
MediaAction.seek,
MediaAction.seekForward,
MediaAction.seekBackward,
},
androidCompactActionIndices: [
if (onSkipToPrevious != null) 0,
onSkipToPrevious != null ? 2 : 1, // Play/Pause button
if (onSkipToNext != null)
onSkipToPrevious != null ? 4 : 3,
].where((i) => i < controls.length).toList(),
processingState: processingState,
playing: isPlaying,
updatePosition: position,
bufferedPosition: bufferedPosition,
speed: 1.0,
queueIndex: 0, // TODO: Update based on actual queue position
));
}
@override
Future<void> play() async {
appLogger.d('Audio handler: play');
await _player.play();
}
@override
Future<void> pause() async {
appLogger.d('Audio handler: pause');
await _player.pause();
}
@override
Future<void> seek(Duration position) async {
appLogger.d('Audio handler: seek to ${position.inSeconds}s');
await _player.seek(position);
}
@override
Future<void> stop() async {
appLogger.d('Audio handler: stop');
await _player.stop();
}
@override
Future<void> fastForward() async {
appLogger.d('Audio handler: fast forward');
final newPosition = _player.state.position + const Duration(seconds: 10);
await _player.seek(newPosition);
}
@override
Future<void> rewind() async {
appLogger.d('Audio handler: rewind');
final newPosition = _player.state.position - const Duration(seconds: 10);
await _player.seek(newPosition > Duration.zero ? newPosition : Duration.zero);
}
@override
Future<void> skipToNext() async {
appLogger.d('Audio handler: skip to next');
if (onSkipToNext != null) {
await onSkipToNext!();
}
}
@override
Future<void> skipToPrevious() async {
appLogger.d('Audio handler: skip to previous');
if (onSkipToPrevious != null) {
await onSkipToPrevious!();
}
}
/// Update the player reference when switching episodes
/// This ensures the handler stays in sync with the current player instance
Future<void> updatePlayer(Player newPlayer) async {
appLogger.d('Audio handler: updating player reference');
// Cancel old subscriptions
await _playingSubscription?.cancel();
await _positionSubscription?.cancel();
await _durationSubscription?.cancel();
await _bufferSubscription?.cancel();
// Update player reference
_player = newPlayer;
// Create new subscriptions with the new player
_playingSubscription = _player.stream.playing.listen((isPlaying) {
_updatePlaybackState();
});
_positionSubscription = _player.stream.position.listen((_) {
_updatePlaybackState();
});
_durationSubscription = _player.stream.duration.listen((_) {
_updatePlaybackState();
});
_bufferSubscription = _player.stream.buffer.listen((_) {
_updatePlaybackState();
});
// Update playback state immediately
_updatePlaybackState();
appLogger.d('Audio handler: player reference updated successfully');
}
Future<void> dispose() async {
// Cancel subscriptions
await _playingSubscription?.cancel();
await _positionSubscription?.cancel();
await _durationSubscription?.cancel();
await _bufferSubscription?.cancel();
await _queueSubject.close();
}
}
+56 -10
View File
@@ -250,9 +250,18 @@ class PlexServer {
factory PlexServer.fromJson(Map<String, dynamic> json) {
final List<dynamic> connectionsJson = json['connections'] as List<dynamic>;
final connections = connectionsJson
.map((c) => PlexConnection.fromJson(c as Map<String, dynamic>))
.toList();
final connections = <PlexConnection>[];
// Parse connections and generate HTTP fallbacks for HTTPS connections
for (final c in connectionsJson) {
final connection = PlexConnection.fromJson(c as Map<String, dynamic>);
connections.add(connection);
// Generate HTTP fallback for HTTPS connections
if (connection.protocol == 'https') {
connections.add(connection.toHttpFallback());
}
}
DateTime? lastSeenAt;
if (json['lastSeenAt'] != null) {
@@ -317,18 +326,33 @@ class PlexServer {
/// Returns a Stream that emits connections progressively:
/// 1. First emission: The first connection that responds successfully
/// 2. Second emission (optional): The best connection after latency testing
/// Priority: local > remote > relay (from successful connections)
/// Priority: local > remote > relay, then HTTPS > HTTP, then lowest latency
/// Tests both plex.direct URI and direct IP for each connection
/// HTTPS connections are tested first, with HTTP as fallback
Stream<PlexConnection> findBestWorkingConnection() async* {
if (connections.isEmpty) return;
// Create candidates: test both uri and directUrl for each connection
final candidates = <_ConnectionCandidate>[];
// Separate HTTPS and HTTP candidates to prioritize HTTPS first
final httpsCandidates = <_ConnectionCandidate>[];
final httpCandidates = <_ConnectionCandidate>[];
for (final connection in connections) {
candidates.add(_ConnectionCandidate(connection, connection.uri, true));
candidates.add(_ConnectionCandidate(connection, connection.directUrl, false));
final uriCandidate = _ConnectionCandidate(connection, connection.uri, true);
final directCandidate = _ConnectionCandidate(connection, connection.directUrl, false);
if (connection.protocol == 'https') {
httpsCandidates.add(uriCandidate);
httpsCandidates.add(directCandidate);
} else {
httpCandidates.add(uriCandidate);
httpCandidates.add(directCandidate);
}
}
// Combine candidates with HTTPS first, then HTTP
final candidates = [...httpsCandidates, ...httpCandidates];
// Phase 1: Race to find first working connection
final completer = Completer<_ConnectionCandidate?>();
_ConnectionCandidate? firstCandidate;
@@ -444,18 +468,24 @@ class PlexServer {
_findLowestLatencyCandidate(relayCandidates);
}
/// Find the candidate with lowest latency, preferring plex.direct URI on tie
/// Find the candidate with lowest latency, preferring HTTPS and plex.direct URI on tie
_ConnectionCandidate? _findLowestLatencyCandidate(
List<MapEntry<_ConnectionCandidate, ConnectionTestResult>> entries,
) {
if (entries.isEmpty) return null;
// Sort by latency first, then by URL type (prefer plex.direct)
// Sort by latency first, then by protocol (HTTPS > HTTP), then by URL type (prefer plex.direct)
entries.sort((a, b) {
final latencyCompare = a.value.latencyMs.compareTo(b.value.latencyMs);
if (latencyCompare != 0) return latencyCompare;
// If latencies are equal, prefer plex.direct URI (isPlexDirectUri = true)
// If latencies are equal, prefer HTTPS over HTTP
final aIsHttps = a.key.connection.protocol == 'https';
final bIsHttps = b.key.connection.protocol == 'https';
if (aIsHttps && !bIsHttps) return -1;
if (!aIsHttps && bIsHttps) return 1;
// If latencies and protocols are equal, prefer plex.direct URI (isPlexDirectUri = true)
if (a.key.isPlexDirectUri && !b.key.isPlexDirectUri) return -1;
if (!a.key.isPlexDirectUri && b.key.isPlexDirectUri) return 1;
return 0;
@@ -518,4 +548,20 @@ class PlexConnection {
if (local) return 'Local';
return 'Remote';
}
/// Create an HTTP fallback version of this HTTPS connection
/// This allows testing HTTP when HTTPS is unavailable (e.g., certificate issues)
PlexConnection toHttpFallback() {
assert(protocol == 'https', 'Can only create HTTP fallback for HTTPS connections');
return PlexConnection(
protocol: 'http',
address: address,
port: port,
uri: uri.replaceFirst('https://', 'http://'),
local: local,
relay: relay,
ipv6: ipv6,
);
}
}
+176
View File
@@ -8,6 +8,8 @@ enum ThemeMode { system, light, dark }
enum LibraryDensity { compact, normal, comfortable }
enum ViewMode { grid, list }
class SettingsService {
static const String _keyThemeMode = 'theme_mode';
static const String _keyEnableDebugLogging = 'enable_debug_logging';
@@ -18,11 +20,26 @@ class SettingsService {
static const String _keyPreferredVideoCodec = 'preferred_video_codec';
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 _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 _keySleepTimerDuration = 'sleep_timer_duration';
static const String _keyAudioSyncOffset = 'audio_sync_offset';
static const String _keySubtitleSyncOffset = 'subtitle_sync_offset';
static const String _keyVolume = 'volume';
static const String _keyRotationLocked = 'rotation_locked';
static const String _keySubtitleFontSize = 'subtitle_font_size';
static const String _keySubtitleTextColor = 'subtitle_text_color';
static const String _keySubtitleBorderSize = 'subtitle_border_size';
static const String _keySubtitleBorderColor = 'subtitle_border_color';
static const String _keySubtitleBackgroundColor = 'subtitle_background_color';
static const String _keySubtitleBackgroundOpacity = 'subtitle_background_opacity';
static const String _keyShuffleUnwatchedOnly = 'shuffle_unwatched_only';
static const String _keyShuffleOrderNavigation = 'shuffle_order_navigation';
static const String _keyShuffleLoopQueue = 'shuffle_loop_queue';
static SettingsService? _instance;
late SharedPreferences _prefs;
@@ -115,6 +132,19 @@ class SettingsService {
);
}
// View Mode
Future<void> setViewMode(ViewMode mode) async {
await _prefs.setString(_keyViewMode, mode.name);
}
ViewMode getViewMode() {
final modeString = _prefs.getString(_keyViewMode);
return ViewMode.values.firstWhere(
(mode) => mode.name == modeString,
orElse: () => ViewMode.grid,
);
}
// Use Season Poster
Future<void> setUseSeasonPoster(bool enabled) async {
await _prefs.setBool(_keyUseSeasonPoster, enabled);
@@ -153,6 +183,108 @@ class SettingsService {
return _prefs.getInt(_keySeekTimeLarge) ?? 30; // Default: 30 seconds
}
// Sleep Timer Duration (in minutes)
Future<void> setSleepTimerDuration(int minutes) async {
await _prefs.setInt(_keySleepTimerDuration, minutes);
}
int getSleepTimerDuration() {
return _prefs.getInt(_keySleepTimerDuration) ?? 30; // Default: 30 minutes
}
// Audio Sync Offset (in milliseconds)
Future<void> setAudioSyncOffset(int milliseconds) async {
await _prefs.setInt(_keyAudioSyncOffset, milliseconds);
}
int getAudioSyncOffset() {
return _prefs.getInt(_keyAudioSyncOffset) ?? 0; // Default: 0ms (no offset)
}
// Subtitle Sync Offset (in milliseconds)
Future<void> setSubtitleSyncOffset(int milliseconds) async {
await _prefs.setInt(_keySubtitleSyncOffset, milliseconds);
}
int getSubtitleSyncOffset() {
return _prefs.getInt(_keySubtitleSyncOffset) ??
0; // Default: 0ms (no offset)
}
// Volume (0.0 to 100.0)
Future<void> setVolume(double volume) async {
await _prefs.setDouble(_keyVolume, volume);
}
double getVolume() {
return _prefs.getDouble(_keyVolume) ?? 100.0; // Default: full volume
}
// Rotation Lock (mobile only)
Future<void> setRotationLocked(bool locked) async {
await _prefs.setBool(_keyRotationLocked, locked);
}
bool getRotationLocked() {
return _prefs.getBool(_keyRotationLocked) ?? true; // Default: locked (landscape only)
}
// Subtitle Styling Settings
// Font Size (30-80, default 55)
Future<void> setSubtitleFontSize(int size) async {
await _prefs.setInt(_keySubtitleFontSize, size);
}
int getSubtitleFontSize() {
return _prefs.getInt(_keySubtitleFontSize) ?? 55;
}
// Text Color (hex format #RRGGBB, default white)
Future<void> setSubtitleTextColor(String color) async {
await _prefs.setString(_keySubtitleTextColor, color);
}
String getSubtitleTextColor() {
return _prefs.getString(_keySubtitleTextColor) ?? '#FFFFFF';
}
// Border Size (0-5, default 3)
Future<void> setSubtitleBorderSize(int size) async {
await _prefs.setInt(_keySubtitleBorderSize, size);
}
int getSubtitleBorderSize() {
return _prefs.getInt(_keySubtitleBorderSize) ?? 3;
}
// Border Color (hex format #RRGGBB, default black)
Future<void> setSubtitleBorderColor(String color) async {
await _prefs.setString(_keySubtitleBorderColor, color);
}
String getSubtitleBorderColor() {
return _prefs.getString(_keySubtitleBorderColor) ?? '#000000';
}
// Background Color (hex format #RRGGBB, default black)
Future<void> setSubtitleBackgroundColor(String color) async {
await _prefs.setString(_keySubtitleBackgroundColor, color);
}
String getSubtitleBackgroundColor() {
return _prefs.getString(_keySubtitleBackgroundColor) ?? '#000000';
}
// Background Opacity (0-100, default 0 for transparent)
Future<void> setSubtitleBackgroundOpacity(int opacity) async {
await _prefs.setInt(_keySubtitleBackgroundOpacity, opacity);
}
int getSubtitleBackgroundOpacity() {
return _prefs.getInt(_keySubtitleBackgroundOpacity) ?? 0;
}
// Keyboard Shortcuts (Legacy String-based)
Map<String, String> getDefaultKeyboardShortcuts() {
return {
@@ -648,6 +780,35 @@ class SettingsService {
}
}
// Shuffle Play Settings
/// Shuffle Unwatched Only - Filter shuffle queue to unwatched episodes only
Future<void> setShuffleUnwatchedOnly(bool enabled) async {
await _prefs.setBool(_keyShuffleUnwatchedOnly, enabled);
}
bool getShuffleUnwatchedOnly() {
return _prefs.getBool(_keyShuffleUnwatchedOnly) ?? true; // Default: true
}
/// Shuffle Order Navigation - Next/previous buttons follow shuffled order
Future<void> setShuffleOrderNavigation(bool enabled) async {
await _prefs.setBool(_keyShuffleOrderNavigation, enabled);
}
bool getShuffleOrderNavigation() {
return _prefs.getBool(_keyShuffleOrderNavigation) ?? true; // Default: true
}
/// Shuffle Loop Queue - Restart queue when reaching the end
Future<void> setShuffleLoopQueue(bool enabled) async {
await _prefs.setBool(_keyShuffleLoopQueue, enabled);
}
bool getShuffleLoopQueue() {
return _prefs.getBool(_keyShuffleLoopQueue) ?? false; // Default: false
}
// Reset all settings to defaults
Future<void> resetAllSettings() async {
await Future.wait([
@@ -660,11 +821,25 @@ class SettingsService {
_prefs.remove(_keyPreferredVideoCodec),
_prefs.remove(_keyPreferredAudioCodec),
_prefs.remove(_keyLibraryDensity),
_prefs.remove(_keyViewMode),
_prefs.remove(_keyUseSeasonPoster),
_prefs.remove(_keyShowHeroSection),
_prefs.remove(_keySeekTimeSmall),
_prefs.remove(_keySeekTimeLarge),
_prefs.remove(_keyMediaVersionPreferences),
_prefs.remove(_keySleepTimerDuration),
_prefs.remove(_keyAudioSyncOffset),
_prefs.remove(_keySubtitleSyncOffset),
_prefs.remove(_keyVolume),
_prefs.remove(_keySubtitleFontSize),
_prefs.remove(_keySubtitleTextColor),
_prefs.remove(_keySubtitleBorderSize),
_prefs.remove(_keySubtitleBorderColor),
_prefs.remove(_keySubtitleBackgroundColor),
_prefs.remove(_keySubtitleBackgroundOpacity),
_prefs.remove(_keyShuffleUnwatchedOnly),
_prefs.remove(_keyShuffleOrderNavigation),
_prefs.remove(_keyShuffleLoopQueue),
]);
}
@@ -688,6 +863,7 @@ class SettingsService {
'preferredVideoCodec': getPreferredVideoCodec(),
'preferredAudioCodec': getPreferredAudioCodec(),
'libraryDensity': getLibraryDensity().name,
'viewMode': getViewMode().name,
'useSeasonPoster': getUseSeasonPoster(),
'seekTimeSmall': getSeekTimeSmall(),
'seekTimeLarge': getSeekTimeLarge(),
+105
View File
@@ -0,0 +1,105 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../utils/app_logger.dart';
/// Service to manage sleep timer functionality
/// Allows setting a timer to pause/stop playback after a specified duration
class SleepTimerService extends ChangeNotifier {
static final SleepTimerService _instance = SleepTimerService._internal();
factory SleepTimerService() => _instance;
SleepTimerService._internal();
Timer? _timer;
DateTime? _endTime;
Duration? _duration;
VoidCallback? _onTimerComplete;
/// Whether a timer is currently active
bool get isActive => _timer != null && _timer!.isActive;
/// The time when the timer will complete
DateTime? get endTime => _endTime;
/// The original duration of the timer
Duration? get duration => _duration;
/// Remaining time on the timer
Duration? get remainingTime {
if (_endTime == null) return null;
final remaining = _endTime!.difference(DateTime.now());
return remaining.isNegative ? Duration.zero : remaining;
}
/// Start a sleep timer with the specified duration
/// [duration] - How long until the timer completes
/// [onComplete] - Callback to execute when timer completes
void startTimer(Duration duration, VoidCallback onComplete) {
// Cancel any existing timer
cancelTimer();
_duration = duration;
_endTime = DateTime.now().add(duration);
_onTimerComplete = onComplete;
appLogger.d('Sleep timer started: ${duration.inMinutes} minutes');
// Create a periodic timer to update remaining time
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
final remaining = remainingTime;
if (remaining == null || remaining.inSeconds <= 0) {
appLogger.d('Sleep timer completed');
_executeCallback();
cancelTimer();
} else {
// Notify listeners to update UI
notifyListeners();
}
});
notifyListeners();
}
/// Cancel the active timer
void cancelTimer() {
if (_timer != null) {
appLogger.d('Sleep timer cancelled');
_timer?.cancel();
_timer = null;
_endTime = null;
_duration = null;
_onTimerComplete = null;
notifyListeners();
}
}
/// Extend the current timer by the specified duration
void extendTimer(Duration additionalTime) {
if (_endTime != null) {
_endTime = _endTime!.add(additionalTime);
_duration = _duration != null
? _duration! + additionalTime
: additionalTime;
appLogger.d(
'Sleep timer extended by ${additionalTime.inMinutes} minutes',
);
notifyListeners();
}
}
void _executeCallback() {
if (_onTimerComplete != null) {
try {
_onTimerComplete!();
} catch (e) {
appLogger.e('Error executing sleep timer callback', error: e);
}
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}
+115
View File
@@ -0,0 +1,115 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/playback_state_provider.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
/// Handle shuffle play action for shows and seasons
///
/// Fetches episodes based on user settings (unwatched only or including watched),
/// shuffles them, and starts playback from the first shuffled episode.
/// The shuffle queue is stored in the PlaybackStateProvider for continuous shuffle playback.
Future<void> handleShufflePlay(
BuildContext context,
PlexMetadata metadata,
) async {
final client = context.client;
if (client == null) return;
final playbackState = context.read<PlaybackStateProvider>();
final settingsProvider = context.read<SettingsProvider>();
final itemType = metadata.type.toLowerCase();
// Get shuffle setting
final unwatchedOnly = settingsProvider.shuffleUnwatchedOnly;
try {
// Show loading indicator
if (context.mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) =>
const Center(child: CircularProgressIndicator()),
);
}
// Get episodes based on type and settings
List<PlexMetadata> episodes;
if (itemType == 'show') {
if (unwatchedOnly) {
// Get only unwatched episodes
episodes = await client.getAllUnwatchedEpisodes(
metadata.ratingKey,
);
} else {
// Get all episodes from all seasons
final allEpisodes = <PlexMetadata>[];
final seasons = await client.getChildren(metadata.ratingKey);
for (final season in seasons) {
if (season.type == 'season') {
final seasonEpisodes = await client.getChildren(season.ratingKey);
final episodesOnly = seasonEpisodes
.where((ep) => ep.type == 'episode')
.toList();
allEpisodes.addAll(episodesOnly);
}
}
episodes = allEpisodes;
}
} else {
// season
if (unwatchedOnly) {
// Get only unwatched episodes
episodes = await client.getUnwatchedEpisodesInSeason(
metadata.ratingKey,
);
} else {
// Get all episodes in season
final seasonEpisodes = await client.getChildren(metadata.ratingKey);
episodes = seasonEpisodes
.where((ep) => ep.type == 'episode')
.toList();
}
}
// Close loading indicator
if (context.mounted) {
Navigator.pop(context);
}
if (episodes.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No episodes found')),
);
}
return;
}
// Shuffle the episodes
episodes.shuffle();
// Store shuffle queue in provider
playbackState.setShuffleQueue(episodes, metadata.ratingKey);
// Navigate to first episode
if (context.mounted) {
await navigateToVideoPlayer(context, metadata: episodes.first);
}
} catch (e) {
// Close loading indicator if it's still open
if (context.mounted && Navigator.canPop(context)) {
Navigator.pop(context);
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error starting shuffle play: $e')),
);
}
}
}
+5 -2
View File
@@ -32,6 +32,9 @@ Future<bool?> navigateToVideoPlayer(
int? selectedMediaIndex,
bool usePushReplacement = false,
}) async {
// Extract navigator before any async operations
final navigator = Navigator.of(context);
// Load saved media version preference if not explicitly provided
int mediaIndex = selectedMediaIndex ?? 0;
if (selectedMediaIndex == null) {
@@ -60,8 +63,8 @@ Future<bool?> navigateToVideoPlayer(
);
if (usePushReplacement) {
return Navigator.of(context).pushReplacement<bool, bool>(route);
return navigator.pushReplacement<bool, bool>(route);
} else {
return Navigator.push<bool>(context, route);
return navigator.push<bool>(route);
}
}
+401 -77
View File
@@ -4,8 +4,10 @@ import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/plex_client_provider.dart';
import '../providers/settings_provider.dart';
import '../services/settings_service.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/content_rating_formatter.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import '../theme/theme_helper.dart';
@@ -16,6 +18,7 @@ class MediaCard extends StatefulWidget {
final double? width;
final double? height;
final void Function(String ratingKey)? onRefresh;
final bool forceGridMode;
const MediaCard({
super.key,
@@ -23,6 +26,7 @@ class MediaCard extends StatefulWidget {
this.width,
this.height,
this.onRefresh,
this.forceGridMode = false,
});
@override
@@ -84,88 +88,124 @@ class _MediaCardState extends State<MediaCard> {
}
}
@override
Widget build(BuildContext context) {
final settingsProvider = context.watch<SettingsProvider>();
final viewMode = widget.forceGridMode
? ViewMode.grid
: settingsProvider.viewMode;
return MediaContextMenu(
metadata: widget.item,
onRefresh: widget.onRefresh,
onTap: () => _handleTap(context),
child: viewMode == ViewMode.grid
? _MediaCardGrid(
item: widget.item,
width: widget.width,
height: widget.height,
onTap: () => _handleTap(context),
)
: _MediaCardList(
item: widget.item,
onTap: () => _handleTap(context),
density: settingsProvider.libraryDensity,
),
);
}
}
/// Grid layout for media cards
class _MediaCardGrid extends StatelessWidget {
final PlexMetadata item;
final double? width;
final double? height;
final VoidCallback onTap;
const _MediaCardGrid({
required this.item,
this.width,
this.height,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return SizedBox(
width: widget.width,
child: MediaContextMenu(
metadata: widget.item,
onRefresh: widget.onRefresh,
onTap: () => _handleTap(context),
child: Semantics(
label: "media-card-${widget.item.ratingKey}",
identifier: "media-card-${widget.item.ratingKey}",
button: true,
child: InkWell(
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Poster
if (widget.height != null)
SizedBox(
width: double.infinity,
height: widget.height,
child: _buildPosterWithOverlay(context),
)
else
Expanded(child: _buildPosterWithOverlay(context)),
const SizedBox(height: 4),
// Text content
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
width: width,
child: Semantics(
label: "media-card-${item.ratingKey}",
identifier: "media-card-${item.ratingKey}",
button: true,
child: InkWell(
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Poster
if (height != null)
SizedBox(
width: double.infinity,
height: height,
child: _buildPosterWithOverlay(context),
)
else
Expanded(child: _buildPosterWithOverlay(context)),
const SizedBox(height: 4),
// Text content
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
item.displayTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
height: 1.1,
),
),
if (item.displaySubtitle != null)
Text(
widget.item.displayTitle,
item.displaySubtitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
height: 1.1,
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
)
else if (item.parentTitle != null)
Text(
item.parentTitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
)
else if (item.year != null)
Text(
'${item.year}',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
),
if (widget.item.displaySubtitle != null)
Text(
widget.item.displaySubtitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
)
else if (widget.item.parentTitle != null)
Text(
widget.item.parentTitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
)
else if (widget.item.year != null)
Text(
'${widget.item.year}',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
),
],
),
],
),
],
),
],
),
),
),
@@ -180,14 +220,298 @@ class _MediaCardState extends State<MediaCard> {
borderRadius: BorderRadius.circular(8),
child: _buildPosterImage(context),
),
_PosterOverlay(item: widget.item),
_PosterOverlay(item: item),
],
);
}
Widget _buildPosterImage(BuildContext context) {
final useSeasonPoster = context.watch<SettingsProvider>().useSeasonPoster;
final posterUrl = widget.item.posterThumb(useSeasonPoster: useSeasonPoster);
final posterUrl = item.posterThumb(useSeasonPoster: useSeasonPoster);
if (posterUrl != null) {
return Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return const SkeletonLoader(
child: Center(
child: Icon(Icons.movie, size: 40, color: Colors.white54),
),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(posterUrl),
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
filterQuality: FilterQuality.medium,
fadeInDuration: const Duration(milliseconds: 300),
placeholder: (context, url) => const SkeletonLoader(),
errorWidget: (context, url, error) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(child: Icon(Icons.broken_image, size: 40)),
),
);
},
);
} else {
return const SkeletonLoader(
child: Center(
child: Icon(Icons.movie, size: 40, color: Colors.white54),
),
);
}
}
}
/// List layout for media cards
class _MediaCardList extends StatelessWidget {
final PlexMetadata item;
final VoidCallback onTap;
final LibraryDensity density;
const _MediaCardList({
required this.item,
required this.onTap,
required this.density,
});
double get _posterWidth {
switch (density) {
case LibraryDensity.compact:
return 80;
case LibraryDensity.normal:
return 100;
case LibraryDensity.comfortable:
return 120;
}
}
double get _posterHeight {
return _posterWidth * 1.5; // Maintain 2:3 aspect ratio
}
double get _titleFontSize {
switch (density) {
case LibraryDensity.compact:
return 14;
case LibraryDensity.normal:
return 15;
case LibraryDensity.comfortable:
return 16;
}
}
double get _metadataFontSize {
switch (density) {
case LibraryDensity.compact:
return 11;
case LibraryDensity.normal:
return 12;
case LibraryDensity.comfortable:
return 13;
}
}
double get _subtitleFontSize {
switch (density) {
case LibraryDensity.compact:
return 12;
case LibraryDensity.normal:
return 13;
case LibraryDensity.comfortable:
return 14;
}
}
double get _summaryFontSize {
switch (density) {
case LibraryDensity.compact:
return 11;
case LibraryDensity.normal:
return 12;
case LibraryDensity.comfortable:
return 13;
}
}
int get _summaryMaxLines {
switch (density) {
case LibraryDensity.compact:
return 2;
case LibraryDensity.normal:
return 3;
case LibraryDensity.comfortable:
return 4;
}
}
String _formatDuration(int milliseconds) {
final duration = Duration(milliseconds: milliseconds);
final hours = duration.inHours;
final minutes = duration.inMinutes.remainder(60);
if (hours > 0) {
return '${hours}h ${minutes}m';
} else {
return '${minutes}m';
}
}
String _buildMetadataLine() {
final parts = <String>[];
// Add content rating
if (item.contentRating != null && item.contentRating!.isNotEmpty) {
final rating = formatContentRating(item.contentRating);
if (rating.isNotEmpty) {
parts.add(rating);
}
}
// Add year
if (item.year != null) {
parts.add('${item.year}');
}
// Add duration
if (item.duration != null) {
parts.add(_formatDuration(item.duration!));
}
// Add user rating
if (item.rating != null) {
parts.add('${item.rating!.toStringAsFixed(1)}★');
}
// Add studio
if (item.studio != null && item.studio!.isNotEmpty) {
parts.add(item.studio!);
}
return parts.join(' • ');
}
String? _buildSubtitleText() {
// For TV episodes, show S#E# format
if (item.parentIndex != null && item.index != null) {
return 'S${item.parentIndex} E${item.index}';
}
// Otherwise use existing subtitle logic
if (item.displaySubtitle != null) {
return item.displaySubtitle;
} else if (item.parentTitle != null) {
return item.parentTitle;
}
// Year is now shown in metadata line, so don't show it here
return null;
}
@override
Widget build(BuildContext context) {
final metadataLine = _buildMetadataLine();
final subtitle = _buildSubtitleText();
return Semantics(
label: "media-card-${item.ratingKey}",
identifier: "media-card-${item.ratingKey}",
button: true,
child: InkWell(
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Poster (responsive size based on density)
SizedBox(
width: _posterWidth,
height: _posterHeight,
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: _buildPosterImage(context),
),
_PosterOverlay(item: item),
],
),
),
const SizedBox(width: 12),
// Metadata
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
// Title
Text(
item.displayTitle,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: _titleFontSize,
height: 1.2,
),
),
const SizedBox(height: 4),
// Metadata info line (rating, duration, score, studio)
if (metadataLine.isNotEmpty) ...[
Text(
metadataLine,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted.withValues(alpha: 0.9),
fontSize: _metadataFontSize,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 2),
],
// Subtitle (S#E# or year/parent title)
if (subtitle != null) ...[
Text(
subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted.withValues(alpha: 0.85),
fontSize: _subtitleFontSize,
),
),
const SizedBox(height: 4),
],
// Summary
if (item.summary != null) ...[
Text(
item.summary!,
maxLines: _summaryMaxLines,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted.withValues(alpha: 0.7),
fontSize: _summaryFontSize,
height: 1.3,
),
),
],
],
),
),
],
),
),
),
);
}
Widget _buildPosterImage(BuildContext context) {
final useSeasonPoster = context.watch<SettingsProvider>().useSeasonPoster;
final posterUrl = item.posterThumb(useSeasonPoster: useSeasonPoster);
if (posterUrl != null) {
return Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
+2 -73
View File
@@ -1,13 +1,11 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../utils/provider_extensions.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import '../widgets/file_info_bottom_sheet.dart';
import '../providers/playback_state_provider.dart';
import '../utils/video_player_navigation.dart';
import '../utils/shuffle_play_helper.dart';
/// Helper class to store menu action data
class _MenuAction {
@@ -251,7 +249,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
break;
case 'shuffle_play':
await _handleShufflePlay(context);
await handleShufflePlay(context, widget.metadata);
break;
}
}
@@ -364,75 +362,6 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
}
}
/// Handle shuffle play action
Future<void> _handleShufflePlay(BuildContext context) async {
final client = context.client;
if (client == null) return;
final playbackState = context.read<PlaybackStateProvider>();
final itemType = widget.metadata.type.toLowerCase();
try {
// Show loading indicator
if (context.mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) =>
const Center(child: CircularProgressIndicator()),
);
}
// Get unwatched episodes based on type
List<PlexMetadata> episodes;
if (itemType == 'show') {
episodes = await client.getAllUnwatchedEpisodes(
widget.metadata.ratingKey,
);
} else {
// season
episodes = await client.getUnwatchedEpisodesInSeason(
widget.metadata.ratingKey,
);
}
// Close loading indicator
if (context.mounted) {
Navigator.pop(context);
}
if (episodes.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No unwatched episodes found')),
);
}
return;
}
// Shuffle the episodes
episodes.shuffle();
// Store shuffle queue in provider
playbackState.setShuffleQueue(episodes, widget.metadata.ratingKey);
// Navigate to first episode
if (context.mounted) {
await navigateToVideoPlayer(context, metadata: episodes.first);
}
} catch (e) {
// Close loading indicator if it's still open
if (context.mounted && Navigator.canPop(context)) {
Navigator.pop(context);
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error starting shuffle play: $e')),
);
}
}
}
@override
Widget build(BuildContext context) {
+53 -50
View File
@@ -90,57 +90,60 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
),
),
Expanded(
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: widget.sortOptions.length,
itemBuilder: (context, index) {
final sort = widget.sortOptions[index];
final isSelected = _currentSort?.key == sort.key;
return ListTile(
title: Text(sort.title),
trailing: isSelected
? Row(
mainAxisSize: MainAxisSize.min,
children: [
SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: Icon(Icons.arrow_upward, size: 16),
),
ButtonSegment(
value: true,
icon: Icon(Icons.arrow_downward, size: 16),
),
],
selected: {_currentDescending},
onSelectionChanged: (Set<bool> newSelection) {
_handleSortChange(sort, newSelection.first);
},
),
],
)
: null,
leading: Radio<PlexSort>(
value: sort,
groupValue: _currentSort,
onChanged: (PlexSort? value) {
if (value != null) {
_handleSortChange(
value,
value.defaultDirection == 'desc',
);
}
},
),
onTap: () {
_handleSortChange(sort, sort.defaultDirection == 'desc');
},
);
child: RadioGroup<PlexSort>(
groupValue: _currentSort,
onChanged: (PlexSort? value) {
if (value != null) {
_handleSortChange(
value,
value.defaultDirection == 'desc',
);
}
},
child: ListView.builder(
controller: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: widget.sortOptions.length,
itemBuilder: (context, index) {
final sort = widget.sortOptions[index];
final isSelected = _currentSort?.key == sort.key;
return ListTile(
title: Text(sort.title),
trailing: isSelected
? Row(
mainAxisSize: MainAxisSize.min,
children: [
SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: Icon(Icons.arrow_upward, size: 16),
),
ButtonSegment(
value: true,
icon: Icon(Icons.arrow_downward, size: 16),
),
],
selected: {_currentDescending},
onSelectionChanged: (Set<bool> newSelection) {
_handleSortChange(sort, newSelection.first);
},
),
],
)
: null,
leading: Radio<PlexSort>(
value: sort,
toggleable: false,
),
onTap: () {
_handleSortChange(sort, sort.defaultDirection == 'desc');
},
);
},
),
),
),
],
@@ -0,0 +1,39 @@
import 'package:flutter/material.dart';
import '../../../models/plex_media_info.dart';
/// Custom painter for drawing chapter markers on the video timeline slider
class ChapterMarkerPainter extends CustomPainter {
final List<PlexChapter> chapters;
final Duration duration;
ChapterMarkerPainter({required this.chapters, required this.duration});
@override
void paint(Canvas canvas, Size size) {
if (duration.inMilliseconds == 0) return;
final paint = Paint()
..color = Colors.white.withValues(alpha: 0.7)
..strokeWidth = 2
..strokeCap = StrokeCap.round;
for (final chapter in chapters) {
final startMs = chapter.startTimeOffset ?? 0;
if (startMs == 0) continue; // Skip first chapter marker at 0:00
final position = (startMs / duration.inMilliseconds) * size.width;
// Draw short vertical line for chapter marker (centered on slider track)
canvas.drawLine(
Offset(position, size.height * 0.45),
Offset(position, size.height * 0.55),
paint,
);
}
}
@override
bool shouldRepaint(ChapterMarkerPainter oldDelegate) {
return oldDelegate.chapters != chapters || oldDelegate.duration != duration;
}
}
@@ -0,0 +1,193 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:plezy/services/settings_service.dart';
/// Bottom sheet for adjusting audio sync offset
class AudioSyncSheet extends StatefulWidget {
final Player player;
final int initialOffset;
const AudioSyncSheet({
super.key,
required this.player,
required this.initialOffset,
});
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
static void show(BuildContext context, Player player, int initialOffset) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: (context) =>
AudioSyncSheet(player: player, initialOffset: initialOffset),
);
}
@override
State<AudioSyncSheet> createState() => _AudioSyncSheetState();
}
class _AudioSyncSheetState extends State<AudioSyncSheet> {
late double _currentOffset;
@override
void initState() {
super.initState();
_currentOffset = widget.initialOffset.toDouble();
}
void _applyOffset(double offsetMs) async {
// Convert milliseconds to seconds for media_kit
final offsetSeconds = offsetMs / 1000.0;
// Apply to player using setProperty
await (widget.player.platform as dynamic).setProperty(
'audio-delay',
offsetSeconds.toString(),
);
// Save to settings
final settings = await SettingsService.getInstance();
await settings.setAudioSyncOffset(offsetMs.round());
}
void _resetOffset() {
setState(() {
_currentOffset = 0;
});
_applyOffset(0);
}
String _formatOffset(double offsetMs) {
final sign = offsetMs >= 0 ? '+' : '';
return '$sign${offsetMs.round()}ms';
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(Icons.sync, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Audio Sync',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.white24, height: 1),
Expanded(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Current offset display
Text(
_formatOffset(_currentOffset),
style: const TextStyle(
color: Colors.white,
fontSize: 48,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
_currentOffset > 0
? 'Audio plays later'
: _currentOffset < 0
? 'Audio plays earlier'
: 'No offset',
style: const TextStyle(
color: Colors.white70,
fontSize: 16,
),
),
const SizedBox(height: 48),
// Slider
Row(
children: [
const Text(
'-2s',
style: TextStyle(color: Colors.white70),
),
Expanded(
child: Slider(
value: _currentOffset,
min: -2000,
max: 2000,
divisions: 80, // 50ms steps
activeColor: Colors.blue,
inactiveColor: Colors.white24,
onChanged: (value) {
setState(() {
_currentOffset = value;
});
},
onChangeEnd: (value) {
_applyOffset(value);
},
),
),
const Text(
'+2s',
style: TextStyle(color: Colors.white70),
),
],
),
const SizedBox(height: 24),
// Reset button
ElevatedButton.icon(
onPressed: _currentOffset != 0 ? _resetOffset : null,
icon: const Icon(Icons.restart_alt),
label: const Text('Reset to 0ms'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.grey[800],
foregroundColor: Colors.white,
disabledBackgroundColor: Colors.grey[850],
disabledForegroundColor: Colors.white38,
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
),
],
),
),
),
],
),
),
);
}
}
@@ -0,0 +1,152 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
/// Bottom sheet for selecting audio tracks
class AudioTrackSheet extends StatelessWidget {
final Player player;
const AudioTrackSheet({
super.key,
required this.player,
});
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
static void show(BuildContext context, Player player) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: (context) => AudioTrackSheet(player: player),
);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Tracks>(
stream: player.stream.tracks,
initialData: player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final audioTracks = (tracks?.audio ?? [])
.where((track) => track.id != 'auto' && track.id != 'no')
.toList();
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(Icons.audiotrack, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Audio Tracks',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.white24, height: 1),
if (audioTracks.isEmpty)
const Expanded(
child: Center(
child: Text(
'No audio tracks available',
style: TextStyle(color: Colors.white70),
),
),
)
else
Expanded(
child: StreamBuilder<Track>(
stream: player.stream.track,
initialData: player.state.track,
builder: (context, selectedSnapshot) {
// Use snapshot data or fall back to current state
final currentTrack =
selectedSnapshot.data ?? player.state.track;
final selectedTrack = currentTrack.audio;
final selectedId = selectedTrack.id;
return ListView.builder(
itemCount: audioTracks.length,
itemBuilder: (context, index) {
final audioTrack = audioTracks[index];
final isSelected = audioTrack.id == selectedId;
final parts = <String>[];
if (audioTrack.title != null &&
audioTrack.title!.isNotEmpty) {
parts.add(audioTrack.title!);
}
if (audioTrack.language != null &&
audioTrack.language!.isNotEmpty) {
parts.add(audioTrack.language!.toUpperCase());
}
if (audioTrack.codec != null &&
audioTrack.codec!.isNotEmpty) {
parts.add(audioTrack.codec!.toUpperCase());
}
if (audioTrack.channelscount != null) {
parts.add('${audioTrack.channelscount}ch');
}
final label = parts.isEmpty
? 'Audio Track ${index + 1}'
: parts.join(' · ');
return ListTile(
title: Text(
label,
style: TextStyle(
color:
isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(
Icons.check,
color: Colors.blue,
)
: null,
onTap: () {
player.setAudioTrack(audioTrack);
Navigator.pop(context);
},
);
},
);
},
),
),
],
),
),
);
},
);
}
}
@@ -0,0 +1,230 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:provider/provider.dart';
import '../../../models/plex_media_info.dart';
import '../../../providers/plex_client_provider.dart';
/// Bottom sheet for selecting chapters
class ChapterSheet extends StatelessWidget {
final Player player;
final List<PlexChapter> chapters;
final bool chaptersLoaded;
const ChapterSheet({
super.key,
required this.player,
required this.chapters,
required this.chaptersLoaded,
});
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
static void show(
BuildContext context,
Player player,
List<PlexChapter> chapters,
bool chaptersLoaded,
) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: (context) => ChapterSheet(
player: player,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
),
);
}
String _formatDuration(Duration duration) {
final hours = duration.inHours;
final minutes = duration.inMinutes.remainder(60);
final seconds = duration.inSeconds.remainder(60);
if (hours > 0) {
return '$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
} else {
return '$minutes:${seconds.toString().padLeft(2, '0')}';
}
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Duration>(
stream: player.stream.position,
initialData: player.state.position,
builder: (context, positionSnapshot) {
final currentPosition = positionSnapshot.data ?? Duration.zero;
final currentPositionMs = currentPosition.inMilliseconds;
// Find the current chapter based on position
int? currentChapterIndex;
for (int i = 0; i < chapters.length; i++) {
final chapter = chapters[i];
final startMs = chapter.startTimeOffset ?? 0;
final endMs = chapter.endTimeOffset ??
(i < chapters.length - 1
? chapters[i + 1].startTimeOffset ?? 0
: double.maxFinite.toInt());
if (currentPositionMs >= startMs && currentPositionMs < endMs) {
currentChapterIndex = i;
break;
}
}
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(Icons.video_library, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Chapters',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.white24, height: 1),
if (!chaptersLoaded)
const Expanded(
child: Center(child: CircularProgressIndicator()),
)
else if (chapters.isEmpty)
const Expanded(
child: Center(
child: Text(
'No chapters available',
style: TextStyle(color: Colors.white70),
),
),
)
else
Expanded(
child: ListView.builder(
itemCount: chapters.length,
itemBuilder: (context, index) {
final chapter = chapters[index];
final isCurrentChapter = currentChapterIndex == index;
return ListTile(
leading: chapter.thumb != null
? Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Consumer<PlexClientProvider>(
builder:
(context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return const Icon(
Icons.image,
color: Colors.white54,
size: 34,
);
}
return Image.network(
client.getThumbnailUrl(
chapter.thumb,
),
width: 60,
height: 34,
fit: BoxFit.cover,
errorBuilder: (
context,
error,
stackTrace,
) =>
const Icon(
Icons.image,
color: Colors.white54,
size: 34,
),
);
},
),
),
if (isCurrentChapter)
Positioned.fill(
child: Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(4),
border: Border.all(
color: Colors.blue,
width: 2,
),
),
),
),
],
)
: null,
title: Text(
chapter.label,
style: TextStyle(
color:
isCurrentChapter ? Colors.blue : Colors.white,
fontWeight: isCurrentChapter
? FontWeight.bold
: FontWeight.normal,
),
),
subtitle: Text(
_formatDuration(chapter.startTime),
style: TextStyle(
color: isCurrentChapter
? Colors.blue.withValues(alpha: 0.7)
: Colors.white70,
fontSize: 12,
),
),
trailing: isCurrentChapter
? const Icon(
Icons.play_circle_filled,
color: Colors.blue,
)
: null,
onTap: () {
player.seek(chapter.startTime);
Navigator.pop(context);
},
);
},
),
),
],
),
),
);
},
);
}
}
@@ -0,0 +1,110 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
/// Bottom sheet for selecting playback speed
class PlaybackSpeedSheet extends StatelessWidget {
final Player player;
const PlaybackSpeedSheet({
super.key,
required this.player,
});
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
static void show(BuildContext context, Player player) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: (context) => PlaybackSpeedSheet(player: player),
);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<double>(
stream: player.stream.rate,
initialData: player.state.rate,
builder: (context, snapshot) {
final currentRate = snapshot.data ?? 1.0;
// Define available playback speeds
final speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0];
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(Icons.speed, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Playback Speed',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.white24, height: 1),
Expanded(
child: ListView.builder(
itemCount: speeds.length,
itemBuilder: (context, index) {
final speed = speeds[index];
final isSelected = (currentRate - speed).abs() < 0.01;
// Format speed label
final label = speed == 1.0
? 'Normal'
: '${speed.toStringAsFixed(2)}x';
return ListTile(
title: Text(
label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
player.setRate(speed);
Navigator.pop(context);
},
);
},
),
),
],
),
),
);
},
);
}
}
@@ -0,0 +1,234 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../../../services/settings_service.dart';
import '../../../services/sleep_timer_service.dart';
/// Bottom sheet for sleep timer configuration
class SleepTimerSheet extends StatelessWidget {
final Player player;
final int defaultDuration;
const SleepTimerSheet({
super.key,
required this.player,
required this.defaultDuration,
});
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
static void show(BuildContext context, Player player) async {
final settingsService = await SettingsService.getInstance();
final defaultDuration = settingsService.getSleepTimerDuration();
if (!context.mounted) return;
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: (context) => SleepTimerSheet(
player: player,
defaultDuration: defaultDuration,
),
);
}
String _formatSleepTimerDuration(Duration duration) {
final hours = duration.inHours;
final minutes = duration.inMinutes.remainder(60);
final seconds = duration.inSeconds.remainder(60);
if (hours > 0) {
return '${hours}h ${minutes}m ${seconds}s';
} else if (minutes > 0) {
return '${minutes}m ${seconds}s';
} else {
return '${seconds}s';
}
}
@override
Widget build(BuildContext context) {
final sleepTimer = SleepTimerService();
return ListenableBuilder(
listenable: sleepTimer,
builder: (context, _) {
final durations = [5, 10, 15, 30, 45, 60, 90, 120];
// Add default duration if not in list
if (!durations.contains(defaultDuration)) {
durations.add(defaultDuration);
durations.sort();
}
final remainingTime = sleepTimer.remainingTime;
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(
sleepTimer.isActive
? Icons.bedtime
: Icons.bedtime_outlined,
color: sleepTimer.isActive ? Colors.amber : Colors.white,
),
const SizedBox(width: 12),
const Text(
'Sleep Timer',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.white24, height: 1),
// Show current timer status if active
if (sleepTimer.isActive && remainingTime != null) ...[
Container(
padding: const EdgeInsets.all(16),
color: Colors.amber.withValues(alpha: 0.1),
child: Column(
children: [
const Text(
'Timer Active',
style: TextStyle(
color: Colors.amber,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
'Playback will pause in ${_formatSleepTimerDuration(remainingTime)}',
style: const TextStyle(
color: Colors.white70,
fontSize: 14,
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlinedButton.icon(
icon: const Icon(Icons.add),
label: const Text('+15 min'),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: const BorderSide(
color: Colors.white54,
),
),
onPressed: () {
sleepTimer.extendTimer(
const Duration(minutes: 15),
);
},
),
const SizedBox(width: 12),
FilledButton.icon(
icon: const Icon(Icons.cancel),
label: const Text('Cancel'),
style: FilledButton.styleFrom(
backgroundColor: Colors.red,
),
onPressed: () {
sleepTimer.cancelTimer();
Navigator.pop(context);
},
),
],
),
],
),
),
const Divider(color: Colors.white24, height: 1),
],
// Duration selection list
Expanded(
child: ListView.builder(
itemCount: durations.length,
itemBuilder: (context, index) {
final minutes = durations[index];
final label = minutes < 60
? '$minutes minutes'
: '${(minutes / 60).toStringAsFixed(minutes % 60 == 0 ? 0 : 1)} ${minutes == 60 ? 'hour' : 'hours'}';
return ListTile(
leading: const Icon(
Icons.timer,
color: Colors.white70,
),
title: Text(
label,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
),
),
onTap: () {
sleepTimer.startTimer(
Duration(minutes: minutes),
() {
// Pause playback when timer completes
player.pause();
// Show a snackbar notification
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Sleep timer completed - playback paused',
),
duration: Duration(seconds: 3),
),
);
}
},
);
Navigator.pop(context);
// Show confirmation snackbar
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Sleep timer set for $label'),
duration: const Duration(seconds: 2),
),
);
},
);
},
),
),
],
),
),
);
},
);
}
}
@@ -0,0 +1,191 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
/// Bottom sheet for selecting subtitle tracks
class SubtitleTrackSheet extends StatelessWidget {
final Player player;
const SubtitleTrackSheet({
super.key,
required this.player,
});
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
static void show(BuildContext context, Player player) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: (context) => SubtitleTrackSheet(player: player),
);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Tracks>(
stream: player.stream.tracks,
initialData: player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final subtitles = (tracks?.subtitle ?? [])
.where((track) => track.id != 'auto' && track.id != 'no')
.toList();
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(Icons.subtitles, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Subtitles',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.white24, height: 1),
if (subtitles.isEmpty)
const Expanded(
child: Center(
child: Text(
'No subtitles available',
style: TextStyle(color: Colors.white70),
),
),
)
else
Expanded(
child: StreamBuilder<Track>(
stream: player.stream.track,
initialData: player.state.track,
builder: (context, selectedSnapshot) {
// Use snapshot data or fall back to current state
final currentTrack =
selectedSnapshot.data ?? player.state.track;
final selectedTrack = currentTrack.subtitle;
final selectedId = selectedTrack.id;
final isOffSelected = selectedId == 'no';
return ListView.builder(
itemCount:
subtitles.length + 1, // +1 for "Off" option
itemBuilder: (context, index) {
// First item is "Off"
if (index == 0) {
return ListTile(
title: Text(
'Off',
style: TextStyle(
color: isOffSelected
? Colors.blue
: Colors.white,
),
),
trailing: isOffSelected
? const Icon(
Icons.check,
color: Colors.blue,
)
: null,
onTap: () {
player.setSubtitleTrack(
SubtitleTrack.no(),
);
Navigator.pop(context);
},
);
}
// Subsequent items are subtitle tracks
final subtitle = subtitles[index - 1];
final isSelected = subtitle.id == selectedId;
// Build label with available info
final parts = <String>[];
if (subtitle.title != null &&
subtitle.title!.isNotEmpty) {
parts.add(subtitle.title!);
}
if (subtitle.language != null &&
subtitle.language!.isNotEmpty) {
parts.add(subtitle.language!.toUpperCase());
}
if (subtitle.codec != null &&
subtitle.codec!.isNotEmpty) {
// Format codec names nicely
String codecName = subtitle.codec!.toUpperCase();
if (codecName == 'SUBRIP') {
codecName = 'SRT';
} else if (codecName == 'DVD_SUBTITLE') {
codecName = 'DVD';
} else if (codecName == 'ASS' ||
codecName == 'SSA') {
codecName = codecName; // Keep as-is
} else if (codecName == 'WEBVTT') {
codecName = 'VTT';
}
parts.add(codecName);
}
final label = parts.isEmpty
? 'Track $index'
: parts.join(' · ');
return ListTile(
title: Text(
label,
style: TextStyle(
color:
isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(
Icons.check,
color: Colors.blue,
)
: null,
onTap: () {
player.setSubtitleTrack(subtitle);
Navigator.pop(context);
},
);
},
);
},
),
),
],
),
),
);
},
);
}
}
@@ -0,0 +1,107 @@
import 'package:flutter/material.dart';
import '../../../models/plex_media_version.dart';
/// Bottom sheet for selecting video version
class VersionSheet extends StatelessWidget {
final List<PlexMediaVersion> availableVersions;
final int selectedMediaIndex;
final Function(int) onVersionSelected;
const VersionSheet({
super.key,
required this.availableVersions,
required this.selectedMediaIndex,
required this.onVersionSelected,
});
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
static void show(
BuildContext context,
List<PlexMediaVersion> availableVersions,
int selectedMediaIndex,
Function(int) onVersionSelected,
) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: (context) => VersionSheet(
availableVersions: availableVersions,
selectedMediaIndex: selectedMediaIndex,
onVersionSelected: onVersionSelected,
),
);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(Icons.video_file, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Video Version',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.white24, height: 1),
Expanded(
child: ListView.builder(
itemCount: availableVersions.length,
itemBuilder: (context, index) {
final version = availableVersions[index];
final isSelected = index == selectedMediaIndex;
return ListTile(
title: Text(
version.displayLabel,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
Navigator.pop(context);
onVersionSelected(index);
},
);
},
),
),
],
),
),
);
}
}
@@ -0,0 +1,620 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../../../services/settings_service.dart';
import '../../../services/sleep_timer_service.dart';
import '../../../utils/platform_detector.dart';
import '../widgets/sync_offset_control.dart';
enum _SettingsView { menu, speed, sleep, audioSync, subtitleSync, audioDevice }
/// Unified settings sheet for playback adjustments with in-sheet navigation
class VideoSettingsSheet extends StatefulWidget {
final Player player;
final int audioSyncOffset;
final int subtitleSyncOffset;
const VideoSettingsSheet({
super.key,
required this.player,
required this.audioSyncOffset,
required this.subtitleSyncOffset,
});
static BoxConstraints getBottomSheetConstraints(BuildContext context) {
final size = MediaQuery.of(context).size;
final isDesktop = size.width > 600;
return BoxConstraints(
maxWidth: isDesktop ? 700 : double.infinity,
maxHeight: isDesktop ? 400 : size.height * 0.75,
minHeight: isDesktop ? 300 : size.height * 0.5,
);
}
static Future<void> show(
BuildContext context,
Player player,
int audioSyncOffset,
int subtitleSyncOffset,
) {
return showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: getBottomSheetConstraints(context),
builder: (context) => VideoSettingsSheet(
player: player,
audioSyncOffset: audioSyncOffset,
subtitleSyncOffset: subtitleSyncOffset,
),
);
}
@override
State<VideoSettingsSheet> createState() => _VideoSettingsSheetState();
}
class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
_SettingsView _currentView = _SettingsView.menu;
late int _audioSyncOffset;
late int _subtitleSyncOffset;
@override
void initState() {
super.initState();
_audioSyncOffset = widget.audioSyncOffset;
_subtitleSyncOffset = widget.subtitleSyncOffset;
}
void _navigateTo(_SettingsView view) {
setState(() {
_currentView = view;
});
}
void _navigateBack() {
setState(() {
_currentView = _SettingsView.menu;
});
}
String _getTitle() {
switch (_currentView) {
case _SettingsView.menu:
return 'Playback Settings';
case _SettingsView.speed:
return 'Playback Speed';
case _SettingsView.sleep:
return 'Sleep Timer';
case _SettingsView.audioSync:
return 'Audio Sync';
case _SettingsView.subtitleSync:
return 'Subtitle Sync';
case _SettingsView.audioDevice:
return 'Audio Output';
}
}
IconData _getIcon() {
switch (_currentView) {
case _SettingsView.menu:
return Icons.tune;
case _SettingsView.speed:
return Icons.speed;
case _SettingsView.sleep:
return Icons.bedtime;
case _SettingsView.audioSync:
return Icons.sync;
case _SettingsView.subtitleSync:
return Icons.subtitles;
case _SettingsView.audioDevice:
return Icons.speaker;
}
}
String _formatSpeed(double speed) {
if (speed == 1.0) return 'Normal';
return '${speed.toStringAsFixed(2)}x';
}
String _formatAudioSync(int offsetMs) {
if (offsetMs == 0) return '0ms';
final sign = offsetMs >= 0 ? '+' : '';
return '$sign${offsetMs}ms';
}
String _formatSleepTimer(SleepTimerService sleepTimer) {
if (!sleepTimer.isActive) return 'Off';
final remaining = sleepTimer.remainingTime;
if (remaining == null) return 'Off';
final minutes = remaining.inMinutes;
final seconds = remaining.inSeconds.remainder(60);
if (minutes > 0) {
return 'Active (${minutes}m ${seconds}s)';
} else {
return 'Active (${seconds}s)';
}
}
String _formatSleepTimerDuration(Duration duration) {
final hours = duration.inHours;
final minutes = duration.inMinutes.remainder(60);
final seconds = duration.inSeconds.remainder(60);
if (hours > 0) {
return '${hours}h ${minutes}m ${seconds}s';
} else if (minutes > 0) {
return '${minutes}m ${seconds}s';
} else {
return '${seconds}s';
}
}
Widget _buildHeader() {
final sleepTimer = SleepTimerService();
final isIconActive =
_currentView == _SettingsView.menu &&
(sleepTimer.isActive ||
_audioSyncOffset != 0 ||
_subtitleSyncOffset != 0);
return Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
// Back button or icon
if (_currentView != _SettingsView.menu)
IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: _navigateBack,
)
else
Icon(_getIcon(), color: isIconActive ? Colors.amber : Colors.white),
const SizedBox(width: 12),
Text(
_getTitle(),
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
);
}
Widget _buildMenuView() {
final sleepTimer = SleepTimerService();
final isDesktop = PlatformDetector.isDesktop(context);
return ListView(
children: [
// Playback Speed
StreamBuilder<double>(
stream: widget.player.stream.rate,
initialData: widget.player.state.rate,
builder: (context, snapshot) {
final currentRate = snapshot.data ?? 1.0;
return ListTile(
leading: const Icon(Icons.speed, color: Colors.white70),
title: const Text(
'Playback Speed',
style: TextStyle(color: Colors.white),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_formatSpeed(currentRate),
style: const TextStyle(color: Colors.white70, fontSize: 14),
),
const SizedBox(width: 8),
const Icon(Icons.chevron_right, color: Colors.white70),
],
),
onTap: () => _navigateTo(_SettingsView.speed),
);
},
),
// Sleep Timer
ListenableBuilder(
listenable: sleepTimer,
builder: (context, _) {
final isActive = sleepTimer.isActive;
return ListTile(
leading: Icon(
isActive ? Icons.bedtime : Icons.bedtime_outlined,
color: isActive ? Colors.amber : Colors.white70,
),
title: const Text(
'Sleep Timer',
style: TextStyle(color: Colors.white),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_formatSleepTimer(sleepTimer),
style: TextStyle(
color: isActive ? Colors.amber : Colors.white70,
fontSize: 14,
),
),
const SizedBox(width: 8),
const Icon(Icons.chevron_right, color: Colors.white70),
],
),
onTap: () => _navigateTo(_SettingsView.sleep),
);
},
),
// Audio Sync
ListTile(
leading: Icon(
Icons.sync,
color: _audioSyncOffset != 0 ? Colors.amber : Colors.white70,
),
title: const Text(
'Audio Sync',
style: TextStyle(color: Colors.white),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_formatAudioSync(_audioSyncOffset),
style: TextStyle(
color: _audioSyncOffset != 0 ? Colors.amber : Colors.white70,
fontSize: 14,
),
),
const SizedBox(width: 8),
const Icon(Icons.chevron_right, color: Colors.white70),
],
),
onTap: () => _navigateTo(_SettingsView.audioSync),
),
// Subtitle Sync
ListTile(
leading: Icon(
Icons.subtitles,
color: _subtitleSyncOffset != 0 ? Colors.amber : Colors.white70,
),
title: const Text(
'Subtitle Sync',
style: TextStyle(color: Colors.white),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_formatAudioSync(_subtitleSyncOffset),
style: TextStyle(
color: _subtitleSyncOffset != 0
? Colors.amber
: Colors.white70,
fontSize: 14,
),
),
const SizedBox(width: 8),
const Icon(Icons.chevron_right, color: Colors.white70),
],
),
onTap: () => _navigateTo(_SettingsView.subtitleSync),
),
// Audio Output Device (Desktop only)
if (isDesktop)
StreamBuilder<AudioDevice>(
stream: widget.player.stream.audioDevice,
initialData: widget.player.state.audioDevice,
builder: (context, snapshot) {
final currentDevice = snapshot.data ?? widget.player.state.audioDevice;
final deviceLabel = currentDevice.description.isEmpty
? currentDevice.name
: currentDevice.description;
return ListTile(
leading: const Icon(Icons.speaker, color: Colors.white70),
title: const Text(
'Audio Output',
style: TextStyle(color: Colors.white),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
deviceLabel,
style: const TextStyle(color: Colors.white70, fontSize: 14),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
const Icon(Icons.chevron_right, color: Colors.white70),
],
),
onTap: () => _navigateTo(_SettingsView.audioDevice),
);
},
),
],
);
}
Widget _buildSpeedView() {
return StreamBuilder<double>(
stream: widget.player.stream.rate,
initialData: widget.player.state.rate,
builder: (context, snapshot) {
final currentRate = snapshot.data ?? 1.0;
final speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0];
return ListView.builder(
itemCount: speeds.length,
itemBuilder: (context, index) {
final speed = speeds[index];
final isSelected = (currentRate - speed).abs() < 0.01;
final label = speed == 1.0
? 'Normal'
: '${speed.toStringAsFixed(2)}x';
return ListTile(
title: Text(
label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
widget.player.setRate(speed);
Navigator.pop(context); // Close sheet after selection
},
);
},
);
},
);
}
Widget _buildSleepView() {
final sleepTimer = SleepTimerService();
return ListenableBuilder(
listenable: sleepTimer,
builder: (context, _) {
final durations = [5, 10, 15, 30, 45, 60, 90, 120];
final remainingTime = sleepTimer.remainingTime;
return Column(
children: [
// Active timer status
if (sleepTimer.isActive && remainingTime != null) ...[
Container(
padding: const EdgeInsets.all(16),
color: Colors.amber.withValues(alpha: 0.1),
child: Column(
children: [
const Text(
'Timer Active',
style: TextStyle(
color: Colors.amber,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
'Playback will pause in ${_formatSleepTimerDuration(remainingTime)}',
style: const TextStyle(
color: Colors.white70,
fontSize: 14,
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlinedButton.icon(
icon: const Icon(Icons.add),
label: const Text('+15 min'),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: const BorderSide(color: Colors.white54),
),
onPressed: () {
sleepTimer.extendTimer(const Duration(minutes: 15));
},
),
const SizedBox(width: 12),
FilledButton.icon(
icon: const Icon(Icons.cancel),
label: const Text('Cancel'),
style: FilledButton.styleFrom(
backgroundColor: Colors.red,
),
onPressed: () {
sleepTimer.cancelTimer();
Navigator.pop(context); // Close after cancel
},
),
],
),
],
),
),
const Divider(color: Colors.white24, height: 1),
],
// Duration list
Expanded(
child: ListView.builder(
itemCount: durations.length,
itemBuilder: (context, index) {
final minutes = durations[index];
final label = minutes < 60
? '$minutes minutes'
: '${(minutes / 60).toStringAsFixed(minutes % 60 == 0 ? 0 : 1)} ${minutes == 60 ? 'hour' : 'hours'}';
return ListTile(
leading: const Icon(Icons.timer, color: Colors.white70),
title: Text(
label,
style: const TextStyle(color: Colors.white),
),
onTap: () {
sleepTimer.startTimer(Duration(minutes: minutes), () {
widget.player.pause();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Sleep timer completed - playback paused',
),
duration: Duration(seconds: 3),
),
);
}
});
Navigator.pop(context); // Close after selection
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Sleep timer set for $label'),
duration: const Duration(seconds: 2),
),
);
},
);
},
),
),
],
);
},
);
}
Widget _buildAudioSyncView() {
return SyncOffsetControl(
player: widget.player,
propertyName: 'audio-delay',
initialOffset: _audioSyncOffset,
labelText: 'Audio',
onOffsetChanged: (offset) async {
final settings = await SettingsService.getInstance();
await settings.setAudioSyncOffset(offset);
setState(() {
_audioSyncOffset = offset;
});
},
);
}
Widget _buildSubtitleSyncView() {
return SyncOffsetControl(
player: widget.player,
propertyName: 'sub-delay',
initialOffset: _subtitleSyncOffset,
labelText: 'Subtitles',
onOffsetChanged: (offset) async {
final settings = await SettingsService.getInstance();
await settings.setSubtitleSyncOffset(offset);
setState(() {
_subtitleSyncOffset = offset;
});
},
);
}
Widget _buildAudioDeviceView() {
return StreamBuilder<List<AudioDevice>>(
stream: widget.player.stream.audioDevices,
initialData: widget.player.state.audioDevices,
builder: (context, snapshot) {
final devices = snapshot.data ?? [];
return StreamBuilder<AudioDevice>(
stream: widget.player.stream.audioDevice,
initialData: widget.player.state.audioDevice,
builder: (context, selectedSnapshot) {
final currentDevice = selectedSnapshot.data ?? widget.player.state.audioDevice;
return ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) {
final device = devices[index];
final isSelected = device.name == currentDevice.name;
final label = device.description.isEmpty
? device.name
: device.description;
return ListTile(
title: Text(
label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
widget.player.setAudioDevice(device);
Navigator.pop(context); // Close sheet after selection
},
);
},
);
},
);
},
);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
_buildHeader(),
const Divider(color: Colors.white24, height: 1),
Expanded(
child: () {
switch (_currentView) {
case _SettingsView.menu:
return _buildMenuView();
case _SettingsView.speed:
return _buildSpeedView();
case _SettingsView.sleep:
return _buildSleepView();
case _SettingsView.audioSync:
return _buildAudioSyncView();
case _SettingsView.subtitleSync:
return _buildSubtitleSyncView();
case _SettingsView.audioDevice:
return _buildAudioDeviceView();
}
}(),
),
],
),
),
);
}
}
@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
/// A standardized button for video player controls with improved tap targets.
///
/// This widget ensures consistent tap target sizing across all video control
/// buttons without changing their visual appearance. The larger tap area makes
/// buttons easier to interact with, especially on mobile devices.
class VideoControlButton extends StatelessWidget {
/// The icon to display in the button.
final IconData icon;
/// Called when the button is tapped.
final VoidCallback? onPressed;
/// The color of the icon. Defaults to white, or amber if [isActive] is true.
final Color? color;
/// Optional tooltip text shown on hover or long press.
final String? tooltip;
/// Whether this button represents an active state (e.g., a feature is enabled).
/// When true, the icon color defaults to amber instead of white.
final bool isActive;
const VideoControlButton({
super.key,
required this.icon,
required this.onPressed,
this.color,
this.tooltip,
this.isActive = false,
});
@override
Widget build(BuildContext context) {
// Determine the effective color: explicit color > active amber > default white
final effectiveColor = color ?? (isActive ? Colors.amber : Colors.white);
return IconButton(
icon: Icon(icon, color: effectiveColor),
onPressed: onPressed,
tooltip: tooltip,
constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
);
}
}
@@ -0,0 +1,145 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
/// Reusable widget for adjusting sync offsets (audio or subtitle)
class SyncOffsetControl extends StatefulWidget {
final Player player;
final String propertyName; // 'audio-delay' or 'sub-delay'
final int initialOffset;
final String labelText; // 'Audio' or 'Subtitles'
final Future<void> Function(int offset) onOffsetChanged;
const SyncOffsetControl({
super.key,
required this.player,
required this.propertyName,
required this.initialOffset,
required this.labelText,
required this.onOffsetChanged,
});
@override
State<SyncOffsetControl> createState() => _SyncOffsetControlState();
}
class _SyncOffsetControlState extends State<SyncOffsetControl> {
late double _currentOffset;
@override
void initState() {
super.initState();
_currentOffset = widget.initialOffset.toDouble();
}
@override
void didUpdateWidget(SyncOffsetControl oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.initialOffset != oldWidget.initialOffset) {
setState(() {
_currentOffset = widget.initialOffset.toDouble();
});
}
}
Future<void> _applyOffset(double offsetMs) async {
// Convert milliseconds to seconds for media_kit
final offsetSeconds = offsetMs / 1000.0;
// Apply to player using setProperty
await (widget.player.platform as dynamic).setProperty(
widget.propertyName,
offsetSeconds.toString(),
);
// Notify parent and save to settings
await widget.onOffsetChanged(offsetMs.round());
}
void _resetOffset() {
setState(() {
_currentOffset = 0;
});
_applyOffset(0);
}
String _formatOffset(double offsetMs) {
final sign = offsetMs >= 0 ? '+' : '';
return '$sign${offsetMs.round()}ms';
}
String _getDescriptionText() {
if (_currentOffset > 0) {
return '${widget.labelText} plays later';
} else if (_currentOffset < 0) {
return '${widget.labelText} plays earlier';
} else {
return 'No offset';
}
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Current offset display
Text(
_formatOffset(_currentOffset),
style: const TextStyle(
color: Colors.white,
fontSize: 48,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
_getDescriptionText(),
style: const TextStyle(color: Colors.white70, fontSize: 16),
),
const SizedBox(height: 48),
// Slider
Row(
children: [
const Text('-2s', style: TextStyle(color: Colors.white70)),
Expanded(
child: Slider(
value: _currentOffset,
min: -2000,
max: 2000,
divisions: 80, // 50ms steps
activeColor: Colors.blue,
inactiveColor: Colors.white24,
onChanged: (value) {
setState(() {
_currentOffset = value;
});
},
onChangeEnd: (value) {
_applyOffset(value);
},
),
),
const Text('+2s', style: TextStyle(color: Colors.white70)),
],
),
const SizedBox(height: 24),
// Reset button
ElevatedButton.icon(
onPressed: _currentOffset != 0 ? _resetOffset : null,
icon: const Icon(Icons.restart_alt),
label: const Text('Reset to 0ms'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.grey[800],
foregroundColor: Colors.white,
disabledBackgroundColor: Colors.grey[850],
disabledForegroundColor: Colors.white38,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
),
],
),
);
}
}
@@ -5,6 +5,8 @@
import FlutterMacOS
import Foundation
import audio_service
import audio_session
import hotkey_manager_macos
import macos_window_utils
import media_kit_libs_macos_video
@@ -20,6 +22,8 @@ import wakelock_plus
import window_manager
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioServicePlugin.register(with: registry.registrar(forPlugin: "AudioServicePlugin"))
AudioSessionPlugin.register(with: registry.registrar(forPlugin: "AudioSessionPlugin"))
HotkeyManagerMacosPlugin.register(with: registry.registrar(forPlugin: "HotkeyManagerMacosPlugin"))
MacOSWindowUtilsPlugin.register(with: registry.registrar(forPlugin: "MacOSWindowUtilsPlugin"))
MediaKitLibsMacosVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitLibsMacosVideoPlugin"))
+15 -2
View File
@@ -1,4 +1,9 @@
PODS:
- audio_service (0.0.1):
- Flutter
- FlutterMacOS
- audio_session (0.0.1):
- FlutterMacOS
- FlutterMacOS (1.0.0)
- HotKey (0.2.1)
- hotkey_manager_macos (0.0.1):
@@ -33,6 +38,8 @@ PODS:
- FlutterMacOS
DEPENDENCIES:
- audio_service (from `Flutter/ephemeral/.symlinks/plugins/audio_service/darwin`)
- audio_session (from `Flutter/ephemeral/.symlinks/plugins/audio_session/macos`)
- FlutterMacOS (from `Flutter/ephemeral`)
- hotkey_manager_macos (from `Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos`)
- macos_window_utils (from `Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos`)
@@ -53,6 +60,10 @@ SPEC REPOS:
- HotKey
EXTERNAL SOURCES:
audio_service:
:path: Flutter/ephemeral/.symlinks/plugins/audio_service/darwin
audio_session:
:path: Flutter/ephemeral/.symlinks/plugins/audio_session/macos
FlutterMacOS:
:path: Flutter/ephemeral
hotkey_manager_macos:
@@ -83,6 +94,8 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/window_manager/macos
SPEC CHECKSUMS:
audio_service: aa99a6ba2ae7565996015322b0bb024e1d25c6fd
audio_session: eaca2512cf2b39212d724f35d11f46180ad3a33e
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
HotKey: 400beb7caa29054ea8d864c96f5ba7e5b4852277
hotkey_manager_macos: a4317849af96d2430fa89944d3c58977ca089fbe
@@ -90,9 +103,9 @@ SPEC CHECKSUMS:
media_kit_libs_macos_video: 85a23e549b5f480e72cae3e5634b5514bc692f65
media_kit_video: fa6564e3799a0a28bff39442334817088b7ca758
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
screen_retriever_macos: 452e51764a9e1cdb74b3c541238795849f21557f
shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
url_launcher_macos: f87a979182d112f911de6820aefddaf56ee9fbfd
volume_controller: 5c068e6d085c80dadd33fc2c918d2114b775b3dd
+134 -63
View File
@@ -5,18 +5,18 @@ packages:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: f0bb5d1648339c8308cc0b9838d8456b3cfe5c91f9dc1a735b4d003269e5da9a
sha256: c209688d9f5a5f26b2fb47a188131a6fb9e876ae9e47af3737c0b4f58a93470d
url: "https://pub.dev"
source: hosted
version: "88.0.0"
version: "91.0.0"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "0b7b9c329d2879f8f05d6c05b32ee9ec025f39b077864bdb5ac9a7b63418a98f"
sha256: f51c8499b35f9b26820cfe914828a6a98a94efd5cc78b37bb7d03debae3a1d08
url: "https://pub.dev"
source: hosted
version: "8.1.1"
version: "8.4.1"
archive:
dependency: transitive
description:
@@ -41,6 +41,39 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.13.0"
audio_service:
dependency: "direct main"
description:
path: audio_service
ref: "4ca42f391183854095188a5a10fa6b59cd641e68"
resolved-ref: "4ca42f391183854095188a5a10fa6b59cd641e68"
url: "https://github.com/marckornberger/audio_service.git"
source: git
version: "0.18.18"
audio_service_platform_interface:
dependency: transitive
description:
name: audio_service_platform_interface
sha256: "6283782851f6c8b501b60904a32fc7199dc631172da0629d7301e66f672ab777"
url: "https://pub.dev"
source: hosted
version: "0.1.3"
audio_service_web:
dependency: transitive
description:
name: audio_service_web
sha256: b8ea9243201ee53383157fbccf13d5d2a866b5dda922ec19d866d1d5d70424df
url: "https://pub.dev"
source: hosted
version: "0.1.4"
audio_session:
dependency: "direct main"
description:
name: audio_session
sha256: "2b7fff16a552486d078bfc09a8cde19f426dc6d6329262b684182597bec5b1ac"
url: "https://pub.dev"
source: hosted
version: "0.1.25"
boolean_selector:
dependency: transitive
description:
@@ -69,18 +102,18 @@ packages:
dependency: transitive
description:
name: build_daemon
sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa"
sha256: "409002f1adeea601018715d613115cfaf0e31f512cb80ae4534c79867ae2363d"
url: "https://pub.dev"
source: hosted
version: "4.0.4"
version: "4.1.0"
build_runner:
dependency: "direct dev"
description:
name: build_runner
sha256: "4e54dbeefdc70691ba80b3bce3976af63b5425c8c07dface348dfee664a0edc1"
sha256: a9461b8e586bf018dd4afd2e13b49b08c6a844a4b226c8d1d10f3a723cdd78c3
url: "https://pub.dev"
source: hosted
version: "2.9.0"
version: "2.10.1"
built_collection:
dependency: transitive
description:
@@ -181,10 +214,10 @@ packages:
dependency: transitive
description:
name: crypto
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
url: "https://pub.dev"
source: hosted
version: "3.0.6"
version: "3.0.7"
dart_style:
dependency: transitive
description:
@@ -249,6 +282,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.1"
flex_color_picker:
dependency: "direct main"
description:
name: flex_color_picker
sha256: f5b0b53d4ae0d59b1e28dfc21d5398e5028cf8e764518e491a52fd050aa23881
url: "https://pub.dev"
source: hosted
version: "3.7.2"
flex_seed_scheme:
dependency: transitive
description:
name: flex_seed_scheme
sha256: "828291a5a4d4283590541519d8b57821946660ac61d2e07d955f81cfcab22e5d"
url: "https://pub.dev"
source: hosted
version: "3.6.1"
flutter:
dependency: "direct main"
description: flutter
@@ -266,10 +315,10 @@ packages:
dependency: "direct dev"
description:
name: flutter_launcher_icons
sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea"
sha256: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7"
url: "https://pub.dev"
source: hosted
version: "0.13.1"
version: "0.14.4"
flutter_lints:
dependency: "direct dev"
description:
@@ -384,6 +433,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.5"
js:
dependency: transitive
description:
name: js
sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc"
url: "https://pub.dev"
source: hosted
version: "0.7.2"
json_annotation:
dependency: "direct main"
description:
@@ -476,59 +533,65 @@ packages:
dependency: "direct main"
description:
path: media_kit
ref: HEAD
resolved-ref: "5d002a6bd9c4b4247f83f1c0719f8144daf87f0f"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.2.1"
media_kit_libs_android_video:
dependency: transitive
description:
name: media_kit_libs_android_video
sha256: "3f6274e5ab2de512c286a25c327288601ee445ed8ac319e0ef0b66148bd8f76c"
url: "https://pub.dev"
source: hosted
version: "1.3.8"
path: "libs/android/media_kit_libs_android_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.3.9"
media_kit_libs_ios_video:
dependency: transitive
description:
name: media_kit_libs_ios_video
sha256: b5382994eb37a4564c368386c154ad70ba0cc78dacdd3fb0cd9f30db6d837991
url: "https://pub.dev"
source: hosted
path: "libs/ios/media_kit_libs_ios_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.1.4"
media_kit_libs_linux:
dependency: transitive
description:
name: media_kit_libs_linux
sha256: "2b473399a49ec94452c4d4ae51cfc0f6585074398d74216092bf3d54aac37ecf"
url: "https://pub.dev"
source: hosted
path: "libs/linux/media_kit_libs_linux"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.2.1"
media_kit_libs_macos_video:
dependency: transitive
description:
name: media_kit_libs_macos_video
sha256: f26aa1452b665df288e360393758f84b911f70ffb3878032e1aabba23aa1032d
url: "https://pub.dev"
source: hosted
version: "1.1.4"
path: "libs/macos/media_kit_libs_macos_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.1.5"
media_kit_libs_video:
dependency: "direct main"
description:
name: media_kit_libs_video
sha256: "2b235b5dac79c6020e01eef5022c6cc85fedc0df1738aadc6ea489daa12a92a9"
url: "https://pub.dev"
source: hosted
path: "libs/universal/media_kit_libs_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.0.7"
media_kit_libs_windows_video:
dependency: transitive
description:
name: media_kit_libs_windows_video
sha256: dff76da2778729ab650229e6b4ec6ec111eb5151431002cbd7ea304ff1f112ab
url: "https://pub.dev"
source: hosted
version: "1.0.11"
path: "libs/windows/media_kit_libs_windows_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.0.12"
media_kit_video:
dependency: "direct main"
description:
@@ -621,10 +684,10 @@ packages:
dependency: transitive
description:
name: path_provider_foundation
sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd"
sha256: efaec349ddfc181528345c56f8eda9d6cccd71c177511b132c6a0ddaefaa2738
url: "https://pub.dev"
source: hosted
version: "2.4.2"
version: "2.4.3"
path_provider_linux:
dependency: transitive
description:
@@ -713,14 +776,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.5.0"
rxdart:
qr:
dependency: transitive
description:
name: rxdart
sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962"
name: qr
sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445"
url: "https://pub.dev"
source: hosted
version: "0.28.0"
version: "3.0.2"
qr_flutter:
dependency: "direct main"
description:
name: qr_flutter
sha256: "5095f0fc6e3f71d08adef8feccc8cea4f12eec18a2e31c2e8d82cb6019f4b097"
url: "https://pub.dev"
source: hosted
version: "4.1.0"
rxdart:
dependency: "direct main"
description:
name: rxdart
sha256: "0c7c0cedd93788d996e33041ffecda924cc54389199cde4e6a34b440f50044cb"
url: "https://pub.dev"
source: hosted
version: "0.27.7"
safe_local_storage:
dependency: transitive
description:
@@ -797,18 +876,18 @@ packages:
dependency: transitive
description:
name: shared_preferences_android
sha256: bd14436108211b0d4ee5038689a56d4ae3620fd72fd6036e113bf1345bc74d9e
sha256: "34266009473bf71d748912da4bf62d439185226c03e01e2d9687bc65bbfcb713"
url: "https://pub.dev"
source: hosted
version: "2.4.13"
version: "2.4.15"
shared_preferences_foundation:
dependency: transitive
description:
name: shared_preferences_foundation
sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03"
sha256: "1c33a907142607c40a7542768ec9badfd16293bac51da3a4482623d15845f88b"
url: "https://pub.dev"
source: hosted
version: "2.5.4"
version: "2.5.5"
shared_preferences_linux:
dependency: transitive
description:
@@ -886,14 +965,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.10.1"
sprintf:
dependency: transitive
description:
name: sprintf
sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23"
url: "https://pub.dev"
source: hosted
version: "7.0.0"
sqflite:
dependency: transitive
description:
@@ -1090,10 +1161,10 @@ packages:
dependency: "direct main"
description:
name: uuid
sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff
sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8
url: "https://pub.dev"
source: hosted
version: "4.5.1"
version: "4.5.2"
vector_math:
dependency: transitive
description:
@@ -1106,10 +1177,10 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60"
url: "https://pub.dev"
source: hosted
version: "15.0.0"
version: "15.0.2"
volume_controller:
dependency: transitive
description:
+18 -2
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.4.0+11
version: 1.6.0+14
environment:
sdk: ^3.8.1
@@ -24,12 +24,27 @@ dependencies:
package_info_plus: ^9.0.0
provider: ^6.1.2
hotkey_manager: ^0.2.3
flex_color_picker: ^3.6.0
qr_flutter: ^4.1.0
audio_session: ^0.1.25
rxdart: ^0.27.2
audio_service:
git:
url: https://github.com/marckornberger/audio_service.git
ref: 4ca42f391183854095188a5a10fa6b59cd641e68
path: audio_service
dependency_overrides:
media_kit:
git:
url: https://github.com/edde746/media-kit
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
path: media_kit
media_kit_libs_video:
git:
url: https://github.com/edde746/media-kit
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
path: libs/universal/media_kit_libs_video
dev_dependencies:
flutter_test:
@@ -37,7 +52,7 @@ dev_dependencies:
flutter_lints: ^5.0.0
build_runner: ^2.4.7
json_serializable: ^6.7.1
flutter_launcher_icons: ^0.13.1
flutter_launcher_icons: ^0.14.4
flutter:
uses-material-design: true
@@ -52,6 +67,7 @@ flutter_launcher_icons:
image_path: "assets/plezy.png"
adaptive_icon_background: "#ffffff"
adaptive_icon_foreground: "assets/plezy_android_foreground.png"
adaptive_icon_monochrome: "assets/plezy_monochrome.png"
macos:
generate: false
windows:
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env bash
# Android Icon Generator Script
# Generates notification icons and monochrome launcher icons from SVG source
# Usage: ./generate_android_icons.sh
set -e
# Configuration
SVG_SOURCE="assets/plezy.svg"
ANDROID_RES="android/app/src/main/res"
TEMP_DIR="/tmp/android_icons_$$"
# Check if source SVG exists
if [ ! -f "$SVG_SOURCE" ]; then
echo "Error: $SVG_SOURCE not found"
exit 1
fi
# Check for required tools
if ! command -v rsvg-convert &> /dev/null; then
echo "Error: rsvg-convert not found. Install with: brew install librsvg"
exit 1
fi
if ! command -v magick &> /dev/null && ! command -v convert &> /dev/null; then
echo "Error: ImageMagick not found. Install with: brew install imagemagick"
exit 1
fi
# Create temp directory
mkdir -p "$TEMP_DIR"
echo "🎨 Generating Android icons from $SVG_SOURCE..."
# Function to generate white silhouette icon
generate_white_icon() {
local size=$1
local output=$2
# Get SVG dimensions to detect if it's non-square
local svg_viewbox=$(grep -o 'viewBox="[^"]*"' "$SVG_SOURCE" | sed 's/viewBox="//;s/"//')
local svg_width=$(echo "$svg_viewbox" | awk '{print $3}')
local svg_height=$(echo "$svg_viewbox" | awk '{print $4}')
# Convert SVG to PNG, preserving aspect ratio
if (( $(echo "$svg_width != $svg_height" | bc -l) )); then
# Non-square SVG: render at size and add padding to center it
rsvg-convert --keep-aspect-ratio --background-color=transparent "$SVG_SOURCE" -o "$TEMP_DIR/temp_unpadded.png"
# Center the image in a square canvas with transparent padding
magick "$TEMP_DIR/temp_unpadded.png" \
-resize "${size}x${size}" \
-gravity center \
-background transparent \
-extent "${size}x${size}" \
"$TEMP_DIR/temp.png"
else
# Square SVG: convert directly
rsvg-convert -w "$size" -h "$size" --background-color=transparent "$SVG_SOURCE" -o "$TEMP_DIR/temp.png"
fi
# Convert to white silhouette: extract alpha, fill with white, apply alpha
magick "$TEMP_DIR/temp.png" \
-alpha extract \
"$TEMP_DIR/alpha_mask.png"
magick -size "${size}x${size}" xc:white \
"$TEMP_DIR/alpha_mask.png" \
-alpha off \
-compose copy-opacity \
-composite \
-define png:color-type=6 \
"$output"
echo " ✓ Generated $(basename $output) (${size}x${size}px)"
}
# Generate Notification Icons (24dp base)
echo ""
echo "📱 Generating notification icons (ic_stat_notification.png)..."
# Notification icon densities: 24dp base
# mdpi=1x, hdpi=1.5x, xhdpi=2x, xxhdpi=3x, xxxhdpi=4x
declare -A NOTIF_SIZES=(
["mdpi"]=24
["hdpi"]=36
["xhdpi"]=48
["xxhdpi"]=72
["xxxhdpi"]=96
)
for density in "${!NOTIF_SIZES[@]}"; do
size=${NOTIF_SIZES[$density]}
output_dir="$ANDROID_RES/drawable-$density"
mkdir -p "$output_dir"
generate_white_icon "$size" "$output_dir/ic_stat_notification.png"
done
# Generate Monochrome Launcher Icons (108dp base)
echo ""
echo "🚀 Generating monochrome launcher icons (ic_launcher_monochrome.png)..."
# Monochrome launcher icon densities: 108dp base
# mdpi=1x, hdpi=1.5x, xhdpi=2x, xxhdpi=3x, xxxhdpi=4x
declare -A MONO_SIZES=(
["mdpi"]=108
["hdpi"]=162
["xhdpi"]=216
["xxhdpi"]=324
["xxxhdpi"]=432
)
for density in "${!MONO_SIZES[@]}"; do
size=${MONO_SIZES[$density]}
output_dir="$ANDROID_RES/mipmap-$density"
mkdir -p "$output_dir"
generate_white_icon "$size" "$output_dir/ic_launcher_monochrome.png"
done
# Clean up
rm -rf "$TEMP_DIR"
echo ""
echo "✅ All icons generated successfully!"
echo ""
echo "Icon locations:"
echo " • Notification icons: $ANDROID_RES/drawable-*/ic_stat_notification.png"
echo " • Monochrome icons: $ANDROID_RES/mipmap-*/ic_launcher_monochrome.png"
echo ""
echo "To apply changes, rebuild the app: flutter clean && flutter build apk"