Compare commits

..
18 Commits
Author SHA1 Message Date
github-actions[bot] 02f2657d18 chore: bump version to 2.3.0 2026-05-26 21:13:32 +00:00
edde746 39709e5c42 test(tv): update keyboard focus expectations 2026-05-26 23:00:44 +02:00
edde746 a101ee76d6 fix(downloads): prevent duplicate native tasks
close #1141
2026-05-26 22:43:05 +02:00
edde746 4eadec5b17 fix(tv): pass root menu to system 2026-05-26 18:27:26 +02:00
edde746 be86a33057 fix(discover): hide duplicate continue watching
close #1113
2026-05-26 14:48:16 +02:00
edde746 ce19b9dfa7 fix(ui): theme recommendation text colors 2026-05-26 14:05:26 +02:00
edde746 15cc85147a fix(tv): improve virtual keyboard input 2026-05-26 14:01:20 +02:00
edde746 3fc3baef83 fix(tv): reveal details without input 2026-05-26 12:02:48 +02:00
edde746 91b926acac fix(android): respect vtt subtitle position 2026-05-26 06:34:59 +02:00
edde746 8b2ff18842 fix(android): improve mpeg-ts seeking 2026-05-26 03:14:19 +02:00
edde746 1958f8ca7e feat(jellyfin): add folder browsing and playback 2026-05-26 01:39:39 +02:00
edde746 8e53232961 fix(jellyfin): avoid side-loading negotiated subtitles 2026-05-25 23:39:55 +02:00
edde746 cec8993b80 fix: update win_http 2026-05-25 23:19:59 +02:00
edde746 366ae67341 feat(jellyfin): add unwatched library filter
close #1116
2026-05-25 22:43:39 +02:00
edde746 50be8565d9 fix(tv): prefer show art for episode backdrops
close #1123
2026-05-25 21:08:33 +02:00
edde746 9365fcf246 fix(tv): keep alpha bar alphabet visible 2026-05-25 16:17:27 +02:00
edde746 8d4ef2757a fix(ios): update MPVKit PiP subtitles 2026-05-25 15:31:41 +02:00
edde746 6b147e2053 fix(ios): enable PiP subtitles 2026-05-25 04:47:55 +02:00
88 changed files with 2808 additions and 508 deletions
@@ -56,6 +56,7 @@ import androidx.media3.extractor.DefaultExtractorsFactory
import androidx.media3.extractor.mkv.MatroskaExtractor
import androidx.media3.extractor.mp4.FragmentedMp4Extractor
import androidx.media3.extractor.mp4.Mp4Extractor
import androidx.media3.extractor.ts.TsExtractor
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.CaptionStyleCompat
import androidx.media3.ui.SubtitleView
@@ -96,6 +97,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
private const val WATCHDOG_TIMEOUT_MS = 8000L
private const val DECODER_HANG_TIMEOUT_MS = 5000L
private const val FPS_SAMPLE_COUNT = 8
private const val TS_TIMESTAMP_SEARCH_PACKETS = 1800
// Codec capability caches — codec support doesn't change at runtime
private val hwAudioDecoderCache = HashMap<String, Boolean>()
@@ -124,6 +126,9 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
private var exoPlayer: ExoPlayer? = null
private var renderersFactory: PlezyRenderersFactory? = null
private val subtitleDelayUs = AtomicLong(0L)
private var subtitlePositionPercent: Int = 100
private var subtitleFontSize: Float = 55f
private var lastSubtitleCues: List<Cue> = emptyList()
private var httpDataSourceFactory: HttpDataSource.Factory? = null
private var dataSourceFactory: DefaultDataSource.Factory? = null
private var trackSelector: DefaultTrackSelector? = null
@@ -456,6 +461,9 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
.setReadTimeoutMs(10_000)
dataSourceFactory = DefaultDataSource.Factory(activity, httpDataSourceFactory!!)
val extractorsFactory = DefaultExtractorsFactory()
// High-bitrate Plex DVR MPEG-TS recordings can have sparse PCR packets; the default
// 600-packet window may leave duration unknown and seeking disabled.
.setTsExtractorTimestampSearchBytes(TS_TIMESTAMP_SEARCH_PACKETS * TsExtractor.TS_PACKET_SIZE)
// Inline buildWithAssSupport to retain AssHandler reference for font scale control.
// OVERLAY_OPEN_GL uses TextureView which follows normal View hierarchy z-ordering,
@@ -723,12 +731,15 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
// With OVERLAY_CANVAS mode, ASS subtitles are rendered directly by AssSubtitleView
// This callback is for non-ASS subtitles (SRT, VTT, etc.)
val incoming = cueGroup.cues
val outgoing = stackUnpositionedCues(incoming)
lastSubtitleCues = incoming
val stacked = stackUnpositionedCues(incoming)
val outgoing = applySubtitlePosition(stacked)
if (incoming.isNotEmpty()) {
Log.d(
TAG,
"onCues: received ${incoming.size} cues (non-ASS)" +
if (outgoing !== incoming) " — stacked" else ""
(if (stacked !== incoming) " - stacked" else "") +
(if (outgoing !== stacked) " - positioned" else "")
)
}
subtitleView?.setCues(outgoing)
@@ -762,6 +773,44 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
return rebuilt
}
private fun applySubtitlePosition(cues: List<Cue>): List<Cue> {
val clampedPosition = subtitlePositionPercent.coerceIn(0, 100)
if (clampedPosition == 100 || cues.isEmpty()) return cues
val baseLine = clampedPosition / 100f
val rowHeight = (subtitleFontSize / 720f * 1.2f).coerceAtLeast(0.01f)
var changed = false
val rebuilt = cues.map { cue ->
if (!usesDefaultVerticalPlacement(cue)) return@map cue
val rowOffset = if (cue.lineType == Cue.LINE_TYPE_NUMBER && cue.line < 0f) {
(-cue.line - 1f).coerceAtLeast(0f)
} else {
0f
}
val line = if (clampedPosition == 0) {
(rowOffset * rowHeight).coerceAtMost(1f)
} else {
(baseLine - rowOffset * rowHeight).coerceIn(0f, 1f)
}
val lineAnchor = if (clampedPosition == 0) Cue.ANCHOR_TYPE_START else Cue.ANCHOR_TYPE_END
changed = true
cue.buildUpon()
.setLine(line, Cue.LINE_TYPE_FRACTION)
.setLineAnchor(lineAnchor)
.build()
}
return if (changed) rebuilt else cues
}
private fun usesDefaultVerticalPlacement(cue: Cue): Boolean {
if (cue.text == null || cue.bitmap != null || cue.verticalType != Cue.TYPE_UNSET) return false
return cue.line == Cue.DIMEN_UNSET || (cue.lineType == Cue.LINE_TYPE_NUMBER && cue.line < 0f)
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
Log.d(TAG, "onIsPlayingChanged: $isPlaying")
if (isPlaying) pendingPlayWhenReady = null
@@ -2043,6 +2092,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
externalSubtitles.clear()
externalSubtitleUris.clear()
lastSubtitleCues = emptyList()
audioTrackGroupMap.clear()
subtitleTrackGroupMap.clear()
selectedAudioTrackId = null
@@ -2397,24 +2447,24 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
val fraction = fontSize / 720f
subtitleView?.setFractionalTextSize(fraction)
// Subtitle position: adjust gravity and bottom padding
// Subtitle position: VTT default cues arrive with explicit line numbers,
// so app positioning is applied at cue level below.
val clampedPosition = subtitlePosition.coerceIn(0, 100)
val gravity = when {
clampedPosition <= 33 -> Gravity.TOP
clampedPosition <= 66 -> Gravity.CENTER
else -> Gravity.BOTTOM
}
(subtitleView?.layoutParams as? FrameLayout.LayoutParams)?.let { params ->
params.gravity = gravity or Gravity.CENTER_HORIZONTAL
subtitleView?.layoutParams = params
}
// Fine-grained positioning within bottom region via bottom padding fraction
subtitlePositionPercent = clampedPosition
subtitleFontSize = fontSize
// Cue-level positioning handles default VTT/SRT placement, whose line
// numbers bypass SubtitleView bottom padding. Authored VTT line positions
// are preserved in applySubtitlePosition().
if (clampedPosition > 66) {
val bottomFraction = (100 - clampedPosition) / 100f
subtitleView?.setBottomPaddingFraction(bottomFraction)
} else {
subtitleView?.setBottomPaddingFraction(0f)
}
if (lastSubtitleCues.isNotEmpty()) {
subtitleView?.setCues(applySubtitlePosition(stackUnpositionedCues(lastSubtitleCues)))
}
// 2. ASS subtitles: font scale via libass
// MPV default sub-font-size is 38
+1 -1
View File
@@ -789,7 +789,7 @@
repositoryURL = "https://github.com/edde746/MPVKit";
requirement = {
kind = revision;
revision = 42dcc3123000361d0be54fbaec981043b77e1e05;
revision = 01bcdad9840ba50fc874bc4d6e83bafd311ebf07;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -40,7 +40,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "42dcc3123000361d0be54fbaec981043b77e1e05"
"revision" : "01bcdad9840ba50fc874bc4d6e83bafd311ebf07"
}
},
{
@@ -40,7 +40,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "42dcc3123000361d0be54fbaec981043b77e1e05"
"revision" : "01bcdad9840ba50fc874bc4d6e83bafd311ebf07"
}
},
{
@@ -188,6 +188,7 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
guard let playerCore = playerCore else { return nil }
guard let pip = ensurePipController() else { return nil }
pendingInlineRestoreAfterPip = false
playerCore.setPipSubtitleCompositing(true)
playerCore.isPipStarting = true
pip.syncTimebase(currentTime: playerCore.timePos, isPlaying: !playerCore.isPaused)
pip.invalidatePlaybackState()
@@ -232,6 +233,7 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
/// Unified cleanup for all PiP exit paths
private func cleanupPip(notify: Bool, pause: Bool = false) {
playerCore?.setPipSubtitleCompositing(false)
playerCore?.isPipStarting = false
playerCore?.isPipActive = false
isManualPipRequest = false
+89 -17
View File
@@ -9,7 +9,7 @@ import '../utils/text_input_diagnostics.dart';
import '../widgets/tv_virtual_keyboard.dart';
import 'dpad_navigator.dart';
bool _usesTvKeyboard(bool enableTvKeyboard) => enableTvKeyboard && PlatformDetector.isAppleTV();
bool _usesTvKeyboard(bool enableTvKeyboard) => enableTvKeyboard && PlatformDetector.isTV();
String? _keyboardHint(InputDecoration? decoration) => decoration?.hintText ?? decoration?.labelText;
@@ -541,9 +541,9 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
return null;
}
void _showTvKeyboard(BuildContext context) {
if (!enabled) return;
showTvVirtualKeyboard(
Future<void> _showTvKeyboard(BuildContext context) {
if (!enabled) return Future.value();
return showTvVirtualKeyboard(
context: context,
controller: controller,
hintText: _keyboardHint(decoration),
@@ -571,12 +571,12 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
}
}
KeyEventResult _handleKey(BuildContext context, FocusNode _, KeyEvent event) {
KeyEventResult _handleKey(BuildContext context, FocusNode _, KeyEvent event, VoidCallback openKeyboard) {
return _handleInputKey(
controller: controller,
usesTvKeyboard: _hasTvKeyboard,
enabled: enabled,
openKeyboard: () => _showTvKeyboard(context),
openKeyboard: openKeyboard,
event: event,
keyboardType: keyboardType,
textInputAction: textInputAction,
@@ -595,14 +595,17 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
);
}
Widget buildFocusableInput(BuildContext context, Widget Function(bool usesTvKeyboard, FocusNode focusNode) builder) {
Widget buildFocusableInput(
BuildContext context,
Widget Function(bool usesTvKeyboard, FocusNode focusNode, VoidCallback openKeyboard) builder,
) {
return _FocusableTextInputHost(input: this, builder: builder);
}
}
class _FocusableTextInputHost extends StatefulWidget {
final _FocusableTextInputBase input;
final Widget Function(bool usesTvKeyboard, FocusNode focusNode) builder;
final Widget Function(bool usesTvKeyboard, FocusNode focusNode, VoidCallback openKeyboard) builder;
const _FocusableTextInputHost({required this.input, required this.builder});
@@ -615,9 +618,12 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
FocusNode? _installedFocusNode;
FocusOnKeyEventCallback? _previousOnKeyEvent;
late final FocusOnKeyEventCallback _keyHandler = _handleKey;
late final VoidCallback _focusListener = _syncNativeTextInputFocus;
late final VoidCallback _focusListener = _handleFocusChanged;
final Object _nativeFocusToken = Object();
bool _reportedNativeTextInputFocused = false;
bool _tvKeyboardOpen = false;
bool _tvKeyboardOpenScheduled = false;
bool _suppressTvKeyboardAutoOpen = false;
FocusNode get _effectiveFocusNode =>
widget.input.focusNode ?? (_ownedFocusNode ??= FocusNode(debugLabel: 'FocusableTextInput'));
@@ -627,8 +633,10 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
super.didUpdateWidget(oldWidget);
if (oldWidget.input.focusNode != widget.input.focusNode) {
_restoreInstalledHandler();
_suppressTvKeyboardAutoOpen = false;
_tvKeyboardOpenScheduled = false;
}
_syncNativeTextInputFocus();
_handleFocusChanged();
}
@override
@@ -638,6 +646,11 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
super.dispose();
}
void _handleFocusChanged() {
_syncNativeTextInputFocus();
_syncTvKeyboardAutoOpen();
}
void _syncNativeTextInputFocus() {
final focused = _installedFocusNode?.hasFocus == true && widget.input.enabled && widget.input._usesNativeTvKeyboard;
_logTvTextInput(
@@ -648,6 +661,65 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
_setNativeTextInputFocused(focused);
}
void _syncTvKeyboardAutoOpen() {
final focused = _installedFocusNode?.hasFocus == true && widget.input.enabled && widget.input._hasTvKeyboard;
final visible = _canShowTvKeyboard;
_logTvTextInput(
'Host.syncTvKeyboardAutoOpen focused=$focused open=$_tvKeyboardOpen scheduled=$_tvKeyboardOpenScheduled '
'suppressed=$_suppressTvKeyboardAutoOpen installed=${_installedFocusNode?.debugLabel} '
'hasFocus=${_installedFocusNode?.hasFocus} enabled=${widget.input.enabled} '
'usesTvKeyboard=${widget.input._hasTvKeyboard} visible=$visible',
);
if (!focused) {
if (!_tvKeyboardOpen && !_tvKeyboardOpenScheduled) {
_suppressTvKeyboardAutoOpen = false;
}
return;
}
if (!visible) return;
if (_suppressTvKeyboardAutoOpen || _tvKeyboardOpen || _tvKeyboardOpenScheduled) return;
_tvKeyboardOpenScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_tvKeyboardOpenScheduled = false;
final stillFocused = _installedFocusNode?.hasFocus == true && widget.input.enabled && widget.input._hasTvKeyboard;
if (!stillFocused || !_canShowTvKeyboard || _suppressTvKeyboardAutoOpen || _tvKeyboardOpen) return;
_openTvKeyboard();
});
}
bool get _canShowTvKeyboard {
final route = ModalRoute.of(context);
return TickerMode.valuesOf(context).enabled && (route?.isCurrent ?? true);
}
void _openTvKeyboard() {
if (!mounted || !widget.input.enabled || !widget.input._hasTvKeyboard || !_canShowTvKeyboard || _tvKeyboardOpen) {
return;
}
_tvKeyboardOpenScheduled = false;
_tvKeyboardOpen = true;
_suppressTvKeyboardAutoOpen = true;
_logTvTextInput('Host.openTvKeyboard node=${_installedFocusNode?.debugLabel}');
unawaited(
widget.input._showTvKeyboard(context).whenComplete(() {
if (!mounted) return;
_tvKeyboardOpen = false;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
if (_installedFocusNode?.hasFocus != true) {
_suppressTvKeyboardAutoOpen = false;
}
_syncTvKeyboardAutoOpen();
});
}),
);
}
void _setNativeTextInputFocused(bool focused) {
if (_reportedNativeTextInputFocused == focused) {
_logTvTextInput('Host.setNativeTextInputFocused no-op focused=$focused');
@@ -667,7 +739,7 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
);
if (result != KeyEventResult.ignored) return result;
}
return widget.input._handleKey(context, node, event);
return widget.input._handleKey(context, node, event, _openTvKeyboard);
}
void _installKeyHandler(FocusNode node) {
@@ -707,8 +779,8 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
Widget build(BuildContext context) {
final focusNode = _effectiveFocusNode;
_installKeyHandler(focusNode);
_syncNativeTextInputFocus();
return widget.builder(widget.input._hasTvKeyboard, focusNode);
_handleFocusChanged();
return widget.builder(widget.input._hasTvKeyboard, focusNode, _openTvKeyboard);
}
}
@@ -756,7 +828,7 @@ class FocusableTextField extends _FocusableTextInputBase {
Widget build(BuildContext context) {
return buildFocusableInput(
context,
(usesTvKeyboard, effectiveFocusNode) => TextField(
(usesTvKeyboard, effectiveFocusNode, openKeyboard) => TextField(
controller: controller,
focusNode: effectiveFocusNode,
enabled: enabled,
@@ -780,7 +852,7 @@ class FocusableTextField extends _FocusableTextInputBase {
readOnly: usesTvKeyboard,
showCursor: usesTvKeyboard ? true : null,
enableInteractiveSelection: usesTvKeyboard ? false : enableInteractiveSelection,
onTap: usesTvKeyboard ? () => _showTvKeyboard(context) : null,
onTap: usesTvKeyboard ? openKeyboard : null,
),
);
}
@@ -831,7 +903,7 @@ class FocusableTextFormField extends _FocusableTextInputBase {
Widget build(BuildContext context) {
return buildFocusableInput(
context,
(usesTvKeyboard, effectiveFocusNode) => TextFormField(
(usesTvKeyboard, effectiveFocusNode, openKeyboard) => TextFormField(
controller: controller,
focusNode: effectiveFocusNode,
enabled: enabled,
@@ -858,7 +930,7 @@ class FocusableTextFormField extends _FocusableTextInputBase {
readOnly: usesTvKeyboard,
showCursor: usesTvKeyboard ? true : null,
enableInteractiveSelection: usesTvKeyboard ? false : enableInteractiveSelection,
onTap: usesTvKeyboard ? () => _showTvKeyboard(context) : null,
onTap: usesTvKeyboard ? openKeyboard : null,
),
);
}
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Genre",
"year": "År",
"contentRating": "Aldersvurdering",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Usete"
},
"sortLabels": {
"title": "Titel",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Genre",
"year": "Jahr",
"contentRating": "Altersfreigabe",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Ungesehene"
},
"sortLabels": {
"title": "Titel",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Genre",
"year": "Year",
"contentRating": "Content Rating",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Unwatched"
},
"sortLabels": {
"title": "Title",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Género",
"year": "Año",
"contentRating": "Clasificación",
"tag": "Etiqueta"
"tag": "Etiqueta",
"unwatched": "No vistos"
},
"sortLabels": {
"title": "Título",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Genre",
"year": "Année",
"contentRating": "Classification",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Non vus"
},
"sortLabels": {
"title": "Titre",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Genere",
"year": "Anno",
"contentRating": "Classificazione",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Non visti"
},
"sortLabels": {
"title": "Titolo",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "ジャンル",
"year": "年",
"contentRating": "視聴年齢区分",
"tag": "タグ"
"tag": "タグ",
"unwatched": "未視聴"
},
"sortLabels": {
"title": "タイトル",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "장르",
"year": "연도",
"contentRating": "시청 등급",
"tag": "태그"
"tag": "태그",
"unwatched": "미시청"
},
"sortLabels": {
"title": "제목",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Sjanger",
"year": "År",
"contentRating": "Aldersgrense",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Usette"
},
"sortLabels": {
"title": "Tittel",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Genre",
"year": "Jaar",
"contentRating": "Leeftijdsclassificatie",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Onbekeken"
},
"sortLabels": {
"title": "Titel",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Gatunek",
"year": "Rok",
"contentRating": "Klasyfikacja wiekowa",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Nieobejrzane"
},
"sortLabels": {
"title": "Tytuł",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Gênero",
"year": "Ano",
"contentRating": "Classificação",
"tag": "Tag"
"tag": "Tag",
"unwatched": "Não assistidos"
},
"sortLabels": {
"title": "Título",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Жанр",
"year": "Год",
"contentRating": "Возрастной рейтинг",
"tag": "Тег"
"tag": "Тег",
"unwatched": "Непросмотренные"
},
"sortLabels": {
"title": "Название",
+1 -1
View File
@@ -4,7 +4,7 @@
/// To regenerate, run: `dart run slang`
///
/// Locales: 15
/// Strings: 17565 (1171 per locale)
/// Strings: 17580 (1172 per locale)
// coverage:ignore-file
// ignore_for_file: type=lint, unused_import
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesDa extends TranslationsLibrariesFilt
@override String get year => 'År';
@override String get contentRating => 'Aldersvurdering';
@override String get tag => 'Tag';
@override String get unwatched => 'Usete';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsDa {
'libraries.filterCategories.year' => 'År',
'libraries.filterCategories.contentRating' => 'Aldersvurdering',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Usete',
'libraries.sortLabels.title' => 'Titel',
'libraries.sortLabels.dateAdded' => 'Tilføjet dato',
'libraries.sortLabels.releaseDate' => 'Udgivelsesdato',
@@ -2825,9 +2827,9 @@ extension on TranslationsDa {
'metadataEdit.summary' => 'Resumé',
'metadataEdit.poster' => 'Plakat',
'metadataEdit.background' => 'Baggrund',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Kvadratisk billede',
'metadataEdit.selectPoster' => 'Vælg plakat',
'metadataEdit.selectBackground' => 'Vælg baggrund',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesDe extends TranslationsLibrariesFilt
@override String get year => 'Jahr';
@override String get contentRating => 'Altersfreigabe';
@override String get tag => 'Tag';
@override String get unwatched => 'Ungesehene';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsDe {
'libraries.filterCategories.year' => 'Jahr',
'libraries.filterCategories.contentRating' => 'Altersfreigabe',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Ungesehene',
'libraries.sortLabels.title' => 'Titel',
'libraries.sortLabels.dateAdded' => 'Hinzugefügt am',
'libraries.sortLabels.releaseDate' => 'Erscheinungsdatum',
@@ -2825,9 +2827,9 @@ extension on TranslationsDe {
'metadataEdit.summary' => 'Zusammenfassung',
'metadataEdit.poster' => 'Poster',
'metadataEdit.background' => 'Hintergrund',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Quadratisches Bild',
'metadataEdit.selectPoster' => 'Poster auswählen',
'metadataEdit.selectBackground' => 'Hintergrund auswählen',
+5 -1
View File
@@ -3775,6 +3775,9 @@ class TranslationsLibrariesFilterCategoriesEn {
/// en: 'Tag'
String get tag => 'Tag';
/// en: 'Unwatched'
String get unwatched => 'Unwatched';
}
// Path: libraries.sortLabels
@@ -4801,6 +4804,7 @@ extension on Translations {
'libraries.filterCategories.year' => 'Year',
'libraries.filterCategories.contentRating' => 'Content Rating',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Unwatched',
'libraries.sortLabels.title' => 'Title',
'libraries.sortLabels.dateAdded' => 'Date Added',
'libraries.sortLabels.releaseDate' => 'Release Date',
@@ -5173,9 +5177,9 @@ extension on Translations {
'metadataEdit.summary' => 'Summary',
'metadataEdit.poster' => 'Poster',
'metadataEdit.background' => 'Background',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Square Art',
'metadataEdit.selectPoster' => 'Select Poster',
'metadataEdit.selectBackground' => 'Select Background',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesEs extends TranslationsLibrariesFilt
@override String get year => 'Año';
@override String get contentRating => 'Clasificación';
@override String get tag => 'Etiqueta';
@override String get unwatched => 'No vistos';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsEs {
'libraries.filterCategories.year' => 'Año',
'libraries.filterCategories.contentRating' => 'Clasificación',
'libraries.filterCategories.tag' => 'Etiqueta',
'libraries.filterCategories.unwatched' => 'No vistos',
'libraries.sortLabels.title' => 'Título',
'libraries.sortLabels.dateAdded' => 'Fecha de adición',
'libraries.sortLabels.releaseDate' => 'Fecha de estreno',
@@ -2825,9 +2827,9 @@ extension on TranslationsEs {
'metadataEdit.summary' => 'Resumen',
'metadataEdit.poster' => 'Póster',
'metadataEdit.background' => 'Fondo',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Imagen cuadrada',
'metadataEdit.selectPoster' => 'Seleccionar póster',
'metadataEdit.selectBackground' => 'Seleccionar fondo',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesFr extends TranslationsLibrariesFilt
@override String get year => 'Année';
@override String get contentRating => 'Classification';
@override String get tag => 'Tag';
@override String get unwatched => 'Non vus';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsFr {
'libraries.filterCategories.year' => 'Année',
'libraries.filterCategories.contentRating' => 'Classification',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Non vus',
'libraries.sortLabels.title' => 'Titre',
'libraries.sortLabels.dateAdded' => 'Date d\'ajout',
'libraries.sortLabels.releaseDate' => 'Date de sortie',
@@ -2825,9 +2827,9 @@ extension on TranslationsFr {
'metadataEdit.summary' => 'Résumé',
'metadataEdit.poster' => 'Affiche',
'metadataEdit.background' => 'Arrière-plan',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Image carrée',
'metadataEdit.selectPoster' => 'Sélectionner l\'affiche',
'metadataEdit.selectBackground' => 'Sélectionner l\'arrière-plan',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesIt extends TranslationsLibrariesFilt
@override String get year => 'Anno';
@override String get contentRating => 'Classificazione';
@override String get tag => 'Tag';
@override String get unwatched => 'Non visti';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsIt {
'libraries.filterCategories.year' => 'Anno',
'libraries.filterCategories.contentRating' => 'Classificazione',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Non visti',
'libraries.sortLabels.title' => 'Titolo',
'libraries.sortLabels.dateAdded' => 'Data di aggiunta',
'libraries.sortLabels.releaseDate' => 'Data di uscita',
@@ -2825,9 +2827,9 @@ extension on TranslationsIt {
'metadataEdit.summary' => 'Trama',
'metadataEdit.poster' => 'Poster',
'metadataEdit.background' => 'Sfondo',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Immagine quadrata',
'metadataEdit.selectPoster' => 'Seleziona poster',
'metadataEdit.selectBackground' => 'Seleziona sfondo',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesJa extends TranslationsLibrariesFilt
@override String get year => '年';
@override String get contentRating => '視聴年齢区分';
@override String get tag => 'タグ';
@override String get unwatched => '未視聴';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsJa {
'libraries.filterCategories.year' => '年',
'libraries.filterCategories.contentRating' => '視聴年齢区分',
'libraries.filterCategories.tag' => 'タグ',
'libraries.filterCategories.unwatched' => '未視聴',
'libraries.sortLabels.title' => 'タイトル',
'libraries.sortLabels.dateAdded' => '追加日',
'libraries.sortLabels.releaseDate' => 'リリース日',
@@ -2825,9 +2827,9 @@ extension on TranslationsJa {
'metadataEdit.summary' => 'あらすじ',
'metadataEdit.poster' => 'ポスター',
'metadataEdit.background' => '背景',
'metadataEdit.logo' => 'ロゴ',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'ロゴ',
'metadataEdit.squareArt' => '正方形アート',
'metadataEdit.selectPoster' => 'ポスターを選択',
'metadataEdit.selectBackground' => '背景を選択',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesKo extends TranslationsLibrariesFilt
@override String get year => '연도';
@override String get contentRating => '시청 등급';
@override String get tag => '태그';
@override String get unwatched => '미시청';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsKo {
'libraries.filterCategories.year' => '연도',
'libraries.filterCategories.contentRating' => '시청 등급',
'libraries.filterCategories.tag' => '태그',
'libraries.filterCategories.unwatched' => '미시청',
'libraries.sortLabels.title' => '제목',
'libraries.sortLabels.dateAdded' => '추가된 날짜',
'libraries.sortLabels.releaseDate' => '출시일',
@@ -2825,9 +2827,9 @@ extension on TranslationsKo {
'metadataEdit.summary' => '줄거리',
'metadataEdit.poster' => '포스터',
'metadataEdit.background' => '배경',
'metadataEdit.logo' => '로고',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => '로고',
'metadataEdit.squareArt' => '정사각형 아트',
'metadataEdit.selectPoster' => '포스터 선택',
'metadataEdit.selectBackground' => '배경 선택',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesNb extends TranslationsLibrariesFilt
@override String get year => 'År';
@override String get contentRating => 'Aldersgrense';
@override String get tag => 'Tag';
@override String get unwatched => 'Usette';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsNb {
'libraries.filterCategories.year' => 'År',
'libraries.filterCategories.contentRating' => 'Aldersgrense',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Usette',
'libraries.sortLabels.title' => 'Tittel',
'libraries.sortLabels.dateAdded' => 'Lagt til-dato',
'libraries.sortLabels.releaseDate' => 'Utgivelsesdato',
@@ -2825,9 +2827,9 @@ extension on TranslationsNb {
'metadataEdit.summary' => 'Sammendrag',
'metadataEdit.poster' => 'Plakat',
'metadataEdit.background' => 'Bakgrunn',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Kvadratisk bilde',
'metadataEdit.selectPoster' => 'Velg plakat',
'metadataEdit.selectBackground' => 'Velg bakgrunn',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesNl extends TranslationsLibrariesFilt
@override String get year => 'Jaar';
@override String get contentRating => 'Leeftijdsclassificatie';
@override String get tag => 'Tag';
@override String get unwatched => 'Onbekeken';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsNl {
'libraries.filterCategories.year' => 'Jaar',
'libraries.filterCategories.contentRating' => 'Leeftijdsclassificatie',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Onbekeken',
'libraries.sortLabels.title' => 'Titel',
'libraries.sortLabels.dateAdded' => 'Toegevoegd op',
'libraries.sortLabels.releaseDate' => 'Uitgavedatum',
@@ -2825,9 +2827,9 @@ extension on TranslationsNl {
'metadataEdit.summary' => 'Samenvatting',
'metadataEdit.poster' => 'Poster',
'metadataEdit.background' => 'Achtergrond',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Vierkante afbeelding',
'metadataEdit.selectPoster' => 'Poster selecteren',
'metadataEdit.selectBackground' => 'Achtergrond selecteren',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesPl extends TranslationsLibrariesFilt
@override String get year => 'Rok';
@override String get contentRating => 'Klasyfikacja wiekowa';
@override String get tag => 'Tag';
@override String get unwatched => 'Nieobejrzane';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsPl {
'libraries.filterCategories.year' => 'Rok',
'libraries.filterCategories.contentRating' => 'Klasyfikacja wiekowa',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Nieobejrzane',
'libraries.sortLabels.title' => 'Tytuł',
'libraries.sortLabels.dateAdded' => 'Data dodania',
'libraries.sortLabels.releaseDate' => 'Data premiery',
@@ -2825,9 +2827,9 @@ extension on TranslationsPl {
'metadataEdit.summary' => 'Opis',
'metadataEdit.poster' => 'Plakat',
'metadataEdit.background' => 'Tło',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Kwadratowy obraz',
'metadataEdit.selectPoster' => 'Wybierz plakat',
'metadataEdit.selectBackground' => 'Wybierz tło',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesPt extends TranslationsLibrariesFilt
@override String get year => 'Ano';
@override String get contentRating => 'Classificação';
@override String get tag => 'Tag';
@override String get unwatched => 'Não assistidos';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsPt {
'libraries.filterCategories.year' => 'Ano',
'libraries.filterCategories.contentRating' => 'Classificação',
'libraries.filterCategories.tag' => 'Tag',
'libraries.filterCategories.unwatched' => 'Não assistidos',
'libraries.sortLabels.title' => 'Título',
'libraries.sortLabels.dateAdded' => 'Data de adição',
'libraries.sortLabels.releaseDate' => 'Data de lançamento',
@@ -2825,9 +2827,9 @@ extension on TranslationsPt {
'metadataEdit.summary' => 'Sinopse',
'metadataEdit.poster' => 'Poster',
'metadataEdit.background' => 'Plano de Fundo',
'metadataEdit.logo' => 'Logo',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logo',
'metadataEdit.squareArt' => 'Imagem Quadrada',
'metadataEdit.selectPoster' => 'Selecionar Poster',
'metadataEdit.selectBackground' => 'Selecionar Plano de Fundo',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesRu extends TranslationsLibrariesFilt
@override String get year => 'Год';
@override String get contentRating => 'Возрастной рейтинг';
@override String get tag => 'Тег';
@override String get unwatched => 'Непросмотренные';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsRu {
'libraries.filterCategories.year' => 'Год',
'libraries.filterCategories.contentRating' => 'Возрастной рейтинг',
'libraries.filterCategories.tag' => 'Тег',
'libraries.filterCategories.unwatched' => 'Непросмотренные',
'libraries.sortLabels.title' => 'Название',
'libraries.sortLabels.dateAdded' => 'Дата добавления',
'libraries.sortLabels.releaseDate' => 'Дата выхода',
@@ -2825,9 +2827,9 @@ extension on TranslationsRu {
'metadataEdit.summary' => 'Описание',
'metadataEdit.poster' => 'Постер',
'metadataEdit.background' => 'Фон',
'metadataEdit.logo' => 'Логотип',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Логотип',
'metadataEdit.squareArt' => 'Квадратное изображение',
'metadataEdit.selectPoster' => 'Выбрать постер',
'metadataEdit.selectBackground' => 'Выбрать фон',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesSv extends TranslationsLibrariesFilt
@override String get year => 'År';
@override String get contentRating => 'Åldersgräns';
@override String get tag => 'Tagg';
@override String get unwatched => 'Osedda';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsSv {
'libraries.filterCategories.year' => 'År',
'libraries.filterCategories.contentRating' => 'Åldersgräns',
'libraries.filterCategories.tag' => 'Tagg',
'libraries.filterCategories.unwatched' => 'Osedda',
'libraries.sortLabels.title' => 'Titel',
'libraries.sortLabels.dateAdded' => 'Tillagd',
'libraries.sortLabels.releaseDate' => 'Releasedatum',
@@ -2825,9 +2827,9 @@ extension on TranslationsSv {
'metadataEdit.summary' => 'Sammanfattning',
'metadataEdit.poster' => 'Poster',
'metadataEdit.background' => 'Bakgrund',
'metadataEdit.logo' => 'Logotyp',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => 'Logotyp',
'metadataEdit.squareArt' => 'Kvadratisk bild',
'metadataEdit.selectPoster' => 'Välj poster',
'metadataEdit.selectBackground' => 'Välj bakgrund',
+3 -1
View File
@@ -1621,6 +1621,7 @@ class _TranslationsLibrariesFilterCategoriesZh extends TranslationsLibrariesFilt
@override String get year => '年份';
@override String get contentRating => '内容分级';
@override String get tag => '标签';
@override String get unwatched => '未观看';
}
// Path: libraries.sortLabels
@@ -2453,6 +2454,7 @@ extension on TranslationsZh {
'libraries.filterCategories.year' => '年份',
'libraries.filterCategories.contentRating' => '内容分级',
'libraries.filterCategories.tag' => '标签',
'libraries.filterCategories.unwatched' => '未观看',
'libraries.sortLabels.title' => '标题',
'libraries.sortLabels.dateAdded' => '添加日期',
'libraries.sortLabels.releaseDate' => '发行日期',
@@ -2825,9 +2827,9 @@ extension on TranslationsZh {
'metadataEdit.summary' => '简介',
'metadataEdit.poster' => '海报',
'metadataEdit.background' => '背景',
'metadataEdit.logo' => '标志',
_ => null,
} ?? switch (path) {
'metadataEdit.logo' => '标志',
'metadataEdit.squareArt' => '方形图片',
'metadataEdit.selectPoster' => '选择海报',
'metadataEdit.selectBackground' => '选择背景',
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "Genre",
"year": "År",
"contentRating": "Åldersgräns",
"tag": "Tagg"
"tag": "Tagg",
"unwatched": "Osedda"
},
"sortLabels": {
"title": "Titel",
+2 -1
View File
@@ -705,7 +705,8 @@
"genre": "类型",
"year": "年份",
"contentRating": "内容分级",
"tag": "标签"
"tag": "标签",
"unwatched": "未观看"
},
"sortLabels": {
"title": "标题",
+6 -1
View File
@@ -465,7 +465,12 @@ sealed class MediaItem with _$MediaItem {
/// Returns hero art candidates in display-preference order.
List<String> heroArtCandidates({required double containerAspectRatio}) {
final preferred = containerAspectRatio < 1.39 ? [backgroundSquarePath, artPath] : [artPath, backgroundSquarePath];
final preferred = switch (kind) {
MediaKind.episode when containerAspectRatio < 1.39 => [backgroundSquarePath, grandparentArtPath, artPath],
MediaKind.episode => [grandparentArtPath, artPath, backgroundSquarePath],
_ when containerAspectRatio < 1.39 => [backgroundSquarePath, artPath],
_ => [artPath, backgroundSquarePath],
};
final candidates = <String>[];
for (final path in preferred) {
+1 -1
View File
@@ -55,7 +55,7 @@ enum MediaKind {
'track' || 'audio' => MediaKind.track,
'collection' || 'boxset' => MediaKind.collection,
'playlist' => MediaKind.playlist,
'clip' || 'trailer' => MediaKind.clip,
'clip' || 'trailer' || 'video' || 'musicvideo' => MediaKind.clip,
'photo' => MediaKind.photo,
_ => MediaKind.unknown,
};
+5 -1
View File
@@ -135,6 +135,7 @@ class MediaSubtitleTrack with _TrackLabelMixin {
final bool forced;
final String? key;
final bool external;
final bool usesExternalDelivery;
MediaSubtitleTrack({
required this.id,
@@ -148,6 +149,7 @@ class MediaSubtitleTrack with _TrackLabelMixin {
required this.forced,
this.key,
this.external = false,
this.usesExternalDelivery = false,
});
String get label {
@@ -178,7 +180,9 @@ class MediaSubtitleTrack with _TrackLabelMixin {
/// Returns true if this subtitle track is an external file (sidecar subtitle).
/// Some backends provide a direct key/URL, others require constructing one
/// from stream metadata.
bool get isExternal => external || (key != null && key!.isNotEmpty);
bool get isExternalFile => external;
bool get isExternal => external || usesExternalDelivery || (key != null && key!.isNotEmpty);
}
class MediaChapter {
+3 -4
View File
@@ -23,10 +23,9 @@ class MediaStream {
// Subtitle
final bool forced;
/// Backend-resolved location for sidecar subtitle download. For Plex this
/// is the Plex-specific `/library/streams/{id}` path; for Jellyfin this is
/// the `DeliveryUrl` returned by `/Items/{id}/PlaybackInfo`. Null for
/// embedded streams.
/// Backend-resolved location for true sidecar subtitle download. Null for
/// embedded streams, even when Jellyfin can expose them through temporary
/// external delivery URLs during playback negotiation.
final String? sidecarPath;
const MediaStream({
+4 -3
View File
@@ -102,9 +102,9 @@ class ServerCapabilities {
/// gates whether the player attempts the load at all.
final bool scrubThumbnails;
/// Library section exposes a folder hierarchy (Plex
/// `/library/sections/{id}/folders`). Jellyfin has no equivalent endpoint,
/// so the "Folders" grouping option is hidden when this is false.
/// Library section exposes a folder hierarchy. Plex uses
/// `/library/sections/{id}/folders`; Jellyfin uses direct-child
/// `/Items?ParentId=...&Recursive=false` queries.
final bool folderGrouping;
const ServerCapabilities({
@@ -179,6 +179,7 @@ class ServerCapabilities {
richMetadataEdit: false,
alphaBar: AlphaBarMode.nameStartsWithFilter,
scrubThumbnails: true,
folderGrouping: true,
);
ServerCapabilities copyWith({
+2 -1
View File
@@ -1006,7 +1006,8 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
final existing = _downloads[globalKey]!;
if (existing.status == DownloadStatus.downloading ||
existing.status == DownloadStatus.completed ||
existing.status == DownloadStatus.queued) {
existing.status == DownloadStatus.queued ||
existing.status == DownloadStatus.paused) {
final claimed = await _claimDownloadForActiveProfile(globalKey);
if (claimed) safeNotifyListeners();
return claimed;
+20 -21
View File
@@ -1217,15 +1217,18 @@ class _DiscoverScreenState extends State<DiscoverScreen>
Widget _buildOverlaidAppBar() {
final statusBarHeight = MediaQuery.paddingOf(context).top;
final colorScheme = Theme.of(context).colorScheme;
final overlayColor = colorScheme.brightness == Brightness.dark ? Colors.black : colorScheme.surface;
final foregroundColor = colorScheme.onSurface;
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black.withValues(alpha: 0.7),
Colors.black.withValues(alpha: 0.5),
Colors.black.withValues(alpha: 0.3),
overlayColor.withValues(alpha: 0.7),
overlayColor.withValues(alpha: 0.5),
overlayColor.withValues(alpha: 0.3),
Colors.transparent,
],
stops: const [0.0, 0.3, 0.6, 1.0],
@@ -1242,20 +1245,23 @@ class _DiscoverScreenState extends State<DiscoverScreen>
t.discover.title,
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(color: Colors.white, fontWeight: FontWeight.bold),
).textTheme.titleLarge?.copyWith(color: foregroundColor, fontWeight: FontWeight.bold),
),
const Spacer(),
Consumer2<WatchTogetherProvider, CompanionRemoteProvider>(
builder: (context, watchTogether, companionRemote, _) {
final isDesktop = PlatformDetector.shouldActAsRemoteHost(context);
final colorScheme = Theme.of(context).colorScheme;
return FocusableActionBar(
key: _actionBarKey,
onNavigateLeft: _navigateToSidebar,
onNavigateDown: _focusContentFromAppBar,
actions: [
FocusableAction(icon: Symbols.refresh_rounded, iconColor: Colors.white, onPressed: _loadContent),
FocusableAction(
icon: Symbols.refresh_rounded,
iconColor: foregroundColor,
onPressed: _loadContent,
),
// Watch Together
FocusableAction(
onPressed: () =>
@@ -1266,7 +1272,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
icon: AppIcon(
Symbols.group_rounded,
fill: watchTogether.isInSession ? 1 : 0,
color: watchTogether.isInSession ? colorScheme.primary : Colors.white,
color: watchTogether.isInSession ? colorScheme.primary : foregroundColor,
),
onPressed: () => Navigator.push(
context,
@@ -1315,7 +1321,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
icon: AppIcon(
Symbols.phone_android_rounded,
fill: companionRemote.isConnected ? 1 : 0,
color: companionRemote.isConnected ? colorScheme.primary : Colors.white,
color: companionRemote.isConnected ? colorScheme.primary : foregroundColor,
),
onPressed: () {
if (isDesktop) {
@@ -1336,10 +1342,10 @@ class _DiscoverScreenState extends State<DiscoverScreen>
child: Container(
width: 8,
height: 8,
decoration: const BoxDecoration(
decoration: BoxDecoration(
color: Colors.green,
shape: BoxShape.circle,
border: Border.fromBorderSide(BorderSide(color: Colors.white, width: 1)),
border: Border.fromBorderSide(BorderSide(color: foregroundColor, width: 1)),
),
),
),
@@ -1995,7 +2001,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
if (heroItem.year != null) heroItem.year.toString(),
].join(' • '),
style: TextStyle(
color: Colors.white,
color: colorScheme.onSurface,
fontSize: isTv ? 18 : 14,
fontWeight: FontWeight.w600,
),
@@ -2015,9 +2021,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
textAlign: alignLeft ? TextAlign.left : TextAlign.center,
text: TextSpan(
style: TextStyle(
color: alignLeft
? Colors.white.withValues(alpha: 0.7)
: colorScheme.onSurface.withValues(alpha: 0.7),
color: colorScheme.onSurface.withValues(alpha: 0.7),
fontSize: isTv ? 18 : 14,
height: isTv ? 1.45 : 1.4,
),
@@ -2025,10 +2029,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
if (isEpisode && heroItem.parentIndex != null && heroItem.index != null)
TextSpan(
text: 'S${heroItem.parentIndex}, E${heroItem.index}: ',
style: TextStyle(
fontWeight: FontWeight.bold,
color: alignLeft ? Colors.white : colorScheme.onSurface,
),
style: TextStyle(fontWeight: FontWeight.bold, color: colorScheme.onSurface),
),
TextSpan(
text: heroItem.summary?.isNotEmpty == true
@@ -2049,9 +2050,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
overflow: TextOverflow.ellipsis,
textAlign: alignLeft ? TextAlign.left : TextAlign.center,
style: TextStyle(
color: alignLeft
? Colors.white.withValues(alpha: 0.7)
: colorScheme.onSurface.withValues(alpha: 0.7),
color: colorScheme.onSurface.withValues(alpha: 0.7),
fontSize: isTv ? 18 : 14,
height: isTv ? 1.45 : 1.4,
),
+18 -9
View File
@@ -12,8 +12,8 @@ import 'alpha_jump_helper.dart';
///
/// Pre-computes a cumulative index map from [firstCharacters] data so that
/// tapping a letter triggers [onJump] with the item index where that letter
/// begins. When more letters exist than fit vertically, the bar keeps the
/// highest-count letters (by item size) and drops the rest.
/// begins. Alphabet-sized lists stay complete and compact vertically when
/// needed; larger character sets are thinned to the highest-count letters.
/// Supports both touch (tap/drag) and D-pad (up/down/select) input.
class AlphaJumpBar extends StatefulWidget {
final List<LibraryFirstCharacter> firstCharacters;
@@ -63,6 +63,10 @@ class _AlphaJumpBarState extends State<AlphaJumpBar> {
/// Minimum vertical space per letter slot.
static const double _minLetterHeight = 20.0;
/// Keep canonical alphabet bars complete instead of hiding trailing letters
/// on shorter TV viewports.
static const int _maxCompactLetterCount = 27;
@override
void initState() {
super.initState();
@@ -100,7 +104,9 @@ class _AlphaJumpBarState extends State<AlphaJumpBar> {
final maxLetters = (availableHeight / _minLetterHeight).floor();
if (maxLetters == _lastMaxLetters) return;
_lastMaxLetters = maxLetters;
_displayed = _helper.displayLetters(maxLetters);
_displayed = _helper.letters.length <= _maxCompactLetterCount
? _helper.letters
: _helper.displayLetters(maxLetters);
_clampHighlight();
}
@@ -209,6 +215,9 @@ class _AlphaJumpBarState extends State<AlphaJumpBar> {
if (_displayed.isEmpty) return const SizedBox.shrink();
final currentLetter = _nearestDisplayed(widget.currentLetter);
final letterSlotHeight = constraints.maxHeight / _displayed.length;
final markerSize = (letterSlotHeight - 2).clamp(10.0, 18.0).toDouble();
final fontSize = (letterSlotHeight * 0.58).clamp(7.0, 10.0).toDouble();
return ClickableCursor(
child: GestureDetector(
@@ -226,10 +235,10 @@ class _AlphaJumpBarState extends State<AlphaJumpBar> {
}
},
child: Container(
width: 28,
width: 20,
decoration: BoxDecoration(
color: colorScheme.surface.withValues(alpha: 0.7),
borderRadius: const BorderRadius.all(Radius.circular(14)),
borderRadius: const BorderRadius.all(Radius.circular(10)),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
@@ -258,17 +267,17 @@ class _AlphaJumpBarState extends State<AlphaJumpBar> {
}
return SizedBox(
height: constraints.maxHeight / _displayed.length,
height: letterSlotHeight,
child: Center(
child: Container(
width: 22,
height: 22,
width: markerSize,
height: markerSize,
decoration: decoration,
alignment: Alignment.center,
child: Text(
letter,
style: TextStyle(
fontSize: 10,
fontSize: fontSize,
fontWeight: (isCurrent || isHighlighted) ? FontWeight.bold : FontWeight.normal,
color: letterColor,
),
+27 -14
View File
@@ -65,6 +65,18 @@ class FolderTreeItem extends StatelessWidget {
};
}
String _rowTitle() {
final title = item.title?.trim();
if (title != null && title.isNotEmpty) return title;
return item.displayTitle;
}
String? _dedupeSubtitle(String? subtitle) {
final value = subtitle?.trim();
if (value == null || value.isEmpty || value == _rowTitle()) return null;
return value;
}
void _handleTap() {
if (isFolder) {
onExpand?.call();
@@ -79,15 +91,12 @@ class FolderTreeItem extends StatelessWidget {
if (item.parentIndex != null && item.index != null) {
parts.add('S${item.parentIndex} E${item.index}');
}
if (item.title != null && item.title!.isNotEmpty) {
parts.add(item.title!);
}
return parts.isNotEmpty ? parts.join(' · ') : null;
return parts.isNotEmpty ? parts.join(' · ') : _dedupeSubtitle(item.displaySubtitle);
}
if (item.isSeason) {
return item.displaySubtitle;
return _dedupeSubtitle(item.displaySubtitle);
}
return item.displaySubtitle;
return _dedupeSubtitle(item.displaySubtitle);
}
String _buildMetadataLine() {
@@ -126,7 +135,7 @@ class FolderTreeItem extends StatelessWidget {
const SizedBox(width: 12),
Expanded(
child: Text(
item.displayTitle,
_rowTitle(),
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -181,7 +190,7 @@ class FolderTreeItem extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
Text(
item.displayTitle,
_rowTitle(),
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500, height: 1.2),
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -336,6 +345,8 @@ class FolderTreeItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
final playAll = onPlayAll;
final shuffle = onShuffle;
final rowContent = isFolder
? _buildFolderRow(context)
: SettingsBuilder(
@@ -362,13 +373,13 @@ class FolderTreeItem extends StatelessWidget {
),
),
// Play/Shuffle buttons for folders
if (isFolder) ...[
// Play/Shuffle buttons for folders when the backend supports them.
if (isFolder && playAll != null) ...[
FocusableButton(
useBackgroundFocus: true,
onPressed: onPlayAll,
onPressed: playAll,
child: IconButton(
onPressed: onPlayAll,
onPressed: playAll,
icon: AppIcon(
Symbols.play_arrow_rounded,
fill: 1,
@@ -382,11 +393,13 @@ class FolderTreeItem extends StatelessWidget {
visualDensity: VisualDensity.compact,
),
),
],
if (isFolder && shuffle != null) ...[
FocusableButton(
useBackgroundFocus: true,
onPressed: onShuffle,
onPressed: shuffle,
child: IconButton(
onPressed: onShuffle,
onPressed: shuffle,
icon: AppIcon(
Symbols.shuffle_rounded,
fill: 1,
+106 -42
View File
@@ -1,8 +1,13 @@
import 'package:flutter/material.dart';
import 'package:material_symbols_icons/symbols.dart';
import '../../media/media_backend.dart';
import '../../media/media_item.dart';
import '../../media/media_kind.dart';
import '../../media/media_server_client.dart';
import '../../services/jellyfin_client.dart';
import '../../services/jellyfin_sequential_launcher.dart';
import '../../services/play_queue_launcher.dart';
import '../../services/plex_client.dart';
import '../../utils/app_logger.dart';
import '../../utils/error_message_utils.dart';
import '../../utils/media_navigation_helper.dart';
@@ -17,6 +22,7 @@ import 'state_messages.dart';
class FolderTreeView extends StatefulWidget {
final String libraryKey;
final String? serverId; // Server this library belongs to
final MediaKind? libraryKind;
final void Function(String)? onRefresh;
final FocusNode? firstItemFocusNode;
final VoidCallback? onNavigateUp;
@@ -25,6 +31,7 @@ class FolderTreeView extends StatefulWidget {
super.key,
required this.libraryKey,
this.serverId,
this.libraryKind,
this.onRefresh,
this.firstItemFocusNode,
this.onNavigateUp,
@@ -39,10 +46,9 @@ class FolderTreeViewState extends State<FolderTreeView> {
/// Reload the root folders. Exposed for parent-driven pull-to-refresh.
Future<void> refresh() => _loadRootFolders();
/// Folders/items returned by the Plex `/library/sections/{id}/folder`
/// endpoint, mapped to neutral [MediaItem]s. The Plex `key` (folder URL)
/// survives in [MediaItem.raw] under the `'key'` slot — see
/// [_folderKey].
/// Folders/items returned by the backend's folder API and mapped to neutral
/// [MediaItem]s. Plex folder URLs survive in [MediaItem.raw]['key'];
/// Jellyfin folders use the item id as their recursive parent id.
List<MediaItem> _rootFolders = [];
final Map<String, List<MediaItem>> _childrenCache = {};
final Set<String> _expandedFolders = {};
@@ -51,11 +57,18 @@ class FolderTreeViewState extends State<FolderTreeView> {
String? _errorMessage;
/// Resolve the Plex folder key from a [MediaItem]'s `raw` map. The key is
/// a relative URL (e.g. `/library/sections/1/folder?parent=...`) used as
/// the cache key and to recursively fetch children from
/// [PlexClient.getFolderChildren].
/// a relative URL (e.g. `/library/sections/1/folder?parent=...`) used to
/// recursively fetch children from [PlexClient.fetchFolderChildren].
String? _folderKey(MediaItem item) => item.raw?['key'] as String?;
String? _itemType(MediaItem item) => (item.raw?['Type'] as String? ?? item.raw?['type'] as String?)?.toLowerCase();
String? _folderIdentity(MediaItem item) {
if (item.backend == MediaBackend.plex) return _folderKey(item);
if (_isFolder(item)) return item.id;
return null;
}
@override
void initState() {
super.initState();
@@ -69,11 +82,8 @@ class FolderTreeViewState extends State<FolderTreeView> {
});
try {
final client = context.getPlexClientForServer(widget.serverId!);
// PlexClient.fetchLibraryFolders returns neutral [MediaItem]s; folders
// come back already tagged with the client's serverId/serverName.
final folders = await client.fetchLibraryFolders(widget.libraryKey);
final client = context.getMediaClientForServer(widget.serverId!);
final folders = await _fetchRootFolders(client);
if (!mounted) return;
@@ -94,40 +104,34 @@ class FolderTreeViewState extends State<FolderTreeView> {
}
Future<void> _loadFolderChildren(MediaItem folder) async {
final folderKey = _folderKey(folder);
if (folderKey == null) return;
final folderIdentity = _folderIdentity(folder);
if (folderIdentity == null) return;
// Already loading this folder
if (_loadingFolders.contains(folderKey)) return;
if (_loadingFolders.contains(folderIdentity)) return;
// Already loaded and cached
if (_childrenCache.containsKey(folderKey)) {
if (_childrenCache.containsKey(folderIdentity)) {
setState(() {
_expandedFolders.add(folderKey);
_expandedFolders.add(folderIdentity);
});
return;
}
setState(() {
_loadingFolders.add(folderKey);
_loadingFolders.add(folderIdentity);
});
try {
final client = context.getPlexClientForServer(widget.serverId!);
// Items are automatically tagged with server info by PlexClient.
final children = await client.fetchFolderChildren(
folderKey,
libraryId: folder.libraryId,
libraryTitle: folder.libraryTitle,
);
final client = context.getMediaClientForServer(widget.serverId!);
final children = await _fetchFolderChildren(client, folder);
if (!mounted) return;
setState(() {
_childrenCache[folderKey] = children;
_expandedFolders.add(folderKey);
_loadingFolders.remove(folderKey);
_childrenCache[folderIdentity] = children;
_expandedFolders.add(folderIdentity);
_loadingFolders.remove(folderIdentity);
});
appLogger.d('Loaded ${children.length} children for folder: ${folder.title}');
@@ -136,7 +140,7 @@ class FolderTreeViewState extends State<FolderTreeView> {
final message = mapUnexpectedErrorToMessage(e, context: t.libraries.folders);
setState(() {
_loadingFolders.remove(folderKey);
_loadingFolders.remove(folderIdentity);
});
if (mounted) {
@@ -146,11 +150,11 @@ class FolderTreeViewState extends State<FolderTreeView> {
}
void _toggleFolder(MediaItem folder) {
final folderKey = _folderKey(folder);
if (folderKey == null) return;
if (_expandedFolders.contains(folderKey)) {
final folderIdentity = _folderIdentity(folder);
if (folderIdentity == null) return;
if (_expandedFolders.contains(folderIdentity)) {
setState(() {
_expandedFolders.remove(folderKey);
_expandedFolders.remove(folderIdentity);
});
} else {
_loadFolderChildren(folder);
@@ -158,10 +162,26 @@ class FolderTreeViewState extends State<FolderTreeView> {
}
Future<void> _handleItemTap(MediaItem item) async {
await navigateToMediaItem(context, item, onRefresh: widget.onRefresh);
final result = await navigateToMediaItem(context, item, onRefresh: widget.onRefresh);
if (!context.mounted) return;
switch (result) {
case MediaNavigationResult.unsupported:
showAppSnackBar(context, t.messages.musicNotSupported);
case MediaNavigationResult.listRefreshNeeded:
widget.onRefresh?.call(item.id);
case MediaNavigationResult.navigated:
case MediaNavigationResult.librarySelected:
break;
}
}
Future<void> _handleFolderPlay(MediaItem folder) async {
if (folder.backend == MediaBackend.jellyfin) {
final launcher = JellyfinSequentialLauncher(context: context);
await launcher.launchFromFolder(folder: folder, shuffle: false);
return;
}
final folderKey = _folderKey(folder);
if (folderKey == null) return;
final client = context.getPlexClientForServer(widget.serverId!);
@@ -175,6 +195,12 @@ class FolderTreeViewState extends State<FolderTreeView> {
}
Future<void> _handleFolderShuffle(MediaItem folder) async {
if (folder.backend == MediaBackend.jellyfin) {
final launcher = JellyfinSequentialLauncher(context: context);
await launcher.launchFromFolder(folder: folder, shuffle: true);
return;
}
final folderKey = _folderKey(folder);
if (folderKey == null) return;
final client = context.getPlexClientForServer(widget.serverId!);
@@ -188,10 +214,47 @@ class FolderTreeViewState extends State<FolderTreeView> {
}
bool _isFolder(MediaItem item) {
// Folders typically have no media kind (Plex returns `type: 'folder'`,
// mapped to [MediaKind.unknown]) or expose `/folder` in their key.
if (item.backend == MediaBackend.jellyfin) {
return _isJellyfinFilesystemFolder(item) || _isJellyfinMediaContainer(item);
}
// Plex folders typically have no media kind (mapped to [MediaKind.unknown])
// or expose `/folder` in their key.
final folderKey = _folderKey(item);
return folderKey?.contains('/folder') == true || item.kind == MediaKind.unknown;
final type = _itemType(item);
return folderKey?.contains('/folder') == true || type == 'folder' || item.kind == MediaKind.unknown;
}
bool _isJellyfinFilesystemFolder(MediaItem item) {
final type = _itemType(item);
return type == 'folder' || type == 'collectionfolder' || (type == null && item.raw?['IsFolder'] == true);
}
bool _isJellyfinMediaContainer(MediaItem item) => item.kind == MediaKind.show || item.kind == MediaKind.season;
bool _canPlayFolder(MediaItem item) {
if (item.backend == MediaBackend.plex) return true;
if (item.backend == MediaBackend.jellyfin) return widget.libraryKind?.isMusic != true;
return false;
}
Future<List<MediaItem>> _fetchRootFolders(MediaServerClient client) {
if (client is PlexClient) return client.fetchLibraryFolders(widget.libraryKey);
if (client is JellyfinClient) return client.fetchLibraryFolders(widget.libraryKey);
throw UnsupportedError('Folder browsing is not supported for ${client.backend.id}');
}
Future<List<MediaItem>> _fetchFolderChildren(MediaServerClient client, MediaItem folder) {
if (client is PlexClient) {
final folderKey = _folderKey(folder);
if (folderKey == null) return Future.value(const <MediaItem>[]);
return client.fetchFolderChildren(folderKey, libraryId: folder.libraryId, libraryTitle: folder.libraryTitle);
}
if (client is JellyfinClient) {
if (_isJellyfinMediaContainer(folder)) return client.fetchChildren(folder.id);
return client.fetchFolderChildren(folder.id);
}
throw UnsupportedError('Folder browsing is not supported for ${client.backend.id}');
}
/// Flatten the visible tree into a list of (item, depth, path) tuples so
@@ -207,7 +270,7 @@ class FolderTreeViewState extends State<FolderTreeView> {
final itemPath = parentPath.isEmpty ? '$i' : '$parentPath-$i';
out.add((item: item, depth: depth, path: itemPath));
final folderKey = _folderKey(item);
final folderKey = _folderIdentity(item);
if (_isFolder(item) &&
folderKey != null &&
_expandedFolders.contains(folderKey) &&
@@ -253,10 +316,11 @@ class FolderTreeViewState extends State<FolderTreeView> {
final entry = flattened[index];
final item = entry.item;
final isFolder = _isFolder(item);
final folderKey = _folderKey(item);
final folderKey = _folderIdentity(item);
final isExpanded = folderKey != null && _expandedFolders.contains(folderKey);
final isLoading = folderKey != null && _loadingFolders.contains(folderKey);
final isFirstRootItem = index == 0;
final canPlayFolder = isFolder && _canPlayFolder(item);
return FolderTreeItem(
key: ValueKey(entry.path),
@@ -268,8 +332,8 @@ class FolderTreeViewState extends State<FolderTreeView> {
serverId: widget.serverId,
onExpand: isFolder ? () => _toggleFolder(item) : null,
onTap: !isFolder ? () => _handleItemTap(item) : null,
onPlayAll: isFolder ? () => _handleFolderPlay(item) : null,
onShuffle: isFolder ? () => _handleFolderShuffle(item) : null,
onPlayAll: canPlayFolder ? () => _handleFolderPlay(item) : null,
onShuffle: canPlayFolder ? () => _handleFolderShuffle(item) : null,
focusNode: isFirstRootItem ? widget.firstItemFocusNode : null,
onNavigateUp: isFirstRootItem ? widget.onNavigateUp : null,
);
@@ -689,10 +689,8 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<MediaItem, LibraryBrows
List<String> _getGroupingOptions() {
final type = widget.library.kind.id.toLowerCase();
// Folder browsing relies on a section folder API
// (Plex `/library/sections/{id}/folders`); gated by capability so any
// future backend that exposes the same can opt in without touching
// this method.
// Folder browsing is gated by backend capability: Plex uses its section
// folder API, while Jellyfin uses direct non-recursive Items queries.
final canFolder = context.tryGetMediaClientForServer(widget.library.serverId)?.capabilities.folderGrouping ?? false;
if (type == 'show') {
return ['shows', 'seasons', 'episodes', if (canFolder) 'folders'];
@@ -1491,6 +1489,7 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<MediaItem, LibraryBrows
key: _folderTreeKey,
libraryKey: widget.library.id,
serverId: widget.library.serverId,
libraryKind: widget.library.kind,
onRefresh: updateItem,
firstItemFocusNode: firstItemFocusNode,
onNavigateUp: _navigateToChips,
+91 -9
View File
@@ -9,6 +9,7 @@ import 'package:provider/provider.dart';
import 'package:window_manager/window_manager.dart';
import '../i18n/strings.g.dart';
import '../services/app_exit_service.dart';
import '../services/tvos_system_navigation_service.dart';
import '../services/update_service.dart';
import '../utils/app_logger.dart';
import '../widgets/auth_error_banner.dart';
@@ -176,6 +177,25 @@ bool shouldRenderMainScreenOffline({
return providerOffline || (startupOfflineUntilConnected && !hasVisibleConnectedServers);
}
@visibleForTesting
bool shouldPassTvosMenuToSystem({
required bool isAppleTV,
required bool isShowingProfileSelection,
required bool isOverlaySheetOpen,
required bool isRouteCurrent,
required bool isSidebarFocused,
required bool hasVisibleTabs,
required bool isCurrentTabRoot,
}) {
return isAppleTV &&
isSidebarFocused &&
!isShowingProfileSelection &&
!isOverlaySheetOpen &&
isRouteCurrent &&
hasVisibleTabs &&
isCurrentTabRoot;
}
class MainScreen extends StatefulWidget {
final bool isOfflineMode;
@@ -241,6 +261,7 @@ class _MainScreenState extends State<MainScreen>
final FocusScopeNode _contentFocusScope = FocusScopeNode(debugLabel: 'Content');
bool _isSidebarFocused = false;
bool _isSidebarInteractionExpanded = false;
bool _isOverlaySheetOpen = false;
/// The binder is now owned by a top-level [Provider] (see main.dart) so
/// the splash can await its first settle before navigating here. We just
@@ -352,6 +373,8 @@ class _MainScreenState extends State<MainScreen>
_contentFocusScope.requestFocus();
}
_updateTvosMenuPassthrough();
// Check for updates on startup
unawaited(_checkForUpdatesOnStartup());
});
@@ -549,10 +572,12 @@ class _MainScreenState extends State<MainScreen>
if (!hasNoActive && !requireOnOpen) return;
_isShowingProfileSelection = true;
_setTvosMenuPassthrough(false);
await Navigator.of(
context,
).push(MaterialPageRoute(builder: (context) => const ProfileSwitchScreen(requireSelection: true)));
_isShowingProfileSelection = false;
_updateTvosMenuPassthrough();
}
Future<void> _checkForUpdatesOnStartup() async {
@@ -785,6 +810,7 @@ class _MainScreenState extends State<MainScreen>
_startupSettleTimeout = null;
_sidebarFocusScope.dispose();
_contentFocusScope.dispose();
_setTvosMenuPassthrough(false);
// Clean up companion remote callbacks
if (_companionRemoteSetup) {
@@ -829,10 +855,12 @@ class _MainScreenState extends State<MainScreen>
if (!activeProfile.hasMultipleProfiles) return;
_isShowingProfileSelection = true;
_setTvosMenuPassthrough(false);
await Navigator.of(
context,
).push(MaterialPageRoute(builder: (context) => const ProfileSwitchScreen(requireSelection: true)));
_isShowingProfileSelection = false;
_updateTvosMenuPassthrough();
}
/// IndexedStack that disables tickers for offscreen children to prevent
@@ -932,6 +960,7 @@ class _MainScreenState extends State<MainScreen>
_screens = _buildScreens(_isOffline);
_currentTab = _normalizeTabForMode(_currentTab, _isOffline);
});
_updateTvosMenuPassthrough();
}
void _handleOfflineStatusChanged() {
@@ -977,6 +1006,7 @@ class _MainScreenState extends State<MainScreen>
_autoSwitchedToDownloads = false;
}
});
_updateTvosMenuPassthrough();
// Refresh sidebar focus after rebuilding navigation
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -1005,6 +1035,7 @@ class _MainScreenState extends State<MainScreen>
// and overwrites lastFocusedKey (e.g. to the Libraries toggle button).
final targetKey = _sideNavKey.currentState?.lastFocusedKey;
setState(() => _isSidebarFocused = true);
_updateTvosMenuPassthrough();
_sidebarFocusScope.requestFocus();
// Focus the active item after the focus scope has focus
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -1012,13 +1043,23 @@ class _MainScreenState extends State<MainScreen>
});
}
void _focusContent() {
void _focusContent({bool restorePreviousFocus = true}) {
setState(() => _isSidebarFocused = false);
_contentFocusScope.requestFocus();
_updateTvosMenuPassthrough();
if (restorePreviousFocus) {
_contentFocusScope.requestFocus();
}
// Only programmatically focus if the scope didn't auto-restore a child.
// This preserves the user's focus position when returning from sidebar.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_contentFocusScope.focusedChild == null) {
if (!mounted) return;
if (restorePreviousFocus) {
if (_contentFocusScope.focusedChild == null) {
if (_screenKeyFor(_currentTab)?.currentState case final FocusableTab focusable) {
focusable.focusActiveTabIfReady();
}
}
} else {
if (_screenKeyFor(_currentTab)?.currentState case final FocusableTab focusable) {
focusable.focusActiveTabIfReady();
}
@@ -1031,6 +1072,12 @@ class _MainScreenState extends State<MainScreen>
setState(() => _isSidebarInteractionExpanded = expanded);
}
void _handleOverlaySheetOpenChanged(bool open) {
if (_isOverlaySheetOpen == open) return;
_isOverlaySheetOpen = open;
_updateTvosMenuPassthrough();
}
double _sideNavigationWidth(BuildContext context, {required bool alwaysExpanded}) {
final isExpanded = alwaysExpanded || _isSidebarFocused || _isSidebarInteractionExpanded;
return isExpanded
@@ -1038,12 +1085,34 @@ class _MainScreenState extends State<MainScreen>
: SideNavigationRailState.collapsedWidthForContext(context);
}
bool get _shouldPassTvosMenuToSystem {
final tabs = _getVisibleTabs(_isOffline);
return shouldPassTvosMenuToSystem(
isAppleTV: PlatformDetector.isAppleTV(),
isShowingProfileSelection: _isShowingProfileSelection,
isOverlaySheetOpen: _isOverlaySheetOpen,
isRouteCurrent: ModalRoute.of(context)?.isCurrent == true,
isSidebarFocused: _isSidebarFocused,
hasVisibleTabs: tabs.isNotEmpty,
isCurrentTabRoot: tabs.isNotEmpty && _currentTab == tabs.first.id,
);
}
void _setTvosMenuPassthrough(bool enabled) {
if (!PlatformDetector.isAppleTV()) return;
unawaited(TvosSystemNavigationService.setMenuPassthroughEnabled(enabled));
}
void _updateTvosMenuPassthrough() {
_setTvosMenuPassthrough(_shouldPassTvosMenuToSystem);
}
/// Suppress stray back events after a child route pops.
/// On Android TV the platform popRoute can arrive before the key events,
/// so BackKeySuppressorObserver misses them and they leak into _handleBackKey.
bool _suppressBackAfterPop = false;
KeyEventResult _handleMainBack({bool allowTvSystemExit = false}) {
KeyEventResult _handleMainBack() {
final tabs = _getVisibleTabs(_isOffline);
if (tabs.isEmpty) return KeyEventResult.handled;
@@ -1054,11 +1123,18 @@ class _MainScreenState extends State<MainScreen>
return KeyEventResult.handled;
}
// The tvOS engine normally passes root Menu presses through to UIKit. If a
// stale event still reaches Flutter, avoid showing an exit prompt that
// cannot be honored app-side.
if (PlatformDetector.isAppleTV()) {
_lastBackPressAt = null;
return KeyEventResult.handled;
}
final now = DateTime.now();
final lastBackPressAt = _lastBackPressAt;
if (lastBackPressAt != null && now.difference(lastBackPressAt) < _backExitWindow) {
_lastBackPressAt = null;
if (allowTvSystemExit && PlatformDetector.isAppleTV()) return KeyEventResult.skipRemainingHandlers;
unawaited(AppExitService.requestExit());
return KeyEventResult.handled;
}
@@ -1079,7 +1155,7 @@ class _MainScreenState extends State<MainScreen>
// matching comment in handleBackKeyAction for why the suppressor pattern
// doesn't fit here.
if (PlatformDetector.isAppleTV() && event is KeyDownEvent) {
final result = _handleMainBack(allowTvSystemExit: true);
final result = _handleMainBack();
if (result == KeyEventResult.handled) {
BackKeyCoordinator.markHandled();
}
@@ -1090,7 +1166,7 @@ class _MainScreenState extends State<MainScreen>
}
if (event is KeyUpEvent) {
final result = _handleMainBack(allowTvSystemExit: PlatformDetector.isAppleTV());
final result = _handleMainBack();
if (result == KeyEventResult.handled) {
BackKeyCoordinator.markHandled();
}
@@ -1167,6 +1243,7 @@ class _MainScreenState extends State<MainScreen>
@override
void didPushNext() {
_setTvosMenuPassthrough(false);
// Called when a child route is pushed on top (e.g., video player)
if (_currentTab == NavigationTabId.discover) {
if (_discoverKey.currentState case final TabVisibilityAware aware) {
@@ -1187,6 +1264,7 @@ class _MainScreenState extends State<MainScreen>
});
// Called when returning to this route from a child route (e.g., from video player)
_updateTvosMenuPassthrough();
if (_currentTab == NavigationTabId.discover) {
if (_discoverKey.currentState case final TabVisibilityAware aware) {
aware.onTabShown();
@@ -1273,6 +1351,7 @@ class _MainScreenState extends State<MainScreen>
_autoSwitchedToDownloads = false;
}
});
_updateTvosMenuPassthrough();
if (previousTab != tab) {
// Notify previous screen it's being hidden
@@ -1362,6 +1441,7 @@ class _MainScreenState extends State<MainScreen>
: SideNavigationRailState.collapsedWidthForContext(context);
return OverlaySheetHost(
onOpenChanged: _handleOverlaySheetOpenChanged,
child: PopScope(
canPop: false, // Prevent system back from popping on Android TV
// ignore: no-empty-block - required callback, back navigation handled by _handleBackKey
@@ -1430,12 +1510,13 @@ class _MainScreenState extends State<MainScreen>
isReconnecting: _isReconnecting,
onInteractionExpandedChanged: _handleSidebarInteractionExpandedChanged,
onDestinationSelected: (tab) {
final restorePreviousFocus = tab == _currentTab;
_selectTab(tab);
_focusContent();
_focusContent(restorePreviousFocus: restorePreviousFocus);
},
onLibrarySelected: (key) {
_selectLibrary(key);
_focusContent();
_focusContent(restorePreviousFocus: false);
},
onNavigateToContent: _focusContent,
onReconnect: _triggerReconnect,
@@ -1464,6 +1545,7 @@ class _MainScreenState extends State<MainScreen>
_handleMainBack();
},
child: OverlaySheetHost(
onOpenChanged: _handleOverlaySheetOpenChanged,
child: ScaffoldMessenger(
key: mainScaffoldMessengerKey,
child: Scaffold(
+11 -13
View File
@@ -779,21 +779,19 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
_tvDetailRevealScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
setState(() {
_tvDetailStableRailHeight = _tvDetailPendingRailHeight ?? railHeight;
_tvDetailRevealScheduled = false;
_tvDetailRevealed = true;
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
setState(() {
_tvDetailStableRailHeight = _tvDetailPendingRailHeight ?? railHeight;
_tvDetailRevealScheduled = false;
_tvDetailRevealed = true;
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
if (focusPrimaryAction) {
_playButtonFocusNode.requestFocus();
} else {
_tvDetailRailKey.currentState?.requestFocus();
}
});
if (focusPrimaryAction) {
_playButtonFocusNode.requestFocus();
} else {
_tvDetailRailKey.currentState?.requestFocus();
}
});
});
}
+137
View File
@@ -6,6 +6,7 @@ import '../media/media_kind.dart';
import '../media/media_library.dart';
import '../media/media_server_client.dart';
import '../utils/app_logger.dart';
import '../utils/external_ids.dart';
import '../utils/global_key_utils.dart';
import '../utils/search_relevance.dart';
import 'multi_server_manager.dart';
@@ -78,6 +79,8 @@ class DataAggregationService {
return bTime.compareTo(aTime); // Descending (most recent first)
});
filteredOnDeck = await _deduplicateContinueWatching(filteredOnDeck);
// Apply limit if specified
final result = limit != null && limit < filteredOnDeck.length ? filteredOnDeck.sublist(0, limit) : filteredOnDeck;
@@ -86,6 +89,140 @@ class DataAggregationService {
return result;
}
Future<List<MediaItem>> _deduplicateContinueWatching(List<MediaItem> items) async {
if (items.length < 2) return items;
final bucketCounts = <String, int>{};
for (final item in items) {
final bucket = _continueWatchingTitleBucket(item);
if (bucket == null) continue;
bucketCounts[bucket] = (bucketCounts[bucket] ?? 0) + 1;
}
final duplicateBuckets = {
for (final entry in bucketCounts.entries)
if (entry.value > 1) entry.key,
};
if (duplicateBuckets.isEmpty) return items;
final externalIdLoads = <String, Future<ExternalIds>>{};
final identityKeysByIndex = <int, Set<String>>{};
final identityKeyLoads = <Future<void>>[];
for (var i = 0; i < items.length; i++) {
if (!duplicateBuckets.contains(_continueWatchingTitleBucket(items[i]))) continue;
final index = i;
identityKeyLoads.add(
_continueWatchingIdentityKeys(items[index], externalIdLoads).then((keys) => identityKeysByIndex[index] = keys),
);
}
await Future.wait(identityKeyLoads);
final seenKeys = <String>{};
final result = <MediaItem>[];
for (var i = 0; i < items.length; i++) {
final item = items[i];
if (!duplicateBuckets.contains(_continueWatchingTitleBucket(item))) {
result.add(item);
continue;
}
final identityKeys = identityKeysByIndex[i] ?? const <String>{};
if (identityKeys.isEmpty) {
result.add(item);
continue;
}
if (identityKeys.any(seenKeys.contains)) continue;
seenKeys.addAll(identityKeys);
result.add(item);
}
return result;
}
String? _continueWatchingTitleBucket(MediaItem item) {
final scope = _continueWatchingIdentityScope(item);
if (scope == null) return null;
final title = switch (item.kind) {
MediaKind.episode || MediaKind.season => item.grandparentTitle ?? item.parentTitle ?? item.title,
_ => item.title,
};
final normalized = title?.trim().toLowerCase().replaceAll(RegExp(r'\s+'), ' ');
if (normalized == null || normalized.isEmpty) return null;
return '$scope:$normalized';
}
Future<Set<String>> _continueWatchingIdentityKeys(
MediaItem item,
Map<String, Future<ExternalIds>> externalIdLoads,
) async {
final scope = _continueWatchingIdentityScope(item);
if (scope == null) return const {};
final keys = <String>{};
final serverId = item.serverId;
final targetId = _continueWatchingIdentityTargetId(item);
final client = serverId == null ? null : _serverManager.getClient(serverId);
if (client != null && targetId != null && targetId.isNotEmpty) {
try {
final cacheKey = buildGlobalKey(serverId!, targetId);
final externalIds = await externalIdLoads.putIfAbsent(cacheKey, () => client.fetchExternalIds(targetId));
_addExternalIdentityKeys(keys, scope, externalIds);
} catch (e, stackTrace) {
appLogger.d(
'Failed to resolve Continue Watching identity for ${item.globalKey}',
error: e,
stackTrace: stackTrace,
);
}
}
final stableGuid = _stableMediaGuid(item.guid);
if (stableGuid != null) {
final guidScope = item.kind == MediaKind.episode ? 'episode' : scope;
keys.add('$guidScope:guid:$stableGuid');
}
return keys;
}
String? _continueWatchingIdentityScope(MediaItem item) {
return switch (item.kind) {
MediaKind.episode || MediaKind.season || MediaKind.show => 'show',
MediaKind.movie => 'movie',
_ => null,
};
}
String? _continueWatchingIdentityTargetId(MediaItem item) {
return switch (item.kind) {
MediaKind.episode => item.grandparentId,
MediaKind.season => item.grandparentId ?? item.parentId,
MediaKind.show || MediaKind.movie => item.id,
_ => null,
};
}
void _addExternalIdentityKeys(Set<String> keys, String scope, ExternalIds externalIds) {
final imdb = externalIds.imdb?.trim().toLowerCase();
if (imdb != null && imdb.isNotEmpty) keys.add('$scope:imdb:$imdb');
final tmdb = externalIds.tmdb;
if (tmdb != null) keys.add('$scope:tmdb:$tmdb');
final tvdb = externalIds.tvdb;
if (tvdb != null) keys.add('$scope:tvdb:$tvdb');
}
String? _stableMediaGuid(String? guid) {
final value = guid?.trim();
if (value == null || value.isEmpty) return null;
if (!value.contains('://')) return null;
if (value.contains('agents.none://')) return null;
return value.toLowerCase();
}
/// Fetch recommendation hubs from all servers as neutral [MediaHub]s.
/// When useGlobalHubs is true (default), rich-hub backends use their true
/// home page hubs (Plex's promoted/global hub endpoint).
+429 -107
View File
@@ -32,6 +32,8 @@ import '../utils/global_key_utils.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
typedef MediaClientResolver = MediaServerClient? Function(String serverId, {String? clientScopeId});
typedef _NativeTaskForId = Future<Task?> Function(String taskId);
typedef _NativeResumeTask = Future<bool> Function(DownloadTask task);
const bool _tvosBuild = bool.fromEnvironment('TVOS_BUILD');
@@ -449,6 +451,8 @@ class DownloadManagerService {
appLogger.i('Rescheduled ${rescheduled.length} killed download task(s)');
}
await _reconcileNativeDownloadTasks();
// One-time migration: normalize stored file paths that may contain a
// doubled base-dir prefix from an earlier bug in the recovery callback.
// Re-run on v2 to also fix paths without a leading / that the v1 migration missed.
@@ -528,6 +532,156 @@ class DownloadManagerService {
}
}
Future<void> _reconcileNativeDownloadTasks() async {
if (!downloadsSupported || !_fileDownloaderInitialized) return;
final List<Task> nativeTasks;
try {
nativeTasks = await FileDownloader().allTasks(group: _downloadGroup);
} catch (e) {
appLogger.w('Failed to enumerate native download tasks during recovery', error: e);
return;
}
if (nativeTasks.isEmpty) return;
final tasksByGlobalKey = <String, List<Task>>{};
for (final task in nativeTasks) {
final globalKey = task.metaData;
if (globalKey.isEmpty) continue;
(tasksByGlobalKey[globalKey] ??= []).add(task);
}
if (tasksByGlobalKey.isEmpty) return;
final rows = await _database.select(_database.downloadedMedia).get();
final rowsByGlobalKey = {for (final row in rows) row.globalKey: row};
for (final entry in tasksByGlobalKey.entries) {
final globalKey = entry.key;
final tasks = entry.value;
final row = rowsByGlobalKey[globalKey];
if (row == null) {
await _cancelNativeTaskIds(
globalKey,
tasks.map((task) => task.taskId),
reason: 'no download row during recovery',
);
continue;
}
switch (DownloadStatus.values[row.status]) {
case DownloadStatus.downloading:
await _reconcileDownloadingNativeTasks(row, tasks);
case DownloadStatus.paused:
await _reconcilePausedNativeTasks(row, tasks);
case DownloadStatus.queued:
await _cancelNativeTaskIds(
globalKey,
tasks.map((task) => task.taskId),
reason: 'queued download during recovery',
);
await _database.addToQueue(mediaGlobalKey: globalKey);
case DownloadStatus.completed:
case DownloadStatus.failed:
case DownloadStatus.cancelled:
case DownloadStatus.partial:
await _cancelNativeTaskIds(
globalKey,
tasks.map((task) => task.taskId),
reason: 'download status ${DownloadStatus.values[row.status]} during recovery',
);
}
}
}
Future<void> _reconcileDownloadingNativeTasks(DownloadedMediaItem row, List<Task> tasks) async {
final currentTaskId = row.bgTaskId;
final matchingCurrentTasks = currentTaskId == null
? const <Task>[]
: tasks.where((task) => task.taskId == currentTaskId).toList(growable: false);
if (matchingCurrentTasks.length == 1) {
await _cancelNativeTaskIds(
row.globalKey,
tasks.where((task) => task.taskId != currentTaskId).map((task) => task.taskId),
reason: 'duplicate downloading task during recovery',
);
return;
}
if (matchingCurrentTasks.length > 1) {
appLogger.w('Multiple native tasks share current task id $currentTaskId for ${row.globalKey}; re-queueing');
await _cancelNativeTaskIds(
row.globalKey,
tasks.map((task) => task.taskId),
reason: 'duplicate current task id during recovery',
);
await _database.updateBgTaskId(row.globalKey, null);
await _database.updateDownloadProgress(row.globalKey, 0, 0, 0);
await _transitionStatus(row.globalKey, DownloadStatus.queued);
await _database.addToQueue(mediaGlobalKey: row.globalKey);
return;
}
if (tasks.length == 1) {
final taskId = tasks.single.taskId;
appLogger.i('Adopting recovered native task $taskId for ${row.globalKey}');
await _database.updateBgTaskId(row.globalKey, taskId);
return;
}
await _cancelNativeTaskIds(
row.globalKey,
tasks.map((task) => task.taskId),
reason: 'ambiguous downloading tasks during recovery',
);
await _database.updateBgTaskId(row.globalKey, null);
await _database.updateDownloadProgress(row.globalKey, 0, 0, 0);
await _transitionStatus(row.globalKey, DownloadStatus.queued);
await _database.addToQueue(mediaGlobalKey: row.globalKey);
}
Future<void> _reconcilePausedNativeTasks(DownloadedMediaItem row, List<Task> tasks) async {
final currentTaskId = row.bgTaskId;
final matchingCurrentTasks = currentTaskId == null
? const <Task>[]
: tasks.where((task) => task.taskId == currentTaskId).toList(growable: false);
if (matchingCurrentTasks.length == 1) {
await _cancelNativeTaskIds(
row.globalKey,
tasks.where((task) => task.taskId != currentTaskId).map((task) => task.taskId),
reason: 'duplicate paused task during recovery',
);
return;
}
if (matchingCurrentTasks.length > 1) {
appLogger.w(
'Multiple paused native tasks share current task id $currentTaskId for ${row.globalKey}; clearing task',
);
}
await _cancelNativeTaskIds(
row.globalKey,
tasks.map((task) => task.taskId),
reason: 'unexpected paused native tasks during recovery',
);
await _database.updateBgTaskId(row.globalKey, null);
}
Future<void> _cancelNativeTaskIds(String globalKey, Iterable<String> taskIds, {required String reason}) async {
if (!downloadsSupported) return;
final ids = taskIds.where((id) => id.isNotEmpty).toSet();
if (ids.isEmpty) return;
try {
final cancelled = await FileDownloader().cancelTasksWithIds(ids);
if (cancelled) {
appLogger.d('Cancelled ${ids.length} native task(s) for $globalKey ($reason): ${ids.join(', ')}');
}
} catch (e) {
appLogger.w('Failed to cancel native tasks for $globalKey ($reason): ${ids.join(', ')}', error: e);
}
}
/// Resume queued downloads that have no active processing.
/// Call after a [MediaServerClient] becomes available (e.g. after server connect on launch).
void resumeQueuedDownloads(MediaServerClient client) {
@@ -841,10 +995,24 @@ class DownloadManagerService {
final globalKey = metadata.globalKey;
final existing = await _database.getDownloadedMedia(globalKey);
if (existing != null &&
(existing.status == DownloadStatus.downloading.index || existing.status == DownloadStatus.completed.index)) {
appLogger.i('Download already exists for $globalKey with status ${existing.status}');
return;
if (existing != null) {
if (existing.status == DownloadStatus.queued.index) {
await _database.addToQueue(
mediaGlobalKey: globalKey,
priority: priority,
downloadSubtitles: downloadSubtitles,
downloadArtwork: downloadArtwork,
);
_emitProgress(globalKey, DownloadStatus.queued, 0);
unawaited(_processQueue(client));
return;
}
if (existing.status == DownloadStatus.downloading.index ||
existing.status == DownloadStatus.paused.index ||
existing.status == DownloadStatus.completed.index) {
appLogger.i('Download already exists for $globalKey with status ${existing.status}');
return;
}
}
await _database.insertDownload(
@@ -917,16 +1085,85 @@ class DownloadManagerService {
/// Cancel any lingering background task and reset progress before re-enqueuing.
Future<void> _cleanupStaleDownload(String globalKey) async {
final existingTaskId = await _database.getBgTaskId(globalKey);
if (existingTaskId != null) {
if (downloadsSupported) {
await FileDownloader().cancelTaskWithId(existingTaskId);
}
await _database.updateBgTaskId(globalKey, null);
appLogger.d('Cancelled stale bg task $existingTaskId for $globalKey');
}
await _database.updateBgTaskId(globalKey, null);
_pendingDownloadContext.remove(globalKey);
await _cancelNativeTasksForGlobalKey(
globalKey,
includeTaskId: existingTaskId,
reason: 'stale task before re-download',
);
await _database.updateDownloadProgress(globalKey, 0, 0, 0);
}
Future<void> _cancelNativeTask(String globalKey, String taskId, {required String reason}) async {
if (!downloadsSupported || taskId.isEmpty) return;
try {
final cancelled = await FileDownloader().cancelTaskWithId(taskId);
if (cancelled) {
appLogger.d('Cancelled native task $taskId for $globalKey ($reason)');
}
} catch (e) {
appLogger.w('Failed to cancel native task $taskId for $globalKey ($reason)', error: e);
}
}
Future<void> _cancelNativeTasksForGlobalKey(
String globalKey, {
String? includeTaskId,
String? exceptTaskId,
required String reason,
}) async {
if (!downloadsSupported) return;
final taskIds = <String>{};
if (includeTaskId != null && includeTaskId != exceptTaskId) taskIds.add(includeTaskId);
if (!_fileDownloaderInitialized && taskIds.isEmpty) return;
try {
final nativeTasks = await FileDownloader().allTasks(group: _downloadGroup);
for (final task in nativeTasks) {
if (task.metaData == globalKey && task.taskId != exceptTaskId) taskIds.add(task.taskId);
}
} catch (e) {
appLogger.w('Failed to enumerate native tasks for $globalKey ($reason)', error: e);
}
if (taskIds.isEmpty) return;
try {
final cancelled = await FileDownloader().cancelTasksWithIds(taskIds);
if (cancelled) {
appLogger.d('Cancelled ${taskIds.length} native task(s) for $globalKey ($reason): ${taskIds.join(', ')}');
}
} catch (e) {
appLogger.w('Failed to cancel native tasks for $globalKey ($reason): ${taskIds.join(', ')}', error: e);
}
}
Future<DownloadedMediaItem?> _downloadForCurrentTaskSession(
String globalKey,
String taskId, {
required String event,
bool cancelStale = false,
}) async {
final existing = await _database.getDownloadedMedia(globalKey);
final currentTaskId = existing?.bgTaskId;
if (existing != null && currentTaskId == taskId) return existing;
appLogger.d(
'Ignoring stale download $event for $globalKey from task $taskId '
'(current task: ${currentTaskId ?? 'none'})',
);
if (cancelStale) {
await _cancelNativeTask(globalKey, taskId, reason: 'stale $event');
}
return null;
}
bool _isNativeTaskActiveStatus(TaskStatus status) {
return status == TaskStatus.enqueued || status == TaskStatus.running || status == TaskStatus.waitingToRetry;
}
Future<bool> _isInactiveForEnqueue(String globalKey) async {
if (_cancellingKeys.contains(globalKey)) return true;
final existing = await _database.getDownloadedMedia(globalKey);
@@ -975,7 +1212,7 @@ class DownloadManagerService {
}
appLogger.i('Preparing download for $globalKey');
if (existing.bgTaskId != null) await _cleanupStaleDownload(globalKey);
await _cleanupStaleDownload(globalKey);
if (await _isInactiveForEnqueue(globalKey)) {
appLogger.d('Skipping enqueue for $globalKey: inactive before transition');
await _database.removeFromQueue(globalKey);
@@ -1068,7 +1305,7 @@ class DownloadManagerService {
updates: Updates.statusAndProgress,
requiresWiFi: requiresWiFi,
retries: _nativeRetries,
allowPause: true,
allowPause: false,
metaData: globalKey,
displayName: displayName,
);
@@ -1157,17 +1394,42 @@ class DownloadManagerService {
/// Callback: background_downloader progress update
void _onTaskProgress(TaskProgressUpdate update) {
if (_disposed) return;
unawaited(
_handleTaskProgress(update).catchError((Object e, StackTrace st) {
appLogger.e('Error handling download progress for ${update.task.metaData}', error: e, stackTrace: st);
}),
);
}
@visibleForTesting
Future<void> debugHandleTaskProgress(TaskProgressUpdate update) => _handleTaskProgress(update);
Future<void> _handleTaskProgress(TaskProgressUpdate update) async {
if (_disposed) return;
final globalKey = update.task.metaData;
if (globalKey.isEmpty || update.progress < 0) return;
final existing = await _downloadForCurrentTaskSession(
globalKey,
update.task.taskId,
event: 'progress',
cancelStale: true,
);
if (existing == null) return;
if (existing.status != DownloadStatus.downloading.index) {
appLogger.d('Ignoring progress for inactive download $globalKey from task ${update.task.taskId}');
await _cancelNativeTask(globalKey, update.task.taskId, reason: 'progress for inactive download');
return;
}
// If this item is being paused, the holding queue promoted it — cancel it
if (_pausingKeys.contains(globalKey)) {
if (downloadsSupported) FileDownloader().cancelTaskWithId(update.task.taskId);
await _cancelNativeTask(globalKey, update.task.taskId, reason: 'pause in progress');
return;
}
if (_cancellingKeys.contains(globalKey)) {
if (downloadsSupported) FileDownloader().cancelTaskWithId(update.task.taskId);
await _cancelNativeTask(globalKey, update.task.taskId, reason: 'cancellation in progress');
return;
}
@@ -1202,23 +1464,51 @@ class DownloadManagerService {
/// Callback: background_downloader status change
void _onTaskStatusChanged(TaskStatusUpdate update) {
if (_disposed) return;
unawaited(
_handleTaskStatusChanged(update).catchError((Object e, StackTrace st) {
appLogger.e('Error handling download status for ${update.task.metaData}', error: e, stackTrace: st);
}),
);
}
@visibleForTesting
Future<void> debugHandleTaskStatus(TaskStatusUpdate update) => _handleTaskStatusChanged(update);
Future<void> _handleTaskStatusChanged(TaskStatusUpdate update) async {
if (_disposed) return;
final globalKey = update.task.metaData;
if (globalKey.isEmpty) return;
appLogger.d('Background task status: ${update.status} for $globalKey');
appLogger.d('Background task status: ${update.status} for $globalKey (task ${update.task.taskId})');
final existing = await _downloadForCurrentTaskSession(
globalKey,
update.task.taskId,
event: 'status ${update.status}',
cancelStale: _isNativeTaskActiveStatus(update.status),
);
if (existing == null) return;
if (existing.status != DownloadStatus.downloading.index) {
appLogger.d('Ignoring ${update.status} for inactive download $globalKey from task ${update.task.taskId}');
if (_isNativeTaskActiveStatus(update.status)) {
await _cancelNativeTask(globalKey, update.task.taskId, reason: 'status for inactive download');
}
return;
}
try {
switch (update.status) {
case TaskStatus.complete:
_onDownloadComplete(globalKey, update.task);
await _onDownloadComplete(globalKey, update.task);
case TaskStatus.failed:
_onDownloadFailed(globalKey, update.exception?.description ?? 'Download failed');
await _onDownloadFailed(globalKey, update.task.taskId, update.exception?.description ?? 'Download failed');
case TaskStatus.notFound:
_onDownloadPermanentlyFailed(globalKey, 'File not found (404)');
await _onDownloadPermanentlyFailed(globalKey, update.task.taskId, 'File not found (404)');
case TaskStatus.canceled:
if (_pausingKeys.contains(globalKey) || _cancellingKeys.contains(globalKey)) break;
_onDownloadCanceled(globalKey);
await _onDownloadCanceled(globalKey, update.task.taskId);
case TaskStatus.paused:
appLogger.d('Download paused by system for $globalKey');
case TaskStatus.waitingToRetry:
@@ -1227,10 +1517,10 @@ class DownloadManagerService {
case TaskStatus.running:
// If this item is being paused, the holding queue promoted it — cancel it
if (_pausingKeys.contains(globalKey)) {
if (downloadsSupported) FileDownloader().cancelTaskWithId(update.task.taskId);
await _cancelNativeTask(globalKey, update.task.taskId, reason: 'pause in progress');
}
if (_cancellingKeys.contains(globalKey)) {
if (downloadsSupported) FileDownloader().cancelTaskWithId(update.task.taskId);
await _cancelNativeTask(globalKey, update.task.taskId, reason: 'cancellation in progress');
}
break;
}
@@ -1240,19 +1530,21 @@ class DownloadManagerService {
}
/// Handle a system-initiated cancel — re-queue unless already completed.
Future<void> _onDownloadCanceled(String globalKey) async {
_cancelDownloadTimers(globalKey);
final ctx = _pendingDownloadContext.remove(globalKey);
if (ctx == null) return;
Future<void> _onDownloadCanceled(String globalKey, String taskId) async {
if (_completingKeys.contains(globalKey)) return;
final existing = await _database.getDownloadedMedia(globalKey);
if (existing == null ||
existing.bgTaskId != taskId ||
existing.status != DownloadStatus.downloading.index ||
existing.status == DownloadStatus.completed.index ||
existing.status == DownloadStatus.cancelled.index) {
return;
}
_cancelDownloadTimers(globalKey);
_pendingDownloadContext.remove(globalKey);
appLogger.w('Download cancelled by system for $globalKey, re-queuing');
await _database.updateBgTaskId(globalKey, null);
await _transitionStatus(globalKey, DownloadStatus.queued);
@@ -1263,7 +1555,7 @@ class DownloadManagerService {
/// Handle a failed download — auto-retry if retries remain, otherwise permanently fail.
/// Native retries (Range-based resume) are already exhausted at this point.
Future<void> _onDownloadFailed(String globalKey, String errorMessage) async {
Future<void> _onDownloadFailed(String globalKey, String taskId, String errorMessage) async {
if (_cancellingKeys.contains(globalKey)) {
appLogger.d('Ignoring failure for $globalKey: cancellation in progress');
return;
@@ -1272,16 +1564,18 @@ class DownloadManagerService {
appLogger.d('Ignoring failure event for $globalKey: completion in progress');
return;
}
_cancelDownloadTimers(globalKey);
_pendingDownloadContext.remove(globalKey);
final existing = await _database.getDownloadedMedia(globalKey);
if (existing == null ||
existing.bgTaskId != taskId ||
existing.status != DownloadStatus.downloading.index ||
existing.status == DownloadStatus.completed.index ||
existing.status == DownloadStatus.cancelled.index) {
appLogger.d('Ignoring stale failure for inactive download $globalKey');
return;
}
_cancelDownloadTimers(globalKey);
_pendingDownloadContext.remove(globalKey);
final retryCount = existing.retryCount;
// DNS/connection errors fail instantly and exhaust native retries in milliseconds,
@@ -1318,12 +1612,12 @@ class DownloadManagerService {
appLogger.w('Network error for $globalKey, failing permanently (no auto-retry): $errorMessage');
}
final userMessage = isServerError ? t.downloads.serverErrorBitrate : errorMessage;
await _onDownloadPermanentlyFailed(globalKey, userMessage);
await _onDownloadPermanentlyFailed(globalKey, taskId, userMessage);
}
}
/// Handle a non-retryable failure (e.g. 404) — fail immediately without auto-retry.
Future<void> _onDownloadPermanentlyFailed(String globalKey, String errorMessage) async {
Future<void> _onDownloadPermanentlyFailed(String globalKey, String taskId, String errorMessage) async {
if (_cancellingKeys.contains(globalKey)) {
appLogger.d('Ignoring permanent failure for $globalKey: cancellation in progress');
return;
@@ -1332,17 +1626,20 @@ class DownloadManagerService {
appLogger.d('Ignoring permanent failure event for $globalKey: completion in progress');
return;
}
_cancelDownloadTimers(globalKey);
_pendingDownloadContext.remove(globalKey);
final existing = await _database.getDownloadedMedia(globalKey);
if (existing == null ||
existing.bgTaskId != taskId ||
existing.status != DownloadStatus.downloading.index ||
existing.status == DownloadStatus.completed.index ||
existing.status == DownloadStatus.cancelled.index) {
appLogger.d('Ignoring stale permanent failure for inactive download $globalKey');
return;
}
_cancelDownloadTimers(globalKey);
_pendingDownloadContext.remove(globalKey);
appLogger.e('Download permanently failed for $globalKey: $errorMessage');
await _transitionStatus(globalKey, DownloadStatus.failed, errorMessage: errorMessage);
await _database.removeFromQueue(globalKey);
@@ -1368,7 +1665,7 @@ class DownloadManagerService {
}
appLogger.i('Auto-retrying download for $globalKey');
await _database.updateBgTaskId(globalKey, null);
await _cleanupStaleDownload(globalKey);
await _transitionStatus(globalKey, DownloadStatus.queued);
await _database.addToQueue(mediaGlobalKey: globalKey);
unawaited(_processQueue(client));
@@ -1384,24 +1681,22 @@ class DownloadManagerService {
}
_completingKeys.add(globalKey);
try {
// Flush any pending debounced progress write + cancel any scheduled retry
_cancelDownloadTimers(globalKey);
// Fresh DB check — bail if already completed (guards against race with orphan scan)
final existingCheck = await _database.getDownloadedMedia(globalKey);
if (_cancellingKeys.contains(globalKey) || existingCheck == null) {
appLogger.d('Download no longer active for $globalKey, skipping completion');
return;
}
if (existingCheck.status == DownloadStatus.completed.index) {
appLogger.d('Download already completed for $globalKey, skipping');
return;
}
if (existingCheck.status == DownloadStatus.cancelled.index) {
appLogger.d('Download cancelled for $globalKey, skipping completion');
if (existingCheck.bgTaskId != task.taskId || existingCheck.status != DownloadStatus.downloading.index) {
appLogger.d(
'Ignoring stale completion for $globalKey from task ${task.taskId} '
'(current task: ${existingCheck.bgTaskId ?? 'none'}, status: ${existingCheck.status})',
);
return;
}
// Flush any pending debounced progress write + cancel any scheduled retry.
_cancelDownloadTimers(globalKey);
final ctx = _pendingDownloadContext.remove(globalKey);
// ── Phase 1 (critical): resolve and store the video file path ──
@@ -1732,6 +2027,7 @@ class DownloadManagerService {
try {
_cancelDownloadTimers(globalKey);
final bgTaskId = await _database.getBgTaskId(globalKey);
await _cancelNativeTasksForGlobalKey(globalKey, exceptTaskId: bgTaskId, reason: 'duplicate task before pause');
if (bgTaskId != null && downloadsSupported) {
final task = await FileDownloader().taskForId(bgTaskId);
if (task != null && task is DownloadTask) {
@@ -1759,36 +2055,60 @@ class DownloadManagerService {
final bgTaskId = await _database.getBgTaskId(globalKey);
// Try native resume first (only works for normal-mode DownloadTask that was paused)
if (bgTaskId != null) {
final task = await FileDownloader().taskForId(bgTaskId);
if (task != null && task is DownloadTask) {
final resumed = await FileDownloader().resume(task);
if (resumed) {
appLogger.i('Resumed download via background_downloader for $globalKey');
await _database.updateDownloadStatus(globalKey, DownloadStatus.downloading.index);
_emitProgress(globalKey, DownloadStatus.downloading, 0);
return;
}
}
}
if (bgTaskId != null && await _tryResumeNativeTask(globalKey, bgTaskId)) return;
// Native resume failed or not supported (SAF mode) — re-enqueue from scratch
await _database.updateBgTaskId(globalKey, null);
await _database.updateDownloadProgress(globalKey, 0, 0, 0);
await _cleanupStaleDownload(globalKey);
await _transitionStatus(globalKey, DownloadStatus.queued);
await _database.addToQueue(mediaGlobalKey: globalKey);
final resolvedClient = await _getClientForDownloadKey(globalKey) ?? client;
unawaited(_processQueue(resolvedClient));
}
Future<bool> _tryResumeNativeTask(
String globalKey,
String bgTaskId, {
_NativeTaskForId? taskForId,
_NativeResumeTask? resumeTask,
}) async {
await _cancelNativeTasksForGlobalKey(globalKey, exceptTaskId: bgTaskId, reason: 'duplicate task before resume');
try {
final task = await (taskForId ?? FileDownloader().taskForId)(bgTaskId);
if (task == null || task is! DownloadTask) return false;
final resumed = await (resumeTask ?? FileDownloader().resume)(task);
if (!resumed) {
appLogger.w('Native resume returned false for $globalKey; re-enqueuing from scratch');
return false;
}
await _transitionStatus(globalKey, DownloadStatus.downloading);
appLogger.i('Resumed download via background_downloader for $globalKey');
return true;
} catch (e) {
appLogger.w('Native resume failed for $globalKey; re-enqueuing from scratch', error: e);
return false;
}
}
@visibleForTesting
Future<bool> debugTryResumeNativeTask(
String globalKey,
String bgTaskId, {
required Future<Task?> Function(String taskId) taskForId,
required Future<bool> Function(DownloadTask task) resumeTask,
}) {
return _tryResumeNativeTask(globalKey, bgTaskId, taskForId: taskForId, resumeTask: resumeTask);
}
/// Retry a failed download
Future<void> retryDownload(String globalKey, MediaServerClient client) async {
if (_skipDownloadsUnsupported('download retry')) return;
_autoRetryTimers.remove(globalKey)?.cancel();
await _cleanupStaleDownload(globalKey);
await _database.clearDownloadError(globalKey);
await _database.updateBgTaskId(globalKey, null);
await _database.updateDownloadProgress(globalKey, 0, 0, 0);
await _transitionStatus(globalKey, DownloadStatus.queued);
await _database.addToQueue(mediaGlobalKey: globalKey);
final resolvedClient = await _getClientForDownloadKey(globalKey) ?? client;
@@ -1801,12 +2121,8 @@ class DownloadManagerService {
try {
_cancelDownloadTimers(globalKey);
final bgTaskId = await _database.getBgTaskId(globalKey);
if (bgTaskId != null) {
if (downloadsSupported) {
await FileDownloader().cancelTaskWithId(bgTaskId);
}
await _database.updateBgTaskId(globalKey, null);
}
await _database.updateBgTaskId(globalKey, null);
await _cancelNativeTasksForGlobalKey(globalKey, includeTaskId: bgTaskId, reason: 'user cancellation');
_pendingDownloadContext.remove(globalKey);
await _transitionStatus(globalKey, DownloadStatus.cancelled);
await _database.removeFromQueue(globalKey);
@@ -1816,56 +2132,62 @@ class DownloadManagerService {
}
Future<void> deleteDownload(String globalKey) async {
_cancelDownloadTimers(globalKey);
final bgTaskId = await _database.getBgTaskId(globalKey);
if (bgTaskId != null) {
if (downloadsSupported) {
await FileDownloader().cancelTaskWithId(bgTaskId);
}
_cancellingKeys.add(globalKey);
try {
_cancelDownloadTimers(globalKey);
final bgTaskId = await _database.getBgTaskId(globalKey);
await _database.updateBgTaskId(globalKey, null);
}
_pendingDownloadContext.remove(globalKey);
await _cancelNativeTasksForGlobalKey(globalKey, includeTaskId: bgTaskId, reason: 'delete download');
_pendingDownloadContext.remove(globalKey);
final parsed = parseGlobalKey(globalKey);
if (parsed == null) {
await _database.deleteDownload(globalKey);
return;
}
final parsed = parseGlobalKey(globalKey);
if (parsed == null) {
await _database.deleteDownload(globalKey);
return;
}
final serverId = parsed.serverId;
final ratingKey = parsed.ratingKey;
final downloadRecord = await _database.getDownloadedMedia(globalKey);
final clientScopeId = downloadRecord?.clientScopeId;
final metadata = await _lookupMetadata(serverId, ratingKey, clientScopeId: clientScopeId);
final serverId = parsed.serverId;
final ratingKey = parsed.ratingKey;
final downloadRecord = await _database.getDownloadedMedia(globalKey);
final clientScopeId = downloadRecord?.clientScopeId;
final metadata = await _lookupMetadata(serverId, ratingKey, clientScopeId: clientScopeId);
if (metadata == null) {
// Fallback deletion without progress
await _deleteMediaFilesWithMetadata(serverId, ratingKey, clientScopeId: clientScopeId);
await _deleteForItemByServer(serverId, ratingKey, clientScopeId: clientScopeId);
await _database.deleteDownload(globalKey);
return;
}
final totalItems = await _getTotalItemsToDelete(metadata, serverId, clientScopeId: clientScopeId);
_emitDeletionProgress(
DeletionProgress(
globalKey: globalKey,
itemTitle: metadata.displayTitle,
currentItem: 0,
totalItems: totalItems,
),
);
if (metadata == null) {
// Fallback deletion without progress
await _deleteMediaFilesWithMetadata(serverId, ratingKey, clientScopeId: clientScopeId);
await _deleteForItemByServer(serverId, ratingKey, clientScopeId: clientScopeId);
await _database.deleteDownload(globalKey);
return;
_emitDeletionProgress(
DeletionProgress(
globalKey: globalKey,
itemTitle: metadata.displayTitle,
currentItem: totalItems,
totalItems: totalItems,
),
);
} finally {
_cancellingKeys.remove(globalKey);
}
final totalItems = await _getTotalItemsToDelete(metadata, serverId, clientScopeId: clientScopeId);
_emitDeletionProgress(
DeletionProgress(globalKey: globalKey, itemTitle: metadata.displayTitle, currentItem: 0, totalItems: totalItems),
);
await _deleteMediaFilesWithMetadata(serverId, ratingKey, clientScopeId: clientScopeId);
await _deleteForItemByServer(serverId, ratingKey, clientScopeId: clientScopeId);
await _database.deleteDownload(globalKey);
_emitDeletionProgress(
DeletionProgress(
globalKey: globalKey,
itemTitle: metadata.displayTitle,
currentItem: totalItems,
totalItems: totalItems,
),
);
}
void _emitDeletionProgress(DeletionProgress progress) {
+9 -3
View File
@@ -22,6 +22,8 @@ typedef JellyfinStreamFields = ({
String? displayTitle,
bool isDefault,
bool isForced,
bool isExternalFile,
bool usesExternalDelivery,
bool isExternal,
String? deliveryUrl,
int? channels,
@@ -30,7 +32,8 @@ typedef JellyfinStreamFields = ({
JellyfinStreamFields parseJellyfinStreamFields(Map<String, dynamic> s, {int fallbackIndex = 0}) {
final deliveryMethod = (s['DeliveryMethod'] as String?)?.toLowerCase();
final isExternal = deliveryMethod != null ? deliveryMethod == 'external' : s['IsExternal'] == true;
final isExternalFile = s['IsExternal'] == true;
final usesExternalDelivery = deliveryMethod == 'external';
return (
type: (s['Type'] as String?)?.toLowerCase(),
index: flexibleInt(s['Index']) ?? fallbackIndex,
@@ -41,7 +44,9 @@ JellyfinStreamFields parseJellyfinStreamFields(Map<String, dynamic> s, {int fall
displayTitle: s['DisplayTitle'] as String?,
isDefault: s['IsDefault'] as bool? ?? false,
isForced: s['IsForced'] as bool? ?? false,
isExternal: isExternal,
isExternalFile: isExternalFile,
usesExternalDelivery: usesExternalDelivery,
isExternal: isExternalFile || usesExternalDelivery,
deliveryUrl: s['DeliveryUrl'] as String?,
channels: flexibleInt(s['Channels']),
frameRate: flexibleDouble(s['RealFrameRate']) ?? flexibleDouble(s['AverageFrameRate']),
@@ -231,7 +236,8 @@ class JellyfinFileInfoStreamReader implements FileInfoStreamReader {
selected: f.isDefault,
forced: f.isForced,
key: f.isExternal ? f.deliveryUrl : null,
external: f.isExternal,
external: f.isExternalFile,
usesExternalDelivery: f.usesExternalDelivery,
);
}
}
+126 -10
View File
@@ -42,6 +42,18 @@ const _episodeQueuePageSize = 200;
const _childrenPageSize = 500;
const _pagedListPageSize = 200;
const _playableDescendantTypes = 'Movie,Episode';
const _playableFolderDescendantTypes = 'Movie,Episode,Video,MusicVideo';
bool _isJellyfinFolderDto(Map<String, dynamic> item) {
final type = (item['Type'] as String?)?.toLowerCase();
return type == 'folder' || type == 'collectionfolder' || (type == null && item['IsFolder'] == true);
}
String _jellyfinFolderSortName(Map<String, dynamic> item) {
final raw = item['SortName'] as String? ?? item['Name'] as String? ?? '';
return raw.toLowerCase();
}
int _fallbackPageTotal({required int offset, required int itemCount, int? requestedSize}) {
if (requestedSize == null || requestedSize <= 0 || itemCount < requestedSize) {
@@ -127,15 +139,26 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
}
/// Jellyfin's `/Items/Filters` returns Genres / OfficialRatings / Tags /
/// Categories + values from `/Items/Filters` in a single call. Keys are
/// translated to Plex's filter naming so the existing filter-param map
/// round-trips through `_buildFilterParams` unchanged; the synthesised
/// `MediaFilter.key` is prefixed `jellyfin:` so FiltersBottomSheet can
/// recognise it as cached and skip the per-category value fetch.
/// Categories + values from `/Items/Filters` in a single call. The unwatched
/// boolean is synthetic because Jellyfin exposes it as an `/Items` query
/// filter, not a filter-listing category. Keys are translated to Plex's
/// filter naming so the existing filter-param map round-trips through
/// `_buildFilterParams` unchanged; the synthesised `MediaFilter.key` is
/// prefixed `jellyfin:` so FiltersBottomSheet can recognise it as cached and
/// skip the per-category value fetch.
@override
Future<LibraryFilterResult> fetchLibraryFiltersWithValues(String libraryId) async {
final filters = <MediaFilter>[
MediaFilter(
filter: 'unwatched',
filterType: 'boolean',
key: 'jellyfin:unwatched',
title: t.libraries.filterCategories.unwatched,
type: 'filter',
),
];
final data = await _safeFetchFilterPayload(libraryId);
if (data == null) return LibraryFilterResult.empty;
if (data == null) return LibraryFilterResult(filters: filters, cachedValues: const {});
List<String> stringList(Object? raw) {
if (raw is! List) return const [];
return raw.whereType<String>().where((s) => s.isNotEmpty).toList();
@@ -157,7 +180,6 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
'contentRating': t.libraries.filterCategories.contentRating,
'tag': t.libraries.filterCategories.tag,
};
final filters = <MediaFilter>[];
final values = <String, List<MediaFilterValue>>{};
for (final key in order) {
final entries = raw[key];
@@ -496,6 +518,68 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
return _mapItems(allRaw);
}
/// Jellyfin folder browsing mirrors Jellyfin Web/Findroid/Swiftfin: query
/// direct children of the library/folder with `Recursive=false`. This is
/// distinct from [fetchLibraryContent], which intentionally recurses through
/// a library to show metadata groupings like albums, artists, shows, etc.
Future<List<MediaItem>> fetchLibraryFolders(String libraryId) => _fetchFolderChildren(libraryId);
/// Contents of a Jellyfin folder. Kept separate from [fetchChildren] so the
/// folder tree can use direct-child semantics even for music libraries.
Future<List<MediaItem>> fetchFolderChildren(String folderId) => _fetchFolderChildren(folderId);
Future<List<MediaItem>> _fetchFolderChildren(String parentId) async {
final cacheKey = '/Items?ParentId=$parentId&Recursive=false&userId=${connection.userId}';
if (isOfflineMode) {
final cached = await cache.get(cacheServerId, cacheKey);
return cached == null ? const [] : _mapItems(_itemsArray(cached));
}
final allRaw = <Map<String, dynamic>>[];
var startIndex = 0;
int? totalRecordCount;
while (totalRecordCount == null || startIndex < totalRecordCount) {
final response = await _http.get(
'/Items',
queryParameters: {
'userId': connection.userId,
'ParentId': parentId,
'Recursive': 'false',
'StartIndex': '$startIndex',
'Limit': '$_childrenPageSize',
'EnableTotalRecordCount': 'true',
'SortBy': 'IsFolder,SortName',
'SortOrder': 'Ascending',
'Fields': _browseFields,
...jellyfinImageQueryParameters,
},
);
throwIfHttpError(response);
final data = response.data;
final page = _itemsArray(data);
allRaw.addAll(page);
if (data is Map<String, dynamic>) {
final rawTotal = data['TotalRecordCount'];
if (rawTotal is int) totalRecordCount = rawTotal;
}
if (page.isEmpty || page.length < _childrenPageSize) break;
startIndex += page.length;
}
allRaw.sort((a, b) {
final folderRank = (_isJellyfinFolderDto(a) ? 0 : 1).compareTo(_isJellyfinFolderDto(b) ? 0 : 1);
if (folderRank != 0) return folderRank;
return _jellyfinFolderSortName(a).compareTo(_jellyfinFolderSortName(b));
});
try {
await cache.put(cacheServerId, cacheKey, {'Items': allRaw, 'TotalRecordCount': allRaw.length});
} catch (e, st) {
appLogger.w('JellyfinClient.fetchFolderChildren cache write failed', error: e, stackTrace: st);
}
return _mapItems(allRaw);
}
/// All directly-playable descendants of [parentId] (Movies + Episodes),
/// recursively expanded. Used by the playback launcher so a collection
/// containing a Series plays its episodes instead of the unplayable
@@ -504,11 +588,27 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
/// since those preserve the container shape (Series rows, PlaylistItemId).
///
@override
Future<List<MediaItem>> fetchPlayableDescendants(String parentId) async {
Future<List<MediaItem>> fetchPlayableDescendants(String parentId) {
return _fetchAllPlayableDescendants(parentId, includeItemTypes: _playableDescendantTypes);
}
/// Playable video descendants for a folder browse row. This includes
/// Jellyfin's generic `Video` / `MusicVideo` kinds for home-video libraries,
/// but deliberately excludes `Audio` so folder playback never starts music.
Future<List<MediaItem>> fetchPlayableFolderDescendants(String parentId) {
return _fetchAllPlayableDescendants(parentId, includeItemTypes: _playableFolderDescendantTypes);
}
Future<List<MediaItem>> _fetchAllPlayableDescendants(String parentId, {required String includeItemTypes}) async {
final all = <MediaItem>[];
var start = 0;
while (true) {
final page = await fetchPlayableDescendantsPage(parentId, start: start, size: _pagedListPageSize);
final page = await _fetchPlayableDescendantsPage(
parentId,
start: start,
size: _pagedListPageSize,
includeItemTypes: includeItemTypes,
);
if (page.items.isEmpty) break;
all.addAll(page.items);
start += page.items.length;
@@ -523,6 +623,22 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
int? start,
int? size,
AbortController? abort,
}) {
return _fetchPlayableDescendantsPage(
parentId,
start: start,
size: size,
abort: abort,
includeItemTypes: _playableDescendantTypes,
);
}
Future<LibraryPage<MediaItem>> _fetchPlayableDescendantsPage(
String parentId, {
int? start,
int? size,
AbortController? abort,
required String includeItemTypes,
}) async {
final offset = start ?? 0;
final pageSize = size ?? _pagedListPageSize;
@@ -532,7 +648,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
'userId': connection.userId,
'ParentId': parentId,
'Recursive': 'true',
'IncludeItemTypes': 'Movie,Episode',
'IncludeItemTypes': includeItemTypes,
'StartIndex': offset.toString(),
'Limit': pageSize.toString(),
'Fields': _browseFields,
@@ -89,7 +89,7 @@ mixin _JellyfinImageDownloadMethods on MediaServerCacheMixin {
if (raw is! Map<String, dynamic>) continue;
if (raw['Type'] != 'Subtitle') continue;
final fields = parseJellyfinStreamFields(raw);
if (!fields.isExternal) continue;
if (!fields.isExternalFile) continue;
final index = raw['Index'];
if (index is! int) continue;
final codec = fields.codec?.toLowerCase();
@@ -150,7 +150,7 @@ mixin _JellyfinPlaybackMethods on MediaServerCacheMixin {
);
var effectiveSourceId = bundle.selectedSourceId;
var effectiveContainer = bundle.container;
var externalSubtitles = _buildExternalSubtitles(metadata.id, effectiveSourceId, mediaInfo);
var includeExternalSubtitleDelivery = false;
String? videoUrl;
String? playSessionId;
@@ -187,7 +187,6 @@ mixin _JellyfinPlaybackMethods on MediaServerCacheMixin {
chapters: bundle.chapters,
trickplay: bundle.trickplay,
);
externalSubtitles = _buildExternalSubtitles(metadata.id, effectiveSourceId, mediaInfo);
}
final negotiatedPlaySessionId = negotiation['PlaySessionId'];
@@ -208,6 +207,7 @@ mixin _JellyfinPlaybackMethods on MediaServerCacheMixin {
videoUrl = _withApiKey(transcodingUrl);
playMethod = 'Transcode';
isTranscoding = true;
includeExternalSubtitleDelivery = true;
} else if (directStreamUrl is String && directStreamUrl.isNotEmpty) {
capturePlaySessionId(directStreamUrl);
videoUrl = _withApiKey(directStreamUrl);
@@ -224,6 +224,12 @@ mixin _JellyfinPlaybackMethods on MediaServerCacheMixin {
final effectiveAudioStreamId = _resolveJellyfinAudioStreamId(requestedAudioStreamId, mediaInfo);
mediaInfo = _withSelectedJellyfinAudioStream(mediaInfo, effectiveAudioStreamId);
final externalSubtitles = _buildExternalSubtitles(
metadata.id,
effectiveSourceId,
mediaInfo,
includeExternalDelivery: includeExternalSubtitleDelivery,
);
final pinnedSourceId = bundle.pinnedSourceIdForItem(metadata.id);
videoUrl ??= buildDirectStreamUrl(metadata.id, container: effectiveContainer, mediaSourceId: pinnedSourceId);
@@ -316,10 +322,15 @@ mixin _JellyfinPlaybackMethods on MediaServerCacheMixin {
return path.startsWith('/') ? path : '/$path';
}
List<SubtitleTrack> _buildExternalSubtitles(String itemId, String? mediaSourceId, MediaSourceInfo mediaInfo) {
List<SubtitleTrack> _buildExternalSubtitles(
String itemId,
String? mediaSourceId,
MediaSourceInfo mediaInfo, {
bool includeExternalDelivery = false,
}) {
final externalSubtitles = <SubtitleTrack>[];
for (final track in mediaInfo.subtitleTracks) {
if (!track.isExternal) continue;
if (!track.isExternalFile && !(includeExternalDelivery && track.usesExternalDelivery)) continue;
final path = track.key ?? _jellyfinSubtitleFallbackPath(itemId, mediaSourceId, track);
if (path == null) continue;
// Jellyfin's subtitle URL is a path relative to baseUrl; build the
+1 -1
View File
@@ -424,7 +424,7 @@ class JellyfinMappers {
channels: f.channels,
frameRate: f.frameRate,
forced: f.isForced,
sidecarPath: f.isExternal ? f.deliveryUrl : null,
sidecarPath: f.isExternalFile ? f.deliveryUrl : null,
),
);
}
@@ -169,6 +169,7 @@ List<MediaSubtitleTrack> _withDefaultSubtitleSelection(List<MediaSubtitleTrack>
forced: track.forced,
key: track.key,
external: track.external,
usesExternalDelivery: track.usesExternalDelivery,
),
];
}
+70 -1
View File
@@ -11,10 +11,11 @@ import '../media/play_queue.dart';
import '../providers/multi_server_provider.dart';
import '../providers/playback_state_provider.dart';
import '../utils/snackbar_helper.dart';
import 'jellyfin_client.dart';
import 'media_list_playback_launcher.dart';
import 'playlist_items_loader.dart';
/// Backend-neutral launcher for Jellyfin collections and playlists.
/// Backend-neutral launcher for Jellyfin collections, playlists, and folders.
///
/// Jellyfin has no server-side queue resource — the client fetches
/// children (collection) or playlist items, applies shuffle locally,
@@ -123,6 +124,74 @@ class JellyfinSequentialLauncher extends MediaListPlaybackLauncher {
);
}
/// Launch playback from a Jellyfin folder row. Jellyfin has no server-side
/// queue resource, so folders use the same local queue path as collections.
/// The client query is video-only; music-only folders return [PlayQueueEmpty].
Future<PlayQueueResult> launchFromFolder({
required MediaItem folder,
required bool shuffle,
bool showLoadingIndicator = true,
}) async {
final serverId = folder.serverId;
if (serverId == null) {
return PlayQueueError(Exception('Item is missing serverId'));
}
return executeWithLoading(
context: context,
showLoading: showLoadingIndicator,
actionLabel: shuffle ? t.common.shuffle : t.common.play,
execute: (dismissLoading) async {
final client = clientForTesting ?? _resolveClient(serverId);
if (client == null) {
await dismissLoading();
if (context.mounted) {
showErrorSnackBar(context, t.errors.noClientAvailable);
}
return PlayQueueError(Exception('No client for server $serverId'));
}
final fetched = client is JellyfinClient
? await client.fetchPlayableFolderDescendants(folder.id)
: await client.fetchPlayableDescendants(folder.id);
var items = fetched.where((item) => item.kind.isVideo).map((item) {
return item.copyWith(
serverId: item.serverId ?? serverId,
serverName: item.serverName ?? folder.serverName,
libraryId: item.libraryId ?? folder.libraryId,
libraryTitle: item.libraryTitle ?? folder.libraryTitle,
);
}).toList();
if (items.isEmpty) return const PlayQueueEmpty();
if (shuffle) {
items = List.of(items)..shuffle(Random());
}
await dismissLoading();
if (!context.mounted && navigateForTesting == null) {
return const PlayQueueError('Context not mounted');
}
final playbackState = playbackStateForTesting ?? context.read<PlaybackStateProvider>();
return launchLocalQueuePlayback(
context: context,
playbackState: playbackState,
queue: LocalPlayQueue(
id: 'jellyfin:folder:${folder.id}',
items: items,
currentIndex: 0,
shuffled: shuffle,
backendId: client.backend.id,
),
contextKey: folder.id,
navigateForTesting: navigateForTesting,
);
},
);
}
@override
Future<PlayQueueResult> launchShuffledShow({required MediaItem metadata, bool showLoadingIndicator = true}) async {
final kind = metadata.kind;
@@ -38,10 +38,10 @@ class PlayQueueError extends PlayQueueResult {
/// Backend-neutral playback launcher for collections and playlists.
///
/// Plex uses server-side `/playQueues` (one round trip, server tracks
/// queue state). Jellyfin has no equivalent — the client builds an
/// in-memory queue from `fetchChildren` (collection) or
/// `fetchPlaylistItems` (playlist). [MediaListPlaybackLauncher.forItem]
/// picks the implementation by inspecting the item's backend.
/// queue state). Jellyfin has no equivalent — the concrete Jellyfin launcher
/// builds an in-memory queue from playable descendants or playlist items.
/// [MediaListPlaybackLauncher.forItem] picks the implementation by inspecting
/// the item's backend.
abstract class MediaListPlaybackLauncher {
/// Launch playback from a collection (a [MediaItem] with
/// `kind == MediaKind.collection`) or a [MediaPlaylist].
+3 -3
View File
@@ -26,9 +26,9 @@ export 'media_list_playback_launcher.dart' show PlayQueueResult, PlayQueueSucces
/// 4. Handling errors with appropriate feedback
///
/// Implements [MediaListPlaybackLauncher.launchFromCollectionOrPlaylist] for
/// the backend-neutral entry point. Plex-only flows
/// ([launchFromPlaylistItem], [launchShuffledShow], [launchFromFolder]) live
/// directly on this class because they have no Jellyfin equivalent.
/// the backend-neutral entry point. Plex-only flows such as
/// [launchFromPlaylistItem] live directly on this class because they have no
/// Jellyfin equivalent.
class PlexPlayQueueLauncher extends MediaListPlaybackLauncher {
final BuildContext context;
final PlexClient client;
+2 -1
View File
@@ -480,7 +480,8 @@ class SyncRuleExecutor {
p != null &&
(p.status == DownloadStatus.completed ||
p.status == DownloadStatus.downloading ||
p.status == DownloadStatus.queued);
p.status == DownloadStatus.queued ||
p.status == DownloadStatus.paused);
Future<List<ConnectivityResult>> _readConnectivity() async {
try {
@@ -0,0 +1,20 @@
import 'package:flutter/services.dart';
import '../utils/platform_detector.dart';
class TvosSystemNavigationService {
static const BasicMessageChannel<Object?> _channel = BasicMessageChannel<Object?>(
'flutter/tvos_system_navigation',
JSONMessageCodec(),
);
static bool? _menuPassthroughEnabled;
static Future<void> setMenuPassthroughEnabled(bool enabled) async {
if (!PlatformDetector.isAppleTV()) return;
if (_menuPassthroughEnabled == enabled) return;
_menuPassthroughEnabled = enabled;
await _channel.send({'menuPassthroughEnabled': enabled});
}
}
+5 -1
View File
@@ -191,8 +191,9 @@ class OverlaySheetController {
/// and skip their own back handling when a sheet is open.
class OverlaySheetHost extends StatefulWidget {
final Widget child;
final ValueChanged<bool>? onOpenChanged;
const OverlaySheetHost({super.key, required this.child});
const OverlaySheetHost({super.key, required this.child, this.onOpenChanged});
@override
State<OverlaySheetHost> createState() => _OverlaySheetHostState();
@@ -264,6 +265,7 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
bool showDragHandle = false,
}) {
// If already open, close first (instant)
final wasOpen = _isOpen;
if (_isOpen) {
for (final entry in _pageStack) {
if (!entry.completer.isCompleted) {
@@ -291,6 +293,7 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
_dragOffset = 0;
_isDragging = false;
});
if (!wasOpen) widget.onOpenChanged?.call(true);
BackKeyUpSuppressor.clearSuppression();
_animationController.forward(from: 0);
@@ -351,6 +354,7 @@ class _OverlaySheetHostState extends State<OverlaySheetHost> with SingleTickerPr
_isDragging = false;
_sheetHorizontalAnchor = null;
});
widget.onOpenChanged?.call(false);
// Clear stale back-key flags. handleBackKeyAction sets
// markClosedViaBackKey() expecting a route pop, but the overlay
// doesn't pop a route. Without clearing, the flag leaks into the
+10 -2
View File
@@ -1059,11 +1059,19 @@ class TvBrowseRailState extends State<TvBrowseRail> {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AppIcon(Symbols.arrow_forward_rounded, fill: 1, size: 42 * scale, color: Colors.white),
AppIcon(
Symbols.arrow_forward_rounded,
fill: 1,
size: 42 * scale,
color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.72),
),
SizedBox(height: 6 * scale),
Text(
t.common.viewAll,
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.72),
fontWeight: FontWeight.w700,
),
),
],
),
+8 -5
View File
@@ -182,6 +182,7 @@ class TvSpotlightBackground extends StatelessWidget {
Widget _buildInfo(BuildContext context, MediaItem media) {
final scale = _scale(context);
final colorScheme = Theme.of(context).colorScheme;
final shouldHideSpoiler = hideSpoilers && media.shouldHideSpoiler;
final summary = shouldHideSpoiler ? null : media.summary;
final title = media.grandparentTitle ?? media.displayTitle;
@@ -200,7 +201,7 @@ class TvSpotlightBackground extends StatelessWidget {
maxLines: compact ? 3 : 4,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Colors.white.withValues(alpha: 0.78),
color: colorScheme.onSurface.withValues(alpha: 0.78),
fontSize: _summaryFontSize(scale),
height: compact ? 1.34 : 1.45,
),
@@ -212,7 +213,7 @@ class TvSpotlightBackground extends StatelessWidget {
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Colors.white.withValues(alpha: 0.72),
color: colorScheme.onSurface.withValues(alpha: 0.72),
fontSize: _summaryFontSize(scale),
height: compact ? 1.34 : 1.45,
),
@@ -285,19 +286,21 @@ class TvSpotlightBackground extends StatelessWidget {
Widget _buildTitle(BuildContext context, String title) {
final scale = _scale(context);
final colorScheme = Theme.of(context).colorScheme;
return FittingTitleText(
title,
style: Theme.of(context).textTheme.displaySmall?.copyWith(
color: Colors.white,
color: colorScheme.onSurface,
fontSize: _titleFontSize(scale),
fontWeight: FontWeight.w800,
shadows: [Shadow(color: Colors.black.withValues(alpha: 0.5), blurRadius: 12)],
shadows: [Shadow(color: colorScheme.surface.withValues(alpha: 0.8), blurRadius: 12)],
),
);
}
Widget _buildMetadataLine(BuildContext context, MediaItem media) {
final scale = _scale(context);
final colorScheme = Theme.of(context).colorScheme;
final episodeLabel = formatSeasonEpisodeLabel(media.parentIndex, media.index);
final parts = [
if (media.isEpisode && episodeLabel != null) episodeLabel,
@@ -315,7 +318,7 @@ class TvSpotlightBackground extends StatelessWidget {
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.white,
color: colorScheme.onSurface,
fontSize: _metadataFontSize(scale),
fontWeight: FontWeight.w700,
letterSpacing: 0.1,
+278 -75
View File
@@ -22,11 +22,13 @@ Future<void> showTvVirtualKeyboard({
ValueChanged<String>? onSubmitted,
VoidCallback? onAction,
}) {
if (!PlatformDetector.isAppleTV()) return Future.value();
if (!PlatformDetector.isTV()) return Future.value();
return showDialog<void>(
context: context,
barrierDismissible: true,
barrierColor: Colors.black.withValues(alpha: 0.10),
useSafeArea: false,
builder: (context) => _TvVirtualKeyboardDialog(
controller: controller,
hintText: hintText,
@@ -43,7 +45,7 @@ Future<void> showTvVirtualKeyboard({
);
}
enum _TvKeyType { spacer, character, shift, space, newline, backspace, clear, cancel, done }
enum _TvKeyType { spacer, character, shift, symbols, space, newline, backspace, clear, cancel, done }
class _TvKey {
final String label;
@@ -88,16 +90,14 @@ class _TvVirtualKeyboardDialog extends StatefulWidget {
}
class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with MountedSetStateMixin {
static const double _keySize = 60;
static const double _keyGap = 6;
static const double _rowGap = 6;
final _focusNode = FocusNode(debugLabel: 'TvVirtualKeyboard');
int _row = 0;
int _column = 0;
bool _shiftEnabled = false;
bool _symbolsPage = false;
List<List<_TvKey>> get _rows => _buildRows();
List<List<_TvKey>> get _rows => _symbolsPage ? _buildSymbolRows() : _buildMainRows();
int get _gridColumnCount => _isNumberKeyboard ? 3 : 12;
@override
void initState() {
@@ -130,7 +130,7 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
return type?.index == TextInputType.multiline.index || (widget.maxLines != null && widget.maxLines != 1);
}
List<List<_TvKey>> _buildRows() {
List<List<_TvKey>> _buildMainRows() {
if (_isNumberKeyboard) {
return [
_characters('123'),
@@ -156,6 +156,7 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
const _TvKey.character('_'),
const _TvKey.character('/'),
const _TvKey.character(':'),
const _TvKey.character('='),
_isMultiline
? const _TvKey.action('Line', _TvKeyType.newline, icon: Icons.keyboard_return_rounded)
: const _TvKey.character('&'),
@@ -165,10 +166,11 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
];
return [
[const _TvKey.spacer(), ..._characters('1234567890')],
[const _TvKey.spacer(), ..._characters('qwertyuiop')],
[const _TvKey.spacer(), ..._characters('asdfghjkl'), const _TvKey.character("'")],
[const _TvKey.spacer(), ..._characters('1234567890'), const _TvKey.spacer()],
[const _TvKey.spacer(), ..._characters('qwertyuiop'), const _TvKey.spacer()],
[const _TvKey.spacer(), ..._characters('asdfghjkl'), const _TvKey.character("'"), const _TvKey.spacer()],
[
const _TvKey.action('', _TvKeyType.symbols, icon: Icons.functions_rounded),
_TvKey.action('Shift', _TvKeyType.shift, icon: Symbols.shift),
..._characters('zxcvbnm.-'),
const _TvKey.action('Del', _TvKeyType.backspace, icon: Icons.backspace_outlined),
@@ -177,6 +179,43 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
];
}
List<List<_TvKey>> _buildSymbolRows() {
return [
[
const _TvKey.action('ABC', _TvKeyType.symbols),
..._symbols(['!', '?', r'$', '%', '^', '*', '+', '=', '~']),
const _TvKey.action('Del', _TvKeyType.backspace, icon: Icons.backspace_outlined),
const _TvKey.spacer(),
],
[
const _TvKey.spacer(),
..._symbols(['`', r'\', '|', ';', ':', '"', "'", '<', '>']),
const _TvKey.spacer(),
const _TvKey.spacer(),
],
[
const _TvKey.spacer(),
..._symbols(['[', ']', '{', '}', '(', ')', ',', '.', '-']),
const _TvKey.spacer(),
const _TvKey.spacer(),
],
[
const _TvKey.spacer(),
const _TvKey.spacer(),
const _TvKey.action('Space', _TvKeyType.space, icon: Icons.space_bar_rounded),
const _TvKey.character('@'),
const _TvKey.character('#'),
const _TvKey.character('_'),
const _TvKey.character('/'),
_TvKey.action(t.common.clear, _TvKeyType.clear, icon: Icons.clear_all_rounded),
_TvKey.action(t.common.cancel, _TvKeyType.cancel, icon: Icons.close_rounded),
_TvKey.action(_doneLabel(), _TvKeyType.done, icon: _doneIcon()),
const _TvKey.spacer(),
const _TvKey.spacer(),
],
];
}
List<_TvKey> _characters(String chars) {
return chars
.split('')
@@ -188,6 +227,10 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
.toList(growable: false);
}
List<_TvKey> _symbols(List<String> symbols) {
return symbols.map((symbol) => _TvKey.character(symbol)).toList(growable: false);
}
String _doneLabel() {
switch (widget.textInputAction) {
case TextInputAction.search:
@@ -223,10 +266,16 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
}
if (event is KeyDownEvent || event is KeyRepeatEvent) {
if (key == LogicalKeyboardKey.backspace || key == LogicalKeyboardKey.delete) {
if (_handlePhysicalKeyboardTextInput(event)) return KeyEventResult.handled;
if (key == LogicalKeyboardKey.backspace) {
_backspace();
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.delete) {
_deleteForward();
return KeyEventResult.handled;
}
if (event.isPhysicalKeyboardEnter) {
if (_isMultiline) {
@@ -269,6 +318,43 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
return KeyEventResult.handled;
}
bool _handlePhysicalKeyboardTextInput(KeyEvent event) {
if (!event.isPhysicalKeyboardEvent) return false;
final key = event.logicalKey;
if (key == LogicalKeyboardKey.backspace) {
_backspace();
_dismissForPhysicalKeyboardInput();
return true;
}
if (key == LogicalKeyboardKey.delete) {
_deleteForward();
_dismissForPhysicalKeyboardInput();
return true;
}
if (event.isPhysicalKeyboardEnter && _isMultiline) {
_insert('\n');
_dismissForPhysicalKeyboardInput();
return true;
}
final character = event.character;
if (character != null && character.isNotEmpty && !key.isNavigationKey && !_isControlCharacter(character)) {
_insert(character);
_dismissForPhysicalKeyboardInput();
return true;
}
return false;
}
bool _isControlCharacter(String text) {
return text.runes.every((codeUnit) => codeUnit < 0x20 || codeUnit == 0x7f);
}
void _dismissForPhysicalKeyboardInput() {
Navigator.of(context).pop();
}
void _moveHorizontal(int delta) {
final nextColumn = _nextFocusableColumn(_row, _column + delta, delta);
if (nextColumn == null) return;
@@ -331,6 +417,9 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
case _TvKeyType.shift:
setState(() => _shiftEnabled = !_shiftEnabled);
return;
case _TvKeyType.symbols:
_toggleSymbolsPage();
return;
case _TvKeyType.space:
_insert(' ');
return;
@@ -352,6 +441,15 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
}
}
void _toggleSymbolsPage() {
setState(() {
_symbolsPage = !_symbolsPage;
final rows = _rows;
_row = _row.clamp(0, rows.length - 1).toInt();
_column = _nearestFocusableColumn(_row, _column);
});
}
void _submit() {
final text = widget.controller.text;
final onSubmitted = widget.onSubmitted;
@@ -368,13 +466,7 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
void _insert(String text) {
final value = widget.controller.value;
final selection = value.selection;
final start = selection.isValid
? (selection.start < selection.end ? selection.start : selection.end)
: value.text.length;
final end = selection.isValid
? (selection.start > selection.end ? selection.start : selection.end)
: value.text.length;
final (:start, :end) = _selectionRangeForEdit(value);
final newText = value.text.replaceRange(start, end, text);
_replace(
value.copyWith(
@@ -387,13 +479,7 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
void _backspace() {
final value = widget.controller.value;
final selection = value.selection;
final start = selection.isValid
? (selection.start < selection.end ? selection.start : selection.end)
: value.text.length;
final end = selection.isValid
? (selection.start > selection.end ? selection.start : selection.end)
: value.text.length;
final (:start, :end) = _selectionRangeForEdit(value);
if (start != end) {
_replace(
@@ -415,6 +501,43 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
);
}
void _deleteForward() {
final value = widget.controller.value;
final (:start, :end) = _selectionRangeForEdit(value);
if (start != end) {
_replace(
value.copyWith(
text: value.text.replaceRange(start, end, ''),
selection: TextSelection.collapsed(offset: start),
composing: TextRange.empty,
),
);
return;
}
if (start >= value.text.length) return;
_replace(
value.copyWith(
text: value.text.replaceRange(start, start + 1, ''),
selection: TextSelection.collapsed(offset: start),
composing: TextRange.empty,
),
);
}
({int start, int end}) _selectionRangeForEdit(TextEditingValue value) {
final selection = value.selection;
if (!selection.isValid) return (start: value.text.length, end: value.text.length);
if (selection.isCollapsed && selection.baseOffset == 0 && value.text.isNotEmpty) {
return (start: value.text.length, end: value.text.length);
}
return (
start: selection.start < selection.end ? selection.start : selection.end,
end: selection.start > selection.end ? selection.start : selection.end,
);
}
void _replace(TextEditingValue nextValue) {
final previousValue = widget.controller.value;
var formattedValue = nextValue;
@@ -427,100 +550,138 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
formattedValue = formatter.formatEditUpdate(previousValue, formattedValue);
}
widget.controller.value = formattedValue;
widget.onChanged?.call(formattedValue.text);
if (formattedValue.text != previousValue.text) {
widget.onChanged?.call(formattedValue.text);
}
}
@override
Widget build(BuildContext context) {
final media = MediaQuery.of(context);
final metrics = _metricsFor(media.size);
final colorScheme = Theme.of(context).colorScheme;
final text = widget.controller.text;
return Dialog(
insetPadding: const EdgeInsets.symmetric(horizontal: 56, vertical: 32),
key: const Key('tv_virtual_keyboard_dialog'),
alignment: Alignment.bottomCenter,
insetPadding: EdgeInsets.only(
left: metrics.edgeInset,
right: metrics.edgeInset,
top: media.padding.top + 48,
bottom: media.padding.bottom + metrics.bottomInset,
),
backgroundColor: Colors.transparent,
elevation: 0,
child: Focus(
focusNode: _focusNode,
onKeyEvent: _handleKey,
child: Container(
constraints: const BoxConstraints(maxWidth: 860),
padding: const EdgeInsets.all(14),
key: const Key('tv_virtual_keyboard_panel'),
constraints: BoxConstraints(maxWidth: metrics.panelWidth),
padding: EdgeInsets.all(metrics.panelPadding),
decoration: BoxDecoration(
color: colorScheme.surface.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(28),
borderRadius: BorderRadius.circular(metrics.panelRadius),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildPreview(context, text),
const SizedBox(height: 12),
for (var row = 0; row < _rows.length; row++) ...[
_buildRow(context, row),
if (row != _rows.length - 1) const SizedBox(height: _rowGap),
child: SizedBox(
width: metrics.gridWidth,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildPreview(context, text, metrics),
SizedBox(height: metrics.previewGap),
for (var row = 0; row < _rows.length; row++) ...[
_buildRow(context, row, metrics),
if (row != _rows.length - 1) SizedBox(height: metrics.rowGap),
],
],
],
),
),
),
),
);
}
Widget _buildPreview(BuildContext context, String text) {
_TvKeyboardMetrics _metricsFor(Size size) {
final columns = _gridColumnCount;
var keySize = (size.height * 0.061).clamp(36.0, 52.0).toDouble();
var keyGap = (keySize * 0.09).clamp(3.0, 6.0).toDouble();
var panelPadding = (keySize * 0.24).clamp(8.0, 14.0).toDouble();
final edgeInset = (size.width * 0.035).clamp(20.0, 56.0).toDouble();
final availableWidth = size.width - edgeInset * 2 - panelPadding * 2;
final maxKeySize = (availableWidth - keyGap * (columns - 1)) / columns;
final widthBoundKeySize = maxKeySize.clamp(24.0, 52.0).toDouble();
if (keySize > widthBoundKeySize) keySize = widthBoundKeySize;
keyGap = (keySize * 0.09).clamp(3.0, 6.0).toDouble();
panelPadding = (keySize * 0.24).clamp(8.0, 14.0).toDouble();
final gridWidth = keySize * columns + keyGap * (columns - 1);
return _TvKeyboardMetrics(
keySize: keySize,
keyGap: keyGap,
rowGap: keyGap,
panelPadding: panelPadding,
edgeInset: edgeInset,
bottomInset: (size.height * 0.025).clamp(12.0, 28.0).toDouble(),
gridWidth: gridWidth,
panelWidth: gridWidth + panelPadding * 2,
panelRadius: (keySize * 0.55).clamp(18.0, 28.0).toDouble(),
keyRadius: (keySize * 0.28).clamp(10.0, 16.0).toDouble(),
previewHeight: (_isMultiline ? keySize * 1.45 : keySize).clamp(40.0, 76.0).toDouble(),
previewGap: (keySize * 0.18).clamp(6.0, 12.0).toDouble(),
previewRadius: (keySize * 0.36).clamp(12.0, 18.0).toDouble(),
iconSize: (keySize * 0.58).clamp(20.0, 30.0).toDouble(),
keyFontSize: (keySize * 0.52).clamp(17.0, 26.0).toDouble(),
);
}
Widget _buildPreview(BuildContext context, String text, _TvKeyboardMetrics metrics) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final isEmpty = text.isEmpty;
final displayText = widget.obscureText && !isEmpty ? List.filled(text.length, '*').join() : text;
final previewText = isEmpty ? (widget.hintText ?? '') : displayText;
final multiline = _isMultiline;
final style = (multiline ? theme.textTheme.titleMedium : theme.textTheme.titleLarge)?.copyWith(
color: isEmpty ? colorScheme.onSurfaceVariant : colorScheme.onSurface,
fontSize: (metrics.keyFontSize * 1.08).clamp(16.0, 24.0).toDouble(),
);
return Container(
height: multiline ? 86 : 60,
height: metrics.previewHeight,
alignment: Alignment.centerLeft,
padding: const EdgeInsets.symmetric(horizontal: 16),
padding: EdgeInsets.symmetric(horizontal: metrics.keySize * 0.30),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(18),
borderRadius: BorderRadius.circular(metrics.previewRadius),
),
child: multiline
? SingleChildScrollView(
reverse: true,
child: Text(
previewText,
maxLines: 3,
style: theme.textTheme.titleLarge?.copyWith(
color: isEmpty ? colorScheme.onSurfaceVariant : colorScheme.onSurface,
),
),
)
? SingleChildScrollView(reverse: true, child: Text(previewText, maxLines: 3, style: style))
: SingleChildScrollView(
scrollDirection: Axis.horizontal,
reverse: true,
child: Text(
previewText,
maxLines: 1,
style: theme.textTheme.headlineSmall?.copyWith(
color: isEmpty ? colorScheme.onSurfaceVariant : colorScheme.onSurface,
),
),
child: Text(previewText, maxLines: 1, style: style),
),
);
}
Widget _buildRow(BuildContext context, int row) {
Widget _buildRow(BuildContext context, int row, _TvKeyboardMetrics metrics) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (var column = 0; column < _rows[row].length; column++) ...[
_buildKey(context, _rows[row][column], row, column),
if (column != _rows[row].length - 1) const SizedBox(width: _keyGap),
_buildKey(context, _rows[row][column], row, column, metrics),
if (column != _rows[row].length - 1) SizedBox(width: metrics.keyGap),
],
],
);
}
Widget _buildKey(BuildContext context, _TvKey key, int row, int column) {
Widget _buildKey(BuildContext context, _TvKey key, int row, int column, _TvKeyboardMetrics metrics) {
if (key.type == _TvKeyType.spacer) {
return const SizedBox(width: _keySize, height: _keySize);
return SizedBox(width: metrics.keySize, height: metrics.keySize);
}
final colorScheme = Theme.of(context).colorScheme;
@@ -548,23 +709,27 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
},
child: AnimatedContainer(
duration: const Duration(milliseconds: 120),
width: _keySize,
height: _keySize,
width: metrics.keySize,
height: metrics.keySize,
alignment: Alignment.center,
decoration: BoxDecoration(color: background, borderRadius: BorderRadius.circular(16)),
decoration: BoxDecoration(color: background, borderRadius: BorderRadius.circular(metrics.keyRadius)),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: _buildKeyContent(context, key, foreground),
padding: EdgeInsets.symmetric(horizontal: metrics.keySize * 0.04),
child: _buildKeyContent(context, key, foreground, metrics),
),
),
),
);
}
Widget _buildKeyContent(BuildContext context, _TvKey key, Color foreground) {
Widget _buildKeyContent(BuildContext context, _TvKey key, Color foreground, _TvKeyboardMetrics metrics) {
final icon = key.icon;
if (icon != null) {
return Icon(icon, color: foreground, size: key.type == _TvKeyType.space ? 34 : 30);
return Icon(
icon,
color: foreground,
size: key.type == _TvKeyType.space ? metrics.iconSize * 1.12 : metrics.iconSize,
);
}
return FittedBox(
@@ -572,8 +737,46 @@ class _TvVirtualKeyboardDialogState extends State<_TvVirtualKeyboardDialog> with
child: Text(
key.label,
maxLines: 1,
style: Theme.of(context).textTheme.titleLarge?.copyWith(color: foreground, fontWeight: FontWeight.w800),
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(color: foreground, fontSize: metrics.keyFontSize, fontWeight: FontWeight.w800),
),
);
}
}
class _TvKeyboardMetrics {
final double keySize;
final double keyGap;
final double rowGap;
final double panelPadding;
final double edgeInset;
final double bottomInset;
final double gridWidth;
final double panelWidth;
final double panelRadius;
final double keyRadius;
final double previewHeight;
final double previewGap;
final double previewRadius;
final double iconSize;
final double keyFontSize;
const _TvKeyboardMetrics({
required this.keySize,
required this.keyGap,
required this.rowGap,
required this.panelPadding,
required this.edgeInset,
required this.bottomInset,
required this.gridWidth,
required this.panelWidth,
required this.panelRadius,
required this.keyRadius,
required this.previewHeight,
required this.previewGap,
required this.previewRadius,
required this.iconSize,
required this.keyFontSize,
});
}
+4 -4
View File
@@ -89,8 +89,8 @@ packages:
dependency: "direct main"
description:
path: "."
ref: "4c965996210e408465e3c8b66e63ab4a659a62f9"
resolved-ref: "4c965996210e408465e3c8b66e63ab4a659a62f9"
ref: b4d36f88bb365faaf308ff26be7ade49bbaec859
resolved-ref: b4d36f88bb365faaf308ff26be7ade49bbaec859
url: "https://github.com/edde746/background_downloader"
source: git
version: "9.5.4"
@@ -1473,10 +1473,10 @@ packages:
dependency: "direct main"
description:
name: win_http
sha256: efbfec044d43665e271b2c51d40864275d055b28eda1e9feddb42d884ae982df
sha256: a50a14f1bf32bc5c9b39add9baa01658b97146b21de25237810ca6b850a6704e
url: "https://pub.dev"
source: hosted
version: "0.2.0"
version: "0.2.1"
window_manager:
dependency: "direct main"
description:
+3 -3
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex and Jellyfin client for Flutter"
publish_to: "none"
version: 2.2.1+101
version: 2.3.0+102
environment:
sdk: ">=3.12.0 <4.0.0"
@@ -59,7 +59,7 @@ dependencies:
background_downloader:
git:
url: https://github.com/edde746/background_downloader
ref: 4c965996210e408465e3c8b66e63ab4a659a62f9
ref: b4d36f88bb365faaf308ff26be7ade49bbaec859
sentry_flutter:
git:
url: https://github.com/edde746/sentry-dart
@@ -72,7 +72,7 @@ dependencies:
ref: 9e150f7
cupertino_http: ^2.4.0
cronet_http: ^1.6.0
win_http: ^0.2.0
win_http: ^0.2.1
collection: ^1.18.0
freezed_annotation: ^3.1.0
xml: ^6.6.1
+17 -1
View File
@@ -426,6 +426,22 @@ class MpvPlayerCoreBase: NSObject {
}
}
/// PiP presents the AVSampleBufferDisplayLayer directly, so subtitles must
/// be composited into the video samples instead of the inline OSD layer.
func setPipSubtitleCompositing(_ enabled: Bool) {
#if os(iOS)
let value = enabled ? "yes" : "no"
setRawStringPropertyAsync("avfoundation-pip-composite-osd", value: value) { result in
if case .failure(let error) = result {
print(
"[MpvPlayerCore] Failed to set PiP subtitle compositing "
+ "to \(value): \(error.localizedDescription)"
)
}
}
#endif
}
func getPropertyAsync(_ name: String, completion: @escaping (Result<String?, Error>) -> Void) {
guard let mpv else {
completion(.success(nil))
@@ -611,7 +627,7 @@ class MpvPlayerCoreBase: NSObject {
private func isManagedRendererProperty(_ name: String) -> Bool {
name == "vo" || name == "wid" || name == "gpu-api" || name == "gpu-context"
|| name == "avfoundation-composite-osd"
|| name == "avfoundation-composite-osd" || name == "avfoundation-pip-composite-osd"
}
private func updateVideoGravityIfNeeded(name: String, value: String) {
+18
View File
@@ -100,6 +100,24 @@ void main() {
expect(movie.heroArtCandidates(containerAspectRatio: 16 / 9), ['/art', '/square']);
expect(movie.heroArt(containerAspectRatio: 16 / 9), '/art');
});
test('episodes prefer show art before episode art for wide hero containers', () {
final episode = MediaItem(
id: 'e1',
backend: MediaBackend.plex,
kind: MediaKind.episode,
title: 'Episode',
grandparentTitle: 'Show',
grandparentArtPath: '/show-art',
artPath: '/episode-art',
backgroundSquarePath: '/square',
serverId: 's1',
);
expect(episode.heroArtCandidates(containerAspectRatio: 16 / 9), ['/show-art', '/episode-art', '/square']);
expect(episode.heroArt(containerAspectRatio: 16 / 9), '/show-art');
expect(episode.heroArtCandidates(containerAspectRatio: 1.0), ['/square', '/show-art', '/episode-art']);
});
});
group('MediaItem.isPartiallyWatched', () {
@@ -415,6 +415,22 @@ void main() {
p.dispose();
});
test('queueDownload leaves paused downloads paused instead of re-queueing them', () async {
final p = DownloadProvider.forTesting(downloadManager: downloadManager, database: db);
await p.ensureInitialized();
p.debugSeedState(
downloads: {'srv:1': const DownloadProgress(globalKey: 'srv:1', status: DownloadStatus.paused)},
metadata: {'srv:1': movie},
);
final count = await p.queueDownload(movie, _ThrowingClient());
expect(count, 0);
expect(p.getProgress('srv:1')?.status, DownloadStatus.paused);
p.dispose();
});
test('deleteDownload removes only active-profile ownership when another owner remains', () async {
await db.addDownloadOwner(profileId: 'test-profile', globalKey: 'srv:1');
await db.addDownloadOwner(profileId: 'profile-b', globalKey: 'srv:1');
@@ -5,6 +5,57 @@ import 'package:plezy/media/library_first_character.dart';
import 'package:plezy/screens/libraries/alpha_jump_bar.dart';
void main() {
const alphabetCharacters = [
LibraryFirstCharacter(key: '#', title: '#', size: 1),
LibraryFirstCharacter(key: 'A', title: 'A', size: 1),
LibraryFirstCharacter(key: 'B', title: 'B', size: 1),
LibraryFirstCharacter(key: 'C', title: 'C', size: 1),
LibraryFirstCharacter(key: 'D', title: 'D', size: 1),
LibraryFirstCharacter(key: 'E', title: 'E', size: 1),
LibraryFirstCharacter(key: 'F', title: 'F', size: 1),
LibraryFirstCharacter(key: 'G', title: 'G', size: 1),
LibraryFirstCharacter(key: 'H', title: 'H', size: 1),
LibraryFirstCharacter(key: 'I', title: 'I', size: 1),
LibraryFirstCharacter(key: 'J', title: 'J', size: 1),
LibraryFirstCharacter(key: 'K', title: 'K', size: 1),
LibraryFirstCharacter(key: 'L', title: 'L', size: 1),
LibraryFirstCharacter(key: 'M', title: 'M', size: 1),
LibraryFirstCharacter(key: 'N', title: 'N', size: 1),
LibraryFirstCharacter(key: 'O', title: 'O', size: 1),
LibraryFirstCharacter(key: 'P', title: 'P', size: 1),
LibraryFirstCharacter(key: 'Q', title: 'Q', size: 1),
LibraryFirstCharacter(key: 'R', title: 'R', size: 1),
LibraryFirstCharacter(key: 'S', title: 'S', size: 1),
LibraryFirstCharacter(key: 'T', title: 'T', size: 1),
LibraryFirstCharacter(key: 'U', title: 'U', size: 1),
LibraryFirstCharacter(key: 'V', title: 'V', size: 1),
LibraryFirstCharacter(key: 'W', title: 'W', size: 1),
LibraryFirstCharacter(key: 'X', title: 'X', size: 1),
LibraryFirstCharacter(key: 'Y', title: 'Y', size: 1),
LibraryFirstCharacter(key: 'Z', title: 'Z', size: 1),
];
testWidgets('keeps the full alphabet visible in a short TV-height bar', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
height: 420,
child: AlphaJumpBar(firstCharacters: alphabetCharacters, currentLetter: '#', onJump: (_) {}),
),
),
),
);
expect(find.text('#'), findsOneWidget);
expect(find.text('U'), findsOneWidget);
expect(find.text('V'), findsOneWidget);
expect(find.text('W'), findsOneWidget);
expect(find.text('X'), findsOneWidget);
expect(find.text('Y'), findsOneWidget);
expect(find.text('Z'), findsOneWidget);
});
testWidgets('Enter jumps to the highlighted letter', (tester) async {
final focusNode = FocusNode(debugLabel: 'test_alpha_jump_bar');
addTearDown(focusNode.dispose);
+29
View File
@@ -41,6 +41,35 @@ void main() {
expect(expanded.left + expanded.width, viewportWidth);
});
test('tvOS Menu pass-through only enables at root with sidebar focus', () {
bool shouldPass({
bool isAppleTV = true,
bool isShowingProfileSelection = false,
bool isOverlaySheetOpen = false,
bool isRouteCurrent = true,
bool isSidebarFocused = true,
bool hasVisibleTabs = true,
bool isCurrentTabRoot = true,
}) {
return shouldPassTvosMenuToSystem(
isAppleTV: isAppleTV,
isShowingProfileSelection: isShowingProfileSelection,
isOverlaySheetOpen: isOverlaySheetOpen,
isRouteCurrent: isRouteCurrent,
isSidebarFocused: isSidebarFocused,
hasVisibleTabs: hasVisibleTabs,
isCurrentTabRoot: isCurrentTabRoot,
);
}
expect(shouldPass(), isTrue);
expect(shouldPass(isSidebarFocused: false), isFalse);
expect(shouldPass(isCurrentTabRoot: false), isFalse);
expect(shouldPass(isOverlaySheetOpen: true), isFalse);
expect(shouldPass(isRouteCurrent: false), isFalse);
expect(shouldPass(isAppleTV: false), isFalse);
});
testWidgets('side navigation bleed animates from the previous value', (tester) async {
Widget build(double targetBleed) {
return Directionality(
@@ -70,6 +70,38 @@ void main() {
expect(titleText.style!.fontSize!, lessThan(baseFontSize));
});
testWidgets('TV detail reveals without waiting for directional input', (tester) async {
await SettingsService.getInstance();
final movie = MediaItem(
id: 'movie_1',
backend: MediaBackend.jellyfin,
kind: MediaKind.movie,
title: 'Idle Reveal Movie',
summary: 'The detail foreground should appear without needing a D-pad frame.',
);
await tester.pumpWidget(
TranslationProvider(
child: MaterialApp(
theme: monoTheme(dark: true),
home: MediaDetailScreen(metadata: movie),
),
),
);
final revealGate = find.byWidgetPredicate(
(widget) => widget is AnimatedOpacity && widget.duration == const Duration(milliseconds: 160),
description: 'TV detail reveal AnimatedOpacity',
);
expect(revealGate, findsOneWidget);
expect(tester.widget<AnimatedOpacity>(revealGate).opacity, 0);
await tester.pump();
expect(tester.widget<AnimatedOpacity>(revealGate).opacity, 1);
});
testWidgets('TV detail defaults to first regular season when specials precede it', (tester) async {
await SettingsService.getInstance();
@@ -30,6 +30,12 @@ void main() {
);
await tester.pumpAndSettle();
expect(FocusManager.instance.primaryFocus?.debugLabel, 'TvVirtualKeyboard');
expect(find.byKey(const Key('tv_virtual_keyboard_panel')), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.gameButtonB);
await tester.pumpAndSettle();
expect(FocusManager.instance.primaryFocus?.debugLabel, 'AddLocalProfile:Name');
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
@@ -45,7 +51,7 @@ void main() {
expect(FocusManager.instance.primaryFocus?.debugLabel, 'AddLocalProfile:Cancel');
});
testWidgets('Android TV native keyboard done leaves profile name input', (tester) async {
testWidgets('Android TV virtual keyboard done leaves profile name input', (tester) async {
TvDetectionService.debugSetAppleTVOverride(null);
await TvDetectionService.getInstance(forceTv: true);
TvDetectionService.setForceTVSync(true);
@@ -57,11 +63,10 @@ void main() {
);
await tester.pumpAndSettle();
expect(FocusManager.instance.primaryFocus?.debugLabel, 'AddLocalProfile:Name');
expect(FocusManager.instance.primaryFocus?.debugLabel, 'TvVirtualKeyboard');
await tester.showKeyboard(find.byType(TextField));
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pump();
await tester.tap(find.byIcon(Icons.check_rounded));
await tester.pumpAndSettle();
expect(FocusManager.instance.primaryFocus?.debugLabel, 'AddLocalProfile:SetPin');
});
@@ -90,6 +95,13 @@ void main() {
await tester.tap(find.text('Open new profile'));
await tester.pumpAndSettle();
expect(find.text(t.profiles.newProfile), findsOneWidget);
expect(find.byKey(const Key('tv_virtual_keyboard_panel')), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.gameButtonB);
await tester.pumpAndSettle();
expect(find.text(t.profiles.newProfile), findsOneWidget);
expect(find.byKey(const Key('tv_virtual_keyboard_panel')), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.gameButtonB);
await tester.pumpAndSettle();
@@ -85,6 +85,13 @@ void main() {
await tester.tap(find.text('Open profile'));
await tester.pumpAndSettle();
expect(find.text(t.profiles.connectionsLabel), findsOneWidget);
expect(find.byKey(const Key('tv_virtual_keyboard_panel')), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.gameButtonB);
await tester.pumpAndSettle();
expect(find.text(t.profiles.connectionsLabel), findsOneWidget);
expect(find.byKey(const Key('tv_virtual_keyboard_panel')), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.gameButtonB);
await tester.pumpAndSettle();
@@ -1,5 +1,3 @@
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -26,16 +24,17 @@ void main() {
expect(field.autofocus, isTrue);
});
testWidgets('TV initial focus stays on the server URL field', (tester) async {
testWidgets('TV initial focus opens the server URL keyboard', (tester) async {
TvDetectionService.debugSetAppleTVOverride(true);
await tester.pumpWidget(const InputModeTracker(child: MaterialApp(home: AddJellyfinScreen())));
await tester.pumpAndSettle();
expect(FocusManager.instance.primaryFocus?.debugLabel, 'AddJellyfin:Url');
expect(FocusManager.instance.primaryFocus?.debugLabel, 'TvVirtualKeyboard');
expect(find.byKey(const Key('tv_virtual_keyboard_panel')), findsOneWidget);
});
testWidgets('Android TV remote navigation stays with native URL keyboard', (tester) async {
testWidgets('Android TV remote navigation stays with virtual URL keyboard', (tester) async {
TvDetectionService.debugSetAppleTVOverride(null);
await TvDetectionService.getInstance(forceTv: true);
TvDetectionService.setForceTVSync(true);
@@ -43,21 +42,17 @@ void main() {
await tester.pumpWidget(const InputModeTracker(child: MaterialApp(home: AddJellyfinScreen())));
await tester.pumpAndSettle();
final urlFocus = FocusManager.instance.primaryFocus!;
expect(urlFocus.debugLabel, 'AddJellyfin:Url');
expect(FocusManager.instance.primaryFocus?.debugLabel, 'TvVirtualKeyboard');
final result = urlFocus.onKeyEvent!(
urlFocus,
const KeyDownEvent(
physicalKey: PhysicalKeyboardKey.arrowDown,
logicalKey: LogicalKeyboardKey.arrowDown,
timeStamp: Duration.zero,
deviceType: ui.KeyEventDeviceType.directionalPad,
),
);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(result, KeyEventResult.skipRemainingHandlers);
expect(FocusManager.instance.primaryFocus?.debugLabel, 'TvVirtualKeyboard');
expect(find.byKey(const Key('tv_virtual_keyboard_panel')), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.gameButtonB);
await tester.pumpAndSettle();
expect(FocusManager.instance.primaryFocus?.debugLabel, 'AddJellyfin:Url');
});
@@ -164,6 +164,150 @@ void main() {
expect(captured.single.queryParameters['count'], '21');
});
test('getOnDeckFromAllServers hides duplicate show entries by stable show ids', () async {
final client = PlexClient.forTesting(
config: PlexConfig(
baseUrl: 'https://plex.example.com',
token: 'token',
clientIdentifier: 'client-id',
product: 'Plezy',
version: 'test',
),
serverId: 'plex-1',
serverName: 'Plex',
httpClient: MockClient((req) async {
if (req.url.path == '/hubs') {
return _json({
'MediaContainer': {
'Hub': [
{
'key': '/hubs/home/continueWatching',
'title': 'Continue Watching',
'type': 'mixed',
'hubIdentifier': 'home.continue',
'size': 2,
'Metadata': [
{
'ratingKey': 'old-episode',
'type': 'episode',
'title': 'Episode 1',
'grandparentRatingKey': 'old-show',
'grandparentTitle': 'Shared Show',
'guid': 'plex://episode/shared-episode-1',
'lastViewedAt': 100,
'librarySectionID': 1,
},
{
'ratingKey': 'new-episode',
'type': 'episode',
'title': 'Episode 2',
'grandparentRatingKey': 'new-show',
'grandparentTitle': 'Shared Show',
'guid': 'plex://episode/shared-episode-2',
'lastViewedAt': 200,
'librarySectionID': 2,
},
],
},
],
},
});
}
if (req.url.path == '/library/metadata/old-show' || req.url.path == '/library/metadata/new-show') {
return _json({
'MediaContainer': {
'Metadata': [
{
'ratingKey': req.url.pathSegments.last,
'type': 'show',
'title': 'Shared Show',
'Guid': [
{'id': 'tvdb://12345'},
],
},
],
},
});
}
return http.Response('unexpected request', 500);
}),
);
addTearDown(client.close);
manager.debugRegisterClientForTesting(client);
final items = await service.getOnDeckFromAllServers(limit: 10);
expect(items.map((item) => item.id), ['new-episode']);
});
test('getOnDeckFromAllServers keeps duplicate titles without stable ids', () async {
final client = PlexClient.forTesting(
config: PlexConfig(
baseUrl: 'https://plex.example.com',
token: 'token',
clientIdentifier: 'client-id',
product: 'Plezy',
version: 'test',
),
serverId: 'plex-1',
serverName: 'Plex',
httpClient: MockClient((req) async {
if (req.url.path == '/hubs') {
return _json({
'MediaContainer': {
'Hub': [
{
'key': '/hubs/home/continueWatching',
'title': 'Continue Watching',
'type': 'mixed',
'hubIdentifier': 'home.continue',
'size': 2,
'Metadata': [
{
'ratingKey': 'old-unmatched',
'type': 'episode',
'title': 'Episode 1',
'grandparentRatingKey': 'old-unmatched-show',
'grandparentTitle': 'Shared Show',
'guid': 'com.plexapp.agents.none://old-unmatched',
'lastViewedAt': 100,
},
{
'ratingKey': 'new-unmatched',
'type': 'episode',
'title': 'Episode 2',
'grandparentRatingKey': 'new-unmatched-show',
'grandparentTitle': 'Shared Show',
'guid': 'com.plexapp.agents.none://new-unmatched',
'lastViewedAt': 200,
},
],
},
],
},
});
}
if (req.url.path == '/library/metadata/old-unmatched-show' ||
req.url.path == '/library/metadata/new-unmatched-show') {
return _json({
'MediaContainer': {
'Metadata': [
{'ratingKey': req.url.pathSegments.last, 'type': 'show', 'title': 'Shared Show'},
],
},
});
}
return http.Response('unexpected request', 500);
}),
);
addTearDown(client.close);
manager.debugRegisterClientForTesting(client);
final items = await service.getOnDeckFromAllServers(limit: 10);
expect(items.map((item) => item.id), ['new-unmatched', 'old-unmatched']);
});
test('per-library hubs skip playback rows and fetch in bounded batches', () async {
final captured = <Uri>[];
var activeLatest = 0;
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'dart:io';
import 'package:background_downloader/background_downloader.dart';
import 'package:drift/drift.dart' show Value;
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -262,6 +263,179 @@ void main() {
expect(row?.thumbPath, artworkStorageKey('/ep-thumb'));
});
});
group('task session validation', () {
test('ignores progress from stale native task ids', () async {
final db = AppDatabase.forTesting(NativeDatabase.memory());
addTearDown(db.close);
const globalKey = 'srv:item-1';
await db.insertDownload(
serverId: 'srv',
ratingKey: 'item-1',
globalKey: globalKey,
type: 'movie',
status: DownloadStatus.downloading.index,
);
await db.updateBgTaskId(globalKey, 'current-task');
final manager = DownloadManagerService(
database: db,
storageService: DownloadStorageService.instance,
downloadsSupportedOverride: false,
);
addTearDown(manager.dispose);
final events = <DownloadProgress>[];
final sub = manager.progressStream.listen(events.add);
addTearDown(sub.cancel);
await manager.debugHandleTaskProgress(TaskProgressUpdate(_downloadTask('stale-task', globalKey), 0.5, 1000));
await Future<void>.delayed(Duration.zero);
expect(events, isEmpty);
await manager.debugHandleTaskProgress(TaskProgressUpdate(_downloadTask('current-task', globalKey), 0.5, 1000));
await Future<void>.delayed(Duration.zero);
expect(events, hasLength(1));
expect(events.single.globalKey, globalKey);
expect(events.single.progress, 50);
});
test('ignores terminal status from stale native task ids', () async {
final db = AppDatabase.forTesting(NativeDatabase.memory());
addTearDown(db.close);
const globalKey = 'srv:item-1';
await db.insertDownload(
serverId: 'srv',
ratingKey: 'item-1',
globalKey: globalKey,
type: 'movie',
status: DownloadStatus.downloading.index,
);
await db.updateBgTaskId(globalKey, 'current-task');
final manager = DownloadManagerService(
database: db,
storageService: DownloadStorageService.instance,
downloadsSupportedOverride: false,
);
addTearDown(manager.dispose);
await manager.debugHandleTaskStatus(TaskStatusUpdate(_downloadTask('stale-task', globalKey), TaskStatus.failed));
final row = await db.getDownloadedMedia(globalKey);
expect(row?.status, DownloadStatus.downloading.index);
expect(row?.errorMessage, isNull);
expect(row?.bgTaskId, 'current-task');
});
test('requeues current system cancel without in-memory context', () async {
final db = AppDatabase.forTesting(NativeDatabase.memory());
addTearDown(db.close);
const globalKey = 'srv:item-1';
await db.insertDownload(
serverId: 'srv',
ratingKey: 'item-1',
globalKey: globalKey,
type: 'movie',
status: DownloadStatus.downloading.index,
);
await db.updateBgTaskId(globalKey, 'current-task');
final manager = DownloadManagerService(
database: db,
storageService: DownloadStorageService.instance,
downloadsSupportedOverride: false,
);
addTearDown(manager.dispose);
await manager.debugHandleTaskStatus(
TaskStatusUpdate(_downloadTask('current-task', globalKey), TaskStatus.canceled),
);
final row = await db.getDownloadedMedia(globalKey);
expect(row?.status, DownloadStatus.queued.index);
expect(row?.bgTaskId, isNull);
expect((await db.getNextQueueItem())?.mediaGlobalKey, globalKey);
});
});
group('resume handling', () {
test('failed native resume leaves paused row paused', () async {
final db = AppDatabase.forTesting(NativeDatabase.memory());
addTearDown(db.close);
const globalKey = 'srv:item-1';
await db.insertDownload(
serverId: 'srv',
ratingKey: 'item-1',
globalKey: globalKey,
type: 'movie',
status: DownloadStatus.paused.index,
);
await db.updateBgTaskId(globalKey, 'current-task');
final manager = DownloadManagerService(
database: db,
storageService: DownloadStorageService.instance,
downloadsSupportedOverride: false,
);
addTearDown(manager.dispose);
final resumed = await manager.debugTryResumeNativeTask(
globalKey,
'current-task',
taskForId: (_) async => _downloadTask('current-task', globalKey),
resumeTask: (_) async => false,
);
final row = await db.getDownloadedMedia(globalKey);
expect(resumed, isFalse);
expect(row?.status, DownloadStatus.paused.index);
expect(row?.bgTaskId, 'current-task');
});
test('successful native resume transitions to downloading', () async {
final db = AppDatabase.forTesting(NativeDatabase.memory());
addTearDown(db.close);
const globalKey = 'srv:item-1';
await db.insertDownload(
serverId: 'srv',
ratingKey: 'item-1',
globalKey: globalKey,
type: 'movie',
status: DownloadStatus.paused.index,
);
await db.updateBgTaskId(globalKey, 'current-task');
final manager = DownloadManagerService(
database: db,
storageService: DownloadStorageService.instance,
downloadsSupportedOverride: false,
);
addTearDown(manager.dispose);
final resumed = await manager.debugTryResumeNativeTask(
globalKey,
'current-task',
taskForId: (_) async => _downloadTask('current-task', globalKey),
resumeTask: (_) async => true,
);
final row = await db.getDownloadedMedia(globalKey);
expect(resumed, isTrue);
expect(row?.status, DownloadStatus.downloading.index);
expect(row?.bgTaskId, 'current-task');
});
});
}
DownloadTask _downloadTask(String taskId, String globalKey) {
return DownloadTask(
taskId: taskId,
url: 'https://example.test/video.mp4',
filename: 'video.mp4',
directory: 'downloads',
metaData: globalKey,
);
}
MediaItem _movie({String? thumbPath}) {
@@ -177,9 +177,20 @@ void main() {
'Language': 'eng',
'DisplayLanguage': 'English',
'DisplayTitle': 'English - SRT',
'IsExternal': true,
'DeliveryMethod': 'External',
'DeliveryUrl': '/Videos/item-1/src-2/Subtitles/3/Stream.srt',
},
{
'Index': 4,
'Type': 'Subtitle',
'Codec': 'srt',
'Language': 'fra',
'DisplayLanguage': 'French',
'DisplayTitle': 'French - SRT',
'DeliveryMethod': 'External',
'DeliveryUrl': '/Videos/item-1/src-2/Subtitles/4/Stream.srt',
},
],
},
],
@@ -332,6 +343,8 @@ void main() {
expect(uri.queryParameters['api_key'], 'tok-abc');
expect(uri.queryParameters.containsKey('StartTimeTicks'), isFalse);
expect(result.mediaInfo!.subtitleTracks, hasLength(1));
expect(result.mediaInfo!.subtitleTracks.single.isExternalFile, isFalse);
expect(result.mediaInfo!.subtitleTracks.single.usesExternalDelivery, isTrue);
expect(result.externalSubtitles, hasLength(1));
expect(result.externalSubtitles.single.title, 'English');
expect(result.externalSubtitles.single.language, 'eng');
@@ -444,6 +457,7 @@ void main() {
'Codec': 'srt',
'Language': 'eng',
'DisplayTitle': 'English - SRT',
'IsExternal': true,
'DeliveryMethod': 'External',
'DeliveryUrl': '/Videos/item-1/src-1/Subtitles/3/Stream.srt',
},
@@ -495,6 +509,85 @@ void main() {
expect(subtitleUri.queryParameters['api_key'], 'tok-abc');
});
test('getPlaybackInitialization skips negotiated subtitle delivery for original playback', () async {
final scoped = JellyfinClient.forTesting(
connection: _conn(),
httpClient: MockClient((request) async {
if (request.url.path == '/Users/user-1/Items/item-1') {
return http.Response(
jsonEncode({
'Id': 'item-1',
'Type': 'Movie',
'Name': 'Movie',
'MediaSources': [
{
'Id': 'src-1',
'Container': 'mkv',
'MediaStreams': [
{'Index': 0, 'Type': 'Video'},
],
},
],
}),
200,
headers: {'content-type': 'application/json'},
);
}
if (request.url.path == '/Items/item-1/PlaybackInfo') {
return http.Response(
jsonEncode({
'PlaySessionId': 'play-session-direct',
'MediaSources': [
{
'Id': 'src-1',
'Container': 'mkv',
'DirectStreamUrl': '/Videos/item-1/stream?MediaSourceId=src-1&PlaySessionId=play-session-direct',
'MediaStreams': [
{'Index': 0, 'Type': 'Video'},
{
'Index': 3,
'Type': 'Subtitle',
'Codec': 'srt',
'Language': 'eng',
'DisplayTitle': 'English - SRT',
'DeliveryMethod': 'External',
'DeliveryUrl': '/Videos/item-1/src-1/Subtitles/3/Stream.srt',
},
{
'Index': 4,
'Type': 'Subtitle',
'Codec': 'srt',
'Language': 'fra',
'DisplayTitle': 'French - SRT',
'DeliveryMethod': 'External',
'DeliveryUrl': '/Videos/item-1/src-1/Subtitles/4/Stream.srt',
},
],
},
],
}),
200,
headers: {'content-type': 'application/json'},
);
}
return http.Response('{}', 404);
}),
);
addTearDown(scoped.close);
final result = await scoped.getPlaybackInitialization(
PlaybackInitializationOptions(
metadata: MediaItem(id: 'item-1', backend: MediaBackend.jellyfin, kind: MediaKind.movie, serverId: 'srv-1'),
selectedMediaIndex: 0,
),
);
expect(result.playMethod, 'DirectStream');
expect(result.mediaInfo!.subtitleTracks, hasLength(2));
expect(result.mediaInfo!.subtitleTracks.every((track) => track.usesExternalDelivery), isTrue);
expect(result.externalSubtitles, isEmpty);
});
test('getPlaybackInitialization ignores TranscodingUrl for original playback static fallback', () async {
final requests = <Uri>[];
final scoped = JellyfinClient.forTesting(
@@ -1343,6 +1436,41 @@ void main() {
expect(captured!.queryParameters['ImageTypeLimit'], '1');
});
test('fetchLibraryFiltersWithValues adds unwatched boolean filter', () async {
Uri? captured;
final scoped = JellyfinClient.forTesting(
connection: _conn(),
httpClient: MockClient((req) async {
captured = req.url;
return http.Response(
jsonEncode({
'Genres': ['Drama', 'Action'],
'OfficialRatings': ['PG-13'],
'Tags': ['Holiday'],
'Years': [2024, 1999],
}),
200,
headers: {'content-type': 'application/json'},
);
}),
);
addTearDown(scoped.close);
final result = await scoped.fetchLibraryFiltersWithValues('lib-1');
expect(captured, isNotNull);
expect(captured!.path, '/Items/Filters');
expect(captured!.queryParameters['ParentId'], 'lib-1');
expect(captured!.queryParameters['userId'], 'user-1');
expect(result.filters.map((filter) => filter.filter), ['unwatched', 'genre', 'year', 'contentRating', 'tag']);
expect(result.filters.first.filterType, 'boolean');
expect(result.filters.first.key, 'jellyfin:unwatched');
expect(result.filters.first.title, 'Unwatched');
expect(result.cachedValues.containsKey('unwatched'), isFalse);
expect(result.cachedValues['genre']!.map((value) => value.key), ['Action', 'Drama']);
expect(result.cachedValues['year']!.map((value) => value.key), ['2024', '1999']);
});
test('fetchLibraryContent uses sentinel total fallback when server omits total', () async {
final scoped = JellyfinClient.forTesting(
connection: _conn(),
@@ -1401,6 +1529,75 @@ void main() {
expect(captured[1].queryParameters['IncludeItemTypes'], 'Episode');
});
test('fetchLibraryFolders uses direct non-recursive Items query and orders folders first', () async {
Uri? captured;
final scoped = JellyfinClient.forTesting(
connection: _conn(),
httpClient: MockClient((req) async {
captured = req.url;
return http.Response(
jsonEncode({
'Items': [
{'Id': 'track-z', 'Type': 'Audio', 'Name': 'Z Track', 'IsFolder': false},
{'Id': 'series-a', 'Type': 'Series', 'Name': 'A Show', 'IsFolder': true},
{'Id': 'folder-z', 'Type': 'Folder', 'Name': 'Z Folder', 'IsFolder': true},
{'Id': 'movie-m', 'Type': 'Movie', 'Name': 'Movie', 'IsFolder': false},
],
'TotalRecordCount': 4,
}),
200,
headers: {'content-type': 'application/json'},
);
}),
);
addTearDown(scoped.close);
final items = await scoped.fetchLibraryFolders('lib-1');
expect(captured, isNotNull);
expect(captured!.path, '/Items');
expect(captured!.queryParameters['ParentId'], 'lib-1');
expect(captured!.queryParameters['Recursive'], 'false');
expect(captured!.queryParameters['EnableTotalRecordCount'], 'true');
expect(captured!.queryParameters['SortBy'], 'IsFolder,SortName');
expect(captured!.queryParameters['SortOrder'], 'Ascending');
expect(captured!.queryParameters['Fields'], isNot(contains('MediaSources')));
expect(items.map((item) => item.id), ['folder-z', 'series-a', 'movie-m', 'track-z']);
expect(items.first.kind, MediaKind.unknown);
expect(items.first.raw?['IsFolder'], isTrue);
expect(items[1].kind, MediaKind.show);
});
test('fetchFolderChildren pages direct folder contents', () async {
final starts = <String?>[];
final scoped = JellyfinClient.forTesting(
connection: _conn(),
httpClient: MockClient((req) async {
starts.add(req.url.queryParameters['StartIndex']);
final start = int.parse(req.url.queryParameters['StartIndex'] ?? '0');
const total = 501;
final end = start == 0 ? 500 : total;
return http.Response(
jsonEncode({
'Items': [
for (var i = start; i < end; i++)
{'Id': 'child-$i', 'Type': 'Movie', 'Name': 'Child $i', 'IsFolder': false},
],
'TotalRecordCount': total,
}),
200,
headers: {'content-type': 'application/json'},
);
}),
);
addTearDown(scoped.close);
final items = await scoped.fetchFolderChildren('folder-1');
expect(starts, ['0', '500']);
expect(items, hasLength(501));
});
test('fetchClientSideEpisodeQueue pages past the first 200 episodes', () async {
final starts = <String?>[];
final pagedClient = JellyfinClient.forTesting(
@@ -2353,6 +2550,37 @@ void main() {
expect(requestUri!.queryParameters['Limit'], '10');
});
test('fetchPlayableFolderDescendants includes generic video but excludes audio', () async {
Uri? requestUri;
final mock = MockClient((req) async {
if (req.url.path == '/Items') {
requestUri = req.url;
return http.Response(
jsonEncode({
'Items': [
{'Id': 'video-1', 'Name': 'Home Video', 'Type': 'Video'},
],
'TotalRecordCount': 1,
}),
200,
headers: {'content-type': 'application/json'},
);
}
return http.Response('not found', 404);
});
final client = JellyfinClient.forTesting(connection: _conn(), httpClient: mock);
addTearDown(client.close);
final items = await client.fetchPlayableFolderDescendants('folder-1');
expect(items.single.kind, MediaKind.clip);
expect(requestUri, isNotNull);
expect(requestUri!.queryParameters['ParentId'], 'folder-1');
expect(requestUri!.queryParameters['Recursive'], 'true');
expect(requestUri!.queryParameters['IncludeItemTypes'], 'Movie,Episode,Video,MusicVideo');
expect(requestUri!.queryParameters['IncludeItemTypes'], isNot(contains('Audio')));
});
test('fetchChildren walks generic children pages', () async {
final itemRequests = <Uri>[];
final mock = MockClient((req) async {
+18
View File
@@ -94,6 +94,24 @@ void main() {
expect(item.isWatched, isFalse);
});
test('maps generic Jellyfin video types to playable clips', () {
final video = JellyfinMappers.mediaItem(
{'Id': 'home-video', 'Name': 'Home Video', 'Type': 'Video'},
serverId: _serverId,
absolutizer: null,
)!;
final musicVideo = JellyfinMappers.mediaItem(
{'Id': 'music-video', 'Name': 'Music Video', 'Type': 'MusicVideo'},
serverId: _serverId,
absolutizer: null,
)!;
expect(video.kind, MediaKind.clip);
expect(musicVideo.kind, MediaKind.clip);
expect(video.kind.isVideo, isTrue);
expect(musicVideo.kind.isVideo, isTrue);
});
test('episode preserves series/season hierarchy', () {
final json = {
'Id': 'ep1',
@@ -214,6 +214,8 @@ void main() {
final sub = info.subtitleTracks.single;
expect(sub.key, '/Videos/item-1/src-1/Subtitles/2/Stream.srt');
expect(sub.isExternal, isTrue);
expect(sub.isExternalFile, isFalse);
expect(sub.usesExternalDelivery, isTrue);
});
test('preserves external Jellyfin audio streams', () {
@@ -247,6 +249,8 @@ void main() {
final sub = info.subtitleTracks.single;
expect(sub.key, isNull);
expect(sub.isExternal, isTrue);
expect(sub.isExternalFile, isTrue);
expect(sub.usesExternalDelivery, isFalse);
});
test('captures mediaSourceId from source Id field', () {
@@ -19,14 +19,17 @@ import 'package:plezy/utils/media_server_http_client.dart';
/// `implements JellyfinClient` so existing tests stay backend-tagged.
class _RecordingJellyfinClient implements JellyfinClient {
final List<MediaItem> playableDescendantsResponse;
final List<MediaItem> playableFolderDescendantsResponse;
final List<MediaItem> seriesEpisodesResponse;
final List<MediaItem> playlistItemsResponse;
final List<String> fetchPlayableDescendantsCalls = [];
final List<String> fetchPlayableFolderDescendantsCalls = [];
final List<String> fetchSeriesEpisodesCalls = [];
final List<({String id, int offset, int limit})> fetchPlaylistItemsCalls = [];
_RecordingJellyfinClient({
this.playableDescendantsResponse = const [],
this.playableFolderDescendantsResponse = const [],
this.seriesEpisodesResponse = const [],
this.playlistItemsResponse = const [],
});
@@ -37,6 +40,12 @@ class _RecordingJellyfinClient implements JellyfinClient {
return playableDescendantsResponse;
}
@override
Future<List<MediaItem>> fetchPlayableFolderDescendants(String parentId) async {
fetchPlayableFolderDescendantsCalls.add(parentId);
return playableFolderDescendantsResponse;
}
@override
Future<List<MediaItem>?> fetchClientSideEpisodeQueue(String seriesId) async {
fetchSeriesEpisodesCalls.add(seriesId);
@@ -80,6 +89,15 @@ MediaItem _ep(String id, {String? serverId = 'srv-jf'}) => MediaItem(
serverId: serverId,
);
MediaItem _movie(String id, {String? serverId = 'srv-jf'}) =>
MediaItem(id: id, backend: MediaBackend.jellyfin, kind: MediaKind.movie, title: 'Movie $id', serverId: serverId);
MediaItem _clip(String id, {String? serverId = 'srv-jf'}) =>
MediaItem(id: id, backend: MediaBackend.jellyfin, kind: MediaKind.clip, title: 'Video $id', serverId: serverId);
MediaItem _track(String id, {String? serverId = 'srv-jf'}) =>
MediaItem(id: id, backend: MediaBackend.jellyfin, kind: MediaKind.track, title: 'Track $id', serverId: serverId);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
@@ -384,6 +402,105 @@ void main() {
expect(navigated.single.id, 'a');
});
testWidgets('folder path seeds a video-only local queue', (tester) async {
final ctx = await pumpContext(tester);
final fakeClient = _RecordingJellyfinClient(
playableFolderDescendantsResponse: [_track('song'), _movie('movie', serverId: null), _clip('video')],
);
final playback = PlaybackStateProvider();
final navigated = <MediaItem>[];
final launcher = JellyfinSequentialLauncher(
context: ctx,
clientForTesting: fakeClient,
playbackStateForTesting: playback,
navigateForTesting: (m) async => navigated.add(m),
);
final folder = MediaItem(
id: 'folder-1',
backend: MediaBackend.jellyfin,
kind: MediaKind.unknown,
title: 'Folder',
serverId: 'srv-jf',
serverName: 'Home Jellyfin',
libraryId: 'lib-1',
libraryTitle: 'Videos',
);
final result = await launcher.launchFromFolder(folder: folder, shuffle: false, showLoadingIndicator: false);
expect(result, isA<PlayQueueSuccess>());
expect(fakeClient.fetchPlayableFolderDescendantsCalls, ['folder-1']);
expect(fakeClient.fetchPlayableDescendantsCalls, isEmpty);
expect(playback.loadedItems.map((m) => m.id).toList(), ['movie', 'video']);
expect(playback.loadedItems.any((m) => m.kind == MediaKind.track), isFalse);
expect(playback.loadedItems.first.serverId, 'srv-jf');
expect(playback.loadedItems.first.libraryId, 'lib-1');
expect(playback.isQueueActive, isTrue);
expect(playback.isShuffleActive, isFalse);
expect(navigated.single.id, 'movie');
});
testWidgets('folder shuffle reorders the video queue', (tester) async {
final ctx = await pumpContext(tester);
final originalIds = List.generate(50, (i) => 'v$i');
final fakeClient = _RecordingJellyfinClient(playableFolderDescendantsResponse: originalIds.map(_clip).toList());
final playback = PlaybackStateProvider();
final launcher = JellyfinSequentialLauncher(
context: ctx,
clientForTesting: fakeClient,
playbackStateForTesting: playback,
navigateForTesting: (_) async {},
);
final folder = MediaItem(
id: 'folder-shuffle',
backend: MediaBackend.jellyfin,
kind: MediaKind.unknown,
serverId: 'srv-jf',
);
final result = await launcher.launchFromFolder(folder: folder, shuffle: true, showLoadingIndicator: false);
expect(result, isA<PlayQueueSuccess>());
final shuffledIds = playback.loadedItems.map((m) => m.id).toList();
expect(shuffledIds.toSet(), originalIds.toSet());
expect(shuffledIds.length, originalIds.length);
expect(shuffledIds, isNot(equals(originalIds)));
expect(playback.isShuffleActive, isTrue);
});
testWidgets('music-only folder returns PlayQueueEmpty', (tester) async {
final ctx = await pumpContext(tester);
final fakeClient = _RecordingJellyfinClient(playableFolderDescendantsResponse: [_track('a'), _track('b')]);
final playback = PlaybackStateProvider();
var didNavigate = false;
final launcher = JellyfinSequentialLauncher(
context: ctx,
clientForTesting: fakeClient,
playbackStateForTesting: playback,
navigateForTesting: (_) async {
didNavigate = true;
},
);
final folder = MediaItem(
id: 'music-folder',
backend: MediaBackend.jellyfin,
kind: MediaKind.unknown,
serverId: 'srv-jf',
);
final result = await launcher.launchFromFolder(folder: folder, shuffle: false, showLoadingIndicator: false);
expect(result, isA<PlayQueueEmpty>());
expect(playback.isQueueActive, isFalse);
expect(didNavigate, isFalse);
});
testWidgets('launchShuffledShow rejects non-show/season kinds', (tester) async {
final ctx = await pumpContext(tester);
final launcher = JellyfinSequentialLauncher(context: ctx);
+145 -71
View File
@@ -179,36 +179,7 @@ void main() {
expect(nextFocusNode.hasPrimaryFocus, isTrue);
});
testWidgets('tvOS keyboard enter does not open virtual keyboard', (tester) async {
TvDetectionService.debugSetAppleTVOverride(true);
final controller = TextEditingController();
final fieldFocusNode = FocusNode(debugLabel: 'search_field');
String? submitted;
addTearDown(controller.dispose);
addTearDown(fieldFocusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: FocusableTextField(
controller: controller,
focusNode: fieldFocusNode,
onSubmitted: (value) => submitted = value,
),
),
),
);
fieldFocusNode.requestFocus();
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsNothing);
expect(submitted, isEmpty);
});
testWidgets('tvOS remote select opens virtual keyboard', (tester) async {
testWidgets('tvOS focus opens virtual keyboard', (tester) async {
TvDetectionService.debugSetAppleTVOverride(true);
await _setTvSurfaceSize(tester);
final controller = TextEditingController();
@@ -225,20 +196,71 @@ void main() {
);
fieldFocusNode.requestFocus();
await tester.pump();
_dispatchKey(
const KeyDownEvent(
physicalKey: PhysicalKeyboardKey.select,
logicalKey: LogicalKeyboardKey.select,
timeStamp: Duration.zero,
deviceType: ui.KeyEventDeviceType.directionalPad,
),
);
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsOneWidget);
});
testWidgets('hidden TV text field does not auto-open virtual keyboard', (tester) async {
TvDetectionService.debugSetAppleTVOverride(true);
await _setTvSurfaceSize(tester);
final controller = TextEditingController(text: 'query');
final fieldFocusNode = FocusNode(debugLabel: 'hidden_search_field');
addTearDown(controller.dispose);
addTearDown(fieldFocusNode.dispose);
Future<void> pumpField({required bool visible}) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: TickerMode(
enabled: visible,
child: FocusableTextField(controller: controller, focusNode: fieldFocusNode),
),
),
),
);
}
await pumpField(visible: false);
fieldFocusNode.requestFocus();
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsNothing);
await pumpField(visible: true);
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsOneWidget);
});
testWidgets('TV virtual keyboard does not immediately reopen after dismissal', (tester) async {
TvDetectionService.debugSetAppleTVOverride(true);
await _setTvSurfaceSize(tester);
final controller = TextEditingController();
final fieldFocusNode = FocusNode(debugLabel: 'search_field');
addTearDown(controller.dispose);
addTearDown(fieldFocusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: FocusableTextField(controller: controller, focusNode: fieldFocusNode),
),
),
);
fieldFocusNode.requestFocus();
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
await tester.pump();
expect(find.byType(Dialog), findsNothing);
});
testWidgets('Android TV native keyboard done uses D-pad navigation', (tester) async {
TvDetectionService.debugSetAppleTVOverride(null);
await TvDetectionService.getInstance(forceTv: true);
@@ -258,6 +280,7 @@ void main() {
FocusableTextField(
controller: controller,
focusNode: fieldFocusNode,
enableTvKeyboard: false,
textInputAction: TextInputAction.done,
onNavigateDown: nextFocusNode.requestFocus,
),
@@ -278,6 +301,30 @@ void main() {
expect(find.byType(Dialog), findsNothing);
});
testWidgets('Android TV focus opens the TV virtual keyboard', (tester) async {
TvDetectionService.debugSetAppleTVOverride(null);
await TvDetectionService.getInstance(forceTv: true);
TvDetectionService.setForceTVSync(true);
await _setTvSurfaceSize(tester);
final controller = TextEditingController();
final fieldFocusNode = FocusNode(debugLabel: 'server_url_field');
addTearDown(controller.dispose);
addTearDown(fieldFocusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: FocusableTextFormField(controller: controller, focusNode: fieldFocusNode),
),
),
);
fieldFocusNode.requestFocus();
await tester.pumpAndSettle();
expect(find.byKey(const Key('tv_virtual_keyboard_panel')), findsOneWidget);
});
testWidgets('Android TV remote keys are passed to native text input', (tester) async {
TvDetectionService.debugSetAppleTVOverride(null);
await TvDetectionService.getInstance(forceTv: true);
@@ -299,6 +346,7 @@ void main() {
FocusableTextFormField(
controller: controller,
focusNode: fieldFocusNode,
enableTvKeyboard: false,
onNavigateDown: nextFocusNode.requestFocus,
onSelect: () => selects++,
onBack: () => backs++,
@@ -373,7 +421,7 @@ void main() {
home: Scaffold(
body: Column(
children: [
FocusableTextFormField(controller: controller, focusNode: fieldFocusNode),
FocusableTextFormField(controller: controller, focusNode: fieldFocusNode, enableTvKeyboard: false),
Focus(focusNode: otherFocusNode, child: const SizedBox.shrink()),
],
),
@@ -398,12 +446,51 @@ void main() {
expect(gamepadFocusStates, [true, false]);
});
testWidgets('Android TV physical keyboard text keys fall through to the field', (tester) async {
testWidgets('Android TV physical keyboard text keys edit the TV field', (tester) async {
TvDetectionService.debugSetAppleTVOverride(null);
await TvDetectionService.getInstance(forceTv: true);
TvDetectionService.setForceTVSync(true);
final controller = TextEditingController();
final fieldFocusNode = FocusNode(debugLabel: 'name_field');
String? submitted;
addTearDown(controller.dispose);
addTearDown(fieldFocusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: FocusableTextField(
controller: controller,
focusNode: fieldFocusNode,
onSubmitted: (value) => submitted = value,
),
),
),
);
fieldFocusNode.requestFocus();
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.keyA, character: 'a');
await tester.pumpAndSettle();
expect(controller.text, 'a');
expect(find.byType(Dialog), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(submitted, 'a');
expect(controller.text, 'a');
expect(find.byType(Dialog), findsNothing);
});
testWidgets('Android TV physical keyboard backspace deletes existing text from end', (tester) async {
TvDetectionService.debugSetAppleTVOverride(null);
await TvDetectionService.getInstance(forceTv: true);
TvDetectionService.setForceTVSync(true);
final controller = TextEditingController(text: 'query');
controller.selection = const TextSelection.collapsed(offset: 0);
final fieldFocusNode = FocusNode(debugLabel: 'search_field');
addTearDown(controller.dispose);
addTearDown(fieldFocusNode.dispose);
@@ -416,24 +503,15 @@ void main() {
);
fieldFocusNode.requestFocus();
await tester.pump();
final result = fieldFocusNode.onKeyEvent!(
fieldFocusNode,
const KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyA,
logicalKey: LogicalKeyboardKey.keyA,
character: 'a',
timeStamp: Duration.zero,
deviceType: ui.KeyEventDeviceType.keyboard,
),
);
await tester.pump();
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.backspace);
await tester.pumpAndSettle();
expect(result, KeyEventResult.ignored);
expect(fieldFocusNode.hasPrimaryFocus, isTrue);
expect(controller.text, 'quer');
expect(find.byType(Dialog), findsNothing);
});
testWidgets('tvOS engine-synthesized select opens the virtual keyboard', (tester) async {
testWidgets('tvOS engine-synthesized select is handled by the virtual keyboard', (tester) async {
// The custom Flutter tvOS engine emits Siri Remote center-dpad presses
// as `LogicalKeyboardKey.select` with `deviceType=keyboard` (via the
// legacy `flutter/keyevent` Android DPAD_CENTER path). On Apple TV this
@@ -470,10 +548,9 @@ void main() {
expect(find.byType(Dialog), findsOneWidget);
});
testWidgets('tvOS text field handles physical keyboard text editing without opening virtual keyboard', (
tester,
) async {
testWidgets('tvOS text field handles physical keyboard text editing through virtual keyboard', (tester) async {
TvDetectionService.debugSetAppleTVOverride(true);
await _setTvSurfaceSize(tester);
final controller = TextEditingController();
final fieldFocusNode = FocusNode(debugLabel: 'search_field');
final changes = <String>[];
@@ -497,8 +574,15 @@ void main() {
expect(tester.widget<TextField>(find.byType(TextField)).readOnly, isTrue);
fieldFocusNode.requestFocus();
await tester.pump();
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.keyA, character: 'a');
await tester.pumpAndSettle();
expect(controller.text, 'a');
expect(find.byType(Dialog), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.keyC, character: 'c');
await tester.sendKeyEvent(LogicalKeyboardKey.keyB, character: 'b');
await tester.pumpAndSettle();
@@ -540,7 +624,7 @@ void main() {
);
fieldFocusNode.requestFocus();
await tester.pump();
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
@@ -554,16 +638,6 @@ Future<void> _setTvSurfaceSize(WidgetTester tester) async {
addTearDown(() => tester.binding.setSurfaceSize(null));
}
KeyEventResult _dispatchKey(KeyEvent event) {
FocusNode? node = FocusManager.instance.primaryFocus;
while (node != null) {
final result = node.onKeyEvent?.call(node, event) ?? KeyEventResult.ignored;
if (result != KeyEventResult.ignored) return result;
node = node.parent;
}
return KeyEventResult.ignored;
}
KeyDownEvent _remoteKey(LogicalKeyboardKey key) {
return KeyDownEvent(
physicalKey: _physicalKeyFor(key),
+63
View File
@@ -0,0 +1,63 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/media/media_backend.dart';
import 'package:plezy/media/media_item.dart';
import 'package:plezy/media/media_kind.dart';
import 'package:plezy/screens/libraries/folder_tree_item.dart';
void main() {
testWidgets('folder rows use the item title for seasons', (tester) async {
final item = MediaItem(
id: 'season-1',
backend: MediaBackend.jellyfin,
kind: MediaKind.season,
title: 'Season 1',
grandparentTitle: 'TV Show',
raw: const {'Type': 'Season', 'IsFolder': true},
);
await tester.pumpWidget(
MaterialApp(
home: Material(child: FolderTreeItem(item: item, depth: 1, isFolder: true)),
),
);
expect(find.text('Season 1'), findsOneWidget);
expect(find.text('TV Show'), findsNothing);
expect(find.byType(IconButton), findsNothing);
});
testWidgets('folder rows show play and shuffle buttons when callbacks are supplied', (tester) async {
final item = MediaItem(
id: 'folder-1',
backend: MediaBackend.jellyfin,
kind: MediaKind.unknown,
title: 'Videos',
raw: const {'Type': 'Folder', 'IsFolder': true},
);
var played = false;
var shuffled = false;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: FolderTreeItem(
item: item,
depth: 0,
isFolder: true,
onPlayAll: () => played = true,
onShuffle: () => shuffled = true,
),
),
),
);
expect(find.byType(IconButton), findsNWidgets(2));
await tester.tap(find.byType(IconButton).first);
await tester.tap(find.byType(IconButton).last);
expect(played, isTrue);
expect(shuffled, isTrue);
});
}
+57 -1
View File
@@ -72,7 +72,63 @@ void main() {
await tester.pumpAndSettle();
expect(controller.text, 'a\n');
expect(find.byType(Dialog), findsOneWidget);
expect(find.byType(Dialog), findsNothing);
});
testWidgets('physical keyboard character inserts text and hides keyboard', (tester) async {
final controller = TextEditingController();
addTearDown(controller.dispose);
await _pumpKeyboard(tester, controller: controller);
await tester.sendKeyEvent(LogicalKeyboardKey.keyA, character: 'a');
await tester.pumpAndSettle();
expect(controller.text, 'a');
expect(find.byType(Dialog), findsNothing);
});
testWidgets('physical keyboard backspace deletes existing text from end and hides keyboard', (tester) async {
final controller = TextEditingController(text: 'query');
controller.selection = const TextSelection.collapsed(offset: 0);
addTearDown(controller.dispose);
await _pumpKeyboard(tester, controller: controller);
await tester.sendKeyEvent(LogicalKeyboardKey.backspace);
await tester.pumpAndSettle();
expect(controller.text, 'quer');
expect(find.byType(Dialog), findsNothing);
});
testWidgets('keyboard is compact and bottom aligned on TV', (tester) async {
final controller = TextEditingController();
addTearDown(controller.dispose);
await _pumpKeyboard(tester, controller: controller);
final panelRect = tester.getRect(find.byKey(const Key('tv_virtual_keyboard_panel')));
expect(panelRect.height, lessThanOrEqualTo(330));
expect(panelRect.width, lessThanOrEqualTo(650));
expect(panelRect.bottom, greaterThan(680));
});
testWidgets('keyboard keeps equals on main page and exposes symbols page', (tester) async {
final controller = TextEditingController();
addTearDown(controller.dispose);
await _pumpKeyboard(tester, controller: controller);
expect(find.text('='), findsOneWidget);
expect(find.byIcon(Icons.functions_rounded), findsOneWidget);
await tester.tap(find.byIcon(Icons.functions_rounded));
await tester.pumpAndSettle();
expect(find.text('ABC'), findsOneWidget);
expect(find.text('!'), findsOneWidget);
expect(find.text('='), findsOneWidget);
});
}
+1 -1
View File
@@ -1 +1 @@
3.44.0
3.44.0+1