-
Notifications
You must be signed in to change notification settings - Fork 109
/
lyrics_screen.dart
562 lines (509 loc) · 20 KB
/
lyrics_screen.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
import 'dart:async';
import 'dart:io';
import 'package:finamp/color_schemes.g.dart';
import 'package:finamp/components/PlayerScreen/player_screen_appbar_title.dart';
import 'package:finamp/models/jellyfin_models.dart';
import 'package:finamp/services/current_track_metadata_provider.dart';
import 'package:finamp/services/feedback_helper.dart';
import 'package:finamp/services/music_player_background_task.dart';
import 'package:finamp/services/progress_state_stream.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_tabler_icons/flutter_tabler_icons.dart';
import 'package:flutter_to_airplay/flutter_to_airplay.dart';
import 'package:flutter_vibrate/flutter_vibrate.dart';
import 'package:get_it/get_it.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import 'package:simple_gesture_detector/simple_gesture_detector.dart';
import '../components/PlayerScreen/control_area.dart';
import '../components/PlayerScreen/player_screen_album_image.dart';
import '../components/PlayerScreen/queue_list.dart';
import '../components/PlayerScreen/song_name_content.dart';
import '../components/finamp_app_bar_button.dart';
import '../services/finamp_settings_helper.dart';
import '../services/player_screen_theme_provider.dart';
import 'blurred_player_screen_background.dart';
import 'player_screen.dart';
class LyricsScreen extends ConsumerWidget {
const LyricsScreen({Key? key}) : super(key: key);
static const routeName = "/lyrics";
@override
Widget build(BuildContext context, WidgetRef ref) {
final imageTheme =
ref.watch(playerScreenThemeProvider(Theme.of(context).brightness));
return AnimatedTheme(
duration: const Duration(milliseconds: 1000),
data: ThemeData(
colorScheme: imageTheme.copyWith(
brightness: Theme.of(context).brightness,
),
iconTheme: Theme.of(context).iconTheme.copyWith(
color: imageTheme.primary,
),
),
child: const _LyricsScreenContent(),
);
}
}
class _LyricsScreenContent extends StatefulWidget {
const _LyricsScreenContent({
super.key,
});
@override
State<_LyricsScreenContent> createState() => _LyricsScreenContentState();
}
class _LyricsScreenContentState extends State<_LyricsScreenContent> {
@override
Widget build(BuildContext context) {
double toolbarHeight = 53;
int maxLines = 2;
var controller = PlayerHideableController();
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
scrolledUnderElevation: 0.0, // disable tint/shadow when content is scrolled under the app bar
centerTitle: true,
toolbarHeight: toolbarHeight,
title: PlayerScreenAppBarTitle(
maxLines: maxLines,
),
leading: FinampAppBarButton(
dismissDirection: AxisDirection.right,
onPressed: () => Navigator.of(context).pop(),
),
actions: [
if (Platform.isIOS)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: AirPlayRoutePickerView(
tintColor: IconTheme.of(context).color ?? Colors.white,
activeTintColor: jellyfinBlueColor,
onShowPickerView: () =>
FeedbackHelper.feedback(FeedbackType.selection),
),
),
],
),
// Required for sleep timer input
resizeToAvoidBottomInset: false, extendBodyBehindAppBar: true,
body: Stack(
children: [
if (FinampSettingsHelper.finampSettings.useCoverAsBackground)
const BlurredPlayerScreenBackground(),
SafeArea(
minimum: EdgeInsets.only(top: toolbarHeight),
child: LayoutBuilder(builder: (context, constraints) {
if (MediaQuery.of(context).orientation == Orientation.landscape) {
controller.updateLayoutLandscape(Size(constraints.maxWidth, constraints.maxHeight));
return SimpleGestureDetector(
onHorizontalSwipe: (direction) {
if (direction == SwipeDirection.right) {
if (!FinampSettingsHelper.finampSettings.disableGesture) {
Navigator.of(context).pop();
}
}
},
child: const LyricsView()
);
} else {
controller.updateLayoutPortrait(Size(constraints.maxWidth, constraints.maxHeight));
return SimpleGestureDetector(
onHorizontalSwipe: (direction) {
if (direction == SwipeDirection.right) {
if (!FinampSettingsHelper.finampSettings.disableGesture) {
Navigator.of(context).pop();
}
}
},
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const Expanded(
child: LyricsView(),
),
SimpleGestureDetector(
onVerticalSwipe: (direction) {
if (direction == SwipeDirection.up) {
// This should never actually be called until widget finishes build and controller is initialized
if (!FinampSettingsHelper.finampSettings.disableGesture) {
showQueueBottomSheet(context);
}
}
},
child: Column(
children: [
SongNameContent(controller),
ControlArea(controller),
const SizedBox(
height: 12,
)
],
)
)
],
),
);
}
}),
),
],
),
);
}
}
class LyricsView extends ConsumerStatefulWidget {
const LyricsView({super.key});
@override
_LyricsViewState createState() => _LyricsViewState();
}
class _LyricsViewState extends ConsumerState<LyricsView> with WidgetsBindingObserver {
late AutoScrollController autoScrollController;
StreamSubscription<ProgressState>? progressStateStreamSubscription;
Duration? currentPosition;
int? currentLineIndex;
int? previousLineIndex;
bool isAutoScrollEnabled = true;
bool _isInForeground = true;
@override
void initState() {
WidgetsBinding.instance!.addObserver(this);
autoScrollController = AutoScrollController(
suggestedRowHeight: 72,
viewportBoundaryGetter: () =>
Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
axis: Axis.vertical);
super.initState();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
_isInForeground = state == AppLifecycleState.resumed;
super.didChangeAppLifecycleState(state);
}
@override
void dispose() {
progressStateStreamSubscription?.cancel();
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
final metadata = ref.watch(currentTrackMetadataProvider);
final _audioHandler = GetIt.instance<MusicPlayerBackgroundTask>();
final isSynchronizedLyrics = metadata.value?.lyrics?.lyrics?.first.start != null;
Widget getEmptyState({
required String message,
required IconData icon,
}) {
return Center(
child: LayoutBuilder(
builder: (context, constraints) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: constraints.maxHeight - 180,
),
child: const PlayerScreenAlbumImage()
),
const SizedBox(height: 24),
Icon(
icon,
size: 32,
color: Theme.of(context).textTheme.headlineMedium!.color,
),
const SizedBox(height: 12),
Text(
message,
style: TextStyle(
color: Theme.of(context).textTheme.headlineMedium!.color,
fontSize: 16,
),
),
],
);
}
),
);
}
if ((metadata.isLoading && !metadata.hasValue) || metadata.isRefreshing) {
return getEmptyState(
message: "Loading lyrics...",
icon: TablerIcons.microphone_2,
);
} else if (metadata.value == null || metadata.value!.hasLyrics && metadata.value!.lyrics == null && !metadata.isLoading) {
return getEmptyState(
message: "Couldn't load lyrics!",
icon: TablerIcons.microphone_2_off,
);
} else if (!metadata.value!.hasLyrics) {
return getEmptyState(
message: "No lyrics available.",
icon: TablerIcons.microphone_2_off,
);
} else {
progressStateStreamSubscription?.cancel();
progressStateStreamSubscription = progressStateStream.listen((state) async {
currentPosition = state.position;
if (!isSynchronizedLyrics || !_isInForeground) {
return;
}
// find the closest line to the current position, clamping to the first and last lines
int closestLineIndex = -1;
for (int i = 0; i < metadata.value!.lyrics!.lyrics!.length; i++) {
closestLineIndex = i;
final line = metadata.value!.lyrics!.lyrics![i];
if ((line.start ?? 0) ~/ 10 > (currentPosition?.inMicroseconds ?? 0)) {
closestLineIndex = i - 1;
break;
}
}
currentLineIndex = closestLineIndex;
if (currentLineIndex! != previousLineIndex) {
setState(() {}); // Rebuild to update the current line
if (autoScrollController.hasClients && isAutoScrollEnabled) {
int clampedIndex = currentLineIndex ?? 0;
if (clampedIndex >= metadata.value!.lyrics!.lyrics!.length) {
clampedIndex = metadata.value!.lyrics!.lyrics!.length - 1;
}
// print("currentPosition: ${currentPosition?.inMicroseconds}, currentLineIndex: $currentLineIndex, line: ${metadata.value!.lyrics!.lyrics![clampedIndex].text}");
if (clampedIndex < 0) {
await autoScrollController.scrollToIndex(
-1,
preferPosition: AutoScrollPosition.middle,
duration: const Duration(milliseconds: 500),
);
} else {
unawaited(autoScrollController.scrollToIndex(
clampedIndex.clamp(0, metadata.value!.lyrics!.lyrics!.length - 1),
preferPosition: AutoScrollPosition.middle,
duration: const Duration(milliseconds: 500),
));
}
}
previousLineIndex = currentLineIndex;
}
});
return LayoutBuilder(
builder: (context, constraints) {
return Padding(
padding: const EdgeInsets.only(left: 20.0, right: 12.0),
child: Stack(
children: [
Listener(
onPointerMove: (event) {
if (isSynchronizedLyrics && event.delta.dy.abs() > 2 * event.delta.dx.abs()) {
setState(() {
isAutoScrollEnabled = false;
});
}
},
child: LyricsListMask(
child: ListView.builder(
controller: autoScrollController,
itemCount: metadata.value!.lyrics!.lyrics?.length ?? 0,
itemBuilder: (context, index) {
final line = metadata.value!.lyrics!.lyrics![index];
final nextLine = index < metadata.value!.lyrics!.lyrics!.length - 1 ? metadata.value!.lyrics!.lyrics![index + 1] : null;
final isCurrentLine = (currentPosition?.inMicroseconds ?? 0) >= (line.start ?? 0) ~/ 10 &&
(nextLine == null || (currentPosition?.inMicroseconds ?? 0) < (nextLine.start ?? 0) ~/ 10 );
return Column(
children: [
if (index == 0)
AutoScrollTag(
key: const ValueKey(-1),
controller: autoScrollController,
index: -1,
child: GestureDetector(
onTap: () async {
// Seek to the start of the song
await _audioHandler.seek(Duration.zero);
},
child: SizedBox(
height: constraints.maxHeight * 0.65,
child: Center(
child: SizedBox(
height: constraints.maxHeight * 0.55,
child: const PlayerScreenAlbumImage()
)
),
),
),
),
AutoScrollTag(
key: ValueKey(index),
controller: autoScrollController,
index: index,
child: _LyricLine(
line: line,
isCurrentLine: isCurrentLine,
onTap: () async {
// Seek to the start of the line
await _audioHandler.seek(Duration(microseconds: (line.start ?? 0) ~/ 10));
setState(() {
isAutoScrollEnabled = true;
});
if (previousLineIndex != null) {
unawaited(autoScrollController.scrollToIndex(
previousLineIndex!,
preferPosition: AutoScrollPosition.middle,
duration: const Duration(milliseconds: 500),
));
}
}
),
),
if (index == metadata.value!.lyrics!.lyrics!.length - 1)
SizedBox(height: constraints.maxHeight * 0.2),
],
);
},
),
),
),
if (isSynchronizedLyrics)
Positioned(
bottom: 24,
right: 0,
child: EnableAutoScrollButton(autoScrollEnabled: isAutoScrollEnabled, onEnableAutoScroll: () {
setState(() {
isAutoScrollEnabled = true;
});
if (previousLineIndex != null) {
unawaited(autoScrollController.scrollToIndex(
previousLineIndex!,
preferPosition: AutoScrollPosition.middle,
duration: const Duration(milliseconds: 500),
));
}
FeedbackHelper.feedback(FeedbackType.impact);
}),
),
],
),
);
}
);
}
}
}
class _LyricLine extends StatelessWidget {
final LyricLine line;
final bool isCurrentLine;
final VoidCallback? onTap;
const _LyricLine({
required this.line,
required this.isCurrentLine,
this.onTap,
});
@override
Widget build(BuildContext context) {
final lowlightLine = !isCurrentLine && line.start != null;
final isSynchronized = line.start != null;
return GestureDetector(
onTap: isSynchronized ? onTap : null,
child: Padding(
padding: EdgeInsets.symmetric(vertical: isSynchronized ? 10.0 : 6.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (line.start != null)
Text(
"${Duration(microseconds: (line.start ?? 0) ~/ 10).inMinutes}:${(Duration(microseconds: (line.start ?? 0) ~/ 10).inSeconds % 60).toString().padLeft(2, '0')}",
style: TextStyle(
color: lowlightLine ? Colors.grey : Theme.of(context).textTheme.bodyLarge!.color,
fontSize: 16,
height: 1.75,
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: Text(
line.text ?? "<missing lyric line>",
textAlign: TextAlign.start,
style: TextStyle(
color: lowlightLine ? Colors.grey : Theme.of(context).textTheme.bodyLarge!.color,
fontWeight: lowlightLine || !isSynchronized ? FontWeight.normal : FontWeight.w500,
letterSpacing: lowlightLine || !isSynchronized ? 0.05 : -0.045, // keep text width consistent across the different weights
fontSize: isSynchronized ? 26 : 20,
height: 1.25,
),
),
),
),
],
),
),
);
}
}
class LyricsListMask extends StatelessWidget {
const LyricsListMask({
super.key,
required this.child,
});
final Widget child;
@override
Widget build(BuildContext context) {
return ShaderMask(
shaderCallback: (bounds) {
return LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.white.withOpacity(0.5),
Colors.white,
Colors.white,
Colors.white.withOpacity(0.5),
Colors.transparent,
],
stops: const [
0.0,
0.05,
0.10,
0.90,
0.95,
1.0,
],
).createShader(bounds);
},
child: child,
);
}
}
class EnableAutoScrollButton extends StatelessWidget {
final bool autoScrollEnabled;
final VoidCallback? onEnableAutoScroll;
const EnableAutoScrollButton({super.key, required this.autoScrollEnabled, this.onEnableAutoScroll});
@override
Widget build(BuildContext context) {
return !autoScrollEnabled
? FloatingActionButton.extended(
onPressed: () {
FeedbackHelper.feedback(FeedbackType.impact);
onEnableAutoScroll?.call();
},
backgroundColor: IconTheme.of(context).color!.withOpacity(0.70),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(16.0))),
icon: Icon(
TablerIcons.arrow_bar_to_up,
size: 28.0,
color: Colors.white.withOpacity(0.9),
),
label: Text(
AppLocalizations.of(context)!.enableAutoScroll,
style: TextStyle(
color: Colors.white.withOpacity(0.9),
fontSize: 14.0,
fontWeight: FontWeight.w500,
),
),
)
: const SizedBox.shrink();
}
}