-
Notifications
You must be signed in to change notification settings - Fork 109
/
music_screen_tab_view.dart
481 lines (440 loc) · 18.6 KB
/
music_screen_tab_view.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import 'dart:async';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:finamp/services/finamp_user_helper.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:hive/hive.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import '../../models/finamp_models.dart';
import '../../models/jellyfin_models.dart';
import '../../services/downloads_service.dart';
import '../../services/finamp_settings_helper.dart';
import '../../services/jellyfin_api_helper.dart';
import '../AlbumScreen/song_list_tile.dart';
import '../first_page_progress_indicator.dart';
import '../global_snackbar.dart';
import '../new_page_progress_indicator.dart';
import 'album_item.dart';
import 'alphabet_item_list.dart';
class MusicScreenTabView extends StatefulWidget {
const MusicScreenTabView({
super.key,
required this.tabContentType,
this.searchTerm,
required this.view,
});
final TabContentType tabContentType;
final String? searchTerm;
final BaseItemDto? view;
@override
State<MusicScreenTabView> createState() => _MusicScreenTabViewState();
}
// We use AutomaticKeepAliveClientMixin so that the view keeps its position after the tab is changed.
// https://stackoverflow.com/questions/49439047/how-to-preserve-widget-states-in-flutter-when-navigating-using-bottomnavigation
class _MusicScreenTabViewState extends State<MusicScreenTabView>
with AutomaticKeepAliveClientMixin<MusicScreenTabView> {
// tabs on the music screen should be kept alive
@override
bool get wantKeepAlive => true;
static const _pageSize = 100;
final PagingController<int, BaseItemDto> _pagingController =
PagingController(firstPageKey: 0, invisibleItemsThreshold: 70);
Future<List<BaseItemDto>>? offlineSortedItems;
final _jellyfinApiHelper = GetIt.instance<JellyfinApiHelper>();
final _isarDownloader = GetIt.instance<DownloadsService>();
StreamSubscription<void>? _refreshStream;
late AutoScrollController controller;
int _requestedPageKey = -1;
String? letterToSearch;
Timer? timer;
int? refreshHash;
int refreshCount = 0;
int fullyLoadedRefresh = -1;
// This function just lets us easily set stuff to the getItems call we want.
Future<void> _getPage(int pageKey) async {
// The jump-to-letter widget and main view scrolling may generate duplicate page
// requests. Only fetch page once in these cases.
if (pageKey <= _requestedPageKey) {
return;
}
_requestedPageKey = pageKey;
var settings = FinampSettingsHelper.finampSettings;
if (settings.isOffline) {
return _getPageOffline();
}
int localRefreshCount = refreshCount;
try {
final sortOrder =
settings.tabSortOrder[widget.tabContentType]?.toString() ??
SortOrder.ascending.toString();
final newItems = await _jellyfinApiHelper.getItems(
// starting with Jellyfin 10.9, only automatically created playlists will have a specific library as parent. user-created playlists will not be returned anymore
// this condition fixes this by not providing a parentId when fetching playlists
parentItem: widget.tabContentType.itemType == BaseItemDtoType.playlist
? null
: widget.view,
includeItemTypes: widget.tabContentType.itemType.idString,
// If we're on the songs tab, sort by "Album,SortName". This is what the
// Jellyfin web client does. If this isn't the case, sort by "SortName".
// If widget.sortBy is set, it is used instead.
sortBy: settings.tabSortBy[widget.tabContentType]
?.jellyfinName(widget.tabContentType) ??
(widget.tabContentType == TabContentType.songs
? "Album,SortName"
: "SortName"),
sortOrder: sortOrder,
searchTerm: widget.searchTerm?.trim(),
filters: settings.onlyShowFavourite ? "IsFavorite" : null,
startIndex: pageKey,
limit: _pageSize,
);
// Skip appending page if a refresh triggered while processing
if (localRefreshCount == refreshCount && mounted) {
if (newItems!.length < _pageSize) {
_pagingController.appendLastPage(newItems);
fullyLoadedRefresh = localRefreshCount;
} else {
_pagingController.appendPage(newItems, pageKey + newItems.length);
}
if (letterToSearch != null) {
scrollToLetter(letterToSearch);
}
}
} catch (e) {
// Ignore errors when logging out
if (GetIt.instance<FinampUserHelper>().currentUser != null) {
GlobalSnackbar.error(e);
}
}
}
Future<void> _getPageOffline() async {
var settings = FinampSettingsHelper.finampSettings;
int localRefreshCount = refreshCount;
List<DownloadStub> offlineItems;
if (widget.tabContentType == TabContentType.songs) {
// If we're on the songs tab, just get all of the downloaded items
// We should probably try to page this, at least if we are sorting by name
offlineItems = await _isarDownloader.getAllSongs(
nameFilter: widget.searchTerm,
viewFilter: widget.view?.id,
nullableViewFilters: settings.showDownloadsWithUnknownLibrary);
} else {
offlineItems = await _isarDownloader.getAllCollections(
nameFilter: widget.searchTerm,
baseTypeFilter: widget.tabContentType.itemType,
fullyDownloaded: settings.onlyShowFullyDownloaded,
viewFilter: widget.tabContentType == TabContentType.albums
? widget.view?.id
: null,
childViewFilter: (widget.tabContentType != TabContentType.albums &&
widget.tabContentType != TabContentType.playlists)
? widget.view?.id
: null,
nullableViewFilters: widget.tabContentType == TabContentType.albums &&
settings.showDownloadsWithUnknownLibrary);
}
var items = offlineItems.map((e) => e.baseItem).whereNotNull().toList();
items = sortItems(items, settings.tabSortBy[widget.tabContentType],
settings.tabSortOrder[widget.tabContentType]);
// Skip appending page if a refresh triggered while processing
if (localRefreshCount == refreshCount && mounted) {
_pagingController.appendLastPage(items);
fullyLoadedRefresh = localRefreshCount;
if (letterToSearch != null) {
scrollToLetter(letterToSearch);
}
}
}
@override
void initState() {
_pagingController.addPageRequestListener((pageKey) {
_getPage(pageKey);
});
controller = AutoScrollController(
suggestedRowHeight: 72,
viewportBoundaryGetter: () =>
Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
axis: Axis.vertical);
_refreshStream = _isarDownloader.offlineDeletesStream.listen((event) {
_pagingController.refresh();
});
super.initState();
}
// Scrolls the list to the first occurrence of the letter in the list
// If clicked in the # element, it goes to the first or last one item, depending on sort order
void scrollToLetter(String? clickedLetter) async {
String? letter = clickedLetter ?? letterToSearch;
if (letter == null || letter.isEmpty) return;
letterToSearch = letter;
var codePointToScrollTo = letterToSearch!.toLowerCase().codeUnitAt(0);
// Max code point is lower case z to increase the chance of seeing a character
// past the target but below the ignore point
final maxCodePoint = 'z'.codeUnitAt(0);
if (letter == '#') {
codePointToScrollTo = 0;
}
//TODO use binary search to improve performance for already loaded pages
bool reversed = FinampSettingsHelper.finampSettings.tabSortOrder[widget.tabContentType] == SortOrder.descending;
for (var i = 0; i < _pagingController.itemList!.length; i++) {
int itemCodePoint =
_pagingController.itemList![i].nameForSorting!.toLowerCase().codeUnitAt(0);
if (itemCodePoint <= maxCodePoint) {
final comparisonResult = itemCodePoint - codePointToScrollTo;
if (comparisonResult == 0) {
timer?.cancel();
await controller.scrollToIndex(i,
duration: _getAnimationDurationForOffsetToIndex(i),
preferPosition: AutoScrollPosition.begin);
letterToSearch = null;
return;
} else if (reversed ? comparisonResult < 0 : comparisonResult > 0) {
// If the letter is before the current item, there was no previous match (letter doesn't seem to exist in library)
// scroll to the previous item instead
timer?.cancel();
await controller.scrollToIndex((i - 1).clamp(0, (_pagingController.itemList?.length ?? 1) - 1),
// duration: scrollDuration,
duration: _getAnimationDurationForOffsetToIndex(i),
preferPosition: AutoScrollPosition.middle);
letterToSearch = null;
return;
}
}
}
timer?.cancel();
if (fullyLoadedRefresh == refreshCount) {
letterToSearch = null;
} else {
timer = Timer(const Duration(seconds: 8), () {
// If page loading takes >5 seconds, cancel search and allow image loading.
letterToSearch = null;
});
_pagingController
.notifyPageRequestListeners(_pagingController.nextPageKey!);
}
await controller.animateTo(controller.position.maxScrollExtent,
duration: const Duration(milliseconds: 500), curve: Curves.ease);
}
Duration _getAnimationDurationForOffsetToIndex(int index) {
final renderedIndices = controller.tagMap.keys;
final medianIndex = renderedIndices.elementAt(renderedIndices.length ~/ 2);
final duration = Duration(
milliseconds: ((medianIndex - index).abs() / 50 * 300).clamp(200, 7500).round(),
);
return duration;
}
@override
void dispose() {
_refreshStream?.cancel();
_pagingController.dispose();
timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
return ValueListenableBuilder<Box<FinampSettings>>(
valueListenable: FinampSettingsHelper.finampSettingsListener,
builder: (context, box, _) {
// If the searchTerm argument is different to lastSearch, the user has changed their search input.
// This makes albumViewFuture search again so that results with the search are shown.
// This also means we don't redo a search unless we actaully need to.
var settings = box.get("FinampSettings")!;
var newRefreshHash = Object.hash(
widget.searchTerm,
settings.onlyShowFavourite,
settings.tabSortBy[widget.tabContentType],
settings.tabSortOrder[widget.tabContentType],
settings.onlyShowFullyDownloaded,
widget.view?.id,
settings.isOffline,
settings.tabOrder.indexOf(widget.tabContentType),
);
if (refreshHash == null) {
refreshHash = newRefreshHash;
} else if (refreshHash != newRefreshHash) {
refreshCount++;
_requestedPageKey = -1;
// This makes refreshing actually work in error cases
_pagingController.value =
const PagingState(nextPageKey: 0, itemList: []);
_pagingController.refresh();
refreshHash = newRefreshHash;
}
var tabContent = box.get("FinampSettings")!.contentViewType ==
ContentViewType.list ||
widget.tabContentType == TabContentType.songs
? PagedListView<int, BaseItemDto>.separated(
pagingController: _pagingController,
scrollController: controller,
physics: _DeferredLoadingAlwaysScrollableScrollPhysics(
tabState: this),
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
builderDelegate: PagedChildBuilderDelegate<BaseItemDto>(
itemBuilder: (context, item, index) {
return AutoScrollTag(
key: ValueKey(index),
controller: controller,
index: index,
child: widget.tabContentType == TabContentType.songs
? SongListTile(
key: ValueKey(item.id),
item: item,
isSong: true,
index: Future.value(index),
isShownInSearch: widget.searchTerm != null,
)
: AlbumItem(
key: ValueKey(item.id),
album: item,
isPlaylist: widget.tabContentType ==
TabContentType.playlists,
),
);
},
firstPageProgressIndicatorBuilder: (_) =>
const FirstPageProgressIndicator(),
newPageProgressIndicatorBuilder: (_) =>
const NewPageProgressIndicator(),
),
separatorBuilder: (context, index) => const SizedBox.shrink(),
)
: PagedGridView(
pagingController: _pagingController,
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
scrollController: controller,
physics: _DeferredLoadingAlwaysScrollableScrollPhysics(
tabState: this),
builderDelegate: PagedChildBuilderDelegate<BaseItemDto>(
itemBuilder: (context, item, index) {
return AutoScrollTag(
key: ValueKey(index),
controller: controller,
index: index,
child: AlbumItem(
key: ValueKey(item.id),
album: item,
isPlaylist:
widget.tabContentType == TabContentType.playlists,
isGrid: true,
gridAddSettingsListener: false,
),
);
},
firstPageProgressIndicatorBuilder: (_) =>
const FirstPageProgressIndicator(),
newPageProgressIndicatorBuilder: (_) =>
const NewPageProgressIndicator(),
),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: MediaQuery.of(context).size.width >
MediaQuery.of(context).size.height
? box
.get("FinampSettings")!
.contentGridViewCrossAxisCountLandscape
: box
.get("FinampSettings")!
.contentGridViewCrossAxisCountPortrait,
),
);
return RefreshIndicator(
onRefresh: () async {
refreshCount++;
_requestedPageKey = -1;
// This makes refreshing actually work in error cases
_pagingController.value =
const PagingState(nextPageKey: 0, itemList: []);
_pagingController.refresh();
},
child: Scrollbar(
controller: controller,
child: box.get("FinampSettings")!.showFastScroller &&
settings.tabSortBy[widget.tabContentType] ==
SortBy.sortName
? AlphabetList(
callback: scrollToLetter,
sortOrder: settings.tabSortOrder[widget.tabContentType] ??
SortOrder.ascending,
child: tabContent)
: tabContent,
),
);
});
}
}
List<BaseItemDto> sortItems(
List<BaseItemDto> itemsToSort, SortBy? sortBy, SortOrder? sortOrder) {
itemsToSort.sort((a, b) {
switch (sortBy ?? SortBy.sortName) {
case SortBy.sortName:
if (a.nameForSorting == null || b.nameForSorting == null) {
// Returning 0 is the same as both being the same
return 0;
} else {
return a.nameForSorting!.compareTo(b.nameForSorting!);
}
case SortBy.albumArtist:
if (a.albumArtist == null || b.albumArtist == null) {
return 0;
} else {
return a.albumArtist!.compareTo(b.albumArtist!);
}
case SortBy.communityRating:
if (a.communityRating == null || b.communityRating == null) {
return 0;
} else {
return a.communityRating!.compareTo(b.communityRating!);
}
case SortBy.criticRating:
if (a.criticRating == null || b.criticRating == null) {
return 0;
} else {
return a.criticRating!.compareTo(b.criticRating!);
}
case SortBy.dateCreated:
if (a.dateCreated == null || b.dateCreated == null) {
return 0;
} else {
return a.dateCreated!.compareTo(b.dateCreated!);
}
case SortBy.premiereDate:
if (a.premiereDate == null || b.premiereDate == null) {
return 0;
} else {
return a.premiereDate!.compareTo(b.premiereDate!);
}
case SortBy.random:
// We subtract the result by one so that we can get -1 values
// (see comareTo documentation)
return Random().nextInt(2) - 1;
default:
throw UnimplementedError("Unimplemented offline sort mode $sortBy");
}
});
return sortOrder == SortOrder.descending
? itemsToSort.reversed.toList()
: itemsToSort;
}
class _DeferredLoadingAlwaysScrollableScrollPhysics
extends AlwaysScrollableScrollPhysics {
const _DeferredLoadingAlwaysScrollableScrollPhysics(
{super.parent, required this.tabState});
final _MusicScreenTabViewState tabState;
@override
_DeferredLoadingAlwaysScrollableScrollPhysics applyTo(
ScrollPhysics? ancestor) {
return _DeferredLoadingAlwaysScrollableScrollPhysics(
parent: buildParent(ancestor), tabState: tabState);
}
@override
bool recommendDeferredLoading(
double velocity, ScrollMetrics metrics, BuildContext context) {
if (tabState.letterToSearch != null) {
return true;
}
return super.recommendDeferredLoading(velocity, metrics, context);
}
}