import 'dart:ui'; import 'dart:convert'; import 'dart:async'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:audio_service/audio_service.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:freezer/api/cache.dart'; import 'package:freezer/api/deezer.dart'; import 'package:freezer/api/definitions.dart'; import 'package:freezer/api/download.dart'; import 'package:freezer/api/player.dart'; import 'package:freezer/page_routes/fade.dart'; import 'package:freezer/settings.dart'; import 'package:freezer/translations.i18n.dart'; import 'package:freezer/ui/cached_image.dart'; import 'package:freezer/ui/lyrics_screen.dart'; import 'package:freezer/ui/menu.dart'; import 'package:freezer/ui/player_bar.dart'; import 'package:freezer/ui/queue_screen.dart'; import 'package:freezer/ui/settings_screen.dart'; import 'package:marquee/marquee.dart'; import 'package:palette_generator/palette_generator.dart'; import 'package:photo_view/photo_view.dart'; import 'package:provider/provider.dart'; //Changing item in queue view and pressing back causes the pageView to skip song bool pageViewLock = false; const _blurStrength = 90.0; /// A simple [ChangeNotifier] that listens to the [AudioHandler.mediaItem] stream and /// notifies its listeners when background changes class BackgroundProvider extends ChangeNotifier { Color _dominantColor; ImageProvider? _imageProvider; StreamSubscription? _mediaItemSub; BackgroundProvider(this._dominantColor); /// Calculate background color from [mediaItem] /// /// Warning: this function is expensive to call, and should only be called when songs change! Future _updateColor(MediaItem mediaItem) async { if (!settings.colorGradientBackground && !settings.blurPlayerBackground) return; final imageProvider = CachedNetworkImageProvider( mediaItem.extras!['thumb'] ?? mediaItem.artUri as String); //Run in isolate PaletteGenerator palette = await PaletteGenerator.fromImageProvider(imageProvider); _dominantColor = palette.dominantColor!.color; _imageProvider = settings.blurPlayerBackground ? imageProvider : null; notifyListeners(); } @override void addListener(VoidCallback listener) { _mediaItemSub ??= audioHandler.mediaItem.listen((mediaItem) { if (mediaItem == null) return; _updateColor(mediaItem); }); super.addListener(listener); } @override void removeListener(VoidCallback listener) { super.removeListener(listener); if (!hasListeners && _mediaItemSub != null) { _mediaItemSub!.cancel(); _mediaItemSub = null; } } @override void dispose() { _mediaItemSub?.cancel(); super.dispose(); } Color get dominantColor => _dominantColor; ImageProvider? get imageProvider => _imageProvider; } class PlayerScreen extends StatelessWidget { const PlayerScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final defaultColor = Theme.of(context).cardColor; return ChangeNotifierProvider( create: (context) => BackgroundProvider(defaultColor), child: PlayerScreenBackground( child: OrientationBuilder( builder: (context, orientation) => orientation == Orientation.landscape ? PlayerScreenHorizontal() : PlayerScreenVertical())), ); } } /// Will change the background based on [BackgroundProvider], /// it will wrap the [child] in a [Scaffold] and [SafeArea] widget class PlayerScreenBackground extends StatelessWidget { final Widget child; final bool enabled; final PreferredSizeWidget? appBar; const PlayerScreenBackground({ required this.child, this.enabled = true, this.appBar, }); Widget _buildChild( BuildContext context, BackgroundProvider provider, Widget child) { return Stack(children: [ if (provider.imageProvider != null || settings.colorGradientBackground) Positioned.fill( child: provider.imageProvider != null ? ImageFiltered( imageFilter: ImageFilter.blur( sigmaX: _blurStrength, sigmaY: _blurStrength, ), child: DecoratedBox( decoration: BoxDecoration( image: DecorationImage( image: provider.imageProvider!, fit: BoxFit.cover, colorFilter: ColorFilter.mode( Colors.white .withOpacity(settings.isDark ? 0.5 : 0.8), BlendMode.dstATop), )), ), ) : DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ provider.dominantColor, Theme.of(context).scaffoldBackgroundColor, ], stops: [0.0, 0.6], )), )), child, ]); } static SystemUiOverlayStyle getSystemUiOverlayStyle(BuildContext context, {bool enabled = true}) { final hasBackground = enabled && (settings.blurPlayerBackground || settings.colorGradientBackground); final color = hasBackground ? Colors.transparent : Theme.of(context).scaffoldBackgroundColor; final brightness = hasBackground ? Brightness.light : (ThemeData.estimateBrightnessForColor(color) == Brightness.light ? Brightness.dark : Brightness.light); return SystemUiOverlayStyle( statusBarColor: color, statusBarBrightness: brightness, statusBarIconBrightness: brightness, systemNavigationBarIconBrightness: brightness, systemNavigationBarColor: color, systemNavigationBarDividerColor: color, ); } @override Widget build(BuildContext context) { final hasBackground = enabled && (settings.blurPlayerBackground || settings.colorGradientBackground); final color = hasBackground ? Colors.transparent : Theme.of(context).scaffoldBackgroundColor; Widget widgetChild = Scaffold( appBar: appBar, backgroundColor: color, body: SafeArea(child: child), ); if (enabled) widgetChild = Consumer( builder: (context, provider, child) { return _buildChild(context, provider, child!); }, child: widgetChild, ); if (appBar == null) widgetChild = AnnotatedRegion( value: getSystemUiOverlayStyle(context, enabled: enabled), child: widgetChild, ); return widgetChild; } } //Landscape class PlayerScreenHorizontal extends StatefulWidget { @override _PlayerScreenHorizontalState createState() => _PlayerScreenHorizontalState(); } class _PlayerScreenHorizontalState extends State { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(16.0), child: Row( mainAxisSize: MainAxisSize.max, children: [ Expanded( flex: 5, child: BigAlbumArt(), ), //Right side Expanded( flex: 5, child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: EdgeInsets.fromLTRB(8, 0, 8, 0), child: Container( child: PlayerScreenTopRow( textSize: ScreenUtil().setSp(24), iconSize: ScreenUtil().setSp(36), textWidth: ScreenUtil().setWidth(350), short: true), )), Column( mainAxisSize: MainAxisSize.min, children: [ Container( height: ScreenUtil().setSp(50), child: audioHandler .mediaItem.value!.displayTitle!.length >= 22 ? Marquee( text: audioHandler.mediaItem.value!.displayTitle!, style: TextStyle( fontSize: 40.sp, fontWeight: FontWeight.bold), blankSpace: 32.0, startPadding: 10.0, accelerationDuration: Duration(seconds: 1), pauseAfterRound: Duration(seconds: 2), ) : Text( audioHandler.mediaItem.value!.displayTitle!, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( fontSize: 40.sp, fontWeight: FontWeight.bold), )), const SizedBox(height: 4.0), Text( audioHandler.mediaItem.value!.displaySubtitle ?? '', maxLines: 1, textAlign: TextAlign.center, overflow: TextOverflow.clip, style: TextStyle( fontSize: 32.sp, color: Theme.of(context).primaryColor, ), ), ], ), const Padding( padding: EdgeInsets.symmetric(horizontal: 16.0), child: SeekBar(), ), PlaybackControls(56.sp), Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0), child: BottomBarControls(size: 42.sp), ) ], ), ) ], ), ); } } //Portrait class PlayerScreenVertical extends StatefulWidget { @override _PlayerScreenVerticalState createState() => _PlayerScreenVerticalState(); } class _PlayerScreenVerticalState extends State { @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.fromLTRB(30, 4, 16, 0), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ PlayerScreenTopRow(), Padding( padding: EdgeInsets.symmetric(horizontal: 16.0), child: SizedBox( child: BigAlbumArt(), width: 1000.w, height: 1000.w, ), ), PlayerTextSubtext(textSize: 64.sp), const SizedBox(height: 4.0), SeekBar(), PlaybackControls(86.sp), Padding( padding: EdgeInsets.symmetric(vertical: 0, horizontal: 16.0), child: BottomBarControls(size: 56.sp), ) ], )); } } class PlayerTextSubtext extends StatelessWidget { final double textSize; const PlayerTextSubtext({Key? key, required this.textSize}) : super(key: key); @override Widget build(BuildContext context) { return StreamBuilder( stream: audioHandler.mediaItem, builder: (context, snapshot) { if (!snapshot.hasData) { return const SizedBox(); } final currentMediaItem = snapshot.data!; return Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox( height: textSize * 1.5, child: currentMediaItem.displayTitle!.length >= 26 ? Marquee( text: currentMediaItem.displayTitle!, style: TextStyle( fontSize: textSize, fontWeight: FontWeight.bold), blankSpace: 32.0, startPadding: 10.0, accelerationDuration: Duration(seconds: 1), pauseAfterRound: Duration(seconds: 2), ) : Text( currentMediaItem.displayTitle!, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( fontSize: textSize, fontWeight: FontWeight.bold), )), const SizedBox(height: 4), Text( currentMediaItem.displaySubtitle ?? '', maxLines: 1, textAlign: TextAlign.center, overflow: TextOverflow.clip, style: TextStyle( fontSize: textSize * 0.8, // 20% smaller color: Theme.of(context).primaryColor, ), ), ], ); }); } } class QualityInfoWidget extends StatefulWidget { @override _QualityInfoWidgetState createState() => _QualityInfoWidgetState(); } class _QualityInfoWidgetState extends State { String value = ''; late StreamSubscription streamSubscription; //Load data from native void _load() async { if (audioHandler.mediaItem.value == null) return; Map? data = await DownloadManager.platform.invokeMethod( "getStreamInfo", {"id": audioHandler.mediaItem.value!.id}); //N/A if (data == null) { if (mounted) setState(() => value = ''); //If not show, try again later if (audioHandler.mediaItem.value!.extras!['show'] == null) Future.delayed(Duration(milliseconds: 200), _load); return; } //Update StreamQualityInfo info = StreamQualityInfo.fromJson(data); setState(() { value = '${info.format} ${info.bitrate(audioHandler.mediaItem.value!.duration)}kbps'; }); } @override void initState() { SchedulerBinding.instance!.addPostFrameCallback((_) => _load()); streamSubscription = audioHandler.mediaItem.listen((_) => _load()); super.initState(); } @override void dispose() { streamSubscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return TextButton( child: Text(value), onPressed: () { Navigator.of(context) .push(MaterialPageRoute(builder: (context) => QualitySettings())); }, ); } } class PlayerMenuButton extends StatelessWidget { final double size; const PlayerMenuButton({required this.size}); @override Widget build(BuildContext context) { return IconButton( icon: Icon( Icons.more_vert, size: size, semanticLabel: "Options".i18n, ), onPressed: () { final currentMediaItem = audioHandler.mediaItem.value!; Track t = Track.fromMediaItem(currentMediaItem); MenuSheet m = MenuSheet(context, navigateCallback: () { Navigator.of(context).pop(); }); if (currentMediaItem.extras!['show'] == null) m.defaultTrackMenu(t, options: [m.sleepTimer(), m.wakelock()]); else m.defaultShowEpisodeMenu( Show.fromJson(jsonDecode(currentMediaItem.extras!['show'])), ShowEpisode.fromMediaItem(currentMediaItem), options: [m.sleepTimer(), m.wakelock()]); }, ); } } class RepeatButton extends StatefulWidget { final double iconSize; RepeatButton(this.iconSize, {Key? key}) : super(key: key); @override _RepeatButtonState createState() => _RepeatButtonState(); } class _RepeatButtonState extends State { // ignore: missing_return Icon get repeatIcon { switch (playerHelper.repeatType) { case AudioServiceRepeatMode.none: return Icon( Icons.repeat, semanticLabel: "Repeat off".i18n, ); case AudioServiceRepeatMode.one: return Icon( Icons.repeat_one, semanticLabel: "Repeat one".i18n, ); case AudioServiceRepeatMode.group: case AudioServiceRepeatMode.all: return Icon( Icons.repeat, semanticLabel: "Repeat".i18n, ); } } @override Widget build(BuildContext context) { return IconButton( color: playerHelper.repeatType == AudioServiceRepeatMode.none ? null : Theme.of(context).primaryColor, iconSize: widget.iconSize, icon: repeatIcon, onPressed: () async { await playerHelper.changeRepeat(); setState(() {}); }, ); } } class ShuffleButton extends StatefulWidget { final double iconSize; const ShuffleButton({Key? key, required this.iconSize}) : super(key: key); @override _ShuffleButtonState createState() => _ShuffleButtonState(); } class _ShuffleButtonState extends State { @override Widget build(BuildContext context) => IconButton( icon: Icon(Icons.shuffle), iconSize: widget.iconSize, color: playerHelper.shuffleEnabled ? Theme.of(context).primaryColor : null, onPressed: _toggleShuffle, ); void _toggleShuffle() { playerHelper.toggleShuffle().then((_) => setState(() => null)); } } class FavoriteButton extends StatefulWidget { final double size; const FavoriteButton({Key? key, required this.size}) : super(key: key); @override _FavoriteButtonState createState() => _FavoriteButtonState(); } class _FavoriteButtonState extends State { Icon get libraryIcon { if (cache.checkTrackFavorite( Track.fromMediaItem(audioHandler.mediaItem.value!))) { return Icon( Icons.favorite, semanticLabel: "Unlove".i18n, ); } return Icon( Icons.favorite_border, semanticLabel: "Love".i18n, ); } @override Widget build(BuildContext context) => IconButton( icon: libraryIcon, iconSize: widget.size, onPressed: () async { if (cache.libraryTracks == null) cache.libraryTracks = []; if (cache.checkTrackFavorite( Track.fromMediaItem(audioHandler.mediaItem.value!))) { //Remove from library setState(() => cache.libraryTracks!.remove(audioHandler.mediaItem.value!.id)); await deezerAPI.removeFavorite(audioHandler.mediaItem.value!.id); await cache.save(); } else { //Add setState(() => cache.libraryTracks!.add(audioHandler.mediaItem.value!.id)); await deezerAPI.addFavoriteTrack(audioHandler.mediaItem.value!.id); await cache.save(); } }, ); } class PlaybackControls extends StatelessWidget { final double size; PlaybackControls(this.size, {Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric(horizontal: 8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.max, children: [ ShuffleButton(iconSize: size * 0.75), PrevNextButton(size, prev: true), if (settings.enableFilledPlayButton) Consumer(builder: (context, provider, _) { final color = Theme.of(context).brightness == Brightness.light ? provider.dominantColor : darken(provider.dominantColor); return PlayPauseButton(size * 2.25, filled: true, color: color, iconColor: Color.lerp( (ThemeData.estimateBrightnessForColor(color) == Brightness.light ? Colors.black : Colors.white), color, 0.25)); }) else PlayPauseButton(size * 1.25), PrevNextButton(size), RepeatButton(size * 0.75), ], ), ); } } class BigAlbumArt extends StatefulWidget { @override _BigAlbumArtState createState() => _BigAlbumArtState(); } class _BigAlbumArtState extends State { final _pageController = PageController( initialPage: playerHelper.queueIndex, viewportFraction: 1.0, ); StreamSubscription? _currentItemSub; bool _animationLock = false; bool _initiatedByUser = false; @override void initState() { _currentItemSub = audioHandler.mediaItem.listen((event) async { if (_initiatedByUser) { _initiatedByUser = false; return; } if (!_pageController.hasClients) return; print('animating controller to page'); _animationLock = true; await _pageController.animateToPage(playerHelper.queueIndex, duration: Duration(milliseconds: 300), curve: Curves.easeInOut); _animationLock = false; }); super.initState(); } @override void dispose() { _currentItemSub?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return GestureDetector( onVerticalDragUpdate: (DragUpdateDetails details) { if (details.delta.dy > 16) { Navigator.of(context).pop(); } }, onTap: () => Navigator.push( context, PageRouteBuilder( opaque: false, // transparent background barrierDismissible: true, pageBuilder: (context, animation, __) { return FadeTransition( opacity: animation, child: PhotoView( imageProvider: CachedNetworkImageProvider( audioHandler.mediaItem.value!.artUri.toString()), maxScale: 8.0, minScale: 0.2, heroAttributes: PhotoViewHeroAttributes( tag: audioHandler.mediaItem.value!.id), backgroundDecoration: BoxDecoration(color: Color.fromARGB(0x90, 0, 0, 0))), ); })), child: StreamBuilder>( stream: audioHandler.queue, initialData: audioHandler.queue.valueOrNull, builder: (context, snapshot) { if (!snapshot.hasData) return const Center(child: CircularProgressIndicator()); final queue = snapshot.data!; return PageView( controller: _pageController, onPageChanged: (int index) { if (pageViewLock || _animationLock) return; _initiatedByUser = true; audioHandler.skipToQueueItem(index); }, children: List.generate( queue.length, (i) => Padding( padding: const EdgeInsets.all(8.0), child: Hero( tag: queue[i].id, child: ClipRRect( borderRadius: BorderRadius.circular(5.0), child: CachedImage( url: queue[i].artUri.toString(), ), ), ), )), ); }), ); } } //Top row containing QueueSource, queue... class PlayerScreenTopRow extends StatelessWidget { final double? textSize; final double? iconSize; final double? textWidth; final bool? short; PlayerScreenTopRow( {this.textSize, this.iconSize, this.textWidth, this.short}); @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: this.textWidth ?? ScreenUtil().setWidth(800), child: Text( (short ?? false) ? (playerHelper.queueSource!.text ?? '') : 'Playing from:'.i18n + ' ' + (playerHelper.queueSource?.text ?? ''), maxLines: 1, overflow: TextOverflow.ellipsis, textAlign: TextAlign.left, style: TextStyle(fontSize: this.textSize ?? ScreenUtil().setSp(38)), ), ), IconButton( icon: Icon( Icons.menu, semanticLabel: "Queue".i18n, ), iconSize: this.iconSize ?? ScreenUtil().setSp(52), splashRadius: this.iconSize ?? ScreenUtil().setWidth(52), onPressed: () => Navigator.of(context) .pushRoute(builder: (context) => QueueScreen()), ), ], ); } } class SeekBar extends StatefulWidget { const SeekBar(); @override _SeekBarState createState() => _SeekBarState(); } class _SeekBarState extends State { bool _seeking = false; late StreamSubscription _subscription; final position = ValueNotifier(Duration.zero); @override void initState() { _subscription = AudioService.position.listen((position) { if (_seeking) return; // user is seeking this.position.value = position; }); super.initState(); } @override void dispose() { _subscription.cancel(); super.dispose(); } double parseDuration(Duration position) { if (position > duration) return duration.inMilliseconds.toDouble(); return position.inMilliseconds.toDouble(); } //Duration to mm:ss String _timeString(Duration d) { return "${d.inMinutes}:${d.inSeconds.remainder(60).toString().padLeft(2, '0')}"; } Duration get duration { if (audioHandler.mediaItem.value == null) return Duration.zero; return audioHandler.mediaItem.value!.duration!; } @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ ValueListenableBuilder( valueListenable: position, builder: (context, value, _) => Slider( focusNode: FocusNode( canRequestFocus: false, skipTraversal: true), // Don't focus on Slider - it doesn't work (and not needed) value: parseDuration(value), max: duration.inMilliseconds.toDouble(), onChangeStart: (double d) { _seeking = true; position.value = Duration(milliseconds: d.toInt()); }, onChanged: (double d) { position.value = Duration(milliseconds: d.toInt()); }, onChangeEnd: (double d) { _seeking = false; audioHandler.seek(Duration(milliseconds: d.toInt())); }, )), Padding( padding: EdgeInsets.symmetric(horizontal: 24.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ ValueListenableBuilder( valueListenable: position, builder: (context, value, _) => Text( _timeString(value), style: TextStyle( fontSize: ScreenUtil().setSp(35), color: Theme.of(context) .textTheme .bodyText1! .color! .withOpacity(.75)), )), StreamBuilder( stream: audioHandler.mediaItem, builder: (context, snapshot) => Text( _timeString(snapshot.data?.duration ?? Duration.zero), style: TextStyle( fontSize: ScreenUtil().setSp(35), color: Theme.of(context) .textTheme .bodyText1! .color! .withOpacity(.75)), )), ], ), ), ], ); } } class BottomBarControls extends StatelessWidget { final double size; const BottomBarControls({Key? key, required this.size}) : super(key: key); @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( icon: Icon( Icons.subtitles, size: size, semanticLabel: "Lyrics".i18n, ), onPressed: () => _pushLyrics(context)), IconButton( icon: Icon( Icons.sentiment_very_dissatisfied, semanticLabel: "Dislike".i18n, ), iconSize: size * 0.85, onPressed: () async { await deezerAPI.dislikeTrack(audioHandler.mediaItem.value!.id); if (playerHelper.queueIndex < audioHandler.queue.value.length - 1) { audioHandler.skipToNext(); } }), // IconButton( // iconSize: size, // icon: Icon( // Icons.file_download, // semanticLabel: "Download".i18n, // ), // onPressed: () async { // Track t = Track.fromMediaItem(audioHandler.mediaItem.value!); // if (await downloadManager.addOfflineTrack(t, // private: false, context: context, isSingleton: true) != // false) // Fluttertoast.showToast( // msg: 'Downloads added!'.i18n, // gravity: ToastGravity.BOTTOM, // toastLength: Toast.LENGTH_SHORT); // }, // ), QualityInfoWidget(), FavoriteButton(size: size * 0.85), PlayerMenuButton(size: size) ], ); } void _pushLyrics(BuildContext context) { final builder = (ctx) => ChangeNotifierProvider.value( value: Provider.of(context), child: LyricsScreen()); if (settings.playerBackgroundOnLyrics) { Navigator.of(context).push(FadePageRoute(builder: builder)); return; } Navigator.of(context).pushRoute(builder: builder); } }