Compare commits

..
20 Commits
Author SHA1 Message Date
github-actions[bot] f31ef704a3 chore: bump version to 1.10.0 2025-12-09 21:54:10 +00:00
edde746 e53ba988aa adjust android options 2025-12-09 19:19:22 +01:00
edde746 471c913ee3 fix: wakelock
close #152
2025-12-09 19:13:38 +01:00
edde746 8b3024b71a refactor: remove old BoxFit code 2025-12-09 16:50:07 +01:00
edde746 3eedb615ef refactor: remove hero focus effect 2025-12-09 16:33:44 +01:00
edde746 ac3f7a0b1d fix: missing tracks on Windows 2025-12-09 16:19:44 +01:00
edde746 32dab8953b feat: use desktop controls on android tv 2025-12-08 13:25:03 +01:00
edde746 c6f41398a9 fix: back on android tv 2025-12-08 01:08:29 +01:00
edde746 65811cd0b2 fix: add missing context menu 2025-12-07 22:51:55 +01:00
edde746 851d74e418 feat: video player dpad support 2025-12-07 22:43:47 +01:00
edde746 e804a2a3cc feat: app reviewer stupidity check 2025-12-07 19:39:56 +01:00
edde746 c9003e0a03 refactor: remove verbose gamepad logs 2025-12-07 19:34:32 +01:00
edde746 12969eeff9 feat: gamepad support
tested with dualsense on macOS, close #25
2025-12-07 19:32:33 +01:00
edde746 f24bb9dc85 refactor: deduplicate video controls, formatters & play queue wiring 2025-12-07 16:31:08 +01:00
edde746 4d65607e59 refactor: deduplicate UI helpers & track handling 2025-12-07 15:54:24 +01:00
edde746 80d60077d7 refactor: remove dead code 2025-12-07 15:14:43 +01:00
edde746 d9ea099727 refactor: deduplicate 2025-12-07 15:00:28 +01:00
edde746 223065cab0 feat: re-implement keyboard navigation 2025-12-07 13:57:52 +01:00
edde746 a373477105 feat: sidenav on desktop 2025-12-06 12:43:31 +01:00
edde746 7b0aa12c38 refactor: remove keyboard navigation 2025-12-05 23:29:37 +01:00
108 changed files with 16490 additions and 19196 deletions
+7
View File
@@ -13,6 +13,11 @@
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
<!-- Android TV support (not required, but allow detection) -->
<uses-feature android:name="android.software.leanback" android:required="false" />
<!-- Touchscreen not required for TV -->
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<application
android:label="Plezy"
android:name="${applicationName}"
@@ -37,6 +42,8 @@
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<!-- Allow app to appear in Android TV launcher -->
<category android:name="android.intent.category.LEANBACK_LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
@@ -159,6 +159,7 @@ class MpvPlayerCore(private val activity: Activity) :
// Video output configuration
MPVLib.setOptionString("vo", "gpu")
MPVLib.setOptionString("gpu-context", "android")
MPVLib.setOptionString("opengl-es", "yes")
// hwdec is set from Flutter via setProperty based on user preference
// Audio configuration
+6
View File
@@ -1,6 +1,8 @@
PODS:
- connectivity_plus (0.0.1):
- Flutter
- device_info_plus (0.0.1):
- Flutter
- Flutter (1.0.0)
- os_media_controls (0.0.1):
- Flutter
@@ -20,6 +22,7 @@ PODS:
DEPENDENCIES:
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
- Flutter (from `Flutter`)
- os_media_controls (from `.symlinks/plugins/os_media_controls/ios`)
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
@@ -31,6 +34,8 @@ DEPENDENCIES:
EXTERNAL SOURCES:
connectivity_plus:
:path: ".symlinks/plugins/connectivity_plus/ios"
device_info_plus:
:path: ".symlinks/plugins/device_info_plus/ios"
Flutter:
:path: Flutter
os_media_controls:
@@ -48,6 +53,7 @@ EXTERNAL SOURCES:
SPEC CHECKSUMS:
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
+54
View File
@@ -0,0 +1,54 @@
import 'package:flutter/services.dart';
/// Extension methods for checking D-pad related keys.
extension DpadKeyExtension on LogicalKeyboardKey {
/// Whether this key is a D-pad directional key.
bool get isDpadDirection {
return this == LogicalKeyboardKey.arrowUp ||
this == LogicalKeyboardKey.arrowDown ||
this == LogicalKeyboardKey.arrowLeft ||
this == LogicalKeyboardKey.arrowRight;
}
/// Whether this key is a select/activate key.
bool get isSelectKey {
return this == LogicalKeyboardKey.select ||
this == LogicalKeyboardKey.enter ||
this == LogicalKeyboardKey.numpadEnter ||
this == LogicalKeyboardKey.gameButtonA;
}
/// Whether this key is a back/cancel key.
bool get isBackKey {
return this == LogicalKeyboardKey.escape ||
this == LogicalKeyboardKey.goBack ||
this == LogicalKeyboardKey.browserBack ||
this == LogicalKeyboardKey.gameButtonB;
}
/// Whether this key is a context menu key.
bool get isContextMenuKey {
return this == LogicalKeyboardKey.contextMenu ||
this == LogicalKeyboardKey.gameButtonX;
}
/// Whether this key moves focus left.
bool get isLeftKey {
return this == LogicalKeyboardKey.arrowLeft;
}
/// Whether this key moves focus right.
bool get isRightKey {
return this == LogicalKeyboardKey.arrowRight;
}
/// Whether this key moves focus up.
bool get isUpKey {
return this == LogicalKeyboardKey.arrowUp;
}
/// Whether this key moves focus down.
bool get isDownKey {
return this == LogicalKeyboardKey.arrowDown;
}
}
+58
View File
@@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
import '../theme/mono_tokens.dart';
/// Focus styling constants for D-pad navigation.
class FocusTheme {
FocusTheme._();
/// Scale factor when an item is focused.
static const double focusScale = 1.02;
/// Border width for the focus indicator.
static const double focusBorderWidth = 2.5;
/// Default border radius (matches MonoTokens.radiusSm).
static const double defaultBorderRadius = 8.0;
/// Get the focus border color from the theme.
static Color getFocusBorderColor(BuildContext context) {
return Theme.of(context).colorScheme.primary;
}
/// Get the animation duration from MonoTokens.
static Duration getAnimationDuration(BuildContext context) {
return Theme.of(context).extension<MonoTokens>()?.fast ??
const Duration(milliseconds: 150);
}
/// Build the focus border decoration.
static BoxDecoration focusDecoration(
BuildContext context, {
required bool isFocused,
double borderRadius = defaultBorderRadius,
}) {
final focusColor = getFocusBorderColor(context);
return BoxDecoration(
borderRadius: BorderRadius.circular(borderRadius),
border: Border.all(
color: isFocused ? focusColor : Colors.transparent,
width: focusBorderWidth,
),
);
}
/// Build focus decoration with background color instead of border.
/// Useful for video controls where it should match the native hover style.
static BoxDecoration focusBackgroundDecoration({
required bool isFocused,
double borderRadius = defaultBorderRadius,
}) {
return BoxDecoration(
borderRadius: BorderRadius.circular(borderRadius),
color: isFocused
? Colors.white.withValues(alpha: 0.2)
: Colors.transparent,
);
}
}
+63
View File
@@ -0,0 +1,63 @@
import 'package:flutter/material.dart';
/// A mixin that provides common FocusNode lifecycle management for chip widgets.
///
/// This mixin handles:
/// - Internal/external FocusNode pattern
/// - `_isFocused` state tracking
/// - Listener setup in `initState`
/// - Listener handoff in `didUpdateWidget`
/// - Cleanup in `dispose`
///
/// To use this mixin:
/// 1. Add `with FocusableChipStateMixin<YourWidget>` to your State class
/// 2. Implement [widgetFocusNode] to return the widget's optional focusNode
/// 3. Implement [debugLabel] to return a debug label for the internal node
/// 4. Call [initFocusNode] in your `initState`
/// 5. Call [updateFocusNode] in your `didUpdateWidget`
/// 6. Call [disposeFocusNode] in your `dispose`
/// 7. Use [focusNode] and [isFocused] in your build method
mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
FocusNode? _internalFocusNode;
bool _isFocused = false;
/// Override to return the widget's optional external focus node.
FocusNode? get widgetFocusNode;
/// Override to return a debug label for the internal focus node.
String get debugLabel;
/// The active focus node (external if provided, otherwise internal).
FocusNode get focusNode {
return widgetFocusNode ??
(_internalFocusNode ??= FocusNode(debugLabel: debugLabel));
}
/// Whether this widget is currently focused.
bool get isFocused => _isFocused;
/// Call this in your `initState` to set up the focus listener.
void initFocusNode() {
focusNode.addListener(_onFocusChange);
}
/// Call this in your `didUpdateWidget` with the old widget's focusNode.
void updateFocusNode(FocusNode? oldFocusNode) {
if (oldFocusNode != widgetFocusNode) {
oldFocusNode?.removeListener(_onFocusChange);
focusNode.addListener(_onFocusChange);
}
}
/// Call this in your `dispose` to clean up the focus listener.
void disposeFocusNode() {
focusNode.removeListener(_onFocusChange);
_internalFocusNode?.dispose();
}
void _onFocusChange() {
if (mounted) {
setState(() => _isFocused = focusNode.hasFocus);
}
}
}
+407
View File
@@ -0,0 +1,407 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'focus_theme.dart';
import 'input_mode_tracker.dart';
/// A wrapper widget that makes its child focusable with D-pad navigation support.
///
/// Provides:
/// - Visual focus indicator (border + scale animation)
/// - Keyboard/D-pad event handling (Enter/Select to activate)
/// - Optional auto-scroll to keep focused item visible
/// - Long-press detection for SELECT key
/// - Navigation callbacks (UP, BACK)
class FocusableWrapper extends StatefulWidget {
/// The child widget to wrap.
final Widget child;
/// Called when the item is selected (Enter/Select/GamepadA).
/// For short press when [enableLongPress] is true.
final VoidCallback? onSelect;
/// Called when long press is triggered (hold SELECT key or context menu key).
/// Only triggered if [enableLongPress] is true.
final VoidCallback? onLongPress;
/// Called when focus changes.
final ValueChanged<bool>? onFocusChange;
/// Called when the user presses UP and there's no focusable item above.
final VoidCallback? onNavigateUp;
/// Called when the user presses BACK.
final VoidCallback? onBack;
/// Whether this widget should request focus when first built.
final bool autofocus;
/// Optional external FocusNode for programmatic focus control.
final FocusNode? focusNode;
/// Border radius for the focus indicator.
final double borderRadius;
/// Whether to scroll the widget into view when focused.
final bool autoScroll;
/// Alignment for auto-scroll (0.0 = start, 0.5 = center, 1.0 = end).
final double scrollAlignment;
/// Whether to use comfortable zone scrolling (only scroll if item is outside middle 60%).
/// If false, always scrolls to [scrollAlignment].
final bool useComfortableZone;
/// Optional semantic label for accessibility.
final String? semanticLabel;
/// Whether the wrapper can receive focus.
final bool canRequestFocus;
/// Custom key event handler. Return KeyEventResult.handled to consume the event.
/// This is called before the default key handling.
final KeyEventResult Function(FocusNode node, KeyEvent event)? onKeyEvent;
/// Whether to enable long-press detection for SELECT key.
/// When enabled, holding SELECT triggers [onLongPress] after 500ms.
/// Short press triggers [onSelect].
final bool enableLongPress;
/// Duration for long-press detection.
final Duration longPressDuration;
/// Whether to use background color instead of border for focus indicator.
/// Useful for video controls where outline doesn't look good.
final bool useBackgroundFocus;
/// Whether to disable the scale animation on focus.
/// Useful for elements like sliders where scaling looks odd.
final bool disableScale;
const FocusableWrapper({
super.key,
required this.child,
this.onSelect,
this.onLongPress,
this.onFocusChange,
this.onNavigateUp,
this.onBack,
this.autofocus = false,
this.focusNode,
this.borderRadius = FocusTheme.defaultBorderRadius,
this.autoScroll = true,
this.scrollAlignment = 0.5,
this.useComfortableZone = false,
this.semanticLabel,
this.canRequestFocus = true,
this.onKeyEvent,
this.enableLongPress = false,
this.longPressDuration = const Duration(milliseconds: 500),
this.useBackgroundFocus = false,
this.disableScale = false,
});
@override
State<FocusableWrapper> createState() => _FocusableWrapperState();
}
class _FocusableWrapperState extends State<FocusableWrapper>
with SingleTickerProviderStateMixin {
late FocusNode _focusNode;
bool _ownsNode = false;
bool _isFocused = false;
late AnimationController _animationController;
late Animation<double> _scaleAnimation;
// Long-press detection for SELECT key
Timer? _longPressTimer;
bool _isSelectKeyDown = false;
@override
void initState() {
super.initState();
_initFocusNode();
_initAnimations();
}
void _initFocusNode() {
if (widget.focusNode != null) {
_focusNode = widget.focusNode!;
_ownsNode = false;
} else {
_focusNode = FocusNode(
debugLabel: widget.semanticLabel ?? 'FocusableWrapper',
canRequestFocus: widget.canRequestFocus,
);
_ownsNode = true;
}
}
void _initAnimations() {
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 150),
);
_scaleAnimation = Tween<double>(begin: 1.0, end: FocusTheme.focusScale)
.animate(
CurvedAnimation(
parent: _animationController,
curve: Curves.easeOutCubic,
),
);
}
@override
void didUpdateWidget(FocusableWrapper oldWidget) {
super.didUpdateWidget(oldWidget);
// Handle focusNode changes
if (widget.focusNode != oldWidget.focusNode) {
if (_ownsNode) {
_focusNode.dispose();
}
_initFocusNode();
}
// Update canRequestFocus
if (widget.canRequestFocus != oldWidget.canRequestFocus) {
_focusNode.canRequestFocus = widget.canRequestFocus;
}
}
@override
void dispose() {
_longPressTimer?.cancel();
_animationController.dispose();
if (_ownsNode) {
_focusNode.dispose();
}
super.dispose();
}
void _handleFocusChange(bool hasFocus) {
if (_isFocused != hasFocus) {
setState(() {
_isFocused = hasFocus;
});
// Animate scale
if (hasFocus) {
_animationController.forward();
} else {
_animationController.reverse();
}
// Auto-scroll into view
if (hasFocus && widget.autoScroll) {
_scrollIntoView();
}
// Notify listener
widget.onFocusChange?.call(hasFocus);
}
}
void _scrollIntoView() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_isFocused) return;
final renderObject = context.findRenderObject();
if (renderObject == null) return;
if (widget.useComfortableZone) {
// Check if item is already in the comfortable zone
final scrollable = Scrollable.maybeOf(context);
if (scrollable == null) return;
final viewport = scrollable.context.findRenderObject() as RenderBox?;
if (viewport == null) return;
// Get item's position relative to viewport
final itemBox = renderObject as RenderBox;
final itemPosition = itemBox.localToGlobal(
Offset.zero,
ancestor: viewport,
);
// Check if item is already in the comfortable zone
final viewportHeight = viewport.size.height;
final itemHeight = itemBox.size.height;
final itemVerticalCenter = itemPosition.dy + itemHeight / 2;
// Define comfortable zone - if item center is within middle 60% of viewport, don't scroll
final comfortZoneTop = viewportHeight * 0.2;
final comfortZoneBottom = viewportHeight * 0.8;
if (itemVerticalCenter >= comfortZoneTop &&
itemVerticalCenter <= comfortZoneBottom) {
// Item is in comfortable zone, no need to scroll
return;
}
}
// Item is outside comfortable zone or comfortable zone disabled, scroll to alignment
Scrollable.ensureVisible(
context,
alignment: widget.scrollAlignment,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
);
});
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
final key = event.logicalKey;
// Call custom key handler first
if (widget.onKeyEvent != null) {
final result = widget.onKeyEvent!(node, event);
if (result == KeyEventResult.handled) {
return result;
}
}
// Handle SELECT key with optional long-press detection
if (_isSelectKey(key)) {
if (widget.enableLongPress) {
if (event is KeyDownEvent) {
// Only start timer on initial press, not repeats
if (!_isSelectKeyDown) {
_isSelectKeyDown = true;
_longPressTimer?.cancel();
_longPressTimer = Timer(widget.longPressDuration, () {
// Long press detected
if (mounted) {
widget.onLongPress?.call();
}
});
}
return KeyEventResult.handled;
} else if (event is KeyRepeatEvent) {
// Consume repeat events to prevent system sounds
return KeyEventResult.handled;
} else if (event is KeyUpEvent) {
final timerWasActive = _longPressTimer?.isActive ?? false;
_longPressTimer?.cancel();
if (timerWasActive && _isSelectKeyDown) {
// Timer still active - short press
widget.onSelect?.call();
}
// If timer already fired, long press was triggered - do nothing on key up
_isSelectKeyDown = false;
return KeyEventResult.handled;
}
} else {
// Simple select handling without long-press
if (event is KeyDownEvent) {
widget.onSelect?.call();
return KeyEventResult.handled;
}
}
}
// Ignore key repeat events for other keys
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
// Context menu key
if (_isContextMenuKey(key)) {
widget.onLongPress?.call();
return KeyEventResult.handled;
}
// UP arrow - if callback provided, navigate up
if (key == LogicalKeyboardKey.arrowUp && widget.onNavigateUp != null) {
widget.onNavigateUp!();
return KeyEventResult.handled;
}
// BACK key
if (_isBackKey(key) && widget.onBack != null) {
widget.onBack!();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
bool _isSelectKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.select ||
key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.numpadEnter ||
key == LogicalKeyboardKey.gameButtonA;
}
bool _isContextMenuKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.contextMenu ||
key == LogicalKeyboardKey.gameButtonX;
}
bool _isBackKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.escape ||
key == LogicalKeyboardKey.goBack ||
key == LogicalKeyboardKey.browserBack ||
key == LogicalKeyboardKey.gameButtonB;
}
@override
Widget build(BuildContext context) {
final duration = FocusTheme.getAnimationDuration(context);
// Only show focus effects during keyboard/d-pad navigation
final showFocus = _isFocused && InputModeTracker.isKeyboardMode(context);
// Update animation duration if theme changes
if (_animationController.duration != duration) {
_animationController.duration = duration;
}
// Choose decoration based on useBackgroundFocus
final decoration = widget.useBackgroundFocus
? FocusTheme.focusBackgroundDecoration(
isFocused: showFocus,
borderRadius: widget.borderRadius,
)
: FocusTheme.focusDecoration(
context,
isFocused: showFocus,
borderRadius: widget.borderRadius,
);
Widget result = Focus(
focusNode: _focusNode,
autofocus: widget.autofocus,
onFocusChange: _handleFocusChange,
onKeyEvent: _handleKeyEvent,
child: AnimatedBuilder(
animation: _scaleAnimation,
builder: (context, child) {
final shouldScale = showFocus && !widget.disableScale;
return Transform.scale(
scale: shouldScale ? _scaleAnimation.value : 1.0,
child: AnimatedContainer(
duration: duration,
curve: Curves.easeOutCubic,
decoration: decoration,
child: widget.child,
),
);
},
),
);
// Add semantics if label provided
if (widget.semanticLabel != null) {
result = Semantics(
label: widget.semanticLabel,
button: widget.onSelect != null,
child: result,
);
}
return result;
}
}
+129
View File
@@ -0,0 +1,129 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/tv_detection_service.dart';
import '../services/gamepad_service.dart';
/// Tracks whether the user is navigating via keyboard/d-pad or pointer (mouse/touch).
///
/// Focus effects should only be shown during keyboard navigation.
enum InputMode { keyboard, pointer }
/// Provides input mode tracking to descendant widgets.
///
/// Wrap your app with this widget to enable input mode detection:
/// ```dart
/// InputModeTracker(
/// child: MaterialApp(...),
/// )
/// ```
///
/// Then check the mode in focusable widgets:
/// ```dart
/// final showFocus = _isFocused && InputModeTracker.isKeyboardMode(context);
/// ```
class InputModeTracker extends StatefulWidget {
final Widget child;
const InputModeTracker({super.key, required this.child});
/// Get the current input mode.
static InputMode of(BuildContext context) {
final provider = context
.dependOnInheritedWidgetOfExactType<_InputModeProvider>();
return provider?.mode ?? InputMode.pointer;
}
/// Convenience method to check if we're in keyboard mode.
static bool isKeyboardMode(BuildContext context) {
return of(context) == InputMode.keyboard;
}
@override
State<InputModeTracker> createState() => _InputModeTrackerState();
}
class _InputModeTrackerState extends State<InputModeTracker> {
// Default to keyboard mode on Android TV, pointer mode elsewhere
InputMode _mode = TvDetectionService.isTVSync()
? InputMode.keyboard
: InputMode.pointer;
@override
void initState() {
super.initState();
// Initialize focus highlight strategy based on starting mode
_updateFocusHighlightStrategy(_mode);
// Listen to hardware keyboard events globally
HardwareKeyboard.instance.addHandler(_handleKeyEvent);
RawKeyboard.instance.addListener(_handleRawKeyEvent);
// Register callback for gamepad input to switch to keyboard mode
GamepadService.onGamepadInput = () => _setMode(InputMode.keyboard);
}
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_handleKeyEvent);
RawKeyboard.instance.removeListener(_handleRawKeyEvent);
GamepadService.onGamepadInput = null;
super.dispose();
}
bool _handleKeyEvent(KeyEvent event) {
// Only switch to keyboard mode on key down (not repeats or releases)
if (event is KeyDownEvent) {
_setMode(InputMode.keyboard);
}
// Return false to let the event continue propagating
return false;
}
void _handleRawKeyEvent(RawKeyEvent event) {
if (event is RawKeyDownEvent) {
_setMode(InputMode.keyboard);
}
}
void _setMode(InputMode mode) {
if (_mode != mode) {
setState(() => _mode = mode);
}
_updateFocusHighlightStrategy(mode);
}
// Keep Material focus highlights in sync with our input mode so keyboard/gamepad
// navigation immediately shows focus without waiting for a real keypress.
void _updateFocusHighlightStrategy(InputMode mode) {
final desiredStrategy = mode == InputMode.keyboard
? FocusHighlightStrategy.alwaysTraditional
: FocusHighlightStrategy.automatic;
if (FocusManager.instance.highlightStrategy != desiredStrategy) {
FocusManager.instance.highlightStrategy = desiredStrategy;
}
}
@override
Widget build(BuildContext context) {
return Listener(
// Switch to pointer mode on mouse activity
onPointerDown: (_) => _setMode(InputMode.pointer),
onPointerHover: (_) => _setMode(InputMode.pointer),
behavior: HitTestBehavior.translucent,
child: _InputModeProvider(mode: _mode, child: widget.child),
);
}
}
/// InheritedWidget that provides the current input mode.
class _InputModeProvider extends InheritedWidget {
final InputMode mode;
const _InputModeProvider({required this.mode, required super.child});
@override
bool updateShouldNotify(_InputModeProvider oldWidget) {
return mode != oldWidget.mode;
}
}
+41
View File
@@ -0,0 +1,41 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dpad_navigator.dart';
/// Handles back key events by popping the current route.
///
/// Optionally pass a [result] to return to the previous route.
///
/// Use this as an `onKeyEvent` callback for Focus widgets that need
/// simple back navigation behavior:
///
/// ```dart
/// Focus(
/// onKeyEvent: (node, event) => handleBackKeyNavigation(context, event),
/// child: ...
/// )
/// ```
///
/// With a result value:
/// ```dart
/// Focus(
/// onKeyEvent: (node, event) => handleBackKeyNavigation(
/// context,
/// event,
/// result: _hasChanges,
/// ),
/// child: ...
/// )
/// ```
KeyEventResult handleBackKeyNavigation<T>(
BuildContext context,
KeyEvent event, {
T? result,
}) {
if (event is KeyDownEvent && event.logicalKey.isBackKey) {
Navigator.pop(context, result);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
+35
View File
@@ -0,0 +1,35 @@
/// Manages focus memory for hub navigation.
///
/// Tracks two things:
/// 1. Per-hub memory: Each hub remembers which item was last focused
/// 2. Global column hint: When entering a hub that hasn't been visited,
/// we use the column position from the last focused hub as a hint
class HubFocusMemory {
static final Map<String, int> _perHubMemory = {};
static int _lastColumnHint = 0;
/// Remember the focused index for a specific hub
static void setForHub(String hubKey, int index) {
_perHubMemory[hubKey] = index;
_lastColumnHint = index;
}
/// Get the remembered index for a hub, or fall back to column hint
static int getForHub(String hubKey, int itemCount) {
if (itemCount <= 0) return 0;
// If this hub has memory, use it
if (_perHubMemory.containsKey(hubKey)) {
return _perHubMemory[hubKey]!.clamp(0, itemCount - 1);
}
// Otherwise use the last column hint (clamped to this hub's item count)
return _lastColumnHint.clamp(0, itemCount - 1);
}
/// Clear all memory (e.g., when leaving a screen)
static void clear() {
_perHubMemory.clear();
_lastColumnHint = 0;
}
}
+6375 -12497
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -412,6 +412,7 @@
"serverDebugCopied": "Server debug data copied to clipboard",
"copyDebugData": "Copy Debug Data",
"noServersFound": "No servers found",
"noServersFoundForAccount": "No servers found for ${username} (${email})",
"malformedServerData": "Found ${count} server(s) with malformed data. No valid servers available.",
"incompleteServerInfo": "Some servers have incomplete information and were skipped. Please check your Plex.tv account.",
"incompleteConnectionInfo": "Server connection information is incomplete. Please try again.",
+1
View File
@@ -414,6 +414,7 @@
"serverDebugCopied": "Server-Debugdaten kopiert",
"copyDebugData": "Debugdaten kopieren",
"noServersFound": "Keine Server gefunden",
"noServersFoundForAccount": "Keine Server gefunden für ${username} (${email})",
"malformedServerData": "${count} Server mit fehlerhaften Daten gefunden. Keine gültigen Server verfügbar.",
"incompleteServerInfo": "Einige Serverinformationen sind unvollständig und wurden übersprungen. Plex.tv-Konto prüfen.",
"incompleteConnectionInfo": "Serververbindungsinformationen unvollständig. Bitte erneut versuchen.",
+1
View File
@@ -414,6 +414,7 @@
"serverDebugCopied": "Dati di debug del server copiati negli appunti",
"copyDebugData": "Copia dati di debug",
"noServersFound": "Nessun server trovato",
"noServersFoundForAccount": "Nessun server trovato per ${username} (${email})",
"malformedServerData": "Trovato ${count} server con dati difettosi. Nessun server valido disponibile.",
"incompleteServerInfo": "Alcuni server presentano informazioni incomplete e sono stati ignorati. Controlla il tuo account Plex.tv.",
"incompleteConnectionInfo": "Le informazioni di connessione al server sono incomplete. Riprova.",
+1
View File
@@ -414,6 +414,7 @@
"serverDebugCopied": "Server debug gegevens gekopieerd naar klembord",
"copyDebugData": "Kopieer debug gegevens",
"noServersFound": "Geen servers gevonden",
"noServersFoundForAccount": "Geen servers gevonden voor ${username} (${email})",
"malformedServerData": "${count} server(s) gevonden met verkeerde data. Geen geldige servers beschikbaar.",
"incompleteServerInfo": "Sommige servers hebben incomplete informatie en zijn overgeslagen. Controleer je Plex.tv account.",
"incompleteConnectionInfo": "Server verbinding informatie is incompleet. Probeer opnieuw.",
+1
View File
@@ -414,6 +414,7 @@
"serverDebugCopied": "Server-felsökningsdata kopierad till urklipp",
"copyDebugData": "Kopiera felsökningsdata",
"noServersFound": "Inga servrar hittades",
"noServersFoundForAccount": "Inga servrar hittades för ${username} (${email})",
"malformedServerData": "Hittade ${count} server(ar) med felformaterad data. Inga giltiga servrar tillgängliga.",
"incompleteServerInfo": "Vissa servrar har ofullständig information och hoppades över. Vänligen kontrollera ditt Plex.tv-konto.",
"incompleteConnectionInfo": "Server-anslutningsinformation är ofullständig. Försök igen.",
+1
View File
@@ -414,6 +414,7 @@
"serverDebugCopied": "服务器调试数据已复制到剪贴板",
"copyDebugData": "复制调试数据",
"noServersFound": "未找到服务器",
"noServersFoundForAccount": "未找到 ${username} (${email}) 的服务器",
"malformedServerData": "找到 ${count} 个数据格式错误的服务器。没有可用的有效服务器。",
"incompleteServerInfo": "某些服务器信息不完整,已被跳过。请检查你的 Plex.tv 账户。",
"incompleteConnectionInfo": "服务器连接信息不完整。请重试。",
+23 -8
View File
@@ -10,6 +10,8 @@ import 'services/macos_titlebar_service.dart';
import 'services/fullscreen_state_manager.dart';
import 'services/update_service.dart';
import 'services/settings_service.dart';
import 'services/tv_detection_service.dart';
import 'services/gamepad_service.dart';
import 'providers/user_profile_provider.dart';
import 'providers/plex_client_provider.dart';
import 'providers/multi_server_provider.dart';
@@ -25,6 +27,7 @@ import 'utils/app_logger.dart';
import 'utils/orientation_helper.dart';
import 'utils/language_codes.dart';
import 'i18n/strings.g.dart';
import 'focus/input_mode_tracker.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
@@ -47,6 +50,11 @@ void main() async {
futures.add(windowManager.ensureInitialized());
}
// Initialize TV detection for Android
if (Platform.isAndroid) {
futures.add(TvDetectionService.getInstance().then((_) {}));
}
// Configure macOS window with custom titlebar (depends on window manager)
futures.add(MacOSTitlebarService.setupCustomTitlebar());
@@ -66,6 +74,11 @@ void main() async {
// Start global fullscreen state monitoring
FullscreenStateManager().startMonitoring();
// Initialize gamepad service for desktop platforms
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
GamepadService.instance.start();
}
// DTD service is available for MCP tooling connection if needed
runApp(const MainApp());
@@ -109,14 +122,16 @@ class MainApp extends StatelessWidget {
child: Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return TranslationProvider(
child: MaterialApp(
title: t.app.title,
debugShowCheckedModeBanner: false,
theme: themeProvider.lightTheme,
darkTheme: themeProvider.darkTheme,
themeMode: themeProvider.materialThemeMode,
navigatorObservers: [routeObserver],
home: const OrientationAwareSetup(),
child: InputModeTracker(
child: MaterialApp(
title: t.app.title,
debugShowCheckedModeBanner: false,
theme: themeProvider.lightTheme,
darkTheme: themeProvider.darkTheme,
themeMode: themeProvider.materialThemeMode,
navigatorObservers: [routeObserver],
home: const OrientationAwareSetup(),
),
),
);
},
-102
View File
@@ -1,102 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/keyboard_utils.dart';
/// A mixin that provides keyboard long-press detection for focusable widgets.
///
/// This allows keyboard/gamepad users to access context menus by holding
/// the activation key (Enter, Space, Select, or GameButtonA) for 1 second.
///
/// Usage:
/// ```dart
/// class _MyWidgetState extends State<MyWidget> with KeyboardLongPressMixin {
/// @override
/// void onKeyboardTap() {
/// // Handle short press (normal tap)
/// }
///
/// @override
/// void onKeyboardLongPress() {
/// // Handle long press (show context menu)
/// }
///
/// KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
/// final result = handleKeyboardLongPress(event);
/// if (result == KeyEventResult.handled) return result;
/// // Handle other keys...
/// return KeyEventResult.ignored;
/// }
/// }
/// ```
mixin KeyboardLongPressMixin<T extends StatefulWidget> on State<T> {
Timer? _longPressTimer;
LogicalKeyboardKey? _pressedKey;
bool _longPressTriggered = false;
static const _longPressDuration = Duration(seconds: 1);
/// Override to handle tap action (short press)
void onKeyboardTap();
/// Override to handle long press action (e.g., show context menu)
void onKeyboardLongPress();
/// Call this from your onKeyEvent handler to enable long-press detection.
/// Returns [KeyEventResult.handled] if the event was an activation key,
/// [KeyEventResult.ignored] otherwise.
KeyEventResult handleKeyboardLongPress(KeyEvent event) {
if (!isKeyboardActivationKey(event.logicalKey)) {
return KeyEventResult.ignored;
}
if (event is KeyDownEvent) {
// Only start timer on initial press (not key repeat)
if (_pressedKey == null) {
_pressedKey = event.logicalKey;
_longPressTriggered = false;
_longPressTimer = Timer(_longPressDuration, () {
_longPressTriggered = true;
onKeyboardLongPress();
});
}
return KeyEventResult.handled;
}
// Handle key repeat events (suppress system sound on macOS)
if (event is KeyRepeatEvent) {
return KeyEventResult.handled;
}
if (event is KeyUpEvent && event.logicalKey == _pressedKey) {
_longPressTimer?.cancel();
_longPressTimer = null;
_pressedKey = null;
// Only trigger tap if long press wasn't already triggered
if (!_longPressTriggered) {
onKeyboardTap();
}
_longPressTriggered = false;
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Cancel any pending long-press timer. Call this if focus is lost
/// or the widget is being disposed while a key is held.
void cancelKeyboardLongPress() {
_longPressTimer?.cancel();
_longPressTimer = null;
_pressedKey = null;
_longPressTriggered = false;
}
@override
void dispose() {
_longPressTimer?.cancel();
super.dispose();
}
}
+34
View File
@@ -0,0 +1,34 @@
import 'package:flutter/material.dart';
/// Mixin that provides focus management for library tabs.
/// Handles the lifecycle of a focus node for the first item and provides
/// a method to request focus on that item.
mixin LibraryTabFocusMixin<T extends StatefulWidget> on State<T> {
/// Focus node for the first item (for programmatic focus)
late final FocusNode firstItemFocusNode;
/// Debug label for the focus node
String get focusNodeDebugLabel;
/// Number of items in the list/grid
int get itemCount;
@override
void initState() {
super.initState();
firstItemFocusNode = FocusNode(debugLabel: focusNodeDebugLabel);
}
@override
void dispose() {
firstItemFocusNode.dispose();
super.dispose();
}
/// Focus the first item in the grid/list (for tab activation)
void focusFirstItem() {
if (itemCount > 0) {
firstItemFocusNode.requestFocus();
}
}
}
+28 -20
View File
@@ -254,37 +254,45 @@ class PlayerNative implements Player {
}
void _updateSelectedAudioTrack(dynamic trackId) {
_updateSelectedTrack<AudioTrack>(
trackId,
_state.tracks.audio.cast<AudioTrack?>().toList(),
(selection, track) => selection.copyWith(audio: track),
);
}
void _updateSelectedSubtitleTrack(dynamic trackId) {
_updateSelectedTrack<SubtitleTrack>(
trackId,
_state.tracks.subtitle.cast<SubtitleTrack?>().toList(),
(selection, track) => selection.copyWith(subtitle: track),
);
}
void _updateSelectedTrack<T>(
dynamic trackId,
List<T?> tracks,
TrackSelection Function(TrackSelection, T?) selectionSetter,
) {
final id = trackId?.toString();
AudioTrack? selectedTrack;
T? selectedTrack;
if (id != null && id != 'no') {
selectedTrack = _state.tracks.audio.cast<AudioTrack?>().firstWhere(
(t) => t?.id == id,
selectedTrack = tracks.firstWhere(
(track) => _getTrackId(track) == id,
orElse: () => null,
);
}
_state = _state.copyWith(
track: _state.track.copyWith(audio: selectedTrack),
track: selectionSetter(_state.track, selectedTrack),
);
_trackController.add(_state.track);
}
void _updateSelectedSubtitleTrack(dynamic trackId) {
final id = trackId?.toString();
SubtitleTrack? selectedTrack;
if (id != null && id != 'no') {
selectedTrack = _state.tracks.subtitle.cast<SubtitleTrack?>().firstWhere(
(t) => t?.id == id,
orElse: () => null,
);
}
_state = _state.copyWith(
track: _state.track.copyWith(subtitle: selectedTrack),
);
_trackController.add(_state.track);
String? _getTrackId<T>(T? track) {
final dynamic t = track;
return t?.id?.toString();
}
Future<void> _ensureInitialized() async {
@@ -309,7 +317,7 @@ class PlayerNative implements Player {
await _observeProperty('paused-for-cache', 'flag');
await _observeProperty(
'track-list',
Platform.isAndroid ? 'string' : 'node',
(Platform.isAndroid || Platform.isWindows) ? 'string' : 'node',
);
await _observeProperty('eof-reached', 'flag');
await _observeProperty('volume', 'double');
-5
View File
@@ -14,7 +14,6 @@ import '../player/video_rect_support.dart';
///
/// Video(
/// player: player,
/// fit: BoxFit.contain,
/// controls: (context) => MyCustomControls(),
/// )
/// ```
@@ -22,9 +21,6 @@ class Video extends StatefulWidget {
/// The player instance.
final Player player;
/// How the video should be inscribed into the widget's box.
final BoxFit fit;
/// Builder for custom video controls overlay.
final Widget Function(BuildContext context)? controls;
@@ -34,7 +30,6 @@ class Video extends StatefulWidget {
const Video({
super.key,
required this.player,
this.fit = BoxFit.contain,
this.controls,
this.backgroundColor = Colors.black,
});
+61 -84
View File
@@ -48,7 +48,11 @@ class _AuthScreenState extends State<AuthScreen> {
});
try {
// Fetch all servers for this user
// Fetch user info and servers for this user
final userInfo = await _authService.getUserInfo(plexToken);
final username = userInfo['username'] as String? ?? '';
final email = userInfo['email'] as String? ?? '';
final servers = await _authService.fetchServers(plexToken);
final storage = await StorageService.getInstance();
@@ -56,7 +60,10 @@ class _AuthScreenState extends State<AuthScreen> {
await storage.clearCredentials();
setState(() {
_isAuthenticating = false;
_errorMessage = t.serverSelection.noServersFound;
_errorMessage = t.serverSelection.noServersFoundForAccount(
username: username,
email: email,
);
});
return;
}
@@ -330,37 +337,10 @@ class _AuthScreenState extends State<AuthScreen> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_isAuthenticating) ...[
if (_useQrFlow && _qrAuthUrl != null) ...[
// QR code flow - hint text above QR code
Text(
t.auth.scanQRCodeInstruction,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: QrImageView(
data: _qrAuthUrl!,
size: 300,
version: QrVersions.auto,
backgroundColor: Colors.white,
),
),
),
_buildRetryButton(),
] else ...[
// Browser auth flow - show spinner and waiting message
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
Text(
t.auth.waitingForAuth,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
_buildRetryButton(),
],
if (_useQrFlow && _qrAuthUrl != null)
_buildQrAuthWidget(qrSize: 300)
else
_buildBrowserAuthWidget(),
] else ...[
// Initial state buttons
ElevatedButton(
@@ -436,57 +416,10 @@ class _AuthScreenState extends State<AuthScreen> {
),
const SizedBox(height: 48),
if (_isAuthenticating) ...[
if (_useQrFlow && _qrAuthUrl != null) ...[
// QR code flow - show QR code and scan instruction
Text(
t.auth.scanQRCodeInstruction,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: QrImageView(
data: _qrAuthUrl!,
size: 200,
version: QrVersions.auto,
backgroundColor: Colors.white,
),
),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
] else ...[
// Browser auth flow - show spinner and waiting message
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
Text(
t.auth.waitingForAuth,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: Text(t.auth.retry),
),
],
if (_useQrFlow && _qrAuthUrl != null)
_buildQrAuthWidget(qrSize: 200)
else
_buildBrowserAuthWidget(),
] else ...[
// add QR button here
ElevatedButton(
@@ -560,4 +493,48 @@ class _AuthScreenState extends State<AuthScreen> {
],
);
}
/// Builds the QR code authentication widget
Widget _buildQrAuthWidget({required double qrSize}) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
t.auth.scanQRCodeInstruction,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: QrImageView(
data: _qrAuthUrl!,
size: qrSize,
version: QrVersions.auto,
backgroundColor: Colors.white,
),
),
),
_buildRetryButton(),
],
);
}
/// Builds the browser authentication waiting widget
Widget _buildBrowserAuthWidget() {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
Text(
t.auth.waitingForAuth,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.grey),
),
_buildRetryButton(),
],
);
}
}
+15 -45
View File
@@ -1,11 +1,8 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/settings_provider.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/media_grid_sliver.dart';
import '../widgets/focused_scroll_scaffold.dart';
import '../i18n/strings.g.dart';
import '../utils/grid_size_calculator.dart';
import '../utils/dialogs.dart';
import '../utils/app_logger.dart';
import 'base_media_list_detail_screen.dart';
@@ -114,47 +111,20 @@ class _CollectionDetailScreenState
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(widget.collection.title),
pinned: true,
actions: buildAppBarActions(onDelete: _deleteCollection),
return FocusedScrollScaffold(
title: Text(widget.collection.title),
actions: buildAppBarActions(onDelete: _deleteCollection),
slivers: [
...buildStateSlivers(),
if (items.isNotEmpty)
MediaGridSliver(
items: items,
onRefresh: updateItem,
collectionId: widget.collection.ratingKey,
onListRefresh: loadItems,
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
),
...buildStateSlivers(),
if (items.isNotEmpty)
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
sliver: Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
GridSizeCalculator.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,
collectionId: widget.collection.ratingKey,
onListRefresh: loadItems,
);
}, childCount: items.length),
);
},
),
),
],
),
],
);
}
}
+456 -250
View File
@@ -14,7 +14,6 @@ import '../providers/playback_state_provider.dart';
import '../widgets/desktop_app_bar.dart';
import 'profile/user_avatar_widget.dart';
import '../widgets/hub_section.dart';
import '../widgets/hub_navigation_controller.dart';
import 'profile/profile_switch_screen.dart';
import '../providers/user_profile_provider.dart';
import '../providers/settings_provider.dart';
@@ -22,12 +21,11 @@ import '../mixins/refreshable.dart';
import '../i18n/strings.g.dart';
import '../mixins/item_updatable.dart';
import '../utils/app_logger.dart';
import '../utils/keyboard_utils.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/content_rating_formatter.dart';
import '../focus/dpad_navigator.dart';
import 'auth_screen.dart';
import 'main_screen.dart';
class DiscoverScreen extends StatefulWidget {
final VoidCallback? onBecameVisible;
@@ -59,7 +57,6 @@ class _DiscoverScreenState extends State<DiscoverScreen>
List<PlexMetadata> _onDeck = [];
List<PlexHub> _hubs = [];
bool _isLoading = true;
bool _isInitialLoad = true;
bool _areHubsLoading = true;
String? _errorMessage;
final PageController _heroController = PageController();
@@ -68,10 +65,17 @@ class _DiscoverScreenState extends State<DiscoverScreen>
Timer? _autoScrollTimer;
late AnimationController _indicatorAnimationController;
bool _isAutoScrollPaused = false;
final HubNavigationController _hubNavigationController =
HubNavigationController();
late final FocusNode _heroFocusNode;
bool _heroIsFocused = false;
// Hub navigation keys
GlobalKey<HubSectionState>? _continueWatchingHubKey;
final List<GlobalKey<HubSectionState>> _hubKeys = [];
// Hero and app bar focus
late FocusNode _heroFocusNode;
late FocusNode _refreshButtonFocusNode;
late FocusNode _userButtonFocusNode;
bool _isRefreshFocused = false;
bool _isUserFocused = false;
/// Get the correct PlexClient for an item's server
PlexClient _getClientForItem(PlexMetadata? item) {
@@ -92,6 +96,69 @@ class _DiscoverScreenState extends State<DiscoverScreen>
return context.getClientForServer(serverId);
}
/// Update hub keys when hubs list changes
void _updateHubKeys() {
_hubKeys.clear();
for (int i = 0; i < _hubs.length; i++) {
_hubKeys.add(GlobalKey<HubSectionState>());
}
// Create continue watching hub key if needed
if (_onDeck.isNotEmpty) {
_continueWatchingHubKey ??= GlobalKey<HubSectionState>();
}
}
/// Get all hub states (continue watching + other hubs)
List<GlobalKey<HubSectionState>> get _allHubKeys {
final keys = <GlobalKey<HubSectionState>>[];
if (_continueWatchingHubKey != null && _onDeck.isNotEmpty) {
keys.add(_continueWatchingHubKey!);
}
keys.addAll(_hubKeys);
return keys;
}
/// Handle vertical navigation between hubs
/// Returns true if the navigation was handled
bool _handleVerticalNavigation(int hubIndex, bool isUp) {
final keys = _allHubKeys;
if (keys.isEmpty) return false;
// UP from first hub: Navigate to hero section
if (isUp && hubIndex == 0) {
_heroFocusNode.requestFocus();
// Scroll to top to show hero fully
_scrollController.animateTo(
0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
return true;
}
int targetIndex;
if (isUp) {
targetIndex = hubIndex - 1;
} else {
targetIndex = hubIndex + 1;
}
// Check if target is valid
if (targetIndex < 0 || targetIndex >= keys.length) {
// At boundary, block navigation (return true to consume the event)
return true;
}
// Navigate to target hub, clamping to available items
final targetState = keys[targetIndex].currentState;
if (targetState != null) {
targetState.requestFocusFromMemory();
return true;
}
return false;
}
@override
void initState() {
super.initState();
@@ -99,77 +166,153 @@ class _DiscoverScreenState extends State<DiscoverScreen>
vsync: this,
duration: _heroAutoScrollDuration,
);
_heroFocusNode = FocusNode(debugLabel: 'HeroSection');
_heroFocusNode.addListener(_handleHeroFocusChange);
_heroFocusNode = FocusNode(debugLabel: 'hero_section');
_refreshButtonFocusNode = FocusNode(debugLabel: 'refresh_button');
_userButtonFocusNode = FocusNode(debugLabel: 'user_button');
_refreshButtonFocusNode.addListener(_onRefreshFocusChange);
_userButtonFocusNode.addListener(_onUserFocusChange);
_loadContent();
_startAutoScroll();
}
void _handleHeroFocusChange() {
if (_heroIsFocused != _heroFocusNode.hasFocus) {
void _onRefreshFocusChange() {
if (mounted) {
setState(() {
_heroIsFocused = _heroFocusNode.hasFocus;
_isRefreshFocused = _refreshButtonFocusNode.hasFocus;
});
if (_heroFocusNode.hasFocus) {
// Scroll to the very top when hero is focused
_scrollController.animateTo(
0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
}
}
}
/// Handle back key press - focus bottom navigation
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
BackNavigationScope.of(context)?.focusBottomNav();
void _onUserFocusChange() {
if (mounted) {
setState(() {
_isUserFocused = _userButtonFocusNode.hasFocus;
});
}
}
/// Handle key events for the hero section
KeyEventResult _handleHeroKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// DOWN: Move to first hub
if (key.isDownKey) {
final keys = _allHubKeys;
if (keys.isNotEmpty) {
keys.first.currentState?.requestFocusFromMemory();
}
return KeyEventResult.handled;
}
// UP: Move to app bar (refresh button)
if (key.isUpKey) {
_refreshButtonFocusNode.requestFocus();
return KeyEventResult.handled;
}
// LEFT: Navigate hero carousel to previous
if (key.isLeftKey) {
if (_currentHeroIndex > 0) {
_heroController.previousPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
return KeyEventResult.handled;
}
// RIGHT: Navigate hero carousel to next
if (key.isRightKey) {
if (_currentHeroIndex < _onDeck.length - 1) {
_heroController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
return KeyEventResult.handled;
}
// SELECT: Play current hero item
if (key.isSelectKey) {
if (_onDeck.isNotEmpty && _currentHeroIndex < _onDeck.length) {
navigateToVideoPlayer(context, metadata: _onDeck[_currentHeroIndex]);
}
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
KeyEventResult _handleHeroKeyEvent(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent) {
// Enter/Space to play current hero item
if (isKeyboardActivationKey(event.logicalKey)) {
if (_onDeck.isNotEmpty && _currentHeroIndex < _onDeck.length) {
navigateToVideoPlayer(context, metadata: _onDeck[_currentHeroIndex]);
return KeyEventResult.handled;
}
}
// Left arrow to go to previous hero item
if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
if (_onDeck.isNotEmpty && _currentHeroIndex > 0) {
_heroController.previousPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
return KeyEventResult.handled;
}
}
// Right arrow to go to next hero item
if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
if (_onDeck.isNotEmpty && _currentHeroIndex < _onDeck.length - 1) {
_heroController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
return KeyEventResult.handled;
}
}
// Down arrow to navigate to first hub section
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
// Try to navigate to the first hub section
if (_hubNavigationController.navigateToAdjacentHub('_hero_', 1)) {
return KeyEventResult.handled;
}
}
/// Handle key events for the refresh button in app bar
KeyEventResult _handleRefreshKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// DOWN: Return to hero
if (key.isDownKey) {
_heroFocusNode.requestFocus();
return KeyEventResult.handled;
}
// RIGHT: Move to user button
if (key.isRightKey) {
_userButtonFocusNode.requestFocus();
return KeyEventResult.handled;
}
// LEFT/UP: Block at boundary
if (key.isLeftKey || key.isUpKey) {
return KeyEventResult.handled;
}
// SELECT: Trigger refresh
if (key.isSelectKey) {
_loadContent();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Handle key events for the user button in app bar
KeyEventResult _handleUserKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// DOWN: Return to hero
if (key.isDownKey) {
_heroFocusNode.requestFocus();
return KeyEventResult.handled;
}
// LEFT: Move to refresh button
if (key.isLeftKey) {
_refreshButtonFocusNode.requestFocus();
return KeyEventResult.handled;
}
// RIGHT/UP: Block at boundary
if (key.isRightKey || key.isUpKey) {
return KeyEventResult.handled;
}
// SELECT: Show user menu
if (key.isSelectKey) {
final userProvider = context.read<UserProfileProvider>();
_showUserMenu(context, userProvider);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@@ -179,9 +322,11 @@ class _DiscoverScreenState extends State<DiscoverScreen>
_heroController.dispose();
_scrollController.dispose();
_indicatorAnimationController.dispose();
_hubNavigationController.dispose();
_heroFocusNode.removeListener(_handleHeroFocusChange);
_heroFocusNode.dispose();
_refreshButtonFocusNode.removeListener(_onRefreshFocusChange);
_refreshButtonFocusNode.dispose();
_userButtonFocusNode.removeListener(_onUserFocusChange);
_userButtonFocusNode.dispose();
super.dispose();
}
@@ -305,17 +450,12 @@ class _DiscoverScreenState extends State<DiscoverScreen>
// Reset hero index to avoid sync issues
_currentHeroIndex = 0;
});
// Focus the hero on initial load
if (_isInitialLoad && onDeck.isNotEmpty) {
_isInitialLoad = false;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
_heroFocusNode.requestFocus();
}
});
}
// Create continue watching hub key if needed
if (_onDeck.isNotEmpty) {
_continueWatchingHubKey ??= GlobalKey<HubSectionState>();
}
});
// Sync PageController to first page after OnDeck loads
if (_heroController.hasClients && onDeck.isNotEmpty) {
@@ -355,6 +495,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
setState(() {
_hubs = filteredHubs;
_areHubsLoading = false;
_updateHubKeys();
});
appLogger.d('Discover content loaded successfully');
@@ -417,13 +558,6 @@ class _DiscoverScreenState extends State<DiscoverScreen>
_loadContent();
}
/// Focus the hero section (for keyboard navigation)
void focusHero() {
if (_onDeck.isNotEmpty) {
_heroFocusNode.requestFocus();
}
}
/// Get icon for hub based on its title
IconData _getHubIcon(String title) {
final lowerTitle = title.toLowerCase();
@@ -600,33 +734,109 @@ class _DiscoverScreenState extends State<DiscoverScreen>
);
}
/// Show user menu programmatically (for D-pad select)
void _showUserMenu(BuildContext context, UserProfileProvider userProvider) {
final RenderBox? button =
_userButtonFocusNode.context?.findRenderObject() as RenderBox?;
if (button == null) return;
final RenderBox overlay =
Navigator.of(context).overlay!.context.findRenderObject() as RenderBox;
final position = RelativeRect.fromRect(
Rect.fromPoints(
button.localToGlobal(Offset.zero, ancestor: overlay),
button.localToGlobal(
button.size.bottomRight(Offset.zero),
ancestor: overlay,
),
),
Offset.zero & overlay.size,
);
showMenu<String>(
context: context,
position: position,
items: [
if (userProvider.hasMultipleUsers)
PopupMenuItem(
value: 'switch_profile',
child: Row(
children: [
Icon(Icons.people),
SizedBox(width: 8),
Text(t.discover.switchProfile),
],
),
),
PopupMenuItem(
value: 'logout',
child: Row(
children: [
Icon(Icons.logout),
SizedBox(width: 8),
Text(t.discover.logout),
],
),
),
],
).then((value) {
if (value == 'switch_profile') {
_handleSwitchProfile(context);
} else if (value == 'logout') {
_handleLogout();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Focus(
onKeyEvent: _handleBackKey,
child: HubNavigationScope(
controller: _hubNavigationController,
child: CustomScrollView(
controller: _scrollController,
slivers: [
DesktopSliverAppBar(
title: Text(t.discover.title),
floating: true,
pinned: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
surfaceTintColor: Colors.transparent,
shadowColor: Colors.transparent,
scrolledUnderElevation: 0,
actions: [
IconButton(
child: CustomScrollView(
controller: _scrollController,
slivers: [
DesktopSliverAppBar(
title: Text(t.discover.title),
floating: true,
pinned: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
surfaceTintColor: Colors.transparent,
shadowColor: Colors.transparent,
scrolledUnderElevation: 0,
actions: [
Focus(
focusNode: _refreshButtonFocusNode,
onKeyEvent: _handleRefreshKeyEvent,
child: Container(
decoration: BoxDecoration(
color: _isRefreshFocused
? Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.08)
: Colors.transparent,
borderRadius: BorderRadius.circular(20),
),
child: IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadContent,
),
Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
return PopupMenuButton<String>(
),
),
Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
return Focus(
focusNode: _userButtonFocusNode,
onKeyEvent: _handleUserKeyEvent,
child: DecoratedBox(
decoration: BoxDecoration(
color: _isUserFocused
? Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.08)
: Colors.transparent,
borderRadius: BorderRadius.circular(20),
),
child: PopupMenuButton<String>(
icon: userProvider.currentUser?.thumb != null
? UserAvatarWidget(
user: userProvider.currentUser!,
@@ -665,175 +875,171 @@ class _DiscoverScreenState extends State<DiscoverScreen>
),
),
],
);
},
),
],
),
),
);
},
),
if (_isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
],
),
if (_isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
),
if (_errorMessage != null)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: Colors.red,
),
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadContent,
child: Text(t.common.retry),
),
],
),
if (_errorMessage != null)
SliverFillRemaining(
child: Center(
),
),
if (!_isLoading && _errorMessage == null) ...[
// Hero Section (Continue Watching)
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (_onDeck.isNotEmpty && settingsProvider.showHeroSection) {
return _buildHeroSection();
}
return const SliverToBoxAdapter(child: SizedBox.shrink());
},
),
// On Deck / Continue Watching
if (_onDeck.isNotEmpty)
SliverToBoxAdapter(
child: HubSection(
key: _continueWatchingHubKey,
hub: PlexHub(
hubKey: 'continue_watching',
title: t.discover.continueWatching,
type: 'mixed',
hubIdentifier: '_continue_watching_',
size: _onDeck.length,
more: false,
items: _onDeck,
),
icon: Icons.play_circle_outline,
onRefresh: updateItem,
onRemoveFromContinueWatching: _refreshContinueWatching,
isInContinueWatching: true,
onVerticalNavigation: (isUp) =>
_handleVerticalNavigation(0, isUp),
),
),
// Recommendation Hubs (Trending, Top in Genre, etc.)
for (int i = 0; i < _hubs.length; i++)
SliverToBoxAdapter(
child: HubSection(
key: i < _hubKeys.length ? _hubKeys[i] : null,
hub: _hubs[i],
icon: _getHubIcon(_hubs[i].title),
onRefresh: updateItem,
// Hub index is i + 1 if continue watching exists, otherwise i
onVerticalNavigation: (isUp) => _handleVerticalNavigation(
_onDeck.isNotEmpty ? i + 1 : i,
isUp,
),
),
),
// Show loading skeleton for hubs while they're loading
if (_areHubsLoading && _hubs.isEmpty)
for (int i = 0; i < 3; i++)
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: Colors.red,
// Hub title skeleton
Container(
width: 200,
height: 24,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadContent,
child: Text(t.common.retry),
// Hub items skeleton
SizedBox(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 5,
itemBuilder: (context, index) {
return Container(
margin: const EdgeInsets.only(right: 12),
width: 140,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
);
},
),
),
],
),
),
),
if (!_isLoading && _errorMessage == null) ...[
// Hero Section (Continue Watching)
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (_onDeck.isNotEmpty &&
settingsProvider.showHeroSection) {
return _buildHeroSection();
}
return const SliverToBoxAdapter(child: SizedBox.shrink());
},
if (_onDeck.isEmpty && _hubs.isEmpty && !_areHubsLoading)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.movie_outlined,
size: 64,
color: Colors.grey,
),
SizedBox(height: 16),
Text(t.discover.noContentAvailable),
SizedBox(height: 8),
Text(
t.discover.addMediaToLibraries,
style: TextStyle(color: Colors.grey),
),
],
),
),
),
// On Deck / Continue Watching
if (_onDeck.isNotEmpty)
SliverToBoxAdapter(
child: HubSection(
hub: PlexHub(
hubKey: 'continue_watching',
title: t.discover.continueWatching,
type: 'mixed',
hubIdentifier: '_continue_watching_',
size: _onDeck.length,
more: false,
items: _onDeck,
),
icon: Icons.play_circle_outline,
onRefresh: updateItem,
onRemoveFromContinueWatching: _refreshContinueWatching,
isInContinueWatching: true,
navigationOrder: 1, // After hero
),
),
// Recommendation Hubs (Trending, Top in Genre, etc.)
for (int i = 0; i < _hubs.length; i++)
SliverToBoxAdapter(
child: HubSection(
hub: _hubs[i],
icon: _getHubIcon(_hubs[i].title),
onRefresh: updateItem,
navigationOrder: 2 + i, // After continue watching
),
),
// Show loading skeleton for hubs while they're loading
if (_areHubsLoading && _hubs.isEmpty)
for (int i = 0; i < 3; i++)
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Hub title skeleton
Container(
width: 200,
height: 24,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(height: 16),
// Hub items skeleton
SizedBox(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 5,
itemBuilder: (context, index) {
return Container(
margin: const EdgeInsets.only(right: 12),
width: 140,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
);
},
),
),
],
),
),
),
if (_onDeck.isEmpty && _hubs.isEmpty && !_areHubsLoading)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.movie_outlined,
size: 64,
color: Colors.grey,
),
SizedBox(height: 16),
Text(t.discover.noContentAvailable),
SizedBox(height: 8),
Text(
t.discover.addMediaToLibraries,
style: TextStyle(color: Colors.grey),
),
],
),
),
),
const SliverToBoxAdapter(child: SizedBox(height: 24)),
],
],
),
),
const SliverToBoxAdapter(child: SizedBox(height: 24)),
],
],
),
),
);
}
Widget _buildHeroSection() {
// Register hero section with navigation controller
// This allows pressing up from first hub to return to hero
_hubNavigationController.register(
HubSectionRegistration(
hubId: '_hero_',
itemCount: 1,
focusItem: (_) => _heroFocusNode.requestFocus(),
order: 0, // Hero is first
),
);
return SliverToBoxAdapter(
child: Focus(
focusNode: _heroFocusNode,
autofocus: true,
onKeyEvent: _handleHeroKeyEvent,
child: SizedBox(
height: 500,
+42 -69
View File
@@ -1,15 +1,12 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../services/plex_client.dart';
import '../models/plex_hub.dart';
import '../models/plex_metadata.dart';
import '../models/plex_sort.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/app_logger.dart';
import '../utils/grid_cross_axis_extent.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/media_grid_sliver.dart';
import '../widgets/focused_scroll_scaffold.dart';
import 'libraries/sort_bottom_sheet.dart';
import '../mixins/refreshable.dart';
import '../i18n/strings.g.dart';
@@ -242,73 +239,49 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(widget.hub.title),
pinned: true,
actions: [
IconButton(
icon: Icon(Icons.swap_vert, semanticLabel: t.libraries.sort),
onPressed: _showSortBottomSheet,
),
],
),
if (_errorMessage != null)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: Colors.red,
),
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadMoreItems,
child: Text(t.common.retry),
),
],
),
),
)
else if (_filteredItems.isEmpty && _isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (_filteredItems.isEmpty)
SliverFillRemaining(
child: Center(child: Text(t.hubDetail.noItemsFound)),
)
else
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: getMaxCrossAxisExtentWithPadding(
context,
context.watch<SettingsProvider>().libraryDensity,
16,
return FocusedScrollScaffold(
title: Text(widget.hub.title),
actions: [
IconButton(
icon: Icon(Icons.swap_vert, semanticLabel: t.libraries.sort),
onPressed: _showSortBottomSheet,
),
],
slivers: [
if (_errorMessage != null)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadMoreItems,
child: Text(t.common.retry),
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
delegate: SliverChildBuilderDelegate((context, index) {
return MediaCard(
item: _filteredItems[index],
onRefresh: _handleItemRefresh,
);
}, childCount: _filteredItems.length),
],
),
),
],
),
)
else if (_filteredItems.isEmpty && _isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (_filteredItems.isEmpty)
SliverFillRemaining(
child: Center(child: Text(t.hubDetail.noItemsFound)),
)
else
MediaGridSliver(
items: _filteredItems,
onRefresh: _handleItemRefresh,
usePaddingAwareExtent: true,
horizontalPadding: 16,
),
],
);
}
}
+53 -50
View File
@@ -1,17 +1,20 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_metadata.dart';
import '../../providers/settings_provider.dart';
import '../../services/settings_service.dart' show ViewMode;
import '../../services/settings_service.dart' show ViewMode, LibraryDensity;
import '../../utils/grid_size_calculator.dart';
import '../../widgets/media_card.dart';
/// A widget that automatically switches between grid and list view
/// based on user settings, providing a consistent layout pattern
/// across all library screens
class AdaptiveMediaGrid extends StatelessWidget {
/// The list of media items to display
final List<PlexMetadata> items;
/// across all library screens.
///
/// Generic type T: The type of items being displayed
class AdaptiveMediaGrid<T> extends StatelessWidget {
/// The list of items to display
final List<T> items;
/// Builder function for each item in the grid/list
final Widget Function(BuildContext context, T item, int index) itemBuilder;
/// Callback when the list needs to be refreshed
final VoidCallback? onRefresh;
@@ -22,65 +25,65 @@ class AdaptiveMediaGrid extends StatelessWidget {
/// Child aspect ratio for grid items (width / height)
final double childAspectRatio;
/// Optional focus node for the first item (for keyboard navigation)
/// Optional focus node for the first item (for programmatic focus)
final FocusNode? firstItemFocusNode;
/// Callback when back button is pressed (for hierarchical navigation)
final VoidCallback? onBack;
const AdaptiveMediaGrid({
super.key,
required this.items,
required this.itemBuilder,
this.onRefresh,
this.padding = const EdgeInsets.fromLTRB(8, 8, 8, 8),
this.childAspectRatio = 2 / 3.3,
this.firstItemFocusNode,
this.onBack,
});
@override
Widget build(BuildContext context) {
return Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return FocusTraversalGroup(
child: ListView.builder(
padding: padding,
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onListRefresh: onRefresh,
focusNode: index == 0 ? firstItemFocusNode : null,
);
},
),
);
} else {
return FocusTraversalGroup(
child: GridView.builder(
padding: padding,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: childAspectRatio,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onListRefresh: onRefresh,
focusNode: index == 0 ? firstItemFocusNode : null,
);
},
),
);
}
return _buildItemsView(
context,
settingsProvider.viewMode,
settingsProvider.libraryDensity,
);
},
);
}
/// Builds either a list or grid view based on the view mode
Widget _buildItemsView(
BuildContext context,
ViewMode viewMode,
LibraryDensity density,
) {
if (viewMode == ViewMode.list) {
return ListView.builder(
padding: padding,
itemCount: items.length,
itemBuilder: (context, index) =>
itemBuilder(context, items[index], index),
);
} else {
return GridView.builder(
padding: padding,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
density,
),
childAspectRatio: childAspectRatio,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) =>
itemBuilder(context, items[index], index),
);
}
}
}
+14 -42
View File
@@ -2,8 +2,9 @@ import 'package:flutter/material.dart';
import '../../models/plex_filter.dart';
import '../../widgets/app_bar_back_button.dart';
import '../../widgets/bottom_sheet_header.dart';
import '../../widgets/focusable_bottom_sheet.dart';
import '../../widgets/focusable_list_tile.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/keyboard_utils.dart';
import '../../i18n/strings.g.dart';
class FiltersBottomSheet extends StatefulWidget {
@@ -31,28 +32,19 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
final Map<String, String> _tempSelectedFilters = {};
final Map<String, String> _filterDisplayNames = {}; // Cache for display names
late List<PlexFilter> _sortedFilters;
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'FilterFirstItem',
);
final FocusNode _filterValuesFocusNode = FocusNode(
debugLabel: 'FilterValuesFirstItem',
);
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_tempSelectedFilters.addAll(widget.selectedFilters);
_sortFilters();
// Focus the first item after build
WidgetsBinding.instance.addPostFrameCallback((_) {
_firstItemFocusNode.requestFocus();
});
_initialFocusNode = FocusNode(debugLabel: 'FiltersBottomSheetInitialFocus');
}
@override
void dispose() {
_firstItemFocusNode.dispose();
_filterValuesFocusNode.dispose();
_initialFocusNode.dispose();
super.dispose();
}
@@ -87,10 +79,6 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
_filterValues = values;
_isLoadingValues = false;
});
// Focus the first filter value after loading
WidgetsBinding.instance.addPostFrameCallback((_) {
_filterValuesFocusNode.requestFocus();
});
} catch (e) {
setState(() {
_filterValues = [];
@@ -111,21 +99,6 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
Navigator.pop(context);
}
/// Handle back key - go back to main view or close sheet
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
if (_currentFilter != null) {
// Go back to main filters view
_goBack();
} else {
// Close the bottom sheet
Navigator.pop(context);
}
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
String _extractFilterValue(String key, String filterName) {
if (key.contains('?')) {
final queryStart = key.indexOf('?');
@@ -140,9 +113,8 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
@override
Widget build(BuildContext context) {
return Focus(
autofocus: true,
onKeyEvent: _handleBackKey,
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: DraggableScrollableSheet(
initialChildSize: 0.7,
minChildSize: 0.5,
@@ -178,8 +150,8 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
final isSelected = !_tempSelectedFilters.containsKey(
_currentFilter!.filter,
);
return ListTile(
focusNode: _filterValuesFocusNode,
return FocusableListTile(
focusNode: _initialFocusNode,
title: Text(t.libraries.all),
selected: isSelected,
onTap: () {
@@ -202,7 +174,7 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
_tempSelectedFilters[_currentFilter!.filter] ==
filterValue;
return ListTile(
return FocusableListTile(
title: Text(value.title),
selected: isSelected,
onTap: () {
@@ -258,8 +230,8 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
final isActive =
_tempSelectedFilters.containsKey(filter.filter) &&
_tempSelectedFilters[filter.filter] == '1';
return SwitchListTile(
focusNode: index == 0 ? _firstItemFocusNode : null,
return FocusableSwitchListTile(
focusNode: index == 0 ? _initialFocusNode : null,
value: isActive,
onChanged: (value) {
setState(() {
@@ -285,8 +257,8 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
selectedValue;
}
return ListTile(
focusNode: index == 0 ? _firstItemFocusNode : null,
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
title: Text(filter.title),
trailing: Row(
mainAxisSize: MainAxisSize.min,
+75 -98
View File
@@ -1,16 +1,14 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../models/plex_metadata.dart';
import '../../utils/keyboard_utils.dart';
/// Individual item in the folder tree
/// Can be either a folder (expandable) or a file (tappable)
class FolderTreeItem extends StatefulWidget {
class FolderTreeItem extends StatelessWidget {
final PlexMetadata item;
final int depth;
final bool isExpanded;
final bool isFolder;
final void Function({bool isKeyboard})? onTap;
final VoidCallback? onTap;
final VoidCallback? onExpand;
final bool isLoading;
@@ -25,20 +23,13 @@ class FolderTreeItem extends StatefulWidget {
this.isLoading = false,
});
@override
State<FolderTreeItem> createState() => _FolderTreeItemState();
}
class _FolderTreeItemState extends State<FolderTreeItem> {
bool _isKeyboardActivation = false;
IconData _getIcon() {
if (widget.isFolder) {
if (isFolder) {
return Icons.folder;
}
// File icons based on type
final type = widget.item.type.toLowerCase();
final type = item.type.toLowerCase();
switch (type) {
case 'movie':
return Icons.movie;
@@ -55,103 +46,89 @@ class _FolderTreeItemState extends State<FolderTreeItem> {
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent && isKeyboardActivationKey(event.logicalKey)) {
_isKeyboardActivation = true;
return KeyEventResult.ignored; // Let InkWell handle the activation
}
return KeyEventResult.ignored;
}
void _handleTap() {
if (widget.isFolder) {
widget.onExpand?.call();
if (isFolder) {
onExpand?.call();
} else {
widget.onTap?.call(isKeyboard: _isKeyboardActivation);
onTap?.call();
}
_isKeyboardActivation = false;
}
@override
Widget build(BuildContext context) {
final indentation = widget.depth * 24.0;
final indentation = depth * 24.0;
return Focus(
onKeyEvent: _handleKeyEvent,
child: InkWell(
onTap: _handleTap,
child: Container(
padding: EdgeInsets.only(
left: 16.0 + indentation,
right: 16.0,
top: 12.0,
bottom: 12.0,
),
child: Row(
children: [
// Expand/collapse icon for folders
if (widget.isFolder)
SizedBox(
width: 24,
child: widget.isLoading
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Icon(
widget.isExpanded
? Icons.keyboard_arrow_down
: Icons.keyboard_arrow_right,
size: 20,
),
)
else
const SizedBox(width: 24),
return InkWell(
onTap: _handleTap,
child: Container(
padding: EdgeInsets.only(
left: 16.0 + indentation,
right: 16.0,
top: 12.0,
bottom: 12.0,
),
child: Row(
children: [
// Expand/collapse icon for folders
if (isFolder)
SizedBox(
width: 24,
child: isLoading
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Icon(
isExpanded
? Icons.keyboard_arrow_down
: Icons.keyboard_arrow_right,
size: 20,
),
)
else
const SizedBox(width: 24),
const SizedBox(width: 8),
const SizedBox(width: 8),
// File/folder icon
Icon(
_getIcon(),
size: 20,
color: widget.isFolder
? Theme.of(context).colorScheme.primary
: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.7),
),
const SizedBox(width: 12),
// Item title
Expanded(
child: Text(
widget.item.title,
style: TextStyle(
fontSize: 14,
fontWeight: widget.isFolder
? FontWeight.w500
: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
// Additional metadata for files
if (!widget.isFolder && widget.item.year != null)
Text(
widget.item.year.toString(),
style: TextStyle(
fontSize: 12,
color: Theme.of(
// File/folder icon
Icon(
_getIcon(),
size: 20,
color: isFolder
? Theme.of(context).colorScheme.primary
: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.6),
),
).colorScheme.onSurface.withValues(alpha: 0.7),
),
const SizedBox(width: 12),
// Item title
Expanded(
child: Text(
item.title,
style: TextStyle(
fontSize: 14,
fontWeight: isFolder ? FontWeight.w500 : FontWeight.w400,
),
],
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
// Additional metadata for files
if (!isFolder && item.year != null)
Text(
item.year.toString(),
style: TextStyle(
fontSize: 12,
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.6),
),
),
],
),
),
);
+4 -40
View File
@@ -1,10 +1,8 @@
import 'package:flutter/material.dart';
import '../../models/plex_metadata.dart';
import '../media_detail_screen.dart';
import '../season_detail_screen.dart';
import '../../utils/app_logger.dart';
import '../../utils/media_navigation_helper.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/video_player_navigation.dart';
import '../../i18n/strings.g.dart';
import 'folder_tree_item.dart';
import 'empty_state_widget.dart';
@@ -150,39 +148,8 @@ class _FolderTreeViewState extends State<FolderTreeView> {
}
}
Future<void> _handleItemTap(
PlexMetadata item, {
bool isKeyboard = false,
}) async {
final itemType = item.type.toLowerCase();
// For episodes, start playback directly
if (itemType == 'episode') {
final result = await navigateToVideoPlayer(context, metadata: item);
if (result == true) {
widget.onRefresh?.call(item.ratingKey);
}
} else if (itemType == 'season') {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
SeasonDetailScreen(season: item, focusFirstEpisode: isKeyboard),
),
);
widget.onRefresh?.call(item.ratingKey);
} else {
// For all other types (shows, movies), show detail screen
final result = await Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) => MediaDetailScreen(metadata: item),
),
);
if (result == true) {
widget.onRefresh?.call(item.ratingKey);
}
}
Future<void> _handleItemTap(PlexMetadata item) async {
await navigateToMediaItem(context, item, onRefresh: widget.onRefresh);
}
bool _isFolder(PlexMetadata item) {
@@ -219,10 +186,7 @@ class _FolderTreeViewState extends State<FolderTreeView> {
isExpanded: isExpanded,
isLoading: isLoading,
onExpand: isFolder ? () => _toggleFolder(item) : null,
onTap: !isFolder
? ({bool isKeyboard = false}) =>
_handleItemTap(item, isKeyboard: isKeyboard)
: null,
onTap: !isFolder ? () => _handleItemTap(item) : null,
),
);
File diff suppressed because it is too large Load Diff
-65
View File
@@ -1,65 +0,0 @@
import 'package:flutter/material.dart';
/// A small badge widget that indicates which server content is from
/// Shows server name or first letter with optional tooltip
class ServerBadge extends StatelessWidget {
final String? serverName;
final Color? backgroundColor;
final Color? textColor;
final double size;
final bool showFullName;
const ServerBadge({
super.key,
required this.serverName,
this.backgroundColor,
this.textColor,
this.size = 20,
this.showFullName = false,
});
@override
Widget build(BuildContext context) {
if (serverName == null || serverName!.isEmpty) {
return const SizedBox.shrink();
}
final theme = Theme.of(context);
final bgColor =
backgroundColor ??
theme.colorScheme.primaryContainer.withValues(alpha: 0.8);
final fgColor = textColor ?? theme.colorScheme.onPrimaryContainer;
final displayText = showFullName
? serverName!
: serverName!.substring(0, 1).toUpperCase();
final badge = Container(
padding: EdgeInsets.symmetric(
horizontal: showFullName ? 6 : 4,
vertical: 2,
),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(4),
),
child: Text(
displayText,
style: TextStyle(
color: fgColor,
fontSize: showFullName ? 10 : 11,
fontWeight: FontWeight.w600,
height: 1.2,
),
),
);
// If showing full name, no need for tooltip
if (showFullName) {
return badge;
}
// Show tooltip with full server name on hover/long press
return Tooltip(message: serverName!, child: badge);
}
}
+44 -74
View File
@@ -1,8 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../models/plex_sort.dart';
import '../../widgets/bottom_sheet_header.dart';
import '../../utils/keyboard_utils.dart';
import '../../widgets/focusable_bottom_sheet.dart';
import '../../widgets/focusable_list_tile.dart';
import '../../i18n/strings.g.dart';
class SortBottomSheet extends StatefulWidget {
@@ -28,22 +28,19 @@ class SortBottomSheet extends StatefulWidget {
class _SortBottomSheetState extends State<SortBottomSheet> {
late PlexSort? _currentSort;
late bool _currentDescending;
final FocusNode _firstItemFocusNode = FocusNode(debugLabel: 'SortFirstItem');
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_currentSort = widget.selectedSort;
_currentDescending = widget.isSortDescending;
// Focus the first item after build
WidgetsBinding.instance.addPostFrameCallback((_) {
_firstItemFocusNode.requestFocus();
});
_initialFocusNode = FocusNode(debugLabel: 'SortBottomSheetInitialFocus');
}
@override
void dispose() {
_firstItemFocusNode.dispose();
_initialFocusNode.dispose();
super.dispose();
}
@@ -67,28 +64,8 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
@override
Widget build(BuildContext context) {
return Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(context);
return KeyEventResult.handled;
}
// Left/right arrows toggle sort direction when a sort is selected
if (event is KeyDownEvent && _currentSort != null) {
if (event.logicalKey == LogicalKeyboardKey.arrowLeft &&
_currentDescending) {
_handleSortChange(_currentSort!, false);
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowRight &&
!_currentDescending) {
_handleSortChange(_currentSort!, true);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: DraggableScrollableSheet(
initialChildSize: 0.6,
minChildSize: 0.4,
@@ -107,52 +84,45 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
: null,
),
Expanded(
child: FocusTraversalGroup(
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;
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 RadioListTile<PlexSort>(
focusNode: index == 0 ? _firstItemFocusNode : null,
title: Text(sort.title),
value: sort,
groupValue: _currentSort,
onChanged: (value) {
if (value != null) {
_handleSortChange(value, value.isDefaultDescending);
}
},
secondary: isSelected
? ExcludeFocus(
child: 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);
},
return FocusableRadioListTile<PlexSort>(
focusNode: index == 0 ? _initialFocusNode : null,
title: Text(sort.title),
value: sort,
groupValue: _currentSort,
onChanged: (value) {
if (value != null) {
_handleSortChange(value, value.isDefaultDescending);
}
},
secondary: isSelected
? SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: Icon(Icons.arrow_upward, size: 16),
),
)
: null,
);
},
),
ButtonSegment(
value: true,
icon: Icon(Icons.arrow_downward, size: 16),
),
],
selected: {_currentDescending},
onSelectionChanged: (Set<bool> newSelection) {
_handleSortChange(sort, newSelection.first);
},
)
: null,
);
},
),
),
],
@@ -25,11 +25,31 @@ abstract class BaseLibraryTab<T> extends StatefulWidget {
final String? viewMode;
final String? density;
/// Callback invoked when data has finished loading successfully.
/// Used by parent to trigger focus on the first item.
final VoidCallback? onDataLoaded;
/// Whether this tab is currently the active/visible tab.
/// Used for internal focus management.
final bool isActive;
/// Whether to suppress auto-focus when tab becomes active.
/// Used when navigating via tab bar to keep focus on the tab chips.
final bool suppressAutoFocus;
/// Called when the user presses BACK in the tab content.
/// Used to navigate focus back to the tab bar.
final VoidCallback? onBack;
const BaseLibraryTab({
super.key,
required this.library,
this.viewMode,
this.density,
this.onDataLoaded,
this.isActive = false,
this.suppressAutoFocus = false,
this.onBack,
});
}
@@ -55,10 +75,25 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
String? _errorMessage;
StreamSubscription<void>? _refreshSubscription;
// Focus management
bool _hasLoadedData = false;
bool _hasFocused = false;
// Getters for subclasses
List<T> get items => _items;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
bool get hasLoadedData => _hasLoadedData;
// Setters for subclasses that override loadItems with custom logic
@protected
set items(List<T> value) => _items = value;
@protected
set isLoading(bool value) => _isLoading = value;
@protected
set errorMessage(String? value) => _errorMessage = value;
@protected
set hasLoadedData(bool value) => _hasLoadedData = value;
@override
void initState() {
@@ -87,8 +122,22 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.globalKey != widget.library.globalKey) {
// Reset focus state for new library
_hasFocused = false;
_hasLoadedData = false;
// Immediately clear stale data before async load
setState(() {
_items = [];
_isLoading = true;
_errorMessage = null;
});
loadItems();
}
// Check if we should focus (became active after data loaded)
if (widget.isActive && !oldWidget.isActive) {
tryFocus();
}
}
/// Load items from the API
@@ -112,11 +161,36 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
/// Return null if no refresh stream is needed
Stream<void>? getRefreshStream() => null;
/// Try to focus the first item if conditions are met (active + loaded + not yet focused)
@protected
void tryFocus() {
// Don't auto-focus if suppressed (e.g., when navigating via tab bar)
if (widget.suppressAutoFocus) return;
if (widget.isActive &&
_hasLoadedData &&
!_hasFocused &&
_items.isNotEmpty) {
_hasFocused = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
focusFirstItem();
}
});
}
}
/// Focus the first item in the tab. Subclasses should override this.
void focusFirstItem() {
// Default implementation - subclasses should override
}
/// Load items with error handling and state management
Future<void> loadItems() async {
setState(() {
_isLoading = true;
_errorMessage = null;
_items = []; // Clear items to prevent showing stale data during load
});
try {
@@ -128,6 +202,17 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
_items = loadedItems;
_isLoading = false;
});
// Mark data as loaded and try to focus
_hasLoadedData = true;
tryFocus();
// Notify parent that data has loaded
if (widget.onDataLoaded != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
widget.onDataLoaded!();
});
}
} catch (e) {
if (!mounted) return;
@@ -139,19 +224,6 @@ abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
}
}
/// Focus the first item in the tab content
/// Subclasses can override this for custom focus behavior
void focusFirstItem() {
// Default implementation: try to focus the first focusable item
if (_items.isNotEmpty && mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
FocusScope.of(context).nextFocus();
}
});
}
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
+219 -201
View File
@@ -1,17 +1,17 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:dio/dio.dart';
import '../../../../services/plex_client.dart';
import '../../../models/plex_library.dart';
import '../../../models/plex_metadata.dart';
import '../../../models/plex_filter.dart';
import '../../../models/plex_sort.dart';
import '../../../providers/settings_provider.dart';
import '../../../utils/error_message_utils.dart';
import '../../../utils/grid_size_calculator.dart';
import '../../../utils/keyboard_utils.dart';
import '../../../widgets/media_card.dart';
import '../../../widgets/focusable_media_card.dart';
import '../../../widgets/focusable_filter_chip.dart';
import '../../../widgets/media_grid_delegate.dart';
import '../../../mixins/library_tab_focus_mixin.dart';
import '../folder_tree_view.dart';
import '../filters_bottom_sheet.dart';
import '../sort_bottom_sheet.dart';
@@ -21,62 +21,52 @@ import '../../../services/storage_service.dart';
import '../../../services/settings_service.dart' show ViewMode;
import '../../../mixins/item_updatable.dart';
import '../../../mixins/library_tab_state.dart';
import '../../../mixins/refreshable.dart';
import '../../../i18n/strings.g.dart';
import 'base_library_tab.dart';
/// Browse tab for library screen
/// Shows library items with grouping, filtering, and sorting
class LibraryBrowseTab extends StatefulWidget {
final PlexLibrary library;
final String? viewMode;
final String? density;
class LibraryBrowseTab extends BaseLibraryTab<PlexMetadata> {
const LibraryBrowseTab({
super.key,
required this.library,
this.viewMode,
this.density,
required super.library,
super.viewMode,
super.density,
super.onDataLoaded,
super.isActive,
super.suppressAutoFocus,
super.onBack,
});
@override
State<LibraryBrowseTab> createState() => _LibraryBrowseTabState();
}
class _LibraryBrowseTabState extends State<LibraryBrowseTab>
with
AutomaticKeepAliveClientMixin,
ItemUpdatable,
Refreshable,
LibraryTabStateMixin {
@override
bool get wantKeepAlive => true;
@override
PlexLibrary get library => widget.library;
class _LibraryBrowseTabState
extends BaseLibraryTabState<PlexMetadata, LibraryBrowseTab>
with ItemUpdatable, LibraryTabStateMixin, LibraryTabFocusMixin {
@override
PlexClient get client => getClientForLibrary();
@override
void refresh() {
_loadContent();
}
String get focusNodeDebugLabel => 'browse_first_item';
@override
int get itemCount => items.length;
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
setState(() {
final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
final index = items.indexWhere((item) => item.ratingKey == ratingKey);
if (index != -1) {
_items[index] = updatedMetadata;
items[index] = updatedMetadata;
}
});
}
List<PlexMetadata> _items = [];
// Browse-specific state (not in base class)
List<PlexFilter> _filters = [];
List<PlexSort> _sortOptions = [];
bool _isLoading = false;
String? _errorMessage;
Map<String, String> _selectedFilters = {};
PlexSort? _selectedSort;
bool _isSortDescending = false;
@@ -89,37 +79,64 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
int _requestId = 0;
static const int _pageSize = 500;
/// Focus node for the first item in the list/grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'BrowseFirstItem',
// Focus nodes for filter chips
final FocusNode _groupingChipFocusNode = FocusNode(
debugLabel: 'grouping_chip',
);
@override
void initState() {
super.initState();
_loadContent();
}
@override
void didUpdateWidget(LibraryBrowseTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.globalKey != widget.library.globalKey) {
_loadContent();
}
}
final FocusNode _filtersChipFocusNode = FocusNode(debugLabel: 'filters_chip');
final FocusNode _sortChipFocusNode = FocusNode(debugLabel: 'sort_chip');
@override
void dispose() {
_cancelToken?.cancel();
_firstItemFocusNode.dispose();
_groupingChipFocusNode.dispose();
_filtersChipFocusNode.dispose();
_sortChipFocusNode.dispose();
super.dispose();
}
/// Focus the first item in the list/grid
// Override loadData to use our custom _loadContent
@override
Future<List<PlexMetadata>> loadData() async {
// This is called by base class loadItems(), but we override loadItems() entirely
// So this just returns empty - actual loading is done in _loadContent
return [];
}
// Override loadItems to use our custom loading with pagination
@override
Future<void> loadItems() async {
await _loadContent();
}
// Required abstract implementations from base class
@override
IconData get emptyIcon => Icons.folder_open;
@override
String get emptyMessage => t.libraries.thisLibraryIsEmpty;
@override
String get errorContext => t.libraries.content;
// Override buildContent - not used since we override build()
@override
Widget buildContent(List<PlexMetadata> items) => const SizedBox.shrink();
/// Focus the first item in the grid/list (for tab activation)
@override
void focusFirstItem() {
if (_items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
if (items.isNotEmpty) {
// Request immediately, then once more on the next frame to handle cases
// where the grid/list attaches after the initial focus attempt.
void request() {
if (mounted && items.isNotEmpty && !firstItemFocusNode.hasFocus) {
firstItemFocusNode.requestFocus();
}
}
request();
WidgetsBinding.instance.addPostFrameCallback((_) => request());
}
}
@@ -133,11 +150,18 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
final client = getClientForLibrary();
setState(() {
_isLoading = true;
_errorMessage = null;
_items = [];
isLoading = true;
errorMessage = null;
items = [];
_currentPage = 0;
_hasMoreItems = true;
// Clear filter/sort state while loading to prevent showing stale options
_filters = [];
_sortOptions = [];
_selectedFilters = {};
_selectedSort = null;
_isSortDescending = false;
_selectedGrouping = _getDefaultGrouping();
});
try {
@@ -186,7 +210,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
}
Future<void> _loadItems({bool loadMore = false}) async {
if (loadMore && _isLoading) return;
if (loadMore && isLoading) return;
if (!loadMore) {
_currentPage = 0;
@@ -200,9 +224,9 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
_cancelToken = CancelToken();
setState(() {
_isLoading = true;
isLoading = true;
if (!loadMore) {
_items = [];
items = [];
}
});
@@ -229,7 +253,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
}
// Items are automatically tagged with server info by PlexClient
final items = await client.getLibraryContent(
final loadedItems = await client.getLibraryContent(
widget.library.key,
start: _currentPage * _pageSize,
size: _pageSize,
@@ -241,14 +265,27 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
setState(() {
if (loadMore) {
_items.addAll(items);
items.addAll(loadedItems);
} else {
_items = items;
items = loadedItems;
}
_hasMoreItems = items.length >= _pageSize;
_hasMoreItems = loadedItems.length >= _pageSize;
_currentPage++;
_isLoading = false;
isLoading = false;
});
// On initial load (not pagination), mark data as loaded and try to focus
if (!loadMore) {
hasLoadedData = true;
tryFocus();
// Notify parent
if (widget.onDataLoaded != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
widget.onDataLoaded!();
});
}
}
} catch (e) {
_handleLoadError(e, currentRequestId);
}
@@ -258,8 +295,8 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
if (currentRequestId != _requestId) return;
setState(() {
_errorMessage = _getErrorMessage(error);
_isLoading = false;
errorMessage = _getErrorMessage(error);
isLoading = false;
});
}
@@ -328,48 +365,35 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
context: context,
builder: (sheetContext) {
final options = _getGroupingOptions();
return Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(sheetContext);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: FocusTraversalGroup(
child: ListView.builder(
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (context, index) {
final grouping = options[index];
return RadioListTile<String>(
autofocus: index == 0,
title: Text(_getGroupingLabel(grouping)),
value: grouping,
groupValue: _selectedGrouping,
onChanged: (value) async {
if (value != null) {
setState(() {
_selectedGrouping = value;
});
return ListView.builder(
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (context, index) {
final grouping = options[index];
return RadioListTile<String>(
title: Text(_getGroupingLabel(grouping)),
value: grouping,
groupValue: _selectedGrouping,
onChanged: (value) async {
if (value != null) {
setState(() {
_selectedGrouping = value;
});
final storage = await StorageService.getInstance();
await storage.saveLibraryGrouping(
widget.library.globalKey,
value,
);
final storage = await StorageService.getInstance();
await storage.saveLibraryGrouping(
widget.library.globalKey,
value,
);
if (!sheetContext.mounted) return;
if (!sheetContext.mounted) return;
Navigator.pop(sheetContext);
_loadItems();
}
},
);
Navigator.pop(sheetContext);
_loadItems();
}
},
),
),
);
},
);
},
);
@@ -430,59 +454,35 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
);
}
Widget _buildFilterChip({
required IconData icon,
required String label,
required VoidCallback onPressed,
}) {
return Focus(
onKeyEvent: (node, event) {
if (event is KeyDownEvent) {
if (isKeyboardActivationKey(event.logicalKey)) {
onPressed();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
child: Builder(
builder: (context) {
final isFocused = Focus.of(context).hasFocus;
final colorScheme = Theme.of(context).colorScheme;
// When focused: inverse colors (white bg + dark text in dark mode, dark bg + light text in light mode)
final backgroundColor = isFocused
? colorScheme.onSurface
: colorScheme.surfaceContainerHighest;
final foregroundColor = isFocused
? colorScheme.surface
: colorScheme.onSurfaceVariant;
return InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 16, color: foregroundColor),
const SizedBox(width: 6),
Text(
label,
style: Theme.of(
context,
).textTheme.labelMedium?.copyWith(color: foregroundColor),
),
],
),
),
);
},
),
/// Navigate focus from chips down to the first grid item
void _navigateToGrid() {
if (items.isNotEmpty) {
firstItemFocusNode.requestFocus();
}
}
/// Navigate focus from grid up to the grouping chip
void _navigateToChips() {
_groupingChipFocusNode.requestFocus();
}
/// Calculate the number of columns in the current grid based on screen width
int _getGridColumnCount(
BuildContext context,
SettingsProvider settingsProvider,
) {
final screenWidth =
MediaQuery.of(context).size.width - 16; // Subtract padding
final maxCrossAxisExtent = GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
);
return (screenWidth / maxCrossAxisExtent).floor().clamp(1, 100);
}
/// Check if the given index is in the first row of the grid
bool _isFirstRow(int index, int columnCount) {
return index < columnCount;
}
@override
@@ -501,15 +501,20 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
mainAxisSize: MainAxisSize.min,
children: [
// Grouping chip
_buildFilterChip(
FocusableFilterChip(
focusNode: _groupingChipFocusNode,
icon: Icons.category,
label: _getGroupingLabel(_selectedGrouping),
onPressed: _showGroupingBottomSheet,
onNavigateDown: _navigateToGrid,
onNavigateUp: widget.onBack,
onBack: widget.onBack,
),
const SizedBox(width: 8),
// Filters chip
if (_filters.isNotEmpty && _selectedGrouping != 'folders')
_buildFilterChip(
FocusableFilterChip(
focusNode: _filtersChipFocusNode,
icon: Icons.filter_alt,
label: _selectedFilters.isEmpty
? t.libraries.filters
@@ -517,15 +522,22 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
count: _selectedFilters.length,
),
onPressed: _showFiltersBottomSheet,
onNavigateDown: _navigateToGrid,
onNavigateUp: widget.onBack,
onBack: widget.onBack,
),
if (_filters.isNotEmpty && _selectedGrouping != 'folders')
const SizedBox(width: 8),
// Sort chip
if (_sortOptions.isNotEmpty && _selectedGrouping != 'folders')
_buildFilterChip(
FocusableFilterChip(
focusNode: _sortChipFocusNode,
icon: Icons.sort,
label: _selectedSort?.title ?? t.libraries.sort,
onPressed: _showSortBottomSheet,
onNavigateDown: _navigateToGrid,
onNavigateUp: widget.onBack,
onBack: widget.onBack,
),
],
),
@@ -548,20 +560,20 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
);
}
if (_isLoading && _items.isEmpty) {
if (isLoading && items.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (_errorMessage != null && _items.isEmpty) {
if (errorMessage != null && items.isEmpty) {
return ErrorStateWidget(
message: _errorMessage!,
message: errorMessage!,
icon: Icons.error_outline,
onRetry: _loadContent,
retryLabel: t.common.retry,
);
}
if (_items.isEmpty) {
if (items.isEmpty) {
return EmptyStateWidget(
message: t.libraries.thisLibraryIsEmpty,
icon: Icons.folder_open,
@@ -573,61 +585,67 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
if (notification.metrics.pixels >=
notification.metrics.maxScrollExtent - 300 &&
_hasMoreItems &&
!_isLoading) {
!isLoading) {
_loadItems(loadMore: true);
}
return false;
},
child: Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return ClipRect(
child: ListView.builder(
clipBehavior: Clip.none, // Allow focus indicator to overflow
padding: const EdgeInsets.all(8),
itemCount:
_items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) => _buildMediaCardItem(index),
),
);
} else {
return ClipRect(
child: GridView.builder(
clipBehavior: Clip.none, // Allow focus indicator to overflow
padding: const EdgeInsets.all(8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount:
_items.length + (_hasMoreItems && _isLoading ? 1 : 0),
itemBuilder: (context, index) => _buildMediaCardItem(index),
),
);
}
return _buildItemsView(context, settingsProvider);
},
),
);
}
Widget _buildMediaCardItem(int index) {
if (index >= _items.length) {
/// Builds either a list or grid view based on the view mode
Widget _buildItemsView(
BuildContext context,
SettingsProvider settingsProvider,
) {
final itemCount = items.length + (_hasMoreItems && isLoading ? 1 : 0);
if (settingsProvider.viewMode == ViewMode.list) {
// In list view, only the first item can navigate up to chips
return ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: itemCount,
itemBuilder: (context, index) =>
_buildMediaCardItem(index, isFirstRow: index == 0),
);
} else {
// In grid view, calculate columns and pass to item builder
final columnCount = _getGridColumnCount(context, settingsProvider);
return GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: MediaGridDelegate.createDelegate(
context: context,
density: settingsProvider.libraryDensity,
),
itemCount: itemCount,
itemBuilder: (context, index) => _buildMediaCardItem(
index,
isFirstRow: _isFirstRow(index, columnCount),
),
);
}
}
Widget _buildMediaCardItem(int index, {required bool isFirstRow}) {
if (index >= items.length) {
return const Padding(
padding: EdgeInsets.all(16.0),
child: Center(child: CircularProgressIndicator()),
);
}
final item = _items[index];
return MediaCard(
final item = items[index];
return FocusableMediaCard(
key: Key(item.ratingKey),
item: item,
focusNode: index == 0 ? firstItemFocusNode : null,
onRefresh: updateItem,
focusNode: index == 0 ? _firstItemFocusNode : null,
onNavigateUp: isFirstRow ? _navigateToChips : null,
onBack: widget.onBack,
);
}
}
@@ -1,9 +1,10 @@
import 'package:flutter/material.dart';
import '../../../models/plex_metadata.dart';
import '../../../utils/library_refresh_notifier.dart';
import '../../../widgets/focusable_media_card.dart';
import '../../../i18n/strings.g.dart';
import '../adaptive_media_grid.dart';
import 'base_library_tab.dart';
import 'library_grid_tab_state.dart';
/// Collections tab for library screen
/// Shows collections for the current library
@@ -13,6 +14,10 @@ class LibraryCollectionsTab extends BaseLibraryTab<PlexMetadata> {
required super.library,
super.viewMode,
super.density,
super.onDataLoaded,
super.isActive,
super.suppressAutoFocus,
super.onBack,
});
@override
@@ -20,17 +25,9 @@ class LibraryCollectionsTab extends BaseLibraryTab<PlexMetadata> {
}
class _LibraryCollectionsTabState
extends BaseLibraryTabState<PlexMetadata, LibraryCollectionsTab> {
/// Focus node for the first item in the grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'CollectionsFirstItem',
);
extends LibraryGridTabState<PlexMetadata, LibraryCollectionsTab> {
@override
void dispose() {
_firstItemFocusNode.dispose();
super.dispose();
}
String get focusNodeDebugLabel => 'collections_first_item';
@override
IconData get emptyIcon => Icons.collections;
@@ -55,18 +52,14 @@ class _LibraryCollectionsTabState
}
@override
void focusFirstItem() {
if (items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
}
}
@override
Widget buildContent(List<PlexMetadata> items) {
return AdaptiveMediaGrid(
items: items,
onRefresh: loadItems,
firstItemFocusNode: _firstItemFocusNode,
Widget buildGridItem(BuildContext context, PlexMetadata item, int index) {
return FocusableMediaCard(
key: Key(item.ratingKey),
item: item,
focusNode: index == 0 ? firstItemFocusNode : null,
onListRefresh: loadItems,
onBack: widget.onBack,
);
}
}
@@ -0,0 +1,31 @@
import 'package:flutter/material.dart';
import '../adaptive_media_grid.dart';
import '../../../mixins/library_tab_focus_mixin.dart';
import 'base_library_tab.dart';
/// Shared state implementation for simple grid-based library tabs.
///
/// Handles focus, item counting, and grid wiring so individual tabs only
/// implement data loading and per-item rendering.
abstract class LibraryGridTabState<T, W extends BaseLibraryTab<T>>
extends BaseLibraryTabState<T, W>
with LibraryTabFocusMixin {
/// Build a single grid item.
Widget buildGridItem(BuildContext context, T item, int index);
@override
int get itemCount => items.length;
@override
Widget buildContent(List<T> items) {
return AdaptiveMediaGrid<T>(
items: items,
itemBuilder: (context, item, index) =>
buildGridItem(context, item, index),
onRefresh: loadItems,
firstItemFocusNode: firstItemFocusNode,
onBack: widget.onBack,
);
}
}
@@ -1,13 +1,10 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../models/plex_playlist.dart';
import '../../../providers/settings_provider.dart';
import '../../../utils/library_refresh_notifier.dart';
import '../../../services/settings_service.dart' show ViewMode;
import '../../../utils/grid_size_calculator.dart';
import '../../../widgets/media_card.dart';
import '../../../widgets/focusable_media_card.dart';
import '../../../i18n/strings.g.dart';
import 'base_library_tab.dart';
import 'library_grid_tab_state.dart';
/// Playlists tab for library screen
/// Shows playlists that contain items from the current library
@@ -17,6 +14,10 @@ class LibraryPlaylistsTab extends BaseLibraryTab<PlexPlaylist> {
required super.library,
super.viewMode,
super.density,
super.onDataLoaded,
super.isActive,
super.suppressAutoFocus,
super.onBack,
});
@override
@@ -24,17 +25,9 @@ class LibraryPlaylistsTab extends BaseLibraryTab<PlexPlaylist> {
}
class _LibraryPlaylistsTabState
extends BaseLibraryTabState<PlexPlaylist, LibraryPlaylistsTab> {
/// Focus node for the first item in the grid
final FocusNode _firstItemFocusNode = FocusNode(
debugLabel: 'PlaylistsFirstItem',
);
extends LibraryGridTabState<PlexPlaylist, LibraryPlaylistsTab> {
@override
void dispose() {
_firstItemFocusNode.dispose();
super.dispose();
}
String get focusNodeDebugLabel => 'playlists_first_item';
@override
IconData get emptyIcon => Icons.playlist_play;
@@ -61,50 +54,13 @@ class _LibraryPlaylistsTabState
}
@override
void focusFirstItem() {
if (items.isNotEmpty) {
_firstItemFocusNode.requestFocus();
}
}
@override
Widget buildContent(List<PlexPlaylist> items) {
return Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
itemCount: items.length,
itemBuilder: (context, index) =>
_buildPlaylistItem(items[index], index),
);
} else {
return GridView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) =>
_buildPlaylistItem(items[index], index),
);
}
},
);
}
Widget _buildPlaylistItem(PlexPlaylist playlist, int index) {
return MediaCard(
Widget buildGridItem(BuildContext context, PlexPlaylist playlist, int index) {
return FocusableMediaCard(
key: Key(playlist.ratingKey),
item: playlist,
focusNode: index == 0 ? firstItemFocusNode : null,
onListRefresh: loadItems,
focusNode: index == 0 ? _firstItemFocusNode : null,
onBack: widget.onBack,
);
}
}
@@ -5,14 +5,20 @@ import '../../../i18n/strings.g.dart';
import '../../../mixins/item_updatable.dart';
import '../../../models/plex_hub.dart';
import '../../../models/plex_metadata.dart';
import '../../../widgets/hub_navigation_controller.dart';
import '../../../widgets/hub_section.dart';
import 'base_library_tab.dart';
/// Recommended tab for library screen
/// Shows library-specific hubs and recommendations, including dedicated Continue Watching
class LibraryRecommendedTab extends BaseLibraryTab<PlexHub> {
const LibraryRecommendedTab({super.key, required super.library});
const LibraryRecommendedTab({
super.key,
required super.library,
super.onDataLoaded,
super.isActive,
super.suppressAutoFocus,
super.onBack,
});
@override
State<LibraryRecommendedTab> createState() => _LibraryRecommendedTabState();
@@ -21,20 +27,8 @@ class LibraryRecommendedTab extends BaseLibraryTab<PlexHub> {
class _LibraryRecommendedTabState
extends BaseLibraryTabState<PlexHub, LibraryRecommendedTab>
with ItemUpdatable {
final HubNavigationController _hubNavigationController =
HubNavigationController();
@override
void dispose() {
_hubNavigationController.dispose();
super.dispose();
}
/// Focus the first item in the first hub
@override
void focusFirstItem() {
_hubNavigationController.focusHub(0, 0);
}
/// GlobalKeys for each hub section to enable vertical navigation
final List<GlobalKey<HubSectionState>> _hubKeys = [];
@override
PlexClient get client => getClientForLibrary();
@@ -63,6 +57,9 @@ class _LibraryRecommendedTabState
@override
Future<List<PlexHub>> loadData() async {
// Clear hub keys before loading new hubs to prevent stale references
_hubKeys.clear();
// Use server-specific client for this library
final client = getClientForLibrary();
@@ -109,30 +106,67 @@ class _LibraryRecommendedTabState
return finalHubs;
}
/// Ensure we have enough GlobalKeys for all hubs
void _ensureHubKeys(int count) {
while (_hubKeys.length < count) {
_hubKeys.add(GlobalKey<HubSectionState>());
}
}
/// Handle vertical navigation between hubs
bool _handleVerticalNavigation(int hubIndex, bool isUp) {
final targetIndex = isUp ? hubIndex - 1 : hubIndex + 1;
// Check if target is valid
if (targetIndex < 0 || targetIndex >= _hubKeys.length) {
// At boundary, block navigation
return true;
}
// Navigate to target hub with column memory
final targetState = _hubKeys[targetIndex].currentState;
if (targetState != null) {
targetState.requestFocusFromMemory();
return true;
}
return false;
}
/// Focus the first item in the first hub (for tab activation)
@override
void focusFirstItem() {
if (_hubKeys.isNotEmpty && items.isNotEmpty) {
_hubKeys[0].currentState?.requestFocusAt(0);
}
}
@override
Widget buildContent(List<PlexHub> items) {
return HubNavigationScope(
controller: _hubNavigationController,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: items.length,
itemBuilder: (context, index) {
final hub = items[index];
final isContinueWatching =
hub.hubIdentifier == '_library_continue_watching_';
_ensureHubKeys(items.length);
return HubSection(
hub: hub,
icon: _getHubIcon(hub),
navigationOrder: index,
isInContinueWatching: isContinueWatching,
onRefresh: updateItem,
onRemoveFromContinueWatching: isContinueWatching
? _refreshContinueWatching
: null,
);
},
),
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: items.length,
itemBuilder: (context, index) {
final hub = items[index];
final isContinueWatching =
hub.hubIdentifier == '_library_continue_watching_';
return HubSection(
key: index < _hubKeys.length ? _hubKeys[index] : null,
hub: hub,
icon: _getHubIcon(hub),
isInContinueWatching: isContinueWatching,
onRefresh: updateItem,
onRemoveFromContinueWatching: isContinueWatching
? _refreshContinueWatching
: null,
onVerticalNavigation: (isUp) =>
_handleVerticalNavigation(index, isUp),
onBack: widget.onBack,
);
},
);
}
+170 -117
View File
@@ -4,8 +4,8 @@ import 'package:provider/provider.dart';
import '../../services/plex_client.dart';
import '../i18n/strings.g.dart';
import '../utils/app_logger.dart';
import '../utils/keyboard_utils.dart';
import '../utils/provider_extensions.dart';
import '../utils/platform_detector.dart';
import '../main.dart';
import '../mixins/refreshable.dart';
import '../providers/multi_server_provider.dart';
@@ -14,32 +14,34 @@ import '../providers/hidden_libraries_provider.dart';
import '../providers/playback_state_provider.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../utils/desktop_window_padding.dart';
import '../widgets/side_navigation_rail.dart';
import 'discover_screen.dart';
import 'libraries/libraries_screen.dart';
import 'search_screen.dart';
import 'settings/settings_screen.dart';
/// InheritedWidget that provides back navigation functionality to child screens
class BackNavigationScope extends InheritedWidget {
final VoidCallback focusBottomNav;
/// Provides access to the main screen's focus control.
class MainScreenFocusScope extends InheritedWidget {
final VoidCallback focusSidebar;
final VoidCallback focusContent;
final bool isSidebarFocused;
const BackNavigationScope({
const MainScreenFocusScope({
super.key,
required this.focusBottomNav,
required this.focusSidebar,
required this.focusContent,
required this.isSidebarFocused,
required super.child,
});
static BackNavigationScope? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<BackNavigationScope>();
}
static BackNavigationScope? maybeOf(BuildContext context) {
return context.getInheritedWidgetOfExactType<BackNavigationScope>();
static MainScreenFocusScope? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MainScreenFocusScope>();
}
@override
bool updateShouldNotify(BackNavigationScope oldWidget) {
return focusBottomNav != oldWidget.focusBottomNav;
bool updateShouldNotify(MainScreenFocusScope oldWidget) {
return isSidebarFocused != oldWidget.isSidebarFocused;
}
}
@@ -54,32 +56,37 @@ class MainScreen extends StatefulWidget {
class _MainScreenState extends State<MainScreen> with RouteAware {
int _currentIndex = 0;
String? _selectedLibraryGlobalKey;
late final List<Widget> _screens;
final GlobalKey<State<DiscoverScreen>> _discoverKey = GlobalKey();
final GlobalKey<State<LibrariesScreen>> _librariesKey = GlobalKey();
final GlobalKey<State<SearchScreen>> _searchKey = GlobalKey();
final GlobalKey<State<SettingsScreen>> _settingsKey = GlobalKey();
final GlobalKey<SideNavigationRailState> _sideNavKey = GlobalKey();
/// Focus scope node for the bottom navigation bar
/// Using FocusScopeNode so requestFocus() focuses the first child
late final FocusScopeNode _bottomNavFocusScopeNode;
/// Focus scope node for the main content area
late final FocusScopeNode _contentFocusScopeNode;
// Focus management for sidebar/content switching
final FocusScopeNode _sidebarFocusScope = FocusScopeNode(
debugLabel: 'Sidebar',
);
final FocusScopeNode _contentFocusScope = FocusScopeNode(
debugLabel: 'Content',
);
bool _isSidebarFocused = false;
@override
void initState() {
super.initState();
_bottomNavFocusScopeNode = FocusScopeNode(debugLabel: 'BottomNavigation');
_contentFocusScopeNode = FocusScopeNode(debugLabel: 'MainContent');
_screens = [
DiscoverScreen(
key: _discoverKey,
onBecameVisible: _onDiscoverBecameVisible,
),
LibrariesScreen(key: _librariesKey),
LibrariesScreen(
key: _librariesKey,
onLibraryOrderChanged: _onLibraryOrderChanged,
),
SearchScreen(key: _searchKey),
SettingsScreen(key: _settingsKey),
];
@@ -92,6 +99,11 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
// Set up data invalidation callback for profile switching
userProfileProvider.setDataInvalidationCallback(_invalidateAllScreens);
// Focus content initially (replaces autofocus which caused focus stealing issues)
if (!_isSidebarFocused) {
_contentFocusScope.requestFocus();
}
});
}
@@ -104,36 +116,54 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
@override
void dispose() {
routeObserver.unsubscribe(this);
_bottomNavFocusScopeNode.dispose();
_contentFocusScopeNode.dispose();
_sidebarFocusScope.dispose();
_contentFocusScope.dispose();
super.dispose();
}
/// Focus the bottom navigation bar (called by child screens on back press)
void _focusBottomNav() {
// Request focus on the scope, then navigate to the currently selected tab
_bottomNavFocusScopeNode.requestFocus();
void _focusSidebar() {
setState(() => _isSidebarFocused = true);
_sidebarFocusScope.requestFocus();
// Focus the active item after the focus scope has focus
WidgetsBinding.instance.addPostFrameCallback((_) {
// Move to first item, then advance to current index
_bottomNavFocusScopeNode.nextFocus();
for (int i = 0; i < _currentIndex; i++) {
_bottomNavFocusScopeNode.nextFocus();
}
_sideNavKey.currentState?.focusActiveItem();
});
}
/// Focus the content area (called when back is pressed in navbar)
void _focusContent() {
_contentFocusScopeNode.requestFocus();
setState(() => _isSidebarFocused = false);
_contentFocusScope.requestFocus();
// When content regains focus while on Libraries, retry focusing the active tab
if (_currentIndex == 1) {
WidgetsBinding.instance.addPostFrameCallback((_) {
final librariesState = _librariesKey.currentState;
if (librariesState != null) {
(librariesState as dynamic).focusActiveTabIfReady();
}
});
}
}
/// Handle back key in navbar - focus content area
KeyEventResult _handleNavBarBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
KeyEventResult _handleBackKey(KeyEvent event) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
// Handle all back keys - this handler is only reached if lower widgets
// (e.g., LibrariesScreen tab content/chips) don't handle the back key first
final isBackKey =
event.logicalKey == LogicalKeyboardKey.escape ||
event.logicalKey == LogicalKeyboardKey.goBack ||
event.logicalKey == LogicalKeyboardKey.browserBack ||
event.logicalKey == LogicalKeyboardKey.gameButtonB;
if (!isBackKey) return KeyEventResult.ignored;
// Toggle focus between sidebar and content
if (_isSidebarFocused) {
_focusContent();
return KeyEventResult.handled;
} else {
_focusSidebar();
}
return KeyEventResult.ignored;
return KeyEventResult.handled;
}
@override
@@ -161,6 +191,11 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
}
}
void _onLibraryOrderChanged() {
// Refresh side navigation when library order changes
_sideNavKey.currentState?.reloadLibraries();
}
/// Invalidate all cached data across all screens when profile is switched
/// Receives the list of servers with new profile tokens for reconnection
Future<void> _invalidateAllScreens(List<PlexServer> servers) async {
@@ -215,110 +250,128 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
}
void _selectTab(int index) {
// Check if selection came from keyboard/d-pad (bottom nav has focus)
final isKeyboardNavigation = _bottomNavFocusScopeNode.hasFocus;
final previousIndex = _currentIndex;
setState(() {
_currentIndex = index;
});
// Notify discover screen when it becomes visible via tab switch
if (index == 0) {
_onDiscoverBecameVisible();
// Focus hero when selecting Home tab via keyboard/d-pad
if (isKeyboardNavigation) {
final discoverState = _discoverKey.currentState;
if (discoverState != null) {
(discoverState as dynamic).focusHero();
}
}
}
// Focus first content item when selecting Libraries tab via keyboard/d-pad
if (index == 1 && isKeyboardNavigation) {
// Ensure the libraries screen applies focus when brought into view
if (index == 1 && previousIndex != 1) {
final librariesState = _librariesKey.currentState;
if (librariesState != null) {
(librariesState as dynamic).focusFirstContentItem();
(librariesState as dynamic).focusActiveTabIfReady();
}
}
// Focus search input when selecting Search tab (for both click/tap and keyboard)
// Focus search input when selecting Search tab
if (index == 2) {
final searchState = _searchKey.currentState;
if (searchState != null) {
(searchState as dynamic).focusSearchInput();
}
}
// Move focus to the content area when selecting a tab via keyboard
if (isKeyboardNavigation) {
_contentFocusScopeNode.requestFocus();
}
/// Handle library selection from side navigation rail
void _selectLibrary(String libraryGlobalKey) {
setState(() {
_selectedLibraryGlobalKey = libraryGlobalKey;
_currentIndex = 1; // Switch to Libraries tab
});
// Tell LibrariesScreen to load this library
final librariesState = _librariesKey.currentState;
if (librariesState != null) {
(librariesState as dynamic).loadLibraryByKey(libraryGlobalKey);
(librariesState as dynamic).focusActiveTabIfReady();
}
}
@override
Widget build(BuildContext context) {
return Shortcuts(
shortcuts: {
// Number keys 1-4 for quick tab switching
const SingleActivator(LogicalKeyboardKey.digit1): _TabIntent(0),
const SingleActivator(LogicalKeyboardKey.digit2): _TabIntent(1),
const SingleActivator(LogicalKeyboardKey.digit3): _TabIntent(2),
const SingleActivator(LogicalKeyboardKey.digit4): _TabIntent(3),
},
child: Actions(
actions: {
_TabIntent: CallbackAction<_TabIntent>(
onInvoke: (intent) {
_selectTab(intent.tabIndex);
return null;
},
),
final useSideNav = PlatformDetector.shouldUseSideNavigation(context);
if (useSideNav) {
return PopScope(
canPop: false, // Prevent system back from popping on Android TV
onPopInvokedWithResult: (didPop, result) {
// No-op: back key events bubble through widget tree and are handled
// by content screens (e.g., LibrariesScreen) or MainScreen's _handleBackKey.
// We only use PopScope to prevent the system from popping the route.
},
child: Scaffold(
body: BackNavigationScope(
focusBottomNav: _focusBottomNav,
child: FocusScope(
node: _contentFocusScopeNode,
child: FocusTraversalGroup(
child: IndexedStack(index: _currentIndex, children: _screens),
child: Focus(
onKeyEvent: (node, event) => _handleBackKey(event),
child: MainScreenFocusScope(
focusSidebar: _focusSidebar,
focusContent: _focusContent,
isSidebarFocused: _isSidebarFocused,
child: SideNavigationScope(
child: Row(
children: [
FocusScope(
node: _sidebarFocusScope,
child: SideNavigationRail(
key: _sideNavKey,
selectedIndex: _currentIndex,
selectedLibraryKey: _selectedLibraryGlobalKey,
onDestinationSelected: (index) {
_selectTab(index);
_focusContent();
},
onLibrarySelected: (key) {
_selectLibrary(key);
_focusContent();
},
),
),
Expanded(
child: FocusScope(
node: _contentFocusScope,
// No autofocus - we control focus programmatically to prevent
// autofocus from stealing focus back after setState() rebuilds
child: IndexedStack(
index: _currentIndex,
children: _screens,
),
),
),
],
),
),
),
bottomNavigationBar: FocusScope(
node: _bottomNavFocusScopeNode,
onKeyEvent: _handleNavBarBackKey,
child: NavigationBar(
selectedIndex: _currentIndex,
onDestinationSelected: _selectTab,
destinations: [
NavigationDestination(
icon: const Icon(Icons.home_outlined),
selectedIcon: const Icon(Icons.home),
label: t.navigation.home,
),
NavigationDestination(
icon: const Icon(Icons.video_library_outlined),
selectedIcon: const Icon(Icons.video_library),
label: t.navigation.libraries,
),
NavigationDestination(
icon: const Icon(Icons.search),
selectedIcon: const Icon(Icons.search),
label: t.navigation.search,
),
NavigationDestination(
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
label: t.navigation.settings,
),
],
),
),
),
);
}
return Scaffold(
body: IndexedStack(index: _currentIndex, children: _screens),
bottomNavigationBar: NavigationBar(
selectedIndex: _currentIndex,
onDestinationSelected: _selectTab,
destinations: [
NavigationDestination(
icon: const Icon(Icons.home_outlined),
selectedIcon: const Icon(Icons.home),
label: t.navigation.home,
),
NavigationDestination(
icon: const Icon(Icons.video_library_outlined),
selectedIcon: const Icon(Icons.video_library),
label: t.navigation.libraries,
),
NavigationDestination(
icon: const Icon(Icons.search),
selectedIcon: const Icon(Icons.search),
label: t.navigation.search,
),
NavigationDestination(
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
label: t.navigation.settings,
),
],
),
);
}
}
/// Intent for switching tabs via keyboard shortcuts
class _TabIntent extends Intent {
final int tabIndex;
const _TabIntent(this.tabIndex);
}
+158 -251
View File
@@ -2,11 +2,11 @@ import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../focus/key_event_utils.dart';
import '../focus/input_mode_tracker.dart';
import '../i18n/strings.g.dart';
import '../widgets/plex_optimized_image.dart';
import '../utils/plex_image_helper.dart';
import '../mixins/keyboard_long_press_mixin.dart';
import '../widgets/focus/focus_indicator.dart';
import '../../services/plex_client.dart';
import '../models/plex_metadata.dart';
import '../providers/playback_state_provider.dart';
@@ -14,7 +14,6 @@ import '../theme/theme_helper.dart';
import '../utils/app_logger.dart';
import '../utils/content_rating_formatter.dart';
import '../utils/duration_formatter.dart';
import '../utils/keyboard_utils.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../widgets/app_bar_back_button.dart';
@@ -40,7 +39,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
bool _isLoadingMetadata = true;
late final ScrollController _scrollController;
bool _watchStateChanged = false;
final FocusNode _playButtonFocusNode = FocusNode(debugLabel: 'PlayButton');
@override
void initState() {
@@ -52,7 +50,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
@override
void dispose() {
_scrollController.dispose();
_playButtonFocusNode.dispose();
super.dispose();
}
@@ -94,11 +91,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
_isLoadingMetadata = false;
});
// Focus the play button after loading
WidgetsBinding.instance.addPostFrameCallback((_) {
_playButtonFocusNode.requestFocus();
});
// Load seasons if it's a show
if (metadata.type.toLowerCase() == 'show') {
_loadSeasons();
@@ -112,11 +104,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
_isLoadingMetadata = false;
});
// Focus the play button after loading
WidgetsBinding.instance.addPostFrameCallback((_) {
_playButtonFocusNode.requestFocus();
});
if (widget.metadata.type.toLowerCase() == 'show') {
_loadSeasons();
}
@@ -127,11 +114,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
_isLoadingMetadata = false;
});
// Focus the play button after loading
WidgetsBinding.instance.addPostFrameCallback((_) {
_playButtonFocusNode.requestFocus();
});
if (widget.metadata.type.toLowerCase() == 'show') {
_loadSeasons();
}
@@ -378,11 +360,17 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
final metadata = _fullMetadata ?? widget.metadata;
final isShow = metadata.type.toLowerCase() == 'show';
KeyEventResult handleBack(FocusNode _, KeyEvent event) =>
handleBackKeyNavigation(context, event, result: _watchStateChanged);
// Show loading state while fetching full metadata
if (_isLoadingMetadata) {
return Scaffold(
appBar: AppBar(),
body: const Center(child: CircularProgressIndicator()),
return Focus(
onKeyEvent: handleBack,
child: Scaffold(
appBar: AppBar(),
body: const Center(child: CircularProgressIndicator()),
),
);
}
@@ -391,17 +379,10 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
final isDesktop = size.width > 600;
final headerHeight = isDesktop ? size.height * 0.6 : size.height * 0.4;
return Scaffold(
body: Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(context, _watchStateChanged);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: CustomScrollView(
return Focus(
onKeyEvent: handleBack,
child: Scaffold(
body: CustomScrollView(
controller: _scrollController,
slivers: [
// Hero header with background art
@@ -753,7 +734,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
child: SizedBox(
height: 48,
child: FilledButton.icon(
focusNode: _playButtonFocusNode,
autofocus: InputModeTracker.isKeyboardMode(
context,
),
onPressed: () async {
// For TV shows, play the OnDeck episode if available
// Otherwise, play the first episode of the first season
@@ -951,43 +934,38 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
),
)
else
FocusTraversalGroup(
child: ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: EdgeInsets.zero,
itemCount: _seasons.length,
separatorBuilder: (context, index) =>
const SizedBox(height: 12),
itemBuilder: (context, index) {
final season = _seasons[index];
return _FocusableSeasonCard(
season: season,
client: _getClientForMetadata(context),
onTap: ({bool isKeyboard = false}) async {
final watchStateChanged =
await Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) =>
SeasonDetailScreen(
season: season,
focusFirstEpisode: isKeyboard,
),
),
);
if (watchStateChanged == true) {
_watchStateChanged = true;
_updateWatchState();
}
},
onRefresh: () {
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: EdgeInsets.zero,
itemCount: _seasons.length,
separatorBuilder: (context, index) =>
const SizedBox(height: 12),
itemBuilder: (context, index) {
final season = _seasons[index];
return _SeasonCard(
season: season,
client: _getClientForMetadata(context),
onTap: () async {
final watchStateChanged =
await Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) =>
SeasonDetailScreen(season: season),
),
);
if (watchStateChanged == true) {
_watchStateChanged = true;
_updateWatchState();
},
);
},
),
}
},
onRefresh: () {
_watchStateChanged = true;
_updateWatchState();
},
);
},
),
const SizedBox(height: 24),
],
@@ -1189,209 +1167,138 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
}
}
/// Focusable season card widget
class _FocusableSeasonCard extends StatefulWidget {
/// Season card widget
class _SeasonCard extends StatelessWidget {
final PlexMetadata season;
final PlexClient client;
final void Function({bool isKeyboard}) onTap;
final VoidCallback onTap;
final VoidCallback onRefresh;
const _FocusableSeasonCard({
const _SeasonCard({
required this.season,
required this.client,
required this.onTap,
required this.onRefresh,
});
@override
State<_FocusableSeasonCard> createState() => _FocusableSeasonCardState();
}
class _FocusableSeasonCardState extends State<_FocusableSeasonCard>
with KeyboardLongPressMixin {
late final FocusNode _focusNode;
bool _isFocused = false;
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
@override
void onKeyboardTap() => widget.onTap(isKeyboard: true);
@override
void onKeyboardLongPress() {
_contextMenuKey.currentState?.showContextMenu(context);
}
@override
void initState() {
super.initState();
_focusNode = FocusNode();
_focusNode.addListener(_handleFocusChange);
}
@override
void dispose() {
_focusNode.removeListener(_handleFocusChange);
_focusNode.dispose();
super.dispose();
}
void _handleFocusChange() {
if (_isFocused != _focusNode.hasFocus) {
setState(() {
_isFocused = _focusNode.hasFocus;
});
if (_focusNode.hasFocus) {
Scrollable.ensureVisible(
context,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
}
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
// Handle long-press detection for activation keys
return handleKeyboardLongPress(event);
}
@override
Widget build(BuildContext context) {
final season = widget.season;
return Focus(
focusNode: _focusNode,
onKeyEvent: _handleKeyEvent,
child: FocusIndicator(
isFocused: _isFocused,
borderRadius: 12,
child: Card(
clipBehavior: Clip.antiAlias,
child: MediaContextMenu(
key: _contextMenuKey,
item: season,
onRefresh: (ratingKey) => widget.onRefresh(),
onTap: () => widget.onTap(isKeyboard: false),
child: Semantics(
label: "media-season-${season.ratingKey}",
identifier: "media-season-${season.ratingKey}",
button: true,
hint: "Tap to view ${season.title}",
child: InkWell(
onTap: () => widget.onTap(isKeyboard: false),
focusColor: Colors.transparent,
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
// Season poster
if (season.thumb != null)
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: PlexPosterImage(
client: widget.client,
imagePath: season.thumb,
width: 80,
height: 120,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
),
)
else
Container(
return Card(
clipBehavior: Clip.antiAlias,
child: MediaContextMenu(
item: season,
onRefresh: (ratingKey) => onRefresh(),
onTap: onTap,
child: Semantics(
label: "media-season-${season.ratingKey}",
identifier: "media-season-${season.ratingKey}",
button: true,
hint: "Tap to view ${season.title}",
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
// Season poster
if (season.thumb != null)
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: PlexOptimizedImage.poster(
client: client,
imagePath: season.thumb,
width: 80,
height: 120,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
width: 80,
height: 120,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
const SizedBox(width: 16),
),
)
else
Container(
width: 80,
height: 120,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
child: const Icon(Icons.movie, size: 32),
),
const SizedBox(width: 16),
// Season info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
season.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
// Season info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
season.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
if (season.leafCount != null)
Text(
t.discover.episodeCount(
count: season.leafCount.toString(),
),
const SizedBox(height: 4),
if (season.leafCount != null)
Text(
t.discover.episodeCount(
count: season.leafCount.toString(),
style: Theme.of(context).textTheme.bodyMedium
?.copyWith(color: Colors.grey),
),
const SizedBox(height: 8),
if (season.viewedLeafCount != null &&
season.leafCount != null)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value:
season.viewedLeafCount! /
season.leafCount!,
backgroundColor: tokens(context).outline,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
),
minHeight: 6,
),
),
style: Theme.of(context).textTheme.bodyMedium
),
const SizedBox(height: 4),
Text(
t.discover.watchedProgress(
watched: season.viewedLeafCount.toString(),
total: season.leafCount.toString(),
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(color: Colors.grey),
),
const SizedBox(height: 8),
if (season.viewedLeafCount != null &&
season.leafCount != null)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value:
season.viewedLeafCount! /
season.leafCount!,
backgroundColor: tokens(
context,
).outline,
valueColor:
AlwaysStoppedAnimation<Color>(
Theme.of(
context,
).colorScheme.primary,
),
minHeight: 6,
),
),
),
const SizedBox(height: 4),
Text(
t.discover.watchedProgress(
watched: season.viewedLeafCount
.toString(),
total: season.leafCount.toString(),
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(color: Colors.grey),
),
],
),
],
),
),
const Icon(Icons.chevron_right),
],
],
),
],
),
),
),
const Icon(Icons.chevron_right),
],
),
),
),
+62 -135
View File
@@ -1,17 +1,13 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../services/plex_client.dart';
import '../../services/play_queue_launcher.dart';
import '../../models/plex_playlist.dart';
import '../../models/plex_metadata.dart';
import '../../providers/settings_provider.dart';
import '../../providers/playback_state_provider.dart';
import '../../utils/app_logger.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/video_player_navigation.dart';
import '../../utils/grid_size_calculator.dart';
import '../../widgets/media_card.dart';
import '../../widgets/media_grid_sliver.dart';
import 'playlist_item_card.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../widgets/focused_scroll_scaffold.dart';
import '../../i18n/strings.g.dart';
import '../../utils/dialogs.dart';
import '../base_media_list_detail_screen.dart';
@@ -207,147 +203,78 @@ class _PlaylistDetailScreenState
Future<void> _playFromItem(int index) async {
if (items.isEmpty || index < 0 || index >= items.length) return;
try {
final client = _getClientForPlaylist();
final plexClient = _getClientForPlaylist();
final selectedItem = items[index];
final selectedItem = items[index];
final launcher = PlayQueueLauncher(
context: context,
client: plexClient,
serverId: widget.playlist.serverId,
serverName: widget.playlist.serverName,
);
// Create play queue from playlist, starting at the selected item
final playQueue = await client.createPlayQueue(
playlistID: int.parse(widget.playlist.ratingKey),
type: 'video',
key: selectedItem.key,
);
if (playQueue == null ||
playQueue.items == null ||
playQueue.items!.isEmpty) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.messages.failedToCreatePlayQueue)),
);
}
return;
}
if (!mounted) return;
// Set play queue in provider
final playbackState = context.read<PlaybackStateProvider>();
playbackState.setClient(client);
await playbackState.setPlaybackFromPlayQueue(
playQueue,
widget.playlist.ratingKey,
);
// Navigate to selected item
if (mounted) {
await navigateToVideoPlayer(
context,
metadata: playQueue.selectedItem ?? playQueue.items!.first,
);
}
} catch (e) {
appLogger.e('Failed to play from item', error: e);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
t.messages.failedPlayback(
action: t.discover.play,
error: e.toString(),
),
),
),
);
}
}
await launcher.launchFromPlaylistItem(
playlist: widget.playlist,
selectedItem: selectedItem,
showLoadingIndicator: true,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
return FocusedScrollScaffold(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.playlist.title, style: const TextStyle(fontSize: 16)),
if (widget.playlist.smart)
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.auto_awesome, size: 12, color: Colors.blue[300]),
const SizedBox(width: 4),
Text(
widget.playlist.title,
style: const TextStyle(fontSize: 16),
),
if (widget.playlist.smart)
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.auto_awesome,
size: 12,
color: Colors.blue[300],
),
const SizedBox(width: 4),
Text(
t.playlists.smartPlaylist,
style: TextStyle(
fontSize: 11,
color: Colors.blue[300],
fontWeight: FontWeight.normal,
),
),
],
t.playlists.smartPlaylist,
style: TextStyle(
fontSize: 11,
color: Colors.blue[300],
fontWeight: FontWeight.normal,
),
),
],
),
pinned: true,
actions: buildAppBarActions(
onDelete: widget.playlist.smart ? null : _deletePlaylist,
deleteTooltip: t.playlists.delete,
showDelete: !widget.playlist.smart,
),
),
...buildStateSlivers(),
if (items.isNotEmpty)
if (widget.playlist.smart)
// Smart playlists: Use grid view (cannot be reordered)
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
GridSizeCalculator.getMaxCrossAxisExtent(
context,
context.watch<SettingsProvider>().libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
delegate: SliverChildBuilderDelegate((context, index) {
return MediaCard(item: items[index], onRefresh: updateItem);
}, childCount: items.length),
),
)
else
// Regular playlists: Use reorderable list view
SliverReorderableList(
itemBuilder: (context, index) {
final item = items[index];
return PlaylistItemCard(
key: ValueKey(item.playlistItemID ?? item.ratingKey),
item: item,
index: index,
onRemove: () => _removeItem(index),
onTap: () => _playFromItem(index),
onRefresh: updateItem,
canReorder: !widget.playlist.smart,
);
},
itemCount: items.length,
onReorder: _onReorder,
),
],
),
actions: buildAppBarActions(
onDelete: widget.playlist.smart ? null : _deletePlaylist,
deleteTooltip: t.playlists.delete,
showDelete: !widget.playlist.smart,
),
slivers: [
...buildStateSlivers(),
if (items.isNotEmpty)
if (widget.playlist.smart)
// Smart playlists: Use grid view (cannot be reordered)
MediaGridSliver(items: items, onRefresh: updateItem)
else
// Regular playlists: Use reorderable list view
SliverReorderableList(
itemBuilder: (context, index) {
final item = items[index];
return PlaylistItemCard(
key: ValueKey(item.playlistItemID ?? item.ratingKey),
item: item,
index: index,
onRemove: () => _removeItem(index),
onTap: () => _playFromItem(index),
onRefresh: updateItem,
canReorder: !widget.playlist.smart,
);
},
itemCount: items.length,
onReorder: _onReorder,
),
],
);
}
}
+80 -102
View File
@@ -1,11 +1,9 @@
import 'package:flutter/material.dart';
import '../../services/plex_client.dart';
import '../../mixins/keyboard_long_press_mixin.dart';
import '../../models/plex_metadata.dart';
import '../../utils/duration_formatter.dart';
import '../../utils/provider_extensions.dart';
import '../../i18n/strings.g.dart';
import '../../widgets/focus/focus_indicator.dart';
import '../../widgets/media_context_menu.dart';
import '../../widgets/plex_optimized_image.dart';
@@ -33,18 +31,9 @@ class PlaylistItemCard extends StatefulWidget {
State<PlaylistItemCard> createState() => _PlaylistItemCardState();
}
class _PlaylistItemCardState extends State<PlaylistItemCard>
with KeyboardLongPressMixin {
class _PlaylistItemCardState extends State<PlaylistItemCard> {
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
@override
void onKeyboardTap() => widget.onTap?.call();
@override
void onKeyboardLongPress() {
_contextMenuKey.currentState?.showContextMenu(context);
}
@override
Widget build(BuildContext context) {
final item = widget.item;
@@ -53,103 +42,92 @@ class _PlaylistItemCardState extends State<PlaylistItemCard>
item: item,
onRefresh: widget.onRefresh,
onTap: widget.onTap,
child: FocusableWrapper(
onKeyEvent: (node, event) => handleKeyboardLongPress(event),
builder: (context, isFocused) => FocusIndicator(
isFocused: isFocused,
borderRadius: 12,
child: Card(
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: InkWell(
onTap: widget.onTap,
focusColor: Colors.transparent,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
// Drag handle (if reorderable)
if (widget.canReorder)
ReorderableDragStartListener(
index: widget.index,
child: const Padding(
padding: EdgeInsets.only(right: 12),
child: Icon(Icons.drag_indicator, color: Colors.grey),
),
),
// Poster thumbnail
_buildPosterImage(context),
const SizedBox(width: 12),
// Title and metadata
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Title
Text(
item.displayTitle,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
// Subtitle (episode info or type)
Text(
_buildSubtitle(),
style: TextStyle(
fontSize: 13,
color: Colors.grey[400],
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
// Progress indicator if partially watched
if (item.viewOffset != null && item.duration != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: LinearProgressIndicator(
value: item.viewOffset! / item.duration!,
backgroundColor: Colors.grey[800],
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
),
minHeight: 3,
),
),
],
),
child: Card(
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: InkWell(
onTap: widget.onTap,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
// Drag handle (if reorderable)
if (widget.canReorder)
ReorderableDragStartListener(
index: widget.index,
child: const Padding(
padding: EdgeInsets.only(right: 12),
child: Icon(Icons.drag_indicator, color: Colors.grey),
),
),
const SizedBox(width: 12),
// Poster thumbnail
_buildPosterImage(context),
// Duration
if (item.duration != null)
const SizedBox(width: 12),
// Title and metadata
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Title
Text(
formatDurationTextual(item.duration!),
style: TextStyle(fontSize: 13, color: Colors.grey[400]),
item.displayTitle,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(width: 8),
const SizedBox(height: 4),
// Remove button
IconButton(
icon: const Icon(Icons.close, size: 20),
onPressed: widget.onRemove,
tooltip: t.playlists.removeItem,
color: Colors.grey[400],
),
],
// Subtitle (episode info or type)
Text(
_buildSubtitle(),
style: TextStyle(fontSize: 13, color: Colors.grey[400]),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
// Progress indicator if partially watched
if (item.viewOffset != null && item.duration != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: LinearProgressIndicator(
value: item.viewOffset! / item.duration!,
backgroundColor: Colors.grey[800],
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
),
minHeight: 3,
),
),
],
),
),
),
const SizedBox(width: 12),
// Duration
if (item.duration != null)
Text(
formatDurationTextual(item.duration!),
style: TextStyle(fontSize: 13, color: Colors.grey[400]),
),
const SizedBox(width: 8),
// Remove button
IconButton(
icon: const Icon(Icons.close, size: 20),
onPressed: widget.onRemove,
tooltip: t.playlists.removeItem,
color: Colors.grey[400],
),
],
),
),
),
@@ -166,7 +144,7 @@ class _PlaylistItemCardState extends State<PlaylistItemCard>
final posterUrl = widget.item.posterThumb();
return ClipRRect(
borderRadius: BorderRadius.circular(6),
child: PlexPosterImage(
child: PlexOptimizedImage.poster(
client: _getClientForItem(context),
imagePath: posterUrl,
width: 60,
+109 -106
View File
@@ -35,64 +35,106 @@ class UserAvatarWidget extends StatelessWidget {
);
}
List<Widget> _buildTextLabels(ThemeData theme) {
/// Helper method to build a circular badge with an icon
///
/// [icon] - The icon to display in the badge
/// [color] - The background color of the badge
/// [iconColor] - The color of the icon
/// [position] - The position of the badge ('topRight' or 'bottomRight')
/// [sizeRatio] - The size ratio relative to the avatar size (default 0.3)
Widget _buildBadge({
required BuildContext context,
required IconData icon,
required Color color,
required Color iconColor,
required String position,
double sizeRatio = 0.3,
}) {
final badgeSize = size * sizeRatio;
final iconSize =
size * (sizeRatio * 0.67); // Approximately 2/3 of badge size
return Positioned(
top: position == 'topRight' ? 0 : null,
bottom: position == 'bottomRight' ? 0 : null,
right: 0,
child: Container(
width: badgeSize,
height: badgeSize,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(context).colorScheme.surface,
width: 1,
),
),
child: Icon(icon, size: iconSize, color: iconColor),
),
);
}
/// Helper method to build a text label chip
///
/// [text] - The text to display in the chip
/// [backgroundColor] - The background color of the chip
/// [textColor] - The color of the text
Widget _buildLabelChip({
required BuildContext context,
required String text,
required Color backgroundColor,
required Color textColor,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(8),
),
child: Text(
text,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: textColor,
fontWeight: FontWeight.bold,
),
),
);
}
List<Widget> _buildTextLabels(BuildContext context, ThemeData theme) {
if (!useTextLabels || !showIndicators) return [];
final labels = <Widget>[];
if (user.isAdminUser) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: BorderRadius.circular(8),
),
child: Text(
t.userStatus.admin,
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
_buildLabelChip(
context: context,
text: t.userStatus.admin,
backgroundColor: theme.colorScheme.primary,
textColor: theme.colorScheme.onPrimary,
),
);
}
if (user.isRestrictedUser && !user.isAdminUser) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.warning ?? Colors.orange,
borderRadius: BorderRadius.circular(8),
),
child: Text(
t.userStatus.restricted,
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
_buildLabelChip(
context: context,
text: t.userStatus.restricted,
backgroundColor: theme.colorScheme.warning ?? Colors.orange,
textColor: theme.colorScheme.onPrimary,
),
);
}
if (user.requiresPassword) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.secondary,
borderRadius: BorderRadius.circular(8),
),
child: Text(
t.userStatus.protected,
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSecondary,
fontWeight: FontWeight.bold,
),
),
_buildLabelChip(
context: context,
text: t.userStatus.protected,
backgroundColor: theme.colorScheme.secondary,
textColor: theme.colorScheme.onSecondary,
),
);
}
@@ -110,7 +152,7 @@ class UserAvatarWidget extends StatelessWidget {
];
}
Widget _buildAvatar(ThemeData theme) {
Widget _buildAvatar(BuildContext context, ThemeData theme) {
return SizedBox(
width: size,
height: size,
@@ -123,9 +165,8 @@ class UserAvatarWidget extends StatelessWidget {
width: size,
height: size,
fit: BoxFit.cover,
placeholder: (context, url) => _buildPlaceholderAvatar(theme),
errorWidget: (context, url, error) =>
_buildPlaceholderAvatar(theme),
placeholder: (ctx, url) => _buildPlaceholderAvatar(theme),
errorWidget: (ctx, url, error) => _buildPlaceholderAvatar(theme),
),
),
@@ -133,74 +174,33 @@ class UserAvatarWidget extends StatelessWidget {
if (showIndicators && !useTextLabels) ...[
// Admin badge
if (user.isAdminUser)
Positioned(
top: 0,
right: 0,
child: Container(
width: size * 0.3,
height: size * 0.3,
decoration: BoxDecoration(
color: theme.colorScheme.primary,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.admin_panel_settings,
size: size * 0.2,
color: theme.colorScheme.onPrimary,
),
),
_buildBadge(
context: context,
icon: Icons.admin_panel_settings,
color: theme.colorScheme.primary,
iconColor: theme.colorScheme.onPrimary,
position: 'topRight',
),
// Restricted badge
if (user.isRestrictedUser && !user.isAdminUser)
Positioned(
top: 0,
right: 0,
child: Container(
width: size * 0.3,
height: size * 0.3,
decoration: BoxDecoration(
color: theme.colorScheme.warning ?? Colors.orange,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.security,
size: size * 0.2,
color: theme.colorScheme.onPrimary,
),
),
_buildBadge(
context: context,
icon: Icons.security,
color: theme.colorScheme.warning ?? Colors.orange,
iconColor: theme.colorScheme.onPrimary,
position: 'topRight',
),
// Password indicator
if (user.requiresPassword)
Positioned(
bottom: 0,
right: 0,
child: Container(
width: size * 0.25,
height: size * 0.25,
decoration: BoxDecoration(
color: theme.colorScheme.secondary,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.lock,
size: size * 0.15,
color: theme.colorScheme.onSecondary,
),
),
_buildBadge(
context: context,
icon: Icons.lock,
color: theme.colorScheme.secondary,
iconColor: theme.colorScheme.onSecondary,
position: 'bottomRight',
sizeRatio: 0.25,
),
],
],
@@ -218,12 +218,15 @@ class UserAvatarWidget extends StatelessWidget {
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [_buildAvatar(theme), ..._buildTextLabels(theme)],
children: [
_buildAvatar(context, theme),
..._buildTextLabels(context, theme),
],
),
);
} else {
// Return just the avatar (original behavior)
return GestureDetector(onTap: onTap, child: _buildAvatar(theme));
return GestureDetector(onTap: onTap, child: _buildAvatar(context, theme));
}
}
}
+108 -166
View File
@@ -1,18 +1,14 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:rate_limiter/rate_limiter.dart';
import '../i18n/strings.g.dart';
import 'main_screen.dart';
import '../mixins/refreshable.dart';
import '../models/plex_metadata.dart';
import '../providers/multi_server_provider.dart';
import '../providers/settings_provider.dart';
import '../services/settings_service.dart';
import '../utils/app_logger.dart';
import '../utils/grid_cross_axis_extent.dart';
import '../utils/keyboard_utils.dart';
import '../utils/sliver_adaptive_media_builder.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/media_card.dart';
@@ -160,178 +156,124 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
}
}
/// Handle back key press - focus bottom navigation
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
// Allow backspace to work normally in search field when it has content
if (event.logicalKey == LogicalKeyboardKey.backspace &&
_searchFocusNode.hasFocus &&
_searchController.text.isNotEmpty) {
return KeyEventResult.ignored;
}
BackNavigationScope.of(context)?.focusBottomNav();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Focus(
onKeyEvent: _handleBackKey,
child: CustomScrollView(
slivers: [
DesktopSliverAppBar(
title: Text(t.screens.search),
floating: true,
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: _searchController,
focusNode: _searchFocusNode,
decoration: InputDecoration(
hintText: t.search.hint,
prefixIcon: const Icon(Icons.search),
suffixIcon: _searchController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.clear();
// State update handled by listener
},
)
: null,
filled: true,
fillColor: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(28),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
child: CustomScrollView(
slivers: [
DesktopSliverAppBar(title: Text(t.screens.search), floating: true),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: _searchController,
focusNode: _searchFocusNode,
decoration: InputDecoration(
hintText: t.search.hint,
prefixIcon: const Icon(Icons.search),
suffixIcon: _searchController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.clear();
// State update handled by listener
},
)
: null,
filled: true,
fillColor: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(28),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
),
),
),
if (_isSearching)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (!_hasSearched)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.search,
size: 80,
color: Colors.grey.shade400,
),
if (_isSearching)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (!_hasSearched)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.search, size: 80, color: Colors.grey.shade400),
const SizedBox(height: 16),
Text(
t.search.searchYourMedia,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.grey.shade600,
),
const SizedBox(height: 16),
Text(
t.search.searchYourMedia,
style: Theme.of(context).textTheme.titleLarge
?.copyWith(color: Colors.grey.shade600),
),
const SizedBox(height: 8),
Text(
t.search.enterTitleActorOrKeyword,
style: TextStyle(color: Colors.grey.shade600),
),
],
),
),
const SizedBox(height: 8),
Text(
t.search.enterTitleActorOrKeyword,
style: TextStyle(color: Colors.grey.shade600),
),
],
),
)
else if (_searchResults.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.search_off,
size: 80,
color: Colors.grey.shade400,
),
const SizedBox(height: 16),
Text(
t.messages.noResultsFound,
style: Theme.of(context).textTheme.titleLarge
?.copyWith(color: Colors.grey.shade600),
),
const SizedBox(height: 8),
Text(
t.search.tryDifferentTerm,
style: TextStyle(color: Colors.grey.shade600),
),
],
),
),
)
else
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),
),
);
} else {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate:
SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
getMaxCrossAxisExtentWithPadding(
context,
settingsProvider.libraryDensity,
32,
),
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),
),
);
}
},
),
],
),
)
else if (_searchResults.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.search_off,
size: 80,
color: Colors.grey.shade400,
),
const SizedBox(height: 16),
Text(
t.messages.noResultsFound,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.grey.shade600,
),
),
const SizedBox(height: 8),
Text(
t.search.tryDifferentTerm,
style: TextStyle(color: Colors.grey.shade600),
),
],
),
),
)
else
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return buildAdaptiveMediaSliverBuilder<PlexMetadata>(
context: context,
items: _searchResults,
itemBuilder: (context, item, index) {
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
},
viewMode: settingsProvider.viewMode,
density: settingsProvider.libraryDensity,
padding: const EdgeInsets.all(16),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
);
},
),
],
),
),
);
+209 -316
View File
@@ -1,31 +1,22 @@
import 'package:flutter/material.dart';
import '../../services/plex_client.dart';
import '../focus/key_event_utils.dart';
import '../focus/input_mode_tracker.dart';
import '../widgets/plex_optimized_image.dart';
import '../widgets/focus/focus_indicator.dart';
import '../models/plex_metadata.dart';
import '../utils/keyboard_utils.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/duration_formatter.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/media_context_menu.dart';
import '../mixins/item_updatable.dart';
import '../mixins/keyboard_long_press_mixin.dart';
import '../theme/theme_helper.dart';
import '../i18n/strings.g.dart';
class SeasonDetailScreen extends StatefulWidget {
final PlexMetadata season;
/// Whether to focus the first episode after loading.
/// Should be true when navigating via keyboard, false for mouse/tap.
final bool focusFirstEpisode;
const SeasonDetailScreen({
super.key,
required this.season,
this.focusFirstEpisode = false,
});
const SeasonDetailScreen({super.key, required this.season});
@override
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
@@ -41,9 +32,6 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
List<PlexMetadata> _episodes = [];
bool _isLoadingEpisodes = false;
bool _watchStateChanged = false;
final FocusNode _firstEpisodeFocusNode = FocusNode(
debugLabel: 'FirstEpisode',
);
/// Get the correct PlexClient for this season's server
PlexClient _getClientForSeason(BuildContext context) {
@@ -60,12 +48,6 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
});
}
@override
void dispose() {
_firstEpisodeFocusNode.dispose();
super.dispose();
}
Future<void> _loadEpisodes() async {
setState(() {
_isLoadingEpisodes = true;
@@ -79,13 +61,6 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
_episodes = episodes;
_isLoadingEpisodes = false;
});
// Focus the first episode after loading (only if keyboard navigation)
if (episodes.isNotEmpty && widget.focusFirstEpisode) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_firstEpisodeFocusNode.requestFocus();
});
}
} catch (e) {
setState(() {
_isLoadingEpisodes = false;
@@ -109,17 +84,11 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
@override
Widget build(BuildContext context) {
return Scaffold(
body: Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (isBackKeyEvent(event)) {
Navigator.pop(context, _watchStateChanged);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: CustomScrollView(
return Focus(
onKeyEvent: (_, event) =>
handleBackKeyNavigation(context, event, result: _watchStateChanged),
child: Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(widget.season.title),
@@ -159,7 +128,8 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
return _EpisodeCard(
episode: episode,
client: _client,
focusNode: index == 0 ? _firstEpisodeFocusNode : null,
autofocus:
index == 0 && InputModeTracker.isKeyboardMode(context),
onTap: () async {
await navigateToVideoPlayer(context, metadata: episode);
// Refresh episodes when returning from video player
@@ -176,79 +146,58 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
}
}
/// Focusable episode card widget
class _EpisodeCard extends StatefulWidget {
/// Episode card widget
class _EpisodeCard extends StatelessWidget {
final PlexMetadata episode;
final PlexClient client;
final VoidCallback onTap;
final Future<void> Function(String) onRefresh;
final FocusNode? focusNode;
final bool autofocus;
const _EpisodeCard({
required this.episode,
required this.client,
required this.onTap,
required this.onRefresh,
this.focusNode,
this.autofocus = false,
});
@override
State<_EpisodeCard> createState() => _EpisodeCardState();
}
class _EpisodeCardState extends State<_EpisodeCard>
with KeyboardLongPressMixin {
FocusNode? _internalFocusNode;
FocusNode get _focusNode =>
widget.focusNode ?? (_internalFocusNode ??= FocusNode());
bool _isFocused = false;
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
@override
void onKeyboardTap() => widget.onTap();
@override
void onKeyboardLongPress() {
_contextMenuKey.currentState?.showContextMenu(context);
}
@override
void initState() {
super.initState();
_focusNode.addListener(_handleFocusChange);
}
@override
void dispose() {
_focusNode.removeListener(_handleFocusChange);
_internalFocusNode?.dispose();
super.dispose();
}
void _handleFocusChange() {
if (_isFocused != _focusNode.hasFocus) {
setState(() {
_isFocused = _focusNode.hasFocus;
});
if (_focusNode.hasFocus) {
Scrollable.ensureVisible(
context,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
}
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
// Handle long-press detection for activation keys
return handleKeyboardLongPress(event);
Widget _buildEpisodeMetaRow(BuildContext context) {
return Row(
children: [
if (episode.duration != null)
Text(
formatDurationTimestamp(Duration(milliseconds: episode.duration!)),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
if (episode.duration != null && episode.isWatched) ...[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Text(
'•',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
),
Text(
'${t.discover.watched} ✓',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
],
],
);
}
@override
Widget build(BuildContext context) {
final episode = widget.episode;
final hasProgress =
episode.viewOffset != null &&
episode.duration != null &&
@@ -258,239 +207,183 @@ class _EpisodeCardState extends State<_EpisodeCard>
: 0.0;
return MediaContextMenu(
key: _contextMenuKey,
item: episode,
onRefresh: widget.onRefresh,
onTap: widget.onTap,
child: Focus(
focusNode: _focusNode,
onKeyEvent: _handleKeyEvent,
child: FocusIndicator(
isFocused: _isFocused,
borderRadius: 0,
scale: 1.0, // No scale for full-width items to avoid clipping
child: InkWell(
key: Key(episode.ratingKey),
onTap: widget.onTap,
hoverColor: Theme.of(
context,
).colorScheme.surface.withValues(alpha: 0.05),
focusColor: Colors.transparent,
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: tokens(context).outline,
width: 0.5,
),
),
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Episode thumbnail (16:9 aspect ratio, fixed width)
SizedBox(
width: 160,
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: AspectRatio(
aspectRatio: 16 / 9,
child: episode.thumb != null
? PlexThumbImage(
client: widget.client,
imagePath: episode.thumb,
filterQuality: FilterQuality.medium,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) =>
Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(
Icons.movie,
size: 32,
),
),
)
: Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
),
),
// Play overlay
Positioned.fill(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black.withValues(alpha: 0.2),
],
),
),
child: Center(
child: Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.6),
shape: BoxShape.circle,
),
child: const Icon(
Icons.play_arrow,
color: Colors.white,
size: 20,
),
),
),
),
),
// Progress bar at bottom
if (hasProgress && !episode.isWatched)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: ClipRRect(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(6),
bottomRight: Radius.circular(6),
),
child: LinearProgressIndicator(
value: progress,
backgroundColor: tokens(context).outline,
minHeight: 3,
),
),
),
],
),
),
const SizedBox(width: 12),
// Episode info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Episode number and title
Row(
children: [
if (episode.index != null)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 3,
),
decoration: BoxDecoration(
onRefresh: onRefresh,
onTap: onTap,
child: InkWell(
key: Key(episode.ratingKey),
autofocus: autofocus,
onTap: onTap,
hoverColor: Theme.of(
context,
).colorScheme.surface.withValues(alpha: 0.05),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: tokens(context).outline, width: 0.5),
),
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Episode thumbnail (16:9 aspect ratio, fixed width)
SizedBox(
width: 160,
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: AspectRatio(
aspectRatio: 16 / 9,
child: episode.thumb != null
? PlexOptimizedImage.thumb(
client: client,
imagePath: episode.thumb,
filterQuality: FilterQuality.medium,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(3),
).colorScheme.surfaceContainerHighest,
),
child: Text(
'E${episode.index}',
style: TextStyle(
color: Theme.of(
context,
).colorScheme.onPrimaryContainer,
fontSize: 11,
fontWeight: FontWeight.w600,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
)
: Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
const SizedBox(width: 8),
Expanded(
child: Text(
episode.title,
style: Theme.of(context).textTheme.titleSmall
?.copyWith(fontWeight: FontWeight.bold),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
// Play overlay
Positioned.fill(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black.withValues(alpha: 0.2),
],
),
),
child: Center(
child: Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.6),
shape: BoxShape.circle,
),
child: const Icon(
Icons.play_arrow,
color: Colors.white,
size: 20,
),
),
),
),
),
// Progress bar at bottom
if (hasProgress && !episode.isWatched)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: ClipRRect(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(6),
bottomRight: Radius.circular(6),
),
child: LinearProgressIndicator(
value: progress,
backgroundColor: tokens(context).outline,
minHeight: 3,
),
),
),
],
),
),
const SizedBox(width: 12),
// Episode info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Episode number and title
Row(
children: [
if (episode.index != null)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 3,
),
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(3),
),
child: Text(
'E${episode.index}',
style: TextStyle(
color: Theme.of(
context,
).colorScheme.onPrimaryContainer,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
],
),
// Summary
if (episode.summary != null &&
episode.summary!.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
episode.summary!,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
height: 1.3,
),
maxLines: 3,
),
const SizedBox(width: 8),
Expanded(
child: Text(
episode.title,
style: Theme.of(context).textTheme.titleSmall
?.copyWith(fontWeight: FontWeight.bold),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
// Metadata row (duration, watched status)
const SizedBox(height: 8),
Row(
children: [
if (episode.duration != null)
Text(
formatDurationTimestamp(
Duration(milliseconds: episode.duration!),
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
if (episode.duration != null &&
episode.isWatched) ...[
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 6,
),
child: Text(
'•',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
),
Text(
'${t.discover.watched} ✓',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
],
],
),
],
),
),
],
// Summary
if (episode.summary != null &&
episode.summary!.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
episode.summary!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
height: 1.3,
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
],
// Metadata row (duration, watched status)
const SizedBox(height: 8),
_buildEpisodeMetaRow(context),
],
),
),
),
],
),
),
),
+58 -60
View File
@@ -1,6 +1,6 @@
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../widgets/focused_scroll_scaffold.dart';
import '../../i18n/strings.g.dart';
import 'licenses_screen.dart';
@@ -34,69 +34,67 @@ class _AboutScreenState extends State<AboutScreen> {
final appName = _appName;
final appVersion = _appVersion;
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.about.title), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// App Icon and Name
Center(
child: Column(
children: [
const SizedBox(height: 24),
Image.asset('assets/plezy.png', width: 80, height: 80),
const SizedBox(height: 16),
Text(
appName,
style: Theme.of(context).textTheme.headlineMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
t.about.versionLabel(version: appVersion),
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 24),
Text(
t.about.appDescription,
style: Theme.of(context).textTheme.bodyLarge,
textAlign: TextAlign.center,
),
],
),
),
const SizedBox(height: 40),
// Open Source Licenses
Card(
child: ListTile(
leading: const Icon(Icons.description),
title: Text(t.about.openSourceLicenses),
subtitle: Text(t.about.viewLicensesDescription),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
return FocusedScrollScaffold(
title: Text(t.about.title),
slivers: [
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// App Icon and Name
Center(
child: Column(
children: [
const SizedBox(height: 24),
Image.asset('assets/plezy.png', width: 80, height: 80),
const SizedBox(height: 16),
Text(
appName,
style: Theme.of(context).textTheme.headlineMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
t.about.versionLabel(version: appVersion),
style: Theme.of(
context,
MaterialPageRoute(
builder: (context) => const LicensesScreen(),
),
);
},
),
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 24),
Text(
t.about.appDescription,
style: Theme.of(context).textTheme.bodyLarge,
textAlign: TextAlign.center,
),
],
),
),
const SizedBox(height: 24),
]),
),
const SizedBox(height: 40),
// Open Source Licenses
Card(
child: ListTile(
leading: const Icon(Icons.description),
title: Text(t.about.openSourceLicenses),
subtitle: Text(t.about.viewLicensesDescription),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const LicensesScreen(),
),
);
},
),
),
const SizedBox(height: 24),
]),
),
],
),
),
],
);
}
}
+116 -115
View File
@@ -1,6 +1,6 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../widgets/focused_scroll_scaffold.dart';
import '../../i18n/strings.g.dart';
class MergedLicenseEntry {
@@ -68,45 +68,50 @@ class _LicensesScreenState extends State<LicensesScreen> {
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.screens.licenses), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final mergedLicense = _mergedLicenses[index];
final packageName = mergedLicense.packageName;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
title: Text(
packageName,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: mergedLicense.licenseEntries.length > 1
? Text(
t.licenses.licensesCount(
count: mergedLicense.licenseEntries.length,
),
)
: null,
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLicenseDetail(mergedLicense),
),
);
}, childCount: _mergedLicenses.length),
),
return FocusedScrollScaffold(
title: Text(t.screens.licenses),
slivers: const [
SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
),
],
),
);
}
return FocusedScrollScaffold(
title: Text(t.screens.licenses),
slivers: [
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final mergedLicense = _mergedLicenses[index];
final packageName = mergedLicense.packageName;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
title: Text(
packageName,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: mergedLicense.licenseEntries.length > 1
? Text(
t.licenses.licensesCount(
count: mergedLicense.licenseEntries.length,
),
)
: null,
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLicenseDetail(mergedLicense),
),
);
}, childCount: _mergedLicenses.length),
),
),
],
);
}
@@ -131,91 +136,87 @@ class _LicenseDetailScreen extends StatelessWidget {
final packageName = mergedLicense.packageName;
final licenseEntries = mergedLicense.licenseEntries;
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(packageName), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// Package info card
if (mergedLicense.allPackageNames.length > 1)
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
t.licenses.relatedPackages,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
mergedLicense.allPackageNames.join(', '),
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
return FocusedScrollScaffold(
title: Text(packageName),
slivers: [
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// Package info card
if (mergedLicense.allPackageNames.length > 1)
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
t.licenses.relatedPackages,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
mergedLicense.allPackageNames.join(', '),
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
if (mergedLicense.allPackageNames.length > 1)
const SizedBox(height: 16),
),
if (mergedLicense.allPackageNames.length > 1)
const SizedBox(height: 16),
// License cards
...licenseEntries.asMap().entries.map((entry) {
final index = entry.key;
final license = entry.value;
final isMultipleLicenses = licenseEntries.length > 1;
// License cards
...licenseEntries.asMap().entries.map((entry) {
final index = entry.key;
final license = entry.value;
final isMultipleLicenses = licenseEntries.length > 1;
return Column(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isMultipleLicenses
? t.licenses.licenseNumber(
number: index + 1,
)
: t.licenses.license,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
...license.paragraphs.map((paragraph) {
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: SelectableText(
paragraph.text,
style: TextStyle(
fontFamily: paragraph.indent > 0
? 'monospace'
: null,
fontSize: 14,
),
return Column(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isMultipleLicenses
? t.licenses.licenseNumber(number: index + 1)
: t.licenses.license,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
...license.paragraphs.map((paragraph) {
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: SelectableText(
paragraph.text,
style: TextStyle(
fontFamily: paragraph.indent > 0
? 'monospace'
: null,
fontSize: 14,
),
);
}),
],
),
),
);
}),
],
),
),
if (index < licenseEntries.length - 1)
const SizedBox(height: 16),
],
);
}),
]),
),
),
if (index < licenseEntries.length - 1)
const SizedBox(height: 16),
],
);
}),
]),
),
],
),
),
],
);
}
}
+23 -37
View File
@@ -4,13 +4,11 @@ import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../i18n/strings.g.dart';
import '../main_screen.dart';
import '../../providers/settings_provider.dart';
import '../../providers/theme_provider.dart';
import '../../services/keyboard_shortcuts_service.dart';
import '../../services/settings_service.dart' as settings;
import '../../services/update_service.dart';
import '../../utils/keyboard_utils.dart';
import '../../widgets/desktop_app_bar.dart';
import 'hotkey_recorder_widget.dart';
import 'about_screen.dart';
@@ -69,15 +67,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
});
}
/// Handle back key press - focus bottom navigation
KeyEventResult _handleBackKey(FocusNode node, KeyEvent event) {
if (isBackKeyEvent(event)) {
BackNavigationScope.of(context)?.focusBottomNav();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
@@ -85,34 +74,31 @@ class _SettingsScreenState extends State<SettingsScreen> {
}
return Scaffold(
body: Focus(
onKeyEvent: _handleBackKey,
child: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.settings.title), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildAppearanceSection(),
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.settings.title), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildAppearanceSection(),
const SizedBox(height: 24),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
const SizedBox(height: 24),
if (UpdateService.isUpdateCheckEnabled) ...[
_buildUpdateSection(),
const SizedBox(height: 24),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
const SizedBox(height: 24),
if (UpdateService.isUpdateCheckEnabled) ...[
_buildUpdateSection(),
const SizedBox(height: 24),
],
_buildAboutSection(),
const SizedBox(height: 24),
]),
),
],
_buildAboutSection(),
const SizedBox(height: 24),
]),
),
],
),
),
],
),
);
}
+18 -5
View File
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:os_media_controls/os_media_controls.dart';
import 'package:provider/provider.dart';
import 'package:wakelock_plus/wakelock_plus.dart';
import '../mpv/mpv.dart';
@@ -180,13 +181,18 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
// Clear media controls when app truly goes to background
// (we don't support background playback)
OsMediaControls.clear();
// Disable wakelock when app goes to background
WakelockPlus.disable();
appLogger.d(
'Media controls cleared due to app being paused/backgrounded',
'Media controls cleared and wakelock disabled due to app being paused/backgrounded',
);
break;
case AppLifecycleState.resumed:
// Restore media controls when app is resumed
// Restore media controls and wakelock when app is resumed
if (_isPlayerInitialized && mounted) {
// Re-enable wakelock since we're back in the video player
WakelockPlus.enable();
// Restore media metadata
final client = _getClientForMetadata(context);
if (_mediaControlsManager != null) {
@@ -207,7 +213,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
}
_updateMediaControlsPlaybackState();
appLogger.d('Media controls restored on app resume');
appLogger.d('Media controls restored and wakelock re-enabled on app resume');
}
break;
case AppLifecycleState.detached:
@@ -330,6 +336,10 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
setState(() {
_isPlayerInitialized = true;
});
// Enable wakelock to prevent screen from turning off during playback
WakelockPlus.enable();
appLogger.d('Wakelock enabled for video playback');
}
// Get the video URL and start playback
@@ -751,6 +761,10 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
_mediaControlsManager?.clear();
_mediaControlsManager?.dispose();
// Disable wakelock when leaving the video player
WakelockPlus.disable();
appLogger.d('Wakelock disabled');
// Restore system UI and orientation preferences (skip if navigating to another video)
if (!_isReplacingWithVideo) {
OrientationHelper.restoreSystemUI();
@@ -1260,7 +1274,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen>
return Video(
player: player!,
fit: _videoFilterManager?.currentBoxFit ?? BoxFit.contain,
controls: (context) => plexVideoControlsBuilder(
player!,
widget.metadata,
@@ -1427,7 +1440,7 @@ String _getHwdecValue(bool enabled) {
if (Platform.isMacOS || Platform.isIOS) {
return 'videotoolbox';
} else if (Platform.isAndroid) {
return 'mediacodec-copy';
return 'auto-safe';
} else {
return 'auto'; // Windows, Linux
}
@@ -0,0 +1,45 @@
import 'package:shared_preferences/shared_preferences.dart';
/// Base class for services that use SharedPreferences singleton pattern.
///
/// This class handles the boilerplate for singleton initialization and
/// SharedPreferences lifecycle management. Subclasses should:
/// 1. Create a private named constructor (e.g., SettingsService._())
/// 2. Implement their own getInstance() method that calls BaseSharedPreferencesService.initializeInstance()
/// 3. Optionally override onInit() for post-initialization setup
abstract class BaseSharedPreferencesService {
static final Map<Type, BaseSharedPreferencesService> _instances = {};
late SharedPreferences _prefs;
/// Protected constructor for subclasses
BaseSharedPreferencesService();
/// Access to SharedPreferences instance
SharedPreferences get prefs => _prefs;
/// Initialize the SharedPreferences instance
///
/// This method handles:
/// - Singleton instance management
/// - SharedPreferences initialization
/// - Calling onInit() hook for subclass-specific setup
static Future<T> initializeInstance<T extends BaseSharedPreferencesService>(
T Function() constructor,
) async {
if (_instances[T] == null) {
final instance = constructor();
_instances[T] = instance;
instance._prefs = await SharedPreferences.getInstance();
await instance.onInit();
}
return _instances[T] as T;
}
/// Hook for subclass-specific initialization after SharedPreferences is ready.
///
/// Override this method to perform any setup that requires access to
/// SharedPreferences (e.g., registering values with other services).
Future<void> onInit() async {
// Default implementation does nothing
}
}
+341
View File
@@ -0,0 +1,341 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/services.dart';
import 'package:gamepads/gamepads.dart';
import '../utils/app_logger.dart';
/// Service that bridges gamepad input to Flutter's focus navigation system.
///
/// Listens to gamepad events from the `gamepads` package and translates them
/// into focus navigation actions and key events that integrate with the
/// existing keyboard navigation system.
class GamepadService {
static GamepadService? _instance;
StreamSubscription<GamepadEvent>? _subscription;
/// Callback to switch InputModeTracker to keyboard mode.
/// Set by InputModeTracker when it initializes.
static VoidCallback? onGamepadInput;
/// Callback for L1 bumper press (previous tab).
/// Screens with tabs can listen to this.
static VoidCallback? onL1Pressed;
/// Callback for R1 bumper press (next tab).
/// Screens with tabs can listen to this.
static VoidCallback? onR1Pressed;
// Deadzone for analog sticks (0.0 to 1.0)
static const double _stickDeadzone = 0.5;
// Track D-pad state to avoid repeated navigation events
bool _dpadUp = false;
bool _dpadDown = false;
bool _dpadLeft = false;
bool _dpadRight = false;
// Track stick state to avoid repeated navigation events
bool _leftStickUp = false;
bool _leftStickDown = false;
bool _leftStickLeft = false;
bool _leftStickRight = false;
// Track button states to prevent repeated events from button holds
final Set<String> _pressedButtons = {};
GamepadService._();
/// Get the singleton instance.
static GamepadService get instance {
_instance ??= GamepadService._();
return _instance!;
}
/// Start listening to gamepad events.
/// Only active on desktop platforms (macOS, Windows, Linux).
void start() async {
// Only enable on desktop platforms
if (!Platform.isMacOS && !Platform.isWindows && !Platform.isLinux) return;
appLogger.i('GamepadService: Starting on ${Platform.operatingSystem}');
// List connected gamepads
try {
final gamepads = await Gamepads.list();
appLogger.i('GamepadService: Found ${gamepads.length} gamepad(s)');
for (final gamepad in gamepads) {
appLogger.i(' - ${gamepad.name} (id: ${gamepad.id})');
}
} catch (e) {
appLogger.e('GamepadService: Error listing gamepads', error: e);
}
_subscription?.cancel();
_subscription = Gamepads.events.listen(
_handleGamepadEvent,
onError: (e) => appLogger.e('GamepadService: Stream error', error: e),
);
appLogger.i('GamepadService: Listening for gamepad events');
}
/// Stop listening to gamepad events.
void stop() {
_subscription?.cancel();
_subscription = null;
}
void _handleGamepadEvent(GamepadEvent event) {
final key = event.key.toLowerCase();
final value = event.value;
// Switch to keyboard mode on any significant gamepad input
if (value.abs() > 0.3) {
onGamepadInput?.call();
_setTraditionalFocusHighlight();
_scheduleFrameIfIdle();
}
// Handle D-pad (reported as axes on macOS)
if (_isDpadYAxis(key)) {
_handleDpadY(value);
return;
}
if (_isDpadXAxis(key)) {
_handleDpadX(value);
return;
}
// Handle face buttons
final isPressed = value > 0.5;
final wasPressed = _pressedButtons.contains(key);
if (isPressed && !wasPressed) {
_pressedButtons.add(key);
if (_isButtonA(key)) {
// Use enter instead of gameButtonA so it works with Flutter's built-in
// widgets (buttons, list tiles, etc.) which listen for enter
_simulateKeyPress(LogicalKeyboardKey.enter);
} else if (_isButtonB(key)) {
// Use escape instead of gameButtonB so it works with Flutter's built-in
// widgets (bottom sheets, dialogs, menus) which only listen for escape
_simulateKeyPress(LogicalKeyboardKey.escape);
} else if (_isButtonX(key)) {
_simulateKeyPress(LogicalKeyboardKey.gameButtonX);
} else if (_isL1(key)) {
onL1Pressed?.call();
} else if (_isR1(key)) {
onR1Pressed?.call();
}
} else if (!isPressed && wasPressed) {
_pressedButtons.remove(key);
}
// Handle left analog stick
if (_isLeftStickY(key)) {
_handleLeftStickY(value);
return;
}
if (_isLeftStickX(key)) {
_handleLeftStickX(value);
return;
}
}
void _moveFocus(TraversalDirection direction) {
// Convert direction to arrow key and simulate a key press
// This allows widgets like HubSection that intercept key events to handle navigation
final logicalKey = _directionToKey(direction);
_simulateKeyPress(logicalKey);
}
LogicalKeyboardKey _directionToKey(TraversalDirection direction) {
switch (direction) {
case TraversalDirection.up:
return LogicalKeyboardKey.arrowUp;
case TraversalDirection.down:
return LogicalKeyboardKey.arrowDown;
case TraversalDirection.left:
return LogicalKeyboardKey.arrowLeft;
case TraversalDirection.right:
return LogicalKeyboardKey.arrowRight;
}
}
void _simulateKeyPress(LogicalKeyboardKey logicalKey) {
// Schedule on next frame to ensure we're on the main thread
SchedulerBinding.instance.addPostFrameCallback((_) {
final focusNode = FocusManager.instance.primaryFocus;
if (focusNode == null) return;
// Create a synthetic key down event
final keyDownEvent = KeyDownEvent(
physicalKey: _getPhysicalKey(logicalKey),
logicalKey: logicalKey,
timeStamp: Duration(
milliseconds: DateTime.now().millisecondsSinceEpoch,
),
);
// Dispatch through the focus system by walking up the focus tree
// and calling each node's onKeyEvent handler
FocusNode? node = focusNode;
KeyEventResult result = KeyEventResult.ignored;
while (node != null && result != KeyEventResult.handled) {
// The Focus widget stores its handler in onKeyEvent
if (node.onKeyEvent != null) {
result = node.onKeyEvent!(node, keyDownEvent);
}
node = node.parent;
}
// Send key up event
final keyUpEvent = KeyUpEvent(
physicalKey: _getPhysicalKey(logicalKey),
logicalKey: logicalKey,
timeStamp: Duration(
milliseconds: DateTime.now().millisecondsSinceEpoch,
),
);
node = focusNode;
while (node != null) {
if (node.onKeyEvent != null) {
final upResult = node.onKeyEvent!(node, keyUpEvent);
if (upResult == KeyEventResult.handled) break;
}
node = node.parent;
}
});
}
PhysicalKeyboardKey _getPhysicalKey(LogicalKeyboardKey logicalKey) {
if (logicalKey == LogicalKeyboardKey.gameButtonA) {
return PhysicalKeyboardKey.gameButtonA;
} else if (logicalKey == LogicalKeyboardKey.gameButtonB) {
return PhysicalKeyboardKey.gameButtonB;
} else if (logicalKey == LogicalKeyboardKey.gameButtonX) {
return PhysicalKeyboardKey.gameButtonX;
} else if (logicalKey == LogicalKeyboardKey.arrowUp) {
return PhysicalKeyboardKey.arrowUp;
} else if (logicalKey == LogicalKeyboardKey.arrowDown) {
return PhysicalKeyboardKey.arrowDown;
} else if (logicalKey == LogicalKeyboardKey.arrowLeft) {
return PhysicalKeyboardKey.arrowLeft;
} else if (logicalKey == LogicalKeyboardKey.arrowRight) {
return PhysicalKeyboardKey.arrowRight;
} else if (logicalKey == LogicalKeyboardKey.escape) {
return PhysicalKeyboardKey.escape;
}
return PhysicalKeyboardKey.enter;
}
// macOS DualSense key matching
// D-pad reports as axes: dpad - xaxis, dpad - yaxis
bool _isDpadYAxis(String key) => key == 'dpad - yaxis';
bool _isDpadXAxis(String key) => key == 'dpad - xaxis';
// Face buttons - macOS uses SF Symbol names for PlayStation controllers
bool _isButtonA(String key) =>
key == 'xmark.circle'; // Cross/X button (bottom)
bool _isButtonB(String key) =>
key == 'circle.circle'; // Circle/O button (right)
bool _isButtonX(String key) => key == 'square.circle'; // Square button (left)
// Analog sticks
bool _isLeftStickX(String key) => key == 'l.joystick - xaxis';
bool _isLeftStickY(String key) => key == 'l.joystick - yaxis';
// Bumper buttons
bool _isL1(String key) => key == 'l1.rectangle.roundedbottom';
bool _isR1(String key) => key == 'r1.rectangle.roundedbottom';
// D-pad Y axis: -1 = down (visually up on controller), 1 = up (visually down)
// Inverted because macOS reports opposite of expected
void _handleDpadY(double value) {
if (value < -0.5 && !_dpadDown) {
_dpadDown = true;
_dpadUp = false;
_moveFocus(TraversalDirection.down);
} else if (value > 0.5 && !_dpadUp) {
_dpadUp = true;
_dpadDown = false;
_moveFocus(TraversalDirection.up);
} else if (value == 0) {
_dpadUp = false;
_dpadDown = false;
}
}
// D-pad X axis: -1 = left, 1 = right, 0 = released
void _handleDpadX(double value) {
if (value < -0.5 && !_dpadLeft) {
_dpadLeft = true;
_dpadRight = false;
_moveFocus(TraversalDirection.left);
} else if (value > 0.5 && !_dpadRight) {
_dpadRight = true;
_dpadLeft = false;
_moveFocus(TraversalDirection.right);
} else if (value == 0) {
_dpadLeft = false;
_dpadRight = false;
}
}
// Left stick Y axis - inverted like D-pad
void _handleLeftStickY(double value) {
if (value < -_stickDeadzone && !_leftStickDown) {
_leftStickDown = true;
_leftStickUp = false;
_moveFocus(TraversalDirection.down);
} else if (value > _stickDeadzone && !_leftStickUp) {
_leftStickUp = true;
_leftStickDown = false;
_moveFocus(TraversalDirection.up);
} else if (value.abs() <= _stickDeadzone) {
_leftStickUp = false;
_leftStickDown = false;
}
}
void _handleLeftStickX(double value) {
if (value < -_stickDeadzone && !_leftStickLeft) {
_leftStickLeft = true;
_leftStickRight = false;
_moveFocus(TraversalDirection.left);
} else if (value > _stickDeadzone && !_leftStickRight) {
_leftStickRight = true;
_leftStickLeft = false;
_moveFocus(TraversalDirection.right);
} else if (value.abs() <= _stickDeadzone) {
_leftStickLeft = false;
_leftStickRight = false;
}
}
// Ensure Material uses traditional (keyboard) focus highlights when navigating
// via gamepad. Synthetic key events we dispatch below don't go through the
// platform key pipeline, so Flutter won't automatically flip highlight mode.
void _setTraditionalFocusHighlight() {
if (FocusManager.instance.highlightStrategy !=
FocusHighlightStrategy.alwaysTraditional) {
FocusManager.instance.highlightStrategy =
FocusHighlightStrategy.alwaysTraditional;
}
}
// Force a frame when the engine is idle so focus visuals update immediately
// on gamepad input (desktop may not wake up without mouse/keyboard activity).
void _scheduleFrameIfIdle() {
final scheduler = SchedulerBinding.instance;
if (scheduler.schedulerPhase == SchedulerPhase.idle) {
scheduler.scheduleFrame();
}
}
}
+2 -3
View File
@@ -3,7 +3,6 @@ import 'package:flutter/services.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import '../mpv/mpv.dart';
import 'settings_service.dart';
import '../utils/keyboard_utils.dart';
import '../utils/player_utils.dart';
class KeyboardShortcutsService {
@@ -159,8 +158,8 @@ class KeyboardShortcutsService {
}) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
// Handle back navigation keys first
if (isBackKey(event.logicalKey)) {
// Handle back navigation keys (Escape)
if (event.logicalKey == LogicalKeyboardKey.escape) {
onBack?.call();
return KeyEventResult.handled;
}
+294
View File
@@ -0,0 +1,294 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/play_queue_response.dart';
import '../models/plex_metadata.dart';
import '../models/plex_playlist.dart';
import '../providers/playback_state_provider.dart';
import '../utils/app_logger.dart';
import '../utils/video_player_navigation.dart';
import '../i18n/strings.g.dart';
import 'plex_client.dart';
/// Result type for play queue operations
sealed class PlayQueueResult {
const PlayQueueResult();
}
class PlayQueueSuccess extends PlayQueueResult {
const PlayQueueSuccess();
}
class PlayQueueEmpty extends PlayQueueResult {
const PlayQueueEmpty();
}
class PlayQueueError extends PlayQueueResult {
final Object error;
const PlayQueueError(this.error);
}
/// Service to handle play queue creation and navigation.
///
/// Centralizes the common pattern of:
/// 1. Creating a play queue via various methods
/// 2. Setting up PlaybackStateProvider
/// 3. Navigating to the video player
/// 4. Handling errors with appropriate feedback
class PlayQueueLauncher {
final BuildContext context;
final PlexClient client;
final String? serverId;
final String? serverName;
PlayQueueLauncher({
required this.context,
required this.client,
this.serverId,
this.serverName,
});
/// Launch playback from a collection or playlist.
Future<PlayQueueResult> launchFromCollectionOrPlaylist({
required dynamic item, // PlexMetadata (collection) or PlexPlaylist
required bool shuffle,
bool showLoadingIndicator = true,
}) async {
final isCollection = item is PlexMetadata;
final isPlaylist = item is PlexPlaylist;
if (!isCollection && !isPlaylist) {
return PlayQueueError(
Exception('Item must be either a collection or playlist'),
);
}
return _executeWithLoading(
showLoading: showLoadingIndicator,
action: t.common.shuffle,
execute: () async {
final String ratingKey = item.ratingKey;
final String? itemServerId = item.serverId ?? serverId;
final String? itemServerName = item.serverName ?? serverName;
PlayQueueResponse? playQueue;
if (isCollection) {
// Get machine identifier (fetch if not cached in config)
final machineId =
client.config.machineIdentifier ??
await client.getMachineIdentifier();
if (machineId == null) {
throw Exception('Could not get server machine identifier');
}
final collectionUri =
'server://$machineId/com.plexapp.plugins.library/library/collections/${item.ratingKey}';
playQueue = await client.createPlayQueue(
uri: collectionUri,
type: 'video',
shuffle: shuffle ? 1 : 0,
);
} else {
// For playlists, use playlistID parameter
playQueue = await client.createPlayQueue(
playlistID: int.parse(item.ratingKey),
type: 'video',
shuffle: shuffle ? 1 : 0,
);
}
// If the queue is empty, try fetching it again with getPlayQueue
if (playQueue != null &&
(playQueue.items == null || playQueue.items!.isEmpty)) {
final fetchedQueue = await client.getPlayQueue(playQueue.playQueueID);
if (fetchedQueue != null &&
fetchedQueue.items != null &&
fetchedQueue.items!.isNotEmpty) {
playQueue = fetchedQueue;
}
}
return _launchFromQueue(
playQueue: playQueue,
ratingKey: ratingKey,
serverId: itemServerId,
serverName: itemServerName,
);
},
);
}
/// Launch playback from a playlist starting at a specific item.
Future<PlayQueueResult> launchFromPlaylistItem({
required PlexPlaylist playlist,
required PlexMetadata selectedItem,
bool showLoadingIndicator = true,
}) async {
return _executeWithLoading(
showLoading: showLoadingIndicator,
action: t.discover.play,
execute: () async {
final playQueue = await client.createPlayQueue(
playlistID: int.parse(playlist.ratingKey),
type: 'video',
key: selectedItem.key,
);
return _launchFromQueue(
playQueue: playQueue,
ratingKey: playlist.ratingKey,
serverId: serverId,
serverName: serverName,
selectedItem: playQueue?.selectedItem,
);
},
);
}
/// Launch shuffled playback for a show or season.
Future<PlayQueueResult> launchShuffledShow({
required PlexMetadata metadata,
bool showLoadingIndicator = true,
}) async {
final itemType = metadata.type.toLowerCase();
if (itemType != 'show' && itemType != 'season') {
return PlayQueueError(
Exception('Shuffle play only works for shows and seasons'),
);
}
return _executeWithLoading(
showLoading: showLoadingIndicator,
action: t.common.shuffle,
execute: () async {
// Determine the rating key for the play queue
String showRatingKey;
if (itemType == 'show') {
showRatingKey = metadata.ratingKey;
} else {
// For seasons, we need the show's rating key
if (metadata.parentRatingKey == null) {
throw Exception('Season is missing parentRatingKey');
}
showRatingKey = metadata.parentRatingKey!;
}
final playQueue = await client.createShowPlayQueue(
showRatingKey: showRatingKey,
shuffle: 1,
);
return _launchFromQueue(
playQueue: playQueue,
ratingKey: showRatingKey,
serverId: metadata.serverId ?? serverId,
serverName: metadata.serverName ?? serverName,
copyServerInfo: true,
);
},
);
}
/// Core method to launch playback from a play queue.
Future<PlayQueueResult> _launchFromQueue({
required PlayQueueResponse? playQueue,
required String ratingKey,
String? serverId,
String? serverName,
PlexMetadata? selectedItem,
bool copyServerInfo = false,
}) async {
if (playQueue == null ||
playQueue.items == null ||
playQueue.items!.isEmpty) {
return const PlayQueueEmpty();
}
if (!context.mounted) return const PlayQueueError('Context not mounted');
// Set up playback state
final playbackState = context.read<PlaybackStateProvider>();
playbackState.setClient(client);
await playbackState.setPlaybackFromPlayQueue(
playQueue,
ratingKey,
serverId: serverId,
serverName: serverName,
);
if (!context.mounted) return const PlayQueueError('Context not mounted');
// Determine which item to navigate to
var itemToPlay = selectedItem ?? playQueue.items!.first;
// Copy server info if needed
if (copyServerInfo && serverId != null) {
itemToPlay = itemToPlay.copyWith(
serverId: serverId,
serverName: serverName,
);
}
// Navigate to video player
await navigateToVideoPlayer(context, metadata: itemToPlay);
return const PlayQueueSuccess();
}
/// Execute an action with optional loading indicator and error handling.
Future<PlayQueueResult> _executeWithLoading({
required bool showLoading,
required String action,
required Future<PlayQueueResult> Function() execute,
}) async {
try {
// Show loading indicator
if (showLoading && context.mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) =>
const Center(child: CircularProgressIndicator()),
);
}
final result = await execute();
// Close loading indicator
if (showLoading && context.mounted && Navigator.canPop(context)) {
Navigator.pop(context);
}
// Handle empty queue result
if (result is PlayQueueEmpty && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.messages.failedToCreatePlayQueueNoItems)),
);
}
return result;
} catch (e) {
appLogger.e('Failed to $action', error: e);
// Close loading indicator if it's still open
if (showLoading && context.mounted && Navigator.canPop(context)) {
Navigator.pop(context);
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
t.messages.failedPlayback(action: action, error: e.toString()),
),
),
);
}
return PlayQueueError(e);
}
}
}
+98 -108
View File
@@ -1,9 +1,9 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import 'package:plezy/utils/app_logger.dart';
import '../i18n/strings.g.dart';
import 'base_shared_preferences_service.dart';
enum ThemeMode { system, light, dark }
@@ -11,7 +11,7 @@ enum LibraryDensity { compact, normal, comfortable }
enum ViewMode { grid, list }
class SettingsService {
class SettingsService extends BaseSharedPreferencesService {
static const String _keyThemeMode = 'theme_mode';
static const String _keyEnableDebugLogging = 'enable_debug_logging';
static const String _keyBufferSize = 'buffer_size';
@@ -46,30 +46,21 @@ class SettingsService {
static const String _keyAutoSkipCredits = 'auto_skip_credits';
static const String _keyAutoSkipDelay = 'auto_skip_delay';
static SettingsService? _instance;
late SharedPreferences _prefs;
SettingsService._();
static Future<SettingsService> getInstance() async {
if (_instance == null) {
_instance = SettingsService._();
await _instance!._init();
}
return _instance!;
}
Future<void> _init() async {
_prefs = await SharedPreferences.getInstance();
return BaseSharedPreferencesService.initializeInstance(
() => SettingsService._(),
);
}
// Theme Mode
Future<void> setThemeMode(ThemeMode mode) async {
await _prefs.setString(_keyThemeMode, mode.name);
await prefs.setString(_keyThemeMode, mode.name);
}
ThemeMode getThemeMode() {
final modeString = _prefs.getString(_keyThemeMode);
final modeString = prefs.getString(_keyThemeMode);
return ThemeMode.values.firstWhere(
(mode) => mode.name == modeString,
orElse: () => ThemeMode.system,
@@ -78,68 +69,67 @@ class SettingsService {
// Debug Logging
Future<void> setEnableDebugLogging(bool enabled) async {
await _prefs.setBool(_keyEnableDebugLogging, enabled);
await prefs.setBool(_keyEnableDebugLogging, enabled);
// Update logger level immediately when setting changes
setLoggerLevel(enabled);
}
bool getEnableDebugLogging() {
return _prefs.getBool(_keyEnableDebugLogging) ?? false;
return prefs.getBool(_keyEnableDebugLogging) ?? false;
}
// Buffer Size (in MB)
Future<void> setBufferSize(int sizeInMB) async {
await _prefs.setInt(_keyBufferSize, sizeInMB);
await prefs.setInt(_keyBufferSize, sizeInMB);
}
int getBufferSize() {
return _prefs.getInt(_keyBufferSize) ?? 128; // Default 128MB
return prefs.getInt(_keyBufferSize) ?? 128; // Default 128MB
}
// Hardware Decoding
Future<void> setEnableHardwareDecoding(bool enabled) async {
await _prefs.setBool(_keyEnableHardwareDecoding, enabled);
await prefs.setBool(_keyEnableHardwareDecoding, enabled);
}
bool getEnableHardwareDecoding() {
return _prefs.getBool(_keyEnableHardwareDecoding) ??
true; // Default enabled
return prefs.getBool(_keyEnableHardwareDecoding) ?? true; // Default enabled
}
// HDR (High Dynamic Range)
Future<void> setEnableHDR(bool enabled) async {
await _prefs.setBool(_keyEnableHDR, enabled);
await prefs.setBool(_keyEnableHDR, enabled);
}
bool getEnableHDR() {
return _prefs.getBool(_keyEnableHDR) ?? true; // Default enabled
return prefs.getBool(_keyEnableHDR) ?? true; // Default enabled
}
// Preferred Video Codec
Future<void> setPreferredVideoCodec(String codec) async {
await _prefs.setString(_keyPreferredVideoCodec, codec);
await prefs.setString(_keyPreferredVideoCodec, codec);
}
String getPreferredVideoCodec() {
return _prefs.getString(_keyPreferredVideoCodec) ?? 'auto';
return prefs.getString(_keyPreferredVideoCodec) ?? 'auto';
}
// Preferred Audio Codec
Future<void> setPreferredAudioCodec(String codec) async {
await _prefs.setString(_keyPreferredAudioCodec, codec);
await prefs.setString(_keyPreferredAudioCodec, codec);
}
String getPreferredAudioCodec() {
return _prefs.getString(_keyPreferredAudioCodec) ?? 'auto';
return prefs.getString(_keyPreferredAudioCodec) ?? 'auto';
}
// Library Density
Future<void> setLibraryDensity(LibraryDensity density) async {
await _prefs.setString(_keyLibraryDensity, density.name);
await prefs.setString(_keyLibraryDensity, density.name);
}
LibraryDensity getLibraryDensity() {
final densityString = _prefs.getString(_keyLibraryDensity);
final densityString = prefs.getString(_keyLibraryDensity);
return LibraryDensity.values.firstWhere(
(density) => density.name == densityString,
orElse: () => LibraryDensity.normal,
@@ -148,11 +138,11 @@ class SettingsService {
// View Mode
Future<void> setViewMode(ViewMode mode) async {
await _prefs.setString(_keyViewMode, mode.name);
await prefs.setString(_keyViewMode, mode.name);
}
ViewMode getViewMode() {
final modeString = _prefs.getString(_keyViewMode);
final modeString = prefs.getString(_keyViewMode);
return ViewMode.values.firstWhere(
(mode) => mode.name == modeString,
orElse: () => ViewMode.grid,
@@ -161,86 +151,86 @@ class SettingsService {
// Use Season Poster
Future<void> setUseSeasonPoster(bool enabled) async {
await _prefs.setBool(_keyUseSeasonPoster, enabled);
await prefs.setBool(_keyUseSeasonPoster, enabled);
}
bool getUseSeasonPoster() {
return _prefs.getBool(_keyUseSeasonPoster) ??
return prefs.getBool(_keyUseSeasonPoster) ??
false; // Default: false (use series poster)
}
// Show Hero Section
Future<void> setShowHeroSection(bool enabled) async {
await _prefs.setBool(_keyShowHeroSection, enabled);
await prefs.setBool(_keyShowHeroSection, enabled);
}
bool getShowHeroSection() {
return _prefs.getBool(_keyShowHeroSection) ??
return prefs.getBool(_keyShowHeroSection) ??
true; // Default: true (show hero section)
}
// Seek Time Small (in seconds)
Future<void> setSeekTimeSmall(int seconds) async {
await _prefs.setInt(_keySeekTimeSmall, seconds);
await prefs.setInt(_keySeekTimeSmall, seconds);
}
int getSeekTimeSmall() {
return _prefs.getInt(_keySeekTimeSmall) ?? 10; // Default: 10 seconds
return prefs.getInt(_keySeekTimeSmall) ?? 10; // Default: 10 seconds
}
// Seek Time Large (in seconds)
Future<void> setSeekTimeLarge(int seconds) async {
await _prefs.setInt(_keySeekTimeLarge, seconds);
await prefs.setInt(_keySeekTimeLarge, seconds);
}
int getSeekTimeLarge() {
return _prefs.getInt(_keySeekTimeLarge) ?? 30; // Default: 30 seconds
return prefs.getInt(_keySeekTimeLarge) ?? 30; // Default: 30 seconds
}
// Sleep Timer Duration (in minutes)
Future<void> setSleepTimerDuration(int minutes) async {
await _prefs.setInt(_keySleepTimerDuration, minutes);
await prefs.setInt(_keySleepTimerDuration, minutes);
}
int getSleepTimerDuration() {
return _prefs.getInt(_keySleepTimerDuration) ?? 30; // Default: 30 minutes
return prefs.getInt(_keySleepTimerDuration) ?? 30; // Default: 30 minutes
}
// Audio Sync Offset (in milliseconds)
Future<void> setAudioSyncOffset(int milliseconds) async {
await _prefs.setInt(_keyAudioSyncOffset, milliseconds);
await prefs.setInt(_keyAudioSyncOffset, milliseconds);
}
int getAudioSyncOffset() {
return _prefs.getInt(_keyAudioSyncOffset) ?? 0; // Default: 0ms (no offset)
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);
await prefs.setInt(_keySubtitleSyncOffset, milliseconds);
}
int getSubtitleSyncOffset() {
return _prefs.getInt(_keySubtitleSyncOffset) ??
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);
await prefs.setDouble(_keyVolume, volume);
}
double getVolume() {
return _prefs.getDouble(_keyVolume) ?? 100.0; // Default: full volume
return prefs.getDouble(_keyVolume) ?? 100.0; // Default: full volume
}
// Rotation Lock (mobile only)
Future<void> setRotationLocked(bool locked) async {
await _prefs.setBool(_keyRotationLocked, locked);
await prefs.setBool(_keyRotationLocked, locked);
}
bool getRotationLocked() {
return _prefs.getBool(_keyRotationLocked) ??
return prefs.getBool(_keyRotationLocked) ??
true; // Default: locked (landscape only)
}
@@ -248,56 +238,56 @@ class SettingsService {
// Font Size (30-80, default 55)
Future<void> setSubtitleFontSize(int size) async {
await _prefs.setInt(_keySubtitleFontSize, size);
await prefs.setInt(_keySubtitleFontSize, size);
}
int getSubtitleFontSize() {
return _prefs.getInt(_keySubtitleFontSize) ?? 55;
return prefs.getInt(_keySubtitleFontSize) ?? 55;
}
// Text Color (hex format #RRGGBB, default white)
Future<void> setSubtitleTextColor(String color) async {
await _prefs.setString(_keySubtitleTextColor, color);
await prefs.setString(_keySubtitleTextColor, color);
}
String getSubtitleTextColor() {
return _prefs.getString(_keySubtitleTextColor) ?? '#FFFFFF';
return prefs.getString(_keySubtitleTextColor) ?? '#FFFFFF';
}
// Border Size (0-5, default 3)
Future<void> setSubtitleBorderSize(int size) async {
await _prefs.setInt(_keySubtitleBorderSize, size);
await prefs.setInt(_keySubtitleBorderSize, size);
}
int getSubtitleBorderSize() {
return _prefs.getInt(_keySubtitleBorderSize) ?? 3;
return prefs.getInt(_keySubtitleBorderSize) ?? 3;
}
// Border Color (hex format #RRGGBB, default black)
Future<void> setSubtitleBorderColor(String color) async {
await _prefs.setString(_keySubtitleBorderColor, color);
await prefs.setString(_keySubtitleBorderColor, color);
}
String getSubtitleBorderColor() {
return _prefs.getString(_keySubtitleBorderColor) ?? '#000000';
return prefs.getString(_keySubtitleBorderColor) ?? '#000000';
}
// Background Color (hex format #RRGGBB, default black)
Future<void> setSubtitleBackgroundColor(String color) async {
await _prefs.setString(_keySubtitleBackgroundColor, color);
await prefs.setString(_keySubtitleBackgroundColor, color);
}
String getSubtitleBackgroundColor() {
return _prefs.getString(_keySubtitleBackgroundColor) ?? '#000000';
return prefs.getString(_keySubtitleBackgroundColor) ?? '#000000';
}
// Background Opacity (0-100, default 0 for transparent)
Future<void> setSubtitleBackgroundOpacity(int opacity) async {
await _prefs.setInt(_keySubtitleBackgroundOpacity, opacity);
await prefs.setInt(_keySubtitleBackgroundOpacity, opacity);
}
int getSubtitleBackgroundOpacity() {
return _prefs.getInt(_keySubtitleBackgroundOpacity) ?? 0;
return prefs.getInt(_keySubtitleBackgroundOpacity) ?? 0;
}
// Keyboard Shortcuts (Legacy String-based)
@@ -357,11 +347,11 @@ class SettingsService {
Future<void> setKeyboardShortcuts(Map<String, String> shortcuts) async {
final jsonString = json.encode(shortcuts);
await _prefs.setString(_keyKeyboardShortcuts, jsonString);
await prefs.setString(_keyKeyboardShortcuts, jsonString);
}
Map<String, String> getKeyboardShortcuts() {
final jsonString = _prefs.getString(_keyKeyboardShortcuts);
final jsonString = prefs.getString(_keyKeyboardShortcuts);
if (jsonString == null) return getDefaultKeyboardShortcuts();
try {
@@ -401,11 +391,11 @@ class SettingsService {
serializedHotkeys[entry.key] = _serializeHotKey(entry.value);
}
final jsonString = json.encode(serializedHotkeys);
await _prefs.setString(_keyKeyboardHotkeys, jsonString);
await prefs.setString(_keyKeyboardHotkeys, jsonString);
}
Future<Map<String, HotKey>> getKeyboardHotkeys() async {
final jsonString = _prefs.getString(_keyKeyboardHotkeys);
final jsonString = prefs.getString(_keyKeyboardHotkeys);
if (jsonString == null) {
return getDefaultKeyboardHotkeys();
}
@@ -763,7 +753,7 @@ class SettingsService {
preferences[seriesRatingKey] = mediaIndex;
final jsonString = json.encode(preferences);
await _prefs.setString(_keyMediaVersionPreferences, jsonString);
await prefs.setString(_keyMediaVersionPreferences, jsonString);
}
/// Get saved media version preference for a series
@@ -779,12 +769,12 @@ class SettingsService {
preferences.remove(seriesRatingKey);
final jsonString = json.encode(preferences);
await _prefs.setString(_keyMediaVersionPreferences, jsonString);
await prefs.setString(_keyMediaVersionPreferences, jsonString);
}
/// Get all media version preferences
Map<String, int> _getMediaVersionPreferences() {
final jsonString = _prefs.getString(_keyMediaVersionPreferences);
final jsonString = prefs.getString(_keyMediaVersionPreferences);
if (jsonString == null) return {};
final decoded = _decodeJsonStringToMap(jsonString);
@@ -802,11 +792,11 @@ class SettingsService {
// App Locale
Future<void> setAppLocale(AppLocale locale) async {
await _prefs.setString(_keyAppLocale, locale.languageCode);
await prefs.setString(_keyAppLocale, locale.languageCode);
}
AppLocale getAppLocale() {
final localeString = _prefs.getString(_keyAppLocale);
final localeString = prefs.getString(_keyAppLocale);
if (localeString == null) return AppLocale.en; // Default to English
return AppLocale.values.firstWhere(
@@ -819,71 +809,71 @@ class SettingsService {
/// Remember Track Selections - Save per-media audio/subtitle language preferences
Future<void> setRememberTrackSelections(bool value) async {
await _prefs.setBool(_keyRememberTrackSelections, value);
await prefs.setBool(_keyRememberTrackSelections, value);
}
bool getRememberTrackSelections() {
return _prefs.getBool(_keyRememberTrackSelections) ?? true;
return prefs.getBool(_keyRememberTrackSelections) ?? true;
}
// Auto Skip Intro
Future<void> setAutoSkipIntro(bool value) async {
await _prefs.setBool(_keyAutoSkipIntro, value);
await prefs.setBool(_keyAutoSkipIntro, value);
}
bool getAutoSkipIntro() {
return _prefs.getBool(_keyAutoSkipIntro) ?? true; // Default: enabled
return prefs.getBool(_keyAutoSkipIntro) ?? true; // Default: enabled
}
// Auto Skip Credits
Future<void> setAutoSkipCredits(bool value) async {
await _prefs.setBool(_keyAutoSkipCredits, value);
await prefs.setBool(_keyAutoSkipCredits, value);
}
bool getAutoSkipCredits() {
return _prefs.getBool(_keyAutoSkipCredits) ?? true; // Default: enabled
return prefs.getBool(_keyAutoSkipCredits) ?? true; // Default: enabled
}
// Auto Skip Delay (in seconds)
Future<void> setAutoSkipDelay(int seconds) async {
await _prefs.setInt(_keyAutoSkipDelay, seconds);
await prefs.setInt(_keyAutoSkipDelay, seconds);
}
int getAutoSkipDelay() {
return _prefs.getInt(_keyAutoSkipDelay) ?? 5; // Default: 5 seconds
return prefs.getInt(_keyAutoSkipDelay) ?? 5; // Default: 5 seconds
}
// Reset all settings to defaults
Future<void> resetAllSettings() async {
await Future.wait([
_prefs.remove(_keyThemeMode),
_prefs.remove(_keyEnableDebugLogging),
_prefs.remove(_keyBufferSize),
_prefs.remove(_keyKeyboardShortcuts),
_prefs.remove(_keyKeyboardHotkeys),
_prefs.remove(_keyEnableHardwareDecoding),
_prefs.remove(_keyEnableHDR),
_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(_keyAppLocale),
_prefs.remove(_keyRememberTrackSelections),
prefs.remove(_keyThemeMode),
prefs.remove(_keyEnableDebugLogging),
prefs.remove(_keyBufferSize),
prefs.remove(_keyKeyboardShortcuts),
prefs.remove(_keyKeyboardHotkeys),
prefs.remove(_keyEnableHardwareDecoding),
prefs.remove(_keyEnableHDR),
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(_keyAppLocale),
prefs.remove(_keyRememberTrackSelections),
]);
}
+69 -75
View File
@@ -1,10 +1,9 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/log_redaction_manager.dart';
import 'base_shared_preferences_service.dart';
class StorageService {
class StorageService extends BaseSharedPreferencesService {
static const String _keyServerUrl = 'server_url';
static const String _keyToken = 'token';
static const String _keyPlexToken = 'plex_token';
@@ -23,21 +22,16 @@ class StorageService {
static const String _keyEnabledServers = 'enabled_servers';
static const String _keyServerOrder = 'server_order';
static StorageService? _instance;
late SharedPreferences _prefs;
StorageService._();
static Future<StorageService> getInstance() async {
if (_instance == null) {
_instance = StorageService._();
await _instance!._init();
}
return _instance!;
return BaseSharedPreferencesService.initializeInstance(
() => StorageService._(),
);
}
Future<void> _init() async {
_prefs = await SharedPreferences.getInstance();
@override
Future<void> onInit() async {
// Seed known values so logs can redact immediately on startup.
LogRedactionManager.registerServerUrl(getServerUrl());
LogRedactionManager.registerToken(getToken());
@@ -46,36 +40,36 @@ class StorageService {
// Server URL
Future<void> saveServerUrl(String url) async {
await _prefs.setString(_keyServerUrl, url);
await prefs.setString(_keyServerUrl, url);
LogRedactionManager.registerServerUrl(url);
}
String? getServerUrl() {
return _prefs.getString(_keyServerUrl);
return prefs.getString(_keyServerUrl);
}
// Per-Server Endpoint URL (for multi-server connection caching)
Future<void> saveServerEndpoint(String serverId, String url) async {
await _prefs.setString('server_endpoint_$serverId', url);
await prefs.setString('server_endpoint_$serverId', url);
LogRedactionManager.registerServerUrl(url);
}
String? getServerEndpoint(String serverId) {
return _prefs.getString('server_endpoint_$serverId');
return prefs.getString('server_endpoint_$serverId');
}
Future<void> clearServerEndpoint(String serverId) async {
await _prefs.remove('server_endpoint_$serverId');
await prefs.remove('server_endpoint_$serverId');
}
// Server Access Token
Future<void> saveToken(String token) async {
await _prefs.setString(_keyToken, token);
await prefs.setString(_keyToken, token);
LogRedactionManager.registerToken(token);
}
String? getToken() {
return _prefs.getString(_keyToken);
return prefs.getString(_keyToken);
}
// Alias for server access token for clarity
@@ -89,18 +83,18 @@ class StorageService {
// Plex.tv Token (for API access)
Future<void> savePlexToken(String token) async {
await _prefs.setString(_keyPlexToken, token);
await prefs.setString(_keyPlexToken, token);
LogRedactionManager.registerToken(token);
}
String? getPlexToken() {
return _prefs.getString(_keyPlexToken);
return prefs.getString(_keyPlexToken);
}
// Server Data (full PlexServer object as JSON)
Future<void> saveServerData(Map<String, dynamic> serverJson) async {
final jsonString = json.encode(serverJson);
await _prefs.setString(_keyServerData, jsonString);
await prefs.setString(_keyServerData, jsonString);
}
Map<String, dynamic>? getServerData() {
@@ -109,11 +103,11 @@ class StorageService {
// Client Identifier
Future<void> saveClientIdentifier(String clientId) async {
await _prefs.setString(_keyClientId, clientId);
await prefs.setString(_keyClientId, clientId);
}
String? getClientIdentifier() {
return _prefs.getString(_keyClientId);
return prefs.getString(_keyClientId);
}
// Save all credentials at once
@@ -137,15 +131,15 @@ class StorageService {
// Clear all credentials
Future<void> clearCredentials() async {
await Future.wait([
_prefs.remove(_keyServerUrl),
_prefs.remove(_keyToken),
_prefs.remove(_keyPlexToken),
_prefs.remove(_keyServerData),
_prefs.remove(_keyClientId),
_prefs.remove(_keyUserProfile),
_prefs.remove(_keyCurrentUserUUID),
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
prefs.remove(_keyServerUrl),
prefs.remove(_keyToken),
prefs.remove(_keyPlexToken),
prefs.remove(_keyServerData),
prefs.remove(_keyClientId),
prefs.remove(_keyUserProfile),
prefs.remove(_keyCurrentUserUUID),
prefs.remove(_keyHomeUsersCache),
prefs.remove(_keyHomeUsersCacheExpiry),
clearMultiServerData(),
]);
LogRedactionManager.clearTrackedValues();
@@ -161,16 +155,16 @@ class StorageService {
}
int? getSelectedLibraryIndex() {
return _prefs.getInt(_keySelectedLibraryIndex);
return prefs.getInt(_keySelectedLibraryIndex);
}
// Selected Library Key (replaces index-based selection)
Future<void> saveSelectedLibraryKey(String key) async {
await _prefs.setString(_keySelectedLibraryKey, key);
await prefs.setString(_keySelectedLibraryKey, key);
}
String? getSelectedLibraryKey() {
return _prefs.getString(_keySelectedLibraryKey);
return prefs.getString(_keySelectedLibraryKey);
}
// Library Filters (stored as JSON string)
@@ -182,7 +176,7 @@ class StorageService {
final key = sectionId != null
? 'library_filters_$sectionId'
: _keyLibraryFilters;
await _prefs.setString(key, jsonString);
await prefs.setString(key, jsonString);
}
Map<String, String> getLibraryFilters({String? sectionId}) {
@@ -192,9 +186,9 @@ class StorageService {
// Prefer per-library filters when available
final jsonString =
_prefs.getString(scopedKey) ??
prefs.getString(scopedKey) ??
// Legacy support: fall back to global filters if present
_prefs.getString(_keyLibraryFilters);
prefs.getString(_keyLibraryFilters);
if (jsonString == null) return {};
final decoded = _decodeJsonStringToMap(jsonString);
@@ -208,7 +202,7 @@ class StorageService {
bool descending = false,
}) async {
final sortData = {'key': sortKey, 'descending': descending};
await _prefs.setString('library_sort_$sectionId', json.encode(sortData));
await prefs.setString('library_sort_$sectionId', json.encode(sortData));
}
Map<String, dynamic>? getLibrarySort(String sectionId) {
@@ -217,31 +211,31 @@ class StorageService {
// Library Grouping (per-library, e.g., 'movies', 'shows', 'seasons', 'episodes')
Future<void> saveLibraryGrouping(String sectionId, String grouping) async {
await _prefs.setString('library_grouping_$sectionId', grouping);
await prefs.setString('library_grouping_$sectionId', grouping);
}
String? getLibraryGrouping(String sectionId) {
return _prefs.getString('library_grouping_$sectionId');
return prefs.getString('library_grouping_$sectionId');
}
// Library Tab (per-library, saves last selected tab index)
Future<void> saveLibraryTab(String sectionId, int tabIndex) async {
await _prefs.setInt('library_tab_$sectionId', tabIndex);
await prefs.setInt('library_tab_$sectionId', tabIndex);
}
int? getLibraryTab(String sectionId) {
return _prefs.getInt('library_tab_$sectionId');
return prefs.getInt('library_tab_$sectionId');
}
// Hidden Libraries (stored as JSON array of library section IDs)
Future<void> saveHiddenLibraries(Set<String> libraryKeys) async {
final list = libraryKeys.toList();
final jsonString = json.encode(list);
await _prefs.setString(_keyHiddenLibraries, jsonString);
await prefs.setString(_keyHiddenLibraries, jsonString);
}
Set<String> getHiddenLibraries() {
final jsonString = _prefs.getString(_keyHiddenLibraries);
final jsonString = prefs.getString(_keyHiddenLibraries);
if (jsonString == null) return {};
try {
@@ -255,22 +249,22 @@ class StorageService {
// Clear library preferences
Future<void> clearLibraryPreferences() async {
await Future.wait([
_prefs.remove(_keySelectedLibraryIndex),
_prefs.remove(_keyLibraryFilters),
_prefs.remove(_keyLibraryOrder),
_prefs.remove(_keyHiddenLibraries),
prefs.remove(_keySelectedLibraryIndex),
prefs.remove(_keyLibraryFilters),
prefs.remove(_keyLibraryOrder),
prefs.remove(_keyHiddenLibraries),
]);
// Also clear all library sort preferences
final keys = _prefs.getKeys();
final keys = prefs.getKeys();
final sortKeys = keys.where((key) => key.startsWith('library_sort_'));
await Future.wait(sortKeys.map((key) => _prefs.remove(key)));
await Future.wait(sortKeys.map((key) => prefs.remove(key)));
}
// Library Order (stored as JSON list of library keys)
Future<void> saveLibraryOrder(List<String> libraryKeys) async {
final jsonString = json.encode(libraryKeys);
await _prefs.setString(_keyLibraryOrder, jsonString);
await prefs.setString(_keyLibraryOrder, jsonString);
}
List<String>? getLibraryOrder() => _getStringList(_keyLibraryOrder);
@@ -278,7 +272,7 @@ class StorageService {
// User Profile (stored as JSON string)
Future<void> saveUserProfile(Map<String, dynamic> profileJson) async {
final jsonString = json.encode(profileJson);
await _prefs.setString(_keyUserProfile, jsonString);
await prefs.setString(_keyUserProfile, jsonString);
}
Map<String, dynamic>? getUserProfile() {
@@ -287,27 +281,27 @@ class StorageService {
// Current User UUID
Future<void> saveCurrentUserUUID(String uuid) async {
await _prefs.setString(_keyCurrentUserUUID, uuid);
await prefs.setString(_keyCurrentUserUUID, uuid);
}
String? getCurrentUserUUID() {
return _prefs.getString(_keyCurrentUserUUID);
return prefs.getString(_keyCurrentUserUUID);
}
// Home Users Cache (stored as JSON string with expiry)
Future<void> saveHomeUsersCache(Map<String, dynamic> homeData) async {
final jsonString = json.encode(homeData);
await _prefs.setString(_keyHomeUsersCache, jsonString);
await prefs.setString(_keyHomeUsersCache, jsonString);
// Set cache expiry to 1 hour from now
final expiry = DateTime.now()
.add(const Duration(hours: 1))
.millisecondsSinceEpoch;
await _prefs.setInt(_keyHomeUsersCacheExpiry, expiry);
await prefs.setInt(_keyHomeUsersCacheExpiry, expiry);
}
Map<String, dynamic>? getHomeUsersCache() {
final expiry = _prefs.getInt(_keyHomeUsersCacheExpiry);
final expiry = prefs.getInt(_keyHomeUsersCacheExpiry);
if (expiry == null || DateTime.now().millisecondsSinceEpoch > expiry) {
// Cache expired, clear it
clearHomeUsersCache();
@@ -319,14 +313,14 @@ class StorageService {
Future<void> clearHomeUsersCache() async {
await Future.wait([
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
prefs.remove(_keyHomeUsersCache),
prefs.remove(_keyHomeUsersCacheExpiry),
]);
}
// Clear current user UUID (for server switching)
Future<void> clearCurrentUserUUID() async {
await _prefs.remove(_keyCurrentUserUUID);
await prefs.remove(_keyCurrentUserUUID);
}
// Clear all user-related data (for logout)
@@ -346,38 +340,38 @@ class StorageService {
/// Get servers list as JSON string
String? getServersListJson() {
return _prefs.getString(_keyServersList);
return prefs.getString(_keyServersList);
}
/// Save servers list as JSON string
Future<void> saveServersListJson(String serversJson) async {
await _prefs.setString(_keyServersList, serversJson);
await prefs.setString(_keyServersList, serversJson);
}
/// Get enabled servers as JSON string
String? getEnabledServersJson() {
return _prefs.getString(_keyEnabledServers);
return prefs.getString(_keyEnabledServers);
}
/// Save enabled servers as JSON string
Future<void> saveEnabledServersJson(String enabledJson) async {
await _prefs.setString(_keyEnabledServers, enabledJson);
await prefs.setString(_keyEnabledServers, enabledJson);
}
/// Clear servers list
Future<void> clearServersList() async {
await _prefs.remove(_keyServersList);
await prefs.remove(_keyServersList);
}
/// Clear enabled servers
Future<void> clearEnabledServers() async {
await _prefs.remove(_keyEnabledServers);
await prefs.remove(_keyEnabledServers);
}
/// Clear all multi-server data
Future<void> clearMultiServerData() async {
// Clear all server endpoint caches
final keys = _prefs.getKeys();
final keys = prefs.getKeys();
final endpointKeys = keys.where(
(key) => key.startsWith('server_endpoint_'),
);
@@ -386,28 +380,28 @@ class StorageService {
clearServersList(),
clearEnabledServers(),
clearServerOrder(),
...endpointKeys.map((key) => _prefs.remove(key)),
...endpointKeys.map((key) => prefs.remove(key)),
]);
}
/// Server Order (stored as JSON list of server IDs)
Future<void> saveServerOrder(List<String> serverIds) async {
final jsonString = json.encode(serverIds);
await _prefs.setString(_keyServerOrder, jsonString);
await prefs.setString(_keyServerOrder, jsonString);
}
List<String>? getServerOrder() => _getStringList(_keyServerOrder);
/// Clear server order
Future<void> clearServerOrder() async {
await _prefs.remove(_keyServerOrder);
await prefs.remove(_keyServerOrder);
}
// Private helper methods
/// Helper to read and decode JSON `List<String>` from preferences
List<String>? _getStringList(String key) {
final jsonString = _prefs.getString(key);
final jsonString = prefs.getString(key);
if (jsonString == null) return null;
try {
@@ -427,7 +421,7 @@ class StorageService {
String key, {
bool legacyStringOk = false,
}) {
final jsonString = _prefs.getString(key);
final jsonString = prefs.getString(key);
if (jsonString == null) return null;
return _decodeJsonStringToMap(jsonString, legacyStringOk: legacyStringOk);
+38
View File
@@ -0,0 +1,38 @@
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
/// Service for detecting if the app is running on Android TV
class TvDetectionService {
static TvDetectionService? _instance;
bool _isTV = false;
bool _initialized = false;
TvDetectionService._();
/// Get the singleton instance, initializing if needed
static Future<TvDetectionService> getInstance() async {
if (_instance == null) {
_instance = TvDetectionService._();
await _instance!._detect();
}
return _instance!;
}
Future<void> _detect() async {
if (_initialized) return;
if (Platform.isAndroid) {
final deviceInfo = DeviceInfoPlugin();
final androidInfo = await deviceInfo.androidInfo;
// Check for android.software.leanback feature (standard Android TV detection)
_isTV = androidInfo.systemFeatures.contains('android.software.leanback');
}
_initialized = true;
}
bool get isTV => _isTV;
/// Synchronous access after initialization (returns false if not initialized)
static bool isTVSync() => _instance?._isTV ?? false;
}
-14
View File
@@ -49,20 +49,6 @@ class VideoFilterManager {
/// Current player size
Size? get playerSize => _playerSize;
/// Get current BoxFit based on mode
BoxFit get currentBoxFit {
switch (_boxFitMode) {
case 0:
return BoxFit.contain;
case 1:
return BoxFit.cover;
case 2:
return BoxFit.fill;
default:
return BoxFit.contain;
}
}
/// Cycle through BoxFit modes: contain → cover → fill → contain (for button)
void cycleBoxFitMode() {
_boxFitMode = (_boxFitMode + 1) % 3;
+19 -120
View File
@@ -1,133 +1,32 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/plex_client.dart';
import '../services/play_queue_launcher.dart';
import '../models/plex_metadata.dart';
import '../models/plex_playlist.dart';
import '../models/play_queue_response.dart';
import '../providers/playback_state_provider.dart';
import '../utils/app_logger.dart';
import '../utils/video_player_navigation.dart';
import '../i18n/strings.g.dart';
/// Helper function to play a collection or playlist
/// Helper function to play a collection or playlist.
///
/// This is a convenience wrapper around [PlayQueueLauncher.launchFromCollectionOrPlaylist].
Future<void> playCollectionOrPlaylist({
required BuildContext context,
required PlexClient client,
required dynamic item, // PlexMetadata (collection) or PlexPlaylist
required bool shuffle,
}) async {
try {
final isCollection = item is PlexMetadata;
final isPlaylist = item is PlexPlaylist;
final launcher = PlayQueueLauncher(
context: context,
client: client,
serverId: item is PlexMetadata
? item.serverId
: (item as PlexPlaylist).serverId,
serverName: item is PlexMetadata
? item.serverName
: (item as PlexPlaylist).serverName,
);
if (!isCollection && !isPlaylist) {
throw Exception('Item must be either a collection or playlist');
}
String ratingKey = item.ratingKey;
String? serverId = item.serverId;
String? serverName = item.serverName;
final PlayQueueResponse? playQueue;
if (isCollection) {
// Get machine identifier (fetch if not cached in config)
final machineId =
client.config.machineIdentifier ??
await client.getMachineIdentifier();
if (machineId == null) {
throw Exception('Could not get server machine identifier');
}
final collectionUri =
'server://$machineId/com.plexapp.plugins.library/library/collections/${item.ratingKey}';
playQueue = await client.createPlayQueue(
uri: collectionUri,
type: 'video',
shuffle: shuffle ? 1 : 0,
);
} else {
// For playlists, use playlistID parameter
playQueue = await client.createPlayQueue(
playlistID: int.parse(item.ratingKey),
type: 'video',
shuffle: shuffle ? 1 : 0,
);
}
// If the queue is empty, try fetching it again with getPlayQueue
if (playQueue != null &&
(playQueue.items == null || playQueue.items!.isEmpty)) {
final fetchedQueue = await client.getPlayQueue(playQueue.playQueueID);
if (fetchedQueue != null &&
fetchedQueue.items != null &&
fetchedQueue.items!.isNotEmpty) {
if (!context.mounted) return;
// Items are automatically tagged with server info by PlexClient
// Set play queue in provider
final playbackState = context.read<PlaybackStateProvider>();
playbackState.setClient(client);
await playbackState.setPlaybackFromPlayQueue(
fetchedQueue,
ratingKey,
serverId: serverId,
serverName: serverName,
);
if (!context.mounted) return;
// Navigate to first item
await navigateToVideoPlayer(
context,
metadata: fetchedQueue.items!.first,
);
return;
}
}
if (playQueue == null ||
playQueue.items == null ||
playQueue.items!.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.messages.failedToCreatePlayQueueNoItems)),
);
}
return;
}
if (!context.mounted) return;
// Items are automatically tagged with server info by PlexClient
// Set play queue in provider
final playbackState = context.read<PlaybackStateProvider>();
playbackState.setClient(client);
await playbackState.setPlaybackFromPlayQueue(
playQueue,
ratingKey,
serverId: serverId,
serverName: serverName,
);
if (!context.mounted) return;
// Navigate to first item
await navigateToVideoPlayer(context, metadata: playQueue.items!.first);
} catch (e) {
appLogger.e('Failed to ${shuffle ? "shuffle play" : "play"}', error: e);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
t.messages.failedPlayback(
action: shuffle ? t.common.shuffle : t.discover.play,
error: e.toString(),
),
),
),
);
}
}
await launcher.launchFromCollectionOrPlaylist(
item: item,
shuffle: shuffle,
showLoadingIndicator: false, // Caller typically handles loading UI
);
}
+54 -1
View File
@@ -2,6 +2,21 @@ import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import '../services/fullscreen_state_manager.dart';
/// InheritedWidget to indicate that a side navigation is present in the widget tree.
/// When present, app bars should skip their left padding since the side nav
/// already handles the macOS traffic lights area.
class SideNavigationScope extends InheritedWidget {
const SideNavigationScope({super.key, required super.child});
static bool isPresent(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<SideNavigationScope>() !=
null;
}
@override
bool updateShouldNotify(SideNavigationScope oldWidget) => false;
}
/// Padding values for desktop window controls
class DesktopWindowPadding {
/// Left padding for macOS traffic lights (normal window mode)
@@ -45,14 +60,28 @@ class DesktopAppBarHelper {
/// Builds leading widget with appropriate left padding for macOS traffic lights
///
/// [includeGestureDetector] - If true, wraps in GestureDetector to prevent window dragging
/// [context] - Required to check if side navigation is visible
static Widget? buildAdjustedLeading(
Widget? leading, {
bool includeGestureDetector = false,
BuildContext? context,
}) {
if (!Platform.isMacOS || leading == null) {
return leading;
}
// Skip left padding when side navigation scope is present in widget tree
if (context != null && SideNavigationScope.isPresent(context)) {
if (includeGestureDetector) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) {},
child: leading,
);
}
return leading;
}
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
@@ -94,11 +123,20 @@ class DesktopAppBarHelper {
}
/// Calculates the leading width for SliverAppBar to account for macOS traffic lights
static double? calculateLeadingWidth(Widget? leading) {
/// [context] - Required to check if side navigation is visible
static double? calculateLeadingWidth(
Widget? leading, {
BuildContext? context,
}) {
if (!Platform.isMacOS || leading == null) {
return null;
}
// Skip extra width when side navigation scope is present in widget tree
if (context != null && SideNavigationScope.isPresent(context)) {
return null;
}
final isFullscreen = FullscreenStateManager().isFullscreen;
final leftPadding = isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
@@ -125,6 +163,8 @@ class DesktopAppBarHelper {
/// A widget that adds padding to account for desktop window controls.
/// On macOS, adds left padding for traffic lights (reduced in fullscreen).
/// When side navigation is visible, left padding is skipped as the side nav
/// already occupies the traffic lights area.
class DesktopTitleBarPadding extends StatelessWidget {
final Widget child;
final double? leftPadding;
@@ -143,6 +183,19 @@ class DesktopTitleBarPadding extends StatelessWidget {
return child;
}
// Skip left padding when side navigation scope is present in widget tree
// (side nav already handles the traffic lights area)
if (SideNavigationScope.isPresent(context)) {
final right = rightPadding ?? 0.0;
if (right == 0.0) {
return child;
}
return Padding(
padding: EdgeInsets.only(right: right),
child: child,
);
}
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
-23
View File
@@ -1,23 +0,0 @@
import 'package:flutter/services.dart';
/// Check if a logical key is a back navigation key
bool isBackKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.escape ||
key == LogicalKeyboardKey.backspace ||
key == LogicalKeyboardKey.goBack ||
key == LogicalKeyboardKey.gameButtonB;
}
/// Check if a key event is a back navigation key down event
bool isBackKeyEvent(KeyEvent event) {
if (event is! KeyDownEvent) return false;
return isBackKey(event.logicalKey);
}
/// Check if the given key should activate/select an item
bool isKeyboardActivationKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.space ||
key == LogicalKeyboardKey.select ||
key == LogicalKeyboardKey.gameButtonA;
}
+60
View File
@@ -0,0 +1,60 @@
import 'package:flutter/material.dart';
import '../models/plex_metadata.dart';
import '../models/plex_playlist.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import '../screens/playlist/playlist_detail_screen.dart';
import 'video_player_navigation.dart';
/// Navigates to the appropriate screen based on the item type.
///
/// For episodes, starts playback directly via video player.
/// For seasons, navigates to season detail screen.
/// For playlists, navigates to playlist detail screen.
/// For other types (shows, movies), navigates to media detail screen.
///
/// The [onRefresh] callback is invoked with the item's ratingKey after
/// returning from the detail screen, allowing the caller to refresh state.
Future<void> navigateToMediaItem(
BuildContext context,
dynamic item, {
void Function(String)? onRefresh,
}) async {
// Handle playlists
if (item is PlexPlaylist) {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PlaylistDetailScreen(playlist: item),
),
);
return;
}
final itemType = (item as PlexMetadata).type.toLowerCase();
// For episodes, start playback directly
if (itemType == 'episode') {
final result = await navigateToVideoPlayer(context, metadata: item);
if (result == true) {
onRefresh?.call(item.ratingKey);
}
} else if (itemType == 'season') {
await Navigator.push(
context,
MaterialPageRoute(builder: (context) => SeasonDetailScreen(season: item)),
);
onRefresh?.call(item.ratingKey);
} else {
// For all other types (shows, movies), show detail screen
final result = await Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) => MediaDetailScreen(metadata: item),
),
);
if (result == true) {
onRefresh?.call(item.ratingKey);
}
}
}
+12
View File
@@ -1,8 +1,20 @@
import 'package:flutter/material.dart';
import 'dart:math';
import '../services/tv_detection_service.dart';
/// Utility class for platform detection
class PlatformDetector {
/// Detects if running on Android TV (requires TvDetectionService to be initialized)
static bool isTV() {
return TvDetectionService.isTVSync();
}
/// Detects if the app should use side navigation (Desktop or TV)
static bool shouldUseSideNavigation(BuildContext context) {
return isDesktop(context) || isTV();
}
/// Detects if running on a mobile platform (iOS or Android)
/// Uses Theme for consistent platform detection across the app
static bool isMobile(BuildContext context) {
@@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import '../services/settings_service.dart';
import 'grid_size_calculator.dart';
/// Builds an adaptive Sliver widget that switches between grid and list
/// based on the current view mode setting.
///
/// This helper consolidates the list vs grid Sliver builders to keep
/// padding and density logic in sync across different screens.
Widget buildAdaptiveMediaSliverBuilder<T>({
required BuildContext context,
required List<T> items,
required Widget Function(BuildContext context, T item, int index) itemBuilder,
required ViewMode viewMode,
required LibraryDensity density,
EdgeInsets padding = const EdgeInsets.all(16),
double childAspectRatio = 2 / 3.3,
double crossAxisSpacing = 8,
double mainAxisSpacing = 8,
}) {
if (viewMode == ViewMode.list) {
return SliverPadding(
padding: padding,
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final item = items[index];
return itemBuilder(context, item, index);
}, childCount: items.length),
),
);
} else {
return SliverPadding(
padding: padding,
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
density,
),
childAspectRatio: childAspectRatio,
crossAxisSpacing: crossAxisSpacing,
mainAxisSpacing: mainAxisSpacing,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = items[index];
return itemBuilder(context, item, index);
}, childCount: items.length),
),
);
}
}
+7 -2
View File
@@ -144,15 +144,20 @@ class _AppBarBackButtonState extends State<AppBarBackButton>
_backgroundAnimation.value,
);
final isPlain = widget.style == BackButtonStyle.plain;
return Container(
margin: const EdgeInsets.all(8),
margin: isPlain ? EdgeInsets.zero : const EdgeInsets.all(8),
width: 40,
height: 40,
decoration: BoxDecoration(
color: currentColor,
shape: BoxShape.circle,
),
child: Icon(Icons.arrow_back, color: effectiveColor, size: 20),
child: Icon(
Icons.arrow_back,
color: effectiveColor,
size: isPlain ? 24 : 20,
),
);
},
),
+191 -63
View File
@@ -3,6 +3,102 @@ import '../utils/desktop_window_padding.dart';
import '../services/fullscreen_state_manager.dart';
import 'app_bar_back_button.dart';
/// Configuration class for common app bar properties.
/// Reduces duplication between different app bar implementations.
class DesktopAppBarConfig {
final Widget? title;
final List<Widget>? actions;
final double? elevation;
final Color? backgroundColor;
final Color? surfaceTintColor;
final Color? shadowColor;
final double? scrolledUnderElevation;
final bool floating;
final bool pinned;
final double? expandedHeight;
final Widget? flexibleSpace;
final PreferredSizeWidget? bottom;
const DesktopAppBarConfig({
this.title,
this.actions,
this.elevation,
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.scrolledUnderElevation,
this.floating = false,
this.pinned = false,
this.expandedHeight,
this.flexibleSpace,
this.bottom,
});
}
/// Helper class for building app bar sections with consistent desktop behavior.
class DesktopAppBarSections {
/// Builds the leading section with proper padding and back button handling.
static Widget? buildLeadingSection({
Widget? leading,
bool automaticallyImplyLeading = true,
required BuildContext context,
}) {
Widget? effectiveLeading = leading;
// If no leading is provided but automaticallyImplyLeading is true,
// create a back button manually so it goes through our padding logic
if (leading == null && automaticallyImplyLeading) {
final parentRoute = ModalRoute.of(context);
final canPop = parentRoute?.canPop ?? false;
if (canPop) {
effectiveLeading = IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
);
}
}
return DesktopAppBarHelper.buildAdjustedLeading(
effectiveLeading,
includeGestureDetector: true,
context: context,
);
}
/// Builds the title section with proper padding.
static Widget? buildTitleSection({
required Widget? title,
required Widget? leading,
}) {
if (title == null) return null;
return DesktopTitleBarPadding(
leftPadding: leading != null ? 0 : null,
child: title,
);
}
/// Builds the actions section with proper padding.
static List<Widget>? buildActionsSection(List<Widget>? actions) {
return DesktopAppBarHelper.buildAdjustedActions(actions);
}
/// Calculates the leading width for the app bar.
static double? calculateLeadingWidthForSection({
required Widget? leading,
required BuildContext context,
}) {
return DesktopAppBarHelper.calculateLeadingWidth(leading, context: context);
}
/// Builds the flexible space section with gesture handling.
static Widget? buildFlexibleSpaceSection(Widget? flexibleSpace) {
return DesktopAppBarHelper.buildAdjustedFlexibleSpace(flexibleSpace);
}
}
/// A custom sliver app bar that automatically handles desktop window controls spacing.
/// Use this instead of SliverAppBar for consistent desktop platform behavior.
class DesktopSliverAppBar extends StatelessWidget {
@@ -41,37 +137,23 @@ class DesktopSliverAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Determine the effective leading widget
Widget? effectiveLeading = leading;
// If no leading is provided but automaticallyImplyLeading is true,
// create a back button manually so it goes through our padding logic
if (leading == null && automaticallyImplyLeading) {
final parentRoute = ModalRoute.of(context);
final canPop = parentRoute?.canPop ?? false;
if (canPop) {
effectiveLeading = IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
);
}
}
final effectiveLeading = DesktopAppBarSections.buildLeadingSection(
leading: leading,
automaticallyImplyLeading: automaticallyImplyLeading,
context: context,
);
return SliverAppBar(
title: title != null
? DesktopTitleBarPadding(
leftPadding: effectiveLeading != null ? 0 : null,
child: title!,
)
: null,
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
leading: DesktopAppBarHelper.buildAdjustedLeading(
effectiveLeading,
includeGestureDetector: true,
title: DesktopAppBarSections.buildTitleSection(
title: title,
leading: effectiveLeading,
),
actions: DesktopAppBarSections.buildActionsSection(actions),
leading: effectiveLeading,
leadingWidth: DesktopAppBarSections.calculateLeadingWidthForSection(
leading: effectiveLeading,
context: context,
),
leadingWidth: DesktopAppBarHelper.calculateLeadingWidth(effectiveLeading),
automaticallyImplyLeading:
false, // Always false since we handle it manually
elevation: elevation,
@@ -82,7 +164,7 @@ class DesktopSliverAppBar extends StatelessWidget {
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: DesktopAppBarHelper.buildAdjustedFlexibleSpace(
flexibleSpace: DesktopAppBarSections.buildFlexibleSpaceSection(
flexibleSpace,
),
bottom: bottom,
@@ -90,7 +172,69 @@ class DesktopSliverAppBar extends StatelessWidget {
}
}
/// Convenient wrapper for DesktopSliverAppBar with built-in back button handling
/// Unified widget for desktop top bars that handles fullscreen state and back button logic.
/// Reduces UI drift by centralizing the app bar implementation.
class DesktopTopBar extends StatelessWidget {
final DesktopAppBarConfig config;
final Widget? leading;
final VoidCallback? onBackPressed;
final bool automaticallyImplyLeading;
const DesktopTopBar({
super.key,
required this.config,
this.leading,
this.onBackPressed,
this.automaticallyImplyLeading = true,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
// Determine the effective leading widget
Widget? effectiveLeading = leading;
if (effectiveLeading == null && automaticallyImplyLeading) {
final parentRoute = ModalRoute.of(context);
final canPop = parentRoute?.canPop ?? false;
if (canPop) {
effectiveLeading = AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: onBackPressed,
);
}
}
return DesktopSliverAppBar(
key: ValueKey('desktop_top_bar_$isFullscreen'),
title: config.title,
actions: config.actions,
leading: effectiveLeading,
automaticallyImplyLeading: false,
elevation: config.elevation,
backgroundColor: config.backgroundColor,
surfaceTintColor: config.surfaceTintColor,
shadowColor: config.shadowColor,
scrolledUnderElevation: config.scrolledUnderElevation,
floating: config.floating,
pinned: config.pinned,
expandedHeight: config.expandedHeight,
flexibleSpace: config.flexibleSpace,
bottom: config.bottom,
);
},
);
}
}
/// Convenient wrapper for DesktopSliverAppBar with built-in back button handling.
///
/// This widget is maintained for backward compatibility. For new code, consider
/// using [DesktopTopBar] directly for a more unified approach.
class CustomAppBar extends StatelessWidget {
final Widget? title;
final List<Widget>? actions;
@@ -125,39 +269,23 @@ class CustomAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
return DesktopSliverAppBar(
key: ValueKey('plex_sliver_app_bar_$isFullscreen'),
title: title,
actions: actions,
leading: _shouldShowBackButton(context)
? AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: onBackPressed,
)
: null,
automaticallyImplyLeading: false,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: flexibleSpace,
bottom: bottom,
);
},
return DesktopTopBar(
config: DesktopAppBarConfig(
title: title,
actions: actions,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: flexibleSpace,
bottom: bottom,
),
onBackPressed: onBackPressed,
automaticallyImplyLeading: true,
);
}
bool _shouldShowBackButton(BuildContext context) {
final parentRoute = ModalRoute.of(context);
return parentRoute?.canPop ?? false;
}
}
+193 -158
View File
@@ -1,8 +1,9 @@
import 'package:flutter/material.dart';
import '../models/plex_file_info.dart';
import '../i18n/strings.g.dart';
import 'focusable_bottom_sheet.dart';
class FileInfoBottomSheet extends StatelessWidget {
class FileInfoBottomSheet extends StatefulWidget {
final PlexFileInfo fileInfo;
final String title;
@@ -12,174 +13,208 @@ class FileInfoBottomSheet extends StatelessWidget {
required this.title,
});
@override
State<FileInfoBottomSheet> createState() => _FileInfoBottomSheetState();
}
class _FileInfoBottomSheetState extends State<FileInfoBottomSheet> {
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_initialFocusNode = FocusNode(
debugLabel: 'FileInfoBottomSheetInitialFocus',
);
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.grey[900],
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: Container(
decoration: BoxDecoration(
color: Colors.grey[900],
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
),
),
),
child: SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
// Header
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(
Icons.info_outline,
color: Colors.white,
size: 24,
),
const SizedBox(width: 12),
Expanded(
child: Text(
t.fileInfo.title,
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
child: SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
// Header
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(
Icons.info_outline,
color: Colors.white,
size: 24,
),
const SizedBox(width: 12),
Expanded(
child: Text(
t.fileInfo.title,
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
IconButton(
focusNode: _initialFocusNode,
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
),
const Divider(color: Colors.grey, height: 1),
// Content
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
// Title
if (title.isNotEmpty) ...[
Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500,
const Divider(color: Colors.grey, height: 1),
// Content
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
// Title
if (widget.title.isNotEmpty) ...[
Text(
widget.title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 20),
],
// Video Section
_buildSectionHeader(t.fileInfo.video),
const SizedBox(height: 8),
_buildInfoRow(
t.fileInfo.codec,
widget.fileInfo.videoCodec ?? t.common.unknown,
),
_buildInfoRow(
t.fileInfo.resolution,
widget.fileInfo.resolutionFormatted,
),
_buildInfoRow(
t.fileInfo.bitrate,
widget.fileInfo.bitrateFormatted,
),
_buildInfoRow(
t.fileInfo.frameRate,
widget.fileInfo.frameRateFormatted,
),
_buildInfoRow(
t.fileInfo.aspectRatio,
widget.fileInfo.aspectRatioFormatted,
),
if (widget.fileInfo.videoProfile != null)
_buildInfoRow(
t.fileInfo.profile,
widget.fileInfo.videoProfile!,
),
if (widget.fileInfo.bitDepth != null)
_buildInfoRow(
t.fileInfo.bitDepth,
'${widget.fileInfo.bitDepth} bit',
),
if (widget.fileInfo.colorSpace != null)
_buildInfoRow(
t.fileInfo.colorSpace,
widget.fileInfo.colorSpace!,
),
if (widget.fileInfo.colorRange != null)
_buildInfoRow(
t.fileInfo.colorRange,
widget.fileInfo.colorRange!,
),
if (widget.fileInfo.colorPrimaries != null)
_buildInfoRow(
t.fileInfo.colorPrimaries,
widget.fileInfo.colorPrimaries!,
),
if (widget.fileInfo.chromaSubsampling != null)
_buildInfoRow(
t.fileInfo.chromaSubsampling,
widget.fileInfo.chromaSubsampling!,
),
const SizedBox(height: 20),
// Audio Section
_buildSectionHeader(t.fileInfo.audio),
const SizedBox(height: 8),
_buildInfoRow(
t.fileInfo.codec,
widget.fileInfo.audioCodec ?? t.common.unknown,
),
_buildInfoRow(
t.fileInfo.channels,
widget.fileInfo.audioChannelsFormatted,
),
if (widget.fileInfo.audioProfile != null)
_buildInfoRow(
t.fileInfo.profile,
widget.fileInfo.audioProfile!,
),
const SizedBox(height: 20),
// File Section
_buildSectionHeader(t.fileInfo.file),
const SizedBox(height: 8),
if (widget.fileInfo.filePath != null)
_buildInfoRow(
t.fileInfo.path,
widget.fileInfo.filePath!,
isMonospace: true,
),
_buildInfoRow(
t.fileInfo.size,
widget.fileInfo.fileSizeFormatted,
),
_buildInfoRow(
t.fileInfo.container,
widget.fileInfo.container ?? t.common.unknown,
),
_buildInfoRow(
t.fileInfo.duration,
widget.fileInfo.durationFormatted,
),
const SizedBox(height: 20),
// Advanced Section
_buildSectionHeader(t.fileInfo.advanced),
const SizedBox(height: 8),
_buildInfoRow(
t.fileInfo.optimizedForStreaming,
widget.fileInfo.optimizedForStreaming == true
? t.common.yes
: t.common.no,
),
_buildInfoRow(
t.fileInfo.has64bitOffsets,
widget.fileInfo.has64bitOffsets == true
? t.common.yes
: t.common.no,
),
],
// Video Section
_buildSectionHeader(t.fileInfo.video),
const SizedBox(height: 8),
_buildInfoRow(
t.fileInfo.codec,
fileInfo.videoCodec ?? t.common.unknown,
),
_buildInfoRow(
t.fileInfo.resolution,
fileInfo.resolutionFormatted,
),
_buildInfoRow(
t.fileInfo.bitrate,
fileInfo.bitrateFormatted,
),
_buildInfoRow(
t.fileInfo.frameRate,
fileInfo.frameRateFormatted,
),
_buildInfoRow(
t.fileInfo.aspectRatio,
fileInfo.aspectRatioFormatted,
),
if (fileInfo.videoProfile != null)
_buildInfoRow(t.fileInfo.profile, fileInfo.videoProfile!),
if (fileInfo.bitDepth != null)
_buildInfoRow(
t.fileInfo.bitDepth,
'${fileInfo.bitDepth} bit',
),
if (fileInfo.colorSpace != null)
_buildInfoRow(
t.fileInfo.colorSpace,
fileInfo.colorSpace!,
),
if (fileInfo.colorRange != null)
_buildInfoRow(
t.fileInfo.colorRange,
fileInfo.colorRange!,
),
if (fileInfo.colorPrimaries != null)
_buildInfoRow(
t.fileInfo.colorPrimaries,
fileInfo.colorPrimaries!,
),
if (fileInfo.chromaSubsampling != null)
_buildInfoRow(
t.fileInfo.chromaSubsampling,
fileInfo.chromaSubsampling!,
),
const SizedBox(height: 20),
// Audio Section
_buildSectionHeader(t.fileInfo.audio),
const SizedBox(height: 8),
_buildInfoRow(
t.fileInfo.codec,
fileInfo.audioCodec ?? t.common.unknown,
),
_buildInfoRow(
t.fileInfo.channels,
fileInfo.audioChannelsFormatted,
),
if (fileInfo.audioProfile != null)
_buildInfoRow(t.fileInfo.profile, fileInfo.audioProfile!),
const SizedBox(height: 20),
// File Section
_buildSectionHeader(t.fileInfo.file),
const SizedBox(height: 8),
if (fileInfo.filePath != null)
_buildInfoRow(
t.fileInfo.path,
fileInfo.filePath!,
isMonospace: true,
),
_buildInfoRow(t.fileInfo.size, fileInfo.fileSizeFormatted),
_buildInfoRow(
t.fileInfo.container,
fileInfo.container ?? t.common.unknown,
),
_buildInfoRow(
t.fileInfo.duration,
fileInfo.durationFormatted,
),
const SizedBox(height: 20),
// Advanced Section
_buildSectionHeader(t.fileInfo.advanced),
const SizedBox(height: 8),
_buildInfoRow(
t.fileInfo.optimizedForStreaming,
fileInfo.optimizedForStreaming == true
? t.common.yes
: t.common.no,
),
_buildInfoRow(
t.fileInfo.has64bitOffsets,
fileInfo.has64bitOffsets == true
? t.common.yes
: t.common.no,
),
],
),
),
),
],
],
),
),
),
),
-151
View File
@@ -1,151 +0,0 @@
import 'package:flutter/material.dart';
/// A reusable focus indicator widget that wraps a child with visual feedback
/// when focused. Provides consistent focus appearance across the app for
/// keyboard/d-pad/controller navigation.
class FocusIndicator extends StatelessWidget {
final Widget child;
final bool isFocused;
final Color? borderColor;
final double borderWidth;
final double borderRadius;
final double scale;
final Duration animationDuration;
final Curve animationCurve;
const FocusIndicator({
super.key,
required this.child,
required this.isFocused,
this.borderColor,
this.borderWidth = 3.0,
this.borderRadius = 8.0,
this.scale = 1.02,
this.animationDuration = const Duration(milliseconds: 150),
this.animationCurve = Curves.easeOutCubic,
});
@override
Widget build(BuildContext context) {
final effectiveBorderColor =
borderColor ?? Theme.of(context).colorScheme.primary;
// Use AnimatedScale for the scale effect (doesn't affect layout)
// and a positioned border overlay that also doesn't affect layout
return AnimatedScale(
scale: isFocused ? scale : 1.0,
duration: animationDuration,
curve: animationCurve,
child: Stack(
clipBehavior: Clip.none,
children: [
child,
// Border overlay - doesn't affect layout
Positioned.fill(
child: IgnorePointer(
child: AnimatedContainer(
duration: animationDuration,
curve: animationCurve,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(borderRadius),
border: Border.all(
color: isFocused
? effectiveBorderColor
: Colors.transparent,
width: borderWidth,
),
),
),
),
),
],
),
);
}
}
/// A wrapper widget that manages its own FocusNode and provides focus state
/// to its builder. Use this for items that need focus handling with
/// automatic FocusNode lifecycle management.
class FocusableWrapper extends StatefulWidget {
final Widget Function(BuildContext context, bool isFocused) builder;
final FocusNode? focusNode;
final bool autofocus;
final VoidCallback? onFocused;
final KeyEventResult Function(FocusNode, KeyEvent)? onKeyEvent;
final void Function(BuildContext context)? onScrollIntoView;
final String? debugLabel;
const FocusableWrapper({
super.key,
required this.builder,
this.focusNode,
this.autofocus = false,
this.onFocused,
this.onKeyEvent,
this.onScrollIntoView,
this.debugLabel,
});
@override
State<FocusableWrapper> createState() => _FocusableWrapperState();
}
class _FocusableWrapperState extends State<FocusableWrapper> {
late FocusNode _focusNode;
bool _isFocused = false;
@override
void initState() {
super.initState();
_focusNode = widget.focusNode ?? FocusNode(debugLabel: widget.debugLabel);
_focusNode.addListener(_handleFocusChange);
}
@override
void dispose() {
_focusNode.removeListener(_handleFocusChange);
// Only dispose if we created the node
if (widget.focusNode == null) {
_focusNode.dispose();
}
super.dispose();
}
void _handleFocusChange() {
final hasFocus = _focusNode.hasFocus;
if (_isFocused != hasFocus) {
setState(() {
_isFocused = hasFocus;
});
if (hasFocus) {
widget.onFocused?.call();
// Use custom scroll behavior if provided, otherwise default
if (widget.onScrollIntoView != null) {
widget.onScrollIntoView!(context);
} else {
Scrollable.ensureVisible(
context,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
}
}
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
return widget.onKeyEvent?.call(node, event) ?? KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
return Focus(
focusNode: _focusNode,
autofocus: widget.autofocus,
onKeyEvent: _handleKeyEvent,
child: widget.builder(context, _isFocused),
);
}
}
+150
View File
@@ -0,0 +1,150 @@
import 'package:flutter/material.dart';
import '../focus/focus_theme.dart';
import '../focus/input_mode_tracker.dart';
/// Shared builders for focusable widgets to reduce code duplication.
///
/// These builders provide consistent focus decoration patterns across
/// different focusable widgets (chips, cards, etc.).
class FocusBuilders {
/// Builds a chip-style focusable widget with background color changes.
///
/// Used by FocusableTabChip and FocusableFilterChip.
///
/// Parameters:
/// - [context]: Build context for theming
/// - [focusNode]: The focus node for this widget
/// - [isFocused]: Whether this widget currently has focus
/// - [onKeyEvent]: Callback for handling key events
/// - [onTap]: Callback for tap/click events
/// - [padding]: Padding inside the chip
/// - [backgroundColor]: Background color for the chip
/// - [borderRadius]: Border radius for the chip (defaults to 20)
/// - [child]: The content to display inside the chip
static Widget buildFocusableChip({
required BuildContext context,
required FocusNode focusNode,
required bool isFocused,
required KeyEventResult Function(FocusNode, KeyEvent) onKeyEvent,
required VoidCallback onTap,
required EdgeInsetsGeometry padding,
required Color backgroundColor,
double borderRadius = 20,
required Widget child,
}) {
final duration = FocusTheme.getAnimationDuration(context);
return Focus(
focusNode: focusNode,
onKeyEvent: onKeyEvent,
child: GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: duration,
curve: Curves.easeOutCubic,
padding: padding,
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(borderRadius),
),
child: child,
),
),
);
}
/// Builds a card-style focusable widget with scale and border decoration.
///
/// Used by FocusableMediaCard and _LockedHubItemWrapper.
///
/// Parameters:
/// - [context]: Build context for theming
/// - [focusNode]: The focus node for this widget (optional for locked wrappers)
/// - [isFocused]: Whether this widget currently has focus
/// - [onKeyEvent]: Callback for handling key events (optional for locked wrappers)
/// - [onTap]: Callback for tap/click events
/// - [onLongPress]: Callback for long press events
/// - [borderRadius]: Border radius for the focus decoration
/// - [child]: The content to display inside the card
static Widget buildFocusableCard({
required BuildContext context,
FocusNode? focusNode,
required bool isFocused,
KeyEventResult Function(FocusNode, KeyEvent)? onKeyEvent,
VoidCallback? onTap,
VoidCallback? onLongPress,
double borderRadius = FocusTheme.defaultBorderRadius,
required Widget child,
}) {
final duration = FocusTheme.getAnimationDuration(context);
// Only show focus effects during keyboard/d-pad navigation
final showFocus = isFocused && InputModeTracker.isKeyboardMode(context);
final focusedWidget = AnimatedScale(
scale: showFocus ? FocusTheme.focusScale : 1.0,
duration: duration,
curve: Curves.easeOutCubic,
child: AnimatedContainer(
duration: duration,
curve: Curves.easeOutCubic,
decoration: FocusTheme.focusDecoration(
context,
isFocused: showFocus,
borderRadius: borderRadius,
),
child: child,
),
);
// Wrap in GestureDetector if tap/long press handlers provided
final gestureWidget = (onTap != null || onLongPress != null)
? GestureDetector(
onTap: onTap,
onLongPress: onLongPress,
child: focusedWidget,
)
: focusedWidget;
// Wrap in Focus if focus node and key event handler provided
if (focusNode != null && onKeyEvent != null) {
return Focus(
focusNode: focusNode,
onKeyEvent: onKeyEvent,
child: gestureWidget,
);
}
return gestureWidget;
}
/// Builds a simple locked wrapper (no Focus widget) with scale and border decoration.
///
/// Used by _LockedHubItemWrapper where focus is managed at a higher level.
///
/// Parameters:
/// - [context]: Build context for theming
/// - [isFocused]: Whether this widget should appear focused
/// - [onTap]: Callback for tap/click events
/// - [onLongPress]: Callback for long press events
/// - [borderRadius]: Border radius for the focus decoration
/// - [child]: The content to display inside the wrapper
static Widget buildLockedFocusWrapper({
required BuildContext context,
required bool isFocused,
VoidCallback? onTap,
VoidCallback? onLongPress,
double borderRadius = FocusTheme.defaultBorderRadius,
required Widget child,
}) {
return buildFocusableCard(
context: context,
focusNode: null,
isFocused: isFocused,
onKeyEvent: null,
onTap: onTap,
onLongPress: onLongPress,
borderRadius: borderRadius,
child: child,
);
}
}
+65
View File
@@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
import '../focus/input_mode_tracker.dart';
/// A wrapper widget that provides autofocus functionality for bottom sheets.
///
/// When the sheet opens and keyboard/controller mode is active, this widget
/// will automatically request focus on the provided [initialFocusNode].
/// This enables keyboard/controller navigation within the sheet.
///
/// When opened via touch/mouse, no autofocus occurs to avoid showing
/// focus indicators unnecessarily.
class FocusableBottomSheet extends StatefulWidget {
/// The content of the bottom sheet.
final Widget child;
/// The FocusNode to focus when the sheet opens in keyboard mode.
/// If null, no autofocus occurs.
final FocusNode? initialFocusNode;
const FocusableBottomSheet({
super.key,
required this.child,
this.initialFocusNode,
});
@override
State<FocusableBottomSheet> createState() => _FocusableBottomSheetState();
}
class _FocusableBottomSheetState extends State<FocusableBottomSheet> {
@override
void initState() {
super.initState();
_requestInitialFocus();
}
void _requestInitialFocus() {
if (widget.initialFocusNode == null) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
// Only autofocus when in keyboard/controller mode
if (InputModeTracker.isKeyboardMode(context)) {
widget.initialFocusNode?.requestFocus();
}
});
}
@override
void didUpdateWidget(FocusableBottomSheet oldWidget) {
super.didUpdateWidget(oldWidget);
// If the focus node changed, request focus on the new one
if (widget.initialFocusNode != oldWidget.initialFocusNode) {
_requestInitialFocus();
}
}
@override
Widget build(BuildContext context) {
return widget.child;
}
}
+143
View File
@@ -0,0 +1,143 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../focus/dpad_navigator.dart';
import '../focus/focusable_chip_mixin.dart';
import '../focus/input_mode_tracker.dart';
import 'focus_builders.dart';
/// A focusable filter chip that shows a color change when focused.
///
/// Unlike FocusableWrapper which uses scale + border, this widget
/// uses a background color change to indicate focus state.
class FocusableFilterChip extends StatefulWidget {
final IconData icon;
final String label;
final VoidCallback onPressed;
/// Optional external focus node for programmatic focus control.
final FocusNode? focusNode;
/// Called when the user presses DOWN from this chip.
final VoidCallback? onNavigateDown;
/// Called when the user presses UP from this chip.
final VoidCallback? onNavigateUp;
/// Called when the user presses BACK from this chip.
final VoidCallback? onBack;
const FocusableFilterChip({
super.key,
required this.icon,
required this.label,
required this.onPressed,
this.focusNode,
this.onNavigateDown,
this.onNavigateUp,
this.onBack,
});
@override
State<FocusableFilterChip> createState() => _FocusableFilterChipState();
}
class _FocusableFilterChipState extends State<FocusableFilterChip>
with FocusableChipStateMixin<FocusableFilterChip> {
@override
FocusNode? get widgetFocusNode => widget.focusNode;
@override
String get debugLabel => 'filter_chip_${widget.label}';
@override
void initState() {
super.initState();
initFocusNode();
}
@override
void didUpdateWidget(FocusableFilterChip oldWidget) {
super.didUpdateWidget(oldWidget);
updateFocusNode(oldWidget.focusNode);
}
@override
void dispose() {
disposeFocusNode();
super.dispose();
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
// SELECT key activates the chip
if (event.logicalKey.isSelectKey) {
widget.onPressed();
return KeyEventResult.handled;
}
// DOWN arrow navigates to the grid
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
widget.onNavigateDown?.call();
return KeyEventResult.handled;
}
// UP arrow navigates to tab bar
if (event.logicalKey == LogicalKeyboardKey.arrowUp &&
widget.onNavigateUp != null) {
widget.onNavigateUp!();
return KeyEventResult.handled;
}
// BACK key navigates to tab bar
if (event.logicalKey.isBackKey && widget.onBack != null) {
widget.onBack!();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
// Only show focus effects during keyboard/d-pad navigation
final showFocus = isFocused && InputModeTracker.isKeyboardMode(context);
// Use primary color when focused, surface color when not
final backgroundColor = showFocus
? colorScheme.primary
: colorScheme.surfaceContainerHighest;
final foregroundColor = showFocus
? colorScheme.onPrimary
: colorScheme.onSurfaceVariant;
return FocusBuilders.buildFocusableChip(
context: context,
focusNode: focusNode,
isFocused: isFocused,
onKeyEvent: _handleKeyEvent,
onTap: widget.onPressed,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
backgroundColor: backgroundColor,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 16, color: foregroundColor),
const SizedBox(width: 6),
Text(
widget.label,
style: Theme.of(
context,
).textTheme.labelMedium?.copyWith(color: foregroundColor),
),
],
),
);
}
IconData get icon => widget.icon;
}
+192
View File
@@ -0,0 +1,192 @@
import 'package:flutter/material.dart';
/// A ListTile that accepts a FocusNode for keyboard/controller navigation.
///
/// Uses Flutter's native ListTile focus support - no custom styling wrapper.
/// The focusNode allows programmatic focus control (e.g., auto-focus first item).
class FocusableListTile extends StatelessWidget {
/// The primary content of the list tile.
final Widget? title;
/// Additional content displayed below the title.
final Widget? subtitle;
/// A widget to display before the title.
final Widget? leading;
/// A widget to display after the title.
final Widget? trailing;
/// Called when the user taps this list tile.
final VoidCallback? onTap;
/// Called when the user long-presses this list tile.
final VoidCallback? onLongPress;
/// Whether this list tile is part of a vertically dense list.
final bool dense;
/// Whether this list tile is interactive.
final bool enabled;
/// If true, the tile is rendered with a selected highlight.
final bool selected;
/// Optional FocusNode for keyboard/controller navigation.
final FocusNode? focusNode;
/// Whether this tile should autofocus when first built.
final bool autofocus;
/// The tile's internal padding.
final EdgeInsetsGeometry? contentPadding;
const FocusableListTile({
super.key,
this.title,
this.subtitle,
this.leading,
this.trailing,
this.onTap,
this.onLongPress,
this.dense = false,
this.enabled = true,
this.selected = false,
this.focusNode,
this.autofocus = false,
this.contentPadding,
});
@override
Widget build(BuildContext context) {
return ListTile(
title: title,
subtitle: subtitle,
leading: leading,
trailing: trailing,
onTap: onTap,
onLongPress: onLongPress,
dense: dense,
enabled: enabled,
selected: selected,
contentPadding: contentPadding,
focusNode: focusNode,
autofocus: autofocus,
);
}
}
/// A RadioListTile that accepts a FocusNode for keyboard/controller navigation.
///
/// Uses Flutter's native RadioListTile focus support - no custom styling wrapper.
class FocusableRadioListTile<T> extends StatelessWidget {
/// The primary content of the list tile.
final Widget? title;
/// Additional content displayed below the title.
final Widget? subtitle;
/// A widget to display on the opposite side from the radio.
final Widget? secondary;
/// The value represented by this radio button.
final T value;
/// The currently selected value for this group of radio buttons.
final T? groupValue;
/// Called when the user selects this radio button.
final ValueChanged<T?>? onChanged;
/// Whether this radio button is part of a vertically dense list.
final bool dense;
/// Optional FocusNode for keyboard/controller navigation.
final FocusNode? focusNode;
/// Whether this tile should autofocus when first built.
final bool autofocus;
const FocusableRadioListTile({
super.key,
this.title,
this.subtitle,
this.secondary,
required this.value,
required this.groupValue,
required this.onChanged,
this.dense = false,
this.focusNode,
this.autofocus = false,
});
@override
Widget build(BuildContext context) {
return RadioListTile<T>(
title: title,
subtitle: subtitle,
secondary: secondary,
value: value,
groupValue: groupValue,
onChanged: onChanged,
dense: dense,
focusNode: focusNode,
autofocus: autofocus,
);
}
}
/// A SwitchListTile that accepts a FocusNode for keyboard/controller navigation.
///
/// Uses Flutter's native SwitchListTile focus support - no custom styling wrapper.
class FocusableSwitchListTile extends StatelessWidget {
/// The primary content of the list tile.
final Widget? title;
/// Additional content displayed below the title.
final Widget? subtitle;
/// A widget to display on the opposite side from the switch.
final Widget? secondary;
/// Whether this switch is checked.
final bool value;
/// Called when the user toggles the switch.
final ValueChanged<bool>? onChanged;
/// Whether this switch is part of a vertically dense list.
final bool dense;
/// Optional FocusNode for keyboard/controller navigation.
final FocusNode? focusNode;
/// Whether this tile should autofocus when first built.
final bool autofocus;
const FocusableSwitchListTile({
super.key,
this.title,
this.subtitle,
this.secondary,
required this.value,
required this.onChanged,
this.dense = false,
this.focusNode,
this.autofocus = false,
});
@override
Widget build(BuildContext context) {
return SwitchListTile(
title: title,
subtitle: subtitle,
secondary: secondary,
value: value,
onChanged: onChanged,
dense: dense,
focusNode: focusNode,
autofocus: autofocus,
);
}
}
+84
View File
@@ -0,0 +1,84 @@
import 'package:flutter/material.dart';
import '../focus/focusable_wrapper.dart';
import 'media_card.dart';
/// A focusable wrapper for MediaCard that handles D-pad navigation.
///
/// Wraps MediaCard with focus handling for TV/desktop navigation:
/// - Shows scale + border decoration when focused
/// - Handles SELECT key for activation with long-press detection
/// - Accepts optional external focusNode for programmatic focus control
class FocusableMediaCard extends StatefulWidget {
final dynamic item; // PlexMetadata or PlexPlaylist
final double? width;
final double? height;
final void Function(String ratingKey)? onRefresh;
final VoidCallback? onRemoveFromContinueWatching;
final VoidCallback? onListRefresh;
final bool forceGridMode;
final bool isInContinueWatching;
final String? collectionId;
/// Optional external focus node for programmatic focus control.
/// If not provided, an internal focus node is created.
final FocusNode? focusNode;
/// Called when the user presses UP and there's no focusable item above.
/// Used to navigate from the top row to filter chips.
final VoidCallback? onNavigateUp;
/// Called when the user presses BACK.
/// Used to navigate from tab content to tab bar.
final VoidCallback? onBack;
const FocusableMediaCard({
super.key,
required this.item,
this.width,
this.height,
this.onRefresh,
this.onRemoveFromContinueWatching,
this.onListRefresh,
this.forceGridMode = false,
this.isInContinueWatching = false,
this.collectionId,
this.focusNode,
this.onNavigateUp,
this.onBack,
});
@override
State<FocusableMediaCard> createState() => _FocusableMediaCardState();
}
class _FocusableMediaCardState extends State<FocusableMediaCard> {
// Key for accessing MediaCard's state
final GlobalKey<MediaCardState> _mediaCardKey = GlobalKey();
@override
Widget build(BuildContext context) {
return FocusableWrapper(
focusNode: widget.focusNode,
onSelect: () => _mediaCardKey.currentState?.handleTap(),
onLongPress: () => _mediaCardKey.currentState?.showContextMenu(),
onNavigateUp: widget.onNavigateUp,
onBack: widget.onBack,
enableLongPress: true,
useComfortableZone: true,
scrollAlignment: 0.5,
child: MediaCard(
key: _mediaCardKey,
item: widget.item,
width: widget.width,
height: widget.height,
onRefresh: widget.onRefresh,
onRemoveFromContinueWatching: widget.onRemoveFromContinueWatching,
onListRefresh: widget.onListRefresh,
forceGridMode: widget.forceGridMode,
isInContinueWatching: widget.isInContinueWatching,
collectionId: widget.collectionId,
),
);
}
}
+171
View File
@@ -0,0 +1,171 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../focus/dpad_navigator.dart';
import '../focus/focusable_chip_mixin.dart';
import '../focus/input_mode_tracker.dart';
import 'focus_builders.dart';
/// A focusable tab chip that shows a color change when focused or selected.
///
/// Used for tab navigation in LibrariesScreen. Handles:
/// - SELECT key to activate the tab
/// - LEFT/RIGHT arrows to switch between tabs
/// - DOWN arrow to navigate to tab content
/// - BACK key to navigate to sidenav
class FocusableTabChip extends StatefulWidget {
final String label;
final bool isSelected;
final VoidCallback onSelect;
/// Optional external focus node for programmatic focus control.
final FocusNode? focusNode;
/// Called when the user presses LEFT from this chip.
/// Should switch to the previous tab.
final VoidCallback? onNavigateLeft;
/// Called when the user presses RIGHT from this chip.
/// Should switch to the next tab.
final VoidCallback? onNavigateRight;
/// Called when the user presses DOWN from this chip.
final VoidCallback? onNavigateDown;
/// Called when the user presses BACK from this chip.
final VoidCallback? onBack;
const FocusableTabChip({
super.key,
required this.label,
required this.isSelected,
required this.onSelect,
this.focusNode,
this.onNavigateLeft,
this.onNavigateRight,
this.onNavigateDown,
this.onBack,
});
@override
State<FocusableTabChip> createState() => _FocusableTabChipState();
}
class _FocusableTabChipState extends State<FocusableTabChip>
with FocusableChipStateMixin<FocusableTabChip> {
@override
FocusNode? get widgetFocusNode => widget.focusNode;
@override
String get debugLabel => 'tab_chip_${widget.label}';
@override
void initState() {
super.initState();
initFocusNode();
}
@override
void didUpdateWidget(FocusableTabChip oldWidget) {
super.didUpdateWidget(oldWidget);
updateFocusNode(oldWidget.focusNode);
}
@override
void dispose() {
disposeFocusNode();
super.dispose();
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// SELECT key activates the tab
if (key.isSelectKey) {
widget.onSelect();
return KeyEventResult.handled;
}
// LEFT arrow switches to previous tab
if (key.isLeftKey && widget.onNavigateLeft != null) {
widget.onNavigateLeft!();
return KeyEventResult.handled;
}
// RIGHT arrow switches to next tab
if (key.isRightKey && widget.onNavigateRight != null) {
widget.onNavigateRight!();
return KeyEventResult.handled;
}
// DOWN arrow navigates to tab content
if (key == LogicalKeyboardKey.arrowDown) {
widget.onNavigateDown?.call();
return KeyEventResult.handled;
}
// BACK key navigates to sidenav
if (key.isBackKey && widget.onBack != null) {
widget.onBack!();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
// Only show focus effects during keyboard/d-pad navigation
final showFocus = isFocused && InputModeTracker.isKeyboardMode(context);
// Determine background color based on focus and selection state
// - Selected + Focused: slightly dimmed primary (to show focus distinction)
// - Selected only: primary color
// - Focused only: primary color
// - Neither: surface color
Color backgroundColor;
Color foregroundColor;
if (widget.isSelected && showFocus) {
// Selected + focused: dim the primary color slightly
backgroundColor = Color.lerp(
colorScheme.primary,
colorScheme.surface,
0.25,
)!;
foregroundColor = colorScheme.onPrimary;
} else if (widget.isSelected || showFocus) {
// Selected or focused (but not both): full primary
backgroundColor = colorScheme.primary;
foregroundColor = colorScheme.onPrimary;
} else {
// Neither selected nor focused
backgroundColor = colorScheme.surfaceContainerHighest;
foregroundColor = colorScheme.onSurfaceVariant;
}
final isHighlighted = showFocus || widget.isSelected;
return FocusBuilders.buildFocusableChip(
context: context,
focusNode: focusNode,
isFocused: isFocused,
onKeyEvent: _handleKeyEvent,
onTap: widget.onSelect,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
backgroundColor: backgroundColor,
child: Text(
widget.label,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
color: foregroundColor,
fontWeight: isHighlighted ? FontWeight.w600 : FontWeight.normal,
),
),
);
}
}
+51
View File
@@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import '../focus/key_event_utils.dart';
import 'desktop_app_bar.dart';
/// A scaffold widget that wraps Focus + Scaffold + CustomScrollView
/// with consistent keyboard navigation handling and app bar styling.
///
/// This widget reduces boilerplate for screens that need:
/// - Keyboard navigation (back key handling)
/// - Custom scrollable content with slivers
/// - Consistent app bar with title and optional actions
class FocusedScrollScaffold extends StatelessWidget {
/// The title to display in the app bar.
/// Can be a Text widget or a more complex widget like Column.
final Widget title;
/// The list of slivers to display in the scroll view.
/// Should not include the app bar (it's added automatically).
final List<Widget> slivers;
/// Optional actions to display in the app bar (e.g., IconButton widgets).
final List<Widget>? actions;
/// Whether the app bar should remain visible when scrolling.
/// Defaults to true.
final bool pinned;
const FocusedScrollScaffold({
super.key,
required this.title,
required this.slivers,
this.actions,
this.pinned = true,
});
@override
Widget build(BuildContext context) {
return Focus(
autofocus: true,
onKeyEvent: (_, event) => handleBackKeyNavigation(context, event),
child: Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: title, pinned: pinned, actions: actions),
...slivers,
],
),
),
);
}
}
+43 -40
View File
@@ -9,11 +9,13 @@ import '../utils/platform_detector.dart';
class HorizontalScrollWithArrows extends StatefulWidget {
final Widget Function(ScrollController) builder;
final double scrollAmount;
final ScrollController? controller;
const HorizontalScrollWithArrows({
super.key,
required this.builder,
this.scrollAmount = 0.8, // Scroll by 80% of viewport width by default
this.controller,
});
@override
@@ -24,6 +26,7 @@ class HorizontalScrollWithArrows extends StatefulWidget {
class _HorizontalScrollWithArrowsState
extends State<HorizontalScrollWithArrows> {
late final ScrollController _scrollController;
late final bool _ownsController;
bool _isHovering = false;
bool _canScrollLeft = false;
bool _canScrollRight = false;
@@ -31,7 +34,8 @@ class _HorizontalScrollWithArrowsState
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_ownsController = widget.controller == null;
_scrollController = widget.controller ?? ScrollController();
_scrollController.addListener(_updateScrollState);
// Initial state update after first frame
WidgetsBinding.instance.addPostFrameCallback((_) => _updateScrollState());
@@ -40,7 +44,9 @@ class _HorizontalScrollWithArrowsState
@override
void dispose() {
_scrollController.removeListener(_updateScrollState);
_scrollController.dispose();
if (_ownsController) {
_scrollController.dispose();
}
super.dispose();
}
@@ -80,6 +86,31 @@ class _HorizontalScrollWithArrowsState
);
}
Widget _buildArrowButton({
required double position,
required IconData icon,
required VoidCallback onPressed,
required bool canScroll,
}) {
return Positioned(
left: position < 0 ? null : position,
right: position < 0 ? -position : null,
top: 0,
bottom: 0,
child: Center(
child: AnimatedOpacity(
opacity: (_isHovering && canScroll) ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
child: IgnorePointer(
ignoring: !(_isHovering && canScroll),
child: _NavigationArrow(icon: icon, onPressed: onPressed),
),
),
),
);
}
@override
Widget build(BuildContext context) {
final child = widget.builder(_scrollController);
@@ -95,45 +126,17 @@ class _HorizontalScrollWithArrowsState
child: Stack(
children: [
child,
// Left arrow
Positioned(
left: 8,
top: 0,
bottom: 0,
child: Center(
child: AnimatedOpacity(
opacity: (_isHovering && _canScrollLeft) ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
child: IgnorePointer(
ignoring: !(_isHovering && _canScrollLeft),
child: _NavigationArrow(
icon: Icons.chevron_left,
onPressed: _scrollLeft,
),
),
),
),
_buildArrowButton(
position: 8,
icon: Icons.chevron_left,
onPressed: _scrollLeft,
canScroll: _canScrollLeft,
),
// Right arrow
Positioned(
right: 8,
top: 0,
bottom: 0,
child: Center(
child: AnimatedOpacity(
opacity: (_isHovering && _canScrollRight) ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
child: IgnorePointer(
ignoring: !(_isHovering && _canScrollRight),
child: _NavigationArrow(
icon: Icons.chevron_right,
onPressed: _scrollRight,
),
),
),
),
_buildArrowButton(
position: -8,
icon: Icons.chevron_right,
onPressed: _scrollRight,
canScroll: _canScrollRight,
),
],
),
-115
View File
@@ -1,115 +0,0 @@
import 'package:flutter/material.dart';
/// Controller that manages navigation between hub sections.
/// Hub sections register themselves, and MediaCards can request
/// to navigate to adjacent hub sections.
class HubNavigationController extends ChangeNotifier {
final List<HubSectionRegistration> _registrations = [];
/// Map of hub ID to last focused item index
final Map<String, int> _focusMemory = {};
/// Register a hub section with the controller
/// If a hub with the same ID is already registered, it will be replaced
/// Registrations are kept sorted by order for consistent navigation
void register(HubSectionRegistration registration) {
// Remove any existing registration with the same hubId
_registrations.removeWhere((r) => r.hubId == registration.hubId);
_registrations.add(registration);
// Sort by order to maintain consistent navigation regardless of registration timing
_registrations.sort((a, b) => a.order.compareTo(b.order));
}
/// Unregister a hub section
void unregister(String hubId) {
_registrations.removeWhere((r) => r.hubId == hubId);
_focusMemory.remove(hubId);
}
/// Remember the focused item index for a hub
void rememberFocusedIndex(String hubId, int index) {
_focusMemory[hubId] = index;
}
/// Get the remembered focused index for a hub (or 0 if none)
int getRememberedIndex(String hubId) {
return _focusMemory[hubId] ?? 0;
}
/// Navigate to the next hub section (direction: 1 for down, -1 for up)
/// Returns true if navigation was handled
bool navigateToAdjacentHub(String currentHubId, int direction) {
final currentIndex = _registrations.indexWhere(
(r) => r.hubId == currentHubId,
);
if (currentIndex == -1) return false;
final targetIndex = currentIndex + direction;
if (targetIndex < 0 || targetIndex >= _registrations.length) return false;
final targetHub = _registrations[targetIndex];
if (targetHub.itemCount == 0) {
// Nothing to focus in the target hub
return false;
}
final rememberedIndex = getRememberedIndex(targetHub.hubId);
// Focus the remembered item or first item
targetHub.focusItem(rememberedIndex.clamp(0, targetHub.itemCount - 1));
return true;
}
/// Focus a specific hub and item by order index
/// [hubIndex] is the index in the sorted list (0 = first hub)
/// [itemIndex] is the item within that hub (0 = first item)
void focusHub(int hubIndex, int itemIndex) {
if (hubIndex < 0 || hubIndex >= _registrations.length) return;
final hub = _registrations[hubIndex];
if (hub.itemCount > 0) {
hub.focusItem(itemIndex.clamp(0, hub.itemCount - 1));
}
}
}
/// Registration info for a hub section
class HubSectionRegistration {
final String hubId;
final int itemCount;
final int order; // Visual order on screen (lower = higher on screen)
final void Function(int index) focusItem;
HubSectionRegistration({
required this.hubId,
required this.itemCount,
required this.focusItem,
this.order = 1000, // Default high order for dynamic hubs
});
}
/// InheritedWidget to provide the HubNavigationController down the tree
class HubNavigationScope extends InheritedWidget {
final HubNavigationController controller;
const HubNavigationScope({
super.key,
required this.controller,
required super.child,
});
static HubNavigationController? of(BuildContext context) {
final scope = context
.dependOnInheritedWidgetOfExactType<HubNavigationScope>();
return scope?.controller;
}
static HubNavigationController? maybeOf(BuildContext context) {
final scope = context.getInheritedWidgetOfExactType<HubNavigationScope>();
return scope?.controller;
}
@override
bool updateShouldNotify(HubNavigationScope oldWidget) {
return controller != oldWidget.controller;
}
}
+327 -219
View File
@@ -1,16 +1,23 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../focus/dpad_navigator.dart';
import '../focus/locked_hub_controller.dart';
import '../models/plex_hub.dart';
import '../screens/hub_detail_screen.dart';
import '../utils/media_navigation_helper.dart';
import 'focus_builders.dart';
import 'media_card.dart';
import 'horizontal_scroll_with_arrows.dart';
import 'hub_navigation_controller.dart';
import '../i18n/strings.g.dart';
import 'focus/focus_indicator.dart';
import '../utils/keyboard_utils.dart';
/// Shared hub section widget used in both discover and library screens
/// Displays a hub title with icon and a horizontal scrollable list of items
///
/// Uses a "locked" focus pattern where:
/// - A single Focus widget at the hub level intercepts ALL arrow keys
/// - Visual focus index is tracked in state (not Flutter's focus system)
/// - Children render focus visuals based on the passed index
/// - Focus never "escapes" to random elements
class HubSection extends StatefulWidget {
final PlexHub hub;
final IconData icon;
@@ -18,8 +25,12 @@ class HubSection extends StatefulWidget {
final VoidCallback? onRemoveFromContinueWatching;
final bool isInContinueWatching;
/// Order for navigation (lower = higher on screen). Default is 1000 for dynamic hubs.
final int navigationOrder;
/// Callback for vertical navigation (up/down). Return true if handled.
final bool Function(bool isUp)? onVerticalNavigation;
/// Called when the user presses BACK.
/// Used to navigate focus back to the tab bar.
final VoidCallback? onBack;
const HubSection({
super.key,
@@ -28,203 +39,270 @@ class HubSection extends StatefulWidget {
this.onRefresh,
this.onRemoveFromContinueWatching,
this.isInContinueWatching = false,
this.navigationOrder = 1000,
this.onVerticalNavigation,
this.onBack,
});
@override
State<HubSection> createState() => _HubSectionState();
State<HubSection> createState() => HubSectionState();
}
class _HubSectionState extends State<HubSection> {
late final FocusNode _headerFocusNode;
bool _headerIsFocused = false;
HubNavigationController? _controller;
class HubSectionState extends State<HubSection> {
late FocusNode _hubFocusNode;
final ScrollController _scrollController = ScrollController();
/// Focus nodes for each item in the hub
List<FocusNode> _itemFocusNodes = [];
String? _registeredHubId;
int? _registeredItemCount;
int? _registeredOrder;
/// Current visual focus index (not tied to Flutter's focus system)
int _focusedIndex = 0;
String get _hubId => widget.hub.hubIdentifier ?? widget.hub.title;
/// Item extent for scroll calculations
double _itemExtent = 0;
static const double _leadingPadding = 12.0;
@override
void initState() {
super.initState();
_headerFocusNode = FocusNode();
_headerFocusNode.addListener(_handleHeaderFocusChange);
_createItemFocusNodes();
}
void _createItemFocusNodes() {
// Create focus nodes for each item
_itemFocusNodes = List.generate(
widget.hub.items.length,
(index) => FocusNode(debugLabel: 'HubItem_${_hubId}_$index'),
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_registerWithController();
_hubFocusNode = FocusNode(debugLabel: 'hub_${widget.hub.hubKey}');
_hubFocusNode.addListener(_onFocusChange);
}
@override
void didUpdateWidget(HubSection oldWidget) {
super.didUpdateWidget(oldWidget);
// If items changed, recreate focus nodes
if (widget.hub.items.length != _itemFocusNodes.length) {
_disposeItemFocusNodes();
_createItemFocusNodes();
// Clamp focus index if item count changed
if (widget.hub.items.length != oldWidget.hub.items.length) {
final maxIndex = widget.hub.items.isEmpty
? 0
: widget.hub.items.length - 1;
if (_focusedIndex > maxIndex) {
_focusedIndex = maxIndex;
}
}
_registerWithController();
}
void _unregisterFromController() {
if (_controller != null && _registeredHubId != null) {
_controller!.unregister(_registeredHubId!);
}
_registeredHubId = null;
_registeredItemCount = null;
_registeredOrder = null;
}
void _registerWithController() {
final controller = HubNavigationScope.maybeOf(context);
final hubId = _hubId;
final itemCount = widget.hub.items.length;
final order = widget.navigationOrder;
if (controller != _controller) {
_unregisterFromController();
_controller = controller;
}
if (controller == null) return;
final registrationChanged =
_registeredHubId != hubId ||
_registeredItemCount != itemCount ||
_registeredOrder != order;
if (registrationChanged) {
_unregisterFromController();
controller.register(
HubSectionRegistration(
hubId: hubId,
itemCount: itemCount,
focusItem: _focusItem,
order: order,
),
);
_registeredHubId = hubId;
_registeredItemCount = itemCount;
_registeredOrder = order;
}
}
void _focusItem(int index) {
if (index >= 0 && index < _itemFocusNodes.length) {
_itemFocusNodes[index].requestFocus();
}
}
void _disposeItemFocusNodes() {
for (final node in _itemFocusNodes) {
node.dispose();
}
_itemFocusNodes = [];
}
@override
void dispose() {
_unregisterFromController();
_headerFocusNode.removeListener(_handleHeaderFocusChange);
_headerFocusNode.dispose();
_disposeItemFocusNodes();
_hubFocusNode.removeListener(_onFocusChange);
_hubFocusNode.dispose();
_scrollController.dispose();
super.dispose();
}
void _handleHeaderFocusChange() {
if (_headerIsFocused != _headerFocusNode.hasFocus) {
setState(() {
_headerIsFocused = _headerFocusNode.hasFocus;
});
void _onFocusChange() {
// Rebuild to update visual focus state
if (mounted) setState(() {});
}
/// Request focus on this hub at a specific item index
void requestFocusAt(int index) {
if (widget.hub.items.isEmpty) return;
final clamped = index.clamp(0, widget.hub.items.length - 1);
_focusedIndex = clamped;
// Remember this position for this specific hub
HubFocusMemory.setForHub(widget.hub.hubKey, clamped);
_scrollToIndex(clamped);
_hubFocusNode.requestFocus();
if (mounted) setState(() {});
// Scroll the hub into view in the parent scroll view
_scrollHubIntoView();
}
/// Request focus using the stored memory for this hub
void requestFocusFromMemory() {
final index = HubFocusMemory.getForHub(
widget.hub.hubKey,
widget.hub.items.length,
);
requestFocusAt(index);
}
/// Scroll this hub into view in the parent scroll view
void _scrollHubIntoView() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
Scrollable.ensureVisible(
context,
alignment: 0.3, // Position hub near top third of viewport
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
});
}
/// Check if this hub currently has focus
bool get hasFocusedItem => _hubFocusNode.hasFocus;
/// Get the number of items in this hub
int get itemCount => widget.hub.items.length;
/// Scroll to center the item at the given index
void _scrollToIndex(int index, {bool animate = true}) {
if (!_scrollController.hasClients || _itemExtent <= 0) return;
final viewport = _scrollController.position.viewportDimension;
final targetCenter =
_leadingPadding + (index * _itemExtent) + (_itemExtent / 2);
final desiredOffset = (targetCenter - (viewport / 2)).clamp(
0.0,
_scrollController.position.maxScrollExtent,
);
if (animate) {
_scrollController.animateTo(
desiredOffset,
duration: const Duration(milliseconds: 150),
curve: Curves.easeOut,
);
} else {
_scrollController.jumpTo(desiredOffset);
}
}
void _navigateToHubDetail() {
/// Handle ALL key events at the hub level
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
// Handle key down and repeat events
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
final itemCount = widget.hub.items.length;
if (itemCount == 0) return KeyEventResult.ignored;
// Left: move to previous item, ALWAYS consume to prevent escape
if (key.isLeftKey) {
if (_focusedIndex > 0) {
_focusedIndex--;
HubFocusMemory.setForHub(widget.hub.hubKey, _focusedIndex);
_scrollToIndex(_focusedIndex);
setState(() {});
}
return KeyEventResult.handled;
}
// Right: move to next item, ALWAYS consume to prevent escape
if (key.isRightKey) {
if (_focusedIndex < itemCount - 1) {
_focusedIndex++;
HubFocusMemory.setForHub(widget.hub.hubKey, _focusedIndex);
_scrollToIndex(_focusedIndex);
setState(() {});
}
return KeyEventResult.handled;
}
// Up/Down: delegate to parent for vertical hub navigation, ALWAYS consume
if (key.isUpKey) {
widget.onVerticalNavigation?.call(true);
return KeyEventResult.handled;
}
if (key.isDownKey) {
widget.onVerticalNavigation?.call(false);
return KeyEventResult.handled;
}
// Select: activate the current item
if (key.isSelectKey) {
_activateCurrentItem();
return KeyEventResult.handled;
}
// Context menu key: show context menu
if (key.isContextMenuKey) {
_showContextMenuForCurrentItem();
return KeyEventResult.handled;
}
// Back key: navigate to tab bar
if (key.isBackKey && widget.onBack != null) {
widget.onBack!();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// GlobalKeys for MediaCards to access their state (for context menu)
final Map<int, GlobalKey<MediaCardState>> _mediaCardKeys = {};
GlobalKey<MediaCardState> _getMediaCardKey(int index) {
return _mediaCardKeys.putIfAbsent(
index,
() => GlobalKey<MediaCardState>(),
);
}
void _activateCurrentItem() {
if (_focusedIndex >= widget.hub.items.length) return;
final item = widget.hub.items[_focusedIndex];
_navigateToItem(item);
}
void _showContextMenuForCurrentItem() {
_mediaCardKeys[_focusedIndex]?.currentState?.showContextMenu();
}
Future<void> _navigateToItem(dynamic item) async {
await navigateToMediaItem(context, item, onRefresh: widget.onRefresh);
}
void _navigateToHubDetail(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HubDetailScreen(hub: widget.hub)),
);
}
KeyEventResult _handleHeaderKeyEvent(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent && widget.hub.more) {
if (isKeyboardActivationKey(event.logicalKey)) {
_navigateToHubDetail();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
return FocusTraversalGroup(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Hub header
Padding(
padding: const EdgeInsets.fromLTRB(16, 24, 16, 8),
child: Focus(
focusNode: _headerFocusNode,
onKeyEvent: _handleHeaderKeyEvent,
canRequestFocus: widget.hub.more, // Only focusable if has "more"
child: FocusIndicator(
isFocused: _headerIsFocused && widget.hub.more,
borderRadius: 8,
child: InkWell(
onTap: widget.hub.more ? _navigateToHubDetail : null,
borderRadius: BorderRadius.circular(8),
focusColor: Colors.transparent,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
final hasFocus = _hubFocusNode.hasFocus;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Hub header (NOT focusable - titles should not be focusable)
Padding(
padding: const EdgeInsets.fromLTRB(16, 24, 16, 8),
child: ExcludeFocus(
child: InkWell(
onTap: widget.hub.more
? () => _navigateToHubDetail(context)
: null,
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(widget.icon),
const SizedBox(width: 8),
Expanded(
child: Text(
widget.hub.title,
style: Theme.of(context).textTheme.titleLarge,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(widget.icon),
const SizedBox(width: 8),
Expanded(
child: Text(
widget.hub.title,
style: Theme.of(context).textTheme.titleLarge,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
if (widget.hub.more) ...[
const SizedBox(width: 4),
const Icon(Icons.chevron_right, size: 20),
],
],
),
),
if (widget.hub.more) ...[
const SizedBox(width: 4),
const Icon(Icons.chevron_right, size: 20),
],
],
),
),
),
),
),
// Hub items (horizontal scroll)
if (widget.hub.items.isNotEmpty)
LayoutBuilder(
// Hub items with locked focus control
if (widget.hub.items.isNotEmpty)
Focus(
focusNode: _hubFocusNode,
onKeyEvent: _handleKeyEvent,
child: LayoutBuilder(
builder: (context, constraints) {
// Responsive card width based on screen size
final screenWidth = constraints.maxWidth;
@@ -236,76 +314,106 @@ class _HubSectionState extends State<HubSection> {
? 190.0
: 160.0;
// Store item extent for scroll calculations
_itemExtent = cardWidth + 4; // 4px total horizontal padding
// MediaCard has 8px padding on all sides (16px total horizontally)
// So actual poster width is cardWidth - 16
final posterWidth = cardWidth - 16;
// 2:3 poster aspect ratio (height is 1.5x width)
// 2:3 poster aspect ratio
final posterHeight = posterWidth * 1.5;
// Container height = poster + padding + spacing + text + focus indicator headroom
// 8px top padding + posterHeight + 4px spacing + ~26px text + 8px bottom padding
// + 10px extra for focus indicator border (3px) and scale effect (1.02x)
final containerHeight = posterHeight + 46 + 10;
// Container height calculation
final containerHeight = posterHeight + 66;
return SizedBox(
height: containerHeight,
child: ClipRect(
clipBehavior: Clip.none,
child: HorizontalScrollWithArrows(
builder: (scrollController) => FocusTraversalGroup(
child: ListView.builder(
controller: scrollController,
scrollDirection: Axis.horizontal,
clipBehavior:
Clip.none, // Allow focus indicator to overflow
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 5,
),
itemCount: widget.hub.items.length,
itemBuilder: (context, index) {
final item = widget.hub.items[index];
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 2,
),
child: MediaCard(
key: Key(item.ratingKey),
item: item,
width: cardWidth,
height: posterHeight,
onRefresh: widget.onRefresh,
onRemoveFromContinueWatching:
widget.onRemoveFromContinueWatching,
forceGridMode: true,
isInContinueWatching:
widget.isInContinueWatching,
focusNode: _itemFocusNodes.length > index
? _itemFocusNodes[index]
: null,
hubId: _hubId,
itemIndex: index,
),
);
},
),
child: HorizontalScrollWithArrows(
controller: _scrollController,
builder: (scrollController) => ListView.builder(
controller: scrollController,
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 5,
),
itemCount: widget.hub.items.length,
itemBuilder: (context, index) {
final item = widget.hub.items[index];
final isItemFocused =
hasFocus && index == _focusedIndex;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
child: _LockedHubItemWrapper(
isFocused: isItemFocused,
onTap: () => _onItemTapped(index),
onLongPress: () =>
_mediaCardKeys[index]?.currentState?.showContextMenu(),
child: MediaCard(
key: _getMediaCardKey(index),
item: item,
width: cardWidth,
height: posterHeight,
onRefresh: widget.onRefresh,
onRemoveFromContinueWatching:
widget.onRemoveFromContinueWatching,
forceGridMode: true,
isInContinueWatching: widget.isInContinueWatching,
),
),
);
},
),
),
);
},
)
else
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
t.messages.noItemsAvailable,
style: Theme.of(
context,
).textTheme.bodySmall?.copyWith(color: Colors.grey),
),
),
],
),
)
else
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
t.messages.noItemsAvailable,
style: Theme.of(
context,
).textTheme.bodySmall?.copyWith(color: Colors.grey),
),
),
],
);
}
/// Called when an item is tapped (mouse/touch)
void _onItemTapped(int index) {
// Update focus to tapped item and request hub focus
_focusedIndex = index;
HubFocusMemory.setForHub(widget.hub.hubKey, index);
_hubFocusNode.requestFocus();
setState(() {});
}
}
/// Wrapper that provides visual focus decoration without using Flutter's focus system.
class _LockedHubItemWrapper extends StatelessWidget {
final bool isFocused;
final Widget child;
final VoidCallback? onTap;
final VoidCallback? onLongPress;
const _LockedHubItemWrapper({
required this.isFocused,
required this.child,
this.onTap,
this.onLongPress,
});
@override
Widget build(BuildContext context) {
return FocusBuilders.buildLockedFocusWrapper(
context: context,
isFocused: isFocused,
onTap: onTap,
onLongPress: onLongPress,
child: child,
);
}
}
+269 -520
View File
@@ -1,10 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'focus/focus_indicator.dart';
import 'hub_navigation_controller.dart';
import '../../services/plex_client.dart';
import '../mixins/keyboard_long_press_mixin.dart';
import '../models/plex_metadata.dart';
import '../models/plex_playlist.dart';
import '../providers/multi_server_provider.dart';
@@ -36,15 +32,6 @@ class MediaCard extends StatefulWidget {
final String?
collectionId; // The collection ID if displaying within a collection
/// External FocusNode for hub navigation (provided by HubSection)
final FocusNode? focusNode;
/// Hub section ID for focus memory tracking
final String? hubId;
/// Item index within the hub section
final int? itemIndex;
const MediaCard({
super.key,
required this.item,
@@ -56,22 +43,29 @@ class MediaCard extends StatefulWidget {
this.forceGridMode = false,
this.isInContinueWatching = false,
this.collectionId,
this.focusNode,
this.hubId,
this.itemIndex,
});
@override
State<MediaCard> createState() => _MediaCardState();
State<MediaCard> createState() => MediaCardState();
}
class _MediaCardState extends State<MediaCard> {
class MediaCardState extends State<MediaCard> {
final _contextMenuKey = GlobalKey<MediaContextMenuState>();
void _showContextMenu() {
_contextMenuKey.currentState?.showContextMenu(context);
}
/// Public method to trigger tap action (for keyboard/gamepad SELECT)
void handleTap() {
_handleTap(context);
}
/// Public method to show context menu (for keyboard/gamepad context menu key)
void showContextMenu() {
_showContextMenu();
}
String _buildSemanticLabel() {
final item = widget.item;
final itemType = item.type.toLowerCase();
@@ -116,7 +110,12 @@ class _MediaCardState extends State<MediaCard> {
return baseLabel;
}
void _handleTap(BuildContext context, {bool isKeyboard = false}) async {
void _handleTap(BuildContext context) async {
// Ignore taps while context menu is open to avoid double-activating
if (_contextMenuKey.currentState?.isContextMenuOpen == true) {
return;
}
// Handle playlists
if (widget.item is PlexPlaylist) {
await Navigator.push(
@@ -175,10 +174,7 @@ class _MediaCardState extends State<MediaCard> {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SeasonDetailScreen(
season: widget.item,
focusFirstEpisode: isKeyboard,
),
builder: (context) => SeasonDetailScreen(season: widget.item),
),
);
// Season screen doesn't return a refresh flag, but we can refresh anyway
@@ -213,18 +209,13 @@ class _MediaCardState extends State<MediaCard> {
width: widget.width,
height: widget.height,
semanticLabel: semanticLabel,
onTap: ({bool isKeyboard = false}) =>
_handleTap(context, isKeyboard: isKeyboard),
onTap: () => _handleTap(context),
onLongPress: _showContextMenu,
focusNode: widget.focusNode,
hubId: widget.hubId,
itemIndex: widget.itemIndex,
)
: _MediaCardList(
item: widget.item,
semanticLabel: semanticLabel,
onTap: ({bool isKeyboard = false}) =>
_handleTap(context, isKeyboard: isKeyboard),
onTap: () => _handleTap(context),
onLongPress: _showContextMenu,
density: settingsProvider.libraryDensity,
);
@@ -245,23 +236,14 @@ class _MediaCardState extends State<MediaCard> {
}
/// Grid layout for media cards
class _MediaCardGrid extends StatefulWidget {
class _MediaCardGrid extends StatelessWidget {
final dynamic item; // Can be PlexMetadata or PlexPlaylist
final double? width;
final double? height;
final String semanticLabel;
final void Function({bool isKeyboard}) onTap;
final VoidCallback onTap;
final VoidCallback onLongPress;
/// External FocusNode for hub navigation (provided by HubSection)
final FocusNode? focusNode;
/// Hub section ID for focus memory tracking
final String? hubId;
/// Item index within the hub section
final int? itemIndex;
const _MediaCardGrid({
required this.item,
this.width,
@@ -269,308 +251,64 @@ class _MediaCardGrid extends StatefulWidget {
required this.semanticLabel,
required this.onTap,
required this.onLongPress,
this.focusNode,
this.hubId,
this.itemIndex,
});
@override
State<_MediaCardGrid> createState() => _MediaCardGridState();
}
class _MediaCardGridState extends State<_MediaCardGrid>
with KeyboardLongPressMixin {
FocusNode? _ownFocusNode;
bool _isFocused = false;
@override
void onKeyboardTap() => widget.onTap(isKeyboard: true);
@override
void onKeyboardLongPress() => widget.onLongPress();
/// Returns the effective focus node (external if provided, otherwise our own)
FocusNode get _focusNode {
if (widget.focusNode != null) return widget.focusNode!;
_ownFocusNode ??= FocusNode();
return _ownFocusNode!;
}
@override
void initState() {
super.initState();
_focusNode.addListener(_handleFocusChange);
}
@override
void didUpdateWidget(_MediaCardGrid oldWidget) {
super.didUpdateWidget(oldWidget);
// If focusNode changed, update listener
if (oldWidget.focusNode != widget.focusNode) {
oldWidget.focusNode?.removeListener(_handleFocusChange);
_focusNode.addListener(_handleFocusChange);
}
}
@override
void dispose() {
_focusNode.removeListener(_handleFocusChange);
// Only dispose if we created the node
_ownFocusNode?.dispose();
super.dispose();
}
void _handleFocusChange() {
if (_isFocused != _focusNode.hasFocus) {
setState(() {
_isFocused = _focusNode.hasFocus;
});
if (_focusNode.hasFocus) {
// Update focus memory if we're in a hub section
if (widget.hubId != null && widget.itemIndex != null) {
final controller = HubNavigationScope.maybeOf(context);
controller?.rememberFocusedIndex(widget.hubId!, widget.itemIndex!);
}
// Scroll to center only if item is not fully visible
_scrollToCenterIfNeeded();
}
}
}
/// Scrolls to center the item only if it's not already fully visible.
/// This prevents unnecessary scrolling when navigating horizontally
/// within the same row while still centering when scrolling is needed.
void _scrollToCenterIfNeeded() {
// For hub sections (nested scrollables), use simple centering
// The smart scroll logic doesn't work well with horizontal+vertical nesting
if (widget.hubId != null) {
Scrollable.ensureVisible(
context,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
return;
}
// For non-hub contexts (like library browse), use smart scrolling
final scrollable = Scrollable.maybeOf(context);
if (scrollable == null) {
// Fallback to simple centering
Scrollable.ensureVisible(
context,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
return;
}
final renderObject = context.findRenderObject();
if (renderObject == null || renderObject is! RenderBox) return;
final box = renderObject;
final scrollRenderObject = scrollable.context.findRenderObject();
if (scrollRenderObject == null) return;
// Get item's position relative to the scroll view
final transform = box.getTransformTo(scrollRenderObject);
final itemRect = MatrixUtils.transformRect(
transform,
Offset.zero & box.size,
);
// Get viewport bounds
final position = scrollable.position;
final viewportHeight = position.viewportDimension;
// Check if item is fully visible (with margin for focus indicator)
const focusMargin = 4.0;
final isFullyVisible =
itemRect.top >= focusMargin &&
itemRect.bottom <= viewportHeight - focusMargin;
if (!isFullyVisible) {
// Item is not fully visible, scroll to center it
Scrollable.ensureVisible(
context,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
// Handle long-press detection for activation keys
final longPressResult = handleKeyboardLongPress(event);
if (longPressResult == KeyEventResult.handled) {
return longPressResult;
}
if (event is KeyDownEvent) {
// Handle up/down for hub navigation
if (widget.hubId != null) {
final controller = HubNavigationScope.maybeOf(context);
if (controller != null) {
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
if (controller.navigateToAdjacentHub(widget.hubId!, -1)) {
return KeyEventResult.handled;
}
} else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
if (controller.navigateToAdjacentHub(widget.hubId!, 1)) {
return KeyEventResult.handled;
}
}
}
}
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
return Focus(
focusNode: _focusNode,
onKeyEvent: _handleKeyEvent,
child: FocusIndicator(
isFocused: _isFocused,
borderRadius: 8,
child: SizedBox(
width: widget.width,
child: Semantics(
label: widget.semanticLabel,
button: true,
child: InkWell(
onTap: () => widget.onTap(isKeyboard: false),
borderRadius: BorderRadius.circular(8),
focusColor: Colors.transparent, // We use our own focus indicator
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
return SizedBox(
width: width,
child: Semantics(
label: semanticLabel,
button: true,
child: InkWell(
canRequestFocus: false, // Keyboard handled by FocusableMediaCard
onTap: onTap,
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: [
// 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: [
Text(
widget.item is PlexPlaylist
? (widget.item as PlexPlaylist).title
: (widget.item as PlexMetadata).displayTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
height: 1.1,
),
),
if (widget.item is PlexPlaylist)
Builder(
builder: (context) {
final playlist = widget.item as PlexPlaylist;
if (playlist.leafCount != null &&
playlist.leafCount! > 0) {
return Text(
t.playlists.itemCount(
count: playlist.leafCount!,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
}
return const SizedBox.shrink();
},
)
else if (widget.item is PlexMetadata) ...[
Builder(
builder: (context) {
final metadata = widget.item as PlexMetadata;
// For collections, show item count
if (metadata.type.toLowerCase() == 'collection') {
final count =
metadata.childCount ?? metadata.leafCount;
if (count != null && count > 0) {
return Text(
t.playlists.itemCount(count: count),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
}
}
// For other media types, show subtitle/parent/year
if (metadata.displaySubtitle != null) {
return Text(
metadata.displaySubtitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
} else if (metadata.parentTitle != null) {
return Text(
metadata.parentTitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
} else if (metadata.year != null) {
return Text(
'${metadata.year}',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
}
return const SizedBox.shrink();
},
),
],
],
Text(
item is PlexPlaylist
? (item as PlexPlaylist).title
: (item as PlexMetadata).displayTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
height: 1.1,
),
),
if (item is PlexPlaylist)
_MediaCardHelpers.buildPlaylistMeta(
context,
item as PlexPlaylist,
)
else if (item is PlexMetadata)
_MediaCardHelpers.buildMetadataSubtitle(
context,
item as PlexMetadata,
),
],
),
),
],
),
),
),
@@ -583,19 +321,19 @@ class _MediaCardGridState extends State<_MediaCardGrid>
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: _buildPosterImage(context, widget.item),
child: _buildPosterImage(context, item),
),
_PosterOverlay(item: widget.item),
_PosterOverlay(item: item),
],
);
}
}
/// List layout for media cards
class _MediaCardList extends StatefulWidget {
class _MediaCardList extends StatelessWidget {
final dynamic item; // Can be PlexMetadata or PlexPlaylist
final String semanticLabel;
final void Function({bool isKeyboard}) onTap;
final VoidCallback onTap;
final VoidCallback onLongPress;
final LibraryDensity density;
@@ -607,71 +345,8 @@ class _MediaCardList extends StatefulWidget {
required this.density,
});
@override
State<_MediaCardList> createState() => _MediaCardListState();
}
class _MediaCardListState extends State<_MediaCardList>
with KeyboardLongPressMixin {
@override
void onKeyboardTap() => widget.onTap(isKeyboard: true);
@override
void onKeyboardLongPress() => widget.onLongPress();
/// Scrolls to center the item only if it's not already fully visible.
/// This prevents unnecessary scrolling when navigating horizontally
/// within the same row while still centering when scrolling is needed.
void _scrollToCenterIfNeeded(BuildContext ctx) {
final scrollable = Scrollable.maybeOf(ctx);
if (scrollable == null) {
// Fallback to simple centering
Scrollable.ensureVisible(
ctx,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
return;
}
final renderObject = ctx.findRenderObject();
if (renderObject == null || renderObject is! RenderBox) return;
final box = renderObject;
final scrollRenderObject = scrollable.context.findRenderObject();
if (scrollRenderObject == null) return;
// Get item's position relative to the scroll view
final transform = box.getTransformTo(scrollRenderObject);
final itemRect = MatrixUtils.transformRect(
transform,
Offset.zero & box.size,
);
// Get viewport bounds
final position = scrollable.position;
final viewportHeight = position.viewportDimension;
// Check if item is fully visible (with margin for focus indicator)
const focusMargin = 4.0;
final isFullyVisible =
itemRect.top >= focusMargin &&
itemRect.bottom <= viewportHeight - focusMargin;
if (!isFullyVisible) {
// Item is not fully visible, scroll to center it
Scrollable.ensureVisible(
ctx,
alignment: 0.5,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
);
}
}
double get _posterWidth {
switch (widget.density) {
switch (density) {
case LibraryDensity.compact:
return 80;
case LibraryDensity.normal:
@@ -686,7 +361,7 @@ class _MediaCardListState extends State<_MediaCardList>
}
double get _titleFontSize {
switch (widget.density) {
switch (density) {
case LibraryDensity.compact:
return 14;
case LibraryDensity.normal:
@@ -697,7 +372,7 @@ class _MediaCardListState extends State<_MediaCardList>
}
double get _metadataFontSize {
switch (widget.density) {
switch (density) {
case LibraryDensity.compact:
return 11;
case LibraryDensity.normal:
@@ -708,7 +383,7 @@ class _MediaCardListState extends State<_MediaCardList>
}
double get _subtitleFontSize {
switch (widget.density) {
switch (density) {
case LibraryDensity.compact:
return 12;
case LibraryDensity.normal:
@@ -724,7 +399,7 @@ class _MediaCardListState extends State<_MediaCardList>
}
int get _summaryMaxLines {
switch (widget.density) {
switch (density) {
case LibraryDensity.compact:
return 2;
case LibraryDensity.normal:
@@ -737,8 +412,8 @@ class _MediaCardListState extends State<_MediaCardList>
String _buildMetadataLine() {
final parts = <String>[];
if (widget.item is PlexPlaylist) {
final playlist = widget.item as PlexPlaylist;
if (item is PlexPlaylist) {
final playlist = item as PlexPlaylist;
// Add item count
if (playlist.leafCount != null && playlist.leafCount! > 0) {
parts.add(t.playlists.itemCount(count: playlist.leafCount!));
@@ -753,8 +428,8 @@ class _MediaCardListState extends State<_MediaCardList>
if (playlist.smart) {
parts.add(t.playlists.smartPlaylist);
}
} else if (widget.item is PlexMetadata) {
final metadata = widget.item as PlexMetadata;
} else if (item is PlexMetadata) {
final metadata = item as PlexMetadata;
// For collections, show item count
if (metadata.type.toLowerCase() == 'collection') {
@@ -799,11 +474,11 @@ class _MediaCardListState extends State<_MediaCardList>
}
String? _buildSubtitleText() {
if (widget.item is PlexPlaylist) {
if (item is PlexPlaylist) {
// Playlists don't have subtitles
return null;
} else if (widget.item is PlexMetadata) {
final metadata = widget.item as PlexMetadata;
} else if (item is PlexMetadata) {
final metadata = item as PlexMetadata;
// For TV episodes, show S#E# format
if (metadata.parentIndex != null && metadata.index != null) {
@@ -827,112 +502,101 @@ class _MediaCardListState extends State<_MediaCardList>
final metadataLine = _buildMetadataLine();
final subtitle = _buildSubtitleText();
return FocusableWrapper(
onKeyEvent: (node, event) => handleKeyboardLongPress(event),
onScrollIntoView: _scrollToCenterIfNeeded,
builder: (context, isFocused) => FocusIndicator(
isFocused: isFocused,
borderRadius: 8,
child: Semantics(
label: widget.semanticLabel,
button: true,
child: InkWell(
onTap: () => widget.onTap(isKeyboard: false),
borderRadius: BorderRadius.circular(8),
focusColor: Colors.transparent, // We use our own focus indicator
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, widget.item),
),
_PosterOverlay(item: widget.item),
],
return Semantics(
label: semanticLabel,
button: true,
child: InkWell(
canRequestFocus: false, // Keyboard handled by FocusableMediaCard
onTap: onTap,
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, item),
),
),
const SizedBox(width: 12),
// Metadata
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
// Title
Text(
widget.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 (widget.item.summary != null) ...[
Text(
widget.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,
),
),
],
],
),
),
],
_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,
),
),
],
],
),
),
],
),
),
),
@@ -973,7 +637,7 @@ Widget _buildPosterImage(BuildContext context, dynamic item) {
posterUrl = item.displayImage;
fallbackIcon = Icons.playlist_play;
return PlexPlaylistImage(
return PlexOptimizedImage.playlist(
client: _getClientForItem(context, item),
imagePath: posterUrl,
width: double.infinity,
@@ -984,7 +648,7 @@ Widget _buildPosterImage(BuildContext context, dynamic item) {
final useSeasonPoster = context.watch<SettingsProvider>().useSeasonPoster;
posterUrl = item.posterThumb(useSeasonPoster: useSeasonPoster);
return PlexPosterImage(
return PlexOptimizedImage.poster(
client: _getClientForItem(context, item),
imagePath: posterUrl,
width: double.infinity,
@@ -1011,8 +675,93 @@ class _PosterOverlay extends StatelessWidget {
return const SizedBox.shrink();
}
final metadata = item as PlexMetadata;
return _MediaCardHelpers.buildWatchProgress(context, item as PlexMetadata);
}
}
/// Helper methods for building media card metadata and subtitles
class _MediaCardHelpers {
/// Builds playlist metadata (item count)
static Widget buildPlaylistMeta(BuildContext context, PlexPlaylist playlist) {
if (playlist.leafCount != null && playlist.leafCount! > 0) {
return Text(
t.playlists.itemCount(count: playlist.leafCount!),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
}
return const SizedBox.shrink();
}
/// Builds metadata subtitle (for collections, episodes, movies, shows)
static Widget buildMetadataSubtitle(
BuildContext context,
PlexMetadata metadata,
) {
// For collections, show item count
if (metadata.type.toLowerCase() == 'collection') {
final count = metadata.childCount ?? metadata.leafCount;
if (count != null && count > 0) {
return Text(
t.playlists.itemCount(count: count),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
}
}
// For other media types, show subtitle/parent/year
if (metadata.displaySubtitle != null) {
return Text(
metadata.displaySubtitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
} else if (metadata.parentTitle != null) {
return Text(
metadata.parentTitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
} else if (metadata.year != null) {
return Text(
'${metadata.year}',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
);
}
return const SizedBox.shrink();
}
/// Builds watch progress overlay (checkmark for watched, progress bar for in-progress)
static Widget buildWatchProgress(
BuildContext context,
PlexMetadata metadata,
) {
return Stack(
children: [
// Watched indicator (checkmark)
+148 -342
View File
@@ -1,21 +1,20 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../services/plex_client.dart';
import '../services/plex_client.dart';
import '../services/play_queue_launcher.dart';
import '../models/plex_metadata.dart';
import '../models/plex_playlist.dart';
import '../providers/multi_server_provider.dart';
import '../providers/playback_state_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/app_logger.dart';
import '../utils/collection_playlist_play_helper.dart';
import '../utils/keyboard_utils.dart';
import '../utils/library_refresh_notifier.dart';
import '../utils/video_player_navigation.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import '../widgets/file_info_bottom_sheet.dart';
import '../widgets/focusable_bottom_sheet.dart';
import '../widgets/focusable_list_tile.dart';
import '../i18n/strings.g.dart';
/// Helper class to store menu action data
@@ -64,6 +63,9 @@ class MediaContextMenuState extends State<MediaContextMenu> {
}
bool _openedFromKeyboard = false;
bool _isContextMenuOpen = false;
bool get isContextMenuOpen => _isContextMenuOpen;
/// Show the context menu programmatically.
/// Used for keyboard/gamepad long-press activation.
@@ -113,8 +115,14 @@ class MediaContextMenuState extends State<MediaContextMenu> {
return context.getClientForServer(serverId);
}
void _handleTap() {
if (_isContextMenuOpen) return;
widget.onTap?.call();
}
void _showContextMenu(BuildContext context) async {
final client = _getClientForItem();
if (_isContextMenuOpen) return;
_isContextMenuOpen = true;
final isPlaylist = widget.item is PlexPlaylist;
final metadata = isPlaylist ? null : widget.item as PlexMetadata;
@@ -307,101 +315,104 @@ class MediaContextMenuState extends State<MediaContextMenu> {
);
}
if (!context.mounted) return;
try {
final client = _getClientForItem();
switch (selected) {
case 'watch':
await _executeAction(
context,
() => client.markAsWatched(metadata!.ratingKey),
t.messages.markedAsWatched,
);
break;
if (!context.mounted) return;
case 'unwatch':
await _executeAction(
context,
() => client.markAsUnwatched(metadata!.ratingKey),
t.messages.markedAsUnwatched,
);
break;
switch (selected) {
case 'watch':
await _executeAction(
context,
() => client.markAsWatched(metadata!.ratingKey),
t.messages.markedAsWatched,
);
break;
case 'remove_from_continue_watching':
// Remove from Continue Watching without affecting watch status or progress
// This preserves the progression for partially watched items
// and doesn't mark unwatched next episodes as watched
try {
await client.removeFromOnDeck(metadata!.ratingKey);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.messages.removedFromContinueWatching)),
);
// Use specific callback if provided, otherwise fallback to onRefresh
if (widget.onRemoveFromContinueWatching != null) {
widget.onRemoveFromContinueWatching!();
} else {
widget.onRefresh?.call(metadata.ratingKey);
case 'unwatch':
await _executeAction(
context,
() => client.markAsUnwatched(metadata!.ratingKey),
t.messages.markedAsUnwatched,
);
break;
case 'remove_from_continue_watching':
// Remove from Continue Watching without affecting watch status or progress
// This preserves the progression for partially watched items
// and doesn't mark unwatched next episodes as watched
try {
await client.removeFromOnDeck(metadata!.ratingKey);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.messages.removedFromContinueWatching)),
);
// Use specific callback if provided, otherwise fallback to onRefresh
if (widget.onRemoveFromContinueWatching != null) {
widget.onRemoveFromContinueWatching!();
} else {
widget.onRefresh?.call(metadata.ratingKey);
}
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(t.messages.errorLoading(error: e.toString())),
),
);
}
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(t.messages.errorLoading(error: e.toString())),
),
);
}
}
break;
break;
case 'remove_from_collection':
await _handleRemoveFromCollection(context, metadata!);
break;
case 'remove_from_collection':
await _handleRemoveFromCollection(context, metadata!);
break;
case 'series':
await _navigateToRelated(
context,
metadata!.grandparentRatingKey,
(metadata) => MediaDetailScreen(metadata: metadata),
t.messages.errorLoadingSeries,
);
break;
case 'series':
await _navigateToRelated(
context,
metadata!.grandparentRatingKey,
(metadata) => MediaDetailScreen(metadata: metadata),
t.messages.errorLoadingSeries,
);
break;
case 'season':
await _navigateToRelated(
context,
metadata!.parentRatingKey,
(metadata) => SeasonDetailScreen(
season: metadata,
focusFirstEpisode: _openedFromKeyboard,
),
t.messages.errorLoadingSeason,
);
break;
case 'season':
await _navigateToRelated(
context,
metadata!.parentRatingKey,
(metadata) => SeasonDetailScreen(season: metadata),
t.messages.errorLoadingSeason,
);
break;
case 'fileinfo':
await _showFileInfo(context);
break;
case 'fileinfo':
await _showFileInfo(context);
break;
case 'add_to':
await _showAddToSubmenu(context);
break;
case 'add_to':
await _showAddToSubmenu(context);
break;
case 'shuffle_play':
await _handleShufflePlayWithQueue(context);
break;
case 'shuffle_play':
await _handleShufflePlayWithQueue(context);
break;
case 'play':
await _handlePlay(context, isCollection, isPlaylist);
break;
case 'play':
await _handlePlay(context, isCollection, isPlaylist);
break;
case 'shuffle':
await _handleShuffle(context, isCollection, isPlaylist);
break;
case 'shuffle':
await _handleShuffle(context, isCollection, isPlaylist);
break;
case 'delete':
await _handleDelete(context, isCollection, isPlaylist);
break;
case 'delete':
await _handleDelete(context, isCollection, isPlaylist);
break;
}
} finally {
_isContextMenuOpen = false;
}
}
@@ -514,91 +525,19 @@ class MediaContextMenuState extends State<MediaContextMenu> {
/// Handle shuffle play using play queues
Future<void> _handleShufflePlayWithQueue(BuildContext context) async {
final client = _getClientForItem();
final metadata = widget.item as PlexMetadata;
final playbackState = context.read<PlaybackStateProvider>();
final itemType = metadata.type.toLowerCase();
try {
// Show loading indicator
if (context.mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) =>
const Center(child: CircularProgressIndicator()),
);
}
final launcher = PlayQueueLauncher(
context: context,
client: client,
serverId: metadata.serverId,
serverName: metadata.serverName,
);
// Determine the rating key for the play queue
String showRatingKey;
if (itemType == 'show') {
showRatingKey = metadata.ratingKey;
} else if (itemType == 'season') {
// For seasons, we need the show's rating key
// The season's parentRatingKey should point to the show
if (metadata.parentRatingKey == null) {
throw Exception('Season is missing parentRatingKey');
}
showRatingKey = metadata.parentRatingKey!;
} else {
throw Exception('Shuffle play only works for shows and seasons');
}
// Create a shuffled play queue for the show
final playQueue = await client.createShowPlayQueue(
showRatingKey: showRatingKey,
shuffle: 1,
);
// Close loading indicator
if (context.mounted) {
Navigator.pop(context);
}
if (playQueue == null ||
playQueue.items == null ||
playQueue.items!.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(t.messages.noEpisodesFound)));
}
return;
}
// Initialize playback state with the play queue
await playbackState.setPlaybackFromPlayQueue(
playQueue,
showRatingKey,
serverId: metadata.serverId,
serverName: metadata.serverName,
);
// Set the client for the playback state provider
playbackState.setClient(client);
// Navigate to the first episode in the shuffled queue
final firstEpisode = playQueue.items!.first.copyWith(
serverId: metadata.serverId,
serverName: metadata.serverName,
);
if (context.mounted) {
await navigateToVideoPlayer(context, metadata: firstEpisode);
}
} 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(t.messages.errorLoading(error: e.toString()))),
);
}
}
await launcher.launchShuffledShow(
metadata: metadata,
showLoadingIndicator: true,
);
}
/// Show submenu for Add to... (Playlist or Collection)
@@ -1213,7 +1152,7 @@ class MediaContextMenuState extends State<MediaContextMenu> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
onTap: _handleTap,
onTapDown: _storeTapPosition,
onLongPress: () => _showContextMenu(context),
onSecondaryTapDown: _storeTapPosition,
@@ -1446,70 +1385,24 @@ class _FocusableContextMenuSheet extends StatefulWidget {
class _FocusableContextMenuSheetState
extends State<_FocusableContextMenuSheet> {
late List<FocusNode> _focusNodes;
int _focusedIndex = 0;
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_focusNodes = List.generate(
widget.actions.length,
(index) => FocusNode(debugLabel: 'ContextMenuItem$index'),
);
if (widget.focusFirstItem && widget.actions.isNotEmpty) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusNodes[0].requestFocus();
});
}
_initialFocusNode = FocusNode(debugLabel: 'ContextMenuSheetInitialFocus');
}
@override
void dispose() {
for (final node in _focusNodes) {
node.dispose();
}
_initialFocusNode.dispose();
super.dispose();
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
// Close on back keys
if (isBackKey(event.logicalKey)) {
Navigator.pop(context);
return KeyEventResult.handled;
}
// Navigate with arrow keys
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
if (_focusedIndex > 0) {
_focusedIndex--;
_focusNodes[_focusedIndex].requestFocus();
}
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
if (_focusedIndex < widget.actions.length - 1) {
_focusedIndex++;
_focusNodes[_focusedIndex].requestFocus();
}
return KeyEventResult.handled;
}
// Select with Enter/Space
if (isKeyboardActivationKey(event.logicalKey)) {
Navigator.pop(context, widget.actions[_focusedIndex].value);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
return Focus(
onKeyEvent: _handleKeyEvent,
return FocusableBottomSheet(
initialFocusNode: widget.focusFirstItem ? _initialFocusNode : null,
child: SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
@@ -1526,27 +1419,11 @@ class _FocusableContextMenuSheetState
...widget.actions.asMap().entries.map((entry) {
final index = entry.key;
final action = entry.value;
return Focus(
focusNode: _focusNodes[index],
onFocusChange: (hasFocus) {
if (hasFocus) {
setState(() => _focusedIndex = index);
}
},
child: Builder(
builder: (context) {
final isFocused = Focus.of(context).hasFocus;
return ListTile(
leading: Icon(action.icon),
title: Text(action.label),
onTap: () => Navigator.pop(context, action.value),
selected: isFocused,
selectedTileColor: Theme.of(
context,
).colorScheme.primary.withValues(alpha: 0.1),
);
},
),
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
leading: Icon(action.icon),
title: Text(action.label),
onTap: () => Navigator.pop(context, action.value),
);
}),
],
@@ -1573,66 +1450,27 @@ class _FocusablePopupMenu extends StatefulWidget {
}
class _FocusablePopupMenuState extends State<_FocusablePopupMenu> {
late List<FocusNode> _focusNodes;
int _focusedIndex = 0;
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_focusNodes = List.generate(
widget.actions.length,
(index) => FocusNode(debugLabel: 'PopupMenuItem$index'),
);
if (widget.focusFirstItem && widget.actions.isNotEmpty) {
_initialFocusNode = FocusNode(debugLabel: 'PopupMenuInitialFocus');
if (widget.focusFirstItem) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusNodes[0].requestFocus();
if (mounted) {
_initialFocusNode.requestFocus();
}
});
}
}
@override
void dispose() {
for (final node in _focusNodes) {
node.dispose();
}
_initialFocusNode.dispose();
super.dispose();
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
// Close on back keys
if (isBackKey(event.logicalKey)) {
Navigator.pop(context);
return KeyEventResult.handled;
}
// Navigate with arrow keys
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
if (_focusedIndex > 0) {
_focusedIndex--;
_focusNodes[_focusedIndex].requestFocus();
}
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
if (_focusedIndex < widget.actions.length - 1) {
_focusedIndex++;
_focusNodes[_focusedIndex].requestFocus();
}
return KeyEventResult.handled;
}
// Select with Enter/Space
if (isKeyboardActivationKey(event.logicalKey)) {
Navigator.pop(context, widget.actions[_focusedIndex].value);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final screenSize = MediaQuery.of(context).size;
@@ -1667,60 +1505,28 @@ class _FocusablePopupMenuState extends State<_FocusablePopupMenu> {
Positioned(
left: left,
top: top,
child: Focus(
autofocus: !widget.focusFirstItem,
onKeyEvent: _handleKeyEvent,
child: Material(
elevation: 8,
borderRadius: BorderRadius.circular(8),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: menuWidth,
maxWidth: menuWidth,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: widget.actions.asMap().entries.map((entry) {
final index = entry.key;
final action = entry.value;
return Focus(
focusNode: _focusNodes[index],
onFocusChange: (hasFocus) {
if (hasFocus) {
setState(() => _focusedIndex = index);
}
},
child: Builder(
builder: (context) {
final isFocused = Focus.of(context).hasFocus;
return InkWell(
onTap: () => Navigator.pop(context, action.value),
child: Container(
color: isFocused
? Theme.of(
context,
).colorScheme.primary.withValues(alpha: 0.1)
: null,
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
child: Row(
children: [
Icon(action.icon, size: 20),
const SizedBox(width: 12),
Expanded(child: Text(action.label)),
],
),
),
);
},
),
);
}).toList(),
),
child: Material(
elevation: 8,
borderRadius: BorderRadius.circular(8),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: menuWidth,
maxWidth: menuWidth,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: widget.actions.asMap().entries.map((entry) {
final index = entry.key;
final action = entry.value;
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
leading: Icon(action.icon, size: 20),
title: Text(action.label),
onTap: () => Navigator.pop(context, action.value),
);
}).toList(),
),
),
),
+39
View File
@@ -0,0 +1,39 @@
import 'package:flutter/material.dart';
import '../services/settings_service.dart';
import '../utils/grid_size_calculator.dart';
import '../utils/grid_cross_axis_extent.dart';
/// Shared grid delegate configuration for media item grids
/// Maintains consistent spacing (2/3.3 aspect ratio, 0 spacing) across all media grids
class MediaGridDelegate {
/// Standard aspect ratio for media cards (poster aspect)
static const double aspectRatio = 2 / 3.3;
/// Standard cross-axis spacing between grid items
static const double crossAxisSpacing = 0;
/// Standard main-axis spacing between grid items
static const double mainAxisSpacing = 0;
/// Creates a standard grid delegate for media items
///
/// Uses [GridSizeCalculator.getMaxCrossAxisExtent] by default.
/// Set [usePaddingAware] to true to use [getMaxCrossAxisExtentWithPadding] instead.
static SliverGridDelegateWithMaxCrossAxisExtent createDelegate({
required BuildContext context,
required LibraryDensity density,
bool usePaddingAware = false,
double horizontalPadding = 16,
}) {
final maxCrossAxisExtent = usePaddingAware
? getMaxCrossAxisExtentWithPadding(context, density, horizontalPadding)
: GridSizeCalculator.getMaxCrossAxisExtent(context, density);
return SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: maxCrossAxisExtent,
childAspectRatio: aspectRatio,
crossAxisSpacing: crossAxisSpacing,
mainAxisSpacing: mainAxisSpacing,
);
}
}
+75
View File
@@ -0,0 +1,75 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/settings_provider.dart';
import 'media_card.dart';
import 'media_grid_delegate.dart';
/// Shared sliver grid builder for displaying media items
/// Used across hub detail, collection detail, playlist detail, and library browse screens
/// to maintain consistent spacing and focus behavior
class MediaGridSliver extends StatelessWidget {
/// The list of media items to display
final List<PlexMetadata> items;
/// Callback when an item needs to be refreshed
final void Function(String ratingKey)? onRefresh;
/// Optional collection ID for collection-specific functionality
final String? collectionId;
/// Optional callback to refresh the entire parent list
final VoidCallback? onListRefresh;
/// Padding around the grid
/// Defaults to EdgeInsets.fromLTRB(8, 0, 8, 8)
final EdgeInsets padding;
/// Whether to use the padding-aware cross axis extent calculation
/// Defaults to false (uses standard GridSizeCalculator)
final bool usePaddingAwareExtent;
/// Horizontal padding to account for when usePaddingAwareExtent is true
/// Only used if usePaddingAwareExtent is true
final double horizontalPadding;
const MediaGridSliver({
super.key,
required this.items,
this.onRefresh,
this.collectionId,
this.onListRefresh,
this.padding = const EdgeInsets.fromLTRB(8, 0, 8, 8),
this.usePaddingAwareExtent = false,
this.horizontalPadding = 16,
});
@override
Widget build(BuildContext context) {
return SliverPadding(
padding: padding,
sliver: Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SliverGrid(
gridDelegate: MediaGridDelegate.createDelegate(
context: context,
density: settingsProvider.libraryDensity,
usePaddingAware: usePaddingAwareExtent,
horizontalPadding: horizontalPadding,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: onRefresh,
collectionId: collectionId,
onListRefresh: onListRefresh,
);
}, childCount: items.length),
);
},
),
);
}
}
+167 -58
View File
@@ -20,7 +20,7 @@ class PlexOptimizedImage extends StatelessWidget {
final IconData? fallbackIcon;
final ImageType imageType;
const PlexOptimizedImage({
const PlexOptimizedImage._({
super.key,
required this.client,
required this.imagePath,
@@ -38,6 +38,172 @@ class PlexOptimizedImage extends StatelessWidget {
this.imageType = ImageType.poster,
});
/// Generic constructor for optimized images.
const factory PlexOptimizedImage({
Key? key,
required PlexClient client,
required String? imagePath,
double? width,
double? height,
BoxFit fit,
FilterQuality filterQuality,
Widget Function(BuildContext, String)? placeholder,
Widget Function(BuildContext, String, dynamic)? errorWidget,
Duration fadeInDuration,
bool enableTranscoding,
String? cacheKey,
Alignment alignment,
IconData? fallbackIcon,
ImageType imageType,
}) = PlexOptimizedImage._;
/// Named constructor for poster images with default fallback icon.
const factory PlexOptimizedImage.poster({
Key? key,
required PlexClient client,
required String? imagePath,
double? width,
double? height,
BoxFit fit,
FilterQuality filterQuality,
Widget Function(BuildContext, String)? placeholder,
Widget Function(BuildContext, String, dynamic)? errorWidget,
Duration fadeInDuration,
bool enableTranscoding,
String? cacheKey,
Alignment alignment,
}) = PlexOptimizedImage._poster;
/// Named constructor for episode thumbnails.
const factory PlexOptimizedImage.thumb({
Key? key,
required PlexClient client,
required String? imagePath,
double? width,
double? height,
BoxFit fit,
FilterQuality filterQuality,
Widget Function(BuildContext, String)? placeholder,
Widget Function(BuildContext, String, dynamic)? errorWidget,
Duration fadeInDuration,
bool enableTranscoding,
String? cacheKey,
Alignment alignment,
}) = PlexOptimizedImage._thumb;
/// Named constructor for playlist images.
const factory PlexOptimizedImage.playlist({
Key? key,
required PlexClient client,
required String? imagePath,
double? width,
double? height,
BoxFit fit,
FilterQuality filterQuality,
Widget Function(BuildContext, String)? placeholder,
Widget Function(BuildContext, String, dynamic)? errorWidget,
Duration fadeInDuration,
bool enableTranscoding,
String? cacheKey,
Alignment alignment,
}) = PlexOptimizedImage._playlist;
const PlexOptimizedImage._poster({
Key? key,
required PlexClient client,
required String? imagePath,
double? width,
double? height,
BoxFit fit = BoxFit.cover,
FilterQuality filterQuality = FilterQuality.medium,
Widget Function(BuildContext, String)? placeholder,
Widget Function(BuildContext, String, dynamic)? errorWidget,
Duration fadeInDuration = const Duration(milliseconds: 300),
bool enableTranscoding = true,
String? cacheKey,
Alignment alignment = Alignment.center,
}) : this._(
key: key,
client: client,
imagePath: imagePath,
width: width,
height: height,
fit: fit,
filterQuality: filterQuality,
placeholder: placeholder,
errorWidget: errorWidget,
fadeInDuration: fadeInDuration,
enableTranscoding: enableTranscoding,
cacheKey: cacheKey,
alignment: alignment,
fallbackIcon: Icons.movie,
imageType: ImageType.poster,
);
const PlexOptimizedImage._thumb({
Key? key,
required PlexClient client,
required String? imagePath,
double? width,
double? height,
BoxFit fit = BoxFit.cover,
FilterQuality filterQuality = FilterQuality.medium,
Widget Function(BuildContext, String)? placeholder,
Widget Function(BuildContext, String, dynamic)? errorWidget,
Duration fadeInDuration = const Duration(milliseconds: 300),
bool enableTranscoding = true,
String? cacheKey,
Alignment alignment = Alignment.center,
}) : this._(
key: key,
client: client,
imagePath: imagePath,
width: width,
height: height,
fit: fit,
filterQuality: filterQuality,
placeholder: placeholder,
errorWidget: errorWidget,
fadeInDuration: fadeInDuration,
enableTranscoding: enableTranscoding,
cacheKey: cacheKey,
alignment: alignment,
fallbackIcon: Icons.video_library,
imageType: ImageType.thumb,
);
const PlexOptimizedImage._playlist({
Key? key,
required PlexClient client,
required String? imagePath,
double? width,
double? height,
BoxFit fit = BoxFit.cover,
FilterQuality filterQuality = FilterQuality.medium,
Widget Function(BuildContext, String)? placeholder,
Widget Function(BuildContext, String, dynamic)? errorWidget,
Duration fadeInDuration = const Duration(milliseconds: 300),
bool enableTranscoding = true,
String? cacheKey,
Alignment alignment = Alignment.center,
}) : this._(
key: key,
client: client,
imagePath: imagePath,
width: width,
height: height,
fit: fit,
filterQuality: filterQuality,
placeholder: placeholder,
errorWidget: errorWidget,
fadeInDuration: fadeInDuration,
enableTranscoding: enableTranscoding,
cacheKey: cacheKey,
alignment: alignment,
fallbackIcon: Icons.playlist_play,
imageType: ImageType.poster,
);
@override
Widget build(BuildContext context) {
double resolvedDimension(
@@ -176,60 +342,3 @@ class PlexOptimizedImage extends StatelessWidget {
return 'plex_optimized_${memWidth}x${memHeight}_$urlHash';
}
}
/// Specialized version for posters with default fallback icon
class PlexPosterImage extends PlexOptimizedImage {
const PlexPosterImage({
super.key,
required super.client,
required super.imagePath,
super.width,
super.height,
super.fit = BoxFit.cover,
super.filterQuality = FilterQuality.medium,
super.placeholder,
super.errorWidget,
super.fadeInDuration = const Duration(milliseconds: 300),
super.enableTranscoding = true,
super.cacheKey,
super.alignment = Alignment.center,
}) : super(fallbackIcon: Icons.movie, imageType: ImageType.poster);
}
/// Specialized version for episode thumbnails
class PlexThumbImage extends PlexOptimizedImage {
const PlexThumbImage({
super.key,
required super.client,
required super.imagePath,
super.width,
super.height,
super.fit = BoxFit.cover,
super.filterQuality = FilterQuality.medium,
super.placeholder,
super.errorWidget,
super.fadeInDuration = const Duration(milliseconds: 300),
super.enableTranscoding = true,
super.cacheKey,
super.alignment = Alignment.center,
}) : super(fallbackIcon: Icons.video_library, imageType: ImageType.thumb);
}
/// Specialized version for playlist images
class PlexPlaylistImage extends PlexOptimizedImage {
const PlexPlaylistImage({
super.key,
required super.client,
required super.imagePath,
super.width,
super.height,
super.fit = BoxFit.cover,
super.filterQuality = FilterQuality.medium,
super.placeholder,
super.errorWidget,
super.fadeInDuration = const Duration(milliseconds: 300),
super.enableTranscoding = true,
super.cacheKey,
super.alignment = Alignment.center,
}) : super(fallbackIcon: Icons.playlist_play, imageType: ImageType.poster);
}
+630
View File
@@ -0,0 +1,630 @@
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../focus/dpad_navigator.dart';
import '../models/plex_library.dart';
import '../providers/hidden_libraries_provider.dart';
import '../providers/multi_server_provider.dart';
import '../services/fullscreen_state_manager.dart';
import '../services/storage_service.dart';
import '../theme/theme_helper.dart';
import '../i18n/strings.g.dart';
/// Reusable navigation rail item widget that handles focus, selection, and interaction
class NavigationRailItem extends StatelessWidget {
final IconData icon;
final IconData? selectedIcon;
final Widget label;
final bool isSelected;
final bool isFocused;
final VoidCallback onTap;
final FocusNode focusNode;
final bool autofocus;
final EdgeInsets padding;
final BorderRadius borderRadius;
final double iconSize;
const NavigationRailItem({
super.key,
required this.icon,
this.selectedIcon,
required this.label,
required this.isSelected,
required this.isFocused,
required this.onTap,
required this.focusNode,
this.autofocus = false,
this.padding = const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
this.borderRadius = const BorderRadius.all(Radius.circular(12)),
this.iconSize = 22,
});
@override
Widget build(BuildContext context) {
final t = tokens(context);
return Focus(
focusNode: focusNode,
autofocus: autofocus,
onKeyEvent: (node, event) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
if (event.logicalKey.isSelectKey) {
onTap();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: borderRadius,
child: Container(
padding: padding,
decoration: BoxDecoration(
color: isSelected && isFocused
? t.text.withValues(alpha: 0.15) // Selected + focused
: isSelected
? t.text.withValues(alpha: 0.1) // Just selected
: isFocused
? t.text.withValues(alpha: 0.12) // Just focused (more visible)
: null,
borderRadius: borderRadius,
),
child: Row(
children: [
Icon(
isSelected && selectedIcon != null ? selectedIcon! : icon,
size: iconSize,
color: isSelected ? t.text : t.textMuted,
),
const SizedBox(width: 12),
Expanded(child: label),
],
),
),
),
),
);
}
}
/// Side navigation rail for Desktop and Android TV platforms
class SideNavigationRail extends StatefulWidget {
final int selectedIndex;
final String? selectedLibraryKey;
final ValueChanged<int> onDestinationSelected;
final ValueChanged<String> onLibrarySelected;
const SideNavigationRail({
super.key,
required this.selectedIndex,
this.selectedLibraryKey,
required this.onDestinationSelected,
required this.onLibrarySelected,
});
@override
State<SideNavigationRail> createState() => SideNavigationRailState();
}
class SideNavigationRailState extends State<SideNavigationRail> {
bool _librariesExpanded = true;
List<PlexLibrary> _libraries = [];
bool _isLoadingLibraries = true;
// Focus nodes for main nav items
late FocusNode _homeFocusNode;
late FocusNode _librariesFocusNode;
late FocusNode _searchFocusNode;
late FocusNode _settingsFocusNode;
// Focus state tracking
bool _isHomeFocused = false;
bool _isLibrariesFocused = false;
bool _isSearchFocused = false;
bool _isSettingsFocused = false;
// Map to store library item focus nodes and states
final Map<String, FocusNode> _libraryFocusNodes = {};
final Set<String> _focusedLibraryKeys = {};
@override
void initState() {
super.initState();
_homeFocusNode = FocusNode(debugLabel: 'nav_home');
_librariesFocusNode = FocusNode(debugLabel: 'nav_libraries');
_searchFocusNode = FocusNode(debugLabel: 'nav_search');
_settingsFocusNode = FocusNode(debugLabel: 'nav_settings');
_homeFocusNode.addListener(
() => _onFocusChange(_homeFocusNode, () {
setState(() => _isHomeFocused = _homeFocusNode.hasFocus);
}),
);
_librariesFocusNode.addListener(
() => _onFocusChange(_librariesFocusNode, () {
setState(() => _isLibrariesFocused = _librariesFocusNode.hasFocus);
}),
);
_searchFocusNode.addListener(
() => _onFocusChange(_searchFocusNode, () {
setState(() => _isSearchFocused = _searchFocusNode.hasFocus);
}),
);
_settingsFocusNode.addListener(
() => _onFocusChange(_settingsFocusNode, () {
setState(() => _isSettingsFocused = _settingsFocusNode.hasFocus);
}),
);
_loadLibraries();
}
void _onFocusChange(FocusNode node, VoidCallback updateState) {
if (mounted) updateState();
}
@override
void dispose() {
_homeFocusNode.dispose();
_librariesFocusNode.dispose();
_searchFocusNode.dispose();
_settingsFocusNode.dispose();
for (final node in _libraryFocusNodes.values) {
node.dispose();
}
super.dispose();
}
/// Get or create a focus node for a library item
FocusNode _getLibraryFocusNode(String globalKey) {
return _libraryFocusNodes.putIfAbsent(globalKey, () {
final node = FocusNode(debugLabel: 'nav_library_$globalKey');
node.addListener(() {
if (mounted) {
setState(() {
if (node.hasFocus) {
_focusedLibraryKeys.add(globalKey);
} else {
_focusedLibraryKeys.remove(globalKey);
}
});
}
});
return node;
});
}
/// Focus the currently selected nav item
void focusActiveItem() {
if (widget.selectedLibraryKey != null) {
// A library is selected - focus that library item
final node = _libraryFocusNodes[widget.selectedLibraryKey];
node?.requestFocus();
} else {
// Focus main nav item based on selectedIndex
switch (widget.selectedIndex) {
case 0:
_homeFocusNode.requestFocus();
break;
case 1:
_librariesFocusNode.requestFocus();
break;
case 2:
_searchFocusNode.requestFocus();
break;
case 3:
_settingsFocusNode.requestFocus();
break;
}
}
}
Future<void> _loadLibraries() async {
final multiServerProvider = context.read<MultiServerProvider>();
if (!multiServerProvider.hasConnectedServers) {
setState(() {
_isLoadingLibraries = false;
});
return;
}
try {
final libraries = await multiServerProvider.aggregationService
.getLibrariesFromAllServers();
// Filter out music libraries (not supported)
var filteredLibraries = libraries
.where((lib) => lib.type != 'artist')
.toList();
// Apply saved library order
final storage = await StorageService.getInstance();
final savedOrder = storage.getLibraryOrder();
if (savedOrder != null && savedOrder.isNotEmpty) {
final libraryMap = {
for (var lib in filteredLibraries) lib.globalKey: lib,
};
final orderedLibraries = <PlexLibrary>[];
for (final key in savedOrder) {
if (libraryMap.containsKey(key)) {
orderedLibraries.add(libraryMap[key]!);
libraryMap.remove(key);
}
}
// Add any new libraries not in saved order
orderedLibraries.addAll(libraryMap.values);
filteredLibraries = orderedLibraries;
}
if (mounted) {
setState(() {
_libraries = filteredLibraries;
_isLoadingLibraries = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_isLoadingLibraries = false;
});
}
}
}
/// Reload libraries (called when servers change)
void reloadLibraries() {
setState(() {
_isLoadingLibraries = true;
});
_loadLibraries();
}
IconData _getLibraryIcon(String type) {
switch (type.toLowerCase()) {
case 'movie':
return Icons.movie_outlined;
case 'show':
return Icons.tv_outlined;
case 'artist':
return Icons.music_note_outlined;
case 'photo':
return Icons.photo_outlined;
default:
return Icons.folder_outlined;
}
}
IconData _getLibraryIconFilled(String type) {
switch (type.toLowerCase()) {
case 'movie':
return Icons.movie;
case 'show':
return Icons.tv;
case 'artist':
return Icons.music_note;
case 'photo':
return Icons.photo;
default:
return Icons.folder;
}
}
/// Calculate top padding for macOS traffic lights
double _getTopPadding(BuildContext context) {
double basePadding = MediaQuery.of(context).padding.top + 16;
// On macOS, add extra padding for traffic lights (when not fullscreen)
if (Platform.isMacOS) {
final isFullscreen = FullscreenStateManager().isFullscreen;
if (!isFullscreen) {
// Traffic lights area is approximately 52 pixels high
basePadding = basePadding < 52 ? 52 : basePadding;
}
}
return basePadding;
}
@override
Widget build(BuildContext context) {
final t = tokens(context);
final hiddenLibrariesProvider = context.watch<HiddenLibrariesProvider>();
final hiddenKeys = hiddenLibrariesProvider.hiddenLibraryKeys;
// Filter visible libraries
final visibleLibraries = _libraries
.where((lib) => !hiddenKeys.contains(lib.globalKey))
.toList();
// Listen to fullscreen changes for macOS
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
return Container(
width: 220,
color: t.surface,
child: Column(
children: [
// Safe area for status bar and macOS traffic lights
SizedBox(height: _getTopPadding(context)),
// Navigation content
Expanded(
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 12),
children: [
// Home
_buildNavItem(
icon: Icons.home_outlined,
selectedIcon: Icons.home,
label: Translations.of(context).navigation.home,
isSelected: widget.selectedIndex == 0,
isFocused: _isHomeFocused,
onTap: () => widget.onDestinationSelected(0),
focusNode: _homeFocusNode,
),
const SizedBox(height: 8),
// Libraries section
_buildLibrariesSection(visibleLibraries, t),
const SizedBox(height: 8),
// Search
_buildNavItem(
icon: Icons.search,
selectedIcon: Icons.search,
label: Translations.of(context).navigation.search,
isSelected: widget.selectedIndex == 2,
isFocused: _isSearchFocused,
onTap: () => widget.onDestinationSelected(2),
focusNode: _searchFocusNode,
),
const SizedBox(height: 8),
// Settings
_buildNavItem(
icon: Icons.settings_outlined,
selectedIcon: Icons.settings,
label: Translations.of(context).navigation.settings,
isSelected: widget.selectedIndex == 3,
isFocused: _isSettingsFocused,
onTap: () => widget.onDestinationSelected(3),
focusNode: _settingsFocusNode,
),
],
),
),
],
),
);
},
);
}
Widget _buildNavItem({
required IconData icon,
required IconData selectedIcon,
required String label,
required bool isSelected,
required bool isFocused,
required VoidCallback onTap,
required FocusNode focusNode,
bool autofocus = false,
}) {
final t = tokens(context);
return NavigationRailItem(
icon: icon,
selectedIcon: selectedIcon,
label: Text(
label,
style: TextStyle(
fontSize: 14,
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
color: isSelected ? t.text : t.textMuted,
),
),
isSelected: isSelected,
isFocused: isFocused,
onTap: onTap,
focusNode: focusNode,
autofocus: autofocus,
);
}
Widget _buildLibrariesSection(List<PlexLibrary> visibleLibraries, dynamic t) {
final isLibrariesSelected =
widget.selectedIndex == 1 && widget.selectedLibraryKey == null;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Libraries header with expand/collapse
Focus(
focusNode: _librariesFocusNode,
onKeyEvent: (node, event) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
if (event.logicalKey.isSelectKey) {
setState(() {
_librariesExpanded = !_librariesExpanded;
});
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
setState(() {
_librariesExpanded = !_librariesExpanded;
});
},
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
decoration: BoxDecoration(
color: isLibrariesSelected
? t.text.withValues(alpha: 0.1)
: _isLibrariesFocused
? t.text.withValues(alpha: 0.08)
: null,
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
Icon(
widget.selectedIndex == 1
? Icons.video_library
: Icons.video_library_outlined,
size: 22,
color: widget.selectedIndex == 1 ? t.text : t.textMuted,
),
const SizedBox(width: 12),
Expanded(
child: Text(
Translations.of(context).navigation.libraries,
style: TextStyle(
fontSize: 14,
fontWeight: widget.selectedIndex == 1
? FontWeight.w600
: FontWeight.w400,
color: widget.selectedIndex == 1
? t.text
: t.textMuted,
),
),
),
Icon(
_librariesExpanded
? Icons.expand_less
: Icons.expand_more,
size: 20,
color: t.textMuted,
),
],
),
),
),
),
),
// Library items
if (_librariesExpanded)
_isLoadingLibraries
? Padding(
padding: const EdgeInsets.all(16),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: t.textMuted,
),
),
),
)
: visibleLibraries.isEmpty
? Padding(
padding: const EdgeInsets.all(16),
child: Text(
Translations.of(context).libraries.noLibrariesFound,
style: TextStyle(fontSize: 12, color: t.textMuted),
),
)
: _buildLibraryItems(visibleLibraries, t),
],
);
}
/// Get set of library names that appear more than once (not globally unique)
Set<String> _getNonUniqueLibraryNames(List<PlexLibrary> libraries) {
final nameCounts = <String, int>{};
for (final lib in libraries) {
nameCounts[lib.title] = (nameCounts[lib.title] ?? 0) + 1;
}
return nameCounts.entries
.where((e) => e.value > 1)
.map((e) => e.key)
.toSet();
}
Widget _buildLibraryItems(List<PlexLibrary> visibleLibraries, dynamic t) {
// Find which library names are not unique
final nonUniqueNames = _getNonUniqueLibraryNames(visibleLibraries);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: visibleLibraries.map((library) {
final showServerName =
nonUniqueNames.contains(library.title) &&
library.serverName != null;
return _buildLibraryItem(library, t, showServerName: showServerName);
}).toList(),
);
}
Widget _buildLibraryItem(
PlexLibrary library,
dynamic t, {
bool showServerName = false,
}) {
final isSelected =
widget.selectedIndex == 1 &&
widget.selectedLibraryKey == library.globalKey;
final isFocused = _focusedLibraryKeys.contains(library.globalKey);
final focusNode = _getLibraryFocusNode(library.globalKey);
return NavigationRailItem(
icon: _getLibraryIcon(library.type),
selectedIcon: _getLibraryIconFilled(library.type),
label: SizedBox(
height: 32, // Fixed height for consistent item sizing
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
library.title,
style: TextStyle(
fontSize: 13,
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
color: isSelected ? t.text : t.textMuted,
),
overflow: TextOverflow.ellipsis,
),
if (showServerName)
Text(
library.serverName!,
style: TextStyle(
fontSize: 9,
color: t.textMuted.withValues(alpha: 0.4),
),
overflow: TextOverflow.ellipsis,
),
],
),
),
isSelected: isSelected,
isFocused: isFocused,
onTap: () => widget.onLibrarySelected(library.globalKey),
focusNode: focusNode,
padding: const EdgeInsets.only(left: 28, right: 12, top: 10, bottom: 10),
borderRadius: BorderRadius.circular(8),
iconSize: 18,
);
}
}
@@ -1,19 +1,23 @@
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../mpv/mpv.dart';
import '../../models/plex_media_info.dart';
import '../../models/plex_media_version.dart';
import '../../models/plex_metadata.dart';
import '../../services/fullscreen_state_manager.dart';
import '../../utils/desktop_window_padding.dart';
import '../../utils/duration_formatter.dart';
import '../../i18n/strings.g.dart';
import '../app_bar_back_button.dart';
import 'widgets/timeline_slider.dart';
import '../../focus/focusable_wrapper.dart';
import 'widgets/video_controls_header.dart';
import 'widgets/video_timeline_bar.dart';
import 'widgets/volume_control.dart';
import 'widgets/track_chapter_controls.dart';
/// Desktop-specific video controls layout with top bar and bottom controls
class DesktopVideoControls extends StatelessWidget {
class DesktopVideoControls extends StatefulWidget {
final Player player;
final PlexMetadata metadata;
final VoidCallback? onNext;
@@ -25,11 +29,35 @@ class DesktopVideoControls extends StatelessWidget {
final VoidCallback onSeekToNextChapter;
final ValueChanged<Duration> onSeek;
final ValueChanged<Duration> onSeekEnd;
final Widget volumeControl;
final Widget trackChapterControls;
final IconData Function(int) getReplayIcon;
final IconData Function(int) getForwardIcon;
/// Called when focus activity occurs (to reset hide timer)
final VoidCallback? onFocusActivity;
/// Called to request focus on play/pause button (e.g., when controls shown via keyboard)
final VoidCallback? onRequestPlayPauseFocus;
/// Called when user navigates up from timeline (to hide controls)
final VoidCallback? onHideControls;
// Track chapter controls parameters
final List<PlexMediaVersion> availableVersions;
final int selectedMediaIndex;
final int boxFitMode;
final int audioSyncOffset;
final int subtitleSyncOffset;
final bool isFullscreen;
final VoidCallback? onCycleBoxFitMode;
final VoidCallback? onToggleFullscreen;
final Function(int)? onSwitchVersion;
final Function(AudioTrack)? onAudioTrackChanged;
final Function(SubtitleTrack)? onSubtitleTrackChanged;
final VoidCallback? onLoadSeekTimes;
final VoidCallback? onCancelAutoHide;
final VoidCallback? onStartAutoHide;
final String serverId;
const DesktopVideoControls({
super.key,
required this.player,
@@ -43,12 +71,254 @@ class DesktopVideoControls extends StatelessWidget {
required this.onSeekToNextChapter,
required this.onSeek,
required this.onSeekEnd,
required this.volumeControl,
required this.trackChapterControls,
required this.getReplayIcon,
required this.getForwardIcon,
this.onFocusActivity,
this.onRequestPlayPauseFocus,
this.onHideControls,
this.availableVersions = const [],
this.selectedMediaIndex = 0,
this.boxFitMode = 0,
this.audioSyncOffset = 0,
this.subtitleSyncOffset = 0,
this.isFullscreen = false,
this.onCycleBoxFitMode,
this.onToggleFullscreen,
this.onSwitchVersion,
this.onAudioTrackChanged,
this.onSubtitleTrackChanged,
this.onLoadSeekTimes,
this.onCancelAutoHide,
this.onStartAutoHide,
this.serverId = '',
});
@override
State<DesktopVideoControls> createState() => DesktopVideoControlsState();
}
class DesktopVideoControlsState extends State<DesktopVideoControls> {
// Focus nodes for playback control buttons
late final FocusNode _prevItemFocusNode;
late final FocusNode _prevChapterFocusNode;
late final FocusNode _playPauseFocusNode;
late final FocusNode _nextChapterFocusNode;
late final FocusNode _nextItemFocusNode;
late final FocusNode _timelineFocusNode;
// Focus node for volume control
late final FocusNode _volumeFocusNode;
// Focus nodes for track/chapter controls (max 8 buttons possible)
late final List<FocusNode> _trackControlFocusNodes;
// List of button focus nodes for horizontal navigation
late final List<FocusNode> _buttonFocusNodes;
@override
void initState() {
super.initState();
_prevItemFocusNode = FocusNode(debugLabel: 'PrevItem');
_prevChapterFocusNode = FocusNode(debugLabel: 'PrevChapter');
_playPauseFocusNode = FocusNode(debugLabel: 'PlayPause');
_nextChapterFocusNode = FocusNode(debugLabel: 'NextChapter');
_nextItemFocusNode = FocusNode(debugLabel: 'NextItem');
_timelineFocusNode = FocusNode(debugLabel: 'Timeline');
_volumeFocusNode = FocusNode(debugLabel: 'Volume');
// Create focus nodes for track controls (up to 8 buttons)
_trackControlFocusNodes = List.generate(
8,
(i) => FocusNode(debugLabel: 'TrackControl$i'),
);
_buttonFocusNodes = [
_prevItemFocusNode,
_prevChapterFocusNode,
_playPauseFocusNode,
_nextChapterFocusNode,
_nextItemFocusNode,
];
}
@override
void dispose() {
_prevItemFocusNode.dispose();
_prevChapterFocusNode.dispose();
_playPauseFocusNode.dispose();
_nextChapterFocusNode.dispose();
_nextItemFocusNode.dispose();
_timelineFocusNode.dispose();
_volumeFocusNode.dispose();
for (final node in _trackControlFocusNodes) {
node.dispose();
}
super.dispose();
}
/// Request focus on the play/pause button (called when controls shown via keyboard)
void requestPlayPauseFocus() {
_playPauseFocusNode.requestFocus();
}
/// Get focus node for volume control
FocusNode get volumeFocusNode => _volumeFocusNode;
/// Get focus nodes for track controls
List<FocusNode> get trackControlFocusNodes => _trackControlFocusNodes;
/// Handle left navigation from first track control - go to volume
void navigateFromTrackToVolume() {
_volumeFocusNode.requestFocus();
widget.onFocusActivity?.call();
}
void _onFocusChange(bool hasFocus) {
if (hasFocus) {
widget.onFocusActivity?.call();
}
}
/// Handle key events for horizontal button navigation
KeyEventResult _handleButtonKeyEvent(
FocusNode node,
KeyEvent event,
int index,
) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// LEFT arrow - move to previous button
if (key == LogicalKeyboardKey.arrowLeft) {
if (index > 0) {
_buttonFocusNodes[index - 1].requestFocus();
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
return KeyEventResult.handled; // At start, consume to prevent bubbling
}
// RIGHT arrow - move to next button or to volume
if (key == LogicalKeyboardKey.arrowRight) {
if (index < _buttonFocusNodes.length - 1) {
_buttonFocusNodes[index + 1].requestFocus();
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
// At end of playback buttons - move to volume
_volumeFocusNode.requestFocus();
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
// UP arrow - move focus to timeline
if (key == LogicalKeyboardKey.arrowUp) {
_timelineFocusNode.requestFocus();
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Handle key events for volume control navigation
KeyEventResult _handleVolumeKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// LEFT arrow - move back to last playback button
if (key == LogicalKeyboardKey.arrowLeft) {
_nextItemFocusNode.requestFocus();
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
// RIGHT arrow - move to first track control button
if (key == LogicalKeyboardKey.arrowRight) {
if (_trackControlFocusNodes.isNotEmpty) {
_trackControlFocusNodes[0].requestFocus();
widget.onFocusActivity?.call();
}
return KeyEventResult.handled;
}
// UP arrow - move focus to timeline
if (key == LogicalKeyboardKey.arrowUp) {
_timelineFocusNode.requestFocus();
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Handle key events for timeline navigation
KeyEventResult _handleTimelineKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
final duration = widget.player.state.duration;
final position = widget.player.state.position;
// UP arrow - hide controls
if (key == LogicalKeyboardKey.arrowUp) {
widget.onHideControls?.call();
return KeyEventResult.handled;
}
// DOWN arrow - move focus to play/pause button
if (key == LogicalKeyboardKey.arrowDown) {
_playPauseFocusNode.requestFocus();
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
// LEFT/RIGHT for smooth scrubbing
if (key == LogicalKeyboardKey.arrowLeft ||
key == LogicalKeyboardKey.arrowRight) {
if (duration.inMilliseconds <= 0) return KeyEventResult.handled;
// Base step: 0.5% of duration, minimum 500ms
final baseStep = Duration(
milliseconds: (duration.inMilliseconds * 0.005)
.clamp(500, 15000)
.toInt(),
);
// Accelerate on key repeat
final step = event is KeyRepeatEvent
? Duration(
milliseconds: (baseStep.inMilliseconds * 2).clamp(500, 30000),
)
: baseStep;
final isForward = key == LogicalKeyboardKey.arrowRight;
final newPosition = isForward ? position + step : position - step;
// Clamp to valid range
final clampedPosition = Duration(
milliseconds: newPosition.inMilliseconds.clamp(
0,
duration.inMilliseconds,
),
);
widget.onSeek(clampedPosition);
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
return Column(
@@ -84,228 +354,180 @@ class DesktopVideoControls extends StatelessWidget {
Widget _buildTopBarContent(BuildContext context, double leftPadding) {
final topBar = Padding(
padding: EdgeInsets.only(left: leftPadding, right: 16),
child: Row(
children: [
AppBarBackButton(
style: BackButtonStyle.video,
semanticLabel: t.videoControls.backButton,
onPressed: () => Navigator.of(context).pop(true),
),
const SizedBox(width: 16),
Expanded(
child: Platform.isMacOS
? _buildMacOSSingleLineTitle()
: _buildMultiLineTitle(),
),
],
child: VideoControlsHeader(
metadata: widget.metadata,
style: Platform.isMacOS
? VideoHeaderStyle.singleLine
: VideoHeaderStyle.multiLine,
),
);
return DesktopAppBarHelper.wrapWithGestureDetector(topBar, opaque: true);
}
Widget _buildMacOSSingleLineTitle() {
// Build single-line title combining series and episode info
final seriesName = metadata.grandparentTitle ?? metadata.title;
final hasEpisodeInfo =
metadata.parentIndex != null && metadata.index != null;
final titleText = hasEpisodeInfo
? '$seriesName · S${metadata.parentIndex} E${metadata.index} · ${metadata.title}'
: seriesName;
return Text(
titleText,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
Widget _buildMultiLineTitle() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
metadata.grandparentTitle ?? metadata.title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (metadata.parentIndex != null && metadata.index != null)
Text(
'S${metadata.parentIndex} · E${metadata.index} · ${metadata.title}',
style: const TextStyle(color: Colors.white70, fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
);
}
Widget _buildBottomControls(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Column(
children: [
// Row 1: Timeline with time indicators
StreamBuilder<Duration>(
stream: player.streams.position,
initialData: player.state.position,
builder: (context, positionSnapshot) {
return StreamBuilder<Duration>(
stream: player.streams.duration,
initialData: player.state.duration,
builder: (context, durationSnapshot) {
final position = positionSnapshot.data ?? Duration.zero;
final duration = durationSnapshot.data ?? Duration.zero;
return Row(
children: [
Text(
formatDurationTimestamp(position),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
const SizedBox(width: 12),
Expanded(
child: TimelineSlider(
position: position,
duration: duration,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
onSeek: onSeek,
onSeekEnd: onSeekEnd,
),
),
const SizedBox(width: 12),
Text(
formatDurationTimestamp(duration),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
],
);
},
);
},
VideoTimelineBar(
player: widget.player,
chapters: widget.chapters,
chaptersLoaded: widget.chaptersLoaded,
onSeek: widget.onSeek,
onSeekEnd: widget.onSeekEnd,
horizontalLayout: true,
focusNode: _timelineFocusNode,
onKeyEvent: _handleTimelineKeyEvent,
onFocusChange: _onFocusChange,
),
const SizedBox(height: 4),
// Row 2: Playback controls and options
Row(
children: [
// Previous item
Semantics(
label: t.videoControls.previousButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
Icons.skip_previous,
color: onPrevious != null ? Colors.white : Colors.white54,
),
onPressed: onPrevious,
),
_buildFocusableButton(
focusNode: _prevItemFocusNode,
index: 0,
icon: Icons.skip_previous,
color: widget.onPrevious != null
? Colors.white
: Colors.white54,
onPressed: widget.onPrevious,
semanticLabel: t.videoControls.previousButton,
),
// Previous chapter (or skip backward if no chapters)
Semantics(
label: chapters.isEmpty
? t.videoControls.seekBackwardButton(seconds: seekTimeSmall)
_buildFocusableButton(
focusNode: _prevChapterFocusNode,
index: 1,
icon: widget.chapters.isEmpty
? widget.getReplayIcon(widget.seekTimeSmall)
: Icons.fast_rewind,
onPressed: widget.onSeekToPreviousChapter,
semanticLabel: widget.chapters.isEmpty
? t.videoControls.seekBackwardButton(
seconds: widget.seekTimeSmall,
)
: t.videoControls.previousChapterButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
chapters.isEmpty
? getReplayIcon(seekTimeSmall)
: Icons.fast_rewind,
color: Colors.white,
),
onPressed: onSeekToPreviousChapter,
),
),
// Play/Pause
StreamBuilder<bool>(
stream: player.streams.playing,
initialData: player.state.playing,
stream: widget.player.streams.playing,
initialData: widget.player.state.playing,
builder: (context, snapshot) {
final isPlaying = snapshot.data ?? false;
return Semantics(
label: isPlaying
return _buildFocusableButton(
focusNode: _playPauseFocusNode,
index: 2,
icon: isPlaying ? Icons.pause : Icons.play_arrow,
iconSize: 32,
onPressed: () {
if (isPlaying) {
widget.player.pause();
} else {
widget.player.play();
}
},
semanticLabel: isPlaying
? t.videoControls.pauseButton
: t.videoControls.playButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
color: Colors.white,
size: 32,
),
iconSize: 32,
onPressed: () {
if (isPlaying) {
player.pause();
} else {
player.play();
}
},
),
);
},
),
// Next chapter (or skip forward if no chapters)
Semantics(
label: chapters.isEmpty
? t.videoControls.seekForwardButton(seconds: seekTimeSmall)
_buildFocusableButton(
focusNode: _nextChapterFocusNode,
index: 3,
icon: widget.chapters.isEmpty
? widget.getForwardIcon(widget.seekTimeSmall)
: Icons.fast_forward,
onPressed: widget.onSeekToNextChapter,
semanticLabel: widget.chapters.isEmpty
? t.videoControls.seekForwardButton(
seconds: widget.seekTimeSmall,
)
: t.videoControls.nextChapterButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
chapters.isEmpty
? getForwardIcon(seekTimeSmall)
: Icons.fast_forward,
color: Colors.white,
),
onPressed: onSeekToNextChapter,
),
),
// Next item
Semantics(
label: t.videoControls.nextButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
Icons.skip_next,
color: onNext != null ? Colors.white : Colors.white54,
),
onPressed: onNext,
),
_buildFocusableButton(
focusNode: _nextItemFocusNode,
index: 4,
icon: Icons.skip_next,
color: widget.onNext != null ? Colors.white : Colors.white54,
onPressed: widget.onNext,
semanticLabel: t.videoControls.nextButton,
),
const Spacer(),
// Volume control
volumeControl,
VolumeControl(
player: widget.player,
focusNode: _volumeFocusNode,
onKeyEvent: _handleVolumeKeyEvent,
onFocusChange: _onFocusChange,
onFocusActivity: widget.onFocusActivity,
),
const SizedBox(width: 16),
// Audio track, subtitle, and chapter controls
trackChapterControls,
TrackChapterControls(
player: widget.player,
chapters: widget.chapters,
chaptersLoaded: widget.chaptersLoaded,
availableVersions: widget.availableVersions,
selectedMediaIndex: widget.selectedMediaIndex,
boxFitMode: widget.boxFitMode,
audioSyncOffset: widget.audioSyncOffset,
subtitleSyncOffset: widget.subtitleSyncOffset,
isRotationLocked: false, // Desktop doesn't have rotation lock
isFullscreen: widget.isFullscreen,
serverId: widget.serverId,
onCycleBoxFitMode: widget.onCycleBoxFitMode,
onToggleFullscreen: widget.onToggleFullscreen,
onSwitchVersion: widget.onSwitchVersion,
onAudioTrackChanged: widget.onAudioTrackChanged,
onSubtitleTrackChanged: widget.onSubtitleTrackChanged,
onLoadSeekTimes: widget.onLoadSeekTimes,
onCancelAutoHide: widget.onCancelAutoHide,
onStartAutoHide: widget.onStartAutoHide,
focusNodes: _trackControlFocusNodes,
onFocusChange: _onFocusChange,
onNavigateLeft: navigateFromTrackToVolume,
),
],
),
],
),
);
}
Widget _buildFocusableButton({
required FocusNode focusNode,
required int index,
required IconData icon,
required VoidCallback? onPressed,
required String semanticLabel,
Color color = Colors.white,
double iconSize = 24,
}) {
return FocusableWrapper(
focusNode: focusNode,
onSelect: onPressed,
onKeyEvent: (node, event) => _handleButtonKeyEvent(node, event, index),
onFocusChange: _onFocusChange,
borderRadius: 20,
autoScroll: false,
useBackgroundFocus: true,
semanticLabel: semanticLabel,
child: Semantics(
label: semanticLabel,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(icon, color: color, size: iconSize),
iconSize: iconSize,
onPressed: onPressed,
),
),
);
}
}
@@ -0,0 +1,39 @@
import '../../../mpv/mpv.dart';
/// Helper class for filtering tracks to remove auto/no tracks
///
/// This keeps track-filter rules in one place and eliminates duplication.
class TrackFilterHelper {
/// Generic method to filter tracks based on type
static List<T> filterTracks<T>(List<T> tracks) {
return tracks.where(_isAllowedTrack).toList();
}
/// Extract and filter tracks from Tracks object
static List<T> extractAndFilterTracks<T>(
Tracks? tracks,
List<T> Function(Tracks?) extractor,
) {
return filterTracks<T>(extractor(tracks));
}
/// Check if a track list has multiple tracks (excluding auto/no)
static bool hasMultipleTracks<T>(List<T> tracks) {
return filterTracks<T>(tracks).length > 1;
}
/// Check if a track list has any tracks (excluding auto/no)
static bool hasTracks<T>(List<T> tracks) {
return filterTracks<T>(tracks).isNotEmpty;
}
static bool _isAllowedTrack<T>(T track) {
final id = switch (track) {
AudioTrack t => t.id,
SubtitleTrack t => t.id,
_ => '',
};
return id != 'auto' && id != 'no';
}
}
@@ -0,0 +1,92 @@
import 'package:flutter/material.dart';
import '../../../mpv/mpv.dart';
import '../../../widgets/focusable_list_tile.dart';
/// Helper class for shared track selection logic
///
/// Provides common utilities for empty states, "Off" handling, and selection logic
class TrackSelectionHelper {
/// Get the appropriate empty message based on track type
static String getEmptyMessage<T>() {
if (T == SubtitleTrack) {
return 'No subtitles available';
} else if (T == AudioTrack) {
return 'No audio tracks available';
}
return 'No tracks available';
}
/// Build a centered empty state widget
static Widget buildEmptyState<T>() {
return Center(
child: Text(
getEmptyMessage<T>(),
style: const TextStyle(color: Colors.white70),
),
);
}
/// Check if "Off" is selected for a track
static bool isOffSelected<T>(
T? selectedTrack,
bool Function(T track)? isOffTrack,
) {
return selectedTrack == null || (isOffTrack?.call(selectedTrack) ?? false);
}
/// Get the track ID from a track object
static String getTrackId<T>(T track) {
if (track is AudioTrack) {
return track.id;
} else if (track is SubtitleTrack) {
return track.id;
}
return '';
}
/// Build the "Off" list tile for track selection
static Widget buildOffTile<T>({
required bool isSelected,
required VoidCallback onTap,
FocusNode? focusNode,
}) {
return _buildSelectableTile(
label: 'Off',
isSelected: isSelected,
onTap: onTap,
focusNode: focusNode,
);
}
/// Build a track selection list tile
static Widget buildTrackTile<T>({
required String label,
required bool isSelected,
required VoidCallback onTap,
FocusNode? focusNode,
}) {
return _buildSelectableTile(
label: label,
isSelected: isSelected,
onTap: onTap,
focusNode: focusNode,
);
}
static Widget _buildSelectableTile({
required String label,
required bool isSelected,
required VoidCallback onTap,
FocusNode? focusNode,
}) {
return FocusableListTile(
focusNode: focusNode,
title: Text(
label,
style: TextStyle(color: isSelected ? Colors.blue : Colors.white),
),
trailing: isSelected ? const Icon(Icons.check, color: Colors.blue) : null,
onTap: onTap,
);
}
}
@@ -4,12 +4,11 @@ import '../../mpv/mpv.dart';
import '../../models/plex_media_info.dart';
import '../../models/plex_metadata.dart';
import '../../utils/desktop_window_padding.dart';
import '../../utils/duration_formatter.dart';
import '../../utils/player_utils.dart';
import '../../utils/video_control_icons.dart';
import '../../i18n/strings.g.dart';
import '../app_bar_back_button.dart';
import 'widgets/timeline_slider.dart';
import 'widgets/video_controls_header.dart';
import 'widgets/video_timeline_bar.dart';
/// Mobile video controls layout for Plex video player
///
@@ -67,44 +66,10 @@ class MobileVideoControls extends StatelessWidget {
bottom: false, // Only respect top safe area when in portrait
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
AppBarBackButton(
style: BackButtonStyle.video,
semanticLabel: t.videoControls.backButton,
onPressed: () => Navigator.of(context).pop(true),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
metadata.grandparentTitle ?? metadata.title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (metadata.parentIndex != null && metadata.index != null)
Text(
'S${metadata.parentIndex} · E${metadata.index} · ${metadata.title}',
style: const TextStyle(
color: Colors.white70,
fontSize: 14,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
// Track and chapter controls in top right
trackChapterControls,
],
child: VideoControlsHeader(
metadata: metadata,
style: VideoHeaderStyle.multiLine,
trailing: trackChapterControls,
),
),
);
@@ -171,54 +136,13 @@ class MobileVideoControls extends StatelessWidget {
top: false, // Only respect bottom safe area when in portrait
child: Padding(
padding: const EdgeInsets.all(16),
child: StreamBuilder<Duration>(
stream: player.streams.position,
initialData: player.state.position,
builder: (context, positionSnapshot) {
return StreamBuilder<Duration>(
stream: player.streams.duration,
initialData: player.state.duration,
builder: (context, durationSnapshot) {
final position = positionSnapshot.data ?? Duration.zero;
final duration = durationSnapshot.data ?? Duration.zero;
return Column(
children: [
TimelineSlider(
position: position,
duration: duration,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
onSeek: onSeek,
onSeekEnd: onSeekEnd,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
formatDurationTimestamp(position),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
Text(
formatDurationTimestamp(duration),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
],
),
),
],
);
},
);
},
child: VideoTimelineBar(
player: player,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
onSeek: onSeek,
onSeekEnd: onSeekEnd,
horizontalLayout: false,
),
),
);
@@ -5,11 +5,14 @@ import '../../../services/plex_client.dart';
import '../../../models/plex_media_info.dart';
import '../../../utils/duration_formatter.dart';
import '../../../utils/provider_extensions.dart';
import '../../../widgets/focusable_bottom_sheet.dart';
import '../../../widgets/focusable_list_tile.dart';
import 'base_video_control_sheet.dart';
import 'video_control_sheet_launcher.dart';
import '../../plex_optimized_image.dart';
/// Bottom sheet for selecting chapters
class ChapterSheet extends StatelessWidget {
class ChapterSheet extends StatefulWidget {
final Player player;
final List<PlexChapter> chapters;
final bool chaptersLoaded;
@@ -32,7 +35,7 @@ class ChapterSheet extends StatelessWidget {
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
BaseVideoControlSheet.showSheet(
VideoControlSheetLauncher.show(
context: context,
onOpen: onOpen,
onClose: onClose,
@@ -45,124 +48,148 @@ class ChapterSheet extends StatelessWidget {
);
}
@override
State<ChapterSheet> createState() => _ChapterSheetState();
}
class _ChapterSheetState extends State<ChapterSheet> {
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_initialFocusNode = FocusNode(debugLabel: 'ChapterSheetInitialFocus');
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
/// Get the correct PlexClient for the metadata's server
PlexClient _getClientForChapters(BuildContext context) {
return context.getClientForServer(serverId!);
return context.getClientForServer(widget.serverId!);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Duration>(
stream: player.streams.position,
initialData: player.state.position,
builder: (context, positionSnapshot) {
final currentPosition = positionSnapshot.data ?? Duration.zero;
final currentPositionMs = currentPosition.inMilliseconds;
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: StreamBuilder<Duration>(
stream: widget.player.streams.position,
initialData: widget.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());
// Find the current chapter based on position
int? currentChapterIndex;
for (int i = 0; i < widget.chapters.length; i++) {
final chapter = widget.chapters[i];
final startMs = chapter.startTimeOffset ?? 0;
final endMs =
chapter.endTimeOffset ??
(i < widget.chapters.length - 1
? widget.chapters[i + 1].startTimeOffset ?? 0
: double.maxFinite.toInt());
if (currentPositionMs >= startMs && currentPositionMs < endMs) {
currentChapterIndex = i;
break;
if (currentPositionMs >= startMs && currentPositionMs < endMs) {
currentChapterIndex = i;
break;
}
}
}
Widget content;
if (!chaptersLoaded) {
content = const Center(child: CircularProgressIndicator());
} else if (chapters.isEmpty) {
content = const Center(
child: Text(
'No chapters available',
style: TextStyle(color: Colors.white70),
),
);
} else {
content = ListView.builder(
itemCount: chapters.length,
itemBuilder: (context, index) {
final chapter = chapters[index];
final isCurrentChapter = currentChapterIndex == index;
Widget content;
if (!widget.chaptersLoaded) {
content = const Center(child: CircularProgressIndicator());
} else if (widget.chapters.isEmpty) {
content = const Center(
child: Text(
'No chapters available',
style: TextStyle(color: Colors.white70),
),
);
} else {
content = ListView.builder(
itemCount: widget.chapters.length,
itemBuilder: (context, index) {
final chapter = widget.chapters[index];
final isCurrentChapter = currentChapterIndex == index;
return ListTile(
leading: chapter.thumb != null
? Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: PlexThumbImage(
client: _getClientForChapters(context),
imagePath: chapter.thumb,
width: 60,
height: 34,
fit: BoxFit.cover,
errorWidget: (context, url, error) => const Icon(
Icons.image,
color: Colors.white54,
size: 34,
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
leading: chapter.thumb != null
? Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: PlexOptimizedImage.thumb(
client: _getClientForChapters(context),
imagePath: chapter.thumb,
width: 60,
height: 34,
fit: BoxFit.cover,
errorWidget: (context, url, error) =>
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,
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,
],
)
: null,
title: Text(
chapter.label,
style: TextStyle(
color: isCurrentChapter ? Colors.blue : Colors.white,
fontWeight: isCurrentChapter
? FontWeight.bold
: FontWeight.normal,
),
),
),
subtitle: Text(
formatDurationTimestamp(chapter.startTime),
style: TextStyle(
color: isCurrentChapter
? Colors.blue.withValues(alpha: 0.7)
: Colors.white70,
fontSize: 12,
subtitle: Text(
formatDurationTimestamp(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);
},
);
},
);
}
trailing: isCurrentChapter
? const Icon(Icons.play_circle_filled, color: Colors.blue)
: null,
onTap: () {
widget.player.seek(chapter.startTime);
Navigator.pop(context);
},
);
},
);
}
return BaseVideoControlSheet(
title: 'Chapters',
icon: Icons.video_library,
child: content,
);
},
return BaseVideoControlSheet(
title: 'Chapters',
icon: Icons.video_library,
child: content,
);
},
),
);
}
}
@@ -1,12 +1,16 @@
import 'package:flutter/material.dart';
import '../../../mpv/mpv.dart';
import '../../../widgets/focusable_bottom_sheet.dart';
import 'base_video_control_sheet.dart';
import 'video_control_sheet_launcher.dart';
import '../helpers/track_filter_helper.dart';
import '../helpers/track_selection_helper.dart';
/// Generic track selection sheet for audio and subtitle tracks
///
/// Type parameter [T] should be either [AudioTrack] or [SubtitleTrack]
class TrackSelectionSheet<T> extends StatelessWidget {
class TrackSelectionSheet<T> extends StatefulWidget {
final Player player;
final String title;
final IconData icon;
@@ -50,7 +54,7 @@ class TrackSelectionSheet<T> extends StatelessWidget {
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
BaseVideoControlSheet.showSheet(
VideoControlSheetLauncher.show(
context: context,
onOpen: onOpen,
onClose: onClose,
@@ -70,136 +74,121 @@ class TrackSelectionSheet<T> extends StatelessWidget {
);
}
String _getEmptyMessage() {
if (T == SubtitleTrack) {
return 'No subtitles available';
} else if (T == AudioTrack) {
return 'No audio tracks available';
}
return 'No tracks available';
@override
State<TrackSelectionSheet<T>> createState() => _TrackSelectionSheetState<T>();
}
class _TrackSelectionSheetState<T> extends State<TrackSelectionSheet<T>> {
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_initialFocusNode = FocusNode(debugLabel: 'TrackSelectionInitialFocus');
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Tracks>(
stream: player.streams.tracks,
initialData: player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final availableTracks = extractTracks(tracks).where((track) {
// Filter out 'auto' and 'no' tracks from the list
if (track is AudioTrack) {
return track.id != 'auto' && track.id != 'no';
} else if (track is SubtitleTrack) {
return track.id != 'auto' && track.id != 'no';
}
return true;
}).toList();
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: StreamBuilder<Tracks>(
stream: widget.player.streams.tracks,
initialData: widget.player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final availableTracks = TrackFilterHelper.extractAndFilterTracks<T>(
tracks,
widget.extractTracks,
);
return BaseVideoControlSheet(
title: title,
icon: icon,
child: availableTracks.isEmpty
? Center(
child: Text(
_getEmptyMessage(),
style: const TextStyle(color: Colors.white70),
),
)
: StreamBuilder<TrackSelection>(
stream: player.streams.track,
initialData: player.state.track,
builder: (context, selectedSnapshot) {
final currentTrack =
selectedSnapshot.data ?? player.state.track;
final selectedTrack = getCurrentTrack(currentTrack);
return BaseVideoControlSheet(
title: widget.title,
icon: widget.icon,
child: availableTracks.isEmpty
? TrackSelectionHelper.buildEmptyState<T>()
: StreamBuilder<TrackSelection>(
stream: widget.player.streams.track,
initialData: widget.player.state.track,
builder: (context, selectedSnapshot) {
final currentTrack =
selectedSnapshot.data ?? widget.player.state.track;
final selectedTrack = widget.getCurrentTrack(
currentTrack,
);
// Determine if "Off" is selected (null or explicit off)
final isOffSelected =
selectedTrack == null ||
(isOffTrack?.call(selectedTrack) ?? false);
// Determine if "Off" is selected (null or explicit off)
final isOffSelected = TrackSelectionHelper.isOffSelected(
selectedTrack,
widget.isOffTrack,
);
final itemCount =
availableTracks.length + (showOffOption ? 1 : 0);
final itemCount =
availableTracks.length +
(widget.showOffOption ? 1 : 0);
return ListView.builder(
itemCount: itemCount,
itemBuilder: (context, index) {
// First item is "Off" if enabled
if (showOffOption && 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,
return ListView.builder(
itemCount: itemCount,
itemBuilder: (context, index) {
// First item is "Off" if enabled
if (widget.showOffOption && index == 0) {
return TrackSelectionHelper.buildOffTile<T>(
isSelected: isOffSelected,
focusNode: _initialFocusNode,
onTap: () {
if (widget.createOffTrack != null) {
final offTrack = widget.createOffTrack!();
widget.setTrack(offTrack);
widget.onTrackChanged?.call(offTrack);
}
Navigator.pop(context);
},
);
}
// Subsequent items are tracks
final trackIndex = widget.showOffOption
? index - 1
: index;
final track = availableTracks[trackIndex];
// Check if this track is selected
final trackId = TrackSelectionHelper.getTrackId(
track,
);
final selectedId = selectedTrack == null
? ''
: TrackSelectionHelper.getTrackId(selectedTrack);
final isSelected = trackId == selectedId;
final label = widget.buildLabel(track, trackIndex);
// Focus the first actual track if no "Off" option
final shouldFocus =
!widget.showOffOption && index == 0;
return TrackSelectionHelper.buildTrackTile<T>(
label: label,
isSelected: isSelected,
focusNode: shouldFocus ? _initialFocusNode : null,
onTap: () {
if (createOffTrack != null) {
final offTrack = createOffTrack!();
setTrack(offTrack);
onTrackChanged?.call(offTrack);
}
widget.setTrack(track);
widget.onTrackChanged?.call(track);
Navigator.pop(context);
},
);
}
// Subsequent items are tracks
final trackIndex = showOffOption ? index - 1 : index;
final track = availableTracks[trackIndex];
// Check if this track is selected
String trackId;
if (track is AudioTrack) {
trackId = track.id;
} else if (track is SubtitleTrack) {
trackId = track.id;
} else {
trackId = '';
}
String selectedId;
if (selectedTrack == null) {
selectedId = '';
} else if (selectedTrack is AudioTrack) {
selectedId = selectedTrack.id;
} else if (selectedTrack is SubtitleTrack) {
selectedId = selectedTrack.id;
} else {
selectedId = '';
}
final isSelected = trackId == selectedId;
final label = buildLabel(track, trackIndex);
return ListTile(
title: Text(
label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
setTrack(track);
onTrackChanged?.call(track);
Navigator.pop(context);
},
);
},
);
},
),
);
},
},
);
},
),
);
},
),
);
}
}
@@ -1,9 +1,12 @@
import 'package:flutter/material.dart';
import '../../../models/plex_media_version.dart';
import '../../../widgets/focusable_bottom_sheet.dart';
import '../../../widgets/focusable_list_tile.dart';
import 'base_video_control_sheet.dart';
import 'video_control_sheet_launcher.dart';
/// Bottom sheet for selecting video version
class VersionSheet extends StatelessWidget {
class VersionSheet extends StatefulWidget {
final List<PlexMediaVersion> availableVersions;
final int selectedMediaIndex;
final Function(int) onVersionSelected;
@@ -23,7 +26,7 @@ class VersionSheet extends StatelessWidget {
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
BaseVideoControlSheet.showSheet(
VideoControlSheetLauncher.show(
context: context,
onOpen: onOpen,
onClose: onClose,
@@ -36,30 +39,55 @@ class VersionSheet extends StatelessWidget {
}
@override
Widget build(BuildContext context) {
return BaseVideoControlSheet(
title: 'Video Version',
icon: Icons.video_file,
child: ListView.builder(
itemCount: availableVersions.length,
itemBuilder: (context, index) {
final version = availableVersions[index];
final isSelected = index == selectedMediaIndex;
State<VersionSheet> createState() => _VersionSheetState();
}
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);
},
);
},
class _VersionSheetState extends State<VersionSheet> {
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_initialFocusNode = FocusNode(debugLabel: 'VersionSheetInitialFocus');
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: BaseVideoControlSheet(
title: 'Video Version',
icon: Icons.video_file,
child: ListView.builder(
itemCount: widget.availableVersions.length,
itemBuilder: (context, index) {
final version = widget.availableVersions[index];
final isSelected = index == widget.selectedMediaIndex;
return FocusableListTile(
focusNode: index == 0 ? _initialFocusNode : null,
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);
widget.onVersionSelected(index);
},
);
},
),
),
);
}
@@ -0,0 +1,22 @@
import 'package:flutter/material.dart';
import 'base_video_control_sheet.dart';
/// Helper class to launch video control sheets with consistent behavior
///
/// This eliminates the need for each sheet to duplicate the showSheet wrapper.
class VideoControlSheetLauncher {
/// Show a video control sheet with consistent styling and callbacks
static Future<T?> show<T>({
required BuildContext context,
required WidgetBuilder builder,
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
return BaseVideoControlSheet.showSheet<T>(
context: context,
onOpen: onOpen,
onClose: onClose,
builder: builder,
);
}
}
@@ -5,12 +5,14 @@ import 'package:flutter/material.dart';
import '../../../mpv/mpv.dart';
import '../../../services/settings_service.dart';
import '../../../services/sleep_timer_service.dart';
import '../../../utils/duration_formatter.dart';
import '../../../utils/platform_detector.dart';
import '../../../widgets/focusable_bottom_sheet.dart';
import '../../../widgets/focusable_list_tile.dart';
import '../widgets/sync_offset_control.dart';
import '../widgets/sleep_timer_content.dart';
import '../../../i18n/strings.g.dart';
import 'base_video_control_sheet.dart';
import 'video_sheet_header.dart';
enum _SettingsView { menu, speed, sleep, audioSync, subtitleSync, audioDevice }
@@ -22,6 +24,7 @@ class _SettingsMenuItem extends StatelessWidget {
final VoidCallback onTap;
final bool isHighlighted;
final bool allowValueOverflow;
final FocusNode? focusNode;
const _SettingsMenuItem({
required this.icon,
@@ -30,6 +33,7 @@ class _SettingsMenuItem extends StatelessWidget {
required this.onTap,
this.isHighlighted = false,
this.allowValueOverflow = false,
this.focusNode,
});
@override
@@ -43,7 +47,8 @@ class _SettingsMenuItem extends StatelessWidget {
overflow: allowValueOverflow ? TextOverflow.ellipsis : null,
);
return ListTile(
return FocusableListTile(
focusNode: focusNode,
leading: Icon(icon, color: isHighlighted ? Colors.amber : Colors.white70),
title: Text(title, style: const TextStyle(color: Colors.white)),
trailing: Row(
@@ -80,20 +85,16 @@ class VideoSettingsSheet extends StatefulWidget {
VoidCallback? onOpen,
VoidCallback? onClose,
}) {
onOpen?.call();
return showModalBottomSheet(
return BaseVideoControlSheet.showSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: BaseVideoControlSheet.getBottomSheetConstraints(context),
onOpen: onOpen,
onClose: onClose,
builder: (context) => VideoSettingsSheet(
player: player,
audioSyncOffset: audioSyncOffset,
subtitleSyncOffset: subtitleSyncOffset,
),
).whenComplete(() {
onClose?.call();
});
);
}
@override
@@ -105,15 +106,23 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
late int _audioSyncOffset;
late int _subtitleSyncOffset;
bool _enableHDR = true;
late final FocusNode _initialFocusNode;
@override
void initState() {
super.initState();
_audioSyncOffset = widget.audioSyncOffset;
_subtitleSyncOffset = widget.subtitleSyncOffset;
_initialFocusNode = FocusNode(debugLabel: 'VideoSettingsInitialFocus');
_loadHDRSetting();
}
@override
void dispose() {
_initialFocusNode.dispose();
super.dispose();
}
Future<void> _loadHDRSetting() async {
final settings = await SettingsService.getInstance();
setState(() {
@@ -183,41 +192,11 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
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)';
}
}
Widget _buildHeader() {
final sleepTimer = SleepTimerService();
final isIconActive =
_currentView == _SettingsView.menu &&
(sleepTimer.isActive ||
_audioSyncOffset != 0 ||
_subtitleSyncOffset != 0);
return VideoSheetHeader(
title: _getTitle(),
icon: _getIcon(),
iconColor: isIconActive ? Colors.amber : Colors.white,
onBack: _currentView != _SettingsView.menu ? _navigateBack : null,
);
return 'Active (${formatDurationWithSeconds(remaining)})';
}
Widget _buildMenuView() {
@@ -233,6 +212,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
builder: (context, snapshot) {
final currentRate = snapshot.data ?? 1.0;
return _SettingsMenuItem(
focusNode: _initialFocusNode,
icon: Icons.speed,
title: 'Playback Speed',
valueText: _formatSpeed(currentRate),
@@ -260,7 +240,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
_SettingsMenuItem(
icon: Icons.sync,
title: 'Audio Sync',
valueText: _formatAudioSync(_audioSyncOffset),
valueText: formatSyncOffset(_audioSyncOffset.toDouble()),
isHighlighted: _audioSyncOffset != 0,
onTap: () => _navigateTo(_SettingsView.audioSync),
),
@@ -269,7 +249,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
_SettingsMenuItem(
icon: Icons.subtitles,
title: 'Subtitle Sync',
valueText: _formatAudioSync(_subtitleSyncOffset),
valueText: formatSyncOffset(_subtitleSyncOffset.toDouble()),
isHighlighted: _subtitleSyncOffset != 0,
onTap: () => _navigateTo(_SettingsView.subtitleSync),
),
@@ -443,33 +423,36 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
@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();
}
}(),
),
],
),
final sleepTimer = SleepTimerService();
final isIconActive =
_currentView == _SettingsView.menu &&
(sleepTimer.isActive ||
_audioSyncOffset != 0 ||
_subtitleSyncOffset != 0);
return FocusableBottomSheet(
initialFocusNode: _initialFocusNode,
child: BaseVideoControlSheet(
title: _getTitle(),
icon: _getIcon(),
iconColor: isIconActive ? Colors.amber : Colors.white,
onBack: _currentView != _SettingsView.menu ? _navigateBack : null,
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();
}
}(),
),
);
}
@@ -1,4 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../focus/focusable_wrapper.dart';
/// A standardized button for video player controls with improved tap targets.
///
@@ -26,6 +29,19 @@ class VideoControlButton extends StatelessWidget {
/// When true, the icon color defaults to amber instead of white.
final bool isActive;
/// Optional FocusNode for D-pad/keyboard navigation.
/// When provided, the button becomes focusable with visual focus indicator.
final FocusNode? focusNode;
/// Custom key event handler for focus navigation.
final KeyEventResult Function(FocusNode, KeyEvent)? onKeyEvent;
/// Called when focus changes.
final ValueChanged<bool>? onFocusChange;
/// Whether this button should autofocus when first built.
final bool autofocus;
const VideoControlButton({
super.key,
required this.icon,
@@ -34,6 +50,10 @@ class VideoControlButton extends StatelessWidget {
this.tooltip,
this.semanticLabel,
this.isActive = false,
this.focusNode,
this.onKeyEvent,
this.onFocusChange,
this.autofocus = false,
});
@override
@@ -48,7 +68,7 @@ class VideoControlButton extends StatelessWidget {
constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
);
return semanticLabel != null
Widget result = semanticLabel != null
? Semantics(
label: semanticLabel,
button: true,
@@ -56,5 +76,23 @@ class VideoControlButton extends StatelessWidget {
child: button,
)
: button;
// Wrap with FocusableWrapper when focusNode is provided
if (focusNode != null) {
result = FocusableWrapper(
focusNode: focusNode,
onSelect: onPressed,
onKeyEvent: onKeyEvent,
onFocusChange: onFocusChange,
autofocus: autofocus,
semanticLabel: semanticLabel,
borderRadius: 20, // Circular for icon buttons
autoScroll: false, // Video controls don't scroll
useBackgroundFocus: true, // Use background highlight for video controls
child: result,
);
}
return result;
}
}
+231 -66
View File
@@ -3,7 +3,13 @@ import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:rate_limiter/rate_limiter.dart';
import 'package:flutter/services.dart' show SystemChrome, DeviceOrientation;
import 'package:flutter/services.dart'
show
SystemChrome,
DeviceOrientation,
LogicalKeyboardKey,
KeyDownEvent,
KeyRepeatEvent;
import 'package:macos_window_utils/macos_window_utils.dart';
import 'package:window_manager/window_manager.dart';
@@ -21,7 +27,7 @@ import '../../utils/player_utils.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/video_control_icons.dart';
import '../../i18n/strings.g.dart';
import 'widgets/volume_control.dart';
import '../../focus/input_mode_tracker.dart';
import 'widgets/track_chapter_controls.dart';
import 'mobile_video_controls.dart';
import 'desktop_video_controls.dart';
@@ -98,6 +104,10 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
int _subtitleSyncOffset = 0; // Default, loaded from settings
bool _isRotationLocked = true; // Default locked (landscape only)
// GlobalKey to access DesktopVideoControls state for focus management
final GlobalKey<DesktopVideoControlsState> _desktopControlsKey =
GlobalKey<DesktopVideoControlsState>();
/// Get the correct PlexClient for this metadata's server
PlexClient _getClientForMetadata() {
return context.getClientForServer(widget.metadata.serverId!);
@@ -152,6 +162,19 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
windowManager.addListener(this);
}
// Focus play/pause button on first frame if in keyboard mode
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusPlayPauseIfKeyboardMode();
});
}
/// Focus play/pause button if we're in keyboard navigation mode (desktop only)
void _focusPlayPauseIfKeyboardMode() {
if (!mounted) return;
final isMobile = PlatformDetector.isMobile(context);
if (!isMobile && InputModeTracker.isKeyboardMode(context)) {
_desktopControlsKey.currentState?.requestPlayPauseFocus();
}
}
Future<void> _initKeyboardService() async {
@@ -734,14 +757,129 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
}
}
/// Check if a key is a directional key (arrow keys)
bool _isDirectionalKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.arrowUp ||
key == LogicalKeyboardKey.arrowDown ||
key == LogicalKeyboardKey.arrowLeft ||
key == LogicalKeyboardKey.arrowRight;
}
/// Check if a key is a back/escape key
bool _isBackKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.escape ||
key == LogicalKeyboardKey.goBack ||
key == LogicalKeyboardKey.browserBack ||
key == LogicalKeyboardKey.gameButtonB;
}
/// Check if a key is a select/enter key
bool _isSelectKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.select ||
key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.numpadEnter ||
key == LogicalKeyboardKey.gameButtonA;
}
/// Show controls and focus play/pause on keyboard input (desktop only)
void _showControlsWithFocus() {
if (!_showControls) {
setState(() {
_showControls = true;
_controlsFullyHidden = false;
});
if (Platform.isLinux) {
widget.player.setControlsVisible(true);
}
if (Platform.isMacOS) {
_updateTrafficLightVisibility();
}
}
_startHideTimer();
// Request focus on play/pause button after controls are shown
WidgetsBinding.instance.addPostFrameCallback((_) {
_desktopControlsKey.currentState?.requestPlayPauseFocus();
});
}
/// Hide controls when navigating up from timeline (keyboard mode)
void _hideControlsFromKeyboard() {
if (_showControls) {
setState(() {
_showControls = false;
});
// Return focus to the main focus node
_focusNode.requestFocus();
if (Platform.isMacOS) {
_updateTrafficLightVisibility();
}
if (Platform.isLinux) {
Future.delayed(const Duration(milliseconds: 250), () {
if (mounted && !_showControls) {
setState(() {
_controlsFullyHidden = true;
});
widget.player.setControlsVisible(false);
}
});
}
}
}
@override
Widget build(BuildContext context) {
final isMobile = PlatformDetector.isMobile(context);
// Use desktop controls for desktop platforms AND Android TV
final isMobile = PlatformDetector.isMobile(context) && !PlatformDetector.isTV();
return Focus(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (node, event) {
// Only handle KeyDown and KeyRepeat events
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
// Reset hide timer on any keyboard/controller input when controls are visible
if (_showControls) {
_restartHideTimerIfPlaying();
}
final key = event.logicalKey;
// Handle Back/Escape: show controls if hidden, navigate back if visible
if (_isBackKey(key)) {
if (!_showControls) {
_showControlsWithFocus();
return KeyEventResult.handled;
}
// Controls visible - navigate back
Navigator.of(context).pop(true);
return KeyEventResult.handled;
}
// Handle Select/Enter when controls are hidden: pause and show controls
// Only intercept if this Focus node itself has primary focus (not a descendant)
if (_isSelectKey(key) && !_showControls && _focusNode.hasPrimaryFocus) {
widget.player.playOrPause();
_showControlsWithFocus();
return KeyEventResult.handled;
}
// On desktop, show controls and focus play/pause on directional input
if (!isMobile && _isDirectionalKey(key)) {
// If controls are hidden, show them and focus play/pause
if (!_showControls) {
_showControlsWithFocus();
return KeyEventResult.handled;
}
// If controls are shown, let the event propagate to the focused control
// The DesktopVideoControls will handle navigation
return KeyEventResult.ignored;
}
// Pass other events to the keyboard shortcuts service
if (_keyboardService == null) return KeyEventResult.ignored;
return _keyboardService!.handleVideoPlayerKeyEvent(
@@ -795,73 +933,100 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
offstage: Platform.isLinux && _controlsFullyHidden,
child: IgnorePointer(
ignoring: !_showControls,
child: AnimatedOpacity(
opacity: _showControls ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
child: GestureDetector(
onTap: _toggleControls,
behavior: HitTestBehavior.deferToChild,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black.withValues(alpha: 0.7),
Colors.transparent,
Colors.transparent,
Colors.black.withValues(alpha: 0.7),
],
stops: const [0.0, 0.2, 0.8, 1.0],
child: FocusScope(
// Prevent focus from entering controls when hidden
canRequestFocus: _showControls,
child: AnimatedOpacity(
opacity: _showControls ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
child: GestureDetector(
onTap: _toggleControls,
behavior: HitTestBehavior.deferToChild,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black.withValues(alpha: 0.7),
Colors.transparent,
Colors.transparent,
Colors.black.withValues(alpha: 0.7),
],
stops: const [0.0, 0.2, 0.8, 1.0],
),
),
),
child: isMobile
? Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) =>
_restartHideTimerIfPlaying(),
child: MobileVideoControls(
player: widget.player,
metadata: widget.metadata,
chapters: _chapters,
chaptersLoaded: _chaptersLoaded,
seekTimeSmall: _seekTimeSmall,
trackChapterControls:
_buildTrackChapterControlsWidget(),
onSeek: _throttledSeek,
onSeekEnd: _finalizeSeek,
onPlayPause:
() {}, // Not used, handled internally
onCancelAutoHide: () => _hideTimer?.cancel(),
onStartAutoHide: _startHideTimer,
),
)
: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) =>
_restartHideTimerIfPlaying(),
child: DesktopVideoControls(
player: widget.player,
metadata: widget.metadata,
onNext: widget.onNext,
onPrevious: widget.onPrevious,
chapters: _chapters,
chaptersLoaded: _chaptersLoaded,
seekTimeSmall: _seekTimeSmall,
volumeControl: VolumeControl(
child: isMobile
? Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) =>
_restartHideTimerIfPlaying(),
child: MobileVideoControls(
player: widget.player,
metadata: widget.metadata,
chapters: _chapters,
chaptersLoaded: _chaptersLoaded,
seekTimeSmall: _seekTimeSmall,
trackChapterControls:
_buildTrackChapterControlsWidget(),
onSeek: _throttledSeek,
onSeekEnd: _finalizeSeek,
onPlayPause:
() {}, // Not used, handled internally
onCancelAutoHide: () =>
_hideTimer?.cancel(),
onStartAutoHide: _startHideTimer,
),
)
: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) =>
_restartHideTimerIfPlaying(),
child: DesktopVideoControls(
key: _desktopControlsKey,
player: widget.player,
metadata: widget.metadata,
onNext: widget.onNext,
onPrevious: widget.onPrevious,
chapters: _chapters,
chaptersLoaded: _chaptersLoaded,
seekTimeSmall: _seekTimeSmall,
onSeekToPreviousChapter:
_seekToPreviousChapter,
onSeekToNextChapter: _seekToNextChapter,
onSeek: _throttledSeek,
onSeekEnd: _finalizeSeek,
getReplayIcon: getReplayIcon,
getForwardIcon: getForwardIcon,
onFocusActivity: _restartHideTimerIfPlaying,
onHideControls: _hideControlsFromKeyboard,
// Track chapter controls data
availableVersions: widget.availableVersions,
selectedMediaIndex:
widget.selectedMediaIndex,
boxFitMode: widget.boxFitMode,
audioSyncOffset: _audioSyncOffset,
subtitleSyncOffset: _subtitleSyncOffset,
isFullscreen: _isFullscreen,
onCycleBoxFitMode: widget.onCycleBoxFitMode,
onToggleFullscreen: _toggleFullscreen,
onSwitchVersion: _switchMediaVersion,
onAudioTrackChanged:
widget.onAudioTrackChanged,
onSubtitleTrackChanged:
widget.onSubtitleTrackChanged,
onLoadSeekTimes: () async {
if (mounted) {
await _loadSeekTimes();
}
},
onCancelAutoHide: () =>
_hideTimer?.cancel(),
onStartAutoHide: _startHideTimer,
serverId: widget.metadata.serverId ?? '',
),
trackChapterControls:
_buildTrackChapterControlsWidget(),
onSeekToPreviousChapter:
_seekToPreviousChapter,
onSeekToNextChapter: _seekToNextChapter,
onSeek: _throttledSeek,
onSeekEnd: _finalizeSeek,
getReplayIcon: getReplayIcon,
getForwardIcon: getForwardIcon,
),
),
),
),
),
),
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../models/plex_media_info.dart';
import '../../../i18n/strings.g.dart';
import '../../../focus/focusable_wrapper.dart';
import '../painters/chapter_marker_painter.dart';
/// Timeline slider with chapter markers for video playback
@@ -16,6 +18,15 @@ class TimelineSlider extends StatelessWidget {
final ValueChanged<Duration> onSeek;
final ValueChanged<Duration> onSeekEnd;
/// Optional FocusNode for D-pad/keyboard navigation.
final FocusNode? focusNode;
/// Custom key event handler for focus navigation.
final KeyEventResult Function(FocusNode, KeyEvent)? onKeyEvent;
/// Called when focus changes.
final ValueChanged<bool>? onFocusChange;
const TimelineSlider({
super.key,
required this.position,
@@ -24,11 +35,14 @@ class TimelineSlider extends StatelessWidget {
required this.chaptersLoaded,
required this.onSeek,
required this.onSeekEnd,
this.focusNode,
this.onKeyEvent,
this.onFocusChange,
});
@override
Widget build(BuildContext context) {
return Stack(
Widget slider = Stack(
alignment: Alignment.center,
children: [
// Chapter markers layer
@@ -106,5 +120,22 @@ class TimelineSlider extends StatelessWidget {
),
],
);
// Wrap with FocusableWrapper when focusNode is provided
if (focusNode != null) {
slider = FocusableWrapper(
focusNode: focusNode,
onKeyEvent: onKeyEvent,
onFocusChange: onFocusChange,
borderRadius: 8,
autoScroll: false,
useBackgroundFocus: true,
disableScale: true,
semanticLabel: t.videoControls.timelineSlider,
child: slider,
);
}
return slider;
}
}
@@ -1,6 +1,7 @@
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../mpv/mpv.dart';
import '../../../models/plex_media_info.dart';
@@ -13,6 +14,7 @@ import '../sheets/chapter_sheet.dart';
import '../sheets/subtitle_track_sheet.dart';
import '../sheets/version_sheet.dart';
import '../sheets/video_settings_sheet.dart';
import '../helpers/track_filter_helper.dart';
import '../video_control_button.dart';
/// Row of track and chapter control buttons for the video player
@@ -38,6 +40,15 @@ class TrackChapterControls extends StatelessWidget {
final VoidCallback? onStartAutoHide;
final String serverId;
/// List of FocusNodes for the buttons (passed from parent for navigation)
final List<FocusNode>? focusNodes;
/// Called when focus changes on any button
final ValueChanged<bool>? onFocusChange;
/// Called to navigate left from the first button
final VoidCallback? onNavigateLeft;
const TrackChapterControls({
super.key,
required this.player,
@@ -60,8 +71,51 @@ class TrackChapterControls extends StatelessWidget {
this.onLoadSeekTimes,
this.onCancelAutoHide,
this.onStartAutoHide,
this.focusNodes,
this.onFocusChange,
this.onNavigateLeft,
});
/// Handle key event for button navigation
KeyEventResult _handleButtonKeyEvent(
FocusNode node,
KeyEvent event,
int index,
int totalButtons,
) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// LEFT arrow - move to previous button or exit to volume
if (key == LogicalKeyboardKey.arrowLeft) {
if (index > 0 && focusNodes != null && focusNodes!.length > index - 1) {
focusNodes![index - 1].requestFocus();
return KeyEventResult.handled;
} else if (index == 0) {
onNavigateLeft?.call();
return KeyEventResult.handled;
}
return KeyEventResult.handled;
}
// RIGHT arrow - move to next button
if (key == LogicalKeyboardKey.arrowRight) {
if (index < totalButtons - 1 &&
focusNodes != null &&
focusNodes!.length > index + 1) {
focusNodes![index + 1].requestFocus();
return KeyEventResult.handled;
}
// At end, consume to prevent bubbling
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Tracks>(
@@ -69,140 +123,299 @@ class TrackChapterControls extends StatelessWidget {
initialData: player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final isMobile = PlatformDetector.isMobile(context);
final isDesktop =
Platform.isWindows || Platform.isLinux || Platform.isMacOS;
// Build list of buttons dynamically to track indices
final buttons = <Widget>[];
int buttonIndex = 0;
// Settings button (always shown)
buttons.add(
ListenableBuilder(
listenable: SleepTimerService(),
builder: (context, _) {
final sleepTimer = SleepTimerService();
final isActive =
sleepTimer.isActive ||
audioSyncOffset != 0 ||
subtitleSyncOffset != 0;
final currentIndex = 0;
return VideoControlButton(
icon: Icons.tune,
isActive: isActive,
semanticLabel: t.videoControls.settingsButton,
focusNode: focusNodes != null && focusNodes!.isNotEmpty
? focusNodes![currentIndex]
: null,
onKeyEvent: focusNodes != null
? (node, event) => _handleButtonKeyEvent(
node,
event,
currentIndex,
_getButtonCount(tracks, isMobile, isDesktop),
)
: null,
onFocusChange: onFocusChange,
onPressed: () async {
await VideoSettingsSheet.show(
context,
player,
audioSyncOffset,
subtitleSyncOffset,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
);
onLoadSeekTimes?.call();
},
);
},
),
);
buttonIndex++;
// Audio track button
if (_hasMultipleAudioTracks(tracks)) {
final currentIndex = buttonIndex;
buttons.add(
VideoControlButton(
icon: Icons.audiotrack,
semanticLabel: t.videoControls.audioTrackButton,
focusNode: focusNodes != null && focusNodes!.length > currentIndex
? focusNodes![currentIndex]
: null,
onKeyEvent: focusNodes != null
? (node, event) => _handleButtonKeyEvent(
node,
event,
currentIndex,
_getButtonCount(tracks, isMobile, isDesktop),
)
: null,
onFocusChange: onFocusChange,
onPressed: () => AudioTrackSheet.show(
context,
player,
onTrackChanged: onAudioTrackChanged,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
),
);
buttonIndex++;
}
// Subtitles button
if (_hasSubtitles(tracks)) {
final currentIndex = buttonIndex;
buttons.add(
VideoControlButton(
icon: Icons.subtitles,
semanticLabel: t.videoControls.subtitlesButton,
focusNode: focusNodes != null && focusNodes!.length > currentIndex
? focusNodes![currentIndex]
: null,
onKeyEvent: focusNodes != null
? (node, event) => _handleButtonKeyEvent(
node,
event,
currentIndex,
_getButtonCount(tracks, isMobile, isDesktop),
)
: null,
onFocusChange: onFocusChange,
onPressed: () => SubtitleTrackSheet.show(
context,
player,
onTrackChanged: onSubtitleTrackChanged,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
),
);
buttonIndex++;
}
// Chapters button
if (chapters.isNotEmpty) {
final currentIndex = buttonIndex;
buttons.add(
VideoControlButton(
icon: Icons.video_library,
semanticLabel: t.videoControls.chaptersButton,
focusNode: focusNodes != null && focusNodes!.length > currentIndex
? focusNodes![currentIndex]
: null,
onKeyEvent: focusNodes != null
? (node, event) => _handleButtonKeyEvent(
node,
event,
currentIndex,
_getButtonCount(tracks, isMobile, isDesktop),
)
: null,
onFocusChange: onFocusChange,
onPressed: () => ChapterSheet.show(
context,
player,
chapters,
chaptersLoaded,
serverId: serverId,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
),
);
buttonIndex++;
}
// Versions button
if (availableVersions.length > 1 && onSwitchVersion != null) {
final currentIndex = buttonIndex;
buttons.add(
VideoControlButton(
icon: Icons.video_file,
semanticLabel: t.videoControls.versionsButton,
focusNode: focusNodes != null && focusNodes!.length > currentIndex
? focusNodes![currentIndex]
: null,
onKeyEvent: focusNodes != null
? (node, event) => _handleButtonKeyEvent(
node,
event,
currentIndex,
_getButtonCount(tracks, isMobile, isDesktop),
)
: null,
onFocusChange: onFocusChange,
onPressed: () => VersionSheet.show(
context,
availableVersions,
selectedMediaIndex,
onSwitchVersion!,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
),
);
buttonIndex++;
}
// BoxFit mode button
if (onCycleBoxFitMode != null) {
final currentIndex = buttonIndex;
buttons.add(
VideoControlButton(
icon: _getBoxFitIcon(boxFitMode),
tooltip: _getBoxFitTooltip(boxFitMode),
semanticLabel: t.videoControls.aspectRatioButton,
focusNode: focusNodes != null && focusNodes!.length > currentIndex
? focusNodes![currentIndex]
: null,
onKeyEvent: focusNodes != null
? (node, event) => _handleButtonKeyEvent(
node,
event,
currentIndex,
_getButtonCount(tracks, isMobile, isDesktop),
)
: null,
onFocusChange: onFocusChange,
onPressed: onCycleBoxFitMode,
),
);
buttonIndex++;
}
// Rotation lock button (mobile only)
if (isMobile) {
final currentIndex = buttonIndex;
buttons.add(
VideoControlButton(
icon: isRotationLocked
? Icons.screen_lock_rotation
: Icons.screen_rotation,
tooltip: isRotationLocked
? t.videoControls.unlockRotation
: t.videoControls.lockRotation,
semanticLabel: t.videoControls.rotationLockButton,
focusNode: focusNodes != null && focusNodes!.length > currentIndex
? focusNodes![currentIndex]
: null,
onKeyEvent: focusNodes != null
? (node, event) => _handleButtonKeyEvent(
node,
event,
currentIndex,
_getButtonCount(tracks, isMobile, isDesktop),
)
: null,
onFocusChange: onFocusChange,
onPressed: onToggleRotationLock,
),
);
buttonIndex++;
}
// Fullscreen button (desktop only)
if (isDesktop) {
final currentIndex = buttonIndex;
buttons.add(
VideoControlButton(
icon: isFullscreen ? Icons.fullscreen_exit : Icons.fullscreen,
semanticLabel: isFullscreen
? t.videoControls.exitFullscreenButton
: t.videoControls.fullscreenButton,
focusNode: focusNodes != null && focusNodes!.length > currentIndex
? focusNodes![currentIndex]
: null,
onKeyEvent: focusNodes != null
? (node, event) => _handleButtonKeyEvent(
node,
event,
currentIndex,
_getButtonCount(tracks, isMobile, isDesktop),
)
: null,
onFocusChange: onFocusChange,
onPressed: onToggleFullscreen,
),
);
}
return IntrinsicHeight(
child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Unified settings button (speed, sleep timer, audio sync, subtitle sync)
ListenableBuilder(
listenable: SleepTimerService(),
builder: (context, _) {
final sleepTimer = SleepTimerService();
final isActive =
sleepTimer.isActive ||
audioSyncOffset != 0 ||
subtitleSyncOffset != 0;
return VideoControlButton(
icon: Icons.tune,
isActive: isActive,
semanticLabel: t.videoControls.settingsButton,
onPressed: () async {
await VideoSettingsSheet.show(
context,
player,
audioSyncOffset,
subtitleSyncOffset,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
);
// Sheet is now closed, reload immediately
onLoadSeekTimes?.call();
},
);
},
),
if (_hasMultipleAudioTracks(tracks))
VideoControlButton(
icon: Icons.audiotrack,
semanticLabel: t.videoControls.audioTrackButton,
onPressed: () => AudioTrackSheet.show(
context,
player,
onTrackChanged: onAudioTrackChanged,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
),
if (_hasSubtitles(tracks))
VideoControlButton(
icon: Icons.subtitles,
semanticLabel: t.videoControls.subtitlesButton,
onPressed: () => SubtitleTrackSheet.show(
context,
player,
onTrackChanged: onSubtitleTrackChanged,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
),
if (chapters.isNotEmpty)
VideoControlButton(
icon: Icons.video_library,
semanticLabel: t.videoControls.chaptersButton,
onPressed: () => ChapterSheet.show(
context,
player,
chapters,
chaptersLoaded,
serverId: serverId,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
),
if (availableVersions.length > 1 && onSwitchVersion != null)
VideoControlButton(
icon: Icons.video_file,
semanticLabel: t.videoControls.versionsButton,
onPressed: () => VersionSheet.show(
context,
availableVersions,
selectedMediaIndex,
onSwitchVersion!,
onOpen: onCancelAutoHide,
onClose: onStartAutoHide,
),
),
// BoxFit mode cycle button
if (onCycleBoxFitMode != null)
VideoControlButton(
icon: _getBoxFitIcon(boxFitMode),
tooltip: _getBoxFitTooltip(boxFitMode),
semanticLabel: t.videoControls.aspectRatioButton,
onPressed: onCycleBoxFitMode,
),
// Rotation lock toggle (mobile only)
if (PlatformDetector.isMobile(context))
VideoControlButton(
icon: isRotationLocked
? Icons.screen_lock_rotation
: Icons.screen_rotation,
tooltip: isRotationLocked
? t.videoControls.unlockRotation
: t.videoControls.lockRotation,
semanticLabel: t.videoControls.rotationLockButton,
onPressed: onToggleRotationLock,
),
// Fullscreen toggle (desktop only)
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS)
VideoControlButton(
icon: isFullscreen ? Icons.fullscreen_exit : Icons.fullscreen,
semanticLabel: isFullscreen
? t.videoControls.exitFullscreenButton
: t.videoControls.fullscreenButton,
onPressed: onToggleFullscreen,
),
],
children: buttons,
),
);
},
);
}
/// Calculate total button count for navigation
int _getButtonCount(Tracks? tracks, bool isMobile, bool isDesktop) {
int count = 1; // Settings button always shown
if (_hasMultipleAudioTracks(tracks)) count++;
if (_hasSubtitles(tracks)) count++;
if (chapters.isNotEmpty) count++;
if (availableVersions.length > 1 && onSwitchVersion != null) count++;
if (onCycleBoxFitMode != null) count++;
if (isMobile) count++;
if (isDesktop) count++;
return count;
}
bool _hasMultipleAudioTracks(Tracks? tracks) {
if (tracks == null) return false;
final audioTracks = tracks.audio
.where((track) => track.id != 'auto' && track.id != 'no')
.toList();
return audioTracks.length > 1;
return TrackFilterHelper.hasMultipleTracks<AudioTrack>(tracks.audio);
}
bool _hasSubtitles(Tracks? tracks) {
if (tracks == null) return false;
final subtitles = tracks.subtitle
.where((track) => track.id != 'auto' && track.id != 'no')
.toList();
return subtitles.isNotEmpty;
return TrackFilterHelper.hasTracks<SubtitleTrack>(tracks.subtitle);
}
IconData _getBoxFitIcon(int mode) {
@@ -0,0 +1,100 @@
import 'package:flutter/material.dart';
import '../../../models/plex_metadata.dart';
import '../../../i18n/strings.g.dart';
import '../../app_bar_back_button.dart';
/// Header layout style for video controls
enum VideoHeaderStyle {
/// Multi-line: Series name on first line, episode info on second line
multiLine,
/// Single-line: All info combined with separators (for macOS)
singleLine,
}
/// Shared header widget for video controls with back button and title.
///
/// Displays the video title with optional series/episode information.
/// Supports both single-line (macOS) and multi-line (other platforms) layouts.
class VideoControlsHeader extends StatelessWidget {
final PlexMetadata metadata;
final VideoHeaderStyle style;
/// Optional trailing widget (e.g., track/chapter controls)
final Widget? trailing;
const VideoControlsHeader({
super.key,
required this.metadata,
this.style = VideoHeaderStyle.multiLine,
this.trailing,
});
@override
Widget build(BuildContext context) {
return Row(
children: [
AppBarBackButton(
style: BackButtonStyle.video,
semanticLabel: t.videoControls.backButton,
onPressed: () => Navigator.of(context).pop(true),
),
const SizedBox(width: 16),
Expanded(
child: style == VideoHeaderStyle.singleLine
? _buildSingleLineTitle()
: _buildMultiLineTitle(),
),
if (trailing != null) trailing!,
],
);
}
Widget _buildSingleLineTitle() {
// Build single-line title combining series and episode info
final seriesName = metadata.grandparentTitle ?? metadata.title;
final hasEpisodeInfo =
metadata.parentIndex != null && metadata.index != null;
final titleText = hasEpisodeInfo
? '$seriesName · S${metadata.parentIndex} E${metadata.index} · ${metadata.title}'
: seriesName;
return Text(
titleText,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
Widget _buildMultiLineTitle() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
metadata.grandparentTitle ?? metadata.title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (metadata.parentIndex != null && metadata.index != null)
Text(
'S${metadata.parentIndex} · E${metadata.index} · ${metadata.title}',
style: const TextStyle(color: Colors.white70, fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
);
}
}
@@ -0,0 +1,118 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../mpv/mpv.dart';
import '../../../models/plex_media_info.dart';
import '../../../utils/duration_formatter.dart';
import 'timeline_slider.dart';
/// Encapsulates the StreamBuilder stack for video timeline with timestamps.
///
/// This widget listens to player position and duration streams, and displays
/// a timeline slider with formatted timestamps. Supports both horizontal
/// layout (timestamps beside slider) and vertical layout (timestamps below slider).
class VideoTimelineBar extends StatelessWidget {
final Player player;
final List<PlexChapter> chapters;
final bool chaptersLoaded;
final ValueChanged<Duration> onSeek;
final ValueChanged<Duration> onSeekEnd;
/// If true, timestamps are shown in a row beside the slider (desktop layout).
/// If false, timestamps are shown in a row below the slider (mobile layout).
final bool horizontalLayout;
/// Optional FocusNode for D-pad/keyboard navigation.
final FocusNode? focusNode;
/// Custom key event handler for focus navigation.
final KeyEventResult Function(FocusNode, KeyEvent)? onKeyEvent;
/// Called when focus changes.
final ValueChanged<bool>? onFocusChange;
const VideoTimelineBar({
super.key,
required this.player,
required this.chapters,
required this.chaptersLoaded,
required this.onSeek,
required this.onSeekEnd,
this.horizontalLayout = true,
this.focusNode,
this.onKeyEvent,
this.onFocusChange,
});
@override
Widget build(BuildContext context) {
return StreamBuilder<Duration>(
stream: player.streams.position,
initialData: player.state.position,
builder: (context, positionSnapshot) {
return StreamBuilder<Duration>(
stream: player.streams.duration,
initialData: player.state.duration,
builder: (context, durationSnapshot) {
final position = positionSnapshot.data ?? Duration.zero;
final duration = durationSnapshot.data ?? Duration.zero;
if (horizontalLayout) {
return _buildHorizontalLayout(position, duration);
} else {
return _buildVerticalLayout(position, duration);
}
},
);
},
);
}
Widget _buildHorizontalLayout(Duration position, Duration duration) {
return Row(
children: [
_buildTimestamp(position),
const SizedBox(width: 12),
Expanded(child: _buildSlider(position, duration)),
const SizedBox(width: 12),
_buildTimestamp(duration),
],
);
}
Widget _buildVerticalLayout(Duration position, Duration duration) {
return Column(
children: [
_buildSlider(position, duration),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [_buildTimestamp(position), _buildTimestamp(duration)],
),
),
],
);
}
Widget _buildTimestamp(Duration time) {
return Text(
formatDurationTimestamp(time),
style: const TextStyle(color: Colors.white, fontSize: 14),
);
}
Widget _buildSlider(Duration position, Duration duration) {
return TimelineSlider(
position: position,
duration: duration,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
onSeek: onSeek,
onSeekEnd: onSeekEnd,
focusNode: focusNode,
onKeyEvent: onKeyEvent,
onFocusChange: onFocusChange,
);
}
}
@@ -1,87 +1,228 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../mpv/mpv.dart';
import '../../../services/settings_service.dart';
import '../../../i18n/strings.g.dart';
import '../../../focus/focusable_wrapper.dart';
import '../../../focus/input_mode_tracker.dart';
/// A volume control widget that displays a mute/unmute button and volume slider.
///
/// This widget integrates with [Player] to control volume and persists
/// the volume setting using [SettingsService].
class VolumeControl extends StatelessWidget {
///
/// When using keyboard/D-pad navigation, pressing Select enters "adjust mode"
/// where left/right arrows adjust volume instead of navigating.
class VolumeControl extends StatefulWidget {
final Player player;
const VolumeControl({super.key, required this.player});
/// Optional FocusNode for D-pad/keyboard navigation.
final FocusNode? focusNode;
/// Custom key event handler for focus navigation (used when NOT in adjust mode).
final KeyEventResult Function(FocusNode, KeyEvent)? onKeyEvent;
/// Called when focus changes.
final ValueChanged<bool>? onFocusChange;
/// Called on any keyboard activity (to reset hide timer).
final VoidCallback? onFocusActivity;
const VolumeControl({
super.key,
required this.player,
this.focusNode,
this.onKeyEvent,
this.onFocusChange,
this.onFocusActivity,
});
@override
State<VolumeControl> createState() => _VolumeControlState();
}
class _VolumeControlState extends State<VolumeControl> {
/// Whether we're in volume adjust mode (left/right adjusts volume).
bool _isAdjustMode = false;
/// Volume step size for keyboard adjustment.
static const double _volumeStep = 5.0;
void _enterAdjustMode() {
setState(() {
_isAdjustMode = true;
});
}
void _exitAdjustMode() {
setState(() {
_isAdjustMode = false;
});
}
Future<void> _adjustVolume(double delta) async {
final currentVolume = widget.player.state.volume;
final newVolume = (currentVolume + delta).clamp(0.0, 100.0);
widget.player.setVolume(newVolume);
final settings = await SettingsService.getInstance();
await settings.setVolume(newVolume);
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
if (_isAdjustMode) {
// Notify activity on any key in adjust mode (to reset hide timer)
widget.onFocusActivity?.call();
// In adjust mode: left/right adjusts volume, back/escape exits
if (key == LogicalKeyboardKey.arrowLeft) {
_adjustVolume(-_volumeStep);
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.arrowRight) {
_adjustVolume(_volumeStep);
return KeyEventResult.handled;
}
if (_isBackKey(key) || _isSelectKey(key)) {
_exitAdjustMode();
return KeyEventResult.handled;
}
// UP/DOWN exits adjust mode and lets navigation continue
if (key == LogicalKeyboardKey.arrowUp ||
key == LogicalKeyboardKey.arrowDown) {
_exitAdjustMode();
// Pass through to normal navigation handler
return widget.onKeyEvent?.call(node, event) ?? KeyEventResult.ignored;
}
// Consume other keys in adjust mode
return KeyEventResult.handled;
}
// Not in adjust mode: use the provided key event handler for navigation
return widget.onKeyEvent?.call(node, event) ?? KeyEventResult.ignored;
}
bool _isBackKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.escape ||
key == LogicalKeyboardKey.goBack ||
key == LogicalKeyboardKey.browserBack ||
key == LogicalKeyboardKey.gameButtonB;
}
bool _isSelectKey(LogicalKeyboardKey key) {
return key == LogicalKeyboardKey.select ||
key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.numpadEnter ||
key == LogicalKeyboardKey.gameButtonA;
}
void _handleFocusChange(bool hasFocus) {
// Exit adjust mode when focus is lost
if (!hasFocus && _isAdjustMode) {
_exitAdjustMode();
}
widget.onFocusChange?.call(hasFocus);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<double>(
stream: player.streams.volume,
initialData: player.state.volume,
stream: widget.player.streams.volume,
initialData: widget.player.state.volume,
builder: (context, snapshot) {
final volume = snapshot.data ?? 100.0;
final isMuted = volume == 0;
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
final muteButton = Semantics(
label: isMuted
? t.videoControls.unmuteButton
: t.videoControls.muteButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
isMuted ? Icons.volume_off : Icons.volume_up,
color: Colors.white,
),
onPressed: () async {
final newVolume = isMuted ? 100.0 : 0.0;
widget.player.setVolume(newVolume);
final settings = await SettingsService.getInstance();
await settings.setVolume(newVolume);
},
),
);
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Semantics(
label: isMuted
? t.videoControls.unmuteButton
: t.videoControls.muteButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
isMuted ? Icons.volume_off : Icons.volume_up,
color: Colors.white,
),
onPressed: () async {
final newVolume = isMuted ? 100.0 : 0.0;
player.setVolume(newVolume);
final settings = await SettingsService.getInstance();
await settings.setVolume(newVolume);
},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
),
if (widget.focusNode != null)
FocusableWrapper(
focusNode: widget.focusNode,
onSelect: _enterAdjustMode,
onKeyEvent: _handleKeyEvent,
onFocusChange: _handleFocusChange,
borderRadius: 20,
autoScroll: false,
useBackgroundFocus: true,
disableScale: true,
semanticLabel: _isAdjustMode
? t.videoControls.volumeSlider
: (isMuted
? t.videoControls.unmuteButton
: t.videoControls.muteButton),
child: muteButton,
)
else
muteButton,
const SizedBox(width: 8),
SizedBox(
width: 100,
child: SliderTheme(
data: SliderThemeData(
trackHeight: 3,
thumbShape: const RoundSliderThumbShape(
enabledThumbRadius: 6,
),
overlayShape: const RoundSliderOverlayShape(
overlayRadius: 12,
),
),
child: Semantics(
label: t.videoControls.volumeSlider,
slider: true,
child: Slider(
value: volume,
min: 0.0,
max: 100.0,
onChanged: (value) {
player.setVolume(value);
},
onChangeEnd: (value) async {
final settings = await SettingsService.getInstance();
await settings.setVolume(value);
},
activeColor: Colors.white,
inactiveColor: Colors.white.withValues(alpha: 0.3),
),
),
),
),
_buildVolumeSlider(volume, isKeyboardMode),
],
);
},
);
}
Widget _buildVolumeSlider(double volume, bool isKeyboardMode) {
// Show visual indicator when in adjust mode with keyboard
final showAdjustIndicator = _isAdjustMode && isKeyboardMode;
return SizedBox(
width: 100,
child: SliderTheme(
data: SliderThemeData(
trackHeight: showAdjustIndicator ? 4 : 3,
thumbShape: RoundSliderThumbShape(
enabledThumbRadius: showAdjustIndicator ? 8 : 6,
),
overlayShape: const RoundSliderOverlayShape(overlayRadius: 12),
),
child: Semantics(
label: t.videoControls.volumeSlider,
slider: true,
child: Slider(
value: volume,
min: 0.0,
max: 100.0,
onChanged: (value) {
widget.player.setVolume(value);
},
onChangeEnd: (value) async {
final settings = await SettingsService.getInstance();
await settings.setVolume(value);
},
activeColor: Colors.white,
inactiveColor: Colors.white.withValues(alpha: 0.3),
),
),
),
);
}
}

Some files were not shown because too many files have changed in this diff Show More